diff --git a/Swiftgram/ChatControllerImplExtension/BUILD b/Swiftgram/ChatControllerImplExtension/BUILD new file mode 100644 index 00000000..15c650e1 --- /dev/null +++ b/Swiftgram/ChatControllerImplExtension/BUILD @@ -0,0 +1,9 @@ +filegroup( + name = "ChatControllerImplExtension", + srcs = glob([ + "Sources/**/*.swift", + ]), + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/ChatControllerImplExtension/Sources/ChatControllerImplExtension.swift b/Swiftgram/ChatControllerImplExtension/Sources/ChatControllerImplExtension.swift new file mode 100644 index 00000000..77d76465 --- /dev/null +++ b/Swiftgram/ChatControllerImplExtension/Sources/ChatControllerImplExtension.swift @@ -0,0 +1,229 @@ +import SGSimpleSettings +import Foundation +import UIKit +import Postbox +import SwiftSignalKit +import Display +import AsyncDisplayKit +import TelegramCore +import SafariServices +import MobileCoreServices +import Intents +import LegacyComponents +import TelegramPresentationData +import TelegramUIPreferences +import DeviceAccess +import TextFormat +import TelegramBaseController +import AccountContext +import TelegramStringFormatting +import OverlayStatusController +import DeviceLocationManager +import ShareController +import UrlEscaping +import ContextUI +import ComposePollUI +import AlertUI +import PresentationDataUtils +import UndoUI +import TelegramCallsUI +import TelegramNotices +import GameUI +import ScreenCaptureDetection +import GalleryUI +import OpenInExternalAppUI +import LegacyUI +import InstantPageUI +import LocationUI +import BotPaymentsUI +import DeleteChatPeerActionSheetItem +import HashtagSearchUI +import LegacyMediaPickerUI +import Emoji +import PeerAvatarGalleryUI +import PeerInfoUI +import RaiseToListen +import UrlHandling +import AvatarNode +import AppBundle +import LocalizedPeerData +import PhoneNumberFormat +import SettingsUI +import UrlWhitelist +import TelegramIntents +import TooltipUI +import StatisticsUI +import MediaResources +import GalleryData +import ChatInterfaceState +import InviteLinksUI +import Markdown +import TelegramPermissionsUI +import Speak +import TranslateUI +import UniversalMediaPlayer +import WallpaperBackgroundNode +import ChatListUI +import CalendarMessageScreen +import ReactionSelectionNode +import ReactionListContextMenuContent +import AttachmentUI +import AttachmentTextInputPanelNode +import MediaPickerUI +import ChatPresentationInterfaceState +import Pasteboard +import ChatSendMessageActionUI +import ChatTextLinkEditUI +import WebUI +import PremiumUI +import ImageTransparency +import StickerPackPreviewUI +import TextNodeWithEntities +import EntityKeyboard +import ChatTitleView +import EmojiStatusComponent +import ChatTimerScreen +import MediaPasteboardUI +import ChatListHeaderComponent +import ChatControllerInteraction +import FeaturedStickersScreen +import ChatEntityKeyboardInputNode +import StorageUsageScreen +import AvatarEditorScreen +import ChatScheduleTimeController +import ICloudResources +import StoryContainerScreen +import MoreHeaderButton +import VolumeButtons +import ChatAvatarNavigationNode +import ChatContextQuery +import PeerReportScreen +import PeerSelectionController +import SaveToCameraRoll +import ChatMessageDateAndStatusNode +import ReplyAccessoryPanelNode +import TextSelectionNode +import ChatMessagePollBubbleContentNode +import ChatMessageItem +import ChatMessageItemImpl +import ChatMessageItemView +import ChatMessageItemCommon +import ChatMessageAnimatedStickerItemNode +import ChatMessageBubbleItemNode +import ChatNavigationButton +import WebsiteType +import ChatQrCodeScreen +import PeerInfoScreen +import MediaEditorScreen +import WallpaperGalleryScreen +import WallpaperGridScreen +import VideoMessageCameraScreen +import TopMessageReactions +import AudioWaveform +import PeerNameColorScreen +import ChatEmptyNode +import ChatMediaInputStickerGridItem +import AdsInfoScreen + +extension ChatControllerImpl { + + func forwardMessagesToCloud(messageIds: [MessageId], removeNames: Bool, openCloud: Bool, resetCurrent: Bool = false) { + let _ = (self.context.engine.data.get(EngineDataMap( + messageIds.map(TelegramEngine.EngineData.Item.Messages.Message.init) + )) + |> deliverOnMainQueue).startStandalone(next: { [weak self] messages in + guard let strongSelf = self else { + return + } + + if resetCurrent { + strongSelf.updateChatPresentationInterfaceState(animated: true, interactive: true, { $0.updatedInterfaceState({ $0.withUpdatedForwardMessageIds(nil).withUpdatedForwardOptionsState(nil).withoutSelectionState() }) }) + } + + let sortedMessages = messages.values.compactMap { $0?._asMessage() }.sorted { lhs, rhs in + return lhs.id < rhs.id + } + + let options = ChatInterfaceForwardOptionsState(hideNames: removeNames, hideCaptions: false, unhideNamesOnCaptionChange: false) + + if !openCloud { + Queue.mainQueue().after(0.88) { + strongSelf.chatDisplayNode.hapticFeedback.success() + } + + let presentationData = strongSelf.context.sharedContext.currentPresentationData.with { $0 } + strongSelf.present(UndoOverlayController(presentationData: presentationData, content: .forward(savedMessages: true, text: messages.count == 1 ? presentationData.strings.Conversation_ForwardTooltip_SavedMessages_One : presentationData.strings.Conversation_ForwardTooltip_SavedMessages_Many), elevatedLayout: false, animateInAsReplacement: true, action: { [weak self] value in + if case .info = value, let strongSelf = self { + let _ = (strongSelf.context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: strongSelf.context.account.peerId)) + |> deliverOnMainQueue).startStandalone(next: { peer in + guard let strongSelf = self, let peer = peer, let navigationController = strongSelf.effectiveNavigationController else { + return + } + + strongSelf.context.sharedContext.navigateToChatController(NavigateToChatControllerParams(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(peer), keepStack: .always, purposefulAction: {}, peekData: nil)) + }) + return true + } + return false + }), in: .current) + } + + let mappedMessages: [EnqueueMessage] + switch strongSelf.buildForwardEnqueueMessages(from: sortedMessages, options: options, threadId: nil) { + case let .messages(messages): + mappedMessages = messages + case .unsupported: + strongSelf.presentUnsupportedProtectedForwardAlert(in: nil) + return + } + + let _ = (enqueueMessages(account: strongSelf.context.account, peerId: strongSelf.context.account.peerId, messages: mappedMessages) + |> deliverOnMainQueue).startStandalone(next: { messageIds in + guard openCloud else { + return + } + if let strongSelf = self { + let signals: [Signal] = messageIds.compactMap({ id -> Signal? in + guard let id = id else { + return nil + } + return strongSelf.context.account.pendingMessageManager.pendingMessageStatus(id) + |> mapToSignal { status, _ -> Signal in + if status != nil { + return .never() + } else { + return .single(true) + } + } + |> take(1) + }) + if strongSelf.shareStatusDisposable == nil { + strongSelf.shareStatusDisposable = MetaDisposable() + } + strongSelf.shareStatusDisposable?.set((combineLatest(signals) + |> deliverOnMainQueue).startStrict(next: { [weak strongSelf] _ in + guard let strongSelf = strongSelf else { + return + } + strongSelf.chatDisplayNode.hapticFeedback.success() + let _ = (strongSelf.context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: strongSelf.context.account.peerId)) + |> deliverOnMainQueue).startStandalone(next: { [weak strongSelf] peer in + guard let strongSelf = strongSelf, let peer = peer, let navigationController = strongSelf.effectiveNavigationController else { + return + } + + var navigationSubject: ChatControllerSubject? = nil + for messageId in messageIds { + if let messageId = messageId { + navigationSubject = .message(id: .id(messageId), highlight: ChatControllerSubject.MessageHighlight(quote: nil), timecode: nil, setupReply: false) + break + } + } + strongSelf.context.sharedContext.navigateToChatController(NavigateToChatControllerParams(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(peer), subject: navigationSubject, keepStack: .always, purposefulAction: {}, peekData: nil)) + }) + } )) + } + }) + }) + } +} diff --git a/Swiftgram/FLEX/BUILD b/Swiftgram/FLEX/BUILD new file mode 100644 index 00000000..e69de29b diff --git a/Swiftgram/FLEX/FLEX.BUILD b/Swiftgram/FLEX/FLEX.BUILD new file mode 100644 index 00000000..52e69f69 --- /dev/null +++ b/Swiftgram/FLEX/FLEX.BUILD @@ -0,0 +1,68 @@ +objc_library( + name = "FLEX", + module_name = "FLEX", + srcs = glob( + ["Classes/**/*"], + exclude = [ + "Classes/Info.plist", + "Classes/Utility/APPLE_LICENSE", + "Classes/Network/OSCache/LICENSE.md", + "Classes/Network/PonyDebugger/LICENSE", + "Classes/GlobalStateExplorers/DatabaseBrowser/LICENSE", + "Classes/GlobalStateExplorers/Keychain/SSKeychain_LICENSE", + "Classes/GlobalStateExplorers/SystemLog/LLVM_LICENSE.TXT", + ] + ), + hdrs = glob([ + "Classes/**/*.h" + ]), + includes = [ + "Classes", + "Classes/Core", + "Classes/Core/Controllers", + "Classes/Core/Views", + "Classes/Core/Views/Cells", + "Classes/Core/Views/Carousel", + "Classes/ObjectExplorers", + "Classes/ObjectExplorers/Sections", + "Classes/ObjectExplorers/Sections/Shortcuts", + "Classes/Network", + "Classes/Network/PonyDebugger", + "Classes/Network/OSCache", + "Classes/Toolbar", + "Classes/Manager", + "Classes/Manager/Private", + "Classes/Editing", + "Classes/Editing/ArgumentInputViews", + "Classes/Headers", + "Classes/ExplorerInterface", + "Classes/ExplorerInterface/Tabs", + "Classes/ExplorerInterface/Bookmarks", + "Classes/GlobalStateExplorers", + "Classes/GlobalStateExplorers/Globals", + "Classes/GlobalStateExplorers/Keychain", + "Classes/GlobalStateExplorers/FileBrowser", + "Classes/GlobalStateExplorers/SystemLog", + "Classes/GlobalStateExplorers/DatabaseBrowser", + "Classes/GlobalStateExplorers/RuntimeBrowser", + "Classes/GlobalStateExplorers/RuntimeBrowser/DataSources", + "Classes/ViewHierarchy", + "Classes/ViewHierarchy/SnapshotExplorer", + "Classes/ViewHierarchy/SnapshotExplorer/Scene", + "Classes/ViewHierarchy/TreeExplorer", + "Classes/Utility", + "Classes/Utility/Runtime", + "Classes/Utility/Runtime/Objc", + "Classes/Utility/Runtime/Objc/Reflection", + "Classes/Utility/Categories", + "Classes/Utility/Categories/Private", + "Classes/Utility/Keyboard" + ], + copts = [ + "-Wno-deprecated-declarations", + "-Wno-strict-prototypes", + "-Wno-unsupported-availability-guard", + ], + deps = [], + visibility = ["//visibility:public"], +) \ No newline at end of file diff --git a/Swiftgram/FixConcurrencyBackport/BUILD b/Swiftgram/FixConcurrencyBackport/BUILD new file mode 100644 index 00000000..bebc96f6 --- /dev/null +++ b/Swiftgram/FixConcurrencyBackport/BUILD @@ -0,0 +1,43 @@ +# Something changed in Telegram versions 11.8.1 -> 11.10 +# https://github.com/TelegramMessenger/Telegram-iOS/compare/release-11.8.1...TelegramMessenger:Telegram-iOS:release-11.10 +# +# Since then, all binaries and libs are linked to the /usr/lib/swift/libswift_Concurrency.dylib instead of expected @rpath/libswift_Concurrency.dylib, +# this makes swift-stdlib-tool to ignore libswift_Concurrency.dylib and not copy it to the app bundle. +# This causes crash on every system that expects this backport (iOS 14 and below). +# This script will remap the path to @rpath/libswift_Concurrency.dylib in all binaries of the App, it's only needed for iphoneos target in this project. +# This is a temporary fix until minimum OS version will be bumped to iOS 15+ or Xcode version changed to 16.3 (with Swift 6.1 support) + +# find "$1" -type f \( -perm +111 -o -name "*.dylib" \) | while read -r bin; do +# if otool -L "$bin" | grep -q "/usr/lib/swift/libswift_Concurrency.dylib"; then +# echo "Patching concurrency backport in: $bin" +# install_name_tool -change /usr/lib/swift/libswift_Concurrency.dylib @rpath/libswift_Concurrency.dylib "$bin" +# fi +# done + +# concurrency-dylib.patch must be applied in build-system/bazel-rules/rules_apple +# cd Swiftgram/FixConcurrencyBackport +# git apply ../../../Swiftgram/FixConcurrencyBackport/concurrency-dylib.patch +# # Make a build +# git apply -R ../../../Swiftgram/FixConcurrencyBackport/concurrency-dylib.patch + +# Refs: +# https://stackoverflow.com/questions/79522371/when-building-the-project-with-xcode-16-2-the-app-crashes-due-to-an-incorrect-l +# https://github.com/swiftlang/swift/issues/74303 +# https://github.com/bazelbuild/rules_apple/pull/1393 + +genrule( + name = "CopyConcurrencyDylib", + cmd_bash = +""" + echo 'ditto "$$(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.5/iphoneos/libswift_Concurrency.dylib" "$$1/Payload/Swiftgram.app/Frameworks/libswift_Concurrency.dylib"' > $(location CopyConcurrencyDylib.sh) + echo 'ditto "$$1/Payload/Swiftgram.app/Frameworks/libswift_Concurrency.dylib" "$$1/SwiftSupport/iphoneos/libswift_Concurrency.dylib"' >> $(location CopyConcurrencyDylib.sh) + echo '' >> $(location CopyConcurrencyDylib.sh) +""", + outs = [ + "CopyConcurrencyDylib.sh", + ], + executable = True, + visibility = [ + "//visibility:public", + ] +) \ No newline at end of file diff --git a/Swiftgram/FixConcurrencyBackport/concurrency-dylib.patch b/Swiftgram/FixConcurrencyBackport/concurrency-dylib.patch new file mode 100644 index 00000000..794749f7 --- /dev/null +++ b/Swiftgram/FixConcurrencyBackport/concurrency-dylib.patch @@ -0,0 +1,25 @@ +diff --git a/tools/swift_stdlib_tool/swift_stdlib_tool.py b/tools/swift_stdlib_tool/swift_stdlib_tool.py +index fbb7f4fb..5a2277c5 100644 +--- a/tools/swift_stdlib_tool/swift_stdlib_tool.py ++++ b/tools/swift_stdlib_tool/swift_stdlib_tool.py +@@ -134,6 +134,20 @@ def _copy_swift_stdlibs(binaries_to_scan, sdk_platform, destination_path): + if os.path.exists(libswiftcore_path): + os.remove(libswiftcore_path) + ++ # MARK: Swiftgram ++ if sdk_platform == "iphoneos": ++ # Copy the concurrency runtime to the destination path. ++ _, stdout, stderr = execute.execute_and_filter_output( ++ [ ++ "ditto", ++ f"{developer_dir}/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.5/iphoneos/libswift_Concurrency.dylib", ++ os.path.join(destination_path, "libswift_Concurrency.dylib") ++ ], raise_on_failure=True) ++ if stderr: ++ print(stderr) ++ if stdout: ++ print(stdout) ++ + + def _lipo_exec_files(exec_files, target_archs, strip_bitcode, source_path, + destination_path): diff --git a/Swiftgram/Playground/.swiftformat b/Swiftgram/Playground/.swiftformat new file mode 100644 index 00000000..842cb77a --- /dev/null +++ b/Swiftgram/Playground/.swiftformat @@ -0,0 +1,3 @@ +--maxwidth 100 +--indent 4 +--disable redundantSelf \ No newline at end of file diff --git a/Swiftgram/Playground/BUILD b/Swiftgram/Playground/BUILD new file mode 100644 index 00000000..f8603786 --- /dev/null +++ b/Swiftgram/Playground/BUILD @@ -0,0 +1,87 @@ +load("@bazel_skylib//rules:common_settings.bzl", + "bool_flag", +) +load("@build_bazel_rules_apple//apple:ios.bzl", "ios_application") +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +load( + "@rules_xcodeproj//xcodeproj:defs.bzl", + "top_level_targets", + "xcodeproj", +) +load( + "@build_configuration//:variables.bzl", "telegram_bazel_path" +) + +bool_flag( + name = "disableProvisioningProfiles", + build_setting_default = False, + visibility = ["//visibility:public"], +) + +config_setting( + name = "disableProvisioningProfilesSetting", + flag_values = { + ":disableProvisioningProfiles": "True", + }, +) + +objc_library( + name = "PlaygroundMain", + srcs = [ + "Sources/main.m" + ], +) + + +swift_library( + name = "PlaygroundLib", + srcs = glob(["Sources/**/*.swift"]), + deps = [ + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + "//submodules/Display:Display", + "//submodules/AsyncDisplayKit:AsyncDisplayKit", + "//submodules/LegacyUI:LegacyUI", + "//submodules/LegacyComponents:LegacyComponents", + "//submodules/MediaPlayer:UniversalMediaPlayer", + "//Swiftgram/SGSwiftUI:SGSwiftUI", + ], + data = [ + "//Telegram:GeneratedPresentationStrings/Resources/PresentationStrings.data", + ], + visibility = ["//visibility:public"], +) + +ios_application( + name = "Playground", + bundle_id = "app.swiftgram.ios.Playground", + families = [ + "iphone", + "ipad", + ], + provisioning_profile = select({ + ":disableProvisioningProfilesSetting": None, + "//conditions:default": "codesigning/Playground.mobileprovision", + }), + infoplists = ["Resources/Info.plist"], + minimum_os_version = "14.0", + visibility = ["//visibility:public"], + strings = [ + "//Telegram:AppStringResources", + ], + launch_storyboard = "Resources/LaunchScreen.storyboard", + deps = [":PlaygroundMain", ":PlaygroundLib"], +) + +xcodeproj( + bazel_path = telegram_bazel_path, + name = "Playground_xcodeproj", + build_mode = "bazel", + project_name = "Playground", + tags = ["manual"], + top_level_targets = top_level_targets( + labels = [ + ":Playground", + ], + target_environments = ["device", "simulator"], + ), +) \ No newline at end of file diff --git a/Swiftgram/Playground/README.md b/Swiftgram/Playground/README.md new file mode 100644 index 00000000..221a308b --- /dev/null +++ b/Swiftgram/Playground/README.md @@ -0,0 +1,25 @@ +# Swiftgram Playground + +Small app to quickly iterate on components testing without building an entire messenger. + +## (Optional) Setup Codesigning + +Create simple `codesigning/Playground.mobileprovision`. It is only required for non-simulator builds and can be skipped with `--disableProvisioningProfiles`. + +## Generate Xcode project + +Same as main project described in [../../Readme.md](../../Readme.md), but with `--target="Swiftgram/Playground"` parameter. + +## Run generated project on simulator + +### From root + +```shell +./Swiftgram/Playground/launch_on_simulator.py +``` + +### From current directory + +```shell +./launch_on_simulator.py +``` diff --git a/Swiftgram/Playground/Resources/Info.plist b/Swiftgram/Playground/Resources/Info.plist new file mode 100644 index 00000000..95fdf06b --- /dev/null +++ b/Swiftgram/Playground/Resources/Info.plist @@ -0,0 +1,39 @@ + + + + + UILaunchScreen + + UILaunchScreen + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + \ No newline at end of file diff --git a/Swiftgram/Playground/Resources/LaunchScreen.storyboard b/Swiftgram/Playground/Resources/LaunchScreen.storyboard new file mode 100644 index 00000000..865e9329 --- /dev/null +++ b/Swiftgram/Playground/Resources/LaunchScreen.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Swiftgram/Playground/Sources/AppDelegate.swift b/Swiftgram/Playground/Sources/AppDelegate.swift new file mode 100644 index 00000000..69404da2 --- /dev/null +++ b/Swiftgram/Playground/Sources/AppDelegate.swift @@ -0,0 +1,82 @@ +import UIKit +import SwiftUI +import AsyncDisplayKit +import Display +import LegacyUI + +let SHOW_SAFE_AREA = false + +@objc(AppDelegate) +final class AppDelegate: NSObject, UIApplicationDelegate { + var window: UIWindow? + + private var mainWindow: Window1? + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { + let statusBarHost = ApplicationStatusBarHost() + let (window, hostView) = nativeWindowHostView() + let mainWindow = Window1(hostView: hostView, statusBarHost: statusBarHost) + self.mainWindow = mainWindow + hostView.containerView.backgroundColor = UIColor.white + self.window = window + + let navigationController = NavigationController( + mode: .single, + theme: NavigationControllerTheme( + statusBar: .black, + navigationBar: THEME.navigationBar, + emptyAreaColor: .white + ) + ) + + mainWindow.viewController = navigationController + + let rootViewController = mySwiftUIViewController(0) + + if SHOW_SAFE_AREA { + // Add insets visualization + rootViewController.view.layoutMargins = .zero + rootViewController.view.subviews.forEach { $0.removeFromSuperview() } + + let topInsetView = UIView() + let leftInsetView = UIView() + let rightInsetView = UIView() + let bottomInsetView = UIView() + + [topInsetView, leftInsetView, rightInsetView, bottomInsetView].forEach { + $0.backgroundColor = .systemRed + $0.alpha = 0.3 + rootViewController.view.addSubview($0) + $0.translatesAutoresizingMaskIntoConstraints = false + } + + NSLayoutConstraint.activate([ + topInsetView.topAnchor.constraint(equalTo: rootViewController.view.topAnchor), + topInsetView.leadingAnchor.constraint(equalTo: rootViewController.view.leadingAnchor), + topInsetView.trailingAnchor.constraint(equalTo: rootViewController.view.trailingAnchor), + topInsetView.bottomAnchor.constraint(equalTo: rootViewController.view.safeAreaLayoutGuide.topAnchor), + + leftInsetView.topAnchor.constraint(equalTo: rootViewController.view.topAnchor), + leftInsetView.leadingAnchor.constraint(equalTo: rootViewController.view.leadingAnchor), + leftInsetView.bottomAnchor.constraint(equalTo: rootViewController.view.bottomAnchor), + leftInsetView.trailingAnchor.constraint(equalTo: rootViewController.view.safeAreaLayoutGuide.leadingAnchor), + + rightInsetView.topAnchor.constraint(equalTo: rootViewController.view.topAnchor), + rightInsetView.trailingAnchor.constraint(equalTo: rootViewController.view.trailingAnchor), + rightInsetView.bottomAnchor.constraint(equalTo: rootViewController.view.bottomAnchor), + rightInsetView.leadingAnchor.constraint(equalTo: rootViewController.view.safeAreaLayoutGuide.trailingAnchor), + + bottomInsetView.bottomAnchor.constraint(equalTo: rootViewController.view.bottomAnchor), + bottomInsetView.leadingAnchor.constraint(equalTo: rootViewController.view.leadingAnchor), + bottomInsetView.trailingAnchor.constraint(equalTo: rootViewController.view.trailingAnchor), + bottomInsetView.topAnchor.constraint(equalTo: rootViewController.view.safeAreaLayoutGuide.bottomAnchor) + ]) + } + + navigationController.setViewControllers([rootViewController], animated: false) + + self.window?.makeKeyAndVisible() + + return true + } +} diff --git a/Swiftgram/Playground/Sources/AppNavigationSetup.swift b/Swiftgram/Playground/Sources/AppNavigationSetup.swift new file mode 100644 index 00000000..28b7549d --- /dev/null +++ b/Swiftgram/Playground/Sources/AppNavigationSetup.swift @@ -0,0 +1,100 @@ +import UIKit +import SwiftUI +import AsyncDisplayKit +import Display + +public func isKeyboardWindow(window: NSObject) -> Bool { + let typeName = NSStringFromClass(type(of: window)) + if #available(iOS 9.0, *) { + if typeName.hasPrefix("UI") && typeName.hasSuffix("RemoteKeyboardWindow") { + return true + } + } else { + if typeName.hasPrefix("UI") && typeName.hasSuffix("TextEffectsWindow") { + return true + } + } + return false +} + +public func isKeyboardView(view: NSObject) -> Bool { + let typeName = NSStringFromClass(type(of: view)) + if typeName.hasPrefix("UI") && typeName.hasSuffix("InputSetHostView") { + return true + } + return false +} + +public func isKeyboardViewContainer(view: NSObject) -> Bool { + let typeName = NSStringFromClass(type(of: view)) + if typeName.hasPrefix("UI") && typeName.hasSuffix("InputSetContainerView") { + return true + } + return false +} + +public class ApplicationStatusBarHost: StatusBarHost { + private let application = UIApplication.shared + + public var isApplicationInForeground: Bool { + switch self.application.applicationState { + case .background: + return false + default: + return true + } + } + + public var statusBarFrame: CGRect { + return self.application.statusBarFrame + } + public var statusBarStyle: UIStatusBarStyle { + get { + return self.application.statusBarStyle + } set(value) { + self.setStatusBarStyle(value, animated: false) + } + } + + public func setStatusBarStyle(_ style: UIStatusBarStyle, animated: Bool) { + if self.shouldChangeStatusBarStyle?(style) ?? true { + self.application.internalSetStatusBarStyle(style, animated: animated) + } + } + + public var shouldChangeStatusBarStyle: ((UIStatusBarStyle) -> Bool)? + + public func setStatusBarHidden(_ value: Bool, animated: Bool) { + self.application.internalSetStatusBarHidden(value, animation: animated ? .fade : .none) + } + + public var keyboardWindow: UIWindow? { + if #available(iOS 16.0, *) { + return UIApplication.shared.internalGetKeyboard() + } + + for window in UIApplication.shared.windows { + if isKeyboardWindow(window: window) { + return window + } + } + return nil + } + + public var keyboardView: UIView? { + guard let keyboardWindow = self.keyboardWindow else { + return nil + } + + for view in keyboardWindow.subviews { + if isKeyboardViewContainer(view: view) { + for subview in view.subviews { + if isKeyboardView(view: subview) { + return subview + } + } + } + } + return nil + } +} diff --git a/Swiftgram/Playground/Sources/Application.swift b/Swiftgram/Playground/Sources/Application.swift new file mode 100644 index 00000000..12e82558 --- /dev/null +++ b/Swiftgram/Playground/Sources/Application.swift @@ -0,0 +1,5 @@ +import UIKit + +@objc(Application) class Application: UIApplication { + +} \ No newline at end of file diff --git a/Swiftgram/Playground/Sources/Example/PlaygroundSplashScreen.swift b/Swiftgram/Playground/Sources/Example/PlaygroundSplashScreen.swift new file mode 100644 index 00000000..982fcbf4 --- /dev/null +++ b/Swiftgram/Playground/Sources/Example/PlaygroundSplashScreen.swift @@ -0,0 +1,95 @@ +import Foundation +import UIKit +import AsyncDisplayKit +import Display + +private final class PlaygroundSplashScreenNode: ASDisplayNode { + private let headerBackgroundNode: ASDisplayNode + private let headerCornerNode: ASImageNode + + private var isDismissed = false + + private var validLayout: (layout: ContainerViewLayout, navigationHeight: CGFloat)? + + override init() { + self.headerBackgroundNode = ASDisplayNode() + self.headerBackgroundNode.backgroundColor = .black + + self.headerCornerNode = ASImageNode() + self.headerCornerNode.displaysAsynchronously = false + self.headerCornerNode.displayWithoutProcessing = true + self.headerCornerNode.image = generateImage(CGSize(width: 20.0, height: 10.0), rotatedContext: { size, context in + context.setFillColor(UIColor.black.cgColor) + context.fill(CGRect(origin: CGPoint(), size: size)) + context.setBlendMode(.copy) + context.setFillColor(UIColor.clear.cgColor) + context.fillEllipse(in: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: 20.0, height: 20.0))) + })?.stretchableImage(withLeftCapWidth: 10, topCapHeight: 1) + + super.init() + + self.backgroundColor = THEME.list.itemBlocksBackgroundColor + + self.addSubnode(self.headerBackgroundNode) + self.addSubnode(self.headerCornerNode) + } + + func containerLayoutUpdated(layout: ContainerViewLayout, navigationHeight: CGFloat, transition: ContainedViewLayoutTransition) { + if self.isDismissed { + return + } + self.validLayout = (layout, navigationHeight) + + let headerHeight = navigationHeight + 260.0 + + transition.updateFrame(node: self.headerBackgroundNode, frame: CGRect(origin: CGPoint(x: -1.0, y: 0), size: CGSize(width: layout.size.width + 2.0, height: headerHeight))) + transition.updateFrame(node: self.headerCornerNode, frame: CGRect(origin: CGPoint(x: 0.0, y: headerHeight), size: CGSize(width: layout.size.width, height: 10.0))) + } + + func animateOut(completion: @escaping () -> Void) { + guard let (layout, navigationHeight) = self.validLayout else { + completion() + return + } + self.isDismissed = true + let transition: ContainedViewLayoutTransition = .animated(duration: 0.4, curve: .spring) + + let headerHeight = navigationHeight + 260.0 + + transition.updateFrame(node: self.headerBackgroundNode, frame: CGRect(origin: CGPoint(x: -1.0, y: -headerHeight - 10.0), size: CGSize(width: layout.size.width + 2.0, height: headerHeight)), completion: { _ in + completion() + }) + transition.updateFrame(node: self.headerCornerNode, frame: CGRect(origin: CGPoint(x: 0.0, y: -10.0), size: CGSize(width: layout.size.width, height: 10.0))) + } +} + +public final class PlaygroundSplashScreen: ViewController { + + public init() { + + let navigationBarTheme = NavigationBarTheme(buttonColor: .white, disabledButtonColor: .white, primaryTextColor: .white, backgroundColor: .clear, enableBackgroundBlur: true, separatorColor: .clear, badgeBackgroundColor: THEME.navigationBar.badgeBackgroundColor, badgeStrokeColor: THEME.navigationBar.badgeStrokeColor, badgeTextColor: THEME.navigationBar.badgeTextColor) + + super.init(navigationBarPresentationData: NavigationBarPresentationData(theme: navigationBarTheme, strings: NavigationBarStrings(back: "", close: ""))) + + self.statusBar.statusBarStyle = .White + } + + required public init(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override public func loadDisplayNode() { + self.displayNode = PlaygroundSplashScreenNode() + } + + override public func containerLayoutUpdated(_ layout: ContainerViewLayout, transition: ContainedViewLayoutTransition) { + super.containerLayoutUpdated(layout, transition: transition) + + (self.displayNode as! PlaygroundSplashScreenNode).containerLayoutUpdated(layout: layout, navigationHeight: self.navigationLayout(layout: layout).navigationFrame.maxY, transition: transition) + } + + public func animateOut(completion: @escaping () -> Void) { + self.statusBar.statusBarStyle = .Black + (self.displayNode as! PlaygroundSplashScreenNode).animateOut(completion: completion) + } +} diff --git a/Swiftgram/Playground/Sources/PlaygroundTheme.swift b/Swiftgram/Playground/Sources/PlaygroundTheme.swift new file mode 100644 index 00000000..b05d7933 --- /dev/null +++ b/Swiftgram/Playground/Sources/PlaygroundTheme.swift @@ -0,0 +1,362 @@ +import Foundation +import UIKit +import Display +import SwiftSignalKit + + +public final class PlaygroundInfoTheme { + public let buttonBackgroundColor: UIColor + public let buttonTextColor: UIColor + public let incomingFundsTitleColor: UIColor + public let outgoingFundsTitleColor: UIColor + + public init( + buttonBackgroundColor: UIColor, + buttonTextColor: UIColor, + incomingFundsTitleColor: UIColor, + outgoingFundsTitleColor: UIColor + ) { + self.buttonBackgroundColor = buttonBackgroundColor + self.buttonTextColor = buttonTextColor + self.incomingFundsTitleColor = incomingFundsTitleColor + self.outgoingFundsTitleColor = outgoingFundsTitleColor + } +} + +public final class PlaygroundTransactionTheme { + public let descriptionBackgroundColor: UIColor + public let descriptionTextColor: UIColor + + public init( + descriptionBackgroundColor: UIColor, + descriptionTextColor: UIColor + ) { + self.descriptionBackgroundColor = descriptionBackgroundColor + self.descriptionTextColor = descriptionTextColor + } +} + +public final class PlaygroundSetupTheme { + public let buttonFillColor: UIColor + public let buttonForegroundColor: UIColor + public let inputBackgroundColor: UIColor + public let inputPlaceholderColor: UIColor + public let inputTextColor: UIColor + public let inputClearButtonColor: UIColor + + public init( + buttonFillColor: UIColor, + buttonForegroundColor: UIColor, + inputBackgroundColor: UIColor, + inputPlaceholderColor: UIColor, + inputTextColor: UIColor, + inputClearButtonColor: UIColor + ) { + self.buttonFillColor = buttonFillColor + self.buttonForegroundColor = buttonForegroundColor + self.inputBackgroundColor = inputBackgroundColor + self.inputPlaceholderColor = inputPlaceholderColor + self.inputTextColor = inputTextColor + self.inputClearButtonColor = inputClearButtonColor + } +} + +public final class PlaygroundListTheme { + public let itemPrimaryTextColor: UIColor + public let itemSecondaryTextColor: UIColor + public let itemPlaceholderTextColor: UIColor + public let itemDestructiveColor: UIColor + public let itemAccentColor: UIColor + public let itemDisabledTextColor: UIColor + public let plainBackgroundColor: UIColor + public let blocksBackgroundColor: UIColor + public let itemPlainSeparatorColor: UIColor + public let itemBlocksBackgroundColor: UIColor + public let itemBlocksSeparatorColor: UIColor + public let itemHighlightedBackgroundColor: UIColor + public let sectionHeaderTextColor: UIColor + public let freeTextColor: UIColor + public let freeTextErrorColor: UIColor + public let inputClearButtonColor: UIColor + + public init( + itemPrimaryTextColor: UIColor, + itemSecondaryTextColor: UIColor, + itemPlaceholderTextColor: UIColor, + itemDestructiveColor: UIColor, + itemAccentColor: UIColor, + itemDisabledTextColor: UIColor, + plainBackgroundColor: UIColor, + blocksBackgroundColor: UIColor, + itemPlainSeparatorColor: UIColor, + itemBlocksBackgroundColor: UIColor, + itemBlocksSeparatorColor: UIColor, + itemHighlightedBackgroundColor: UIColor, + sectionHeaderTextColor: UIColor, + freeTextColor: UIColor, + freeTextErrorColor: UIColor, + inputClearButtonColor: UIColor + ) { + self.itemPrimaryTextColor = itemPrimaryTextColor + self.itemSecondaryTextColor = itemSecondaryTextColor + self.itemPlaceholderTextColor = itemPlaceholderTextColor + self.itemDestructiveColor = itemDestructiveColor + self.itemAccentColor = itemAccentColor + self.itemDisabledTextColor = itemDisabledTextColor + self.plainBackgroundColor = plainBackgroundColor + self.blocksBackgroundColor = blocksBackgroundColor + self.itemPlainSeparatorColor = itemPlainSeparatorColor + self.itemBlocksBackgroundColor = itemBlocksBackgroundColor + self.itemBlocksSeparatorColor = itemBlocksSeparatorColor + self.itemHighlightedBackgroundColor = itemHighlightedBackgroundColor + self.sectionHeaderTextColor = sectionHeaderTextColor + self.freeTextColor = freeTextColor + self.freeTextErrorColor = freeTextErrorColor + self.inputClearButtonColor = inputClearButtonColor + } +} + +public final class PlaygroundTheme: Equatable { + public let info: PlaygroundInfoTheme + public let transaction: PlaygroundTransactionTheme + public let setup: PlaygroundSetupTheme + public let list: PlaygroundListTheme + public let statusBarStyle: StatusBarStyle + public let navigationBar: NavigationBarTheme + public let keyboardAppearance: UIKeyboardAppearance + public let alert: AlertControllerTheme + public let actionSheet: ActionSheetControllerTheme + + private let resourceCache = PlaygroundThemeResourceCache() + + public init(info: PlaygroundInfoTheme, transaction: PlaygroundTransactionTheme, setup: PlaygroundSetupTheme, list: PlaygroundListTheme, statusBarStyle: StatusBarStyle, navigationBar: NavigationBarTheme, keyboardAppearance: UIKeyboardAppearance, alert: AlertControllerTheme, actionSheet: ActionSheetControllerTheme) { + self.info = info + self.transaction = transaction + self.setup = setup + self.list = list + self.statusBarStyle = statusBarStyle + self.navigationBar = navigationBar + self.keyboardAppearance = keyboardAppearance + self.alert = alert + self.actionSheet = actionSheet + } + + func image(_ key: Int32, _ generate: (PlaygroundTheme) -> UIImage?) -> UIImage? { + return self.resourceCache.image(key, self, generate) + } + + public static func ==(lhs: PlaygroundTheme, rhs: PlaygroundTheme) -> Bool { + return lhs === rhs + } +} + + +private final class PlaygroundThemeResourceCacheHolder { + var images: [Int32: UIImage] = [:] +} + +private final class PlaygroundThemeResourceCache { + private let imageCache = Atomic(value: PlaygroundThemeResourceCacheHolder()) + + public func image(_ key: Int32, _ theme: PlaygroundTheme, _ generate: (PlaygroundTheme) -> UIImage?) -> UIImage? { + let result = self.imageCache.with { holder -> UIImage? in + return holder.images[key] + } + if let result = result { + return result + } else { + if let image = generate(theme) { + self.imageCache.with { holder -> Void in + holder.images[key] = image + } + return image + } else { + return nil + } + } + } +} + +enum PlaygroundThemeResourceKey: Int32 { + case itemListCornersBoth + case itemListCornersTop + case itemListCornersBottom + case itemListClearInputIcon + case itemListDisclosureArrow + case navigationShareIcon + case transactionLockIcon + + case clockMin + case clockFrame +} + +func cornersImage(_ theme: PlaygroundTheme, top: Bool, bottom: Bool) -> UIImage? { + if !top && !bottom { + return nil + } + let key: PlaygroundThemeResourceKey + if top && bottom { + key = .itemListCornersBoth + } else if top { + key = .itemListCornersTop + } else { + key = .itemListCornersBottom + } + return theme.image(key.rawValue, { theme in + return generateImage(CGSize(width: 50.0, height: 50.0), rotatedContext: { (size, context) in + let bounds = CGRect(origin: CGPoint(), size: size) + context.setFillColor(theme.list.blocksBackgroundColor.cgColor) + context.fill(bounds) + + context.setBlendMode(.clear) + + var corners: UIRectCorner = [] + if top { + corners.insert(.topLeft) + corners.insert(.topRight) + } + if bottom { + corners.insert(.bottomLeft) + corners.insert(.bottomRight) + } + let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: 11.0, height: 11.0)) + context.addPath(path.cgPath) + context.fillPath() + })?.stretchableImage(withLeftCapWidth: 25, topCapHeight: 25) + }) +} + +func itemListClearInputIcon(_ theme: PlaygroundTheme) -> UIImage? { + return theme.image(PlaygroundThemeResourceKey.itemListClearInputIcon.rawValue, { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Playground/ClearInput"), color: theme.list.inputClearButtonColor) + }) +} + +func navigationShareIcon(_ theme: PlaygroundTheme) -> UIImage? { + return theme.image(PlaygroundThemeResourceKey.navigationShareIcon.rawValue, { theme in + generateTintedImage(image: UIImage(bundleImageName: "Playground/NavigationShare"), color: theme.navigationBar.buttonColor) + }) +} + +func disclosureArrowImage(_ theme: PlaygroundTheme) -> UIImage? { + return theme.image(PlaygroundThemeResourceKey.itemListDisclosureArrow.rawValue, { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Playground/DisclosureArrow"), color: theme.list.itemSecondaryTextColor) + }) +} + +func clockFrameImage(_ theme: PlaygroundTheme) -> UIImage? { + return theme.image(PlaygroundThemeResourceKey.clockFrame.rawValue, { theme in + let color = theme.list.itemSecondaryTextColor + return generateImage(CGSize(width: 11.0, height: 11.0), contextGenerator: { size, context in + context.clear(CGRect(origin: CGPoint(), size: size)) + context.setStrokeColor(color.cgColor) + context.setFillColor(color.cgColor) + let strokeWidth: CGFloat = 1.0 + context.setLineWidth(strokeWidth) + context.strokeEllipse(in: CGRect(x: strokeWidth / 2.0, y: strokeWidth / 2.0, width: size.width - strokeWidth, height: size.height - strokeWidth)) + context.fill(CGRect(x: (11.0 - strokeWidth) / 2.0, y: strokeWidth * 3.0, width: strokeWidth, height: 11.0 / 2.0 - strokeWidth * 3.0)) + }) + }) +} + +func clockMinImage(_ theme: PlaygroundTheme) -> UIImage? { + return theme.image(PlaygroundThemeResourceKey.clockMin.rawValue, { theme in + let color = theme.list.itemSecondaryTextColor + return generateImage(CGSize(width: 11.0, height: 11.0), contextGenerator: { size, context in + context.clear(CGRect(origin: CGPoint(), size: size)) + context.setFillColor(color.cgColor) + let strokeWidth: CGFloat = 1.0 + context.fill(CGRect(x: (11.0 - strokeWidth) / 2.0, y: (11.0 - strokeWidth) / 2.0, width: 11.0 / 2.0 - strokeWidth, height: strokeWidth)) + }) + }) +} + +func PlaygroundTransactionLockIcon(_ theme: PlaygroundTheme) -> UIImage? { + return theme.image(PlaygroundThemeResourceKey.transactionLockIcon.rawValue, { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Playground/EncryptedComment"), color: theme.list.itemSecondaryTextColor) + }) +} + + +public let ACCENT_COLOR = UIColor(rgb: 0x007ee5) +public let NAVIGATION_BAR_THEME = NavigationBarTheme( + buttonColor: ACCENT_COLOR, + disabledButtonColor: UIColor(rgb: 0xd0d0d0), + primaryTextColor: .black, + backgroundColor: UIColor(rgb: 0xf7f7f7), + enableBackgroundBlur: true, + separatorColor: UIColor(rgb: 0xb1b1b1), + badgeBackgroundColor: UIColor(rgb: 0xff3b30), + badgeStrokeColor: UIColor(rgb: 0xff3b30), + badgeTextColor: .white +) +public let THEME = PlaygroundTheme( + info: PlaygroundInfoTheme( + buttonBackgroundColor: UIColor(rgb: 0x32aafe), + buttonTextColor: .white, + incomingFundsTitleColor: UIColor(rgb: 0x00b12c), + outgoingFundsTitleColor: UIColor(rgb: 0xff3b30) + ), transaction: PlaygroundTransactionTheme( + descriptionBackgroundColor: UIColor(rgb: 0xf1f1f4), + descriptionTextColor: .black + ), setup: PlaygroundSetupTheme( + buttonFillColor: ACCENT_COLOR, + buttonForegroundColor: .white, + inputBackgroundColor: UIColor(rgb: 0xe9e9e9), + inputPlaceholderColor: UIColor(rgb: 0x818086), + inputTextColor: .black, + inputClearButtonColor: UIColor(rgb: 0x7b7b81).withAlphaComponent(0.8) + ), + list: PlaygroundListTheme( + itemPrimaryTextColor: .black, + itemSecondaryTextColor: UIColor(rgb: 0x8e8e93), + itemPlaceholderTextColor: UIColor(rgb: 0xc8c8ce), + itemDestructiveColor: UIColor(rgb: 0xff3b30), + itemAccentColor: ACCENT_COLOR, + itemDisabledTextColor: UIColor(rgb: 0x8e8e93), + plainBackgroundColor: .white, + blocksBackgroundColor: UIColor(rgb: 0xefeff4), + itemPlainSeparatorColor: UIColor(rgb: 0xc8c7cc), + itemBlocksBackgroundColor: .white, + itemBlocksSeparatorColor: UIColor(rgb: 0xc8c7cc), + itemHighlightedBackgroundColor: UIColor(rgb: 0xe5e5ea), + sectionHeaderTextColor: UIColor(rgb: 0x6d6d72), + freeTextColor: UIColor(rgb: 0x6d6d72), + freeTextErrorColor: UIColor(rgb: 0xcf3030), + inputClearButtonColor: UIColor(rgb: 0xcccccc) + ), + statusBarStyle: .Black, + navigationBar: NAVIGATION_BAR_THEME, + keyboardAppearance: .light, + alert: AlertControllerTheme( + backgroundType: .light, + backgroundColor: .white, + separatorColor: UIColor(white: 0.9, alpha: 1.0), + highlightedItemColor: UIColor(rgb: 0xe5e5ea), + primaryColor: .black, + secondaryColor: UIColor(rgb: 0x5e5e5e), + accentColor: ACCENT_COLOR, + contrastColor: .green, + destructiveColor: UIColor(rgb: 0xff3b30), + disabledColor: UIColor(rgb: 0xd0d0d0), + controlBorderColor: .green, + baseFontSize: 17.0 + ), + actionSheet: ActionSheetControllerTheme( + dimColor: UIColor(white: 0.0, alpha: 0.4), + backgroundType: .light, + itemBackgroundColor: .white, + itemHighlightedBackgroundColor: UIColor(white: 0.9, alpha: 1.0), + standardActionTextColor: ACCENT_COLOR, + destructiveActionTextColor: UIColor(rgb: 0xff3b30), + disabledActionTextColor: UIColor(rgb: 0xb3b3b3), + primaryTextColor: .black, + secondaryTextColor: UIColor(rgb: 0x5e5e5e), + controlAccentColor: ACCENT_COLOR, + controlColor: UIColor(rgb: 0x7e8791), + switchFrameColor: UIColor(rgb: 0xe0e0e0), + switchContentColor: UIColor(rgb: 0x77d572), + switchHandleColor: UIColor(rgb: 0xffffff), + baseFontSize: 17.0 + ) +) diff --git a/Swiftgram/Playground/Sources/SwiftUIViewController.swift b/Swiftgram/Playground/Sources/SwiftUIViewController.swift new file mode 100644 index 00000000..139230a3 --- /dev/null +++ b/Swiftgram/Playground/Sources/SwiftUIViewController.swift @@ -0,0 +1,85 @@ +import AsyncDisplayKit +import Display +import Foundation +import LegacyUI +import SGSwiftUI +import SwiftUI +import TelegramPresentationData +import UIKit + +struct MySwiftUIView: View { + weak var wrapperController: LegacyController? + + var num: Int64 + + var body: some View { + ScrollView { + Text("Hello, World!") + .font(.title) + .foregroundColor(.black) + + Spacer(minLength: 0) + + Button("Push") { + self.wrapperController?.push(mySwiftUIViewController(num + 1)) + }.buttonStyle(AppleButtonStyle()) + Spacer() + Button("Modal") { + self.wrapperController?.present( + mySwiftUIViewController(num + 1), + in: .window(.root), + with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet) + ) + }.buttonStyle(AppleButtonStyle()) + Spacer() + if num > 0 { + Button("Dismiss") { + self.wrapperController?.dismiss() + }.buttonStyle(AppleButtonStyle()) + Spacer() + } + ForEach(1..<20, id: \.self) { i in + Button("TAP: \(i)") { + print("Tapped \(i)") + }.buttonStyle(AppleButtonStyle()) + } + + } + .background(Color.green) + } +} + +struct AppleButtonStyle: ButtonStyle { + func makeBody(configuration: Configuration) -> some View { + configuration.label + .font(.headline) + .foregroundColor(.white) + .padding() + .frame(minWidth: 0, maxWidth: .infinity) + .background(Color.blue) + .cornerRadius(10) + .scaleEffect(configuration.isPressed ? 0.95 : 1) + .opacity(configuration.isPressed ? 0.9 : 1) + } +} + +public func mySwiftUIViewController(_ num: Int64) -> ViewController { + let legacyController = LegacySwiftUIController( + presentation: .modal(animateIn: true), + theme: defaultPresentationTheme, + strings: defaultPresentationStrings + ) + legacyController.statusBar.statusBarStyle = defaultPresentationTheme.rootController + .statusBarStyle.style + legacyController.title = "Controller: \(num)" + + let swiftUIView = SGSwiftUIView( + navigationBarHeight: legacyController.navigationBarHeightModel, + containerViewLayout: legacyController.containerViewLayoutModel, + content: { MySwiftUIView(wrapperController: legacyController, num: num) } + ) + let controller = UIHostingController(rootView: swiftUIView, ignoreSafeArea: true) + legacyController.bind(controller: controller) + + return legacyController +} diff --git a/Swiftgram/Playground/Sources/main.m b/Swiftgram/Playground/Sources/main.m new file mode 100644 index 00000000..a63f787d --- /dev/null +++ b/Swiftgram/Playground/Sources/main.m @@ -0,0 +1,7 @@ +#import + +int main(int argc, char *argv[]) { + @autoreleasepool { + return UIApplicationMain(argc, argv, @"Application", @"AppDelegate"); + } +} \ No newline at end of file diff --git a/Swiftgram/Playground/generate_project.py b/Swiftgram/Playground/generate_project.py new file mode 100755 index 00000000..cc2e1351 --- /dev/null +++ b/Swiftgram/Playground/generate_project.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 + +from contextlib import contextmanager +import os +import subprocess +import sys +import shutil +import textwrap + +# Import the locate_bazel function +sys.path.append( + os.path.join(os.path.dirname(__file__), "..", "..", "build-system", "Make") +) +from BazelLocation import locate_bazel + + +@contextmanager +def cwd(path): + oldpwd = os.getcwd() + os.chdir(path) + try: + yield + finally: + os.chdir(oldpwd) + + +def main(): + # Get the current script directory + current_script_dir = os.path.dirname(os.path.abspath(__file__)) + with cwd(os.path.join(current_script_dir, "..", "..")): + bazel_path = locate_bazel(os.getcwd(), cache_host=None) + # 1. Kill all Xcode processes + subprocess.run(["killall", "Xcode"], check=False) + + # 2. Delete xcodeproj.bazelrc if it exists and write a new one + bazelrc_path = os.path.join(current_script_dir, "..", "..", "xcodeproj.bazelrc") + if os.path.exists(bazelrc_path): + os.remove(bazelrc_path) + + with open(bazelrc_path, "w") as f: + f.write( + textwrap.dedent( + """ + build --announce_rc + build --features=swift.use_global_module_cache + build --verbose_failures + build --features=swift.enable_batch_mode + build --features=-swift.debug_prefix_map + # build --disk_cache= + + build --swiftcopt=-no-warnings-as-errors + build --copt=-Wno-error + """ + ) + ) + + # 3. Delete the Xcode project if it exists + xcode_project_path = os.path.join(current_script_dir, "Playground.xcodeproj") + if os.path.exists(xcode_project_path): + shutil.rmtree(xcode_project_path) + + # 4. Write content to generate_project.py + generate_project_path = os.path.join(current_script_dir, "custom_bazel_path.bzl") + with open(generate_project_path, "w") as f: + f.write("def custom_bazel_path():\n") + f.write(f' return "{bazel_path}"\n') + + # 5. Run xcodeproj generator + working_dir = os.path.join(current_script_dir, "..", "..") + bazel_command = f'"{bazel_path}" run //Swiftgram/Playground:Playground_xcodeproj' + subprocess.run(bazel_command, shell=True, cwd=working_dir, check=True) + + # 5. Open Xcode project + subprocess.run(["open", xcode_project_path], check=True) + + +if __name__ == "__main__": + main() diff --git a/Swiftgram/Playground/launch_on_simulator.py b/Swiftgram/Playground/launch_on_simulator.py new file mode 100755 index 00000000..feefa4f9 --- /dev/null +++ b/Swiftgram/Playground/launch_on_simulator.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 + +import subprocess +import json +import os +import time + + +def find_app(start_path): + for root, dirs, _ in os.walk(start_path): + for dir in dirs: + if dir.endswith(".app"): + return os.path.join(root, dir) + return None + + +def ensure_simulator_booted(device_name) -> str: + # List all devices + devices_json = subprocess.check_output( + ["xcrun", "simctl", "list", "devices", "--json"] + ).decode() + devices = json.loads(devices_json) + for runtime in devices["devices"]: + for device in devices["devices"][runtime]: + if device["name"] == device_name: + device_udid = device["udid"] + if device["state"] == "Booted": + print(f"Simulator {device_name} is already booted.") + return device_udid + break + if device_udid: + break + + if not device_udid: + raise Exception(f"Simulator {device_name} not found") + + # Boot the device + print(f"Booting simulator {device_name}...") + subprocess.run(["xcrun", "simctl", "boot", device_udid], check=True) + + # Wait for the device to finish booting + print("Waiting for simulator to finish booting...") + while True: + boot_status = subprocess.check_output( + ["xcrun", "simctl", "list", "devices"] + ).decode() + if f"{device_name} ({device_udid}) (Booted)" in boot_status: + break + time.sleep(0.5) + + print(f"Simulator {device_name} is now booted.") + return device_udid + + +def build_and_run_xcode_project(project_path, scheme_name, destination): + # Change to the directory containing the .xcodeproj file + os.chdir(os.path.dirname(project_path)) + + # Build the project + build_command = [ + "xcodebuild", + "-project", + project_path, + "-scheme", + scheme_name, + "-destination", + destination, + "-sdk", + "iphonesimulator", + "build", + ] + + try: + subprocess.run(build_command, check=True) + print("Build successful!") + except subprocess.CalledProcessError as e: + print(f"Build failed with error: {e}") + return + + # Get the bundle identifier and app path + settings_command = [ + "xcodebuild", + "-project", + project_path, + "-scheme", + scheme_name, + "-sdk", + "iphonesimulator", + "-showBuildSettings", + ] + + try: + result = subprocess.run( + settings_command, capture_output=True, text=True, check=True + ) + settings = result.stdout.split("\n") + bundle_id = next( + line.split("=")[1].strip() + for line in settings + if "PRODUCT_BUNDLE_IDENTIFIER" in line + ) + build_dir = next( + line.split("=")[1].strip() + for line in settings + if "TARGET_BUILD_DIR" in line + ) + + app_path = find_app(build_dir) + if not app_path: + print(f"Could not find .app file in {build_dir}") + return + print(f"Found app at: {app_path}") + print(f"Bundle identifier: {bundle_id}") + print(f"App path: {app_path}") + except (subprocess.CalledProcessError, StopIteration) as e: + print(f"Failed to get build settings: {e}") + return + + device_udid = ensure_simulator_booted(simulator_name) + + # Install the app on the simulator + install_command = ["xcrun", "simctl", "install", device_udid, app_path] + + try: + subprocess.run(install_command, check=True) + print("App installed on simulator successfully!") + except subprocess.CalledProcessError as e: + print(f"Failed to install app on simulator: {e}") + return + + # List installed apps + try: + listapps_cmd = "/usr/bin/xcrun simctl listapps booted | /usr/bin/plutil -convert json -r -o - -- -" + result = subprocess.run( + listapps_cmd, shell=True, capture_output=True, text=True, check=True + ) + apps = json.loads(result.stdout) + + if bundle_id in apps: + print(f"App {bundle_id} is installed on the simulator") + else: + print(f"App {bundle_id} is not installed on the simulator") + print("Installed apps:", list(apps.keys())) + except subprocess.CalledProcessError as e: + print(f"Failed to list apps: {e}") + except json.JSONDecodeError as e: + print(f"Failed to parse app list: {e}") + + # Focus simulator + subprocess.run(["open", "-a", "Simulator"], check=True) + + # Run the project on the simulator + run_command = ["xcrun", "simctl", "launch", "booted", bundle_id] + + try: + subprocess.run(run_command, check=True) + print("Application launched in simulator!") + except subprocess.CalledProcessError as e: + print(f"Failed to launch application in simulator: {e}") + + +# Usage +current_script_dir = os.path.dirname(os.path.abspath(__file__)) +project_path = os.path.join(current_script_dir, "Playground.xcodeproj") +scheme_name = "Playground" +simulator_name = "iPhone 15" +destination = f"platform=iOS Simulator,name={simulator_name},OS=latest" + +if __name__ == "__main__": + build_and_run_xcode_project(project_path, scheme_name, destination) diff --git a/Swiftgram/SFSafariViewControllerPlus/BUILD b/Swiftgram/SFSafariViewControllerPlus/BUILD new file mode 100644 index 00000000..72a719f0 --- /dev/null +++ b/Swiftgram/SFSafariViewControllerPlus/BUILD @@ -0,0 +1,17 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SFSafariViewControllerPlus", + module_name = "SFSafariViewControllerPlus", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SFSafariViewControllerPlus/Sources/SFSafariViewControllerPlus.swift b/Swiftgram/SFSafariViewControllerPlus/Sources/SFSafariViewControllerPlus.swift new file mode 100644 index 00000000..1df3ddba --- /dev/null +++ b/Swiftgram/SFSafariViewControllerPlus/Sources/SFSafariViewControllerPlus.swift @@ -0,0 +1,14 @@ +import SafariServices + +public class SFSafariViewControllerPlusDidFinish: SFSafariViewController, SFSafariViewControllerDelegate { + public var onDidFinish: (() -> Void)? + + public override init(url URL: URL, configuration: SFSafariViewController.Configuration = SFSafariViewController.Configuration()) { + super.init(url: URL, configuration: configuration) + self.delegate = self + } + + public func safariViewControllerDidFinish(_ controller: SFSafariViewController) { + onDidFinish?() + } +} diff --git a/Swiftgram/SGAPI/BUILD b/Swiftgram/SGAPI/BUILD new file mode 100644 index 00000000..1a7634e2 --- /dev/null +++ b/Swiftgram/SGAPI/BUILD @@ -0,0 +1,25 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGAPI", + module_name = "SGAPI", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + "//Swiftgram/SGLogging:SGLogging", + "//Swiftgram/SGWebAppExtensions:SGWebAppExtensions", + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//Swiftgram/SGWebSettingsScheme:SGWebSettingsScheme", + "//Swiftgram/SGRegDateScheme:SGRegDateScheme", + "//Swiftgram/SGRequests:SGRequests", + "//Swiftgram/SGConfig:SGConfig" + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGAPI/Sources/SGAPI.swift b/Swiftgram/SGAPI/Sources/SGAPI.swift new file mode 100644 index 00000000..9a85f809 --- /dev/null +++ b/Swiftgram/SGAPI/Sources/SGAPI.swift @@ -0,0 +1,188 @@ +import Foundation +import SwiftSignalKit + +import SGConfig +import SGLogging +import SGSimpleSettings +import SGWebAppExtensions +import SGWebSettingsScheme +import SGRequests +import SGRegDateScheme + +private let API_VERSION: String = "0" + +private func buildApiUrl(_ endpoint: String) -> String { + return "\(SG_CONFIG.apiUrl)/v\(API_VERSION)/\(endpoint)" +} + +public let SG_API_AUTHORIZATION_HEADER = "Authorization" +public let SG_API_DEVICE_TOKEN_HEADER = "Device-Token" + +private enum HTTPRequestError { + case network +} + +public enum SGAPIError { + case generic(String? = nil) +} + +public func getSGSettings(token: String) -> Signal { + return Signal { subscriber in + + let url = URL(string: buildApiUrl("settings"))! + let headers = [SG_API_AUTHORIZATION_HEADER: "Token \(token)"] + let completed = Atomic(value: false) + + var request = URLRequest(url: url) + headers.forEach { key, value in + request.addValue(value, forHTTPHeaderField: key) + } + + let downloadSignal = requestsCustom(request: request).start(next: { data, urlResponse in + let _ = completed.swap(true) + do { + let decoder = JSONDecoder() + decoder.keyDecodingStrategy = .convertFromSnakeCase + let settings = try decoder.decode(SGWebSettings.self, from: data) + subscriber.putNext(settings) + subscriber.putCompletion() + } catch { + subscriber.putError(.generic("Can't parse user settings: \(error). Response: \(String(data: data, encoding: .utf8) ?? "")")) + } + }, error: { error in + subscriber.putError(.generic("Error requesting user settings: \(String(describing: error))")) + }) + + return ActionDisposable { + if !completed.with({ $0 }) { + downloadSignal.dispose() + } + } + } +} + + + +public func postSGSettings(token: String, data: [String:Any]) -> Signal { + return Signal { subscriber in + + let url = URL(string: buildApiUrl("settings"))! + let headers = [SG_API_AUTHORIZATION_HEADER: "Token \(token)"] + let completed = Atomic(value: false) + + var request = URLRequest(url: url) + headers.forEach { key, value in + request.addValue(value, forHTTPHeaderField: key) + } + request.httpMethod = "POST" + + let jsonData = try? JSONSerialization.data(withJSONObject: data, options: []) + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.httpBody = jsonData + + let dataSignal = requestsCustom(request: request).start(next: { data, urlResponse in + let _ = completed.swap(true) + + if let httpResponse = urlResponse as? HTTPURLResponse { + switch httpResponse.statusCode { + case 200...299: + subscriber.putCompletion() + default: + subscriber.putError(.generic("Can't update settings: \(httpResponse.statusCode). Response: \(String(data: data, encoding: .utf8) ?? "")")) + } + } else { + subscriber.putError(.generic("Not an HTTP response: \(String(describing: urlResponse))")) + } + }, error: { error in + subscriber.putError(.generic("Error updating settings: \(String(describing: error))")) + }) + + return ActionDisposable { + if !completed.with({ $0 }) { + dataSignal.dispose() + } + } + } +} + +public func getSGAPIRegDate(token: String, deviceToken: String, userId: Int64) -> Signal { + return Signal { subscriber in + + let url = URL(string: buildApiUrl("regdate/\(userId)"))! + let headers = [ + SG_API_AUTHORIZATION_HEADER: "Token \(token)", + SG_API_DEVICE_TOKEN_HEADER: deviceToken + ] + let completed = Atomic(value: false) + + var request = URLRequest(url: url) + headers.forEach { key, value in + request.addValue(value, forHTTPHeaderField: key) + } + request.timeoutInterval = 10 + + let downloadSignal = requestsCustom(request: request).start(next: { data, urlResponse in + let _ = completed.swap(true) + do { + let decoder = JSONDecoder() + decoder.keyDecodingStrategy = .convertFromSnakeCase + let settings = try decoder.decode(RegDate.self, from: data) + subscriber.putNext(settings) + subscriber.putCompletion() + } catch { + subscriber.putError(.generic("Can't parse regDate: \(error). Response: \(String(data: data, encoding: .utf8) ?? "")")) + } + }, error: { error in + subscriber.putError(.generic("Error requesting regDate: \(String(describing: error))")) + }) + + return ActionDisposable { + if !completed.with({ $0 }) { + downloadSignal.dispose() + } + } + } +} + + +public func postSGReceipt(token: String, deviceToken: String, encodedReceiptData: Data) -> Signal { + return Signal { subscriber in + + let url = URL(string: buildApiUrl("validate"))! + let headers = [ + SG_API_AUTHORIZATION_HEADER: "Token \(token)", + SG_API_DEVICE_TOKEN_HEADER: deviceToken + ] + let completed = Atomic(value: false) + + var request = URLRequest(url: url) + headers.forEach { key, value in + request.addValue(value, forHTTPHeaderField: key) + } + request.httpMethod = "POST" + request.httpBody = encodedReceiptData + + let dataSignal = requestsCustom(request: request).start(next: { data, urlResponse in + let _ = completed.swap(true) + + if let httpResponse = urlResponse as? HTTPURLResponse { + switch httpResponse.statusCode { + case 200...299: + subscriber.putCompletion() + default: + subscriber.putError(.generic("Error posting Receipt: \(httpResponse.statusCode). Response: \(String(data: data, encoding: .utf8) ?? "")")) + } + } else { + subscriber.putError(.generic("Not an HTTP response: \(String(describing: urlResponse))")) + } + }, error: { error in + subscriber.putError(.generic("Error posting Receipt: \(String(describing: error))")) + }) + + return ActionDisposable { + if !completed.with({ $0 }) { + dataSignal.dispose() + } + } + } +} diff --git a/Swiftgram/SGAPIToken/BUILD b/Swiftgram/SGAPIToken/BUILD new file mode 100644 index 00000000..9b507e1c --- /dev/null +++ b/Swiftgram/SGAPIToken/BUILD @@ -0,0 +1,24 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGAPIToken", + module_name = "SGAPIToken", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + "//submodules/AccountContext:AccountContext", + "//submodules/TelegramCore:TelegramCore", + "//Swiftgram/SGLogging:SGLogging", + "//Swiftgram/SGWebSettingsScheme:SGWebSettingsScheme", + "//Swiftgram/SGConfig:SGConfig", + "//Swiftgram/SGWebAppExtensions:SGWebAppExtensions", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGAPIToken/Sources/SGAPIToken.swift b/Swiftgram/SGAPIToken/Sources/SGAPIToken.swift new file mode 100644 index 00000000..209cbb04 --- /dev/null +++ b/Swiftgram/SGAPIToken/Sources/SGAPIToken.swift @@ -0,0 +1,133 @@ +import Foundation +import SwiftSignalKit +import AccountContext +import TelegramCore +import SGLogging +import SGConfig +import SGWebAppExtensions + +private let tokenExpirationTime: TimeInterval = 30 * 60 // 30 minutes + +private var tokenCache: [Int64: (token: String, expiration: Date)] = [:] + +public enum SGAPITokenError { + case generic(String? = nil) +} + +public func getSGApiToken(context: AccountContext, botUsername: String = SG_CONFIG.botUsername) -> Signal { + let userId = context.account.peerId.id._internalGetInt64Value() + + if let (token, expiration) = tokenCache[userId], Date() < expiration { + // SGLogger.shared.log("SGAPI", "Using cached token. Expiring at: \(expiration)") + return Signal { subscriber in + subscriber.putNext(token) + subscriber.putCompletion() + return EmptyDisposable + } + } + + SGLogger.shared.log("SGAPI", "Requesting new token") + // Workaround for Apple Review + if context.account.testingEnvironment { + return context.account.postbox.transaction { transaction -> String? in + if let testUserPeer = transaction.getPeer(context.account.peerId) as? TelegramUser, let testPhone = testUserPeer.phone { + return testPhone + } else { + return nil + } + } + |> mapToSignalPromotingError { phone -> Signal in + if let phone = phone { + // https://core.telegram.org/api/auth#test-accounts + if phone.starts(with: String(99966)) { + SGLogger.shared.log("SGAPI", "Using demo token") + tokenCache[userId] = (phone, Date().addingTimeInterval(tokenExpirationTime)) + return .single(phone) + } else { + return .fail(.generic("Non-demo phone number on test DC")) + } + } else { + return .fail(.generic("Missing test account peer or it's number (how?)")) + } + } + } + + return Signal { subscriber in + let getSettingsURLSignal = getSGSettingsURL(context: context, botUsername: botUsername).start(next: { url in + if let hashPart = url.components(separatedBy: "#").last { + let parsedParams = urlParseHashParams(hashPart) + if let token = parsedParams["tgWebAppData"], let token = token { + tokenCache[userId] = (token, Date().addingTimeInterval(tokenExpirationTime)) + #if DEBUG + print("[SGAPI]", "API Token: \(token)") + #endif + subscriber.putNext(token) + subscriber.putCompletion() + } else { + subscriber.putError(.generic("Invalid or missing token in response url! \(url)")) + } + } else { + subscriber.putError(.generic("No hash part in URL \(url)")) + } + }) + + return ActionDisposable { + getSettingsURLSignal.dispose() + } + } +} + +public func getSGSettingsURL(context: AccountContext, botUsername: String = SG_CONFIG.botUsername, url: String = SG_CONFIG.webappUrl, themeParams: [String: Any]? = nil) -> Signal { + return Signal { subscriber in + // themeParams = generateWebAppThemeParams( + // context.sharedContext.currentPresentationData.with { $0 }.theme + // ) + var requestWebViewSignalDisposable: Disposable? = nil + var requestUpdatePeerIsBlocked: Disposable? = nil + let resolvePeerSignal = ( + context.engine.peers.resolvePeerByName(name: botUsername, referrer: nil) + |> mapToSignal { result -> Signal in + guard case let .result(result) = result else { + return .complete() + } + return .single(result) + }).start(next: { botPeer in + if let botPeer = botPeer { + SGLogger.shared.log("SGAPI", "Botpeer found for \(botUsername)") + let requestWebViewSignal = context.engine.messages.requestWebView(peerId: botPeer.id, botId: botPeer.id, url: url, payload: nil, themeParams: themeParams, fromMenu: true, replyToMessageId: nil, threadId: nil) + + requestWebViewSignalDisposable = requestWebViewSignal.start(next: { webViewResult in + subscriber.putNext(webViewResult.url) + subscriber.putCompletion() + }, error: { e in + SGLogger.shared.log("SGAPI", "Webview request error, retrying with unblock") + // if e.errorDescription == "YOU_BLOCKED_USER" { + requestUpdatePeerIsBlocked = (context.engine.privacy.requestUpdatePeerIsBlocked(peerId: botPeer.id, isBlocked: false) + |> afterDisposed( + { + requestWebViewSignalDisposable?.dispose() + requestWebViewSignalDisposable = requestWebViewSignal.start(next: { webViewResult in + SGLogger.shared.log("SGAPI", "Webview retry success \(webViewResult)") + subscriber.putNext(webViewResult.url) + subscriber.putCompletion() + }, error: { e in + SGLogger.shared.log("SGAPI", "Webview retry failure \(e)") + subscriber.putError(.generic("Webview retry failure \(e)")) + }) + })).start() + // } + }) + + } else { + SGLogger.shared.log("SGAPI", "Botpeer not found for \(botUsername)") + subscriber.putError(.generic()) + } + }) + + return ActionDisposable { + resolvePeerSignal.dispose() + requestUpdatePeerIsBlocked?.dispose() + requestWebViewSignalDisposable?.dispose() + } + } +} diff --git a/Swiftgram/SGAPIWebSettings/BUILD b/Swiftgram/SGAPIWebSettings/BUILD new file mode 100644 index 00000000..9964398d --- /dev/null +++ b/Swiftgram/SGAPIWebSettings/BUILD @@ -0,0 +1,23 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGAPIWebSettings", + module_name = "SGAPIWebSettings", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//Swiftgram/SGAPI:SGAPI", + "//Swiftgram/SGAPIToken:SGAPIToken", + "//Swiftgram/SGLogging:SGLogging", + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//submodules/AccountContext:AccountContext", + "//submodules/TelegramCore:TelegramCore", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGAPIWebSettings/Sources/File.swift b/Swiftgram/SGAPIWebSettings/Sources/File.swift new file mode 100644 index 00000000..f29a97c9 --- /dev/null +++ b/Swiftgram/SGAPIWebSettings/Sources/File.swift @@ -0,0 +1,51 @@ +import Foundation + +import SGAPIToken +import SGAPI +import SGLogging + +import AccountContext + +import SGSimpleSettings +import TelegramCore + +public func updateSGWebSettingsInteractivelly(context: AccountContext) { + let _ = getSGApiToken(context: context).startStandalone(next: { token in + let _ = getSGSettings(token: token).startStandalone(next: { webSettings in + SGLogger.shared.log("SGAPI", "New SGWebSettings for id \(context.account.peerId.id._internalGetInt64Value()): \(webSettings) ") + SGSimpleSettings.shared.canUseStealthMode = webSettings.global.storiesAvailable + SGSimpleSettings.shared.duckyAppIconAvailable = webSettings.global.duckyAppIconAvailable + SGSimpleSettings.shared.canUseNY = webSettings.global.nyAvailable + let _ = (context.account.postbox.transaction { transaction in + updateAppConfiguration(transaction: transaction, { configuration -> AppConfiguration in + var configuration = configuration + configuration.sgWebSettings = webSettings + return configuration + }) + }).startStandalone() + }, error: { e in + if case let .generic(errorMessage) = e, let errorMessage = errorMessage { + SGLogger.shared.log("SGAPI", errorMessage) + } + }) + }, error: { e in + if case let .generic(errorMessage) = e, let errorMessage = errorMessage { + SGLogger.shared.log("SGAPI", errorMessage) + } + }) +} + + +public func postSGWebSettingsInteractivelly(context: AccountContext, data: [String: Any]) { + let _ = getSGApiToken(context: context).startStandalone(next: { token in + let _ = postSGSettings(token: token, data: data).startStandalone(error: { e in + if case let .generic(errorMessage) = e, let errorMessage = errorMessage { + SGLogger.shared.log("SGAPI", errorMessage) + } + }) + }, error: { e in + if case let .generic(errorMessage) = e, let errorMessage = errorMessage { + SGLogger.shared.log("SGAPI", errorMessage) + } + }) +} diff --git a/Swiftgram/SGActionRequestHandlerSanitizer/BUILD b/Swiftgram/SGActionRequestHandlerSanitizer/BUILD new file mode 100644 index 00000000..a2737779 --- /dev/null +++ b/Swiftgram/SGActionRequestHandlerSanitizer/BUILD @@ -0,0 +1,17 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGActionRequestHandlerSanitizer", + module_name = "SGActionRequestHandlerSanitizer", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGActionRequestHandlerSanitizer/Sources/File.swift b/Swiftgram/SGActionRequestHandlerSanitizer/Sources/File.swift new file mode 100644 index 00000000..f94edc1c --- /dev/null +++ b/Swiftgram/SGActionRequestHandlerSanitizer/Sources/File.swift @@ -0,0 +1,15 @@ +import Foundation + +public func sgActionRequestHandlerSanitizer(_ url: URL) -> URL { + var url = url + if let scheme = url.scheme { + let openInPrefix = "\(scheme)://parseurl?url=" + let urlString = url.absoluteString + if urlString.hasPrefix(openInPrefix) { + if let unwrappedUrlString = String(urlString.dropFirst(openInPrefix.count)).removingPercentEncoding, let newUrl = URL(string: unwrappedUrlString) { + url = newUrl + } + } + } + return url +} diff --git a/Swiftgram/SGAppBadgeAssets/BUILD b/Swiftgram/SGAppBadgeAssets/BUILD new file mode 100644 index 00000000..d916184c --- /dev/null +++ b/Swiftgram/SGAppBadgeAssets/BUILD @@ -0,0 +1,5 @@ +filegroup( + name = "SGAppBadgeAssets", + srcs = glob(["Images.xcassets/**"]), + visibility = ["//visibility:public"], +) \ No newline at end of file diff --git a/Swiftgram/SGAppBadgeAssets/Images.xcassets/Contents.json b/Swiftgram/SGAppBadgeAssets/Images.xcassets/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/Swiftgram/SGAppBadgeAssets/Images.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGAppBadgeAssets/Images.xcassets/DayAppBadge.imageset/Contents.json b/Swiftgram/SGAppBadgeAssets/Images.xcassets/DayAppBadge.imageset/Contents.json new file mode 100644 index 00000000..b1a95561 --- /dev/null +++ b/Swiftgram/SGAppBadgeAssets/Images.xcassets/DayAppBadge.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Day@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGAppBadgeAssets/Images.xcassets/DayAppBadge.imageset/Day@3x.png b/Swiftgram/SGAppBadgeAssets/Images.xcassets/DayAppBadge.imageset/Day@3x.png new file mode 100644 index 00000000..d335dc3d Binary files /dev/null and b/Swiftgram/SGAppBadgeAssets/Images.xcassets/DayAppBadge.imageset/Day@3x.png differ diff --git a/Swiftgram/SGAppBadgeAssets/Images.xcassets/DuckyAppBadge.imageset/Contents.json b/Swiftgram/SGAppBadgeAssets/Images.xcassets/DuckyAppBadge.imageset/Contents.json new file mode 100644 index 00000000..3e95b39a --- /dev/null +++ b/Swiftgram/SGAppBadgeAssets/Images.xcassets/DuckyAppBadge.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Ducky@3.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGAppBadgeAssets/Images.xcassets/DuckyAppBadge.imageset/Ducky@3.png b/Swiftgram/SGAppBadgeAssets/Images.xcassets/DuckyAppBadge.imageset/Ducky@3.png new file mode 100644 index 00000000..69b26db1 Binary files /dev/null and b/Swiftgram/SGAppBadgeAssets/Images.xcassets/DuckyAppBadge.imageset/Ducky@3.png differ diff --git a/Swiftgram/SGAppBadgeAssets/Images.xcassets/NightAppBadge.imageset/Contents.json b/Swiftgram/SGAppBadgeAssets/Images.xcassets/NightAppBadge.imageset/Contents.json new file mode 100644 index 00000000..baa6cad8 --- /dev/null +++ b/Swiftgram/SGAppBadgeAssets/Images.xcassets/NightAppBadge.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Night@3-1.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGAppBadgeAssets/Images.xcassets/NightAppBadge.imageset/Night@3-1.png b/Swiftgram/SGAppBadgeAssets/Images.xcassets/NightAppBadge.imageset/Night@3-1.png new file mode 100644 index 00000000..b4013589 Binary files /dev/null and b/Swiftgram/SGAppBadgeAssets/Images.xcassets/NightAppBadge.imageset/Night@3-1.png differ diff --git a/Swiftgram/SGAppBadgeAssets/Images.xcassets/ProAppBadge.imageset/Contents.json b/Swiftgram/SGAppBadgeAssets/Images.xcassets/ProAppBadge.imageset/Contents.json new file mode 100644 index 00000000..7007dd0f --- /dev/null +++ b/Swiftgram/SGAppBadgeAssets/Images.xcassets/ProAppBadge.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Pro@3.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGAppBadgeAssets/Images.xcassets/ProAppBadge.imageset/Pro@3.png b/Swiftgram/SGAppBadgeAssets/Images.xcassets/ProAppBadge.imageset/Pro@3.png new file mode 100644 index 00000000..aba68aaa Binary files /dev/null and b/Swiftgram/SGAppBadgeAssets/Images.xcassets/ProAppBadge.imageset/Pro@3.png differ diff --git a/Swiftgram/SGAppBadgeAssets/Images.xcassets/SkyAppBadge.imageset/Contents.json b/Swiftgram/SGAppBadgeAssets/Images.xcassets/SkyAppBadge.imageset/Contents.json new file mode 100644 index 00000000..e6afa8ae --- /dev/null +++ b/Swiftgram/SGAppBadgeAssets/Images.xcassets/SkyAppBadge.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Sky@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGAppBadgeAssets/Images.xcassets/SkyAppBadge.imageset/Sky@3x.png b/Swiftgram/SGAppBadgeAssets/Images.xcassets/SkyAppBadge.imageset/Sky@3x.png new file mode 100644 index 00000000..4b2894c8 Binary files /dev/null and b/Swiftgram/SGAppBadgeAssets/Images.xcassets/SkyAppBadge.imageset/Sky@3x.png differ diff --git a/Swiftgram/SGAppBadgeAssets/Images.xcassets/SparklingAppBadge.imageset/Contents.json b/Swiftgram/SGAppBadgeAssets/Images.xcassets/SparklingAppBadge.imageset/Contents.json new file mode 100644 index 00000000..4b7eedb9 --- /dev/null +++ b/Swiftgram/SGAppBadgeAssets/Images.xcassets/SparklingAppBadge.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Sparkling@3.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGAppBadgeAssets/Images.xcassets/SparklingAppBadge.imageset/Sparkling@3.png b/Swiftgram/SGAppBadgeAssets/Images.xcassets/SparklingAppBadge.imageset/Sparkling@3.png new file mode 100644 index 00000000..829e3624 Binary files /dev/null and b/Swiftgram/SGAppBadgeAssets/Images.xcassets/SparklingAppBadge.imageset/Sparkling@3.png differ diff --git a/Swiftgram/SGAppBadgeAssets/Images.xcassets/TitaniumAppBadge.imageset/Contents.json b/Swiftgram/SGAppBadgeAssets/Images.xcassets/TitaniumAppBadge.imageset/Contents.json new file mode 100644 index 00000000..c3b56ecd --- /dev/null +++ b/Swiftgram/SGAppBadgeAssets/Images.xcassets/TitaniumAppBadge.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Titanium@3.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGAppBadgeAssets/Images.xcassets/TitaniumAppBadge.imageset/Titanium@3.png b/Swiftgram/SGAppBadgeAssets/Images.xcassets/TitaniumAppBadge.imageset/Titanium@3.png new file mode 100644 index 00000000..2dc02344 Binary files /dev/null and b/Swiftgram/SGAppBadgeAssets/Images.xcassets/TitaniumAppBadge.imageset/Titanium@3.png differ diff --git a/Swiftgram/SGAppBadgeOffset/BUILD b/Swiftgram/SGAppBadgeOffset/BUILD new file mode 100644 index 00000000..23409546 --- /dev/null +++ b/Swiftgram/SGAppBadgeOffset/BUILD @@ -0,0 +1,9 @@ +filegroup( + name = "SGAppBadgeOffset", + srcs = glob([ + "Sources/**/*.swift", + ]), + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGAppBadgeOffset/Sources/SGAppBadgeOffset.swift b/Swiftgram/SGAppBadgeOffset/Sources/SGAppBadgeOffset.swift new file mode 100644 index 00000000..06b0c890 --- /dev/null +++ b/Swiftgram/SGAppBadgeOffset/Sources/SGAppBadgeOffset.swift @@ -0,0 +1,84 @@ +import UIKit +import DeviceModel + + +let DEVICE_MODELS_WITH_APP_BADGE_SUPPORT: [DeviceModel] = [ + .iPhoneX, + .iPhoneXS, + .iPhoneXSMax, + .iPhoneXR, + .iPhone11, + .iPhone11Pro, + .iPhone11ProMax, + .iPhone12, + .iPhone12Mini, + .iPhone12Pro, + .iPhone12ProMax, + .iPhone13, + .iPhone13Mini, + .iPhone13Pro, + .iPhone13ProMax, + .iPhone14, + .iPhone14Plus, + .iPhone14Pro, + .iPhone14ProMax, + .iPhone15, + .iPhone15Plus, + .iPhone15Pro, + .iPhone15ProMax, + .iPhone16, + .iPhone16Plus, + .iPhone16Pro, + .iPhone16ProMax, + .iPhone16e +] + +extension DeviceMetrics { + + func sgAppBadgeOffset() -> CGFloat { + let currentDevice = DeviceModel.current + var defaultOffset: CGFloat = 0.0 + // https://www.ios-resolution.com/ + // Similar height + Scale + switch currentDevice { + case .iPhoneX, .iPhoneXS, .iPhone11Pro, .iPhone12Mini, .iPhone13Mini: + defaultOffset = 2.0 + case .iPhone11, .iPhoneXR: + defaultOffset = 6.0 + case .iPhone11ProMax, .iPhoneXSMax: + defaultOffset = 4.0 + case .iPhone12, .iPhone12Pro, .iPhone13, .iPhone13Pro, .iPhone14, .iPhone16e: + defaultOffset = 4.0 + case .iPhone12ProMax, .iPhone13ProMax, .iPhone14Plus: + defaultOffset = 6.0 + case .iPhone14Pro, .iPhone15, .iPhone15Pro, .iPhone16: + defaultOffset = 18.0 + case .iPhone14ProMax, .iPhone15Plus, .iPhone15ProMax, .iPhone16Plus: + defaultOffset = 19.0 + case .iPhone16Pro: + defaultOffset = 21.0 + case .iPhone16ProMax: + defaultOffset = 22.0 + default: + defaultOffset = 0.0 // Any device in 2025+ should be like iPhone 14 Pro or better + } + let offset: CGFloat = floorToScreenPixels(defaultOffset * self.sgScaleFactor) + #if DEBUG + print("deviceMetrics \(self). deviceModel: \(currentDevice). sgIsDisplayZoomed: \(self.sgIsDisplayZoomed). sgScaleFactor: \(self.sgScaleFactor) defaultOffset: \(defaultOffset), offset: \(offset)") + #endif + return offset + } + + var sgIsDisplayZoomed: Bool { + UIScreen.main.scale < UIScreen.main.nativeScale + } + + var sgScaleFactor: CGFloat { + UIScreen.main.scale / UIScreen.main.nativeScale + } + + var sgShowAppBadge: Bool { + return DEVICE_MODELS_WITH_APP_BADGE_SUPPORT.contains(DeviceModel.current) // MARK: Swiftgram + } + +} diff --git a/Swiftgram/SGAppGroupIdentifier/BUILD b/Swiftgram/SGAppGroupIdentifier/BUILD new file mode 100644 index 00000000..cc3e1398 --- /dev/null +++ b/Swiftgram/SGAppGroupIdentifier/BUILD @@ -0,0 +1,17 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGAppGroupIdentifier", + module_name = "SGAppGroupIdentifier", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGAppGroupIdentifier/Sources/SGAppGroupIdentifier.swift b/Swiftgram/SGAppGroupIdentifier/Sources/SGAppGroupIdentifier.swift new file mode 100644 index 00000000..90859ac8 --- /dev/null +++ b/Swiftgram/SGAppGroupIdentifier/Sources/SGAppGroupIdentifier.swift @@ -0,0 +1,31 @@ +import Foundation + +public let FALLBACK_BASE_BUNDLE_ID: String = "app.swiftgram.ios" + +public func sgBaseBundleIdentifier() -> String { + let baseBundleId: String + if let bundleId: String = Bundle.main.bundleIdentifier { + if Bundle.main.bundlePath.hasSuffix(".appex") { + if let lastDotRange: Range = bundleId.range(of: ".", options: [.backwards]) { + baseBundleId = String(bundleId[.. String { + let result: String = "group.\(sgBaseBundleIdentifier())" + + #if DEBUG + print("APP_GROUP_IDENTIFIER: \(result)") + #endif + + return result +} diff --git a/Swiftgram/SGChatListSimpleSettingsSignal/BUILD b/Swiftgram/SGChatListSimpleSettingsSignal/BUILD new file mode 100644 index 00000000..862019aa --- /dev/null +++ b/Swiftgram/SGChatListSimpleSettingsSignal/BUILD @@ -0,0 +1,9 @@ +filegroup( + name = "SGChatListSimpleSettingsSignal", + srcs = glob([ + "Sources/**/*.swift", + ]), + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGChatListSimpleSettingsSignal/Sources/SGChatListSimpleSettingsSignal.swift b/Swiftgram/SGChatListSimpleSettingsSignal/Sources/SGChatListSimpleSettingsSignal.swift new file mode 100644 index 00000000..c46e1702 --- /dev/null +++ b/Swiftgram/SGChatListSimpleSettingsSignal/Sources/SGChatListSimpleSettingsSignal.swift @@ -0,0 +1,21 @@ +import SGSimpleSettings +import Foundation +import SwiftSignalKit + +public func sgSimpleSettingsBoolSignal(_ key: SGSimpleSettings.Keys, defaultValue: Bool) -> Signal { + let initial = Signal.single(UserDefaults.standard.object(forKey: key.rawValue) as? Bool ?? defaultValue) + let changes = Signal { subscriber in + let observer = NotificationCenter.default.addObserver( + forName: UserDefaults.didChangeNotification, + object: UserDefaults.standard, + queue: nil + ) { _ in + let value = UserDefaults.standard.object(forKey: key.rawValue) as? Bool ?? defaultValue + subscriber.putNext(value) + } + return ActionDisposable { + NotificationCenter.default.removeObserver(observer) + } + } + return (initial |> then(changes)) |> distinctUntilChanged +} diff --git a/Swiftgram/SGChatListSimpleSettingsSignal/Sources/SGCompactMessagePreviewLayout.swift b/Swiftgram/SGChatListSimpleSettingsSignal/Sources/SGCompactMessagePreviewLayout.swift new file mode 100644 index 00000000..5d643350 --- /dev/null +++ b/Swiftgram/SGChatListSimpleSettingsSignal/Sources/SGCompactMessagePreviewLayout.swift @@ -0,0 +1,60 @@ +import SGSimpleSettings +import CoreGraphics +import Display + +enum SGCompactMessagePreviewLayout { + static func isEnabled() -> Bool { + (SGSimpleSettings.ChatListLines(rawValue: SGSimpleSettings.shared.chatListLines) ?? .three) != .three + } + + static func avatarScaleDivisor(compactChatList: Bool, compactMessagePreview: Bool) -> CGFloat { + compactChatList ? 1.5 : (compactMessagePreview ? 1.1 : 1.0) + } + + static func forumTopicIconYOffset(compactMessagePreview: Bool) -> CGFloat { + compactMessagePreview ? 8.0 : 0.0 + } + + static func badgeOffset(sizeFactor: CGFloat, compactMessagePreview: Bool, compactChatList: Bool) -> CGFloat { + guard compactMessagePreview && !compactChatList else { + return 0.0 + } + + let sizeRange: CGFloat = 0.5 + let maxLift: CGFloat = 16.0 + let maxDownshift: CGFloat = 24.0 + let sizeDelta = sizeFactor - 1.0 + let lift: CGFloat + if sizeDelta >= 0.0 { + let sizeGrow = min(sizeRange, sizeDelta) + let sizeGrowFactor = sizeGrow / sizeRange + lift = maxLift * sizeGrowFactor * sizeGrowFactor * (3.0 - 2.0 * sizeGrowFactor) + } else { + let sizeShrink = min(sizeRange, -sizeDelta) + let sizeShrinkFactor = sizeShrink / sizeRange + let downshift = maxDownshift * sizeShrinkFactor * sizeShrinkFactor * (3.0 - 2.0 * sizeShrinkFactor) + lift = -downshift + } + + return floorToScreenPixels(lift) + } + + static func textVerticalOffset(sizeFactor: CGFloat, compactMessagePreview: Bool, compactChatList: Bool, hasAuthorLine: Bool) -> CGFloat { + guard compactMessagePreview && !compactChatList && !hasAuthorLine else { + return 0.0 + } + return floorToScreenPixels(6.0 * sizeFactor) + } + + static func titleTextSpacing(sizeFactor: CGFloat, compactMessagePreview: Bool, compactChatList: Bool, hasAuthorLine: Bool) -> CGFloat { + guard compactMessagePreview && !compactChatList && !hasAuthorLine else { + return 0.0 + } + return floorToScreenPixels(6.0 * sizeFactor) + } + + static func textBlockOffset(sizeFactor: CGFloat, compactMessagePreview: Bool, compactChatList: Bool, hasAuthorLine: Bool) -> CGFloat { + textVerticalOffset(sizeFactor: sizeFactor, compactMessagePreview: compactMessagePreview, compactChatList: compactChatList, hasAuthorLine: hasAuthorLine) + + titleTextSpacing(sizeFactor: sizeFactor, compactMessagePreview: compactMessagePreview, compactChatList: compactChatList, hasAuthorLine: hasAuthorLine) + } +} diff --git a/Swiftgram/SGConfig/BUILD b/Swiftgram/SGConfig/BUILD new file mode 100644 index 00000000..68f53fc3 --- /dev/null +++ b/Swiftgram/SGConfig/BUILD @@ -0,0 +1,18 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGConfig", + module_name = "SGConfig", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/BuildConfig:BuildConfig" + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGConfig/Sources/File.swift b/Swiftgram/SGConfig/Sources/File.swift new file mode 100644 index 00000000..83294f42 --- /dev/null +++ b/Swiftgram/SGConfig/Sources/File.swift @@ -0,0 +1,12 @@ +import Foundation + +public struct SGConfig: Codable { + public var apiUrl: String = "https://api.swiftgram.app" + public var webappUrl: String = "https://my.swiftgram.app" + public var botUsername: String = "SwiftgramBot" + public var publicKey: String? + public var iaps: [String] = [] +} + +public let SG_CONFIG: SGConfig = SGConfig() +public let SG_API_WEBAPP_URL_PARSED = URL(string: SG_CONFIG.webappUrl)! diff --git a/Swiftgram/SGContentAnalysis/BUILD b/Swiftgram/SGContentAnalysis/BUILD new file mode 100644 index 00000000..8679395f --- /dev/null +++ b/Swiftgram/SGContentAnalysis/BUILD @@ -0,0 +1,18 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGContentAnalysis", + module_name = "SGContentAnalysis", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGContentAnalysis/Sources/ContentAnalysis.swift b/Swiftgram/SGContentAnalysis/Sources/ContentAnalysis.swift new file mode 100644 index 00000000..b75ba3fd --- /dev/null +++ b/Swiftgram/SGContentAnalysis/Sources/ContentAnalysis.swift @@ -0,0 +1,64 @@ +import SensitiveContentAnalysis +import SwiftSignalKit + +public enum ContentAnalysisError: Error { + case generic(_ message: String) +} + +public enum ContentAnalysisMediaType { + case image + case video +} + +public func canAnalyzeMedia() -> Bool { + if #available(iOS 17, *) { + let analyzer = SCSensitivityAnalyzer() + let policy = analyzer.analysisPolicy + return policy != .disabled + } else { + return false + } +} + + +public func analyzeMediaSignal(_ url: URL, mediaType: ContentAnalysisMediaType = .image) -> Signal { + return Signal { subscriber in + analyzeMedia(url: url, mediaType: mediaType, completion: { result, error in + if let result = result { + subscriber.putNext(result) + subscriber.putCompletion() + } else if let error = error { + subscriber.putError(error) + } else { + subscriber.putError(ContentAnalysisError.generic("Unknown response")) + } + }) + + return ActionDisposable { + } + } +} + +private func analyzeMedia(url: URL, mediaType: ContentAnalysisMediaType, completion: @escaping (Bool?, Error?) -> Void) { + if #available(iOS 17, *) { + let analyzer = SCSensitivityAnalyzer() + switch mediaType { + case .image: + analyzer.analyzeImage(at: url) { analysisResult, analysisError in + completion(analysisResult?.isSensitive, analysisError) + } + case .video: + Task { + do { + let handler = analyzer.videoAnalysis(forFileAt: url) + let response = try await handler.hasSensitiveContent() + completion(response.isSensitive, nil) + } catch { + completion(nil, error) + } + } + } + } else { + completion(false, nil) + } +} diff --git a/Swiftgram/SGDBReset/BUILD b/Swiftgram/SGDBReset/BUILD new file mode 100644 index 00000000..c9e2113b --- /dev/null +++ b/Swiftgram/SGDBReset/BUILD @@ -0,0 +1,9 @@ +filegroup( + name = "SGDBReset", + srcs = glob([ + "Sources/**/*.swift", + ]), + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGDBReset/Sources/File.swift b/Swiftgram/SGDBReset/Sources/File.swift new file mode 100644 index 00000000..3cb9b939 --- /dev/null +++ b/Swiftgram/SGDBReset/Sources/File.swift @@ -0,0 +1,162 @@ +import UIKit +import Foundation +import SGLogging + +private let dbResetKey = "sg_db_reset" +private let dbHardResetKey = "sg_db_hard_reset" + +public func sgDBResetIfNeeded(databasePath: String, present: ((UIViewController) -> ())?) { + guard UserDefaults.standard.bool(forKey: dbResetKey) else { + return + } + NSLog("[SG.DBReset] Resetting DB with system settings") + let alert = UIAlertController( + title: "Metadata Reset.\nPlease wait...", + message: nil, + preferredStyle: .alert + ) + present?(alert) + do { + let _ = try FileManager.default.removeItem(atPath: databasePath) + NSLog("[SG.DBReset] Done. Reset completed") + let successAlert = UIAlertController( + title: "Metadata Reset completed", + message: nil, + preferredStyle: .alert + ) + successAlert.addAction(UIAlertAction(title: "Restart App", style: .cancel) { _ in + exit(0) + }) + successAlert.addAction(UIAlertAction(title: "OK", style: .default)) + alert.dismiss(animated: false) { + present?(successAlert) + } + } catch { + NSLog("[SG.DBReset] ERROR. Failed to reset database: \(error)") + let failAlert = UIAlertController( + title: "ERROR. Failed to Reset database", + message: "\(error)", + preferredStyle: .alert + ) + alert.dismiss(animated: false) { + present?(failAlert) + } + } + UserDefaults.standard.set(false, forKey: dbResetKey) +// let semaphore = DispatchSemaphore(value: 0) +// semaphore.wait() +} + +public func sgHardReset(dataPath: String, present: ((UIViewController) -> ())?) { + let startAlert = UIAlertController( + title: "ATTENTION", + message: "Confirm RESET ALL?", + preferredStyle: .alert + ) + + startAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in + exit(0) + }) + startAlert.addAction(UIAlertAction(title: "RESET", style: .destructive) { _ in + let ensureAlert = UIAlertController( + title: "⚠️ ATTENTION ⚠️", + message: "ARE YOU SURE you want to make a RESET ALL?", + preferredStyle: .alert + ) + + ensureAlert.addAction(UIAlertAction(title: "Cancel", style: .default) { _ in + exit(0) + }) + ensureAlert.addAction(UIAlertAction(title: "RESET NOW", style: .destructive) { _ in + NSLog("[SG.DBReset] Reset All with system settings") + let alert = UIAlertController( + title: "Reset All.\nPlease wait...", + message: nil, + preferredStyle: .alert + ) + ensureAlert.dismiss(animated: false) { + present?(alert) + } + + do { + let fileManager = FileManager.default + let contents = try fileManager.contentsOfDirectory(atPath: dataPath) + + // Filter directories that match our criteria + let accountDirectories = contents.compactMap { filename in + let fullPath = (dataPath as NSString).appendingPathComponent(filename) + + var isDirectory: ObjCBool = false + if fileManager.fileExists(atPath: fullPath, isDirectory: &isDirectory), isDirectory.boolValue { + if filename.hasPrefix("account-") || filename == "accounts-metadata" { + return fullPath + } + } + return nil + } + + NSLog("[SG.DBReset] Found \(accountDirectories.count) account dirs...") + var deletedPostboxCount = 0 + for accountDir in accountDirectories { + let accountName = (accountDir as NSString).lastPathComponent + let postboxPath = (accountDir as NSString).appendingPathComponent("postbox") + + var isPostboxDir: ObjCBool = false + if fileManager.fileExists(atPath: postboxPath, isDirectory: &isPostboxDir), isPostboxDir.boolValue { + // Delete postbox/db + let dbPath = (postboxPath as NSString).appendingPathComponent("db") + var isDbDir: ObjCBool = false + if fileManager.fileExists(atPath: dbPath, isDirectory: &isDbDir), isDbDir.boolValue { + NSLog("[SG.DBReset] Trying to delete postbox/db in: \(accountName)") + try fileManager.removeItem(atPath: dbPath) + NSLog("[SG.DBReset] OK. Deleted postbox/db directory in: \(accountName)") + } + + // Delete postbox/media + let mediaPath = (postboxPath as NSString).appendingPathComponent("media") + var isMediaDir: ObjCBool = false + if fileManager.fileExists(atPath: mediaPath, isDirectory: &isMediaDir), isMediaDir.boolValue { + NSLog("[SG.DBReset] Trying to delete postbox/media in: \(accountName)") + try fileManager.removeItem(atPath: mediaPath) + NSLog("[SG.DBReset] OK. Deleted postbox/media directory in: \(accountName)") + } + + deletedPostboxCount += 1 + } + } + + + NSLog("[SG.DBReset] Done. Reset All completed") + let successAlert = UIAlertController( + title: "Reset All completed", + message: nil, + preferredStyle: .alert + ) + successAlert.addAction(UIAlertAction(title: "Restart App", style: .cancel) { _ in + exit(0) + }) + alert.dismiss(animated: false) { + present?(successAlert) + } + } catch { + NSLog("[SG.DBReset] ERROR. Reset All failed: \(error)") + let failAlert = UIAlertController( + title: "ERROR. Reset All failed", + message: "\(error)", + preferredStyle: .alert + ) + alert.dismiss(animated: false) { + present?(failAlert) + } + } + }) + ensureAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in + exit(0) + }) + + present?(ensureAlert) + }) + + present?(startAlert) + UserDefaults.standard.set(false, forKey: dbHardResetKey) +} diff --git a/Swiftgram/SGDebugUI/BUILD b/Swiftgram/SGDebugUI/BUILD new file mode 100644 index 00000000..c3a6130f --- /dev/null +++ b/Swiftgram/SGDebugUI/BUILD @@ -0,0 +1,51 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +config_setting( + name = "debug_build", + values = { + "compilation_mode": "dbg", + }, +) + +flex_dependency = select({ + ":debug_build": [ + "@flex_sdk//:FLEX" + ], + "//conditions:default": [], +}) + + +swift_library( + name = "SGDebugUI", + module_name = "SGDebugUI", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//Swiftgram/SGItemListUI:SGItemListUI", + "//Swiftgram/SGLogging:SGLogging", + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//Swiftgram/SGStrings:SGStrings", + "//Swiftgram/SGSwiftUI:SGSwiftUI", + "//Swiftgram/SGIAP:SGIAP", + "//Swiftgram/SGPayWall:SGPayWall", + "//submodules/TelegramUIPreferences:TelegramUIPreferences", + "//submodules/LegacyUI:LegacyUI", + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + "//submodules/Postbox:Postbox", + "//submodules/Display:Display", + "//submodules/TelegramCore:TelegramCore", + "//submodules/TelegramPresentationData:TelegramPresentationData", + "//submodules/ItemListUI:ItemListUI", + "//submodules/PresentationDataUtils:PresentationDataUtils", + "//submodules/OverlayStatusController:OverlayStatusController", + "//submodules/AccountContext:AccountContext", + "//submodules/UndoUI:UndoUI" + ] + flex_dependency, + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGDebugUI/Sources/SGDebugUI.swift b/Swiftgram/SGDebugUI/Sources/SGDebugUI.swift new file mode 100644 index 00000000..085d1459 --- /dev/null +++ b/Swiftgram/SGDebugUI/Sources/SGDebugUI.swift @@ -0,0 +1,216 @@ +import Foundation +import UniformTypeIdentifiers +import SGItemListUI +import UndoUI +import AccountContext +import Display +import TelegramCore +import Postbox +import ItemListUI +import SwiftSignalKit +import TelegramPresentationData +import PresentationDataUtils +import TelegramUIPreferences + +// Optional +import SGSimpleSettings +import SGLogging +import SGPayWall +import OverlayStatusController +#if DEBUG +import FLEX +#endif + + +private enum SGDebugControllerSection: Int32, SGItemListSection { + case base + case notifications +} + +private enum SGDebugDisclosureLink: String { + case sessionBackupManager + case messageFilter + case debugIAP +} + +private enum SGDebugActions: String { + case flexing + case fileManager + case clearRegDateCache + case clearOutgoingTranslationLanguageCache + case restorePurchases + case setIAP + case resetIAP +} + +private enum SGDebugToggles: String { + case forceImmediateShareSheet + case legacyNotificationsFix + case inputToolbar +} + + +private enum SGDebugOneFromManySetting: String { + case pinnedMessageNotifications + case mentionsAndRepliesNotifications +} + +private typealias SGDebugControllerEntry = SGItemListUIEntry + +private func SGDebugControllerEntries(presentationData: PresentationData) -> [SGDebugControllerEntry] { + var entries: [SGDebugControllerEntry] = [] + + let id = SGItemListCounter() + #if DEBUG + entries.append(.action(id: id.count, section: .base, actionType: .flexing, text: "FLEX", kind: .generic)) + entries.append(.action(id: id.count, section: .base, actionType: .fileManager, text: "FileManager", kind: .generic)) + #endif + + entries.append(.action(id: id.count, section: .base, actionType: .clearRegDateCache, text: "Clear Regdate cache", kind: .generic)) + entries.append(.action(id: id.count, section: .base, actionType: .clearOutgoingTranslationLanguageCache, text: "Clear Outgoing Translation cache", kind: .generic)) + entries.append(.toggle(id: id.count, section: .base, settingName: .forceImmediateShareSheet, value: SGSimpleSettings.shared.forceSystemSharing, text: "Force System Share Sheet", enabled: true)) + + entries.append(.action(id: id.count, section: .base, actionType: .restorePurchases, text: "PayWall.RestorePurchases".i18n(presentationData.strings.baseLanguageCode), kind: .generic)) + #if DEBUG + entries.append(.action(id: id.count, section: .base, actionType: .setIAP, text: "Set Pro", kind: .generic)) + #endif + entries.append(.action(id: id.count, section: .base, actionType: .resetIAP, text: "Reset Pro", kind: .destructive)) + + entries.append(.toggle(id: id.count, section: .notifications, settingName: .legacyNotificationsFix, value: SGSimpleSettings.shared.legacyNotificationsFix, text: "[OLD] Fix empty notifications", enabled: true)) + return entries +} +private func okUndoController(_ text: String, _ presentationData: PresentationData) -> UndoOverlayController { + return UndoOverlayController(presentationData: presentationData, content: .succeed(text: text, timeout: nil, customUndoText: nil), elevatedLayout: false, action: { _ in return false }) +} + + +public func sgDebugController(context: AccountContext) -> ViewController { + var presentControllerImpl: ((ViewController, ViewControllerPresentationArguments?) -> Void)? + var pushControllerImpl: ((ViewController) -> Void)? + + let simplePromise = ValuePromise(true, ignoreRepeated: false) + + let arguments = SGItemListArguments(context: context, setBoolValue: { toggleName, value in + switch toggleName { + case .forceImmediateShareSheet: + SGSimpleSettings.shared.forceSystemSharing = value + case .legacyNotificationsFix: + SGSimpleSettings.shared.legacyNotificationsFix = value + SGSimpleSettings.shared.synchronizeShared() + case .inputToolbar: + SGSimpleSettings.shared.inputToolbar = value + } + }, setOneFromManyValue: { setting in + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + let actionSheet = ActionSheetController(presentationData: presentationData) + let items: [ActionSheetItem] = [] +// var items: [ActionSheetItem] = [] + +// switch (setting) { +// } + + actionSheet.setItemGroups([ActionSheetItemGroup(items: items), ActionSheetItemGroup(items: [ + ActionSheetButtonItem(title: presentationData.strings.Common_Cancel, color: .accent, font: .bold, action: { [weak actionSheet] in + actionSheet?.dismissAnimated() + }) + ])]) + presentControllerImpl?(actionSheet, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + }, openDisclosureLink: { _ in + }, action: { actionType in + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + switch actionType { + case .clearRegDateCache: + SGLogger.shared.log("SGDebug", "Regdate cache cleanup init") + + /* + let spinner = OverlayStatusController(theme: presentationData.theme, type: .loading(cancelled: nil)) + + presentControllerImpl?(spinner, nil) + */ + SGSimpleSettings.shared.regDateCache.drop() + SGLogger.shared.log("SGDebug", "Regdate cache cleanup succesfull") + presentControllerImpl?(okUndoController("OK: Regdate cache cleaned", presentationData), nil) + /* + Queue.mainQueue().async() { [weak spinner] in + spinner?.dismiss() + } + */ + case .clearOutgoingTranslationLanguageCache: + SGLogger.shared.log("SGDebug", "Outgoing translation language cache cleanup init") + SGSimpleSettings.shared.outgoingLanguageTranslation.drop() + SGLogger.shared.log("SGDebug", "Outgoing translation language cache cleanup succesfull") + presentControllerImpl?(okUndoController("OK: Outgoing translation language cache cleaned", presentationData), nil) + case .flexing: + #if DEBUG + FLEXManager.shared.toggleExplorer() + #endif + case .fileManager: + #if DEBUG + let baseAppBundleId = Bundle.main.bundleIdentifier! + let appGroupName = "group.\(baseAppBundleId)" + let maybeAppGroupUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupName) + if let maybeAppGroupUrl = maybeAppGroupUrl { + if let fileManager = FLEXFileBrowserController(path: maybeAppGroupUrl.path) { + FLEXManager.shared.showExplorer() + let flexNavigation = FLEXNavigationController(rootViewController: fileManager) + FLEXManager.shared.presentTool({ return flexNavigation }) + } + } else { + presentControllerImpl?(UndoOverlayController( + presentationData: presentationData, + content: .info(title: nil, text: "Empty path", timeout: nil, customUndoText: nil), + elevatedLayout: false, + action: { _ in return false } + ), + nil) + } + #endif + case .restorePurchases: + presentControllerImpl?(UndoOverlayController( + presentationData: presentationData, + content: .info(title: nil, text: "PayWall.Button.Restoring".i18n(args: context.sharedContext.currentPresentationData.with { $0 }.strings.baseLanguageCode), timeout: nil, customUndoText: nil), + elevatedLayout: false, + action: { _ in return false } + ), + nil) + context.sharedContext.SGIAP?.restorePurchases {} + case .setIAP: + #if DEBUG + #endif + case .resetIAP: + SGSimpleSettings.shared.primaryUserId = "" + presentControllerImpl?(UndoOverlayController( + presentationData: presentationData, + content: .info(title: nil, text: "Status reset completed. You can now restore purchases.", timeout: nil, customUndoText: nil), + elevatedLayout: false, + action: { _ in return false } + ), + nil) + } + }) + + let signal: Signal<(ItemListControllerState, (ItemListNodeState, SGItemListArguments)), NoError> = combineLatest(context.sharedContext.presentationData, simplePromise.get()) + |> map { presentationData, _ -> (ItemListControllerState, (ItemListNodeState, SGItemListArguments)) in + + let entries = SGDebugControllerEntries(presentationData: presentationData) + + let controllerState = ItemListControllerState(presentationData: ItemListPresentationData(presentationData), title: .text("Swiftgram Debug"), leftNavigationButton: nil, rightNavigationButton: nil, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back)) + + let listState = ItemListNodeState(presentationData: ItemListPresentationData(presentationData), entries: entries, style: .blocks, ensureVisibleItemTag: /*focusOnItemTag*/ nil, initialScrollToItem: nil /* scrollToItem*/ ) + + return (controllerState, (listState, arguments)) + } + + let controller = ItemListController(context: context, state: signal) + presentControllerImpl = { [weak controller] c, a in + controller?.present(c, in: .window(.root), with: a) + } + pushControllerImpl = { [weak controller] c in + (controller?.navigationController as? NavigationController)?.pushViewController(c) + } + // Workaround + let _ = pushControllerImpl + + return controller +} + diff --git a/Swiftgram/SGDeviceToken/BUILD b/Swiftgram/SGDeviceToken/BUILD new file mode 100644 index 00000000..8a1446f3 --- /dev/null +++ b/Swiftgram/SGDeviceToken/BUILD @@ -0,0 +1,18 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGDeviceToken", + module_name = "SGDeviceToken", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGDeviceToken/Sources/File.swift b/Swiftgram/SGDeviceToken/Sources/File.swift new file mode 100644 index 00000000..abf7df33 --- /dev/null +++ b/Swiftgram/SGDeviceToken/Sources/File.swift @@ -0,0 +1,31 @@ +import SwiftSignalKit +import DeviceCheck + +public enum SGDeviceTokenError { + case unsupportedDevice + case generic(String) +} + +public func getDeviceToken() -> Signal { + return Signal { subscriber in + let currentDevice = DCDevice.current + if currentDevice.isSupported { + currentDevice.generateToken { (data, error) in + guard error == nil else { + subscriber.putError(.generic(error!.localizedDescription)) + return + } + if let tokenData = data { + subscriber.putNext(tokenData.base64EncodedString()) + subscriber.putCompletion() + } else { + subscriber.putError(.generic("Empty Token")) + } + } + } else { + subscriber.putError(.unsupportedDevice) + } + return ActionDisposable { + } + } +} diff --git a/Swiftgram/SGDoubleTapMessageAction/BUILD b/Swiftgram/SGDoubleTapMessageAction/BUILD new file mode 100644 index 00000000..ac9be00d --- /dev/null +++ b/Swiftgram/SGDoubleTapMessageAction/BUILD @@ -0,0 +1,9 @@ +filegroup( + name = "SGDoubleTapMessageAction", + srcs = glob([ + "Sources/**/*.swift", + ]), + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGDoubleTapMessageAction/Sources/SGDoubleTapMessageAction.swift b/Swiftgram/SGDoubleTapMessageAction/Sources/SGDoubleTapMessageAction.swift new file mode 100644 index 00000000..2cefa9b8 --- /dev/null +++ b/Swiftgram/SGDoubleTapMessageAction/Sources/SGDoubleTapMessageAction.swift @@ -0,0 +1,13 @@ +import Foundation +import SGSimpleSettings +import Postbox +import TelegramCore + + +func sgDoubleTapMessageAction(incoming: Bool, message: Message) -> String { + if incoming { + return SGSimpleSettings.MessageDoubleTapAction.default.rawValue + } else { + return SGSimpleSettings.shared.messageDoubleTapActionOutgoing + } +} diff --git a/Swiftgram/SGEmojiKeyboardDefaultFirst/BUILD b/Swiftgram/SGEmojiKeyboardDefaultFirst/BUILD new file mode 100644 index 00000000..87428676 --- /dev/null +++ b/Swiftgram/SGEmojiKeyboardDefaultFirst/BUILD @@ -0,0 +1,9 @@ +filegroup( + name = "SGEmojiKeyboardDefaultFirst", + srcs = glob([ + "Sources/**/*.swift", + ]), + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGEmojiKeyboardDefaultFirst/Sources/SGEmojiKeyboardDefaultFirst.swift b/Swiftgram/SGEmojiKeyboardDefaultFirst/Sources/SGEmojiKeyboardDefaultFirst.swift new file mode 100644 index 00000000..8d582084 --- /dev/null +++ b/Swiftgram/SGEmojiKeyboardDefaultFirst/Sources/SGEmojiKeyboardDefaultFirst.swift @@ -0,0 +1,23 @@ +import Foundation + + +func sgPatchEmojiKeyboardItems(_ items: [EmojiPagerContentComponent.ItemGroup]) -> [EmojiPagerContentComponent.ItemGroup] { + var items = items + let staticEmojisIndex = items.firstIndex { item in + if let groupId = item.groupId.base as? String, groupId == "static" { + return true + } + return false + } + let recentEmojisIndex = items.firstIndex { item in + if let groupId = item.groupId.base as? String, groupId == "recent" { + return true + } + return false + } + if let staticEmojisIndex = staticEmojisIndex { + let staticEmojiItem = items.remove(at: staticEmojisIndex) + items.insert(staticEmojiItem, at: (recentEmojisIndex ?? -1) + 1 ) + } + return items +} \ No newline at end of file diff --git a/Swiftgram/SGGHSettings/BUILD b/Swiftgram/SGGHSettings/BUILD new file mode 100644 index 00000000..94ed6252 --- /dev/null +++ b/Swiftgram/SGGHSettings/BUILD @@ -0,0 +1,21 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGGHSettings", + module_name = "SGGHSettings", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//Swiftgram/SGGHSettingsScheme:SGGHSettingsScheme", + "//Swiftgram/SGLogging:SGLogging", + "//submodules/AccountContext:AccountContext", + "//submodules/TelegramCore:TelegramCore", + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGGHSettings/Sources/SGGHSettings.swift b/Swiftgram/SGGHSettings/Sources/SGGHSettings.swift new file mode 100644 index 00000000..5482caca --- /dev/null +++ b/Swiftgram/SGGHSettings/Sources/SGGHSettings.swift @@ -0,0 +1,100 @@ +import Foundation +import SGLogging +import SGGHSettingsScheme +import AccountContext +import TelegramCore +import SwiftSignalKit + + +public func updateSGGHSettingsInteractivelly(context: AccountContext) { + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + let locale = presentationData.strings.baseLanguageCode + let _ = Task { + do { + let settings = try await fetchSGGHSettings(locale: locale) + let _ = context.account.postbox.transaction { transaction in + updateAppConfiguration(transaction: transaction, { configuration -> AppConfiguration in + var configuration = configuration + configuration.sgGHSettings = settings + return configuration + }) + }.start() + } catch { + return + } + + } +} + + +let maxRetries: Int = 3 + +enum SGGHFetchError: Error { + case invalidURL + case notFound + case fetchFailed(statusCode: Int) + case decodingFailed +} + +func fetchSGGHSettings(locale: String) async throws -> SGGHSettings { + let baseURL = "https://raw.githubusercontent.com/Swiftgram/settings/refs/heads/main" + var candidates: [String] = [] + if let buildNumber = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String { + if locale != "en" { + candidates.append("\(buildNumber)_\(locale).json") + } + candidates.append("\(buildNumber).json") + } + if locale != "en" { + candidates.append("latest_\(locale).json") + } + candidates.append("latest.json") + + var lastError: Error? + for candidate in candidates { + let urlString = "\(baseURL)/\(candidate)" + guard let url = URL(string: urlString) else { + SGLogger.shared.log("SGGHSettings", "[0] Fetch failed for \(candidate). Invalid URL: \(urlString)") + continue + } + + attemptsOuter: for attempt in 1...maxRetries { + do { + let (data, response) = try await URLSession.shared.data(from: url) + guard let httpResponse = response as? HTTPURLResponse else { + SGLogger.shared.log("SGGHSettings", "[\(attempt)] Fetch failed for \(candidate). Invalid response type: \(response)") + throw SGGHFetchError.fetchFailed(statusCode: -1) + } + + switch httpResponse.statusCode { + case 200: + do { + let jsonDecoder = JSONDecoder() + jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase + let settings = try jsonDecoder.decode(SGGHSettings.self, from: data) + SGLogger.shared.log("SGGHSettings", "[\(attempt)] Fetched \(candidate): \(settings)") + return settings + } catch { + SGLogger.shared.log("SGGHSettings", "[\(attempt)] Failed to decode \(candidate): \(error)") + throw SGGHFetchError.decodingFailed + } + case 404: + SGLogger.shared.log("SGGHSettings", "[\(attempt)] Not found \(candidate) on the remote.") + break attemptsOuter + default: + SGLogger.shared.log("SGGHSettings", "[\(attempt)] Fetch failed for \(candidate), status code: \(httpResponse.statusCode)") + throw SGGHFetchError.fetchFailed(statusCode: httpResponse.statusCode) + } + } catch { + lastError = error + if attempt == maxRetries { + break + } + try await Task.sleep(nanoseconds: UInt64(attempt * 2 * 1_000_000_000)) + } + } + } + + SGLogger.shared.log("SGGHSettings", "All attempts failed. Last error: \(String(describing: lastError))") + throw SGGHFetchError.fetchFailed(statusCode: -1) +} diff --git a/Swiftgram/SGGHSettingsScheme/BUILD b/Swiftgram/SGGHSettingsScheme/BUILD new file mode 100644 index 00000000..105e0f6a --- /dev/null +++ b/Swiftgram/SGGHSettingsScheme/BUILD @@ -0,0 +1,17 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGGHSettingsScheme", + module_name = "SGGHSettingsScheme", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGGHSettingsScheme/Sources/SGGHSettingsScheme.swift b/Swiftgram/SGGHSettingsScheme/Sources/SGGHSettingsScheme.swift new file mode 100644 index 00000000..1335c375 --- /dev/null +++ b/Swiftgram/SGGHSettingsScheme/Sources/SGGHSettingsScheme.swift @@ -0,0 +1,9 @@ +import Foundation + +public struct SGGHSettings: Codable, Equatable { + public let announcementsData: String? + + public static var defaultValue: SGGHSettings { + return SGGHSettings(announcementsData: nil) + } +} \ No newline at end of file diff --git a/Swiftgram/SGIAP/BUILD b/Swiftgram/SGIAP/BUILD new file mode 100644 index 00000000..c80d9725 --- /dev/null +++ b/Swiftgram/SGIAP/BUILD @@ -0,0 +1,21 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGIAP", + module_name = "SGIAP", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//Swiftgram/SGLogging:SGLogging", + "//Swiftgram/SGConfig:SGConfig", + "//submodules/AppBundle:AppBundle", + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGIAP/Sources/SGIAP.swift b/Swiftgram/SGIAP/Sources/SGIAP.swift new file mode 100644 index 00000000..c2940161 --- /dev/null +++ b/Swiftgram/SGIAP/Sources/SGIAP.swift @@ -0,0 +1,384 @@ +import StoreKit +import SGConfig +import SGLogging +import AppBundle +import Combine + +private final class CurrencyFormatterEntry { + public let symbol: String + public let thousandsSeparator: String + public let decimalSeparator: String + public let symbolOnLeft: Bool + public let spaceBetweenAmountAndSymbol: Bool + public let decimalDigits: Int + + public init(symbol: String, thousandsSeparator: String, decimalSeparator: String, symbolOnLeft: Bool, spaceBetweenAmountAndSymbol: Bool, decimalDigits: Int) { + self.symbol = symbol + self.thousandsSeparator = thousandsSeparator + self.decimalSeparator = decimalSeparator + self.symbolOnLeft = symbolOnLeft + self.spaceBetweenAmountAndSymbol = spaceBetweenAmountAndSymbol + self.decimalDigits = decimalDigits + } +} + +private func getCurrencyExp(currency: String) -> Int { + switch currency { + case "CLF": + return 4 + case "BHD", "IQD", "JOD", "KWD", "LYD", "OMR", "TND": + return 3 + case "BIF", "BYR", "CLP", "CVE", "DJF", "GNF", "ISK", "JPY", "KMF", "KRW", "MGA", "PYG", "RWF", "UGX", "UYI", "VND", "VUV", "XAF", "XOF", "XPF": + return 0 + case "MRO": + return 1 + default: + return 2 + } +} + +private func loadCurrencyFormatterEntries() -> [String: CurrencyFormatterEntry] { + guard let filePath = getAppBundle().path(forResource: "currencies", ofType: "json") else { + return [:] + } + guard let data = try? Data(contentsOf: URL(fileURLWithPath: filePath)) else { + return [:] + } + + guard let object = try? JSONSerialization.jsonObject(with: data, options: []), let dict = object as? [String: AnyObject] else { + return [:] + } + + var result: [String: CurrencyFormatterEntry] = [:] + + for (code, contents) in dict { + if let contentsDict = contents as? [String: AnyObject] { + let entry = CurrencyFormatterEntry( + symbol: contentsDict["symbol"] as! String, + thousandsSeparator: contentsDict["thousandsSeparator"] as! String, + decimalSeparator: contentsDict["decimalSeparator"] as! String, + symbolOnLeft: (contentsDict["symbolOnLeft"] as! NSNumber).boolValue, + spaceBetweenAmountAndSymbol: (contentsDict["spaceBetweenAmountAndSymbol"] as! NSNumber).boolValue, + decimalDigits: getCurrencyExp(currency: code.uppercased()) + ) + result[code] = entry + result[code.lowercased()] = entry + } + } + + return result +} + +private let currencyFormatterEntries = loadCurrencyFormatterEntries() + +private func fractionalValueToCurrencyAmount(value: Double, currency: String) -> Int64? { + guard let entry = currencyFormatterEntries[currency] ?? currencyFormatterEntries["USD"] else { + return nil + } + var factor: Double = 1.0 + for _ in 0 ..< entry.decimalDigits { + factor *= 10.0 + } + if value > Double(Int64.max) / factor { + return nil + } else { + return Int64(value * factor) + } +} + + +public extension Notification.Name { + static let SGIAPHelperPurchaseNotification = Notification.Name("SGIAPPurchaseNotification") + static let SGIAPHelperErrorNotification = Notification.Name("SGIAPErrorNotification") + static let SGIAPHelperProductsUpdatedNotification = Notification.Name("SGIAPProductsUpdatedNotification") + static let SGIAPHelperValidationErrorNotification = Notification.Name("SGIAPValidationErrorNotification") +} + +public final class SGIAPManager: NSObject { + private var productRequest: SKProductsRequest? + private var productsRequestCompletion: (([SKProduct]) -> Void)? + private var purchaseCompletion: ((Bool, Error?) -> Void)? + + public private(set) var availableProducts: [SGProduct] = [] + private var finishedSuccessfulTransactions = Set() + private var onRestoreCompletion: (() -> Void)? + + public final class SGProduct: Equatable { + private lazy var numberFormatter: NumberFormatter = { + let numberFormatter = NumberFormatter() + numberFormatter.numberStyle = .currency + numberFormatter.locale = self.skProduct.priceLocale + return numberFormatter + }() + + public let skProduct: SKProduct + + init(skProduct: SKProduct) { + self.skProduct = skProduct + } + + public var id: String { + return self.skProduct.productIdentifier + } + + public var isSubscription: Bool { + if #available(iOS 12.0, *) { + return self.skProduct.subscriptionGroupIdentifier != nil + } else { + return self.skProduct.subscriptionPeriod != nil + } + } + + public var price: String { + return self.numberFormatter.string(from: self.skProduct.price) ?? "" + } + + public func pricePerMonth(_ monthsCount: Int) -> String { + let price = self.skProduct.price.dividing(by: NSDecimalNumber(value: monthsCount)).round(2) + return self.numberFormatter.string(from: price) ?? "" + } + + public func defaultPrice(_ value: NSDecimalNumber, monthsCount: Int) -> String { + let price = value.multiplying(by: NSDecimalNumber(value: monthsCount)).round(2) + let prettierPrice = price + .multiplying(by: NSDecimalNumber(value: 2)) + .rounding(accordingToBehavior: + NSDecimalNumberHandler( + roundingMode: .up, + scale: Int16(0), + raiseOnExactness: false, + raiseOnOverflow: false, + raiseOnUnderflow: false, + raiseOnDivideByZero: false + ) + ) + .dividing(by: NSDecimalNumber(value: 2)) + .subtracting(NSDecimalNumber(value: 0.01)) + return self.numberFormatter.string(from: prettierPrice) ?? "" + } + + public func multipliedPrice(count: Int) -> String { + let price = self.skProduct.price.multiplying(by: NSDecimalNumber(value: count)).round(2) + let prettierPrice = price + .multiplying(by: NSDecimalNumber(value: 2)) + .rounding(accordingToBehavior: + NSDecimalNumberHandler( + roundingMode: .up, + scale: Int16(0), + raiseOnExactness: false, + raiseOnOverflow: false, + raiseOnUnderflow: false, + raiseOnDivideByZero: false + ) + ) + .dividing(by: NSDecimalNumber(value: 2)) + .subtracting(NSDecimalNumber(value: 0.01)) + return self.numberFormatter.string(from: prettierPrice) ?? "" + } + + public var priceValue: NSDecimalNumber { + return self.skProduct.price + } + + public var priceCurrencyAndAmount: (currency: String, amount: Int64) { + if let currencyCode = self.numberFormatter.currencyCode, + let amount = fractionalValueToCurrencyAmount(value: self.priceValue.doubleValue, currency: currencyCode) { + return (currencyCode, amount) + } else { + return ("", 0) + } + } + + public static func ==(lhs: SGProduct, rhs: SGProduct) -> Bool { + if lhs.id != rhs.id { + return false + } + if lhs.isSubscription != rhs.isSubscription { + return false + } + if lhs.priceValue != rhs.priceValue { + return false + } + return true + } + + } + + public init(foo: Bool = false) { // I don't want to override init, idk why + super.init() + + SKPaymentQueue.default().add(self) + + #if DEBUG && false + DispatchQueue.main.asyncAfter(deadline: .now() + 20) { + self.requestProducts() + } + #else + self.requestProducts() + #endif + } + + deinit { + SKPaymentQueue.default().remove(self) + } + + public var canMakePayments: Bool { + return SKPaymentQueue.canMakePayments() + } + + public func buyProduct(_ product: SKProduct) { + SGLogger.shared.log("SGIAP", "Buying \(product.productIdentifier)...") + let payment = SKPayment(product: product) + SKPaymentQueue.default().add(payment) + } + + private func requestProducts() { + SGLogger.shared.log("SGIAP", "Requesting products for \(SG_CONFIG.iaps.count) ids...") + let productRequest = SKProductsRequest(productIdentifiers: Set(SG_CONFIG.iaps)) + + productRequest.delegate = self + productRequest.start() + + self.productRequest = productRequest + } + + public func restorePurchases(completion: @escaping () -> Void) { + SGLogger.shared.log("SGIAP", "Restoring purchases...") + self.onRestoreCompletion = completion + + let paymentQueue = SKPaymentQueue.default() + paymentQueue.restoreCompletedTransactions() + } + +} + +extension SGIAPManager: SKProductsRequestDelegate { + public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { + self.productRequest = nil + + DispatchQueue.main.async { + let products = response.products + SGLogger.shared.log("SGIAP", "Received products (\(products.count)): \(products.map({ $0.productIdentifier }).joined(separator: ", "))") + let currentlyAvailableProducts = self.availableProducts + self.availableProducts = products.map({ SGProduct(skProduct: $0) }) + if currentlyAvailableProducts != self.availableProducts { + NotificationCenter.default.post(name: .SGIAPHelperProductsUpdatedNotification, object: nil) + } + } + } + + public func request(_ request: SKRequest, didFailWithError error: Error) { + SGLogger.shared.log("SGIAP", "Failed to load list of products. Error \(error.localizedDescription)") + self.productRequest = nil + } +} + +extension SGIAPManager: SKPaymentTransactionObserver { + public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { + SGLogger.shared.log("SGIAP", "paymentQueue transactions \(transactions.count)") + var purchaceTransactions: [SKPaymentTransaction] = [] + for transaction in transactions { + SGLogger.shared.log("SGIAP", "Transaction \(transaction.transactionIdentifier ?? "nil") state for product \(transaction.payment.productIdentifier): \(transaction.transactionState.description)") + switch transaction.transactionState { + case .purchased, .restored: + purchaceTransactions.append(transaction) + break + case .purchasing, .deferred: + // Ignoring + break + case .failed: + var localizedError: String = "" + if let transactionError = transaction.error as NSError?, + let localizedDescription = transaction.error?.localizedDescription, + transactionError.code != SKError.paymentCancelled.rawValue { + localizedError = localizedDescription + SGLogger.shared.log("SGIAP", "Transaction Error [\(transaction.transactionIdentifier ?? "nil")]: \(localizedDescription)") + } + SGLogger.shared.log("SGIAP", "Sending SGIAPHelperErrorNotification for \(transaction.transactionIdentifier ?? "nil")") + NotificationCenter.default.post(name: .SGIAPHelperErrorNotification, object: transaction, userInfo: ["localizedError": localizedError]) + default: + SGLogger.shared.log("SGIAP", "Unknown transaction \(transaction.transactionIdentifier ?? "nil") state \(transaction.transactionState). Finishing transaction.") + SKPaymentQueue.default().finishTransaction(transaction) + } + } + + if !purchaceTransactions.isEmpty { + SGLogger.shared.log("SGIAP", "Sending SGIAPHelperPurchaseNotification for \(purchaceTransactions.map({ $0.transactionIdentifier ?? "nil" }).joined(separator: ", "))") + NotificationCenter.default.post(name: .SGIAPHelperPurchaseNotification, object: purchaceTransactions) + } + } + + public func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) { + SGLogger.shared.log("SGIAP", "Transactions restored") + + if let onRestoreCompletion = self.onRestoreCompletion { + self.onRestoreCompletion = nil + onRestoreCompletion() + } + } + +} + +private extension NSDecimalNumber { + func round(_ decimals: Int) -> NSDecimalNumber { + return self.rounding(accordingToBehavior: + NSDecimalNumberHandler(roundingMode: .down, + scale: Int16(decimals), + raiseOnExactness: false, + raiseOnOverflow: false, + raiseOnUnderflow: false, + raiseOnDivideByZero: false)) + } + + func prettyPrice() -> NSDecimalNumber { + return self.multiplying(by: NSDecimalNumber(value: 2)) + .rounding(accordingToBehavior: + NSDecimalNumberHandler( + roundingMode: .plain, + scale: Int16(0), + raiseOnExactness: false, + raiseOnOverflow: false, + raiseOnUnderflow: false, + raiseOnDivideByZero: false + ) + ) + .dividing(by: NSDecimalNumber(value: 2)) + .subtracting(NSDecimalNumber(value: 0.01)) + } +} + + +public func getPurchaceReceiptData() -> Data? { + var receiptData: Data? + if let appStoreReceiptURL = Bundle.main.appStoreReceiptURL, FileManager.default.fileExists(atPath: appStoreReceiptURL.path) { + do { + receiptData = try Data(contentsOf: appStoreReceiptURL, options: .alwaysMapped) + } catch { + SGLogger.shared.log("SGIAP", "Couldn't read receipt data with error: \(error.localizedDescription)") + } + } else { + SGLogger.shared.log("SGIAP", "Couldn't find receipt path") + } + return receiptData +} + + +extension SKPaymentTransactionState { + var description: String { + switch self { + case .purchasing: + return "Purchasing" + case .purchased: + return "Purchased" + case .failed: + return "Failed" + case .restored: + return "Restored" + case .deferred: + return "Deferred" + @unknown default: + return "Unknown" + } + } +} + diff --git a/Swiftgram/SGIQTP/BUILD b/Swiftgram/SGIQTP/BUILD new file mode 100644 index 00000000..99dbb603 --- /dev/null +++ b/Swiftgram/SGIQTP/BUILD @@ -0,0 +1,9 @@ +filegroup( + name = "SGIQTP", + srcs = glob([ + "Sources/**/*.swift", + ]), + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGIQTP/Sources/SGIQTP.swift b/Swiftgram/SGIQTP/Sources/SGIQTP.swift new file mode 100644 index 00000000..7d6cff03 --- /dev/null +++ b/Swiftgram/SGIQTP/Sources/SGIQTP.swift @@ -0,0 +1,251 @@ +import SGConfig +import SGLogging +import CryptoKit +import Foundation +import MtProtoKit +import Postbox +import Security +import SwiftSignalKit +import TelegramApi + + +public struct SGIQTPResponse { + public let status: Int + public let value: String +} + + +private let sgIqtpTokenPrefix = "sgsig.v1." +private let sgIqtpTokenMinimumParts = 4 +private let sgIqtpTokenSeparator: Character = "." +private let sgIqtpTokenMaxPastSkew: Int64 = 30 +private let sgIqtpTokenMaxFutureSkew: Int64 = 10 * 60 +private let sgIqtpApiVersion = 1 + +private func sgBase64UrlEncode(_ data: Data) -> String { + let sgBase64 = data.base64EncodedString() + return sgBase64 + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") +} + +public func makeIqtpQuery(_ method: String, _ args: [String] = []) -> String { + let buildNumber = Bundle.main.infoDictionary?[kCFBundleVersionKey as String] ?? "" + let nonceLength = 16 + var bytes = [UInt8](repeating: 0, count: nonceLength) + let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) + if status != errSecSuccess { + for index in 0.. Signal { + let queryId = arc4random() + func sgVerifySignedAnswer(query: String, answer: String, peerId: PeerId) -> String? { + func sgBase64UrlDecode(_ value: String) -> Data? { + var sgBase64 = value + .replacingOccurrences(of: "-", with: "+") + .replacingOccurrences(of: "_", with: "/") + let sgRemainder = sgBase64.count % 4 + if sgRemainder > 0 { + sgBase64 += String(repeating: "=", count: 4 - sgRemainder) + } + return Data(base64Encoded: sgBase64) + } + + func sgDecodePublicKey(_ value: String) -> Data? { + if let sgData = Data(base64Encoded: value) { + return sgData + } + return sgBase64UrlDecode(value) + } + + func sgExtractSignedToken(from text: String) -> (payload: String, signature: String)? { + guard let sgRange = text.range(of: sgIqtpTokenPrefix) else { + return nil + } + let sgTokenStart = text[sgRange.lowerBound...] + guard let sgTokenPart = sgTokenStart.split(whereSeparator: { $0 == " " || $0 == "\n" || $0 == "\t" }).first else { + return nil + } + let sgParts = sgTokenPart.split(separator: sgIqtpTokenSeparator, omittingEmptySubsequences: false) + guard sgParts.count >= sgIqtpTokenMinimumParts else { + return nil + } + guard sgParts[0] == "sgsig", sgParts[1] == "v1" else { + return nil + } + return (payload: String(sgParts[2]), signature: String(sgParts[3])) + } + + let sgQueryParts = query.split(separator: ":", omittingEmptySubsequences: false) + guard sgQueryParts.count >= 4, sgQueryParts[0] == "tp" else { + SGLogger.shared.log("SGIQTP", "Missing IQTP query info") + return nil + } + guard let sgQueryVersion = Int(sgQueryParts[1]), sgQueryVersion == 1 else { + SGLogger.shared.log("SGIQTP", "Unsupported IQTP version") + return nil + } + let sgQueryBuild = String(sgQueryParts[2]) + let sgQueryMethod = String(sgQueryParts[3]) + let sgQueryArgs = sgQueryParts.count > 4 ? sgQueryParts[4...].map { String($0) } : [] + guard let sgNonce = sgQueryArgs.first, !sgNonce.isEmpty else { + SGLogger.shared.log("SGIQTP", "Missing IQTP nonce") + return nil + } + + guard let sgPublicKey = SG_CONFIG.publicKey, !sgPublicKey.isEmpty else { + SGLogger.shared.log("SGIQTP", "Missing public key") + return nil + } + guard let sgToken = sgExtractSignedToken(from: answer) else { + SGLogger.shared.log("SGIQTP", "Missing signed IQTP token") + return nil + } + guard let sgAnswerData = sgBase64UrlDecode(sgToken.payload) else { + SGLogger.shared.log("SGIQTP", "Invalid IQTP answer encoding") + return nil + } + guard let sgSignatureData = sgBase64UrlDecode(sgToken.signature) else { + SGLogger.shared.log("SGIQTP", "Invalid IQTP signature encoding") + return nil + } + guard let sgPublicKeyData = sgDecodePublicKey(sgPublicKey) else { + SGLogger.shared.log("SGIQTP", "Invalid public key") + return nil + } + guard let sgSigningKey = try? Curve25519.Signing.PublicKey(rawRepresentation: sgPublicKeyData) else { + SGLogger.shared.log("SGIQTP", "Invalid public key bytes") + return nil + } + guard sgSigningKey.isValidSignature(sgSignatureData, for: sgAnswerData) else { + SGLogger.shared.log("SGIQTP", "Invalid IQTP signature") + return nil + } + guard let sgAnswerString = String(data: sgAnswerData, encoding: .utf8) else { + SGLogger.shared.log("SGIQTP", "Invalid IQTP answer string") + return nil + } + let sgAnswerParts = sgAnswerString.split(separator: ":", omittingEmptySubsequences: false) + guard sgAnswerParts.count == 8 else { + SGLogger.shared.log("SGIQTP", "Invalid IQTP answer parts count") + return nil + } + guard let sgAnswerVersion = Int(sgAnswerParts[0]), sgAnswerVersion == 1 else { + SGLogger.shared.log("SGIQTP", "Invalid IQTP answer version") + return nil + } + let sgAnswerMethod = String(sgAnswerParts[1]) + guard sgAnswerMethod == sgQueryMethod else { + SGLogger.shared.log("SGIQTP", "Invalid IQTP answer method") + return nil + } + guard let sgAnswerPeerId = Int64(sgAnswerParts[2]) else { + SGLogger.shared.log("SGIQTP", "Invalid IQTP answer peer id") + return nil + } + let sgAnswerNonce = String(sgAnswerParts[3]) + guard sgAnswerNonce == sgNonce else { + SGLogger.shared.log("SGIQTP", "Invalid IQTP answer nonce") + return nil + } + guard let sgIat = Int64(sgAnswerParts[4]), let sgExp = Int64(sgAnswerParts[5]) else { + SGLogger.shared.log("SGIQTP", "Invalid IQTP answer timing") + return nil + } + let sgValue = String(sgAnswerParts[6]) + let sgAnswerBuild = String(sgAnswerParts[7]) + guard sgAnswerBuild == sgQueryBuild else { + SGLogger.shared.log("SGIQTP", "Invalid IQTP answer build number") + return nil + } + let sgNow = Int64(Date().timeIntervalSince1970) + guard sgExp >= sgNow - sgIqtpTokenMaxPastSkew else { + SGLogger.shared.log("SGIQTP", "Expired IQTP answer") + return nil + } + guard sgExp <= sgNow + sgIqtpTokenMaxFutureSkew else { + SGLogger.shared.log("SGIQTP", "IQTP answer exp too far in future") + return nil + } + guard sgIat <= sgExp else { + SGLogger.shared.log("SGIQTP", "Invalid IQTP answer timing order") + return nil + } + let sgCurrentPeerId = peerId.id._internalGetInt64Value() + guard sgAnswerPeerId == sgCurrentPeerId else { + SGLogger.shared.log("SGIQTP", "IQTP answer peer id mismatch") + return nil + } + return sgValue + } + #if DEBUG + SGLogger.shared.log("SGIQTP", "[\(queryId)] Query: \(query)") + #else + SGLogger.shared.log("SGIQTP", "[\(queryId)] Query") + #endif + return engine.peers.resolvePeerByName(name: SG_CONFIG.botUsername, referrer: nil) + |> mapToSignal { result -> Signal in + guard case let .result(result) = result else { + SGLogger.shared.log("SGIQTP", "[\(queryId)] Failed to resolve peer \(SG_CONFIG.botUsername)") + return .complete() + } + return .single(result) + } + |> mapToSignal { peer -> Signal in + guard let peer = peer else { + SGLogger.shared.log("SGIQTP", "[\(queryId)] Empty peer") + return .single(nil) + } + return engine.messages.requestChatContextResults(IQTP: true, botId: peer.id, peerId: engine.account.peerId, query: query, offset: "", incompleteResults: incompleteResults, staleCachedResults: staleCachedResults) + |> map { results -> ChatContextResultCollection? in + return results?.results + } + |> `catch` { error -> Signal in + SGLogger.shared.log("SGIQTP", "[\(queryId)] Failed to request inline results") + return .single(nil) + } + } + |> map { contextResult -> SGIQTPResponse? in + guard let contextResult, let firstResult = contextResult.results.first else { + SGLogger.shared.log("SGIQTP", "[\(queryId)] Empty inline result") + return nil + } + + var t: String? + if case let .text(text, _, _, _, _) = firstResult.message { + t = text + } + + guard let t else { + SGLogger.shared.log("SGIQTP", "[\(queryId)] Missing signed IQTP answer") + return nil + } + let sgValue: String + if let sgVerifiedValue = sgVerifySignedAnswer(query: query, answer: t, peerId: engine.account.peerId) { + sgValue = sgVerifiedValue + } else { + SGLogger.shared.log("SGIQTP", "[\(queryId)] Invalid signed IQTP token") + return nil + } + + var status = 400 + if let title = firstResult.title { + status = Int(title) ?? 400 + } + let response = SGIQTPResponse(status: status, value: sgValue) + SGLogger.shared.log("SGIQTP", "[\(queryId)] Response status: \(status)") + return response + } +} diff --git a/Swiftgram/SGInputToolbar/BUILD b/Swiftgram/SGInputToolbar/BUILD new file mode 100644 index 00000000..6b2de974 --- /dev/null +++ b/Swiftgram/SGInputToolbar/BUILD @@ -0,0 +1,17 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGInputToolbar", + module_name = "SGInputToolbar", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGInputToolbar/Sources/SGInputToolbar.swift b/Swiftgram/SGInputToolbar/Sources/SGInputToolbar.swift new file mode 100644 index 00000000..5f0beceb --- /dev/null +++ b/Swiftgram/SGInputToolbar/Sources/SGInputToolbar.swift @@ -0,0 +1,209 @@ +import SwiftUI +import Foundation + + +// MARK: Swiftgram +public struct ChatToolbarView: View { + var onQuote: () -> Void + var onSpoiler: () -> Void + var onBold: () -> Void + var onItalic: () -> Void + var onMonospace: () -> Void + var onLink: () -> Void + var onStrikethrough: () -> Void + var onUnderline: () -> Void + var onCode: () -> Void + + var onNewLine: () -> Void + @Binding private var showNewLine: Bool + + var onClearFormatting: () -> Void + + public init( + onQuote: @escaping () -> Void, + onSpoiler: @escaping () -> Void, + onBold: @escaping () -> Void, + onItalic: @escaping () -> Void, + onMonospace: @escaping () -> Void, + onLink: @escaping () -> Void, + onStrikethrough: @escaping () -> Void, + onUnderline: @escaping () -> Void, + onCode: @escaping () -> Void, + onNewLine: @escaping () -> Void, + showNewLine: Binding, + onClearFormatting: @escaping () -> Void + ) { + self.onQuote = onQuote + self.onSpoiler = onSpoiler + self.onBold = onBold + self.onItalic = onItalic + self.onMonospace = onMonospace + self.onLink = onLink + self.onStrikethrough = onStrikethrough + self.onUnderline = onUnderline + self.onCode = onCode + self.onNewLine = onNewLine + self._showNewLine = showNewLine + self.onClearFormatting = onClearFormatting + } + + public func setShowNewLine(_ value: Bool) { + self.showNewLine = value + } + + public var body: some View { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 12) { + if showNewLine { + Button(action: onNewLine) { + Image(systemName: "return") + } + .buttonStyle(ToolbarButtonStyle()) + } + Button(action: onClearFormatting) { + Image(systemName: "pencil.slash") + } + .buttonStyle(ToolbarButtonStyle()) + Spacer() + // Quote Button + Button(action: onQuote) { + Image(systemName: "text.quote") + } + .buttonStyle(ToolbarButtonStyle()) + + // Spoiler Button + Button(action: onSpoiler) { + Image(systemName: "eye.slash") + } + .buttonStyle(ToolbarButtonStyle()) + + // Bold Button + Button(action: onBold) { + Image(systemName: "bold") + } + .buttonStyle(ToolbarButtonStyle()) + + // Italic Button + Button(action: onItalic) { + Image(systemName: "italic") + } + .buttonStyle(ToolbarButtonStyle()) + + // Monospace Button + Button(action: onMonospace) { + if #available(iOS 16.4, *) { + Text("M").monospaced() + } else { + Text("M") + } + } + .buttonStyle(ToolbarButtonStyle()) + + // Link Button + Button(action: onLink) { + Image(systemName: "link") + } + .buttonStyle(ToolbarButtonStyle()) + + // Underline Button + Button(action: onUnderline) { + Image(systemName: "underline") + } + .buttonStyle(ToolbarButtonStyle()) + + + // Strikethrough Button + Button(action: onStrikethrough) { + Image(systemName: "strikethrough") + } + .buttonStyle(ToolbarButtonStyle()) + + + // Code Button + Button(action: onCode) { + Image(systemName: "chevron.left.forwardslash.chevron.right") + } + .buttonStyle(ToolbarButtonStyle()) + } + .padding(.horizontal, 8) + .padding(.vertical, 8) + } + .background(Color(UIColor.clear)) + } +} + + +// iOS 13–14 blur fallback +@available(iOS 13.0, *) +struct BlurView: UIViewRepresentable { + let style: UIBlurEffect.Style + func makeUIView(context: Context) -> UIVisualEffectView { + UIVisualEffectView(effect: UIBlurEffect(style: style)) + } + func updateUIView(_ uiView: UIVisualEffectView, context: Context) { + uiView.effect = UIBlurEffect(style: style) + } +} + +// Simple glass background (now supports round + adaptive brightness) +@available(iOS 13.0, *) +struct Glass: View { + var cornerRadius: CGFloat? + @Environment(\.colorScheme) private var colorScheme + + var body: some View { + let isDark = colorScheme == .dark + + Group { + if #available(iOS 15.0, *) { + Circle() + .fill(.ultraThinMaterial) + .overlay( + Circle() + .fill( + Color.white.opacity(isDark ? 0.05 : 0.25) + ) + ) + } else { + Circle() + .fill(Color.clear) + .background( + BlurView(style: .systemThinMaterial) + .clipShape(Circle()) + ) + .overlay( + Circle() + .fill( + Color.white.opacity(isDark ? 0.05 : 0.25) + ) + ) + } + } + .overlay( + Circle() + .stroke(Color.white.opacity(0.25), lineWidth: 1) + ) + .shadow(color: Color.black.opacity(0.12), radius: 6, x: 0, y: 3) + } + +} + +// Button style +@available(iOS 13.0, *) +struct ToolbarButtonStyle: ButtonStyle { + var size: CGFloat = 39 + + func makeBody(configuration: Configuration) -> some View { + configuration.label + .frame(width: size, height: size) + .contentShape(Circle()) + .background(Glass()) + .overlay( + Circle() + .fill(Color.black.opacity(configuration.isPressed ? 0.08 : 0)) + ) + .scaleEffect(configuration.isPressed ? 0.95 : 1) + .animation(nil, value: configuration.isPressed) + } +} + diff --git a/Swiftgram/SGItemListUI/BUILD b/Swiftgram/SGItemListUI/BUILD new file mode 100644 index 00000000..d0dd4589 --- /dev/null +++ b/Swiftgram/SGItemListUI/BUILD @@ -0,0 +1,30 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGItemListUI", + module_name = "SGItemListUI", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + "//submodules/Display:Display", + "//submodules/Postbox:Postbox", + "//submodules/TelegramCore:TelegramCore", + "//submodules/MtProtoKit:MtProtoKit", + "//submodules/TelegramPresentationData:TelegramPresentationData", + "//submodules/TelegramUIPreferences:TelegramUIPreferences", + "//submodules/ItemListUI:ItemListUI", + "//submodules/PresentationDataUtils:PresentationDataUtils", + "//submodules/OverlayStatusController:OverlayStatusController", + "//submodules/AccountContext:AccountContext", + "//submodules/AppBundle:AppBundle", + "//submodules/TelegramUI/Components/Settings/PeerNameColorScreen", + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGItemListUI/Sources/SGItemListUI.swift b/Swiftgram/SGItemListUI/Sources/SGItemListUI.swift new file mode 100644 index 00000000..a450bdd4 --- /dev/null +++ b/Swiftgram/SGItemListUI/Sources/SGItemListUI.swift @@ -0,0 +1,332 @@ +import Foundation +import UIKit +import Display +import SwiftSignalKit +import Postbox +import TelegramCore +import MtProtoKit +import MessageUI +import TelegramPresentationData +import TelegramUIPreferences +import ItemListUI +import PresentationDataUtils +import OverlayStatusController +import AccountContext +import AppBundle +import WebKit +import PeerNameColorScreen + +public class SGItemListCounter { + private var _count = 0 + + public init() {} + + public var count: Int { + _count += 1 + return _count + } + + public func increment(_ amount: Int) { + _count += amount + } + + public func countWith(_ amount: Int) -> Int { + _count += amount + return count + } +} + + +public protocol SGItemListSection: Equatable { + var rawValue: Int32 { get } +} + +public final class SGItemListArguments { + let context: AccountContext + // + let setBoolValue: (BoolSetting, Bool) -> Void + let updateSliderValue: (SliderSetting, Int32) -> Void + let setOneFromManyValue: (OneFromManySetting) -> Void + let openDisclosureLink: (DisclosureLink) -> Void + let action: (ActionType) -> Void + let searchInput: (String) -> Void + + + public init( + context: AccountContext, + // + setBoolValue: @escaping (BoolSetting, Bool) -> Void = { _,_ in }, + updateSliderValue: @escaping (SliderSetting, Int32) -> Void = { _,_ in }, + setOneFromManyValue: @escaping (OneFromManySetting) -> Void = { _ in }, + openDisclosureLink: @escaping (DisclosureLink) -> Void = { _ in}, + action: @escaping (ActionType) -> Void = { _ in }, + searchInput: @escaping (String) -> Void = { _ in } + ) { + self.context = context + // + self.setBoolValue = setBoolValue + self.updateSliderValue = updateSliderValue + self.setOneFromManyValue = setOneFromManyValue + self.openDisclosureLink = openDisclosureLink + self.action = action + self.searchInput = searchInput + } +} + +public enum SGItemListUIEntry: ItemListNodeEntry { + case header(id: Int, section: Section, text: String, badge: String?) + case toggle(id: Int, section: Section, settingName: BoolSetting, value: Bool, text: String, enabled: Bool) + case notice(id: Int, section: Section, text: String) + case percentageSlider(id: Int, section: Section, settingName: SliderSetting, value: Int32) + case oneFromManySelector(id: Int, section: Section, settingName: OneFromManySetting, text: String, value: String, enabled: Bool) + case disclosure(id: Int, section: Section, link: DisclosureLink, text: String) + case peerColorDisclosurePreview(id: Int, section: Section, name: String, color: UIColor) + case action(id: Int, section: Section, actionType: ActionType, text: String, kind: ItemListActionKind) + case searchInput(id: Int, section: Section, title: NSAttributedString, text: String, placeholder: String) + + public var section: ItemListSectionId { + switch self { + case let .header(_, sectionId, _, _): + return sectionId.rawValue + case let .toggle(_, sectionId, _, _, _, _): + return sectionId.rawValue + case let .notice(_, sectionId, _): + return sectionId.rawValue + + case let .disclosure(_, sectionId, _, _): + return sectionId.rawValue + + case let .percentageSlider(_, sectionId, _, _): + return sectionId.rawValue + + case let .peerColorDisclosurePreview(_, sectionId, _, _): + return sectionId.rawValue + case let .oneFromManySelector(_, sectionId, _, _, _, _): + return sectionId.rawValue + + case let .action(_, sectionId, _, _, _): + return sectionId.rawValue + + case let .searchInput(_, sectionId, _, _, _): + return sectionId.rawValue + } + } + + public var stableId: Int { + switch self { + case let .header(stableIdValue, _, _, _): + return stableIdValue + case let .toggle(stableIdValue, _, _, _, _, _): + return stableIdValue + case let .notice(stableIdValue, _, _): + return stableIdValue + case let .disclosure(stableIdValue, _, _, _): + return stableIdValue + case let .percentageSlider(stableIdValue, _, _, _): + return stableIdValue + case let .peerColorDisclosurePreview(stableIdValue, _, _, _): + return stableIdValue + case let .oneFromManySelector(stableIdValue, _, _, _, _, _): + return stableIdValue + case let .action(stableIdValue, _, _, _, _): + return stableIdValue + case let .searchInput(stableIdValue, _, _, _, _): + return stableIdValue + } + } + + public static func <(lhs: SGItemListUIEntry, rhs: SGItemListUIEntry) -> Bool { + return lhs.stableId < rhs.stableId + } + + public static func ==(lhs: SGItemListUIEntry, rhs: SGItemListUIEntry) -> Bool { + switch (lhs, rhs) { + case let (.header(id1, section1, text1, badge1), .header(id2, section2, text2, badge2)): + return id1 == id2 && section1 == section2 && text1 == text2 && badge1 == badge2 + + case let (.toggle(id1, section1, settingName1, value1, text1, enabled1), .toggle(id2, section2, settingName2, value2, text2, enabled2)): + return id1 == id2 && section1 == section2 && settingName1 == settingName2 && value1 == value2 && text1 == text2 && enabled1 == enabled2 + + case let (.notice(id1, section1, text1), .notice(id2, section2, text2)): + return id1 == id2 && section1 == section2 && text1 == text2 + + case let (.percentageSlider(id1, section1, settingName1, value1), .percentageSlider(id2, section2, settingName2, value2)): + return id1 == id2 && section1 == section2 && value1 == value2 && settingName1 == settingName2 + + case let (.disclosure(id1, section1, link1, text1), .disclosure(id2, section2, link2, text2)): + return id1 == id2 && section1 == section2 && link1 == link2 && text1 == text2 + + case let (.peerColorDisclosurePreview(id1, section1, name1, currentColor1), .peerColorDisclosurePreview(id2, section2, name2, currentColor2)): + return id1 == id2 && section1 == section2 && name1 == name2 && currentColor1 == currentColor2 + + case let (.oneFromManySelector(id1, section1, settingName1, text1, value1, enabled1), .oneFromManySelector(id2, section2, settingName2, text2, value2, enabled2)): + return id1 == id2 && section1 == section2 && settingName1 == settingName2 && text1 == text2 && value1 == value2 && enabled1 == enabled2 + case let (.action(id1, section1, actionType1, text1, kind1), .action(id2, section2, actionType2, text2, kind2)): + return id1 == id2 && section1 == section2 && actionType1 == actionType2 && text1 == text2 && kind1 == kind2 + + case let (.searchInput(id1, lhsValue1, lhsValue2, lhsValue3, lhsValue4), .searchInput(id2, rhsValue1, rhsValue2, rhsValue3, rhsValue4)): + return id1 == id2 && lhsValue1 == rhsValue1 && lhsValue2 == rhsValue2 && lhsValue3 == rhsValue3 && lhsValue4 == rhsValue4 + + default: + return false + } + } + + + public func item(presentationData: ItemListPresentationData, arguments: Any) -> ListViewItem { + let arguments = arguments as! SGItemListArguments + switch self { + case let .header(_, _, string, badge): + return ItemListSectionHeaderItem(presentationData: presentationData, text: string, badge: badge, sectionId: self.section) + + case let .toggle(_, _, setting, value, text, enabled): + return ItemListSwitchItem(presentationData: presentationData, systemStyle: .glass, title: text, value: value, enabled: enabled, maximumNumberOfLines: 0, sectionId: self.section, style: .blocks, updated: { value in + arguments.setBoolValue(setting, value) + }) + case let .notice(_, _, string): + return ItemListTextItem(presentationData: presentationData, text: .markdown(string), sectionId: self.section) + case let .disclosure(_, _, link, text): + return ItemListDisclosureItem(presentationData: presentationData, systemStyle: .glass, title: text, label: "", sectionId: self.section, style: .blocks) { + arguments.openDisclosureLink(link) + } + case let .percentageSlider(_, _, setting, value): + return SliderPercentageItem( + theme: presentationData.theme, + strings: presentationData.strings, + value: value, + sectionId: self.section, + systemStyle: .glass, + updated: { value in + arguments.updateSliderValue(setting, value) + } + ) + + case let .peerColorDisclosurePreview(_, _, name, color): + return ItemListDisclosureItem(presentationData: presentationData, systemStyle: .glass, title: " ", enabled: false, label: name, labelStyle: .semitransparentBadge(color), sectionId: self.section, style: .blocks, disclosureStyle: .none, action: { + }) + + case let .oneFromManySelector(_, _, settingName, text, value, enabled): + return ItemListDisclosureItem(presentationData: presentationData, systemStyle: .glass, title: text, enabled: enabled, label: value, sectionId: self.section, style: .blocks, action: { + UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) // Closing search keyboard if active + arguments.setOneFromManyValue(settingName) + }) + case let .action(_, _, actionType, text, kind): + return ItemListActionItem(presentationData: presentationData, systemStyle: .glass, title: text, kind: kind, alignment: .natural, sectionId: self.section, style: .blocks, action: { + UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) // Closing search keyboard if active + arguments.action(actionType) + }) + case let .searchInput(_, _, title, text, placeholder): + return ItemListSingleLineInputItem(presentationData: presentationData, systemStyle: .glass, title: title, text: text, placeholder: placeholder, returnKeyType: .done, spacing: 3.0, clearType: .always, selectAllOnFocus: true, secondaryStyle: true, sectionId: self.section, textUpdated: { input in arguments.searchInput(input) }, action: { + UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) + }) + } + } +} + + +public func filterSGItemListUIEntrires( + entries: [SGItemListUIEntry], + by searchQuery: String? +) -> [SGItemListUIEntry] { + + guard let query = searchQuery?.lowercased(), !query.isEmpty else { + return entries + } + + var sectionIdsForEntireIncludion: Set = [] + var sectionIdsWithMatches: Set = [] + var filteredEntries: [SGItemListUIEntry] = [] + + func entryMatches(_ entry: SGItemListUIEntry, query: String) -> Bool { + switch entry { + case .header(_, _, let text, _): + return text.lowercased().contains(query) + case .toggle(_, _, _, _, let text, _): + return text.lowercased().contains(query) + case .notice(_, _, let text): + return text.lowercased().contains(query) + case .percentageSlider: + return false // Assuming percentage sliders don't have searchable text + case .oneFromManySelector(_, _, _, let text, let value, _): + return text.lowercased().contains(query) || value.lowercased().contains(query) + case .disclosure(_, _, _, let text): + return text.lowercased().contains(query) + case .peerColorDisclosurePreview: + return false // Never indexed during search + case .action(_, _, _, let text, _): + return text.lowercased().contains(query) + case .searchInput: + return true // Never hiding search input + } + } + + // First pass: identify sections with matches + for entry in entries { + if entryMatches(entry, query: query) { + switch entry { + case .searchInput: + continue + default: + sectionIdsWithMatches.insert(entry.section) + } + } + } + + // Second pass: keep matching entries and headers of sections with matches + for (index, entry) in entries.enumerated() { + switch entry { + case .header: + if entryMatches(entry, query: query) { + // Will show all entries for the same section + sectionIdsForEntireIncludion.insert(entry.section) + if !filteredEntries.contains(entry) { + filteredEntries.append(entry) + } + } + // Or show header if something from the section already matched + if sectionIdsWithMatches.contains(entry.section) { + if !filteredEntries.contains(entry) { + filteredEntries.append(entry) + } + } + default: + if entryMatches(entry, query: query) { + if case .notice = entry { + // add previous entry to if it's not another notice and if it's not already here + // possibly targeting related toggle / setting if we've matched it's description (notice) in search + if index > 0 { + let previousEntry = entries[index - 1] + if case .notice = previousEntry {} else { + if !filteredEntries.contains(previousEntry) { + filteredEntries.append(previousEntry) + } + } + } + if !filteredEntries.contains(entry) { + filteredEntries.append(entry) + } + } else { + if !filteredEntries.contains(entry) { + filteredEntries.append(entry) + } + // add next entry if it's notice + // possibly targeting description (notice) for the currently search-matched toggle/setting + if index < entries.count - 1 { + let nextEntry = entries[index + 1] + if case .notice = nextEntry { + if !filteredEntries.contains(nextEntry) { + filteredEntries.append(nextEntry) + } + } + } + } + } else if sectionIdsForEntireIncludion.contains(entry.section) { + if !filteredEntries.contains(entry) { + filteredEntries.append(entry) + } + } + } + } + + return filteredEntries +} diff --git a/Swiftgram/SGItemListUI/Sources/SliderPercentageItem.swift b/Swiftgram/SGItemListUI/Sources/SliderPercentageItem.swift new file mode 100644 index 00000000..04c6388a --- /dev/null +++ b/Swiftgram/SGItemListUI/Sources/SliderPercentageItem.swift @@ -0,0 +1,355 @@ +import Foundation +import UIKit +import Display +import AsyncDisplayKit +import SwiftSignalKit +import TelegramCore +import TelegramPresentationData +import LegacyComponents +import ItemListUI +import PresentationDataUtils +import AppBundle + +public class SliderPercentageItem: ListViewItem, ItemListItem { + let theme: PresentationTheme + let strings: PresentationStrings + let value: Int32 + let systemStyle: ItemListSystemStyle + public let sectionId: ItemListSectionId + let updated: (Int32) -> Void + + public init(theme: PresentationTheme, strings: PresentationStrings, value: Int32, sectionId: ItemListSectionId, systemStyle: ItemListSystemStyle = .glass, updated: @escaping (Int32) -> Void) { + self.theme = theme + self.strings = strings + self.value = value + self.sectionId = sectionId + self.systemStyle = systemStyle + self.updated = updated + } + + public func nodeConfiguredForParams(async: @escaping (@escaping () -> Void) -> Void, params: ListViewItemLayoutParams, synchronousLoads: Bool, previousItem: ListViewItem?, nextItem: ListViewItem?, completion: @escaping (ListViewItemNode, @escaping () -> (Signal?, (ListViewItemApply) -> Void)) -> Void) { + async { + let node = SliderPercentageItemNode() + let (layout, apply) = node.asyncLayout()(self, params, itemListNeighbors(item: self, topItem: previousItem as? ItemListItem, bottomItem: nextItem as? ItemListItem)) + + node.contentSize = layout.contentSize + node.insets = layout.insets + + Queue.mainQueue().async { + completion(node, { + return (nil, { _ in apply() }) + }) + } + } + } + + public func updateNode(async: @escaping (@escaping () -> Void) -> Void, node: @escaping () -> ListViewItemNode, params: ListViewItemLayoutParams, previousItem: ListViewItem?, nextItem: ListViewItem?, animation: ListViewItemUpdateAnimation, completion: @escaping (ListViewItemNodeLayout, @escaping (ListViewItemApply) -> Void) -> Void) { + Queue.mainQueue().async { + if let nodeValue = node() as? SliderPercentageItemNode { + let makeLayout = nodeValue.asyncLayout() + + async { + let (layout, apply) = makeLayout(self, params, itemListNeighbors(item: self, topItem: previousItem as? ItemListItem, bottomItem: nextItem as? ItemListItem)) + Queue.mainQueue().async { + completion(layout, { _ in + apply() + }) + } + } + } + } + } +} + +private func rescalePercentageValueToSlider(_ value: CGFloat) -> CGFloat { + return max(0.0, min(1.0, value)) +} + +private func rescaleSliderValueToPercentageValue(_ value: CGFloat) -> CGFloat { + return max(0.0, min(1.0, value)) +} + +class SliderPercentageItemNode: ListViewItemNode { + private let backgroundNode: ASDisplayNode + private let topStripeNode: ASDisplayNode + private let bottomStripeNode: ASDisplayNode + private let maskNode: ASImageNode + + private var sliderView: TGPhotoEditorSliderView? + private let leftTextNode: ImmediateTextNode + private let rightTextNode: ImmediateTextNode + private let centerTextNode: ImmediateTextNode + private let centerMeasureTextNode: ImmediateTextNode + + private let batteryImage: UIImage? + private let batteryBackgroundNode: ASImageNode + private let batteryForegroundNode: ASImageNode + + private var item: SliderPercentageItem? + private var layoutParams: ListViewItemLayoutParams? + + // MARK: Swiftgram + private let activateArea: AccessibilityAreaNode + + init() { + self.backgroundNode = ASDisplayNode() + self.backgroundNode.isLayerBacked = true + + self.topStripeNode = ASDisplayNode() + self.topStripeNode.isLayerBacked = true + + self.bottomStripeNode = ASDisplayNode() + self.bottomStripeNode.isLayerBacked = true + + self.maskNode = ASImageNode() + + self.leftTextNode = ImmediateTextNode() + self.rightTextNode = ImmediateTextNode() + self.centerTextNode = ImmediateTextNode() + self.centerMeasureTextNode = ImmediateTextNode() + + self.batteryImage = nil //UIImage(bundleImageName: "Settings/UsageBatteryFrame") + self.batteryBackgroundNode = ASImageNode() + self.batteryForegroundNode = ASImageNode() + + // MARK: Swiftgram + self.activateArea = AccessibilityAreaNode() + + super.init(layerBacked: false) + + self.addSubnode(self.leftTextNode) + self.addSubnode(self.rightTextNode) + self.addSubnode(self.centerTextNode) + self.addSubnode(self.batteryBackgroundNode) + self.addSubnode(self.batteryForegroundNode) + self.addSubnode(self.activateArea) + + // MARK: Swiftgram + self.activateArea.increment = { [weak self] in + if let self { + self.sliderView?.increase(by: 0.10) + } + } + + self.activateArea.decrement = { [weak self] in + if let self { + self.sliderView?.decrease(by: 0.10) + } + } + } + + override func didLoad() { + super.didLoad() + + let sliderView = TGPhotoEditorSliderView() + sliderView.enableEdgeTap = true + sliderView.enablePanHandling = true + sliderView.trackCornerRadius = 1.0 + sliderView.lineSize = 4.0 + sliderView.minimumValue = 0.0 + sliderView.startValue = 0.0 + sliderView.maximumValue = 1.0 + sliderView.disablesInteractiveTransitionGestureRecognizer = true + sliderView.displayEdges = true + if let item = self.item, let params = self.layoutParams { + sliderView.value = rescalePercentageValueToSlider(CGFloat(item.value) / 100.0) + sliderView.backgroundColor = item.theme.list.itemBlocksBackgroundColor + sliderView.backColor = item.theme.list.itemSwitchColors.frameColor + sliderView.trackColor = item.theme.list.itemAccentColor + sliderView.knobImage = PresentationResourcesItemList.knobImage(item.theme) + + sliderView.frame = CGRect(origin: CGPoint(x: params.leftInset + 18.0, y: 36.0), size: CGSize(width: params.width - params.leftInset - params.rightInset - 18.0 * 2.0, height: 44.0)) + } + self.view.addSubview(sliderView) + sliderView.addTarget(self, action: #selector(self.sliderValueChanged), for: .valueChanged) + self.sliderView = sliderView + } + + func asyncLayout() -> (_ item: SliderPercentageItem, _ params: ListViewItemLayoutParams, _ neighbors: ItemListNeighbors) -> (ListViewItemNodeLayout, () -> Void) { + let currentItem = self.item + + return { item, params, neighbors in + var themeUpdated = false + if currentItem?.theme !== item.theme { + themeUpdated = true + } + + let contentSize: CGSize + let insets: UIEdgeInsets + let separatorHeight = UIScreenPixel + + contentSize = CGSize(width: params.width, height: 88.0) + insets = itemListNeighborsGroupedInsets(neighbors, params) + + let layout = ListViewItemNodeLayout(contentSize: contentSize, insets: insets) + let layoutSize = layout.size + + return (layout, { [weak self] in + if let strongSelf = self { + strongSelf.item = item + strongSelf.layoutParams = params + + strongSelf.backgroundNode.backgroundColor = item.theme.list.itemBlocksBackgroundColor + strongSelf.topStripeNode.backgroundColor = item.theme.list.itemBlocksSeparatorColor + strongSelf.bottomStripeNode.backgroundColor = item.theme.list.itemBlocksSeparatorColor + + if strongSelf.backgroundNode.supernode == nil { + strongSelf.insertSubnode(strongSelf.backgroundNode, at: 0) + } + if strongSelf.topStripeNode.supernode == nil { + strongSelf.insertSubnode(strongSelf.topStripeNode, at: 1) + } + if strongSelf.bottomStripeNode.supernode == nil { + strongSelf.insertSubnode(strongSelf.bottomStripeNode, at: 2) + } + if strongSelf.maskNode.supernode == nil { + strongSelf.insertSubnode(strongSelf.maskNode, at: 3) + } + + let hasCorners = itemListHasRoundedBlockLayout(params) + var hasTopCorners = false + var hasBottomCorners = false + switch neighbors.top { + case .sameSection(false): + strongSelf.topStripeNode.isHidden = true + default: + hasTopCorners = true + strongSelf.topStripeNode.isHidden = hasCorners + } + let bottomStripeInset: CGFloat + let bottomStripeOffset: CGFloat + switch neighbors.bottom { + case .sameSection(false): + bottomStripeInset = params.leftInset + 16.0 + bottomStripeOffset = -separatorHeight + strongSelf.bottomStripeNode.isHidden = false + default: + bottomStripeInset = 0.0 + bottomStripeOffset = 0.0 + hasBottomCorners = true + strongSelf.bottomStripeNode.isHidden = hasCorners + } + + strongSelf.maskNode.image = hasCorners ? PresentationResourcesItemList.cornersImage(item.theme, top: hasTopCorners, bottom: hasBottomCorners, glass: item.systemStyle == .glass) : nil + + strongSelf.backgroundNode.frame = CGRect(origin: CGPoint(x: 0.0, y: -min(insets.top, separatorHeight)), size: CGSize(width: params.width, height: contentSize.height + min(insets.top, separatorHeight) + min(insets.bottom, separatorHeight))) + strongSelf.maskNode.frame = strongSelf.backgroundNode.frame.insetBy(dx: params.leftInset, dy: 0.0) + strongSelf.topStripeNode.frame = CGRect(origin: CGPoint(x: 0.0, y: -min(insets.top, separatorHeight)), size: CGSize(width: layoutSize.width, height: separatorHeight)) + strongSelf.bottomStripeNode.frame = CGRect(origin: CGPoint(x: bottomStripeInset, y: contentSize.height + bottomStripeOffset), size: CGSize(width: layoutSize.width - bottomStripeInset, height: separatorHeight)) + + strongSelf.leftTextNode.attributedText = NSAttributedString(string: "0%", font: Font.regular(13.0), textColor: item.theme.list.itemSecondaryTextColor) + strongSelf.rightTextNode.attributedText = NSAttributedString(string: "100%", font: Font.regular(13.0), textColor: item.theme.list.itemSecondaryTextColor) + + let centralText: String = "\(item.value)%" + let centralMeasureText: String = centralText + strongSelf.batteryBackgroundNode.isHidden = true + strongSelf.batteryForegroundNode.isHidden = strongSelf.batteryBackgroundNode.isHidden + strongSelf.centerTextNode.attributedText = NSAttributedString(string: centralText, font: Font.regular(16.0), textColor: item.theme.list.itemPrimaryTextColor) + strongSelf.centerMeasureTextNode.attributedText = NSAttributedString(string: centralMeasureText, font: Font.regular(16.0), textColor: item.theme.list.itemPrimaryTextColor) + + strongSelf.leftTextNode.isAccessibilityElement = true + strongSelf.leftTextNode.accessibilityLabel = "Minimum: \(Int32(rescaleSliderValueToPercentageValue(strongSelf.sliderView?.minimumValue ?? 0.0) * 100.0))%" + strongSelf.rightTextNode.isAccessibilityElement = true + strongSelf.rightTextNode.accessibilityLabel = "Maximum: \(Int32(rescaleSliderValueToPercentageValue(strongSelf.sliderView?.maximumValue ?? 1.0) * 100.0))%" + + let leftTextSize = strongSelf.leftTextNode.updateLayout(CGSize(width: 100.0, height: 100.0)) + let rightTextSize = strongSelf.rightTextNode.updateLayout(CGSize(width: 100.0, height: 100.0)) + let centerTextSize = strongSelf.centerTextNode.updateLayout(CGSize(width: 200.0, height: 100.0)) + let centerMeasureTextSize = strongSelf.centerMeasureTextNode.updateLayout(CGSize(width: 200.0, height: 100.0)) + + let sideInset: CGFloat = 18.0 + + strongSelf.leftTextNode.frame = CGRect(origin: CGPoint(x: params.leftInset + sideInset, y: 15.0), size: leftTextSize) + strongSelf.rightTextNode.frame = CGRect(origin: CGPoint(x: params.width - params.leftInset - sideInset - rightTextSize.width, y: 15.0), size: rightTextSize) + + var centerFrame = CGRect(origin: CGPoint(x: floor((params.width - centerMeasureTextSize.width) / 2.0), y: 11.0), size: centerTextSize) + if !strongSelf.batteryBackgroundNode.isHidden { + centerFrame.origin.x -= 12.0 + } + strongSelf.centerTextNode.frame = centerFrame + + if let frameImage = strongSelf.batteryImage { + strongSelf.batteryBackgroundNode.image = generateImage(frameImage.size, rotatedContext: { size, context in + UIGraphicsPushContext(context) + + context.clear(CGRect(origin: CGPoint(), size: size)) + + if let image = generateTintedImage(image: frameImage, color: item.theme.list.itemPrimaryTextColor.withMultipliedAlpha(0.9)) { + image.draw(in: CGRect(origin: CGPoint(), size: size)) + + let contentRect = CGRect(origin: CGPoint(x: 3.0, y: (size.height - 9.0) * 0.5), size: CGSize(width: 20.8, height: 9.0)) + context.addPath(UIBezierPath(roundedRect: contentRect, cornerRadius: 2.0).cgPath) + context.clip() + } + + UIGraphicsPopContext() + }) + strongSelf.batteryForegroundNode.image = generateImage(frameImage.size, rotatedContext: { size, context in + UIGraphicsPushContext(context) + + context.clear(CGRect(origin: CGPoint(), size: size)) + + let contentRect = CGRect(origin: CGPoint(x: 3.0, y: (size.height - 9.0) * 0.5), size: CGSize(width: 20.8, height: 9.0)) + context.addPath(UIBezierPath(roundedRect: contentRect, cornerRadius: 2.0).cgPath) + context.clip() + + context.setFillColor(UIColor.white.cgColor) + context.addPath(UIBezierPath(roundedRect: CGRect(origin: contentRect.origin, size: CGSize(width: contentRect.width * CGFloat(item.value) / 100.0, height: contentRect.height)), cornerRadius: 1.0).cgPath) + context.fillPath() + + UIGraphicsPopContext() + }) + + let batteryColor: UIColor + if item.value <= 20 { + batteryColor = UIColor(rgb: 0xFF3B30) + } else { + batteryColor = item.theme.list.itemSwitchColors.positiveColor + } + + if strongSelf.batteryForegroundNode.layer.layerTintColor == nil { + strongSelf.batteryForegroundNode.layer.layerTintColor = batteryColor.cgColor + } else { + ContainedViewLayoutTransition.animated(duration: 0.2, curve: .easeInOut).updateTintColor(layer: strongSelf.batteryForegroundNode.layer, color: batteryColor) + } + + strongSelf.batteryBackgroundNode.frame = CGRect(origin: CGPoint(x: centerFrame.minX + centerMeasureTextSize.width + 4.0, y: floor(centerFrame.midY - frameImage.size.height * 0.5)), size: frameImage.size) + strongSelf.batteryForegroundNode.frame = strongSelf.batteryBackgroundNode.frame + } + + if let sliderView = strongSelf.sliderView { + if themeUpdated { + sliderView.backgroundColor = item.theme.list.itemBlocksBackgroundColor + sliderView.backColor = item.theme.list.itemSecondaryTextColor + sliderView.trackColor = item.theme.list.itemAccentColor.withAlphaComponent(0.45) + sliderView.knobImage = PresentationResourcesItemList.knobImage(item.theme) + } + + sliderView.frame = CGRect(origin: CGPoint(x: params.leftInset + 18.0, y: 36.0), size: CGSize(width: params.width - params.leftInset - params.rightInset - 18.0 * 2.0, height: 44.0)) + } + + strongSelf.activateArea.accessibilityLabel = "Slider" + strongSelf.activateArea.accessibilityValue = centralMeasureText + strongSelf.activateArea.accessibilityTraits = .adjustable + strongSelf.activateArea.frame = CGRect(origin: CGPoint(x: params.leftInset, y: 0.0), size: CGSize(width: params.width - params.leftInset - params.rightInset, height: layout.contentSize.height)) + } + }) + } + } + + override func animateInsertion(_ currentTimestamp: Double, duration: Double, options: ListViewItemAnimationOptions) { + self.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.4) + } + + override func animateRemoved(_ currentTimestamp: Double, duration: Double) { + self.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.15, removeOnCompletion: false) + } + + @objc func sliderValueChanged() { + guard let sliderView = self.sliderView else { + return + } + self.item?.updated(Int32(rescaleSliderValueToPercentageValue(sliderView.value) * 100.0)) + } +} + diff --git a/Swiftgram/SGKeychainBackupManager/BUILD b/Swiftgram/SGKeychainBackupManager/BUILD new file mode 100644 index 00000000..cd1a5d12 --- /dev/null +++ b/Swiftgram/SGKeychainBackupManager/BUILD @@ -0,0 +1,17 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGKeychainBackupManager", + module_name = "SGKeychainBackupManager", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGKeychainBackupManager/Sources/SGKeychainBackupManager.swift b/Swiftgram/SGKeychainBackupManager/Sources/SGKeychainBackupManager.swift new file mode 100644 index 00000000..2de2ebd5 --- /dev/null +++ b/Swiftgram/SGKeychainBackupManager/Sources/SGKeychainBackupManager.swift @@ -0,0 +1,131 @@ +import Foundation +import Security + +public enum KeychainError: Error { + case duplicateEntry + case unknown(OSStatus) + case itemNotFound + case invalidItemFormat +} + +public class KeychainBackupManager { + public static let shared = KeychainBackupManager() + private let service = "\(Bundle.main.bundleIdentifier!).sessionsbackup" + + private init() {} + + // MARK: - Save Credentials + public func saveSession(id: String, _ session: Data) throws { + // Create query dictionary + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: id, + kSecValueData as String: session, + kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlocked + ] + + // Add to keychain + let status = SecItemAdd(query as CFDictionary, nil) + + if status == errSecDuplicateItem { + // Item already exists, update it + let updateQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: id + ] + + let attributesToUpdate: [String: Any] = [ + kSecValueData as String: session + ] + + let updateStatus = SecItemUpdate(updateQuery as CFDictionary, + attributesToUpdate as CFDictionary) + + if updateStatus != errSecSuccess { + throw KeychainError.unknown(updateStatus) + } + } else if status != errSecSuccess { + throw KeychainError.unknown(status) + } + } + + // MARK: - Retrieve Credentials + public func retrieveSession(for id: String) throws -> Data { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: id, + kSecReturnData as String: true + ] + + var result: AnyObject? + let status = SecItemCopyMatching(query as CFDictionary, &result) + + guard status == errSecSuccess, let sessionData = result as? Data else { + throw KeychainError.itemNotFound + } + + return sessionData + } + + // MARK: - Delete Credentials + public func deleteSession(for id: String) throws { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: id + ] + + let status = SecItemDelete(query as CFDictionary) + + if status != errSecSuccess && status != errSecItemNotFound { + throw KeychainError.unknown(status) + } + } + + // MARK: - Retrieve All Accounts + public func getAllSessons() throws -> [Data] { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecReturnData as String: true, + kSecMatchLimit as String: kSecMatchLimitAll + ] + + var result: AnyObject? + let status = SecItemCopyMatching(query as CFDictionary, &result) + + if status == errSecItemNotFound { + return [] + } + + guard status == errSecSuccess, + let credentialsDataArray = result as? [Data] else { + throw KeychainError.unknown(status) + } + + return credentialsDataArray + } + + // MARK: - Delete All Sessions + public func deleteAllSessions() throws { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service + ] + + let status = SecItemDelete(query as CFDictionary) + + // If no items were found, that's fine - just return + if status == errSecItemNotFound { + return + } + + // For any other error, throw + if status != errSecSuccess { + throw KeychainError.unknown(status) + } + } +} diff --git a/Swiftgram/SGLogging/BUILD b/Swiftgram/SGLogging/BUILD new file mode 100644 index 00000000..49839697 --- /dev/null +++ b/Swiftgram/SGLogging/BUILD @@ -0,0 +1,19 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGLogging", + module_name = "SGLogging", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + "//submodules/ManagedFile:ManagedFile" + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGLogging/Sources/SGLogger.swift b/Swiftgram/SGLogging/Sources/SGLogger.swift new file mode 100644 index 00000000..a3c8a09b --- /dev/null +++ b/Swiftgram/SGLogging/Sources/SGLogger.swift @@ -0,0 +1,183 @@ +import Foundation +import SwiftSignalKit +import ManagedFile + +private let queue = DispatchQueue(label: "app.swiftgram.ios.trace", qos: .utility) + +private var sharedLogger: SGLogger? + +private let binaryEventMarker: UInt64 = 0xcadebabef00dcafe + +private func rootPathForBasePath(_ appGroupPath: String) -> String { + return appGroupPath + "/telegram-data" +} + +public class SGLogger { + public let queue = Queue(name: "app.swiftgram.ios.log", qos: .utility) + private let maxLength: Int = 2 * 1024 * 1024 + private let maxShortLength: Int = 1 * 1024 * 1024 + private let maxFiles: Int = 20 + + public let rootPath: String + public let basePath: String + private var file: (ManagedFile, Int)? + private var shortFile: (ManagedFile, Int)? + + public static let sgLogsPath = "/logs/app-logs-sg" + + public var logToFile: Bool = true + public var logToConsole: Bool = true + public var redactSensitiveData: Bool = true + + public static func setSharedLogger(_ logger: SGLogger) { + sharedLogger = logger + } + + public static var shared: SGLogger { + if let sharedLogger = sharedLogger { + return sharedLogger + } else { + print("SGLogger setup...") + guard let baseAppBundleId = Bundle.main.bundleIdentifier else { + print("Can't setup logger (1)!") + return SGLogger(rootPath: "", basePath: "") + } + let appGroupName = "group.\(baseAppBundleId)" + let maybeAppGroupUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupName) + guard let appGroupUrl = maybeAppGroupUrl else { + print("Can't setup logger (2)!") + return SGLogger(rootPath: "", basePath: "") + } + let newRootPath = rootPathForBasePath(appGroupUrl.path) + let newLogsPath = newRootPath + sgLogsPath + let _ = try? FileManager.default.createDirectory(atPath: newLogsPath, withIntermediateDirectories: true, attributes: nil) + self.setSharedLogger(SGLogger(rootPath: newRootPath, basePath: newLogsPath)) + if let sharedLogger = sharedLogger { + return sharedLogger + } else { + print("Can't setup logger (3)!") + return SGLogger(rootPath: "", basePath: "") + } + } + } + + public init(rootPath: String, basePath: String) { + self.rootPath = rootPath + self.basePath = basePath + } + + public func log(_ tag: String, _ what: @autoclosure () -> String) { + if !self.logToFile && !self.logToConsole { + return + } + + let string = what() + + var rawTime = time_t() + time(&rawTime) + var timeinfo = tm() + localtime_r(&rawTime, &timeinfo) + + var curTime = timeval() + gettimeofday(&curTime, nil) + let milliseconds = curTime.tv_usec / 1000 + + var consoleContent: String? + if self.logToConsole { + let content = String(format: "[SG.%@] %d-%d-%d %02d:%02d:%02d.%03d %@", arguments: [tag, Int(timeinfo.tm_year) + 1900, Int(timeinfo.tm_mon + 1), Int(timeinfo.tm_mday), Int(timeinfo.tm_hour), Int(timeinfo.tm_min), Int(timeinfo.tm_sec), Int(milliseconds), string]) + consoleContent = content + print(content) + } + + if self.logToFile { + self.queue.async { + let content: String + if let consoleContent = consoleContent { + content = consoleContent + } else { + content = String(format: "[SG.%@] %d-%d-%d %02d:%02d:%02d.%03d %@", arguments: [tag, Int(timeinfo.tm_year) + 1900, Int(timeinfo.tm_mon + 1), Int(timeinfo.tm_mday), Int(timeinfo.tm_hour), Int(timeinfo.tm_min), Int(timeinfo.tm_sec), Int(milliseconds), string]) + } + + var currentFile: ManagedFile? + var openNew = false + if let (file, length) = self.file { + if length >= self.maxLength { + self.file = nil + openNew = true + } else { + currentFile = file + } + } else { + openNew = true + } + if openNew { + let _ = try? FileManager.default.createDirectory(atPath: self.basePath, withIntermediateDirectories: true, attributes: nil) + + var createNew = false + if let files = try? FileManager.default.contentsOfDirectory(at: URL(fileURLWithPath: self.basePath), includingPropertiesForKeys: [URLResourceKey.creationDateKey], options: []) { + var minCreationDate: (Date, URL)? + var maxCreationDate: (Date, URL)? + var count = 0 + for url in files { + if url.lastPathComponent.hasPrefix("log-") { + if let values = try? url.resourceValues(forKeys: Set([URLResourceKey.creationDateKey])), let creationDate = values.creationDate { + count += 1 + if minCreationDate == nil || minCreationDate!.0 > creationDate { + minCreationDate = (creationDate, url) + } + if maxCreationDate == nil || maxCreationDate!.0 < creationDate { + maxCreationDate = (creationDate, url) + } + } + } + } + if let (_, url) = minCreationDate, count >= self.maxFiles { + let _ = try? FileManager.default.removeItem(at: url) + } + if let (_, url) = maxCreationDate { + var value = stat() + if stat(url.path, &value) == 0 && Int(value.st_size) < self.maxLength { + if let file = ManagedFile(queue: self.queue, path: url.path, mode: .append) { + self.file = (file, Int(value.st_size)) + currentFile = file + } + } else { + createNew = true + } + } else { + createNew = true + } + } + + if createNew { + let fileName = String(format: "log-%d-%d-%d_%02d-%02d-%02d.%03d.txt", arguments: [Int(timeinfo.tm_year) + 1900, Int(timeinfo.tm_mon + 1), Int(timeinfo.tm_mday), Int(timeinfo.tm_hour), Int(timeinfo.tm_min), Int(timeinfo.tm_sec), Int(milliseconds)]) + + let path = self.basePath + "/" + fileName + + if let file = ManagedFile(queue: self.queue, path: path, mode: .append) { + self.file = (file, 0) + currentFile = file + } + } + } + + if let currentFile = currentFile { + if let data = content.data(using: .utf8) { + data.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + + let _ = currentFile.write(bytes, count: data.count) + } + var newline: UInt8 = 0x0a + let _ = currentFile.write(&newline, count: 1) + if let file = self.file { + self.file = (file.0, file.1 + data.count + 1) + } else { + assertionFailure() + } + } + } + } + } + } +} diff --git a/Swiftgram/SGLogging/Sources/Utils.swift b/Swiftgram/SGLogging/Sources/Utils.swift new file mode 100644 index 00000000..68381110 --- /dev/null +++ b/Swiftgram/SGLogging/Sources/Utils.swift @@ -0,0 +1,6 @@ +//import Foundation +// +//public func extractNameFromPath(_ path: String) -> String { +// let fileName = URL(fileURLWithPath: path).lastPathComponent +// return String(fileName.prefix(upTo: fileName.lastIndex { $0 == "." } ?? fileName.endIndex)) +//} diff --git a/Swiftgram/SGLoggingComposer/BUILD b/Swiftgram/SGLoggingComposer/BUILD new file mode 100644 index 00000000..bce950b1 --- /dev/null +++ b/Swiftgram/SGLoggingComposer/BUILD @@ -0,0 +1,19 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGLoggingComposer", + module_name = "SGLoggingComposer", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//Swiftgram/SGLogging:SGLogging", + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGLoggingComposer/Sources/SGLoggingComposer.swift b/Swiftgram/SGLoggingComposer/Sources/SGLoggingComposer.swift new file mode 100644 index 00000000..726f014d --- /dev/null +++ b/Swiftgram/SGLoggingComposer/Sources/SGLoggingComposer.swift @@ -0,0 +1,59 @@ +import Foundation +import SGLogging +import SwiftSignalKit + + +extension SGLogger { + public func collectLogs(prefix: String? = nil) -> Signal<[(String, String)], NoError> { + return Signal { subscriber in + self.queue.async { + let logsPath: String + if let prefix = prefix { + logsPath = self.rootPath + prefix + } else { + logsPath = self.basePath + } + + var result: [(Date, String, String)] = [] + if let files = try? FileManager.default.contentsOfDirectory(at: URL(fileURLWithPath: logsPath), includingPropertiesForKeys: [URLResourceKey.creationDateKey], options: []) { + for url in files { + if url.lastPathComponent.hasPrefix("log-") { + if let creationDate = (try? url.resourceValues(forKeys: Set([.creationDateKey])))?.creationDate { + result.append((creationDate, url.lastPathComponent, url.path)) + } + } + } + } + result.sort(by: { $0.0 < $1.0 }) + subscriber.putNext(result.map { ($0.1, $0.2) }) + subscriber.putCompletion() + } + + return EmptyDisposable + } + } + + public func collectLogs(basePath: String) -> Signal<[(String, String)], NoError> { + return Signal { subscriber in + self.queue.async { + let logsPath: String = basePath + + var result: [(Date, String, String)] = [] + if let files = try? FileManager.default.contentsOfDirectory(at: URL(fileURLWithPath: logsPath), includingPropertiesForKeys: [URLResourceKey.creationDateKey], options: []) { + for url in files { + if url.lastPathComponent.hasPrefix("log-") { + if let creationDate = (try? url.resourceValues(forKeys: Set([.creationDateKey])))?.creationDate { + result.append((creationDate, url.lastPathComponent, url.path)) + } + } + } + } + result.sort(by: { $0.0 < $1.0 }) + subscriber.putNext(result.map { ($0.1, $0.2) }) + subscriber.putCompletion() + } + + return EmptyDisposable + } + } +} diff --git a/Swiftgram/SGNY/BUILD b/Swiftgram/SGNY/BUILD new file mode 100644 index 00000000..3228a543 --- /dev/null +++ b/Swiftgram/SGNY/BUILD @@ -0,0 +1,15 @@ +filegroup( + name = "SGNY", + srcs = glob([ + "Sources/**/*.swift", + ]), + visibility = [ + "//visibility:public", + ], +) + +filegroup( + name = "SGNYAssets", + srcs = glob(["Images.xcassets/**"]), + visibility = ["//visibility:public"], +) \ No newline at end of file diff --git a/Swiftgram/SGNY/Images.xcassets/SGSnowflake.imageset/Contents.json b/Swiftgram/SGNY/Images.xcassets/SGSnowflake.imageset/Contents.json new file mode 100644 index 00000000..3a7a8bfe --- /dev/null +++ b/Swiftgram/SGNY/Images.xcassets/SGSnowflake.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "SGSnowflake.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGNY/Images.xcassets/SGSnowflake.imageset/SGSnowflake.png b/Swiftgram/SGNY/Images.xcassets/SGSnowflake.imageset/SGSnowflake.png new file mode 100644 index 00000000..f781e571 Binary files /dev/null and b/Swiftgram/SGNY/Images.xcassets/SGSnowflake.imageset/SGSnowflake.png differ diff --git a/Swiftgram/SGNY/Sources/SGNY.swift b/Swiftgram/SGNY/Sources/SGNY.swift new file mode 100644 index 00000000..a15481a4 --- /dev/null +++ b/Swiftgram/SGNY/Sources/SGNY.swift @@ -0,0 +1,97 @@ +import Foundation +import UIKit +import AsyncDisplayKit +import Display +import SGSimpleSettings + + +class WallpaperNYNode: ASDisplayNode { + private var emitterLayer: CAEmitterLayer? + + func updateLayout(size: CGSize) { + if self.emitterLayer == nil { + let particlesLayer = CAEmitterLayer() + self.emitterLayer = particlesLayer + + self.layer.addSublayer(particlesLayer) + self.layer.masksToBounds = true + + particlesLayer.backgroundColor = UIColor.clear.cgColor + particlesLayer.emitterShape = .circle + particlesLayer.emitterMode = .surface + particlesLayer.renderMode = .oldestLast + + let cell1 = CAEmitterCell() + switch SGSimpleSettings.shared.nyStyle { + case SGSimpleSettings.NYStyle.lightning.rawValue: + // cell1.contents = generateTintedImage(image: UIImage(bundleImageName: "SwiftgramContextMenu"), color: .white) + if let image = UIImage(bundleImageName: "SwiftgramContextMenu") { + cell1.contents = paintImage(image, to: UIColor.white.cgColor).cgImage + } + cell1.name = "lightning" + cell1.scale = 0.15 + cell1.scaleRange = 0.25 + cell1.birthRate = 10.0 + default: + cell1.contents = UIImage(bundleImageName: "SGSnowflake")?.cgImage + cell1.name = "snow" + cell1.scale = 0.04 + cell1.scaleRange = 0.15 + cell1.birthRate = 10.0 + } + cell1.lifetime = 55.0 + cell1.velocity = 1.0 + cell1.velocityRange = -1.5 + cell1.xAcceleration = 0.33 + cell1.yAcceleration = 1.0 + cell1.emissionRange = .pi + cell1.spin = -28.6 * (.pi / 180.0) + cell1.spinRange = 57.2 * (.pi / 180.0) + cell1.color = UIColor.white.withAlphaComponent(0.58).cgColor +// cell1.alphaRange = -0.2 + if ProcessInfo.processInfo.isLowPowerModeEnabled || UIAccessibility.isReduceMotionEnabled { + cell1.birthRate = cell1.birthRate / 3 + } + particlesLayer.emitterCells = [cell1] + } + + if let emitterLayer = self.emitterLayer { + var emitterWidthK: CGFloat = 1.5 + switch SGSimpleSettings.shared.nyStyle { + case SGSimpleSettings.NYStyle.lightning.rawValue: + emitterWidthK = 1.5 + default: + break + } + emitterLayer.emitterPosition = CGPoint(x: 0.0, y: -size.height / 8.0) + emitterLayer.emitterSize = CGSize(width: size.width * emitterWidthK, height: size.height) + emitterLayer.frame = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height) + } + } +} + + +func paintImage(_ image: UIImage, to: CGColor) -> UIImage { + let rect = CGRect(origin: .zero, size: image.size) + + UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale) + guard let ctx = UIGraphicsGetCurrentContext() else { return image } + + // Flip context + ctx.translateBy(x: 0, y: image.size.height) + ctx.scaleBy(x: 1, y: -1) + + // Draw alpha mask + ctx.setBlendMode(.normal) + ctx.clip(to: rect, mask: image.cgImage!) + + // Fill with white + ctx.setFillColor(to) + ctx.fill(rect) + + let result = UIGraphicsGetImageFromCurrentImageContext() + UIGraphicsEndImageContext() + + return result ?? image +} + diff --git a/Swiftgram/SGPayWall/BUILD b/Swiftgram/SGPayWall/BUILD new file mode 100644 index 00000000..d822f25b --- /dev/null +++ b/Swiftgram/SGPayWall/BUILD @@ -0,0 +1,29 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +filegroup( + name = "SGPayWallAssets", + srcs = glob(["Images.xcassets/**"]), + visibility = ["//visibility:public"], +) + +swift_library( + name = "SGPayWall", + module_name = "SGPayWall", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//Swiftgram/SGIAP:SGIAP", + "//Swiftgram/SGLogging:SGLogging", + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//Swiftgram/SGSwiftUI:SGSwiftUI", + "//Swiftgram/SGStrings:SGStrings", + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGPayWall/Images.xcassets/Contents.json b/Swiftgram/SGPayWall/Images.xcassets/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/Swiftgram/SGPayWall/Images.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGPayWall/Images.xcassets/ProDetailsBackup.imageset/Backup.png b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsBackup.imageset/Backup.png new file mode 100644 index 00000000..06fbd1ff Binary files /dev/null and b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsBackup.imageset/Backup.png differ diff --git a/Swiftgram/SGPayWall/Images.xcassets/ProDetailsBackup.imageset/Contents.json b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsBackup.imageset/Contents.json new file mode 100644 index 00000000..558d4c78 --- /dev/null +++ b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsBackup.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Backup.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGPayWall/Images.xcassets/ProDetailsFilter.imageset/Contents.json b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsFilter.imageset/Contents.json new file mode 100644 index 00000000..7c01e065 --- /dev/null +++ b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsFilter.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Filter.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGPayWall/Images.xcassets/ProDetailsFilter.imageset/Filter.png b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsFilter.imageset/Filter.png new file mode 100644 index 00000000..665a294e Binary files /dev/null and b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsFilter.imageset/Filter.png differ diff --git a/Swiftgram/SGPayWall/Images.xcassets/ProDetailsFormatting.imageset/Contents.json b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsFormatting.imageset/Contents.json new file mode 100644 index 00000000..2c6fae70 --- /dev/null +++ b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsFormatting.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Formatting.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGPayWall/Images.xcassets/ProDetailsFormatting.imageset/Formatting.png b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsFormatting.imageset/Formatting.png new file mode 100644 index 00000000..9945739a Binary files /dev/null and b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsFormatting.imageset/Formatting.png differ diff --git a/Swiftgram/SGPayWall/Images.xcassets/ProDetailsIcons.imageset/Contents.json b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsIcons.imageset/Contents.json new file mode 100644 index 00000000..7a1f30c7 --- /dev/null +++ b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsIcons.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Icons.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGPayWall/Images.xcassets/ProDetailsIcons.imageset/Icons.png b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsIcons.imageset/Icons.png new file mode 100644 index 00000000..300ec522 Binary files /dev/null and b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsIcons.imageset/Icons.png differ diff --git a/Swiftgram/SGPayWall/Images.xcassets/ProDetailsMute.imageset/Contents.json b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsMute.imageset/Contents.json new file mode 100644 index 00000000..3527b118 --- /dev/null +++ b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsMute.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Mute.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGPayWall/Images.xcassets/ProDetailsMute.imageset/Mute.png b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsMute.imageset/Mute.png new file mode 100644 index 00000000..05e22393 Binary files /dev/null and b/Swiftgram/SGPayWall/Images.xcassets/ProDetailsMute.imageset/Mute.png differ diff --git a/Swiftgram/SGPayWall/Images.xcassets/pro.imageset/Contents.json b/Swiftgram/SGPayWall/Images.xcassets/pro.imageset/Contents.json new file mode 100644 index 00000000..6c7c64d6 --- /dev/null +++ b/Swiftgram/SGPayWall/Images.xcassets/pro.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "filename" : "pro.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "pro@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "pro@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGPayWall/Images.xcassets/pro.imageset/pro.png b/Swiftgram/SGPayWall/Images.xcassets/pro.imageset/pro.png new file mode 100644 index 00000000..56e048db Binary files /dev/null and b/Swiftgram/SGPayWall/Images.xcassets/pro.imageset/pro.png differ diff --git a/Swiftgram/SGPayWall/Images.xcassets/pro.imageset/pro@2x.png b/Swiftgram/SGPayWall/Images.xcassets/pro.imageset/pro@2x.png new file mode 100644 index 00000000..c76f57d4 Binary files /dev/null and b/Swiftgram/SGPayWall/Images.xcassets/pro.imageset/pro@2x.png differ diff --git a/Swiftgram/SGPayWall/Images.xcassets/pro.imageset/pro@3x.png b/Swiftgram/SGPayWall/Images.xcassets/pro.imageset/pro@3x.png new file mode 100644 index 00000000..942d676d Binary files /dev/null and b/Swiftgram/SGPayWall/Images.xcassets/pro.imageset/pro@3x.png differ diff --git a/Swiftgram/SGPayWall/Sources/SGPayWall.swift b/Swiftgram/SGPayWall/Sources/SGPayWall.swift new file mode 100644 index 00000000..5af886cd --- /dev/null +++ b/Swiftgram/SGPayWall/Sources/SGPayWall.swift @@ -0,0 +1,985 @@ +import Foundation +import SwiftUI +import StoreKit +import SGSwiftUI +import SGIAP +import TelegramPresentationData +import LegacyUI +import Display +import SGConfig +import SGStrings +import SwiftSignalKit +import TelegramUIPreferences + + + +public func sgPayWallController(statusSignal: Signal, replacementController: ViewController, presentationData: PresentationData? = nil, SGIAPManager: SGIAPManager, openUrl: @escaping (String, Bool) -> Void /* url, forceExternal */, paymentsEnabled: Bool, canBuyInBeta: Bool, openAppStorePage: @escaping () -> Void, proSupportUrl: String?) -> ViewController { + // let theme = presentationData?.theme ?? (UITraitCollection.current.userInterfaceStyle == .dark ? defaultDarkColorPresentationTheme : defaultPresentationTheme) + let theme = defaultDarkColorPresentationTheme + let strings = presentationData?.strings ?? defaultPresentationStrings + + let legacyController = LegacySwiftUIController( + presentation: .modal(animateIn: true), + theme: theme, + strings: strings + ) + // legacyController.displayNavigationBar = false + legacyController.statusBar.statusBarStyle = .White + legacyController.attemptNavigation = { _ in return false } + legacyController.view.disablesInteractiveTransitionGestureRecognizer = true + + let swiftUIView = SGSwiftUIView( + legacyController: legacyController, + content: { + SGPayWallView(wrapperController: legacyController, replacementController: replacementController, SGIAP: SGIAPManager, statusSignal: statusSignal, openUrl: openUrl, openAppStorePage: openAppStorePage, paymentsEnabled: paymentsEnabled, canBuyInBeta: canBuyInBeta, proSupportUrl: proSupportUrl) + } + ) + let controller = UIHostingController(rootView: swiftUIView, ignoreSafeArea: true) + legacyController.bind(controller: controller) + + return legacyController +} + +private let innerShadowWidth: CGFloat = 15.0 +private let accentColorHex: String = "F1552E" + + + +struct BackgroundView: View { + + var body: some View { + ZStack { + LinearGradient( + gradient: Gradient(stops: [ + .init(color: Color(hex: "A053F8").opacity(0.8), location: 0.0), // purple gradient + .init(color: Color.clear, location: 0.20), + + ]), + startPoint: .topLeading, + endPoint: .bottomTrailing + ) + .edgesIgnoringSafeArea(.all) + LinearGradient( + gradient: Gradient(stops: [ + .init(color: Color(hex: "CC4303").opacity(0.6), location: 0.0), // orange gradient + .init(color: Color.clear, location: 0.15), + ]), + startPoint: .topTrailing, + endPoint: .bottomLeading + ) + .blendMode(.lighten) + + .edgesIgnoringSafeArea(.all) + .overlay( + RoundedRectangle(cornerRadius: 0) + .stroke(Color.clear, lineWidth: 0) + .background( + ZStack { + innerShadow(x: -2, y: -2, blur: 4, color: Color(hex: "FF8C56")) // orange shadow + innerShadow(x: 2, y: 2, blur: 4, color: Color(hex: "A053F8")) // purple shadow + // innerShadow(x: 0, y: 0, blur: 4, color: Color.white.opacity(0.3)) + } + ) + ) + .edgesIgnoringSafeArea(.all) + } + .background(Color.black) + } + + func innerShadow(x: CGFloat, y: CGFloat, blur: CGFloat, color: Color) -> some View { + return RoundedRectangle(cornerRadius: 0) + .stroke(color, lineWidth: innerShadowWidth) + .blur(radius: blur) + .offset(x: x, y: y) + .mask(RoundedRectangle(cornerRadius: 0).fill(LinearGradient(gradient: Gradient(colors: [Color.black, Color.clear]), startPoint: .top, endPoint: .bottom))) + } +} + + + +struct SGPayWallFeatureDetails: View { + + let dismissAction: () -> Void + var bottomOffset: CGFloat = 0.0 + let contentHeight: CGFloat = 690.0 + let features: [SGProFeature] + + @State var shownFeature: SGProFeatureId? + // Add animation states + @State private var showBackground = false + @State private var showContent = false + + @State private var dragOffset: CGFloat = 0 + + var body: some View { + ZStack(alignment: .bottom) { + // Background overlay + if showBackground { + Color.black.opacity(0.4) + .zIndex(0) + .edgesIgnoringSafeArea(.all) + .onTapGesture { + dismissWithAnimation() + } + .transition(.opacity) + } + + // Bottom sheet content + if showContent { + VStack { + if #available(iOS 14.0, *) { + TabView(selection: $shownFeature) { + ForEach(features) { feature in + ScrollView(showsIndicators: false) { + SGProFeatureView( + feature: feature + ) + Color.clear.frame(height: 8.0) // paginator padding + } + .tag(feature.id) + .scrollBounceBehaviorIfAvailable(.basedOnSize) + } + } + .tabViewStyle(.page) + .padding(.bottom, bottomOffset - 8.0) + } + + // Spacer for purchase buttons + if !bottomOffset.isZero { + Color.clear.frame(height: bottomOffset) + } + } + .zIndex(1) + .frame(maxHeight: contentHeight) + .background(Color(.black)) + .cornerRadius(8, corners: [.topLeft, .topRight]) + .overlay(closeButtonView) + .offset(y: max(0, dragOffset)) + .gesture( + DragGesture() + .onChanged { value in + // Only track downward movement + if value.translation.height > 0 { + dragOffset = value.translation.height + } + } + .onEnded { value in + // If dragged down more than 150 points or with significant velocity, dismiss + if value.translation.height > 150 || value.predictedEndTranslation.height > 200 { + dismissWithAnimation() + } else { + // Otherwise, reset position + withAnimation(.spring()) { + dragOffset = 0 + } + } + } + ) + .transition(.move(edge: .bottom)) + } + } + .onAppear { + appearWithAnimation() + } + } + + private func appearWithAnimation() { + withAnimation(.easeIn(duration: 0.2)) { + showBackground = true + } + + withAnimation(.spring(duration: 0.3)/*.delay(0.1)*/) { + showContent = true + } + } + + private func dismissWithAnimation() { + withAnimation(.spring()) { + showContent = false + dragOffset = 0 + } + + withAnimation(.easeOut(duration: 0.2).delay(0.1)) { + showBackground = false + } + + DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { + dismissAction() + } + } + + private var closeButtonView: some View { + Button(action: { + dismissWithAnimation() + }) { + Image(systemName: "xmark") + .font(.headline) + .foregroundColor(.secondary.opacity(0.6)) + .frame(width: 44, height: 44) + .contentShape(Rectangle()) // Improve tappable area + } + .opacity(showContent ? 1.0 : 0.0) + .padding([.top, .trailing], 8) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing) + } +} + + + +struct SGProFeatureView: View { + let feature: SGProFeature + + var body: some View { + VStack(spacing: 16) { + feature.image + .resizable() + .aspectRatio(contentMode: .fit) + .frame(maxWidth: .infinity, maxHeight: 400.0, alignment: .top) + .clipped() + + VStack(alignment: .center, spacing: 8) { + Text(feature.title) + .font(.title) + .fontWeight(.bold) + .multilineTextAlignment(.center) + Text(featureSubtitle) + .font(.subheadline) + .foregroundColor(.secondary) + .multilineTextAlignment(.center) + } + .padding(.horizontal) + + Spacer() + } + } + + var featureSubtitle: String { + return feature.description ?? feature.subtitle + } +} + +enum SGProFeatureId: Hashable { + case backup + case filter + case notifications + case toolbar + case icons +} + + + +struct SGProFeature: Identifiable { + + let id: SGProFeatureId + let title: String + let subtitle: String + let description: String? + + @ViewBuilder + public var icon: some View { + switch (id) { + case .backup: + FeatureIcon(icon: "lock.fill", backgroundColor: .blue) + case .filter: + FeatureIcon(icon: "nosign", backgroundColor: .gray, fontWeight: .bold) + case .notifications: + FeatureIcon(icon: "bell.badge.slash.fill", backgroundColor: .red) + case .toolbar: + FeatureIcon(icon: "bold.underline", backgroundColor: .blue, iconSize: 16) + case .icons: + Image("SwiftgramSettings") + .resizable() + .frame(width: 32, height: 32) + @unknown default: + Image("SwiftgramPro") + .resizable() + .frame(width: 32, height: 32) + } + } + + public var image: Image { + switch (id) { + case .backup: + return Image("ProDetailsBackup") + case .filter: + return Image("ProDetailsFilter") + case .notifications: + return Image("ProDetailsMute") + case .toolbar: + return Image("ProDetailsFormatting") + case .icons: + return Image("ProDetailsIcons") + @unknown default: + return Image("pro") + } + } +} + + + +struct SGPayWallView: View { + @Environment(\.navigationBarHeight) var navigationBarHeight: CGFloat + @Environment(\.containerViewLayout) var containerViewLayout: ContainerViewLayout? + @Environment(\.lang) var lang: String + + weak var wrapperController: LegacyController? + let replacementController: ViewController + let SGIAP: SGIAPManager + let statusSignal: Signal + let openUrl: (String, Bool) -> Void // url, forceExternal + let openAppStorePage: () -> Void + let paymentsEnabled: Bool + let canBuyInBeta: Bool + let proSupportUrl: String? + + private enum PayWallState: Equatable { + case ready // ready to buy + case restoring + case purchasing + case validating + } + + // State management + @State private var product: SGIAPManager.SGProduct? + @State private var currentStatus: Int64 = 1 + @State private var state: PayWallState = .ready + @State private var showErrorAlert: Bool = false + @State private var showConfetti: Bool = false + @State private var showDetails: Bool = false + @State private var shownFeature: SGProFeatureId? = nil + + private let productsPub = NotificationCenter.default.publisher(for: .SGIAPHelperProductsUpdatedNotification, object: nil) + private let buyOrRestoreSuccessPub = NotificationCenter.default.publisher(for: .SGIAPHelperPurchaseNotification, object: nil) + private let buyErrorPub = NotificationCenter.default.publisher(for: .SGIAPHelperErrorNotification, object: nil) + private let validationErrorPub = NotificationCenter.default.publisher(for: .SGIAPHelperValidationErrorNotification, object: nil) + + @State private var statusDisposable = MetaDisposable() + + @State private var hapticFeedback: HapticFeedback? + private let confettiDuration: Double = 5.0 + + @State private var purchaseSectionSize: CGSize = .zero + + private var features: [SGProFeature] { + return [ + SGProFeature(id: .toolbar, title: "PayWall.InputToolbar.Title".i18n(lang), subtitle: "PayWall.InputToolbar.Notice".i18n(lang), description: "PayWall.InputToolbar.Description".i18n(lang)), + SGProFeature(id: .filter, title: "PayWall.MessageFilter.Title".i18n(lang), subtitle: "PayWall.MessageFilter.Notice".i18n(lang), description: "PayWall.MessageFilter.Description".i18n(lang)), + SGProFeature(id: .icons, title: "PayWall.AppIcons.Title".i18n(lang), subtitle: "PayWall.AppIcons.Notice".i18n(lang), description: nil), + SGProFeature(id: .backup, title: "PayWall.SessionBackup.Title".i18n(lang), subtitle: "PayWall.SessionBackup.Notice".i18n(lang), description: "PayWall.SessionBackup.Description".i18n(lang)), + SGProFeature(id: .notifications, title: "PayWall.Notifications.Title".i18n(lang), subtitle: "PayWall.Notifications.Notice".i18n(lang), description: "PayWall.Notifications.Description".i18n(lang)), + ] + } + + var body: some View { + ZStack { + BackgroundView() + + ZStack(alignment: .bottom) { + ScrollView(showsIndicators: false) { + VStack(spacing: 24) { + // Icon + Image("pro") + .frame(width: 100, height: 100) + + // Title and Subtitle + VStack(spacing: 8) { + Text("Swiftgram Pro") + .font(.largeTitle) + .fontWeight(.bold) + + Text("PayWall.Text".i18n(lang)) + .font(.callout) + .multilineTextAlignment(.center) + .padding(.horizontal) + } + + // Features + VStack(spacing: 36) { + featuresSection + + aboutSection + + VStack(spacing: 8) { + HStack { + legalSection + Spacer() + } + + HStack { + restorePurchasesButton + Spacer() + } + } + } + + + // Spacer for purchase buttons + Color.clear.frame(height: (purchaseSectionSize.height / 2.0)) + } + .padding(.vertical, (purchaseSectionSize.height / 2.0)) + } + .padding(.leading, max(innerShadowWidth + 8.0, sgLeftSafeAreaInset(containerViewLayout))) + .padding(.trailing, max(innerShadowWidth + 8.0, sgRightSafeAreaInset(containerViewLayout))) + + if showDetails { + SGPayWallFeatureDetails( + dismissAction: dismissDetails, + bottomOffset: (purchaseSectionSize.height / 2.0) * 0.9, // reduced offset for paginator + features: features, + shownFeature: shownFeature) + } + + // Fixed purchase button at bottom + purchaseSection + .trackSize($purchaseSectionSize) + } + } + .confetti(isActive: $showConfetti, duration: confettiDuration) + .overlay(closeButtonView) + .colorScheme(.dark) + .onReceive(productsPub) { _ in + updateSelectedProduct() + } + .onAppear { + hapticFeedback = HapticFeedback() + updateSelectedProduct() + statusDisposable.set((statusSignal + |> deliverOnMainQueue).start(next: { newStatus in + #if DEBUG + print("SGPayWallView: newStatus = \(newStatus)") + #endif + + if currentStatus != newStatus { + currentStatus = newStatus + + if newStatus > 1 { + handleUpgradedStatus() + } + } + })) + } + .onDisappear { + #if DEBUG + print("Disposing status signal subscription") + #endif + statusDisposable.set(nil) + } + .onReceive(buyOrRestoreSuccessPub) { _ in + state = .validating + } + .onReceive(buyErrorPub) { notification in + if let userInfo = notification.userInfo, let error = userInfo["localizedError"] as? String, !error.isEmpty { + showErrorAlert(error) + } + } + .onReceive(validationErrorPub) { notification in + if state == .validating { + if let userInfo = notification.userInfo, let error = userInfo["error"] as? String, !error.isEmpty { + showErrorAlert(error.i18n(lang)) + } else { + showErrorAlert("PayWall.ValidationError".i18n(lang)) + } + } + } + } + + private var featuresSection: some View { + VStack(spacing: 8) { + ForEach(features) { feature in + FeatureRow( + icon: feature.icon, + title: feature.title, + subtitle: feature.subtitle, + action: { + showDetailsForFeature(feature.id) + } + ) + } + } + } + + private var restorePurchasesButton: some View { + Button(action: handleRestorePurchases) { + Text("PayWall.RestorePurchases".i18n(lang)) + .font(.footnote) + .fontWeight(.semibold) + .foregroundColor(Color(hex: accentColorHex)) + } + .disabled(state == .restoring || product == nil) + .opacity((state == .restoring || product == nil) ? 0.5 : 1.0) + } + + private var purchaseSection: some View { + VStack(spacing: 0) { + Divider() + VStack(spacing: 8) { + Button(action: handlePurchase) { + Text(buttonTitle) + .fontWeight(.semibold) + .frame(maxWidth: .infinity) + .padding() + .background(Color(hex: accentColorHex)) + .foregroundColor(.white) + .cornerRadius(12) + } + .disabled((state != .ready || !canPurchase) && !(currentStatus > 1)) + .opacity(((state != .ready || !canPurchase) && !(currentStatus > 1)) ? 0.5 : 1.0) + + if let proSupportUrl = proSupportUrl { + HStack(alignment: .center, spacing: 4) { + Text("PayWall.ProSupport.Title".i18n(lang)) + .font(.caption) + .foregroundColor(.secondary) + Button(action: { + openUrl(proSupportUrl, false) + }) { + Text("PayWall.ProSupport.Contact".i18n(lang)) + .font(.caption) + .foregroundColor(Color(hex: accentColorHex)) + } + } + } + } + .padding([.horizontal, .top]) + .padding(.bottom, sgBottomSafeAreaInset(containerViewLayout) + 2.0) + } + .foregroundColor(Color.black) + .backgroundIfAvailable(material: .ultraThinMaterial) + .shadow(radius: 8, y: -4) + } + + private var legalSection: some View { + Group { + if #available(iOS 15.0, *) { + Text(LocalizedStringKey("PayWall.Notice.Markdown".i18n(lang, args: "PayWall.TermsURL".i18n(lang), "PayWall.PrivacyURL".i18n(lang)))) + .font(.caption) + .tint(Color(hex: accentColorHex)) + .foregroundColor(.secondary) + .environment(\.openURL, OpenURLAction { url in + openUrl(url.absoluteString, false) + return .handled + }) + } else { + Text("PayWall.Notice.Raw".i18n(lang)) + .font(.caption) + .foregroundColor(.secondary) + HStack(alignment: .top, spacing: 8) { + Button(action: { + openUrl("PayWall.PrivacyURL".i18n(lang), true) + }) { + Text("PayWall.Privacy".i18n(lang)) + .font(.caption) + .foregroundColor(Color(hex: accentColorHex)) + } + Button(action: { + openUrl("PayWall.TermsURL".i18n(lang), true) + }) { + Text("PayWall.Terms".i18n(lang)) + .font(.caption) + .foregroundColor(Color(hex: accentColorHex)) + } + } + } + } + } + + + private var aboutSection: some View { + VStack(spacing: 8) { + HStack { + Text("PayWall.About.Title".i18n(lang)) + .font(.headline) + .fontWeight(.medium) + Spacer() + } + + HStack { + Text("PayWall.About.Notice".i18n(lang)) + .font(.subheadline) + .foregroundColor(.secondary) + Spacer() + } + HStack { + Button(action: { + openUrl("PayWall.About.SignatureURL".i18n(lang), false) + }) { + Text("PayWall.About.Signature".i18n(lang)) + .font(.caption) + .foregroundColor(Color(hex: accentColorHex)) + } + Spacer() + } + } + } + + private var closeButtonView: some View { + Button(action: { + wrapperController?.dismiss(animated: true) + }) { + Image(systemName: "xmark") + .font(.headline) + .foregroundColor(.secondary.opacity(0.6)) + .frame(width: 44, height: 44) + .contentShape(Rectangle()) // Improve tappable area + } + .disabled(showDetails) + .opacity(showDetails ? 0.0 : 1.0) + .padding([.top, .trailing], 16) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing) + } + + private var buttonTitle: String { + if currentStatus > 1 { + return "PayWall.Button.OpenPro".i18n(lang) + } else { + if state == .purchasing { + return "PayWall.Button.Purchasing".i18n(lang) + } else if state == .restoring { + return "PayWall.Button.Restoring".i18n(lang) + } else if state == .validating { + return "PayWall.Button.Validating".i18n(lang) + } else if let product = product { + if !SGIAP.canMakePayments || paymentsEnabled == false { + return "PayWall.Button.PaymentsUnavailable".i18n(lang) + } else if Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" && !canBuyInBeta { + return "PayWall.Button.BuyInAppStore".i18n(lang) + } else { + return "PayWall.Button.Subscribe".i18n(lang, args: product.price) + } + } else { + return "PayWall.Button.ContactingAppStore".i18n(lang) + } + } + } + + private var canPurchase: Bool { + if !SGIAP.canMakePayments || paymentsEnabled == false { + return false + } else { + return product != nil + } + } + + private func showDetailsForFeature(_ featureId: SGProFeatureId) { + if #available(iOS 14.0, *) { + shownFeature = featureId + showDetails = true + } // pagination is not available on iOS 13 + } + + private func dismissDetails() { +// shownFeature = nil + showDetails = false + } + + private func updateSelectedProduct() { + product = SGIAP.availableProducts.first { $0.id == SG_CONFIG.iaps.first ?? "" } + } + + private func handlePurchase() { + if currentStatus > 1 { + wrapperController?.replace(with: replacementController) + } else { + if Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" && !canBuyInBeta { + openAppStorePage() + } else { + guard let product = product else { return } + state = .purchasing + SGIAP.buyProduct(product.skProduct) + } + } + } + + private func handleRestorePurchases() { + state = .restoring + SGIAP.restorePurchases { + state = .validating + } + } + + private func handleUpgradedStatus() { + DispatchQueue.main.async { + hapticFeedback?.success() + showConfetti = true + DispatchQueue.main.asyncAfter(deadline: .now() + confettiDuration + 1.0) { + showConfetti = false + } + } + } + + private func showErrorAlert(_ message: String) { + let alertController = UIAlertController(title: "Error", message: message, preferredStyle: .alert) + alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in + state = .ready + })) + DispatchQueue.main.async { + wrapperController?.present(alertController, animated: true) + } + } +} + + + +struct FeatureIcon: View { + let icon: String + let iconColor: Color + let backgroundColor: Color + let iconSize: CGFloat + let frameSize: CGFloat + let fontWeight: SwiftUI.Font.Weight + + init( + icon: String, + iconColor: Color = .white, + backgroundColor: Color = .blue, + iconSize: CGFloat = 18, + frameSize: CGFloat = 32, + fontWeight: SwiftUI.Font.Weight = .regular + ) { + self.icon = icon + self.iconColor = iconColor + self.backgroundColor = backgroundColor + self.iconSize = iconSize + self.frameSize = frameSize + self.fontWeight = fontWeight + } + + var body: some View { + Image(systemName: icon) + .font(.system(size: iconSize)) + .fontWeightIfAvailable(fontWeight) + .foregroundColor(iconColor) + .frame(width: frameSize, height: frameSize) + .background(backgroundColor) + .clipShape(RoundedRectangle(cornerRadius: 8)) + } +} + + + +struct FeatureRow: View { + let icon: IconContent + let title: String + let subtitle: String + let action: () -> Void + + var body: some View { + Button(action: action) { + HStack(spacing: 16) { + + HStack(alignment: .top, spacing: 12) { + icon + + VStack(alignment: .leading, spacing: 4) { + Text(title) + .font(.headline) + .fontWeight(.medium) + + Text(subtitle) + .font(.subheadline) + .foregroundColor(.secondary) + } + } + + Spacer() + if #available(iOS 14.0, *) { + Image(systemName: "chevron.right") + .font(.system(size: 12, weight: .semibold)) + .foregroundColor(.secondary) + } // Descriptions are not available on iOS 13 + } + .padding() + .background( + RoundedRectangle(cornerRadius: 12) + .fill(Color(.systemGray6)) + .shadow(color: .black.opacity(0.05), radius: 8, x: 0, y: 4) + ) + } + .buttonStyle(PlainButtonStyle()) + } +} + + + +// Confetti + +struct ConfettiType { + let color: Color + let shape: ConfettiShape + + static func random() -> ConfettiType { + let colors: [Color] = [.red, .blue, .green, .yellow, .pink, .purple, .orange] + return ConfettiType( + color: colors.randomElement() ?? .blue, + shape: ConfettiShape.allCases.randomElement() ?? .circle + ) + } +} + + +enum ConfettiShape: CaseIterable { + case circle + case triangle + case square + case slimRectangle + case roundedCross + + @ViewBuilder + func view(color: Color) -> some View { + switch self { + case .circle: + Circle().fill(color) + case .triangle: + Triangle().fill(color) + case .square: + Rectangle().fill(color) + case .slimRectangle: + SlimRectangle().fill(color) + case .roundedCross: + RoundedCross().fill(color) + } + } +} + + +struct Triangle: Shape { + func path(in rect: CGRect) -> Path { + var path = Path() + path.move(to: CGPoint(x: rect.midX, y: rect.minY)) + path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) + path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY)) + path.closeSubpath() + return path + } +} + + +public struct SlimRectangle: Shape { + public func path(in rect: CGRect) -> Path { + var path = Path() + + path.move(to: CGPoint(x: rect.minX, y: 4*rect.maxY/5)) + path.addLine(to: CGPoint(x: rect.maxX, y: 4*rect.maxY/5)) + path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) + path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY)) + + return path + } +} + + +public struct RoundedCross: Shape { + public func path(in rect: CGRect) -> Path { + var path = Path() + + path.move(to: CGPoint(x: rect.minX, y: rect.maxY/3)) + path.addQuadCurve(to: CGPoint(x: rect.maxX/3, y: rect.minY), control: CGPoint(x: rect.maxX/3, y: rect.maxY/3)) + path.addLine(to: CGPoint(x: 2*rect.maxX/3, y: rect.minY)) + + path.addQuadCurve(to: CGPoint(x: rect.maxX, y: rect.maxY/3), control: CGPoint(x: 2*rect.maxX/3, y: rect.maxY/3)) + path.addLine(to: CGPoint(x: rect.maxX, y: 2*rect.maxY/3)) + + path.addQuadCurve(to: CGPoint(x: 2*rect.maxX/3, y: rect.maxY), control: CGPoint(x: 2*rect.maxX/3, y: 2*rect.maxY/3)) + path.addLine(to: CGPoint(x: rect.maxX/3, y: rect.maxY)) + + path.addQuadCurve(to: CGPoint(x: 2*rect.minX/3, y: 2*rect.maxY/3), control: CGPoint(x: rect.maxX/3, y: 2*rect.maxY/3)) + + return path + } +} + + +struct ConfettiModifier: ViewModifier { + @Binding var isActive: Bool + let duration: Double + + func body(content: Content) -> some View { + content.overlay( + ZStack { + if isActive { + ForEach(0..<70) { _ in + ConfettiPiece( + confettiType: .random(), + duration: duration + ) + } + } + } + ) + } +} + + +struct ConfettiPiece: View { + let confettiType: ConfettiType + let duration: Double + + @State private var isAnimating = false + @State private var rotation = Double.random(in: 0...1080) + + var body: some View { + confettiType.shape.view(color: confettiType.color) + .frame(width: 10, height: 10) + .rotationEffect(.degrees(rotation)) + .position( + x: .random(in: 0...UIScreen.main.bounds.width), + y: 0 //-20 + ) + .modifier(FallingModifier(distance: UIScreen.main.bounds.height + 20, duration: duration)) + .opacity(isAnimating ? 0 : 1) + .onAppear { + withAnimation(.linear(duration: duration)) { + isAnimating = true + } + } + } +} + + +struct FallingModifier: ViewModifier { + let distance: CGFloat + let duration: Double + + func body(content: Content) -> some View { + content.modifier( + MoveModifier( + offset: CGSize( + width: .random(in: -100...100), + height: distance + ), + duration: duration + ) + ) + } +} + + +struct MoveModifier: ViewModifier { + let offset: CGSize + let duration: Double + + @State private var isAnimating = false + + func body(content: Content) -> some View { + content.offset( + x: isAnimating ? offset.width : 0, + y: isAnimating ? offset.height : 0 + ) + .onAppear { + withAnimation( + .linear(duration: duration) + .speed(.random(in: 0.5...2.5)) + ) { + isAnimating = true + } + } + } +} + +// Extension to make it easier to use + +extension View { + func confetti(isActive: Binding, duration: Double = 2.0) -> some View { + modifier(ConfettiModifier(isActive: isActive, duration: duration)) + } +} diff --git a/Swiftgram/SGProUI/BUILD b/Swiftgram/SGProUI/BUILD new file mode 100644 index 00000000..a85f5f20 --- /dev/null +++ b/Swiftgram/SGProUI/BUILD @@ -0,0 +1,43 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + + +swift_library( + name = "SGProUI", + module_name = "SGProUI", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//Swiftgram/SGKeychainBackupManager:SGKeychainBackupManager", + "//Swiftgram/SGItemListUI:SGItemListUI", + "//Swiftgram/SGLogging:SGLogging", + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//Swiftgram/SGStrings:SGStrings", + "//Swiftgram/SGAPI:SGAPI", + "//Swiftgram/SGAPIToken:SGAPIToken", + "//Swiftgram/SGSwiftUI:SGSwiftUI", + # + "//submodules/SettingsUI:SettingsUI", + # + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + "//submodules/Display:Display", + "//submodules/Postbox:Postbox", + "//submodules/TelegramCore:TelegramCore", + "//submodules/MtProtoKit:MtProtoKit", + "//submodules/TelegramPresentationData:TelegramPresentationData", + "//submodules/TelegramUIPreferences:TelegramUIPreferences", + "//submodules/ItemListUI:ItemListUI", + "//submodules/PresentationDataUtils:PresentationDataUtils", + "//submodules/OverlayStatusController:OverlayStatusController", + "//submodules/AccountContext:AccountContext", + "//submodules/AppBundle:AppBundle", + "//submodules/TelegramUI/Components/Settings/PeerNameColorScreen", + "//submodules/UndoUI:UndoUI", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGProUI/Sources/AppBadgeSelectorController.swift b/Swiftgram/SGProUI/Sources/AppBadgeSelectorController.swift new file mode 100644 index 00000000..417f9658 --- /dev/null +++ b/Swiftgram/SGProUI/Sources/AppBadgeSelectorController.swift @@ -0,0 +1,147 @@ +import Foundation +import SwiftUI +import SGSwiftUI +import SGStrings +import SGSimpleSettings +import LegacyUI +import Display +import TelegramPresentationData +import AccountContext + + +struct AppBadge: Identifiable, Hashable { + let id: UUID = .init() + let displayName: String + let assetName: String +} + +func getAvailableAppBadges() -> [AppBadge] { + var appBadges: [AppBadge] = [ + .init(displayName: "Default", assetName: "Components/AppBadge"), + .init(displayName: "Sky", assetName: "SkyAppBadge"), + .init(displayName: "Night", assetName: "NightAppBadge"), + .init(displayName: "Titanium", assetName: "TitaniumAppBadge"), + .init(displayName: "Pro", assetName: "ProAppBadge"), + .init(displayName: "Day", assetName: "DayAppBadge"), + ] + + if SGSimpleSettings.shared.duckyAppIconAvailable { + appBadges.append(.init(displayName: "Ducky", assetName: "DuckyAppBadge")) + } + appBadges += [ + .init(displayName: "Sparkling", assetName: "SparklingAppBadge"), + ] + + return appBadges +} + +@available(iOS 14.0, *) +struct AppBadgeSettingsView: View { + weak var wrapperController: LegacyController? + let context: AccountContext + + @Environment(\.colorScheme) var colorScheme + @Environment(\.lang) var lang: String + + @State var selectedBadge: AppBadge + let availableAppBadges: [AppBadge] = getAvailableAppBadges() + + private enum Layout { + static let cardCorner: CGFloat = 12 + static let imageHeight: CGFloat = 56 + static let columnSpacing: CGFloat = 16 + static let horizontalPadding: CGFloat = 20 + } + + private var columns: [SwiftUI.GridItem] { + Array(repeating: GridItem(.flexible(), spacing: Layout.columnSpacing), count: 2) + } + + init(wrapperController: LegacyController?, context: AccountContext) { + self.wrapperController = wrapperController + self.context = context + + for badge in self.availableAppBadges { + if badge.assetName == SGSimpleSettings.shared.customAppBadge { + self._selectedBadge = State(initialValue: badge) + return + } + } + + self._selectedBadge = State(initialValue: self.availableAppBadges.first!) + } + + private func onSelectBadge(_ badge: AppBadge) { + self.selectedBadge = badge + let image = UIImage(bundleImageName: selectedBadge.assetName) ?? UIImage(bundleImageName: "Components/AppBadge") + DispatchQueue.main.async { + SGSimpleSettings.shared.customAppBadge = selectedBadge.assetName + self.context.sharedContext.mainWindow?.badgeView.image = image + } + } + + var body: some View { + ScrollView { + LazyVGrid(columns: columns, alignment: .center, spacing: Layout.columnSpacing) { + ForEach(availableAppBadges) { badge in + Button { + onSelectBadge(badge) + } label: { + VStack(spacing: 8) { + Image(badge.assetName) + .resizable() + .scaledToFit() + .frame(height: Layout.imageHeight) + .accessibilityHidden(true) + + Text(badge.displayName) + .font(.footnote) + } + .frame(maxWidth: .infinity) + .padding() + .background(Color(colorScheme == .dark ? .secondarySystemBackground : .systemBackground)) + .cornerRadius(Layout.cardCorner) + .overlay( + RoundedRectangle(cornerRadius: Layout.cardCorner) + .stroke(selectedBadge == badge ? Color.accentColor : Color.clear, lineWidth: 2) + ) + } + .buttonStyle(.plain) + } + } + .padding(.horizontal, Layout.horizontalPadding) + .padding(.vertical, 24) + + } + .background(Color(colorScheme == .light ? .secondarySystemBackground : .systemBackground).ignoresSafeArea()) + } + +} + +@available(iOS 14.0, *) +public func sgAppBadgeSettingsController(context: AccountContext, presentationData: PresentationData? = nil) -> ViewController { + let theme = presentationData?.theme ?? (UITraitCollection.current.userInterfaceStyle == .dark ? defaultDarkColorPresentationTheme : defaultPresentationTheme) + let strings = presentationData?.strings ?? defaultPresentationStrings + + let legacyController = LegacySwiftUIController( + presentation: .navigation, + theme: theme, + strings: strings + ) + + legacyController.statusBar.statusBarStyle = theme.rootController + .statusBarStyle.style + legacyController.title = "AppBadge.Title".i18n(strings.baseLanguageCode) + + let swiftUIView = SGSwiftUIView( + legacyController: legacyController, + manageSafeArea: true, + content: { + AppBadgeSettingsView(wrapperController: legacyController, context: context) + } + ) + let controller = UIHostingController(rootView: swiftUIView, ignoreSafeArea: true) + legacyController.bind(controller: controller) + + return legacyController +} diff --git a/Swiftgram/SGProUI/Sources/MessageFilterController.swift b/Swiftgram/SGProUI/Sources/MessageFilterController.swift new file mode 100644 index 00000000..eb36ac2e --- /dev/null +++ b/Swiftgram/SGProUI/Sources/MessageFilterController.swift @@ -0,0 +1,181 @@ +import Foundation +import SwiftUI +import SGSwiftUI +import SGStrings +import SGSimpleSettings +import LegacyUI +import Display +import TelegramPresentationData + +@available(iOS 13.0, *) +struct MessageFilterKeywordInputFieldModifier: ViewModifier { + @Binding var newKeyword: String + let onAdd: () -> Void + + func body(content: Content) -> some View { + if #available(iOS 15.0, *) { + content + .submitLabel(.return) + .submitScope(false) // TODO(swiftgram): Keyboard still closing + .interactiveDismissDisabled() + .onSubmit { + onAdd() + } + } else { + content + } + } +} + + +@available(iOS 13.0, *) +struct MessageFilterKeywordInputView: View { + @Environment(\.lang) var lang: String + @Binding var newKeyword: String + let onAdd: () -> Void + + var body: some View { + HStack { + TextField("MessageFilter.InputPlaceholder".i18n(lang), text: $newKeyword) + .autocorrectionDisabled(true) + .autocapitalization(.none) + .keyboardType(.default) + .modifier(MessageFilterKeywordInputFieldModifier(newKeyword: $newKeyword, onAdd: onAdd)) + + + Button(action: onAdd) { + Image(systemName: "plus.circle.fill") + .foregroundColor(newKeyword.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? .secondary : .accentColor) + .imageScale(.large) + } + .disabled(newKeyword.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + .buttonStyle(PlainButtonStyle()) + } + } +} + +@available(iOS 13.0, *) +struct MessageFilterView: View { + weak var wrapperController: LegacyController? + @Environment(\.lang) var lang: String + + @State private var newKeyword: String = "" + @State private var keywords: [String] { + didSet { + SGSimpleSettings.shared.messageFilterKeywords = keywords + } + } + + init(wrapperController: LegacyController?) { + self.wrapperController = wrapperController + _keywords = State(initialValue: SGSimpleSettings.shared.messageFilterKeywords) + } + + var bodyContent: some View { + List { + Section { + // Icon and title + VStack(spacing: 8) { + Image(systemName: "nosign.app.fill") + .font(.system(size: 50)) + .foregroundColor(.secondary) + + Text("MessageFilter.Title".i18n(lang)) + .font(.title) + .bold() + + Text("MessageFilter.SubTitle".i18n(lang)) + .font(.body) + .foregroundColor(.secondary) + .multilineTextAlignment(.center) + .padding(.horizontal) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 16) + .listRowInsets(EdgeInsets()) + + } + + Section { + MessageFilterKeywordInputView(newKeyword: $newKeyword, onAdd: addKeyword) + } + + Section(header: Text("MessageFilter.Keywords.Title".i18n(lang))) { + ForEach(keywords.reversed(), id: \.self) { keyword in + Text(keyword) + } + .onDelete { indexSet in + let originalIndices = IndexSet( + indexSet.map { keywords.count - 1 - $0 } + ) + deleteKeywords(at: originalIndices) + } + } + } + .tgNavigationBackButton(wrapperController: wrapperController) + } + + var body: some View { + NavigationView { + if #available(iOS 14.0, *) { + bodyContent + .toolbar { + EditButton() + } + } else { + bodyContent + } + } + } + + private func addKeyword() { + let trimmedKeyword = newKeyword.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmedKeyword.isEmpty else { return } + + let keywordExists = keywords.contains { + $0 == trimmedKeyword + } + + guard !keywordExists else { + return + } + + withAnimation { + keywords.append(trimmedKeyword) + } + newKeyword = "" + + } + + private func deleteKeywords(at offsets: IndexSet) { + withAnimation { + keywords.remove(atOffsets: offsets) + } + } +} + +@available(iOS 13.0, *) +public func sgMessageFilterController(presentationData: PresentationData? = nil) -> ViewController { + let theme = presentationData?.theme ?? (UITraitCollection.current.userInterfaceStyle == .dark ? defaultDarkColorPresentationTheme : defaultPresentationTheme) + let strings = presentationData?.strings ?? defaultPresentationStrings + + let legacyController = LegacySwiftUIController( + presentation: .navigation, + theme: theme, + strings: strings + ) + // Status bar color will break if theme changed + legacyController.statusBar.statusBarStyle = theme.rootController + .statusBarStyle.style + legacyController.displayNavigationBar = false + let swiftUIView = SGSwiftUIView( + legacyController: legacyController, + content: { + MessageFilterView(wrapperController: legacyController) + } + ) + let controller = UIHostingController(rootView: swiftUIView, ignoreSafeArea: true) + legacyController.bind(controller: controller) + + return legacyController +} diff --git a/Swiftgram/SGProUI/Sources/SGProUI.swift b/Swiftgram/SGProUI/Sources/SGProUI.swift new file mode 100644 index 00000000..fd59b2e6 --- /dev/null +++ b/Swiftgram/SGProUI/Sources/SGProUI.swift @@ -0,0 +1,189 @@ +import Foundation +import UniformTypeIdentifiers +import SGItemListUI +import UndoUI +import AccountContext +import Display +import TelegramCore +import Postbox +import ItemListUI +import SwiftSignalKit +import TelegramPresentationData +import PresentationDataUtils +import TelegramUIPreferences +import SettingsUI + +// Optional +import SGSimpleSettings +import SGLogging + + +private enum SGProControllerSection: Int32, SGItemListSection { + case base + case appearance + case notifications + case footer +} + +private enum SGProDisclosureLink: String { + case sessionBackupManager + case messageFilter + case appIcons + case appBages +} + +private enum SGProToggles: String { + case inputToolbar +} + +private enum SGProOneFromManySetting: String { + case pinnedMessageNotifications + case mentionsAndRepliesNotifications +} + +private enum SGProAction { + case resetIAP +} + +private typealias SGProControllerEntry = SGItemListUIEntry + +private func SGProControllerEntries(presentationData: PresentationData) -> [SGProControllerEntry] { + var entries: [SGProControllerEntry] = [] + let lang = presentationData.strings.baseLanguageCode + + let id = SGItemListCounter() + + entries.append(.disclosure(id: id.count, section: .base, link: .sessionBackupManager, text: "SessionBackup.Title".i18n(lang))) + entries.append(.disclosure(id: id.count, section: .base, link: .messageFilter, text: "MessageFilter.Title".i18n(lang))) + entries.append(.toggle(id: id.count, section: .base, settingName: .inputToolbar, value: SGSimpleSettings.shared.inputToolbar, text: "InputToolbar.Title".i18n(lang), enabled: true)) + + entries.append(.header(id: id.count, section: .notifications, text: presentationData.strings.Notifications_Title.uppercased(), badge: nil)) + entries.append(.oneFromManySelector(id: id.count, section: .notifications, settingName: .pinnedMessageNotifications, text: "Notifications.PinnedMessages.Title".i18n(lang), value: "Notifications.PinnedMessages.value.\(SGSimpleSettings.shared.pinnedMessageNotifications)".i18n(lang), enabled: true)) + entries.append(.oneFromManySelector(id: id.count, section: .notifications, settingName: .mentionsAndRepliesNotifications, text: "Notifications.MentionsAndReplies.Title".i18n(lang), value: "Notifications.MentionsAndReplies.value.\(SGSimpleSettings.shared.mentionsAndRepliesNotifications)".i18n(lang), enabled: true)) + entries.append(.header(id: id.count, section: .appearance, text: presentationData.strings.Appearance_Title.uppercased(), badge: nil)) + entries.append(.disclosure(id: id.count, section: .appearance, link: .appIcons, text: presentationData.strings.Appearance_AppIcon)) + entries.append(.disclosure(id: id.count, section: .appearance, link: .appBages, text: "AppBadge.Title".i18n(lang))) + entries.append(.notice(id: id.count, section: .appearance, text: "AppBadge.Notice".i18n(lang))) + + #if DEBUG + entries.append(.action(id: id.count, section: .footer, actionType: .resetIAP, text: "Reset Pro", kind: .destructive)) + #endif + + return entries +} + +public func okUndoController(_ text: String, _ presentationData: PresentationData) -> UndoOverlayController { + return UndoOverlayController(presentationData: presentationData, content: .succeed(text: text, timeout: nil, customUndoText: nil), elevatedLayout: false, action: { _ in return false }) +} + +public func sgProController(context: AccountContext) -> ViewController { + var presentControllerImpl: ((ViewController, ViewControllerPresentationArguments?) -> Void)? + var pushControllerImpl: ((ViewController) -> Void)? + + let simplePromise = ValuePromise(true, ignoreRepeated: false) + + let arguments = SGItemListArguments(context: context, setBoolValue: { toggleName, value in + switch toggleName { + case .inputToolbar: + SGSimpleSettings.shared.inputToolbar = value + } + }, setOneFromManyValue: { setting in + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + let lang = presentationData.strings.baseLanguageCode + let actionSheet = ActionSheetController(presentationData: presentationData) + var items: [ActionSheetItem] = [] + + switch (setting) { + case .pinnedMessageNotifications: + let setAction: (String) -> Void = { value in + SGSimpleSettings.shared.pinnedMessageNotifications = value + SGSimpleSettings.shared.synchronizeShared() + simplePromise.set(true) + } + + for value in SGSimpleSettings.PinnedMessageNotificationsSettings.allCases { + items.append(ActionSheetButtonItem(title: "Notifications.PinnedMessages.value.\(value.rawValue)".i18n(lang), color: .accent, action: { [weak actionSheet] in + actionSheet?.dismissAnimated() + setAction(value.rawValue) + })) + } + case .mentionsAndRepliesNotifications: + let setAction: (String) -> Void = { value in + SGSimpleSettings.shared.mentionsAndRepliesNotifications = value + SGSimpleSettings.shared.synchronizeShared() + simplePromise.set(true) + } + + for value in SGSimpleSettings.MentionsAndRepliesNotificationsSettings.allCases { + items.append(ActionSheetButtonItem(title: "Notifications.MentionsAndReplies.value.\(value.rawValue)".i18n(lang), color: .accent, action: { [weak actionSheet] in + actionSheet?.dismissAnimated() + setAction(value.rawValue) + })) + } + } + + actionSheet.setItemGroups([ActionSheetItemGroup(items: items), ActionSheetItemGroup(items: [ + ActionSheetButtonItem(title: presentationData.strings.Common_Cancel, color: .accent, font: .bold, action: { [weak actionSheet] in + actionSheet?.dismissAnimated() + }) + ])]) + presentControllerImpl?(actionSheet, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + }, openDisclosureLink: { link in + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + switch (link) { + case .sessionBackupManager: + pushControllerImpl?(sgSessionBackupManagerController(context: context, presentationData: presentationData)) + case .messageFilter: + pushControllerImpl?(sgMessageFilterController(presentationData: presentationData)) + case .appIcons: + pushControllerImpl?(themeSettingsController(context: context, focusOnItemTag: .icon)) + case .appBages: + if #available(iOS 14.0, *) { + pushControllerImpl?(sgAppBadgeSettingsController(context: context, presentationData: presentationData)) + } else { + presentControllerImpl?(UndoOverlayController( + presentationData: presentationData, + content: .info(title: nil, text: "iOS 14 or newer is required for this feature.", timeout: nil, customUndoText: nil), + elevatedLayout: false, + action: { _ in return false } + ), nil) + } + } + }, action: { action in + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + switch action { + case .resetIAP: + presentControllerImpl?(UndoOverlayController( + presentationData: presentationData, + content: .info(title: nil, text: "Reset is unavailable in this build.", timeout: nil, customUndoText: nil), + elevatedLayout: false, + action: { _ in return false } + ), nil) + } + }) + + let signal = combineLatest(context.sharedContext.presentationData, simplePromise.get()) + |> map { presentationData, _ -> (ItemListControllerState, (ItemListNodeState, Any)) in + + let entries = SGProControllerEntries(presentationData: presentationData) + + let controllerState = ItemListControllerState(presentationData: ItemListPresentationData(presentationData), title: .text("Swiftgram Pro"), leftNavigationButton: nil, rightNavigationButton: nil, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back)) + + let listState = ItemListNodeState(presentationData: ItemListPresentationData(presentationData), entries: entries, style: .blocks, ensureVisibleItemTag: /*focusOnItemTag*/ nil, initialScrollToItem: nil /* scrollToItem*/ ) + + return (controllerState, (listState, arguments)) + } + + let controller = ItemListController(context: context, state: signal) + presentControllerImpl = { [weak controller] c, a in + controller?.present(c, in: .window(.root), with: a) + } + pushControllerImpl = { [weak controller] c in + (controller?.navigationController as? NavigationController)?.pushViewController(c) + } + // Workaround + let _ = pushControllerImpl + + return controller +} + diff --git a/Swiftgram/SGProUI/Sources/SessionBackupController.swift b/Swiftgram/SGProUI/Sources/SessionBackupController.swift new file mode 100644 index 00000000..df9c1f26 --- /dev/null +++ b/Swiftgram/SGProUI/Sources/SessionBackupController.swift @@ -0,0 +1,519 @@ +import Foundation +import UndoUI +import AccountContext +import TelegramCore +import Postbox +import Display +import SwiftSignalKit +import TelegramPresentationData +import PresentationDataUtils +import SGSimpleSettings +import SGLogging +import SGKeychainBackupManager + +struct SessionBackup: Codable { + var name: String? = nil + var date: Date = Date() + let accountRecord: AccountRecord + + var peerIdInternal: Int64 { + var userId: Int64 = 0 + for attribute in accountRecord.attributes { + if case let .backupData(backupData) = attribute, let backupPeerID = backupData.data?.peerId { + userId = backupPeerID + break + } + } + return userId + } + + var userId: Int64 { + return PeerId(peerIdInternal).id._internalGetInt64Value() + } +} + +import SwiftUI +import SGSwiftUI +import LegacyUI +import SGStrings + + +@available(iOS 13.0, *) +struct SessionBackupRow: View { + @Environment(\.lang) var lang: String + let backup: SessionBackup + let isLoggedIn: Bool + + + private let dateFormatter: DateFormatter = { + let formatter = DateFormatter() + formatter.dateStyle = .short + formatter.timeStyle = .short + return formatter + }() + + var formattedDate: String { + if #available(iOS 15.0, *) { + return backup.date.formatted(date: .abbreviated, time: .shortened) + } else { + return dateFormatter.string(from: backup.date) + } + } + + var body: some View { + HStack { + VStack(alignment: .leading, spacing: 2) { + Text(backup.name ?? String(backup.userId)) + .font(.body) + + Text("ID: \(backup.userId)") + .font(.subheadline) + .foregroundColor(.secondary) + + Text("SessionBackup.LastBackupAt".i18n(lang, args: formattedDate)) + .font(.caption) + .foregroundColor(.secondary) + } + + Spacer() + + Text((isLoggedIn ? "SessionBackup.LoggedIn" : "SessionBackup.LoggedOut").i18n(lang)) + .font(.caption) + .foregroundColor(isLoggedIn ? .white : .secondary) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(isLoggedIn ? Color.accentColor : Color.secondary.opacity(0.1)) + .cornerRadius(4) + } + .padding(.vertical, 4) + } +} + + +@available(iOS 13.0, *) +struct BorderedButtonStyle: ButtonStyle { + func makeBody(configuration: Configuration) -> some View { + configuration.label + .background( + RoundedRectangle(cornerRadius: 8) + .stroke(Color.accentColor, lineWidth: 1) + ) + .opacity(configuration.isPressed ? 0.7 : 1.0) + } +} + +@available(iOS 13.0, *) +struct SessionBackupManagerView: View { + @Environment(\.lang) var lang: String + weak var wrapperController: LegacyController? + let context: AccountContext + + @State private var sessions: [SessionBackup] = [] + @State private var loggedInPeerIDs: [Int64] = [] + @State private var loggedInAccountsDisposable: Disposable? = nil + + private func performBackup() { + let controller = OverlayStatusController(theme: context.sharedContext.currentPresentationData.with { $0 }.theme, type: .loading(cancelled: nil)) + + let signal = context.sharedContext.accountManager.accountRecords() + |> take(1) + |> deliverOnMainQueue + + let signal2 = context.sharedContext.activeAccountsWithInfo + |> take(1) + |> deliverOnMainQueue + + wrapperController?.present(controller, in: .window(.root), with: nil) + + let _ = (combineLatest(signal, signal2) + |> take(1) + |> deliverOnMainQueue).start(next: { view, accountsWithInfo in + backupSessionsFromView(view, accountsWithInfo: accountsWithInfo.1) + withAnimation { + sessions = getBackedSessions() + } + controller.dismiss() + }) + + } + + private func performRestore() { + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + let controller = OverlayStatusController(theme: presentationData.theme, type: .loading(cancelled: nil)) + + let _ = (context.sharedContext.accountManager.accountRecords() + |> take(1) + |> deliverOnMainQueue).start(next: { [weak controller] view in + + let backupSessions = getBackedSessions() + var restoredSessions: Int64 = 0 + + func importNextBackup(index: Int) { + // Check if we're done + if index >= backupSessions.count { + // All done, update UI + withAnimation { + sessions = getBackedSessions() + } + controller?.dismiss() + wrapperController?.present( + okUndoController("SessionBackup.RestoreOK".i18n(lang, args: "\(restoredSessions)"), presentationData), + in: .current + ) + return + } + + let backup = backupSessions[index] + + // Check for existing record + let existingRecord = view.records.first { record in + var userId: Int64 = 0 + for attribute in record.attributes { + if case let .backupData(backupData) = attribute { + userId = backupData.data?.peerId ?? 0 + } + } + return userId == backup.peerIdInternal + } + + if existingRecord != nil { + SGLogger.shared.log("SessionBackup", "Record \(backup.userId) already exists, skipping") + importNextBackup(index: index + 1) + return + } + + var importAttributes = backup.accountRecord.attributes + importAttributes.removeAll { attribute in + if case .sortOrder = attribute { + return true + } + return false + } + + let importBackupSignal = context.sharedContext.accountManager.transaction { transaction -> Void in + let nextSortOrder = (transaction.getRecords().map({ record -> Int32 in + for attribute in record.attributes { + if case let .sortOrder(sortOrder) = attribute { + return sortOrder.order + } + } + return 0 + }).max() ?? 0) + 1 + importAttributes.append(.sortOrder(AccountSortOrderAttribute(order: nextSortOrder))) + let accountRecordId = transaction.createRecord(importAttributes) + SGLogger.shared.log("SessionBackup", "Imported record \(accountRecordId) for \(backup.userId)") + restoredSessions += 1 + } + |> deliverOnMainQueue + + let _ = importBackupSignal.start(completed: { + importNextBackup(index: index + 1) + }) + } + + // Start the import chain + importNextBackup(index: 0) + }) + + wrapperController?.present(controller, in: .window(.root), with: nil) + } + + private func performDeleteAll() { + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + + let controller = textAlertController(context: context, title: "SessionBackup.DeleteAll.Title".i18n(lang), text: "SessionBackup.DeleteAll.Text".i18n(lang), actions: [ + TextAlertAction(type: .destructiveAction, title: presentationData.strings.Common_Delete, action: { + let controller = OverlayStatusController(theme: presentationData.theme, type: .loading(cancelled: nil)) + wrapperController?.present(controller, in: .window(.root), with: nil) + do { + try KeychainBackupManager.shared.deleteAllSessions() + withAnimation { + sessions = getBackedSessions() + } + controller.dismiss() + } catch let e { + SGLogger.shared.log("SessionBackup", "Error deleting all sessions: \(e)") + } + }), + TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_Cancel, action: {}) + ]) + + wrapperController?.present(controller, in: .window(.root), with: nil) + } + + private func performDelete(_ session: SessionBackup) { + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + + let controller = textAlertController(context: context, title: "SessionBackup.DeleteSingle.Title".i18n(lang), text: "SessionBackup.DeleteSingle.Text".i18n(lang, args: "\(session.name ?? "\(session.userId)")"), actions: [ + TextAlertAction(type: .destructiveAction, title: presentationData.strings.Common_Delete, action: { + let controller = OverlayStatusController(theme: presentationData.theme, type: .loading(cancelled: nil)) + wrapperController?.present(controller, in: .window(.root), with: nil) + do { + try KeychainBackupManager.shared.deleteSession(for: "\(session.peerIdInternal)") + withAnimation { + sessions = getBackedSessions() + } + controller.dismiss() + } catch let e { + SGLogger.shared.log("SessionBackup", "Error deleting session: \(e)") + } + }), + TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_Cancel, action: {}) + ]) + + wrapperController?.present(controller, in: .window(.root), with: nil) + } + + + private func performRemoveSessionFromApp(session: SessionBackup) { + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + + let controller = textAlertController(context: context, title: "SessionBackup.RemoveFromApp.Title".i18n(lang), text: "SessionBackup.RemoveFromApp.Text".i18n(lang, args: "\(session.name ?? "\(session.userId)")"), actions: [ + TextAlertAction(type: .destructiveAction, title: presentationData.strings.Common_Delete, action: { + let controller = OverlayStatusController(theme: presentationData.theme, type: .loading(cancelled: nil)) + wrapperController?.present(controller, in: .window(.root), with: nil) + + let signal = context.sharedContext.accountManager.accountRecords() + |> take(1) + |> deliverOnMainQueue + + let _ = signal.start(next: { [weak controller] view in + + // Find record to delete + let accountRecord = view.records.first { record in + var userId: Int64 = 0 + for attribute in record.attributes { + if case let .backupData(backupData) = attribute { + userId = backupData.data?.peerId ?? 0 + } + } + return userId == session.peerIdInternal + } + + if let record = accountRecord { + let deleteSignal = context.sharedContext.accountManager.transaction { transaction -> Void in + transaction.updateRecord(record.id, { _ in return nil}) + } + |> deliverOnMainQueue + + let _ = deleteSignal.start(next: { + withAnimation { + sessions = getBackedSessions() + } + controller?.dismiss() + }) + } else { + controller?.dismiss() + } + }) + + }), + TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_Cancel, action: {}) + ]) + + wrapperController?.present(controller, in: .window(.root), with: nil) + } + + + var body: some View { + List { + Section() { + Button(action: performBackup) { + HStack { + Image(systemName: "key.fill") + .frame(width: 30) + Text("SessionBackup.Actions.Backup".i18n(lang)) + Spacer() + } + } + + Button(action: performRestore) { + HStack { + Image(systemName: "arrow.2.circlepath") + .frame(width: 30) + Text("SessionBackup.Actions.Restore".i18n(lang)) + Spacer() + } + } + + Button(action: performDeleteAll) { + HStack { + Image(systemName: "trash") + .frame(width: 30) + Text("SessionBackup.Actions.DeleteAll".i18n(lang)) + } + } + .foregroundColor(.red) + + } + + Text("SessionBackup.Notice".i18n(lang)) + .font(.caption) + .foregroundColor(.secondary) + + Section(header: Text("SessionBackup.Sessions.Title".i18n(lang))) { + ForEach(sessions, id: \.peerIdInternal) { session in + SessionBackupRow( + backup: session, + isLoggedIn: loggedInPeerIDs.contains(session.peerIdInternal) + ) + .contextMenu { + Button(action: { + performDelete(session) + }, label: { + HStack(spacing: 4) { + Text("SessionBackup.Actions.DeleteOne".i18n(lang)) + Image(systemName: "trash") + } + }) + Button(action: { + performRemoveSessionFromApp(session: session) + }, label: { + + HStack(spacing: 4) { + Text("SessionBackup.Actions.RemoveFromApp".i18n(lang)) + Image(systemName: "trash") + } + }) + } + } +// .onDelete { indexSet in +// performDelete(indexSet) +// } + } + } + .onAppear { + withAnimation { + sessions = getBackedSessions() + } + + let accountsSignal = context.sharedContext.accountManager.accountRecords() + |> deliverOnMainQueue + + loggedInAccountsDisposable = accountsSignal.start(next: { view in + var result: [Int64] = [] + for record in view.records { + var isLoggedOut: Bool = false + var userId: Int64 = 0 + for attribute in record.attributes { + if case .loggedOut = attribute { + isLoggedOut = true + } else if case let .backupData(backupData) = attribute { + userId = backupData.data?.peerId ?? 0 + } + } + + if !isLoggedOut && userId != 0 { + result.append(userId) + } + } + + SGLogger.shared.log("SessionBackup", "Logged in accounts: \(result)") + if loggedInPeerIDs != result { + SGLogger.shared.log("SessionBackup", "Updating logged in accounts: \(result)") + loggedInPeerIDs = result + } + }) + + } + .onDisappear { + loggedInAccountsDisposable?.dispose() + } + } + +} + + +func getBackedSessions() -> [SessionBackup] { + var sessions: [SessionBackup] = [] + do { + let backupSessionsData = try KeychainBackupManager.shared.getAllSessons() + for sessionBackupData in backupSessionsData { + do { + let backup = try JSONDecoder().decode(SessionBackup.self, from: sessionBackupData) + sessions.append(backup) + } catch let e { + SGLogger.shared.log("SessionBackup", "IMPORT ERROR: \(e)") + } + } + } catch let e { + SGLogger.shared.log("SessionBackup", "Error getting all sessions: \(e)") + } + return sessions +} + + +func backupSessionsFromView(_ view: AccountRecordsView, accountsWithInfo: [AccountWithInfo] = []) { + var recordsToBackup: [Int64: AccountRecord] = [:] + for record in view.records { + var sortOrder: Int32 = 0 + var isLoggedOut: Bool = false + var isTestingEnvironment: Bool = false + var peerId: Int64 = 0 + for attribute in record.attributes { + if case let .sortOrder(value) = attribute { + sortOrder = value.order + } else if case .loggedOut = attribute { + isLoggedOut = true + } else if case let .environment(environment) = attribute, case .test = environment.environment { + isTestingEnvironment = true + } else if case let .backupData(backupData) = attribute { + peerId = backupData.data?.peerId ?? 0 + } + } + let _ = sortOrder + let _ = isTestingEnvironment + + if !isLoggedOut && peerId != 0 { + recordsToBackup[peerId] = record + } + } + + for (peerId, record) in recordsToBackup { + var backupName: String? = nil + if let accountWithInfo = accountsWithInfo.first(where: { $0.peer.id == PeerId(peerId) }) { + if let user = accountWithInfo.peer as? TelegramUser { + if let username = user.username { + backupName = "@\(username)" + } else { + backupName = user.nameOrPhone + } + } + } + let backup = SessionBackup(name: backupName, accountRecord: record) + do { + let data = try JSONEncoder().encode(backup) + try KeychainBackupManager.shared.saveSession(id: "\(backup.peerIdInternal)", data) + } catch let e { + SGLogger.shared.log("SessionBackup", "BACKUP ERROR: \(e)") + } + } +} + + +@available(iOS 13.0, *) +public func sgSessionBackupManagerController(context: AccountContext, presentationData: PresentationData? = nil) -> ViewController { + let theme = presentationData?.theme ?? (UITraitCollection.current.userInterfaceStyle == .dark ? defaultDarkColorPresentationTheme : defaultPresentationTheme) + let strings = presentationData?.strings ?? defaultPresentationStrings + + let legacyController = LegacySwiftUIController( + presentation: .navigation, + theme: theme, + strings: strings + ) + legacyController.statusBar.statusBarStyle = theme.rootController + .statusBarStyle.style + legacyController.title = "SessionBackup.Title".i18n(strings.baseLanguageCode) + + let swiftUIView = SGSwiftUIView( + legacyController: legacyController, + manageSafeArea: true, + content: { + SessionBackupManagerView(wrapperController: legacyController, context: context) + } + ) + let controller = UIHostingController(rootView: swiftUIView, ignoreSafeArea: true) + legacyController.bind(controller: controller) + + return legacyController +} diff --git a/Swiftgram/SGRecentSessionApiId/BUILD b/Swiftgram/SGRecentSessionApiId/BUILD new file mode 100644 index 00000000..30754866 --- /dev/null +++ b/Swiftgram/SGRecentSessionApiId/BUILD @@ -0,0 +1,9 @@ +filegroup( + name = "SGRecentSessionApiId", + srcs = glob([ + "Sources/**/*.swift", + ]), + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGRecentSessionApiId/Sources/SGRecentSessionApiId.swift b/Swiftgram/SGRecentSessionApiId/Sources/SGRecentSessionApiId.swift new file mode 100644 index 00000000..05bbd09e --- /dev/null +++ b/Swiftgram/SGRecentSessionApiId/Sources/SGRecentSessionApiId.swift @@ -0,0 +1,16 @@ +import Foundation +import BuildConfig +import TelegramCore + +public enum SGRecentSessionApiId { + public static func string(for session: RecentAccountSession) -> String? { + guard !session.isCurrent, let baseAppBundleId = Bundle.main.bundleIdentifier else { + return nil + } + let buildConfig = BuildConfig(baseAppBundleId: baseAppBundleId) + guard buildConfig.apiId != session.apiId else { + return nil + } + return String(session.apiId) + } +} diff --git a/Swiftgram/SGRecentSessionApiId/Sources/SGRecentSessionApiIdItem.swift b/Swiftgram/SGRecentSessionApiId/Sources/SGRecentSessionApiIdItem.swift new file mode 100644 index 00000000..11e8688e --- /dev/null +++ b/Swiftgram/SGRecentSessionApiId/Sources/SGRecentSessionApiIdItem.swift @@ -0,0 +1,70 @@ +import UIKit +import Display +import ComponentFlow +import TelegramPresentationData +import MultilineTextComponent +import ListActionItemComponent +import UndoUI + +func sgRecentSessionApiIdItem( + apiIdString: String, + theme: PresentationTheme, + presentationData: PresentationData, + strings: PresentationStrings, + controller: RecentSessionScreen? +) -> AnyComponentWithIdentity { + let sgApiIdTextAttribute = NSAttributedString.Key(rawValue: "SGRecentSessionApiIdAttribute") + let sgApiIdText = NSMutableAttributedString( + string: apiIdString, + font: Font.regular(presentationData.listsFontSize.itemListBaseFontSize), + textColor: theme.list.itemSecondaryTextColor + ) + sgApiIdText.addAttribute(sgApiIdTextAttribute, value: true, range: NSRange(location: 0, length: sgApiIdText.length)) + + return AnyComponentWithIdentity(id: "api_id", component: AnyComponent( + ListActionItemComponent( + theme: theme, + style: .glass, + title: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: "api_id", + font: Font.regular(17.0), + textColor: theme.list.itemPrimaryTextColor + )), + maximumNumberOfLines: 1 + )), + accessory: .custom(ListActionItemComponent.CustomAccessory( + component: AnyComponentWithIdentity( + id: "info", + component: AnyComponent(MultilineTextComponent( + text: .plain(sgApiIdText), + maximumNumberOfLines: 1, + highlightColor: theme.list.itemAccentColor.withMultipliedAlpha(0.15), + highlightAction: { attributes in + if let _ = attributes[sgApiIdTextAttribute] { + return sgApiIdTextAttribute + } + return nil + }, + longTapAction: { [weak controller] attributes, _ in + guard let _ = attributes[sgApiIdTextAttribute] else { + return + } + UIPasteboard.general.string = apiIdString + controller?.present(UndoOverlayController( + presentationData: presentationData, + content: .copy(text: strings.Conversation_TextCopied), + elevatedLayout: false, + animateInAsReplacement: false, + action: { _ in return false } + ), in: .current) + } + )) + ), + insets: UIEdgeInsets(top: 0.0, left: 8.0, bottom: 0.0, right: 14.0), + isInteractive: true + )), + action: nil + ) + )) +} diff --git a/Swiftgram/SGRegDate/BUILD b/Swiftgram/SGRegDate/BUILD new file mode 100644 index 00000000..ff5f233e --- /dev/null +++ b/Swiftgram/SGRegDate/BUILD @@ -0,0 +1,27 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGRegDate", + module_name = "SGRegDate", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//Swiftgram/SGRegDateScheme:SGRegDateScheme", + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//Swiftgram/SGAPI:SGAPI", + "//Swiftgram/SGAPIToken:SGAPIToken", + "//Swiftgram/SGDeviceToken:SGDeviceToken", + "//Swiftgram/SGStrings:SGStrings", + + "//submodules/AccountContext:AccountContext", + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + "//submodules/TelegramPresentationData:TelegramPresentationData", + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGRegDate/Sources/SGRegDate.swift b/Swiftgram/SGRegDate/Sources/SGRegDate.swift new file mode 100644 index 00000000..0be00196 --- /dev/null +++ b/Swiftgram/SGRegDate/Sources/SGRegDate.swift @@ -0,0 +1,45 @@ +import Foundation +import SwiftSignalKit +import TelegramPresentationData + +import SGLogging +import SGStrings +import SGRegDateScheme +import AccountContext +import SGSimpleSettings +import SGAPI +import SGAPIToken +import SGDeviceToken + +public enum RegDateError { + case generic +} + +public func getRegDate(context: AccountContext, peerId: Int64) -> Signal { + return Signal { subscriber in + var tokensRequestSignal: Disposable? = nil + var apiRequestSignal: Disposable? = nil + if let regDateData = SGSimpleSettings.shared.regDateCache[String(peerId)], let regDate = try? JSONDecoder().decode(RegDate.self, from: regDateData), regDate.validUntil == 0 || regDate.validUntil > Int64(Date().timeIntervalSince1970) { + subscriber.putNext(regDate) + subscriber.putCompletion() + } else if SGSimpleSettings.shared.showRegDate { + tokensRequestSignal = combineLatest(getDeviceToken() |> mapError { error -> Void in SGLogger.shared.log("SGDeviceToken", "Error generating token: \(error)"); return Void() } , getSGApiToken(context: context) |> mapError { _ -> Void in return Void() }).start(next: { deviceToken, apiToken in + apiRequestSignal = getSGAPIRegDate(token: apiToken, deviceToken: deviceToken, userId: peerId).start(next: { regDate in + if let data = try? JSONEncoder().encode(regDate) { + SGSimpleSettings.shared.regDateCache[String(peerId)] = data + } + subscriber.putNext(regDate) + subscriber.putCompletion() + }) + }) + } else { + subscriber.putNext(nil) + subscriber.putCompletion() + } + + return ActionDisposable { + tokensRequestSignal?.dispose() + apiRequestSignal?.dispose() + } + } +} diff --git a/Swiftgram/SGRegDateScheme/BUILD b/Swiftgram/SGRegDateScheme/BUILD new file mode 100644 index 00000000..008f8265 --- /dev/null +++ b/Swiftgram/SGRegDateScheme/BUILD @@ -0,0 +1,17 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGRegDateScheme", + module_name = "SGRegDateScheme", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGRegDateScheme/Sources/File.swift b/Swiftgram/SGRegDateScheme/Sources/File.swift new file mode 100644 index 00000000..a972377e --- /dev/null +++ b/Swiftgram/SGRegDateScheme/Sources/File.swift @@ -0,0 +1,7 @@ +import Foundation + +public struct RegDate: Codable { + public let from: Int64 + public let to: Int64 + public let validUntil: Int64 +} diff --git a/Swiftgram/SGRequests/BUILD b/Swiftgram/SGRequests/BUILD new file mode 100644 index 00000000..979d84f3 --- /dev/null +++ b/Swiftgram/SGRequests/BUILD @@ -0,0 +1,18 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGRequests", + module_name = "SGRequests", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit" + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGRequests/Sources/File.swift b/Swiftgram/SGRequests/Sources/File.swift new file mode 100644 index 00000000..19dfa3da --- /dev/null +++ b/Swiftgram/SGRequests/Sources/File.swift @@ -0,0 +1,72 @@ +import Foundation +import SwiftSignalKit + + +public func requestsDownload(url: URL) -> Signal<(Data, URLResponse?), Error?> { + return Signal { subscriber in + let completed = Atomic(value: false) + + let downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { location, response, error in + let _ = completed.swap(true) + if let location = location, let data = try? Data(contentsOf: location) { + subscriber.putNext((data, response)) + subscriber.putCompletion() + } else { + subscriber.putError(error) + } + }) + downloadTask.resume() + + return ActionDisposable { + if !completed.with({ $0 }) { + downloadTask.cancel() + } + } + } +} + +public func requestsGet(url: URL) -> Signal<(Data, URLResponse?), Error?> { + return Signal { subscriber in + let completed = Atomic(value: false) + + let urlTask = URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in + let _ = completed.swap(true) + if let strongData = data { + subscriber.putNext((strongData, response)) + subscriber.putCompletion() + } else { + subscriber.putError(error) + } + }) + urlTask.resume() + + return ActionDisposable { + if !completed.with({ $0 }) { + urlTask.cancel() + } + } + } +} + + +public func requestsCustom(request: URLRequest) -> Signal<(Data, URLResponse?), Error?> { + return Signal { subscriber in + let completed = Atomic(value: false) + let urlTask = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in + _ = completed.swap(true) + if let strongData = data { + subscriber.putNext((strongData, response)) + subscriber.putCompletion() + } else { + subscriber.putError(error) + } + }) + urlTask.resume() + + return ActionDisposable { + if !completed.with({ $0 }) { + urlTask.cancel() + } + } + } +} diff --git a/Swiftgram/SGSettingsBundle/BUILD b/Swiftgram/SGSettingsBundle/BUILD new file mode 100644 index 00000000..e0d37a3c --- /dev/null +++ b/Swiftgram/SGSettingsBundle/BUILD @@ -0,0 +1,10 @@ +load("@build_bazel_rules_apple//apple:resources.bzl", "apple_bundle_import") + +apple_bundle_import( + name = "SGSettingsBundle", + bundle_imports = glob([ + "Settings.bundle/*", + "Settings.bundle/**/*", + ]), + visibility = ["//visibility:public"] +) \ No newline at end of file diff --git a/Swiftgram/SGSettingsBundle/Settings.bundle/Root.plist b/Swiftgram/SGSettingsBundle/Settings.bundle/Root.plist new file mode 100644 index 00000000..148a2283 --- /dev/null +++ b/Swiftgram/SGSettingsBundle/Settings.bundle/Root.plist @@ -0,0 +1,47 @@ + + + + + StringsTable + Root + PreferenceSpecifiers + + + Type + PSGroupSpecifier + FooterText + Reset.Notice + Title + Reset.Title + + + Type + PSToggleSwitchSpecifier + Title + Reset.Toggle + Key + sg_db_reset + DefaultValue + + + + Type + PSGroupSpecifier + FooterText + HardReset.Notice + Title + HardReset.Title + + + Type + PSToggleSwitchSpecifier + Title + HardReset.Toggle + Key + sg_db_hard_reset + DefaultValue + + + + + diff --git a/Swiftgram/SGSettingsBundle/Settings.bundle/en.lproj/Root.strings b/Swiftgram/SGSettingsBundle/Settings.bundle/en.lproj/Root.strings new file mode 100644 index 00000000..e40aa8c2 --- /dev/null +++ b/Swiftgram/SGSettingsBundle/Settings.bundle/en.lproj/Root.strings @@ -0,0 +1,8 @@ +/* A single strings file, whose title is specified in your preferences schema. The strings files provide the localized content to display to the user for each of your preferences. */ + +"Reset.Title" = "TROUBLESHOOTING"; +"Reset.Toggle" = "Reset Metadata"; +"Reset.Notice" = "Use in case you're stuck and can't open the app. This WILL NOT log out your accounts, but all secret chats will be lost."; +"HardReset.Title" = ""; +"HardReset.Toggle" = "Reset All"; +"HardReset.Notice" = "Clears metadata, cached messages and media for all accounts. This should not log out your accounts, but proceed at YOUR OWN RISK. All secret chats will be lost."; \ No newline at end of file diff --git a/Swiftgram/SGSettingsBundle/Settings.bundle/ru.lproj/Root.strings b/Swiftgram/SGSettingsBundle/Settings.bundle/ru.lproj/Root.strings new file mode 100644 index 00000000..a0f39d27 --- /dev/null +++ b/Swiftgram/SGSettingsBundle/Settings.bundle/ru.lproj/Root.strings @@ -0,0 +1,6 @@ +"Reset.Title" = "РЕШЕНИЕ ПРОБЛЕМ"; +"Reset.Toggle" = "Сбросить Метаданные"; +"Reset.Notice" = "Используйте, если приложение вылетает или не загружается. Эта опция НЕ СБРАСЫВАЕТ ваши аккаунты, но удалит все секретные чаты."; +"HardReset.Title" = ""; +"HardReset.Toggle" = "Сбросить Всё"; +"HardReset.Notice" = "Сбрасывает метаданные, кэшированные сообщения и медиа для всех аккаунтов. Эта опция не должна разлогинить ваши аккаунты, но используйте её на СВОЙ СТРАХ И РИСК. Все секретные чаты удалятся."; \ No newline at end of file diff --git a/Swiftgram/SGSettingsUI/BUILD b/Swiftgram/SGSettingsUI/BUILD new file mode 100644 index 00000000..dc1613e7 --- /dev/null +++ b/Swiftgram/SGSettingsUI/BUILD @@ -0,0 +1,43 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +filegroup( + name = "SGUIAssets", + srcs = glob(["Images.xcassets/**"]), + visibility = ["//visibility:public"], +) + +swift_library( + name = "SGSettingsUI", + module_name = "SGSettingsUI", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//Swiftgram/SGItemListUI:SGItemListUI", + "//Swiftgram/SGLogging:SGLogging", + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//Swiftgram/SGStrings:SGStrings", +# "//Swiftgram/SGAPI:SGAPI", + "//Swiftgram/SGAPIToken:SGAPIToken", + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + "//submodules/Display:Display", + "//submodules/Postbox:Postbox", + "//submodules/TelegramCore:TelegramCore", + "//submodules/MtProtoKit:MtProtoKit", + "//submodules/TelegramPresentationData:TelegramPresentationData", + "//submodules/TelegramUIPreferences:TelegramUIPreferences", + "//submodules/ItemListUI:ItemListUI", + "//submodules/PresentationDataUtils:PresentationDataUtils", + "//submodules/OverlayStatusController:OverlayStatusController", + "//submodules/AccountContext:AccountContext", + "//submodules/AppBundle:AppBundle", + "//submodules/TelegramUI/Components/Settings/PeerNameColorScreen", + "//submodules/UndoUI:UndoUI", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGSettingsUI/Images.xcassets/Contents.json b/Swiftgram/SGSettingsUI/Images.xcassets/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/Swiftgram/SGSettingsUI/Images.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swiftgram/SGSettingsUI/Images.xcassets/SaveToCloud.imageset/Contents.json b/Swiftgram/SGSettingsUI/Images.xcassets/SaveToCloud.imageset/Contents.json new file mode 100644 index 00000000..526cf46d --- /dev/null +++ b/Swiftgram/SGSettingsUI/Images.xcassets/SaveToCloud.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "ic_lt_savetocloud.pdf" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Swiftgram/SGSettingsUI/Images.xcassets/SaveToCloud.imageset/ic_lt_savetocloud.pdf b/Swiftgram/SGSettingsUI/Images.xcassets/SaveToCloud.imageset/ic_lt_savetocloud.pdf new file mode 100644 index 00000000..ed4efd96 Binary files /dev/null and b/Swiftgram/SGSettingsUI/Images.xcassets/SaveToCloud.imageset/ic_lt_savetocloud.pdf differ diff --git a/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramContextMenu.imageset/Contents.json b/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramContextMenu.imageset/Contents.json new file mode 100644 index 00000000..6fb419fc --- /dev/null +++ b/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramContextMenu.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "swiftgram_context_menu.pdf" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramContextMenu.imageset/swiftgram_context_menu.pdf b/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramContextMenu.imageset/swiftgram_context_menu.pdf new file mode 100644 index 00000000..30789ecb --- /dev/null +++ b/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramContextMenu.imageset/swiftgram_context_menu.pdf @@ -0,0 +1,81 @@ +%PDF-1.7 + +1 0 obj + << >> +endobj + +2 0 obj + << /Length 3 0 R >> +stream +/DeviceRGB CS +/DeviceRGB cs +q +1.000000 0.000000 -0.000000 1.000000 4.000000 2.964844 cm +0.000000 0.000000 0.000000 scn +15.076375 10.766671 m +15.473662 11.399487 14.937258 12.204764 14.200223 12.081993 c +9.059459 11.225675 l +8.855769 11.191745 8.670359 11.348825 8.670359 11.555322 c +8.670359 18.524288 l +8.670359 19.289572 7.652856 19.554642 7.279467 18.886631 c +1.036950 7.718488 l +0.658048 7.040615 1.293577 6.244993 2.038416 6.464749 c +9.378864 8.630468 l +9.637225 8.706696 9.814250 8.373775 9.606588 8.202201 c +6.918006 5.980853 l +6.462659 5.604639 6.199009 5.044809 6.199009 4.454151 c +6.199009 -0.793964 l +6.199009 -1.539309 7.174314 -1.820084 7.570620 -1.188831 c +15.076375 10.766671 l +h +f* +n +Q + +endstream +endobj + +3 0 obj + 702 +endobj + +4 0 obj + << /Annots [] + /Type /Page + /MediaBox [ 0.000000 0.000000 24.000000 24.000000 ] + /Resources 1 0 R + /Contents 2 0 R + /Parent 5 0 R + >> +endobj + +5 0 obj + << /Kids [ 4 0 R ] + /Count 1 + /Type /Pages + >> +endobj + +6 0 obj + << /Pages 5 0 R + /Type /Catalog + >> +endobj + +xref +0 7 +0000000000 65535 f +0000000010 00000 n +0000000034 00000 n +0000000792 00000 n +0000000814 00000 n +0000000987 00000 n +0000001061 00000 n +trailer +<< /ID [ (some) (id) ] + /Root 6 0 R + /Size 7 +>> +startxref +1120 +%%EOF \ No newline at end of file diff --git a/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramPro.imageset/Contents.json b/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramPro.imageset/Contents.json new file mode 100644 index 00000000..7506e639 --- /dev/null +++ b/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramPro.imageset/Contents.json @@ -0,0 +1,13 @@ +{ + "images" : [ + { + "filename" : "SwiftgramPro.pdf", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } + } + \ No newline at end of file diff --git a/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramPro.imageset/SwiftgramPro.pdf b/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramPro.imageset/SwiftgramPro.pdf new file mode 100644 index 00000000..fb4264fd Binary files /dev/null and b/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramPro.imageset/SwiftgramPro.pdf differ diff --git a/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramSettings.imageset/Contents.json b/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramSettings.imageset/Contents.json new file mode 100644 index 00000000..1bf20b6b --- /dev/null +++ b/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramSettings.imageset/Contents.json @@ -0,0 +1,13 @@ +{ + "images" : [ + { + "filename" : "Swiftgram.pdf", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } + } + \ No newline at end of file diff --git a/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramSettings.imageset/Swiftgram.pdf b/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramSettings.imageset/Swiftgram.pdf new file mode 100644 index 00000000..6abd681b --- /dev/null +++ b/Swiftgram/SGSettingsUI/Images.xcassets/SwiftgramSettings.imageset/Swiftgram.pdf @@ -0,0 +1,242 @@ +%PDF-1.7 + +1 0 obj + << /Length 2 0 R + /Range [ 0.000000 1.000000 0.000000 1.000000 0.000000 1.000000 ] + /Domain [ 0.000000 1.000000 ] + /FunctionType 4 + >> +stream +{ 1.000000 exch 0.764706 exch 0.415686 exch dup 0.000000 gt { exch pop exch pop exch pop dup 0.000000 sub -0.098039 mul 1.000000 add exch dup 0.000000 sub -0.764706 mul 0.764706 add exch dup 0.000000 sub -0.415686 mul 0.415686 add exch } if dup 1.000000 gt { exch pop exch pop exch pop 0.901961 exch 0.000000 exch 0.000000 exch } if pop } +endstream +endobj + +2 0 obj + 339 +endobj + +3 0 obj + << /Type /XObject + /Length 4 0 R + /Group << /Type /Group + /S /Transparency + >> + /Subtype /Form + /Resources << /Pattern << /P1 << /Matrix [ -625.250061 -1215.250000 1215.250000 -625.250061 -946.303711 1659.980225 ] + /Shading << /Coords [ 0.000000 0.000000 1.000000 0.000000 ] + /ColorSpace /DeviceRGB + /Function 1 0 R + /Domain [ 0.000000 1.000000 ] + /ShadingType 2 + /Extend [ true true ] + >> + /PatternType 2 + /Type /Pattern + >> >> >> + /BBox [ 0.000000 0.000000 512.000000 512.000000 ] + >> +stream +/DeviceRGB CS +/DeviceRGB cs +q +1.000000 0.000000 -0.000000 1.000000 0.000000 0.000000 cm +/Pattern cs +/P1 scn +0.000000 320.853333 m +0.000000 387.754669 0.000000 421.205322 12.970667 446.805328 c +24.405334 469.333344 42.666668 487.594666 65.194672 499.029327 c +90.794670 512.000000 124.245338 512.000000 191.146667 512.000000 c +320.853333 512.000000 l +387.754669 512.000000 421.205353 512.000000 446.805359 499.029327 c +469.333374 487.594666 487.594696 469.333344 499.029358 446.805328 c +512.000000 421.205322 512.000000 387.754669 512.000000 320.853333 c +512.000000 191.146667 l +512.000000 124.245331 512.000000 90.794647 499.029358 65.194641 c +487.594696 42.666626 469.333374 24.405304 446.805359 12.970642 c +421.205353 0.000000 387.754669 0.000000 320.853333 0.000000 c +191.146667 0.000000 l +124.245338 0.000000 90.794670 0.000000 65.194672 12.970642 c +42.666668 24.405304 24.405334 42.666626 12.970667 65.194641 c +0.000000 90.794647 0.000000 124.245331 0.000000 191.146667 c +0.000000 320.853333 l +h +f +n +Q +q +1.000000 0.000000 -0.000000 1.000000 119.500000 103.400391 cm +1.000000 1.000000 1.000000 scn +256.015533 182.826599 m +262.761963 193.572601 253.653152 207.247192 241.137390 205.162399 c +153.840836 190.621048 l +150.381927 190.044891 147.233429 192.712296 147.233429 196.218872 c +147.233429 314.560455 l +147.233429 327.555908 129.954987 332.057098 123.614365 320.713440 c +17.608702 131.064743 l +11.174477 119.553635 21.966566 106.042999 34.614845 109.774734 c +159.264740 146.551285 l +163.652023 147.845703 166.658112 142.192291 163.131760 139.278763 c +117.476318 101.557587 l +109.743965 95.169006 105.266861 85.662384 105.266861 75.632263 c +105.266861 -13.487152 l +105.266861 -26.143982 121.828712 -30.911926 128.558456 -20.192505 c +256.015533 182.826599 l +h +f* +n +Q + +endstream +endobj + +4 0 obj + 1771 +endobj + +5 0 obj + << /Length 6 0 R + /Range [ 0.000000 1.000000 0.000000 1.000000 0.000000 1.000000 ] + /Domain [ 0.000000 1.000000 ] + /FunctionType 4 + >> +stream +{ 1.000000 exch 0.764706 exch 0.415686 exch dup 0.000000 gt { exch pop exch pop exch pop dup 0.000000 sub -0.098039 mul 1.000000 add exch dup 0.000000 sub -0.764706 mul 0.764706 add exch dup 0.000000 sub -0.415686 mul 0.415686 add exch } if dup 1.000000 gt { exch pop exch pop exch pop 0.901961 exch 0.000000 exch 0.000000 exch } if pop } +endstream +endobj + +6 0 obj + 339 +endobj + +7 0 obj + << /Type /XObject + /Length 8 0 R + /Group << /Type /Group + /S /Transparency + >> + /Subtype /Form + /Resources << /Pattern << /P1 << /Matrix [ -625.250061 -1215.250000 1215.250000 -625.250061 -946.303711 1659.980225 ] + /Shading << /Coords [ 0.000000 0.000000 1.000000 0.000000 ] + /ColorSpace /DeviceRGB + /Function 5 0 R + /Domain [ 0.000000 1.000000 ] + /ShadingType 2 + /Extend [ true true ] + >> + /PatternType 2 + /Type /Pattern + >> >> >> + /BBox [ 0.000000 0.000000 512.000000 512.000000 ] + >> +stream +/DeviceRGB CS +/DeviceRGB cs +q +1.000000 0.000000 -0.000000 1.000000 0.000000 0.000000 cm +/Pattern cs +/P1 scn +0.000000 320.853333 m +0.000000 387.754669 0.000000 421.205322 12.970667 446.805328 c +24.405334 469.333344 42.666668 487.594666 65.194672 499.029327 c +90.794670 512.000000 124.245338 512.000000 191.146667 512.000000 c +320.853333 512.000000 l +387.754669 512.000000 421.205353 512.000000 446.805359 499.029327 c +469.333374 487.594666 487.594696 469.333344 499.029358 446.805328 c +512.000000 421.205322 512.000000 387.754669 512.000000 320.853333 c +512.000000 191.146667 l +512.000000 124.245331 512.000000 90.794647 499.029358 65.194641 c +487.594696 42.666626 469.333374 24.405304 446.805359 12.970642 c +421.205353 0.000000 387.754669 0.000000 320.853333 0.000000 c +191.146667 0.000000 l +124.245338 0.000000 90.794670 0.000000 65.194672 12.970642 c +42.666668 24.405304 24.405334 42.666626 12.970667 65.194641 c +0.000000 90.794647 0.000000 124.245331 0.000000 191.146667 c +0.000000 320.853333 l +h +f +n +Q + +endstream +endobj + +8 0 obj + 1006 +endobj + +9 0 obj + << /XObject << /X1 3 0 R >> + /ExtGState << /E1 << /SMask << /Type /Mask + /G 7 0 R + /S /Alpha + >> + /Type /ExtGState + >> >> + >> +endobj + +10 0 obj + << /Length 11 0 R >> +stream +/DeviceRGB CS +/DeviceRGB cs +q +/E1 gs +/X1 Do +Q + +endstream +endobj + +11 0 obj + 46 +endobj + +12 0 obj + << /Annots [] + /Type /Page + /MediaBox [ 0.000000 0.000000 512.000000 512.000000 ] + /Resources 9 0 R + /Contents 10 0 R + /Parent 13 0 R + >> +endobj + +13 0 obj + << /Kids [ 12 0 R ] + /Count 1 + /Type /Pages + >> +endobj + +14 0 obj + << /Pages 13 0 R + /Type /Catalog + >> +endobj + +xref +0 15 +0000000000 65535 f +0000000010 00000 n +0000000533 00000 n +0000000555 00000 n +0000003331 00000 n +0000003354 00000 n +0000003877 00000 n +0000003899 00000 n +0000005910 00000 n +0000005933 00000 n +0000006231 00000 n +0000006335 00000 n +0000006357 00000 n +0000006535 00000 n +0000006611 00000 n +trailer +<< /ID [ (some) (id) ] + /Root 14 0 R + /Size 15 +>> +startxref +6672 +%%EOF \ No newline at end of file diff --git a/Swiftgram/SGSettingsUI/Sources/SGSettingsController.swift b/Swiftgram/SGSettingsUI/Sources/SGSettingsController.swift new file mode 100644 index 00000000..d63b2baa --- /dev/null +++ b/Swiftgram/SGSettingsUI/Sources/SGSettingsController.swift @@ -0,0 +1,769 @@ +// MARK: Swiftgram +import SGLogging +import SGSimpleSettings +import SGStrings +import SGAPIToken + +import SGItemListUI +import Foundation +import UIKit +import Display +import SwiftSignalKit +import Postbox +import TelegramCore +import MtProtoKit +import MessageUI +import TelegramPresentationData +import TelegramUIPreferences +import ItemListUI +import PresentationDataUtils +import OverlayStatusController +import AccountContext +import AppBundle +import WebKit +import PeerNameColorScreen +import UndoUI + + +private enum SGControllerSection: Int32, SGItemListSection { + case search + case trending + case content + case tabs + case folders + case chatList + case profiles + case stories + case translation + case voiceMessages + case calls + case photo + case stickers + case videoNotes + case contextMenu + case accountColors + case other +} + +private enum SGBoolSetting: String { + case hidePhoneInSettings + case showTabNames + case showContactsTab + case showCallsTab + case wideTabBar + case foldersAtBottom + case startTelescopeWithRearCam + case hideStories + case uploadSpeedBoost + case showProfileId + case warnOnStoriesOpen + case sendWithReturnKey + case rememberLastFolder + case sendLargePhotos + case storyStealthMode + case disableSwipeToRecordStory + case disableDeleteChatSwipeOption + case hideReactions + case showRepostToStory + case contextShowSelectFromUser + case contextShowSaveToCloud + case contextShowHideForwardName + case contextShowRestrict + case contextShowReport + case contextShowReply + case contextShowPin + case contextShowSaveMedia + case contextShowMessageReplies + case contextShowJson + case disableScrollToNextChannel + case disableScrollToNextTopic + case disableChatSwipeOptions + case disableGalleryCamera + case disableGalleryCameraPreview + case disableSendAsButton + case disableSnapDeletionEffect + case stickerTimestamp + case hideRecordingButton + case hideTabBar + case showDC + case showCreationDate + case showRegDate + case compactChatList + case compactMessagePreview + case compactFolderNames + case allChatsHidden + case defaultEmojisFirst + case messageDoubleTapActionOutgoingEdit + case wideChannelPosts + case forceEmojiTab + case forceBuiltInMic + case secondsInMessages + case hideChannelBottomButton + case confirmCalls + case swipeForVideoPIP + case enableVoipTcp + case nyStyleSnow + case nyStyleLightning + case tabBarSearchEnabled +} + +private enum SGOneFromManySetting: String { + case nyStyle + case bottomTabStyle + case downloadSpeedBoost + case allChatsTitleLengthOverride +// case allChatsFolderPositionOverride + case translationBackend + case transcriptionBackend +} + +private enum SGSliderSetting: String { + case accountColorsSaturation + case outgoingPhotoQuality + case stickerSize +} + +private enum SGDisclosureLink: String { + case contentSettings + case languageSettings +} + +private struct PeerNameColorScreenState: Equatable { + var updatedNameColor: PeerNameColor? + var updatedBackgroundEmojiId: Int64? +} + +private struct SGSettingsControllerState: Equatable { + var searchQuery: String? +} + +private typealias SGControllerEntry = SGItemListUIEntry +private typealias SGControllerArguments = SGItemListArguments + +private func SGControllerEntries(presentationData: PresentationData, callListSettings: CallListSettings, experimentalUISettings: ExperimentalUISettings, appConfiguration _: AppConfiguration, nameColors: PeerNameColors, state: SGSettingsControllerState) -> [SGControllerEntry] { + + let lang = presentationData.strings.baseLanguageCode + let strings = presentationData.strings + let newStr = strings.Settings_New + var entries: [SGControllerEntry] = [] + + let id = SGItemListCounter() + + entries.append(.searchInput(id: id.count, section: .search, title: NSAttributedString(string: "🔍"), text: state.searchQuery ?? "", placeholder: strings.Common_Search)) + + + if SGSimpleSettings.shared.canUseNY { + entries.append(.header(id: id.count, section: .trending, text: i18n("Settings.NY.Header", lang), badge: newStr)) + entries.append(.toggle(id: id.count, section: .trending, settingName: .nyStyleSnow, value: SGSimpleSettings.shared.nyStyle == SGSimpleSettings.NYStyle.snow.rawValue, text: i18n("Settings.NY.Style.snow", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .trending, settingName: .nyStyleLightning, value: SGSimpleSettings.shared.nyStyle == SGSimpleSettings.NYStyle.lightning.rawValue, text: i18n("Settings.NY.Style.lightning", lang), enabled: true)) + // entries.append(.oneFromManySelector(id: id.count, section: .trending, settingName: .nyStyle, text: i18n("Settings.NY.Style", lang), value: i18n("Settings.NY.Style.\(SGSimpleSettings.shared.nyStyle)", lang), enabled: true)) + entries.append(.notice(id: id.count, section: .trending, text: i18n("Settings.NY.Notice", lang))) + } else { + id.increment(3) + } + + entries.append(.disclosure(id: id.count, section: .content, link: .contentSettings, text: i18n("Settings.ContentSettings", lang))) + + entries.append(.header(id: id.count, section: .tabs, text: i18n("Settings.Tabs.Header", lang), badge: nil)) + entries.append(.toggle(id: id.count, section: .tabs, settingName: .hideTabBar, value: SGSimpleSettings.shared.hideTabBar, text: i18n("Settings.Tabs.HideTabBar", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .tabs, settingName: .showContactsTab, value: callListSettings.showContactsTab, text: i18n("Settings.Tabs.ShowContacts", lang), enabled: !SGSimpleSettings.shared.hideTabBar)) + entries.append(.toggle(id: id.count, section: .tabs, settingName: .showCallsTab, value: callListSettings.showTab, text: strings.CallSettings_TabIcon, enabled: !SGSimpleSettings.shared.hideTabBar)) + entries.append(.toggle(id: id.count, section: .tabs, settingName: .showTabNames, value: SGSimpleSettings.shared.showTabNames, text: i18n("Settings.Tabs.ShowNames", lang), enabled: !SGSimpleSettings.shared.hideTabBar)) + entries.append(.toggle(id: id.count, section: .tabs, settingName: .tabBarSearchEnabled, value: SGSimpleSettings.shared.tabBarSearchEnabled, text: i18n("Settings.Tabs.SearchButton", lang), enabled: !SGSimpleSettings.shared.hideTabBar)) + entries.append(.toggle(id: id.count, section: .tabs, settingName: .wideTabBar, value: SGSimpleSettings.shared.wideTabBar, text: i18n("Settings.Tabs.WideTabBar", lang), enabled: !SGSimpleSettings.shared.hideTabBar)) + entries.append(.notice(id: id.count, section: .tabs, text: i18n("Settings.Tabs.WideTabBar.Notice", lang))) + + entries.append(.header(id: id.count, section: .folders, text: strings.Settings_ChatFolders.uppercased(), badge: nil)) + entries.append(.toggle(id: id.count, section: .folders, settingName: .foldersAtBottom, value: experimentalUISettings.foldersTabAtBottom, text: i18n("Settings.Folders.BottomTab", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .folders, settingName: .allChatsHidden, value: SGSimpleSettings.shared.allChatsHidden, text: i18n("Settings.Folders.AllChatsHidden", lang, strings.ChatList_Tabs_AllChats), enabled: true)) + #if DEBUG +// entries.append(.oneFromManySelector(id: id.count, section: .folders, settingName: .allChatsFolderPositionOverride, text: i18n("Settings.Folders.AllChatsPlacement", lang), value: i18n("Settings.Folders.AllChatsPlacement.\(SGSimpleSettings.shared.allChatsFolderPositionOverride)", lang), enabled: true)) + #endif + entries.append(.toggle(id: id.count, section: .folders, settingName: .compactFolderNames, value: SGSimpleSettings.shared.compactFolderNames, text: i18n("Settings.Folders.CompactNames", lang), enabled: true)) + entries.append(.oneFromManySelector(id: id.count, section: .folders, settingName: .allChatsTitleLengthOverride, text: i18n("Settings.Folders.AllChatsTitle", lang), value: i18n("Settings.Folders.AllChatsTitle.\(SGSimpleSettings.shared.allChatsTitleLengthOverride)", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .folders, settingName: .rememberLastFolder, value: SGSimpleSettings.shared.rememberLastFolder, text: i18n("Settings.Folders.RememberLast", lang), enabled: true)) + entries.append(.notice(id: id.count, section: .folders, text: i18n("Settings.Folders.RememberLast.Notice", lang))) + + entries.append(.header(id: id.count, section: .chatList, text: i18n("Settings.ChatList.Header", lang), badge: nil)) + entries.append(.toggle(id: id.count, section: .chatList, settingName: .compactChatList, value: SGSimpleSettings.shared.compactChatList, text: i18n("Settings.CompactChatList", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .chatList, settingName: .compactMessagePreview, value: SGSimpleSettings.shared.chatListLines != SGSimpleSettings.ChatListLines.three.rawValue, text: i18n("Settings.CompactMessagePreview", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .chatList, settingName: .disableChatSwipeOptions, value: !SGSimpleSettings.shared.disableChatSwipeOptions, text: i18n("Settings.ChatSwipeOptions", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .chatList, settingName: .disableDeleteChatSwipeOption, value: !SGSimpleSettings.shared.disableDeleteChatSwipeOption, text: i18n("Settings.DeleteChatSwipeOption", lang), enabled: !SGSimpleSettings.shared.disableChatSwipeOptions)) + + entries.append(.header(id: id.count, section: .profiles, text: i18n("Settings.Profiles.Header", lang), badge: nil)) + entries.append(.toggle(id: id.count, section: .profiles, settingName: .showProfileId, value: SGSimpleSettings.shared.showProfileId, text: i18n("Settings.ShowProfileID", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .profiles, settingName: .showDC, value: SGSimpleSettings.shared.showDC, text: i18n("Settings.ShowDC", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .profiles, settingName: .showRegDate, value: SGSimpleSettings.shared.showRegDate, text: i18n("Settings.ShowRegDate", lang), enabled: true)) + entries.append(.notice(id: id.count, section: .profiles, text: i18n("Settings.ShowRegDate.Notice", lang))) + entries.append(.toggle(id: id.count, section: .profiles, settingName: .showCreationDate, value: SGSimpleSettings.shared.showCreationDate, text: i18n("Settings.ShowCreationDate", lang), enabled: true)) + entries.append(.notice(id: id.count, section: .profiles, text: i18n("Settings.ShowCreationDate.Notice", lang))) + entries.append(.toggle(id: id.count, section: .profiles, settingName: .confirmCalls, value: SGSimpleSettings.shared.confirmCalls, text: i18n("Settings.CallConfirmation", lang), enabled: true)) + entries.append(.notice(id: id.count, section: .profiles, text: i18n("Settings.CallConfirmation.Notice", lang))) + + entries.append(.header(id: id.count, section: .stories, text: strings.AutoDownloadSettings_Stories.uppercased(), badge: nil)) + entries.append(.toggle(id: id.count, section: .stories, settingName: .hideStories, value: SGSimpleSettings.shared.hideStories, text: i18n("Settings.Stories.Hide", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .stories, settingName: .disableSwipeToRecordStory, value: SGSimpleSettings.shared.disableSwipeToRecordStory, text: i18n("Settings.Stories.DisableSwipeToRecord", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .stories, settingName: .warnOnStoriesOpen, value: SGSimpleSettings.shared.warnOnStoriesOpen, text: i18n("Settings.Stories.WarnBeforeView", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .stories, settingName: .showRepostToStory, value: SGSimpleSettings.shared.showRepostToStoryV2, text: strings.Share_RepostToStory.replacingOccurrences(of: "\n", with: " "), enabled: true)) + if SGSimpleSettings.shared.canUseStealthMode { + entries.append(.toggle(id: id.count, section: .stories, settingName: .storyStealthMode, value: SGSimpleSettings.shared.storyStealthMode, text: strings.Story_StealthMode_Title, enabled: true)) + entries.append(.notice(id: id.count, section: .stories, text: strings.Story_StealthMode_ControlText)) + } else { + id.increment(2) + } + + + entries.append(.header(id: id.count, section: .translation, text: strings.Localization_TranslateMessages.uppercased(), badge: nil)) + entries.append(.oneFromManySelector(id: id.count, section: .translation, settingName: .translationBackend, text: i18n("Settings.Translation.Backend", lang), value: i18n("Settings.Translation.Backend.\(SGSimpleSettings.shared.translationBackend)", lang), enabled: true)) + if SGSimpleSettings.shared.translationBackendEnum != .gtranslate { + entries.append(.notice(id: id.count, section: .translation, text: i18n("Settings.Translation.Backend.Notice", lang, "Settings.Translation.Backend.\(SGSimpleSettings.TranslationBackend.gtranslate.rawValue)".i18n(lang)))) + } else { + id.increment(1) + } + entries.append(.disclosure(id: id.count, section: .translation, link: .languageSettings, text: strings.Localization_TranslateEntireChat)) + entries.append(.notice(id: id.count, section: .translation, text: i18n("Common.NoTelegramPremiumNeeded", lang, strings.Settings_Premium))) + + entries.append(.header(id: id.count, section: .voiceMessages, text: "Settings.Transcription.Header".i18n(lang), badge: nil)) + entries.append(.oneFromManySelector(id: id.count, section: .voiceMessages, settingName: .transcriptionBackend, text: i18n("Settings.Transcription.Backend", lang), value: i18n("Settings.Transcription.Backend.\(SGSimpleSettings.shared.transcriptionBackend)", lang), enabled: true)) + if SGSimpleSettings.shared.transcriptionBackendEnum != .apple { + entries.append(.notice(id: id.count, section: .voiceMessages, text: i18n("Settings.Transcription.Backend.Notice", lang, "Settings.Transcription.Backend.\(SGSimpleSettings.TranscriptionBackend.apple.rawValue)".i18n(lang)))) + } else { + id.increment(1) + } + entries.append(.header(id: id.count, section: .voiceMessages, text: strings.Privacy_VoiceMessages.uppercased(), badge: nil)) + entries.append(.toggle(id: id.count, section: .voiceMessages, settingName: .forceBuiltInMic, value: SGSimpleSettings.shared.forceBuiltInMic, text: i18n("Settings.forceBuiltInMic", lang), enabled: true)) + entries.append(.notice(id: id.count, section: .voiceMessages, text: i18n("Settings.forceBuiltInMic.Notice", lang))) + + entries.append(.header(id: id.count, section: .calls, text: strings.Calls_TabTitle.uppercased(), badge: nil)) + entries.append(.toggle(id: id.count, section: .calls, settingName: .enableVoipTcp, value: experimentalUISettings.enableVoipTcp, text: "Force TCP", enabled: true)) + entries.append(.notice(id: id.count, section: .calls, text: "Common.KnowWhatYouDo".i18n(lang))) + + entries.append(.header(id: id.count, section: .photo, text: strings.NetworkUsageSettings_MediaImageDataSection, badge: nil)) + entries.append(.header(id: id.count, section: .photo, text: strings.PhotoEditor_QualityTool.uppercased(), badge: nil)) + entries.append(.percentageSlider(id: id.count, section: .photo, settingName: .outgoingPhotoQuality, value: SGSimpleSettings.shared.outgoingPhotoQuality)) + entries.append(.notice(id: id.count, section: .photo, text: i18n("Settings.Photo.Quality.Notice", lang))) + entries.append(.toggle(id: id.count, section: .photo, settingName: .sendLargePhotos, value: SGSimpleSettings.shared.sendLargePhotos, text: i18n("Settings.Photo.SendLarge", lang), enabled: true)) + entries.append(.notice(id: id.count, section: .photo, text: i18n("Settings.Photo.SendLarge.Notice", lang))) + + entries.append(.header(id: id.count, section: .stickers, text: strings.StickerPacksSettings_Title.uppercased(), badge: nil)) + entries.append(.header(id: id.count, section: .stickers, text: i18n("Settings.Stickers.Size", lang), badge: nil)) + entries.append(.percentageSlider(id: id.count, section: .stickers, settingName: .stickerSize, value: SGSimpleSettings.shared.stickerSize)) + entries.append(.toggle(id: id.count, section: .stickers, settingName: .stickerTimestamp, value: SGSimpleSettings.shared.stickerTimestamp, text: i18n("Settings.Stickers.Timestamp", lang), enabled: true)) + + + entries.append(.header(id: id.count, section: .videoNotes, text: i18n("Settings.VideoNotes.Header", lang), badge: nil)) + entries.append(.toggle(id: id.count, section: .videoNotes, settingName: .startTelescopeWithRearCam, value: SGSimpleSettings.shared.startTelescopeWithRearCam, text: i18n("Settings.VideoNotes.StartWithRearCam", lang), enabled: true)) + + entries.append(.header(id: id.count, section: .contextMenu, text: i18n("Settings.ContextMenu", lang), badge: nil)) + entries.append(.notice(id: id.count, section: .contextMenu, text: i18n("Settings.ContextMenu.Notice", lang))) + entries.append(.toggle(id: id.count, section: .contextMenu, settingName: .contextShowSaveToCloud, value: SGSimpleSettings.shared.contextShowSaveToCloud, text: i18n("ContextMenu.SaveToCloud", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .contextMenu, settingName: .contextShowHideForwardName, value: SGSimpleSettings.shared.contextShowHideForwardName, text: strings.Conversation_ForwardOptions_HideSendersNames, enabled: true)) + entries.append(.toggle(id: id.count, section: .contextMenu, settingName: .contextShowSelectFromUser, value: SGSimpleSettings.shared.contextShowSelectFromUser, text: i18n("ContextMenu.SelectFromUser", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .contextMenu, settingName: .contextShowRestrict, value: SGSimpleSettings.shared.contextShowRestrict, text: strings.Conversation_ContextMenuBan, enabled: true)) + entries.append(.toggle(id: id.count, section: .contextMenu, settingName: .contextShowReport, value: SGSimpleSettings.shared.contextShowReport, text: strings.Conversation_ContextMenuReport, enabled: true)) + entries.append(.toggle(id: id.count, section: .contextMenu, settingName: .contextShowReply, value: SGSimpleSettings.shared.contextShowReply, text: strings.Conversation_ContextMenuReply, enabled: true)) + entries.append(.toggle(id: id.count, section: .contextMenu, settingName: .contextShowPin, value: SGSimpleSettings.shared.contextShowPin, text: strings.Conversation_Pin, enabled: true)) + entries.append(.toggle(id: id.count, section: .contextMenu, settingName: .contextShowSaveMedia, value: SGSimpleSettings.shared.contextShowSaveMedia, text: strings.Conversation_SaveToFiles, enabled: true)) + entries.append(.toggle(id: id.count, section: .contextMenu, settingName: .contextShowMessageReplies, value: SGSimpleSettings.shared.contextShowMessageReplies, text: strings.Conversation_ContextViewThread, enabled: true)) + entries.append(.toggle(id: id.count, section: .contextMenu, settingName: .contextShowJson, value: SGSimpleSettings.shared.contextShowJson, text: "JSON", enabled: true)) + /* entries.append(.toggle(id: id.count, section: .contextMenu, settingName: .contextShowRestrict, value: SGSimpleSettings.shared.contextShowRestrict, text: strings.Conversation_ContextMenuBan)) */ + + entries.append(.header(id: id.count, section: .accountColors, text: i18n("Settings.CustomColors.Header", lang), badge: nil)) + entries.append(.header(id: id.count, section: .accountColors, text: i18n("Settings.CustomColors.Saturation", lang), badge: nil)) + let accountColorSaturation = SGSimpleSettings.shared.accountColorsSaturation + entries.append(.percentageSlider(id: id.count, section: .accountColors, settingName: .accountColorsSaturation, value: accountColorSaturation)) +// let nameColor: PeerNameColor +// if let updatedNameColor = state.updatedNameColor { +// nameColor = updatedNameColor +// } else { +// nameColor = .blue +// } +// let _ = nameColors.get(nameColor, dark: presentationData.theme.overallDarkAppearance) +// entries.append(.peerColorPicker(id: entries.count, section: .other, +// colors: nameColors, +// currentColor: nameColor, // TODO: PeerNameColor(rawValue: <#T##Int32#>) +// currentSaturation: accountColorSaturation +// )) + + if accountColorSaturation == 0 { + id.increment(100) + entries.append(.peerColorDisclosurePreview(id: id.count, section: .accountColors, name: "\(strings.UserInfo_FirstNamePlaceholder) \(strings.UserInfo_LastNamePlaceholder)", color: presentationData.theme.chat.message.incoming.accentTextColor)) + } else { + id.increment(200) + for index in nameColors.displayOrder.prefix(3) { + let color: PeerNameColor = PeerNameColor(rawValue: index) + let colors = nameColors.get(color, dark: presentationData.theme.overallDarkAppearance) + entries.append(.peerColorDisclosurePreview(id: id.count, section: .accountColors, name: "\(strings.UserInfo_FirstNamePlaceholder) \(strings.UserInfo_LastNamePlaceholder)", color: colors.main)) + } + } + entries.append(.notice(id: id.count, section: .accountColors, text: i18n("Settings.CustomColors.Saturation.Notice", lang))) + + id.increment(10000) + entries.append(.header(id: id.count, section: .other, text: strings.Appearance_Other.uppercased(), badge: nil)) + entries.append(.toggle(id: id.count, section: .other, settingName: .swipeForVideoPIP, value: SGSimpleSettings.shared.videoPIPSwipeDirection == SGSimpleSettings.VideoPIPSwipeDirection.up.rawValue, text: i18n("Settings.swipeForVideoPIP", lang), enabled: true)) + entries.append(.notice(id: id.count, section: .other, text: i18n("Settings.swipeForVideoPIP.Notice", lang))) + entries.append(.toggle(id: id.count, section: .other, settingName: .hideChannelBottomButton, value: !SGSimpleSettings.shared.hideChannelBottomButton, text: i18n("Settings.showChannelBottomButton", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .other, settingName: .wideChannelPosts, value: SGSimpleSettings.shared.wideChannelPosts, text: i18n("Settings.wideChannelPosts", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .other, settingName: .secondsInMessages, value: SGSimpleSettings.shared.secondsInMessages, text: i18n("Settings.secondsInMessages", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .other, settingName: .messageDoubleTapActionOutgoingEdit, value: SGSimpleSettings.shared.messageDoubleTapActionOutgoing == SGSimpleSettings.MessageDoubleTapAction.edit.rawValue, text: i18n("Settings.messageDoubleTapActionOutgoingEdit", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .other, settingName: .hideRecordingButton, value: !SGSimpleSettings.shared.hideRecordingButton, text: i18n("Settings.RecordingButton", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .other, settingName: .disableSnapDeletionEffect, value: !SGSimpleSettings.shared.disableSnapDeletionEffect, text: i18n("Settings.SnapDeletionEffect", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .other, settingName: .disableSendAsButton, value: !SGSimpleSettings.shared.disableSendAsButton, text: i18n("Settings.SendAsButton", lang, strings.Conversation_SendMesageAs), enabled: true)) + entries.append(.toggle(id: id.count, section: .other, settingName: .disableGalleryCamera, value: !SGSimpleSettings.shared.disableGalleryCamera, text: i18n("Settings.GalleryCamera", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .other, settingName: .disableGalleryCameraPreview, value: !SGSimpleSettings.shared.disableGalleryCameraPreview, text: i18n("Settings.GalleryCameraPreview", lang), enabled: !SGSimpleSettings.shared.disableGalleryCamera)) + entries.append(.toggle(id: id.count, section: .other, settingName: .disableScrollToNextChannel, value: !SGSimpleSettings.shared.disableScrollToNextChannel, text: i18n("Settings.PullToNextChannel", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .other, settingName: .disableScrollToNextTopic, value: !SGSimpleSettings.shared.disableScrollToNextTopic, text: i18n("Settings.PullToNextTopic", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .other, settingName: .hideReactions, value: SGSimpleSettings.shared.hideReactions, text: i18n("Settings.HideReactions", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .other, settingName: .uploadSpeedBoost, value: SGSimpleSettings.shared.uploadSpeedBoost, text: i18n("Settings.UploadsBoost", lang), enabled: true)) + entries.append(.oneFromManySelector(id: id.count, section: .other, settingName: .downloadSpeedBoost, text: i18n("Settings.DownloadsBoost", lang), value: i18n("Settings.DownloadsBoost.\(SGSimpleSettings.shared.downloadSpeedBoost)", lang), enabled: true)) + entries.append(.notice(id: id.count, section: .other, text: i18n("Settings.DownloadsBoost.Notice", lang))) + entries.append(.toggle(id: id.count, section: .other, settingName: .sendWithReturnKey, value: SGSimpleSettings.shared.sendWithReturnKey, text: i18n("Settings.SendWithReturnKey", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .other, settingName: .forceEmojiTab, value: SGSimpleSettings.shared.forceEmojiTab, text: i18n("Settings.ForceEmojiTab", lang), enabled: true)) + entries.append(.toggle(id: id.count, section: .other, settingName: .defaultEmojisFirst, value: SGSimpleSettings.shared.defaultEmojisFirst, text: i18n("Settings.DefaultEmojisFirst", lang), enabled: true)) + entries.append(.notice(id: id.count, section: .other, text: i18n("Settings.DefaultEmojisFirst.Notice", lang))) + entries.append(.toggle(id: id.count, section: .other, settingName: .hidePhoneInSettings, value: SGSimpleSettings.shared.hidePhoneInSettings, text: i18n("Settings.HidePhoneInSettingsUI", lang), enabled: true)) + entries.append(.notice(id: id.count, section: .other, text: i18n("Settings.HidePhoneInSettingsUI.Notice", lang))) + + return filterSGItemListUIEntrires(entries: entries, by: state.searchQuery) +} + +public func sgSettingsController(context: AccountContext/*, focusOnItemTag: Int? = nil*/) -> ViewController { + var presentControllerImpl: ((ViewController, ViewControllerPresentationArguments?) -> Void)? + var pushControllerImpl: ((ViewController) -> Void)? +// var getRootControllerImpl: (() -> UIViewController?)? +// var getNavigationControllerImpl: (() -> NavigationController?)? + var askForRestart: (() -> Void)? + + let initialState = SGSettingsControllerState() + let statePromise = ValuePromise(initialState, ignoreRepeated: true) + let stateValue = Atomic(value: initialState) + let updateState: ((SGSettingsControllerState) -> SGSettingsControllerState) -> Void = { f in + statePromise.set(stateValue.modify { f($0) }) + } + +// let sliderPromise = ValuePromise(SGSimpleSettings.shared.accountColorsSaturation, ignoreRepeated: true) +// let sliderStateValue = Atomic(value: SGSimpleSettings.shared.accountColorsSaturation) +// let _: ((Int32) -> Int32) -> Void = { f in +// sliderPromise.set(sliderStateValue.modify( {f($0)})) +// } + + let simplePromise = ValuePromise(true, ignoreRepeated: false) + + let arguments = SGControllerArguments( + context: context, + /*updatePeerColor: { color in + updateState { state in + var updatedState = state + updatedState.updatedNameColor = color + return updatedState + } + },*/ setBoolValue: { setting, value in + switch setting { + case .hidePhoneInSettings: + SGSimpleSettings.shared.hidePhoneInSettings = value + askForRestart?() + case .showTabNames: + SGSimpleSettings.shared.showTabNames = value + askForRestart?() + case .showContactsTab: + let _ = ( + updateCallListSettingsInteractively( + accountManager: context.sharedContext.accountManager, { $0.withUpdatedShowContactsTab(value) } + ) + ).start() + case .showCallsTab: + let _ = ( + updateCallListSettingsInteractively( + accountManager: context.sharedContext.accountManager, { $0.withUpdatedShowTab(value) } + ) + ).start() + case .tabBarSearchEnabled: + SGSimpleSettings.shared.tabBarSearchEnabled = value + case .wideTabBar: + SGSimpleSettings.shared.wideTabBar = value + askForRestart?() + case .foldersAtBottom: + let _ = ( + updateExperimentalUISettingsInteractively(accountManager: context.sharedContext.accountManager, { settings in + var settings = settings + settings.foldersTabAtBottom = value + return settings + } + ) + ).start() + case .startTelescopeWithRearCam: + SGSimpleSettings.shared.startTelescopeWithRearCam = value + case .hideStories: + SGSimpleSettings.shared.hideStories = value + case .showProfileId: + SGSimpleSettings.shared.showProfileId = value + case .warnOnStoriesOpen: + SGSimpleSettings.shared.warnOnStoriesOpen = value + case .sendWithReturnKey: + SGSimpleSettings.shared.sendWithReturnKey = value + case .rememberLastFolder: + SGSimpleSettings.shared.rememberLastFolder = value + case .sendLargePhotos: + SGSimpleSettings.shared.sendLargePhotos = value + case .storyStealthMode: + SGSimpleSettings.shared.storyStealthMode = value + case .disableSwipeToRecordStory: + SGSimpleSettings.shared.disableSwipeToRecordStory = value + case .uploadSpeedBoost: + SGSimpleSettings.shared.uploadSpeedBoost = value + case .hideReactions: + SGSimpleSettings.shared.hideReactions = value + case .showRepostToStory: + SGSimpleSettings.shared.showRepostToStoryV2 = value + case .contextShowSelectFromUser: + SGSimpleSettings.shared.contextShowSelectFromUser = value + case .contextShowSaveToCloud: + SGSimpleSettings.shared.contextShowSaveToCloud = value + case .contextShowRestrict: + SGSimpleSettings.shared.contextShowRestrict = value + case .contextShowHideForwardName: + SGSimpleSettings.shared.contextShowHideForwardName = value + case .disableScrollToNextChannel: + SGSimpleSettings.shared.disableScrollToNextChannel = !value + case .disableScrollToNextTopic: + SGSimpleSettings.shared.disableScrollToNextTopic = !value + case .disableChatSwipeOptions: + SGSimpleSettings.shared.disableChatSwipeOptions = !value + simplePromise.set(true) // Trigger update for 'enabled' field of other toggles + askForRestart?() + case .disableDeleteChatSwipeOption: + SGSimpleSettings.shared.disableDeleteChatSwipeOption = !value + askForRestart?() + case .disableGalleryCamera: + SGSimpleSettings.shared.disableGalleryCamera = !value + simplePromise.set(true) + case .disableGalleryCameraPreview: + SGSimpleSettings.shared.disableGalleryCameraPreview = !value + case .disableSendAsButton: + SGSimpleSettings.shared.disableSendAsButton = !value + case .disableSnapDeletionEffect: + SGSimpleSettings.shared.disableSnapDeletionEffect = !value + case .contextShowReport: + SGSimpleSettings.shared.contextShowReport = value + case .contextShowReply: + SGSimpleSettings.shared.contextShowReply = value + case .contextShowPin: + SGSimpleSettings.shared.contextShowPin = value + case .contextShowSaveMedia: + SGSimpleSettings.shared.contextShowSaveMedia = value + case .contextShowMessageReplies: + SGSimpleSettings.shared.contextShowMessageReplies = value + case .stickerTimestamp: + SGSimpleSettings.shared.stickerTimestamp = value + case .contextShowJson: + SGSimpleSettings.shared.contextShowJson = value + case .hideRecordingButton: + SGSimpleSettings.shared.hideRecordingButton = !value + case .hideTabBar: + SGSimpleSettings.shared.hideTabBar = value + simplePromise.set(true) // Trigger update for 'enabled' field of other toggles + askForRestart?() + case .showDC: + SGSimpleSettings.shared.showDC = value + case .showCreationDate: + SGSimpleSettings.shared.showCreationDate = value + case .showRegDate: + SGSimpleSettings.shared.showRegDate = value + case .compactChatList: + SGSimpleSettings.shared.compactChatList = value + askForRestart?() + case .compactMessagePreview: + SGSimpleSettings.shared.chatListLines = value ? SGSimpleSettings.ChatListLines.one.rawValue : SGSimpleSettings.ChatListLines.three.rawValue + askForRestart?() + case .compactFolderNames: + SGSimpleSettings.shared.compactFolderNames = value + askForRestart?() + case .allChatsHidden: + SGSimpleSettings.shared.allChatsHidden = value + askForRestart?() + case .defaultEmojisFirst: + SGSimpleSettings.shared.defaultEmojisFirst = value + case .messageDoubleTapActionOutgoingEdit: + SGSimpleSettings.shared.messageDoubleTapActionOutgoing = value ? SGSimpleSettings.MessageDoubleTapAction.edit.rawValue : SGSimpleSettings.MessageDoubleTapAction.default.rawValue + case .wideChannelPosts: + SGSimpleSettings.shared.wideChannelPosts = value + case .forceEmojiTab: + SGSimpleSettings.shared.forceEmojiTab = value + case .forceBuiltInMic: + SGSimpleSettings.shared.forceBuiltInMic = value + case .hideChannelBottomButton: + SGSimpleSettings.shared.hideChannelBottomButton = !value + case .secondsInMessages: + SGSimpleSettings.shared.secondsInMessages = value + case .confirmCalls: + SGSimpleSettings.shared.confirmCalls = value + case .swipeForVideoPIP: + SGSimpleSettings.shared.videoPIPSwipeDirection = value ? SGSimpleSettings.VideoPIPSwipeDirection.up.rawValue : SGSimpleSettings.VideoPIPSwipeDirection.none.rawValue + case .enableVoipTcp: + let _ = ( + updateExperimentalUISettingsInteractively(accountManager: context.sharedContext.accountManager, { settings in + var settings = settings + settings.enableVoipTcp = value + return settings + } + ) + ).start() + case .nyStyleSnow: + SGSimpleSettings.shared.nyStyle = value ? SGSimpleSettings.NYStyle.snow.rawValue : SGSimpleSettings.NYStyle.default.rawValue + simplePromise.set(true) // Trigger update for 'enabled' field of other toggles + case .nyStyleLightning: + SGSimpleSettings.shared.nyStyle = value ? SGSimpleSettings.NYStyle.lightning.rawValue : SGSimpleSettings.NYStyle.default.rawValue + simplePromise.set(true) // Trigger update for 'enabled' field of other toggles + } + }, updateSliderValue: { setting, value in + switch (setting) { + case .accountColorsSaturation: + if SGSimpleSettings.shared.accountColorsSaturation != value { + SGSimpleSettings.shared.accountColorsSaturation = value + simplePromise.set(true) + } + case .outgoingPhotoQuality: + if SGSimpleSettings.shared.outgoingPhotoQuality != value { + SGSimpleSettings.shared.outgoingPhotoQuality = value + simplePromise.set(true) + } + case .stickerSize: + if SGSimpleSettings.shared.stickerSize != value { + SGSimpleSettings.shared.stickerSize = value + simplePromise.set(true) + } + } + + }, setOneFromManyValue: { setting in + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + let actionSheet = ActionSheetController(presentationData: presentationData) + var items: [ActionSheetItem] = [] + + switch (setting) { + case .downloadSpeedBoost: + let setAction: (String) -> Void = { value in + SGSimpleSettings.shared.downloadSpeedBoost = value + + let enableDownloadX: Bool + switch (value) { + case SGSimpleSettings.DownloadSpeedBoostValues.none.rawValue: + enableDownloadX = false + default: + enableDownloadX = true + } + + // Updating controller + simplePromise.set(true) + + let _ = updateNetworkSettingsInteractively(postbox: context.account.postbox, network: context.account.network, { settings in + var settings = settings + settings.useExperimentalDownload = enableDownloadX + return settings + }).start(completed: { + Queue.mainQueue().async { + askForRestart?() + } + }) + } + + for value in SGSimpleSettings.DownloadSpeedBoostValues.allCases { + items.append(ActionSheetButtonItem(title: i18n("Settings.DownloadsBoost.\(value.rawValue)", presentationData.strings.baseLanguageCode), color: .accent, action: { [weak actionSheet] in + actionSheet?.dismissAnimated() + setAction(value.rawValue) + })) + } + case .bottomTabStyle: + let setAction: (String) -> Void = { value in + SGSimpleSettings.shared.bottomTabStyle = value + simplePromise.set(true) + } + + for value in SGSimpleSettings.BottomTabStyleValues.allCases { + items.append(ActionSheetButtonItem(title: i18n("Settings.Folders.BottomTabStyle.\(value.rawValue)", presentationData.strings.baseLanguageCode), color: .accent, action: { [weak actionSheet] in + actionSheet?.dismissAnimated() + setAction(value.rawValue) + })) + } + case .allChatsTitleLengthOverride: + let setAction: (String) -> Void = { value in + SGSimpleSettings.shared.allChatsTitleLengthOverride = value + simplePromise.set(true) + } + + for value in SGSimpleSettings.AllChatsTitleLengthOverride.allCases { + let title: String + switch (value) { + case SGSimpleSettings.AllChatsTitleLengthOverride.short: + title = "\"\(presentationData.strings.ChatList_Tabs_All)\"" + case SGSimpleSettings.AllChatsTitleLengthOverride.long: + title = "\"\(presentationData.strings.ChatList_Tabs_AllChats)\"" + default: + title = i18n("Settings.Folders.AllChatsTitle.none", presentationData.strings.baseLanguageCode) + } + items.append(ActionSheetButtonItem(title: title, color: .accent, action: { [weak actionSheet] in + actionSheet?.dismissAnimated() + setAction(value.rawValue) + })) + } +// case .allChatsFolderPositionOverride: +// let setAction: (String) -> Void = { value in +// SGSimpleSettings.shared.allChatsFolderPositionOverride = value +// simplePromise.set(true) +// } +// +// for value in SGSimpleSettings.AllChatsFolderPositionOverride.allCases { +// items.append(ActionSheetButtonItem(title: i18n("Settings.Folders.AllChatsTitle.\(value)", presentationData.strings.baseLanguageCode), color: .accent, action: { [weak actionSheet] in +// actionSheet?.dismissAnimated() +// setAction(value.rawValue) +// })) +// } + case .translationBackend: + let setAction: (String) -> Void = { value in + SGSimpleSettings.shared.translationBackend = value + simplePromise.set(true) + } + + for value in SGSimpleSettings.TranslationBackend.allCases { + if value == .system { + if #available(iOS 18.0, *) { + } else { + continue // System translation is not available on iOS 17 and below + } + } + items.append(ActionSheetButtonItem(title: i18n("Settings.Translation.Backend.\(value.rawValue)", presentationData.strings.baseLanguageCode), color: .accent, action: { [weak actionSheet] in + actionSheet?.dismissAnimated() + setAction(value.rawValue) + })) + } + case .transcriptionBackend: + let setAction: (String) -> Void = { value in + SGSimpleSettings.shared.transcriptionBackend = value + simplePromise.set(true) + } + + for value in SGSimpleSettings.TranscriptionBackend.allCases { + if #available(iOS 13.0, *) { + } else { + if value == .apple { + continue // Apple recognition is not available on iOS 12 + } + } + items.append(ActionSheetButtonItem(title: i18n("Settings.Transcription.Backend.\(value.rawValue)", presentationData.strings.baseLanguageCode), color: .accent, action: { [weak actionSheet] in + actionSheet?.dismissAnimated() + setAction(value.rawValue) + })) + } + case .nyStyle: + let setAction: (String) -> Void = { value in + SGSimpleSettings.shared.nyStyle = value + simplePromise.set(true) + } + + for value in SGSimpleSettings.NYStyle.allCases { + items.append(ActionSheetButtonItem(title: i18n("Settings.NY.Style.\(value.rawValue)", presentationData.strings.baseLanguageCode), color: .accent, action: { [weak actionSheet] in + actionSheet?.dismissAnimated() + setAction(value.rawValue) + })) + } + } + + actionSheet.setItemGroups([ActionSheetItemGroup(items: items), ActionSheetItemGroup(items: [ + ActionSheetButtonItem(title: presentationData.strings.Common_Cancel, color: .accent, font: .bold, action: { [weak actionSheet] in + actionSheet?.dismissAnimated() + }) + ])]) + presentControllerImpl?(actionSheet, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + }, openDisclosureLink: { link in + switch (link) { + case .languageSettings: + pushControllerImpl?(context.sharedContext.makeLocalizationListController(context: context)) + case .contentSettings: + let _ = (getSGSettingsURL(context: context) |> deliverOnMainQueue).start(next: { [weak context] url in + guard let strongContext = context else { + return + } + strongContext.sharedContext.applicationBindings.openUrl(url) + }) + } + }, searchInput: { searchQuery in + updateState { state in + var updatedState = state + updatedState.searchQuery = searchQuery + return updatedState + } + }) + + let sharedData = context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.callListSettings, ApplicationSpecificSharedDataKeys.experimentalUISettings]) + let preferences = context.account.postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]) + let updatedContentSettingsConfiguration = contentSettingsConfiguration(network: context.account.network) + |> map(Optional.init) + let contentSettingsConfiguration = Promise() + contentSettingsConfiguration.set(.single(nil) + |> then(updatedContentSettingsConfiguration)) + + let signal: Signal<(ItemListControllerState, (ItemListNodeState, SGControllerArguments)), NoError> = combineLatest(simplePromise.get(), /*sliderPromise.get(),*/ statePromise.get(), context.sharedContext.presentationData, sharedData, preferences, contentSettingsConfiguration.get(), + context.engine.accountData.observeAvailableColorOptions(scope: .replies), + context.engine.accountData.observeAvailableColorOptions(scope: .profile) + ) + |> map { _, /*sliderValue,*/ state, presentationData, sharedData, view, contentSettingsConfiguration, availableReplyColors, availableProfileColors -> (ItemListControllerState, (ItemListNodeState, SGControllerArguments)) in + + let appConfiguration: AppConfiguration = view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? AppConfiguration.defaultValue + let callListSettings: CallListSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.callListSettings]?.get(CallListSettings.self) ?? CallListSettings.defaultSettings + let experimentalUISettings: ExperimentalUISettings = sharedData.entries[ApplicationSpecificSharedDataKeys.experimentalUISettings]?.get(ExperimentalUISettings.self) ?? ExperimentalUISettings.defaultSettings + + let entries = SGControllerEntries(presentationData: presentationData, callListSettings: callListSettings, experimentalUISettings: experimentalUISettings, appConfiguration: appConfiguration, nameColors: PeerNameColors.with(availableReplyColors: availableReplyColors, availableProfileColors: availableProfileColors), state: state) + + let controllerState = ItemListControllerState(presentationData: ItemListPresentationData(presentationData), title: .text("Swiftgram"), leftNavigationButton: nil, rightNavigationButton: nil, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back)) + + // TODO(swiftgram): focusOnItemTag support + /* var index = 0 + var scrollToItem: ListViewScrollToItem? + if let focusOnItemTag = focusOnItemTag { + for entry in entries { + if entry.tag?.isEqual(to: focusOnItemTag) ?? false { + scrollToItem = ListViewScrollToItem(index: index, position: .top(0.0), animated: false, curve: .Default(duration: 0.0), directionHint: .Up) + } + index += 1 + } + } */ + + let listState = ItemListNodeState(presentationData: ItemListPresentationData(presentationData), entries: entries, style: .blocks, ensureVisibleItemTag: /*focusOnItemTag*/ nil, initialScrollToItem: nil /* scrollToItem*/ ) + + return (controllerState, (listState, arguments)) + } + + let controller = ItemListController(context: context, state: signal) + presentControllerImpl = { [weak controller] c, a in + controller?.present(c, in: .window(.root), with: a) + } + pushControllerImpl = { [weak controller] c in + (controller?.navigationController as? NavigationController)?.pushViewController(c) + } +// getRootControllerImpl = { [weak controller] in +// return controller?.view.window?.rootViewController +// } +// getNavigationControllerImpl = { [weak controller] in +// return controller?.navigationController as? NavigationController +// } + askForRestart = { [weak context] in + guard let context = context else { + return + } + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + presentControllerImpl?( + UndoOverlayController( + presentationData: presentationData, + content: .info(title: nil, // i18n("Common.RestartRequired", presentationData.strings.baseLanguageCode), + text: i18n("Common.RestartRequired", presentationData.strings.baseLanguageCode), + timeout: nil, + customUndoText: i18n("Common.RestartNow", presentationData.strings.baseLanguageCode) //presentationData.strings.Common_Yes + ), + elevatedLayout: false, + action: { action in if action == .undo { exit(0) }; return true } + ), + nil + ) + } + return controller + +} diff --git a/Swiftgram/SGSharedAccountContextMigration/BUILD b/Swiftgram/SGSharedAccountContextMigration/BUILD new file mode 100644 index 00000000..435918da --- /dev/null +++ b/Swiftgram/SGSharedAccountContextMigration/BUILD @@ -0,0 +1,9 @@ +filegroup( + name = "SGSharedAccountContextMigration", + srcs = glob([ + "Sources/**/*.swift", + ]), + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGSharedAccountContextMigration/Sources/SharedAccountContext+SGUISettingsMigration.swift b/Swiftgram/SGSharedAccountContextMigration/Sources/SharedAccountContext+SGUISettingsMigration.swift new file mode 100644 index 00000000..3d3bbec5 --- /dev/null +++ b/Swiftgram/SGSharedAccountContextMigration/Sources/SharedAccountContext+SGUISettingsMigration.swift @@ -0,0 +1,19 @@ +// MARK: Swiftgram +import SGLogging +import SGAppGroupIdentifier +import SGSimpleSettings +import SwiftSignalKit +import TelegramUIPreferences +import AccountContext +import Postbox +import Foundation + +extension SharedAccountContextImpl { + // MARK: Swiftgram + func performSGUISettingsMigrationIfNecessary() { + if self.didPerformSGUISettingsMigration { + return + } + self.didPerformSGUISettingsMigration = true + } +} diff --git a/Swiftgram/SGShowMessageJson/BUILD b/Swiftgram/SGShowMessageJson/BUILD new file mode 100644 index 00000000..8097e4c9 --- /dev/null +++ b/Swiftgram/SGShowMessageJson/BUILD @@ -0,0 +1,9 @@ +filegroup( + name = "SGShowMessageJson", + srcs = glob([ + "Sources/**/*.swift", + ]), + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGShowMessageJson/Sources/SGShowMessageJson.swift b/Swiftgram/SGShowMessageJson/Sources/SGShowMessageJson.swift new file mode 100644 index 00000000..7868b0db --- /dev/null +++ b/Swiftgram/SGShowMessageJson/Sources/SGShowMessageJson.swift @@ -0,0 +1,76 @@ +import Foundation +import Wrap +import SGLogging +import ChatControllerInteraction +import ChatPresentationInterfaceState +import Postbox +import TelegramCore +import AccountContext + +public func showMessageJson(controllerInteraction: ChatControllerInteraction, chatPresentationInterfaceState: ChatPresentationInterfaceState, message: Message, context: AccountContext) { + if let navigationController = controllerInteraction.navigationController(), let rootController = navigationController.view.window?.rootViewController { + var writingOptions: JSONSerialization.WritingOptions = [ + .prettyPrinted, + //.sortedKeys, + ] + if #available(iOS 13.0, *) { + writingOptions.insert(.withoutEscapingSlashes) + } + + var messageData: Data? = nil + do { + messageData = try wrap( + message, + writingOptions: writingOptions + ) + } catch { + SGLogger.shared.log("ShowMessageJSON", "Error parsing data: \(error)") + messageData = nil + } + + guard let messageData = messageData else { return } + + let id = Int64.random(in: Int64.min ... Int64.max) + let fileResource = LocalFileMediaResource(fileId: id, size: Int64(messageData.count), isSecretRelated: false) + context.account.postbox.mediaBox.storeResourceData(fileResource.id, data: messageData, synchronous: true) + + let file = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: id), partialReference: nil, resource: fileResource, previewRepresentations: [], videoThumbnails: [], immediateThumbnailData: nil, mimeType: "application/json; charset=utf-8", size: Int64(messageData.count), attributes: [.FileName(fileName: "message.json")], alternativeRepresentations: []) + + presentDocumentPreviewController(rootController: rootController, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings, postbox: context.account.postbox, file: file, canShare: !message.isCopyProtected()) + + } +} + +extension MemoryBuffer: @retroactive WrapCustomizable { + + public func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? { + let hexString = self.description + return ["string": hexStringToString(hexString) ?? hexString] + } +} + +// There's a chacne we will need it for each empty/weird type, or it will be a runtime crash. +extension ContentRequiresValidationMessageAttribute: @retroactive WrapCustomizable { + + public func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? { + return ["@type": "ContentRequiresValidationMessageAttribute"] + } +} + +func hexStringToString(_ hexString: String) -> String? { + var chars = Array(hexString) + var result = "" + + while chars.count > 0 { + let c = String(chars[0...1]) + chars = Array(chars.dropFirst(2)) + if let byte = UInt8(c, radix: 16) { + let scalar = UnicodeScalar(byte) + result.append(String(scalar)) + } else { + return nil + } + } + + return result +} diff --git a/Swiftgram/SGSimpleSettings/BUILD b/Swiftgram/SGSimpleSettings/BUILD new file mode 100644 index 00000000..cd8266c4 --- /dev/null +++ b/Swiftgram/SGSimpleSettings/BUILD @@ -0,0 +1,19 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGSimpleSettings", + module_name = "SGSimpleSettings", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//Swiftgram/SGAppGroupIdentifier:SGAppGroupIdentifier", + "//Swiftgram/SGLogging:SGLogging", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGSimpleSettings/Sources/AtomicWrapper.swift b/Swiftgram/SGSimpleSettings/Sources/AtomicWrapper.swift new file mode 100644 index 00000000..b0d07360 --- /dev/null +++ b/Swiftgram/SGSimpleSettings/Sources/AtomicWrapper.swift @@ -0,0 +1,58 @@ +//// A copy of Atomic from SwiftSignalKit +//import Foundation +// +//public enum AtomicWrapperLockError: Error { +// case isLocked +//} +// +//public final class AtomicWrapper { +// private var lock: pthread_mutex_t +// private var value: T +// +// public init(value: T) { +// self.lock = pthread_mutex_t() +// self.value = value +// +// pthread_mutex_init(&self.lock, nil) +// } +// +// deinit { +// pthread_mutex_destroy(&self.lock) +// } +// +// public func with(_ f: (T) -> R) -> R { +// pthread_mutex_lock(&self.lock) +// let result = f(self.value) +// pthread_mutex_unlock(&self.lock) +// +// return result +// } +// +// public func tryWith(_ f: (T) -> R) throws -> R { +// if pthread_mutex_trylock(&self.lock) == 0 { +// let result = f(self.value) +// pthread_mutex_unlock(&self.lock) +// return result +// } else { +// throw AtomicWrapperLockError.isLocked +// } +// } +// +// public func modify(_ f: (T) -> T) -> T { +// pthread_mutex_lock(&self.lock) +// let result = f(self.value) +// self.value = result +// pthread_mutex_unlock(&self.lock) +// +// return result +// } +// +// public func swap(_ value: T) -> T { +// pthread_mutex_lock(&self.lock) +// let previous = self.value +// self.value = value +// pthread_mutex_unlock(&self.lock) +// +// return previous +// } +//} diff --git a/Swiftgram/SGSimpleSettings/Sources/RWLock.swift b/Swiftgram/SGSimpleSettings/Sources/RWLock.swift new file mode 100644 index 00000000..3ea2436c --- /dev/null +++ b/Swiftgram/SGSimpleSettings/Sources/RWLock.swift @@ -0,0 +1,36 @@ +// +// RWLock.swift +// SwiftConcurrentCollections +// +// Created by Pete Prokop on 09/02/2020. +// Copyright © 2020 Pete Prokop. All rights reserved. +// + +import Foundation + +public final class RWLock { + private var lock: pthread_rwlock_t + + // MARK: Lifecycle + deinit { + pthread_rwlock_destroy(&lock) + } + + public init() { + lock = pthread_rwlock_t() + pthread_rwlock_init(&lock, nil) + } + + // MARK: Public + public func writeLock() { + pthread_rwlock_wrlock(&lock) + } + + public func readLock() { + pthread_rwlock_rdlock(&lock) + } + + public func unlock() { + pthread_rwlock_unlock(&lock) + } +} diff --git a/Swiftgram/SGSimpleSettings/Sources/SimpleSettings.swift b/Swiftgram/SGSimpleSettings/Sources/SimpleSettings.swift new file mode 100644 index 00000000..2db47deb --- /dev/null +++ b/Swiftgram/SGSimpleSettings/Sources/SimpleSettings.swift @@ -0,0 +1,665 @@ +import Foundation +import SGAppGroupIdentifier +import SGLogging + +let APP_GROUP_IDENTIFIER = sgAppGroupIdentifier() + +public class SGSimpleSettings { + + public static let shared = SGSimpleSettings() + + private init() { + setDefaultValues() + migrate() + preCacheValues() + } + + private func setDefaultValues() { + UserDefaults.standard.register(defaults: SGSimpleSettings.defaultValues) + // Just in case group defaults will be nil + UserDefaults.standard.register(defaults: SGSimpleSettings.groupDefaultValues) + if let groupUserDefaults = UserDefaults(suiteName: APP_GROUP_IDENTIFIER) { + groupUserDefaults.register(defaults: SGSimpleSettings.groupDefaultValues) + } + } + + private func migrate() { + let showRepostToStoryMigrationKey = "migrated_\(Keys.showRepostToStory.rawValue)" + if let groupUserDefaults = UserDefaults(suiteName: APP_GROUP_IDENTIFIER) { + if !groupUserDefaults.bool(forKey: showRepostToStoryMigrationKey) { + self.showRepostToStoryV2 = self.showRepostToStory + groupUserDefaults.set(true, forKey: showRepostToStoryMigrationKey) + SGLogger.shared.log("SGSimpleSettings", "Migrated showRepostToStory. \(self.showRepostToStory) -> \(self.showRepostToStoryV2)") + } + } else { + SGLogger.shared.log("SGSimpleSettings", "Unable to migrate showRepostToStory. Shared UserDefaults suite is not available for '\(APP_GROUP_IDENTIFIER)'.") + } + + let chatListLinesMigrationKey = "migrated_\(Keys.chatListLines.rawValue)" + if !UserDefaults.standard.bool(forKey: chatListLinesMigrationKey) { + let legacyCompactMessagePreviewKey = "compactMessagePreview" + if UserDefaults.standard.object(forKey: legacyCompactMessagePreviewKey) != nil { + if UserDefaults.standard.bool(forKey: legacyCompactMessagePreviewKey) { + self.chatListLines = ChatListLines.one.rawValue + } + UserDefaults.standard.removeObject(forKey: legacyCompactMessagePreviewKey) + SGLogger.shared.log("SGSimpleSettings", "Migrated compactMessagePreview -> chatListLines. \(self.chatListLines)") + } + UserDefaults.standard.set(true, forKey: chatListLinesMigrationKey) + } + } + + private func preCacheValues() { + // let dispatchGroup = DispatchGroup() + + let tasks = [ +// { let _ = self.allChatsFolderPositionOverride }, + { let _ = self.tabBarSearchEnabled }, + { let _ = self.allChatsHidden }, + { let _ = self.hideTabBar }, + { let _ = self.bottomTabStyle }, + { let _ = self.compactChatList }, + { let _ = self.chatListLines }, + { let _ = self.compactFolderNames }, + { let _ = self.disableSwipeToRecordStory }, + { let _ = self.rememberLastFolder }, + { let _ = self.quickTranslateButton }, + { let _ = self.stickerSize }, + { let _ = self.stickerTimestamp }, + { let _ = self.hideReactions }, + { let _ = self.disableGalleryCamera }, + { let _ = self.disableSendAsButton }, + { let _ = self.disableSnapDeletionEffect }, + { let _ = self.startTelescopeWithRearCam }, + { let _ = self.hideRecordingButton }, + { let _ = self.inputToolbar }, + { let _ = self.dismissedSGSuggestions }, + { let _ = self.customAppBadge } + ] + + tasks.forEach { task in + DispatchQueue.global(qos: .background).async(/*group: dispatchGroup*/) { + task() + } + } + + // dispatchGroup.notify(queue: DispatchQueue.main) {} + } + + public func synchronizeShared() { + if let groupUserDefaults = UserDefaults(suiteName: APP_GROUP_IDENTIFIER) { + groupUserDefaults.synchronize() + } + } + + public enum Keys: String, CaseIterable { + case hidePhoneInSettings + case showTabNames + case startTelescopeWithRearCam + case accountColorsSaturation + case uploadSpeedBoost + case downloadSpeedBoost + case bottomTabStyle + case rememberLastFolder + case lastAccountFolders + case localDNSForProxyHost + case sendLargePhotos + case outgoingPhotoQuality + case storyStealthMode + case canUseStealthMode + case disableSwipeToRecordStory + case quickTranslateButton + case outgoingLanguageTranslation + case hideReactions + case showRepostToStory + case showRepostToStoryV2 + case contextShowSelectFromUser + case contextShowSaveToCloud + case contextShowRestrict + // case contextShowBan + case contextShowHideForwardName + case contextShowReport + case contextShowReply + case contextShowPin + case contextShowSaveMedia + case contextShowMessageReplies + case contextShowJson + case disableScrollToNextChannel + case disableScrollToNextTopic + case disableChatSwipeOptions + case disableDeleteChatSwipeOption + case disableGalleryCamera + case disableGalleryCameraPreview + case disableSendAsButton + case disableSnapDeletionEffect + case stickerSize + case stickerTimestamp + case hideRecordingButton + case hideTabBar + case showDC + case showCreationDate + case showRegDate + case regDateCache + case compactChatList + case chatListLines + case compactFolderNames + case allChatsTitleLengthOverride +// case allChatsFolderPositionOverride + case allChatsHidden + case defaultEmojisFirst + case messageDoubleTapActionOutgoing + case wideChannelPosts + case forceEmojiTab + case forceBuiltInMic + case secondsInMessages + case hideChannelBottomButton + case forceSystemSharing + case confirmCalls + case videoPIPSwipeDirection + case legacyNotificationsFix + case messageFilterKeywords + case inputToolbar + case pinnedMessageNotifications + case mentionsAndRepliesNotifications + case primaryUserId + case status + case dismissedSGSuggestions + case duckyAppIconAvailable + case transcriptionBackend + case translationBackend + case customAppBadge + case canUseNY + case nyStyle + case wideTabBar + case tabBarSearchEnabled + case hideStories + case warnOnStoriesOpen + case showProfileId + case sendWithReturnKey + } + + public enum DownloadSpeedBoostValues: String, CaseIterable { + case none + case medium + case maximum + } + + public enum BottomTabStyleValues: String, CaseIterable { + case telegram + case ios + } + + public enum AllChatsTitleLengthOverride: String, CaseIterable { + case none + case short + case long + } + + public enum AllChatsFolderPositionOverride: String, CaseIterable { + case none + case last + case hidden + } + + public enum ChatListLines: String, CaseIterable { + case three = "3" + case two = "2" + case one = "1" + + public static let defaultValue: ChatListLines = .three + } + + public enum MessageDoubleTapAction: String, CaseIterable { + case `default` + case none + case edit + } + + public enum VideoPIPSwipeDirection: String, CaseIterable { + case up + case down + case none + } + + public enum TranscriptionBackend: String, CaseIterable { + case `default` + case apple + } + + public enum TranslationBackend: String, CaseIterable { + case `default` + case gtranslate + case system + // Make sure to update TranslationConfiguration + } + + public enum PinnedMessageNotificationsSettings: String, CaseIterable { + case `default` + case silenced + case disabled + } + + public enum MentionsAndRepliesNotificationsSettings: String, CaseIterable { + case `default` + case silenced + case disabled + } + + public enum NYStyle: String, CaseIterable { + case `default` + case snow + case lightning + } + + public static let defaultValues: [String: Any] = [ + Keys.hidePhoneInSettings.rawValue: true, + Keys.showTabNames.rawValue: true, + Keys.startTelescopeWithRearCam.rawValue: false, + Keys.accountColorsSaturation.rawValue: 100, + Keys.uploadSpeedBoost.rawValue: false, + Keys.downloadSpeedBoost.rawValue: DownloadSpeedBoostValues.none.rawValue, + Keys.rememberLastFolder.rawValue: false, + Keys.bottomTabStyle.rawValue: BottomTabStyleValues.telegram.rawValue, + Keys.lastAccountFolders.rawValue: [:], + Keys.localDNSForProxyHost.rawValue: false, + Keys.sendLargePhotos.rawValue: false, + Keys.outgoingPhotoQuality.rawValue: 70, + Keys.storyStealthMode.rawValue: false, + Keys.canUseStealthMode.rawValue: true, + Keys.disableSwipeToRecordStory.rawValue: false, + Keys.quickTranslateButton.rawValue: false, + Keys.outgoingLanguageTranslation.rawValue: [:], + Keys.hideReactions.rawValue: false, + Keys.showRepostToStory.rawValue: true, + Keys.contextShowSelectFromUser.rawValue: true, + Keys.contextShowSaveToCloud.rawValue: true, + Keys.contextShowRestrict.rawValue: true, + // Keys.contextShowBan.rawValue: true, + Keys.contextShowHideForwardName.rawValue: true, + Keys.contextShowReport.rawValue: true, + Keys.contextShowReply.rawValue: true, + Keys.contextShowPin.rawValue: true, + Keys.contextShowSaveMedia.rawValue: true, + Keys.contextShowMessageReplies.rawValue: true, + Keys.contextShowJson.rawValue: false, + Keys.disableScrollToNextChannel.rawValue: false, + Keys.disableScrollToNextTopic.rawValue: false, + Keys.disableChatSwipeOptions.rawValue: false, + Keys.disableDeleteChatSwipeOption.rawValue: false, + Keys.disableGalleryCamera.rawValue: false, + Keys.disableGalleryCameraPreview.rawValue: false, + Keys.disableSendAsButton.rawValue: false, + Keys.disableSnapDeletionEffect.rawValue: false, + Keys.stickerSize.rawValue: 100, + Keys.stickerTimestamp.rawValue: true, + Keys.hideRecordingButton.rawValue: false, + Keys.hideTabBar.rawValue: false, + Keys.showDC.rawValue: false, + Keys.showCreationDate.rawValue: true, + Keys.showRegDate.rawValue: true, + Keys.regDateCache.rawValue: [:], + Keys.compactChatList.rawValue: false, + Keys.chatListLines.rawValue: ChatListLines.defaultValue.rawValue, + Keys.compactFolderNames.rawValue: false, + Keys.allChatsTitleLengthOverride.rawValue: AllChatsTitleLengthOverride.none.rawValue, +// Keys.allChatsFolderPositionOverride.rawValue: AllChatsFolderPositionOverride.none.rawValue + Keys.allChatsHidden.rawValue: false, + Keys.defaultEmojisFirst.rawValue: false, + Keys.messageDoubleTapActionOutgoing.rawValue: MessageDoubleTapAction.default.rawValue, + Keys.wideChannelPosts.rawValue: false, + Keys.forceEmojiTab.rawValue: false, + Keys.hideChannelBottomButton.rawValue: false, + Keys.secondsInMessages.rawValue: false, + Keys.forceSystemSharing.rawValue: false, + Keys.confirmCalls.rawValue: true, + Keys.videoPIPSwipeDirection.rawValue: VideoPIPSwipeDirection.up.rawValue, + Keys.messageFilterKeywords.rawValue: [], + Keys.inputToolbar.rawValue: false, + Keys.primaryUserId.rawValue: "", + Keys.dismissedSGSuggestions.rawValue: [], + Keys.duckyAppIconAvailable.rawValue: true, + Keys.transcriptionBackend.rawValue: TranscriptionBackend.default.rawValue, + Keys.translationBackend.rawValue: TranslationBackend.default.rawValue, + Keys.customAppBadge.rawValue: "", + Keys.canUseNY.rawValue: false, + Keys.nyStyle.rawValue: NYStyle.default.rawValue, + Keys.wideTabBar.rawValue: false, + Keys.tabBarSearchEnabled.rawValue: true, + Keys.hideStories.rawValue: false, + Keys.warnOnStoriesOpen.rawValue: false, + Keys.showProfileId.rawValue: true, + Keys.sendWithReturnKey.rawValue: false + ] + + public static let groupDefaultValues: [String: Any] = [ + Keys.legacyNotificationsFix.rawValue: false, + Keys.pinnedMessageNotifications.rawValue: PinnedMessageNotificationsSettings.default.rawValue, + Keys.mentionsAndRepliesNotifications.rawValue: MentionsAndRepliesNotificationsSettings.default.rawValue, + Keys.status.rawValue: 1, + Keys.showRepostToStoryV2.rawValue: true, + ] + + @UserDefault(key: Keys.hidePhoneInSettings.rawValue) + public var hidePhoneInSettings: Bool + + @UserDefault(key: Keys.showTabNames.rawValue) + public var showTabNames: Bool + + @UserDefault(key: Keys.startTelescopeWithRearCam.rawValue) + public var startTelescopeWithRearCam: Bool + + @UserDefault(key: Keys.accountColorsSaturation.rawValue) + public var accountColorsSaturation: Int32 + + @UserDefault(key: Keys.uploadSpeedBoost.rawValue) + public var uploadSpeedBoost: Bool + + @UserDefault(key: Keys.downloadSpeedBoost.rawValue) + public var downloadSpeedBoost: String + + @UserDefault(key: Keys.rememberLastFolder.rawValue) + public var rememberLastFolder: Bool + + // Disabled while Telegram is migrating to Glass + // @UserDefault(key: Keys.bottomTabStyle.rawValue) + public var bottomTabStyle: String { + set {} + get { + return BottomTabStyleValues.ios.rawValue + } + } + + public var lastAccountFolders = UserDefaultsBackedDictionary(userDefaultsKey: Keys.lastAccountFolders.rawValue, threadSafe: false) + + @UserDefault(key: Keys.localDNSForProxyHost.rawValue) + public var localDNSForProxyHost: Bool + + @UserDefault(key: Keys.sendLargePhotos.rawValue) + public var sendLargePhotos: Bool + + @UserDefault(key: Keys.outgoingPhotoQuality.rawValue) + public var outgoingPhotoQuality: Int32 + + @UserDefault(key: Keys.hideStories.rawValue) + public var hideStories: Bool + + @UserDefault(key: Keys.warnOnStoriesOpen.rawValue) + public var warnOnStoriesOpen: Bool + + @UserDefault(key: Keys.storyStealthMode.rawValue) + public var storyStealthMode: Bool + + @UserDefault(key: Keys.canUseStealthMode.rawValue) + public var canUseStealthMode: Bool + + @UserDefault(key: Keys.disableSwipeToRecordStory.rawValue) + public var disableSwipeToRecordStory: Bool + + @UserDefault(key: Keys.quickTranslateButton.rawValue) + public var quickTranslateButton: Bool + + public var outgoingLanguageTranslation = UserDefaultsBackedDictionary(userDefaultsKey: Keys.outgoingLanguageTranslation.rawValue, threadSafe: false) + + @UserDefault(key: Keys.hideReactions.rawValue) + public var hideReactions: Bool + + // @available(*, deprecated, message: "Use showRepostToStoryV2 instead") + @UserDefault(key: Keys.showRepostToStory.rawValue) + public var showRepostToStory: Bool + + @UserDefault(key: Keys.showRepostToStoryV2.rawValue, userDefaults: UserDefaults(suiteName: APP_GROUP_IDENTIFIER) ?? .standard) + public var showRepostToStoryV2: Bool + + @UserDefault(key: Keys.contextShowRestrict.rawValue) + public var contextShowRestrict: Bool + + /*@UserDefault(key: Keys.contextShowBan.rawValue) + public var contextShowBan: Bool*/ + + @UserDefault(key: Keys.contextShowSelectFromUser.rawValue) + public var contextShowSelectFromUser: Bool + + @UserDefault(key: Keys.contextShowSaveToCloud.rawValue) + public var contextShowSaveToCloud: Bool + + @UserDefault(key: Keys.contextShowHideForwardName.rawValue) + public var contextShowHideForwardName: Bool + + @UserDefault(key: Keys.contextShowReport.rawValue) + public var contextShowReport: Bool + + @UserDefault(key: Keys.contextShowReply.rawValue) + public var contextShowReply: Bool + + @UserDefault(key: Keys.contextShowPin.rawValue) + public var contextShowPin: Bool + + @UserDefault(key: Keys.contextShowSaveMedia.rawValue) + public var contextShowSaveMedia: Bool + + @UserDefault(key: Keys.contextShowMessageReplies.rawValue) + public var contextShowMessageReplies: Bool + + @UserDefault(key: Keys.contextShowJson.rawValue) + public var contextShowJson: Bool + + @UserDefault(key: Keys.disableScrollToNextChannel.rawValue) + public var disableScrollToNextChannel: Bool + + @UserDefault(key: Keys.disableScrollToNextTopic.rawValue) + public var disableScrollToNextTopic: Bool + + @UserDefault(key: Keys.disableChatSwipeOptions.rawValue) + public var disableChatSwipeOptions: Bool + + @UserDefault(key: Keys.disableDeleteChatSwipeOption.rawValue) + public var disableDeleteChatSwipeOption: Bool + + @UserDefault(key: Keys.disableGalleryCamera.rawValue) + public var disableGalleryCamera: Bool + + @UserDefault(key: Keys.disableGalleryCameraPreview.rawValue) + public var disableGalleryCameraPreview: Bool + + @UserDefault(key: Keys.disableSendAsButton.rawValue) + public var disableSendAsButton: Bool + + @UserDefault(key: Keys.disableSnapDeletionEffect.rawValue) + public var disableSnapDeletionEffect: Bool + + @UserDefault(key: Keys.stickerSize.rawValue) + public var stickerSize: Int32 + + @UserDefault(key: Keys.stickerTimestamp.rawValue) + public var stickerTimestamp: Bool + + @UserDefault(key: Keys.hideRecordingButton.rawValue) + public var hideRecordingButton: Bool + + @UserDefault(key: Keys.hideTabBar.rawValue) + public var hideTabBar: Bool + + @UserDefault(key: Keys.showProfileId.rawValue) + public var showProfileId: Bool + + @UserDefault(key: Keys.showDC.rawValue) + public var showDC: Bool + + @UserDefault(key: Keys.showCreationDate.rawValue) + public var showCreationDate: Bool + + @UserDefault(key: Keys.showRegDate.rawValue) + public var showRegDate: Bool + + public var regDateCache = UserDefaultsBackedDictionary(userDefaultsKey: Keys.regDateCache.rawValue, threadSafe: false) + + @UserDefault(key: Keys.compactChatList.rawValue) + public var compactChatList: Bool + + @UserDefault(key: Keys.chatListLines.rawValue) + public var chatListLines: String + + @UserDefault(key: Keys.compactFolderNames.rawValue) + public var compactFolderNames: Bool + + @UserDefault(key: Keys.allChatsTitleLengthOverride.rawValue) + public var allChatsTitleLengthOverride: String +// +// @UserDefault(key: Keys.allChatsFolderPositionOverride.rawValue) +// public var allChatsFolderPositionOverride: String + @UserDefault(key: Keys.allChatsHidden.rawValue) + public var allChatsHidden: Bool + + @UserDefault(key: Keys.defaultEmojisFirst.rawValue) + public var defaultEmojisFirst: Bool + + @UserDefault(key: Keys.messageDoubleTapActionOutgoing.rawValue) + public var messageDoubleTapActionOutgoing: String + + @UserDefault(key: Keys.wideChannelPosts.rawValue) + public var wideChannelPosts: Bool + + @UserDefault(key: Keys.forceEmojiTab.rawValue) + public var forceEmojiTab: Bool + + @UserDefault(key: Keys.forceBuiltInMic.rawValue) + public var forceBuiltInMic: Bool + + @UserDefault(key: Keys.secondsInMessages.rawValue) + public var secondsInMessages: Bool + + @UserDefault(key: Keys.hideChannelBottomButton.rawValue) + public var hideChannelBottomButton: Bool + + @UserDefault(key: Keys.forceSystemSharing.rawValue) + public var forceSystemSharing: Bool + + @UserDefault(key: Keys.confirmCalls.rawValue) + public var confirmCalls: Bool + + @UserDefault(key: Keys.videoPIPSwipeDirection.rawValue) + public var videoPIPSwipeDirection: String + + @UserDefault(key: Keys.legacyNotificationsFix.rawValue, userDefaults: UserDefaults(suiteName: APP_GROUP_IDENTIFIER) ?? .standard) + public var legacyNotificationsFix: Bool + + @UserDefault(key: Keys.status.rawValue, userDefaults: UserDefaults(suiteName: APP_GROUP_IDENTIFIER) ?? .standard) + public var status: Int64 + + public var ephemeralStatus: Int64 = 1 + + @UserDefault(key: Keys.messageFilterKeywords.rawValue) + public var messageFilterKeywords: [String] + + @UserDefault(key: Keys.inputToolbar.rawValue) + public var inputToolbar: Bool + + @UserDefault(key: Keys.sendWithReturnKey.rawValue) + public var sendWithReturnKey: Bool + + @UserDefault(key: Keys.pinnedMessageNotifications.rawValue, userDefaults: UserDefaults(suiteName: APP_GROUP_IDENTIFIER) ?? .standard) + public var pinnedMessageNotifications: String + + @UserDefault(key: Keys.mentionsAndRepliesNotifications.rawValue, userDefaults: UserDefaults(suiteName: APP_GROUP_IDENTIFIER) ?? .standard) + public var mentionsAndRepliesNotifications: String + + @UserDefault(key: Keys.primaryUserId.rawValue) + public var primaryUserId: String + + @UserDefault(key: Keys.dismissedSGSuggestions.rawValue) + public var dismissedSGSuggestions: [String] + + @UserDefault(key: Keys.duckyAppIconAvailable.rawValue) + public var duckyAppIconAvailable: Bool + + @UserDefault(key: Keys.transcriptionBackend.rawValue) + public var transcriptionBackend: String + + @UserDefault(key: Keys.translationBackend.rawValue) + public var translationBackend: String + + @UserDefault(key: Keys.customAppBadge.rawValue) + public var customAppBadge: String + + @UserDefault(key: Keys.canUseNY.rawValue) + public var canUseNY: Bool + + @UserDefault(key: Keys.nyStyle.rawValue) + public var nyStyle: String + + @UserDefault(key: Keys.wideTabBar.rawValue) + public var wideTabBar: Bool + + @UserDefault(key: Keys.tabBarSearchEnabled.rawValue) + public var tabBarSearchEnabled: Bool +} + +extension SGSimpleSettings { + public var isStealthModeEnabled: Bool { + return storyStealthMode && canUseStealthMode + } + + public static func makeOutgoingLanguageTranslationKey(accountId: Int64, peerId: Int64) -> String { + return "\(accountId):\(peerId)" + } +} + +extension SGSimpleSettings { + public var translationBackendEnum: SGSimpleSettings.TranslationBackend { + return TranslationBackend(rawValue: translationBackend) ?? .default + } + + public var transcriptionBackendEnum: SGSimpleSettings.TranscriptionBackend { + return TranscriptionBackend(rawValue: transcriptionBackend) ?? .default + } +} + +extension SGSimpleSettings { + public var isNYEnabled: Bool { + return canUseNY && NYStyle(rawValue: nyStyle) != .default + } +} + +public func getSGDownloadPartSize(_ default: Int64, fileSize: Int64?) -> Int64 { + let currentDownloadSetting = SGSimpleSettings.shared.downloadSpeedBoost + // Increasing chunk size for small files make it worse in terms of overall download performance + let smallFileSizeThreshold = 1 * 1024 * 1024 // 1 MB + switch (currentDownloadSetting) { + case SGSimpleSettings.DownloadSpeedBoostValues.medium.rawValue: + if let fileSize, fileSize <= smallFileSizeThreshold { + return `default` + } + return 512 * 1024 + case SGSimpleSettings.DownloadSpeedBoostValues.maximum.rawValue: + if let fileSize, fileSize <= smallFileSizeThreshold { + return `default` + } + return 1024 * 1024 + default: + return `default` + } +} + +public func getSGMaxPendingParts(_ default: Int) -> Int { + let currentDownloadSetting = SGSimpleSettings.shared.downloadSpeedBoost + switch (currentDownloadSetting) { + case SGSimpleSettings.DownloadSpeedBoostValues.medium.rawValue: + return 8 + case SGSimpleSettings.DownloadSpeedBoostValues.maximum.rawValue: + return 12 + default: + return `default` + } +} + +public func sgUseShortAllChatsTitle(_ default: Bool) -> Bool { + let currentOverride = SGSimpleSettings.shared.allChatsTitleLengthOverride + switch (currentOverride) { + case SGSimpleSettings.AllChatsTitleLengthOverride.short.rawValue: + return true + case SGSimpleSettings.AllChatsTitleLengthOverride.long.rawValue: + return false + default: + return `default` + } +} diff --git a/Swiftgram/SGSimpleSettings/Sources/UserDefaultsWrapper.swift b/Swiftgram/SGSimpleSettings/Sources/UserDefaultsWrapper.swift new file mode 100644 index 00000000..63784ff3 --- /dev/null +++ b/Swiftgram/SGSimpleSettings/Sources/UserDefaultsWrapper.swift @@ -0,0 +1,408 @@ +import Foundation + +public protocol AllowedUserDefaultTypes {} + +/* // This one is more painful than helpful +extension Bool: AllowedUserDefaultTypes {} +extension String: AllowedUserDefaultTypes {} +extension Int: AllowedUserDefaultTypes {} +extension Int32: AllowedUserDefaultTypes {} +extension Double: AllowedUserDefaultTypes {} +extension Float: AllowedUserDefaultTypes {} +extension Data: AllowedUserDefaultTypes {} +extension URL: AllowedUserDefaultTypes {} +//extension Dictionary: AllowedUserDefaultTypes {} +extension Array: AllowedUserDefaultTypes where Element: AllowedUserDefaultTypes {} +*/ + +// Does not support Optional types due to caching +@propertyWrapper +public class UserDefault /*where T: AllowedUserDefaultTypes*/ { + public let key: String + public let userDefaults: UserDefaults + private var cachedValue: T? + + public init(key: String, userDefaults: UserDefaults = .standard) { + self.key = key + self.userDefaults = userDefaults + } + + public var wrappedValue: T { + get { + #if DEBUG && false + SGtrace("UD.\(key)", what: "GET") + #endif + + if let strongCachedValue = cachedValue { + #if DEBUG && false + SGtrace("UD", what: "CACHED \(key) \(strongCachedValue)") + #endif + return strongCachedValue + } + + cachedValue = readFromUserDefaults() + + #if DEBUG + SGtrace("UD.\(key)", what: "EXTRACTED: \(cachedValue!)") + #endif + return cachedValue! + } + set { + cachedValue = newValue + #if DEBUG + SGtrace("UD.\(key)", what: "CACHE UPDATED \(cachedValue!)") + #endif + userDefaults.set(newValue, forKey: key) + } + } + + fileprivate func readFromUserDefaults() -> T { + switch T.self { + case is Bool.Type: + return (userDefaults.bool(forKey: key) as! T) + case is String.Type: + return (userDefaults.string(forKey: key) as! T) + case is Int64.Type: + return (Int64(exactly: userDefaults.integer(forKey: key)) as! T) + case is Int32.Type: + return (Int32(exactly: userDefaults.integer(forKey: key)) as! T) + case is Int.Type: + return (userDefaults.integer(forKey: key) as! T) + case is Double.Type: + return (userDefaults.double(forKey: key) as! T) + case is Float.Type: + return (userDefaults.float(forKey: key) as! T) + case is Data.Type: + return (userDefaults.data(forKey: key) as! T) + case is URL.Type: + return (userDefaults.url(forKey: key) as! T) + case is Array.Type: + return (userDefaults.stringArray(forKey: key) as! T) + case is Array.Type: + return (userDefaults.array(forKey: key) as! T) + default: + fatalError("Unsupported UserDefault type \(T.self)") + // cachedValue = (userDefaults.object(forKey: key) as! T) + } + } +} + +//public class AtomicUserDefault: UserDefault { +// private let atomicCachedValue: AtomicWrapper = AtomicWrapper(value: nil) +// +// public override var wrappedValue: T { +// get { +// return atomicCachedValue.modify({ value in +// if let strongValue = value { +// return strongValue +// } +// return self.readFromUserDefaults() +// })! +// } +// set { +// let _ = atomicCachedValue.modify({ _ in +// userDefaults.set(newValue, forKey: key) +// return newValue +// }) +// } +// } +//} + + + +// Based on ConcurrentDictionary.swift from https://github.com/peterprokop/SwiftConcurrentCollections + +/// Thread-safe UserDefaults dictionary wrapper +/// - Important: Note that this is a `class`, i.e. reference (not value) type +/// - Important: Key can only be String type +public class UserDefaultsBackedDictionary { + public let userDefaultsKey: String + public let userDefaults: UserDefaults + + private var container: [Key: Value]? = nil + private let rwlock = RWLock() + private let threadSafe: Bool + + public var keys: [Key] { + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "KEYS") + #endif + let result: [Key] + if threadSafe { + rwlock.readLock() + } + if container == nil { + container = userDefaultsContainer + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "EXTRACTED: \(container!)") + #endif + } else { + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "FROM CACHE: \(container!)") + #endif + } + result = Array(container!.keys) + if threadSafe { + rwlock.unlock() + } + return result + } + + public var values: [Value] { + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "VALUES") + #endif + let result: [Value] + if threadSafe { + rwlock.readLock() + } + if container == nil { + container = userDefaultsContainer + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "EXTRACTED: \(container!)") + #endif + } else { + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "FROM CACHE: \(container!)") + #endif + } + result = Array(container!.values) + if threadSafe { + rwlock.unlock() + } + return result + } + + public init(userDefaultsKey: String, userDefaults: UserDefaults = .standard, threadSafe: Bool) { + self.userDefaultsKey = userDefaultsKey + self.userDefaults = userDefaults + self.threadSafe = threadSafe + } + + /// Sets the value for key + /// + /// - Parameters: + /// - value: The value to set for key + /// - key: The key to set value for + public func set(value: Value, forKey key: Key) { + if threadSafe { + rwlock.writeLock() + } + _set(value: value, forKey: key) + if threadSafe { + rwlock.unlock() + } + } + + @discardableResult + public func remove(_ key: Key) -> Value? { + let result: Value? + if threadSafe { + rwlock.writeLock() + } + result = _remove(key) + if threadSafe { + rwlock.unlock() + } + return result + } + + @discardableResult + public func removeValue(forKey: Key) -> Value? { + return self.remove(forKey) + } + + public func contains(_ key: Key) -> Bool { + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "CONTAINS") + #endif + let result: Bool + if threadSafe { + rwlock.readLock() + } + if container == nil { + container = userDefaultsContainer + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "EXTRACTED: \(container!)") + #endif + } else { + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "FROM CACHE: \(container!)") + #endif + } + result = container!.index(forKey: key) != nil + if threadSafe { + rwlock.unlock() + } + return result + } + + public func value(forKey key: Key) -> Value? { + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "VALUE") + #endif + let result: Value? + if threadSafe { + rwlock.readLock() + } + if container == nil { + container = userDefaultsContainer + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "EXTRACTED: \(container!)") + #endif + } else { + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "FROM CACHE: \(container!)") + #endif + } + result = container![key] + if threadSafe { + rwlock.unlock() + } + return result + } + + public func mutateValue(forKey key: Key, mutation: (Value) -> Value) { + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "MUTATE") + #endif + if threadSafe { + rwlock.writeLock() + } + if container == nil { + container = userDefaultsContainer + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "EXTRACTED: \(container!)") + #endif + } else { + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "FROM CACHE: \(container!)") + #endif + } + if let value = container![key] { + container![key] = mutation(value) + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "UPDATING CACHE \(key): \(value), \(container!)") + #endif + userDefaultsContainer = container! + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "CACHE UPDATED \(key): \(value), \(container!)") + #endif + } + if threadSafe { + rwlock.unlock() + } + } + + public var isEmpty: Bool { + return self.keys.isEmpty + } + + // MARK: Subscript + public subscript(key: Key) -> Value? { + get { + return value(forKey: key) + } + set { + if threadSafe { + rwlock.writeLock() + } + defer { + if threadSafe { + rwlock.unlock() + } + } + guard let newValue = newValue else { + _remove(key) + return + } + _set(value: newValue, forKey: key) + } + } + + // MARK: Private + @inline(__always) + private func _set(value: Value, forKey key: Key) { + if container == nil { + container = userDefaultsContainer + } + self.container![key] = value + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "UPDATING CACHE \(key): \(value), \(container!)") + #endif + userDefaultsContainer = container! + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "CACHE UPDATED \(key): \(value), \(container!)") + #endif + } + + @inline(__always) + @discardableResult + private func _remove(_ key: Key) -> Value? { + if container == nil { + container = userDefaultsContainer + } + guard let index = container!.index(forKey: key) else { return nil } + + let tuple = container!.remove(at: index) + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "UPDATING CACHE REMOVE \(key) \(container!)") + #endif + userDefaultsContainer = container! + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "CACHE UPDATED REMOVED \(key) \(container!)") + #endif + return tuple.value + } + + private var userDefaultsContainer: [Key: Value] { + get { + return userDefaults.dictionary(forKey: userDefaultsKey) as! [Key: Value] + } + set { + userDefaults.set(newValue, forKey: userDefaultsKey) + } + } + + public func drop() { + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "DROPPING") + #endif + if threadSafe { + rwlock.writeLock() + } + userDefaults.removeObject(forKey: userDefaultsKey) + container = userDefaultsContainer + #if DEBUG + SGtrace("UD.\(userDefaultsKey)\(threadSafe ? "-ts" : "")", what: "DROPPED: \(container!)") + #endif + if threadSafe { + rwlock.unlock() + } + } + +} + + +#if DEBUG +private let queue = DispatchQueue(label: "app.swiftgram.ios.trace", qos: .utility) + +public func SGtrace(_ domain: String, what: @autoclosure() -> String) { + let string = what() + var rawTime = time_t() + time(&rawTime) + var timeinfo = tm() + localtime_r(&rawTime, &timeinfo) + + var curTime = timeval() + gettimeofday(&curTime, nil) + let seconds = Int(curTime.tv_sec % 60) // Extracting the current second + let microseconds = curTime.tv_usec // Full microsecond precision + + queue.async { + let result = String(format: "[%@] %d-%d-%d %02d:%02d:%02d.%06d %@", arguments: [domain, Int(timeinfo.tm_year) + 1900, Int(timeinfo.tm_mon + 1), Int(timeinfo.tm_mday), Int(timeinfo.tm_hour), Int(timeinfo.tm_min), seconds, microseconds, string]) + + print(result) + } +} +#endif diff --git a/Swiftgram/SGStatus/BUILD b/Swiftgram/SGStatus/BUILD new file mode 100644 index 00000000..8f19fe25 --- /dev/null +++ b/Swiftgram/SGStatus/BUILD @@ -0,0 +1,17 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGStatus", + srcs = glob([ + "Sources/**/*.swift", + ]), + module_name = "SGStatus", + deps = [ + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + "//submodules/TelegramCore:TelegramCore", + "//submodules/TelegramUIPreferences:TelegramUIPreferences", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGStatus/Sources/SGStatus.swift b/Swiftgram/SGStatus/Sources/SGStatus.swift new file mode 100644 index 00000000..23d42bc8 --- /dev/null +++ b/Swiftgram/SGStatus/Sources/SGStatus.swift @@ -0,0 +1,42 @@ +import Foundation +import SwiftSignalKit +import TelegramCore +import TelegramUIPreferences + +public struct SGStatus: Equatable, Codable { + public var status: Int64 + + public static var `default`: SGStatus { + return SGStatus(status: 1) + } + + public init(status: Int64) { + self.status = status + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.status = try container.decodeIfPresent(Int64.self, forKey: "status") ?? 1 + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encodeIfPresent(self.status, forKey: "status") + } +} + +public func updateSGStatusInteractively(accountManager: AccountManager, _ f: @escaping (SGStatus) -> SGStatus) -> Signal { + return accountManager.transaction { transaction -> Void in + transaction.updateSharedData(ApplicationSpecificSharedDataKeys.sgStatus, { entry in + let currentSettings: SGStatus + if let entry = entry?.get(SGStatus.self) { + currentSettings = entry + } else { + currentSettings = SGStatus.default + } + return SharedPreferencesEntry(f(currentSettings)) + }) + } +} diff --git a/Swiftgram/SGStrings/BUILD b/Swiftgram/SGStrings/BUILD new file mode 100644 index 00000000..dea96881 --- /dev/null +++ b/Swiftgram/SGStrings/BUILD @@ -0,0 +1,27 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGStrings", + module_name = "SGStrings", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/AppBundle:AppBundle", + "//Swiftgram/SGLogging:SGLogging" + ], + visibility = [ + "//visibility:public", + ], +) + +filegroup( + name = "SGLocalizableStrings", + srcs = glob(["Strings/*.lproj/SGLocalizable.strings"]), + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGStrings/Sources/LocalizationManager.swift b/Swiftgram/SGStrings/Sources/LocalizationManager.swift new file mode 100644 index 00000000..331586aa --- /dev/null +++ b/Swiftgram/SGStrings/Sources/LocalizationManager.swift @@ -0,0 +1,134 @@ +import Foundation + +// Assuming NGLogging and AppBundle are custom modules, they are imported here. +import SGLogging +import AppBundle + + +public let SGFallbackLocale = "en" + +public class SGLocalizationManager { + + public static let shared = SGLocalizationManager() + + private let appBundle: Bundle + private var localizations: [String: [String: String]] = [:] + private var webLocalizations: [String: [String: String]] = [:] + private let fallbackMappings: [String: String] = [ + // "from": "to" + "zh-hant": "zh-hans", + "be": "ru", + "nb": "no", + "ckb": "ku", + "sdh": "ku" + ] + + private init(fetchLocale: String = SGFallbackLocale) { + self.appBundle = getAppBundle() + // Iterating over all the app languages and loading SGLocalizable.strings + self.appBundle.localizations.forEach { locale in + if locale != "Base" { + localizations[locale] = loadLocalDictionary(for: locale) + } + } + // Downloading one specific locale + self.downloadLocale(fetchLocale) + } + + public func localizedString(_ key: String, _ locale: String = SGFallbackLocale, args: CVarArg...) -> String { + let sanitizedLocale = self.sanitizeLocale(locale) + + if let localizedString = findLocalizedString(forKey: key, inLocale: sanitizedLocale) { + if args.isEmpty { + return String(format: localizedString) + } else { + return String(format: localizedString, arguments: args) + } + } + + SGLogger.shared.log("Strings", "Missing string for key: \(key) in locale: \(locale)") + return key + } + + private func loadLocalDictionary(for locale: String) -> [String: String] { + guard let path = self.appBundle.path(forResource: "SGLocalizable", ofType: "strings", inDirectory: nil, forLocalization: locale) else { + // SGLogger.shared.log("Localization", "Unable to find path for locale: \(locale)") + return [:] + } + + guard let dictionary = NSDictionary(contentsOf: URL(fileURLWithPath: path)) as? [String: String] else { + // SGLogger.shared.log("Localization", "Unable to load dictionary for locale: \(locale)") + return [:] + } + + return dictionary + } + + public func downloadLocale(_ locale: String) { + #if DEBUG + SGLogger.shared.log("Strings", "DEBUG ignoring locale download: \(locale)") + if ({ return true }()) { + return + } + #endif + let sanitizedLocale = self.sanitizeLocale(locale) + guard let url = URL(string: self.getStringsUrl(for: sanitizedLocale)) else { + SGLogger.shared.log("Strings", "Invalid URL for locale: \(sanitizedLocale)") + return + } + + DispatchQueue.global(qos: .background).async { + if let localeDict = NSDictionary(contentsOf: url) as? [String: String] { + DispatchQueue.main.async { + self.webLocalizations[sanitizedLocale] = localeDict + SGLogger.shared.log("Strings", "Successfully downloaded locale \(sanitizedLocale)") + } + } else { + SGLogger.shared.log("Strings", "Failed to download \(sanitizedLocale)") + } + } + } + + private func sanitizeLocale(_ locale: String) -> String { + var sanitizedLocale = locale + let rawSuffix = "-raw" + if locale.hasSuffix(rawSuffix) { + sanitizedLocale = String(locale.dropLast(rawSuffix.count)) + } + + if sanitizedLocale == "pt-br" { + sanitizedLocale = "pt" + } else if sanitizedLocale == "nb" { + sanitizedLocale = "no" + } + + return sanitizedLocale + } + + private func findLocalizedString(forKey key: String, inLocale locale: String) -> String? { + if let string = self.webLocalizations[locale]?[key], !string.isEmpty { + return string + } + if let string = self.localizations[locale]?[key], !string.isEmpty { + return string + } + if let fallbackLocale = self.fallbackMappings[locale] { + return self.findLocalizedString(forKey: key, inLocale: fallbackLocale) + } + return self.localizations[SGFallbackLocale]?[key] + } + + private func getStringsUrl(for locale: String) -> String { + return "https://raw.githubusercontent.com/Swiftgram/Telegram-iOS/master/Swiftgram/SGStrings/Strings/\(locale).lproj/SGLocalizable.strings" + } + +} + +public let i18n = SGLocalizationManager.shared.localizedString + + +public extension String { + func i18n(_ locale: String = SGFallbackLocale, args: CVarArg...) -> String { + return SGLocalizationManager.shared.localizedString(self, locale, args: args) + } +} diff --git a/Swiftgram/SGStrings/Strings/af.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/af.lproj/SGLocalizable.strings new file mode 100644 index 00000000..5acfe970 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/af.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Inhoudinstellings"; + +"Settings.Tabs.Header" = "OORTJIES"; +"Settings.Tabs.HideTabBar" = "Versteek Tabbalk"; +"Settings.Tabs.ShowContacts" = "Wys Kontak Oortjie"; +"Settings.Tabs.ShowNames" = "Wys oortjiename"; + +"Settings.Folders.BottomTab" = "Lêers onderaan"; +"Settings.Folders.BottomTabStyle" = "Bodem Lêerstyl"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Versteek \"%@\""; +"Settings.Folders.RememberLast" = "Maak laaste lêer oop"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram sal die laaste gebruikte lêer oopmaak na herbegin of rekeningwissel."; + +"Settings.Folders.CompactNames" = "Kleiner spasie"; +"Settings.Folders.AllChatsTitle" = "\"Alle Chats\" titel"; +"Settings.Folders.AllChatsTitle.short" = "Kort"; +"Settings.Folders.AllChatsTitle.long" = "Lank"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Verstek"; + + +"Settings.ChatList.Header" = "CHATLYS"; +"Settings.CompactChatList" = "Kompakte Chatlys"; + +"Settings.Profiles.Header" = "PROFIELE"; + +"Settings.Stories.Hide" = "Versteek Stories"; +"Settings.Stories.WarnBeforeView" = "Vra voor besigtiging"; +"Settings.Stories.DisableSwipeToRecord" = "Deaktiveer swiep om op te neem"; + +"Settings.Translation.QuickTranslateButton" = "Vinnige Vertaalknoppie"; + +"Stories.Warning.Author" = "Outeur"; +"Stories.Warning.ViewStory" = "Besigtig Storie?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ SAL KAN SIEN dat jy hul Storie besigtig het."; +"Stories.Warning.NoticeStealth" = "%@ Sal nie kan sien dat jy hul Storie besigtig het nie."; + +"Settings.Photo.Quality.Notice" = "Kwaliteit van uitgaande foto's en fotostories."; +"Settings.Photo.SendLarge" = "Stuur groot foto's"; +"Settings.Photo.SendLarge.Notice" = "Verhoog die sybeperking op saamgeperste beelde tot 2560px."; + +"Settings.VideoNotes.Header" = "RONDE VIDEOS"; +"Settings.VideoNotes.StartWithRearCam" = "Begin met agterkamera"; + +"Settings.CustomColors.Header" = "REKENING KLEURE"; +"Settings.CustomColors.Saturation" = "VERSATIGING"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Stel versadiging op 0%% om rekening kleure te deaktiveer."; + +"Settings.UploadsBoost" = "Oplaai versterking"; +"Settings.DownloadsBoost" = "Aflaai versterking"; +"Settings.DownloadsBoost.Notice" = "Verhoog die aantal parallelle verbindings en die grootte van lêerstukke. As jou netwerk nie die las kan hanteer nie, probeer verskillende opsies wat by jou verbinding pas."; +"Settings.DownloadsBoost.none" = "Gedeaktiveer"; +"Settings.DownloadsBoost.medium" = "Medium"; +"Settings.DownloadsBoost.maximum" = "Maksimum"; + +"Settings.ShowProfileID" = "Wys profiel ID"; +"Settings.ShowDC" = "Wys Data Sentrum"; +"Settings.ShowCreationDate" = "Wys Geskep Datum van Geselskap"; +"Settings.ShowCreationDate.Notice" = "Die skeppingsdatum mag onbekend wees vir sommige gesprekke."; + +"Settings.ShowRegDate" = "Wys Registrasie Datum"; +"Settings.ShowRegDate.Notice" = "Die registrasiedatum is benaderend."; + +"Settings.SendWithReturnKey" = "Stuur met \"terug\" sleutel"; +"Settings.HidePhoneInSettingsUI" = "Versteek telefoon in instellings"; +"Settings.HidePhoneInSettingsUI.Notice" = "Dit sal slegs jou telefoonnommer versteek vanaf die instellingskoppelvlak. Om dit vir ander te versteek, gaan na Privaatheid en Sekuriteit."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "As weg vir 5 sekondes"; + +"ProxySettings.UseSystemDNS" = "Gebruik stelsel DNS"; +"ProxySettings.UseSystemDNS.Notice" = "Gebruik stelsel DNS om uitvaltyd te omseil as jy nie toegang tot Google DNS het nie"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Jy **het nie nodig** %@ nie!"; +"Common.RestartRequired" = "Herbegin benodig"; +"Common.RestartNow" = "Herbegin Nou"; +"Common.OpenTelegram" = "Maak Telegram oop"; +"Common.UseTelegramForPremium" = "Let daarop dat om Telegram Premium te kry, moet jy die amptelike Telegram-app gebruik. Nadat jy Telegram Premium verkry het, sal al sy funksies beskikbaar word in Swiftgram."; + +"Message.HoldToShowOrReport" = "Hou vas om te Wys of te Rapporteer."; + +"Auth.AccountBackupReminder" = "Maak seker jy het 'n rugsteun toegangsmetode. Hou 'n SIM vir SMS of 'n addisionele sessie aangemeld om te verhoed dat jy uitgesluit word."; +"Auth.UnofficialAppCodeTitle" = "Jy kan die kode slegs met die amptelike app kry"; + +"Settings.SmallReactions" = "Klein reaksies"; +"Settings.HideReactions" = "Verberg Reaksies"; + +"ContextMenu.SaveToCloud" = "Stoor na Wolk"; +"ContextMenu.SelectFromUser" = "Kies vanaf Outeur"; + +"Settings.ContextMenu" = "KONTEKSMENU"; +"Settings.ContextMenu.Notice" = "Gedeaktiveerde inskrywings sal beskikbaar wees in die \"Swiftgram\" sub-menu."; + + +"Settings.ChatSwipeOptions" = "Chat List Swipe Options"; +"Settings.DeleteChatSwipeOption" = "Veeg om Klets Te Verwyder"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Trek na Volgende Ongelese Kanaal"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Trek na Volgende Onderwerp"; +"Settings.GalleryCamera" = "Camera in Gallery"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" Button"; +"Settings.SnapDeletionEffect" = "Message Deletion Effects"; + +"Settings.Stickers.Size" = "SIZE"; +"Settings.Stickers.Timestamp" = "Show Timestamp"; + +"Settings.RecordingButton" = "Voice Recording Button"; + +"Settings.DefaultEmojisFirst" = "Prioritise standaard emojis"; +"Settings.DefaultEmojisFirst.Notice" = "Wys standaard emojis voor premium op die emoji sleutelbord"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "geskep: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Sluit aan by %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Geregistreer"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Dubbelklik om boodskap te wysig"; + +"Settings.wideChannelPosts" = "Wye pos in kanale"; +"Settings.ForceEmojiTab" = "Emoji klawerbord standaard"; + +"Settings.forceBuiltInMic" = "Kragtoestel Mikrofoon"; +"Settings.forceBuiltInMic.Notice" = "Indien geaktiveer, sal die app slegs die toestel se mikrofoon gebruik selfs as oorfone aangesluit is."; + +"Settings.hideChannelBottomButton" = "Verberg Kanaal Onderpaneel"; + +"Settings.CallConfirmation" = "Bel Bevestiging"; +"Settings.CallConfirmation.Notice" = "Swiftgram sal om jou bevestiging vra voordat 'n oproep gemaak word."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Maak 'n Oproep?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Maak 'n Video Oproep?"; + +"MutualContact.Label" = "ewige kontak"; + +"Settings.swipeForVideoPIP" = "Video PIP met Veeg"; +"Settings.swipeForVideoPIP.Notice" = "As geaktiveer, sal die veeg van die video dit in Prent-in-Prent modus oopmaak."; diff --git a/Swiftgram/SGStrings/Strings/ar.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/ar.lproj/SGLocalizable.strings new file mode 100644 index 00000000..41f11684 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/ar.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "إعدادات المحتوى"; + +"Settings.Tabs.Header" = "تبويبات"; +"Settings.Tabs.HideTabBar" = "إخفاء شريط علامات التبويب"; +"Settings.Tabs.ShowContacts" = "إظهار تبويب جهات الاتصال"; +"Settings.Tabs.ShowNames" = "إظهار أسماء التبويبات"; + +"Settings.Folders.BottomTab" = "المجلدات في الأسفل"; +"Settings.Folders.BottomTabStyle" = "نمط المجلدات السفلية"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "إخفاء \"%@\""; +"Settings.Folders.RememberLast" = "فتح المجلد الأخير"; +"Settings.Folders.RememberLast.Notice" = "سيفتح Swiftgram آخر مجلد مستخدم عند إعادة تشغيل التطبيق أو تبديل الحسابات."; + +"Settings.Folders.CompactNames" = "مسافات أصغر"; +"Settings.Folders.AllChatsTitle" = "عنوان \"كل المحادثات\""; +"Settings.Folders.AllChatsTitle.short" = "قصير"; +"Settings.Folders.AllChatsTitle.long" = "طويل"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "الافتراضي"; + + +"Settings.ChatList.Header" = "قائمة الفواصل"; +"Settings.CompactChatList" = "قائمة الدردشة المتراصة"; + +"Settings.Profiles.Header" = "الملفات الشخصية"; + +"Settings.Stories.Hide" = "إخفاء القصص"; +"Settings.Stories.WarnBeforeView" = "اسأل قبل العرض"; +"Settings.Stories.DisableSwipeToRecord" = "تعطيل السحب للتسجيل"; + +"Settings.Translation.QuickTranslateButton" = "زر الترجمة الفوري"; + +"Stories.Warning.Author" = "الكاتب"; +"Stories.Warning.ViewStory" = "عرض القصة؟"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ WILL BE يتم إخبارهم بأنك شاهدت قصتهم."; +"Stories.Warning.NoticeStealth" = "%@ لن يتمكن من رؤية أنك شاهدت قصته."; + +"Settings.Photo.Quality.Notice" = "جودة الصور والصور الصادرة والقصص."; +"Settings.Photo.SendLarge" = "إرسال صور كبيرة"; +"Settings.Photo.SendLarge.Notice" = "زيادة الحد الجانبي للصور المضغوطة إلى 2560 بكسل."; + +"Settings.VideoNotes.Header" = "فيديوهات مستديرة"; +"Settings.VideoNotes.StartWithRearCam" = "البدء بالكاميرا الخلفية"; + +"Settings.CustomColors.Header" = "ألوان الحساب"; +"Settings.CustomColors.Saturation" = "مستوى التشبع"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "تعيين التشبع إلى 0%% لتعطيل ألوان الحساب."; + +"Settings.UploadsBoost" = "تعزيز التحميلات"; +"Settings.DownloadsBoost" = "تعزيز التنزيلات"; +"Settings.DownloadsBoost.Notice" = "يزيد من عدد الاتصالات المتوازية وحجم أجزاء الملفات. إذا لم يتمكن شبكتك من تحمل الحمل، حاول خيارات مختلفة تناسب اتصالك."; +"Settings.DownloadsBoost.none" = "تعطيل"; +"Settings.DownloadsBoost.medium" = "متوسط"; +"Settings.DownloadsBoost.maximum" = "الحد الاقصى"; + +"Settings.ShowProfileID" = "إظهار معرف الملف الشخصي ID"; +"Settings.ShowDC" = "إظهار مركز البيانات"; +"Settings.ShowCreationDate" = "إظهار تاريخ إنشاء المحادثة"; +"Settings.ShowCreationDate.Notice" = "قد يكون تاريخ الإنشاء مفقوداً لبضع المحادثات."; + +"Settings.ShowRegDate" = "إظهار تاريخ التسجيل"; +"Settings.ShowRegDate.Notice" = "تاريخ التسجيل تقريبي."; + +"Settings.SendWithReturnKey" = "إرسال مع مفتاح \"العودة\""; +"Settings.HidePhoneInSettingsUI" = "إخفاء الرقم من الإعدادات"; +"Settings.HidePhoneInSettingsUI.Notice" = "سيتم اخفاء رقمك من التطبيق فقط. لأخفاءهُ من المستخدمين الآخرين، يرجى استخدام إعدادات الخصوصية."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "إذا كان بعيدا لمدة 5 ثوان"; + +"ProxySettings.UseSystemDNS" = "استخدم DNS النظام"; +"ProxySettings.UseSystemDNS.Notice" = "استخدم نظام DNS لتجاوز المهلة إذا لم تكن لديك حق الوصول إلى Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "أنت **لا تحتاج** %@!"; +"Common.RestartRequired" = "إعادة التشغيل مطلوب"; +"Common.RestartNow" = "إعادة التشغيل الآن"; +"Common.OpenTelegram" = "افتح Telegram"; +"Common.UseTelegramForPremium" = "يُرجى ملاحظة أنه للحصول على Telegram Premium، يجب عليك استخدام تطبيق تيليجرام الرسمي. بمجرد حصولك على Telegram Premium، ستصبح جميع ميزاته متاحة في Swiftgram."; + +"Message.HoldToShowOrReport" = "اضغط للعرض أو الإبلاغ."; + +"Auth.AccountBackupReminder" = "تأكد من أن لديك طريقة الوصول إلى النسخ الاحتياطي. حافظ على شريحة SIM للرسائل القصيرة أو جلسة إضافية لتسجيل الدخول لتجنب أن تكون مغفلة."; +"Auth.UnofficialAppCodeTitle" = "يمكنك الحصول على الرمز فقط من خلال التطبيق الرسمي"; + +"Settings.SmallReactions" = "ردود أفعال صغيرة"; +"Settings.HideReactions" = "إخفاء الردود"; + +"ContextMenu.SaveToCloud" = "الحفظ في السحابة"; +"ContextMenu.SelectFromUser" = "حدد من المؤلف"; + +"Settings.ContextMenu" = "قائمة السياق"; +"Settings.ContextMenu.Notice" = "المدخلات المعطلة ستكون متوفرة في القائمة الفرعية \"Swiftgram\"."; + + +"Settings.ChatSwipeOptions" = "خيارات التمرير لقائمة المحادثة"; +"Settings.DeleteChatSwipeOption" = "اسحب لحذف المحادثة"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "اسحب للقناة الغير مقروءة التالية"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "اسحب للموضوع التالي"; +"Settings.GalleryCamera" = "الكاميرا في معرض الصور"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "زر \"%@\""; +"Settings.SnapDeletionEffect" = "تأثيرات حذف الرسالة"; + +"Settings.Stickers.Size" = "مقاس"; +"Settings.Stickers.Timestamp" = "إظهار الطابع الزمني"; + +"Settings.RecordingButton" = "زر التسجيل الصوتي"; + +"Settings.DefaultEmojisFirst" = "الأفضلية للرموز التعبيرية الافتراضية"; +"Settings.DefaultEmojisFirst.Notice" = "عرض الرموز التعبيرية الافتراضية قبل الرموز المتميزة في لوحة المفاتيح"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "تم إنشاؤه: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "انضم %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "مسجل"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "اضغط مزدوجًا لتحرير الرسالة"; + +"Settings.wideChannelPosts" = "المشاركات الواسعة في القنوات"; +"Settings.ForceEmojiTab" = "لوحة مفاتيح الرموز التعبيرية افتراضيًا"; + +"Settings.forceBuiltInMic" = "قوة ميكروفون الجهاز"; +"Settings.forceBuiltInMic.Notice" = "إذا تم تمكينه، سيستخدم التطبيق فقط ميكروفون الجهاز حتى لو كانت سماعات الرأس متصلة."; + +"Settings.hideChannelBottomButton" = "إخفاء لوحة قاعدة القناة"; + +"Settings.CallConfirmation" = "تأكيد الاتصال"; +"Settings.CallConfirmation.Notice" = "سيطلب Swiftgram تأكيدك قبل إجراء مكالمة."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "هل ترغب في إجراء مكالمة؟"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "هل ترغب في إجراء مكالمة فيديو؟"; + +"MutualContact.Label" = "جهة اتصال مشتركة"; + +"Settings.swipeForVideoPIP" = "فيديو PIP مع السحب"; +"Settings.swipeForVideoPIP.Notice" = "إذا تم تمكينه، سيفتح سحب الفيديو في وضع الصورة في الصورة."; diff --git a/Swiftgram/SGStrings/Strings/ca.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/ca.lproj/SGLocalizable.strings new file mode 100644 index 00000000..a48c45fa --- /dev/null +++ b/Swiftgram/SGStrings/Strings/ca.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Configuració del Contingut"; + +"Settings.Tabs.Header" = "PESTANYES"; +"Settings.Tabs.HideTabBar" = "Amagar barra de pestanyes"; +"Settings.Tabs.ShowContacts" = "Mostrar Pestanya de Contactes"; +"Settings.Tabs.ShowNames" = "Mostrar noms de les pestanyes"; + +"Settings.Folders.BottomTab" = "Carpetes a la part inferior"; +"Settings.Folders.BottomTabStyle" = "Bottom Folders Style"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Amaga \"%@\""; +"Settings.Folders.RememberLast" = "Obrir l'última carpeta"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram obrirà l'última carpeta utilitzada després de reiniciar o canviar de compte."; + +"Settings.Folders.CompactNames" = "Espaiat més petit"; +"Settings.Folders.AllChatsTitle" = "Títol \"Tots els xats\""; +"Settings.Folders.AllChatsTitle.short" = "Curt"; +"Settings.Folders.AllChatsTitle.long" = "Llarg"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Per defecte"; + + +"Settings.ChatList.Header" = "LLISTA DE XATS"; +"Settings.CompactChatList" = "Llista de xats compacta"; + +"Settings.Profiles.Header" = "PERFILS"; + +"Settings.Stories.Hide" = "Amagar Històries"; +"Settings.Stories.WarnBeforeView" = "Preguntar abans de veure"; +"Settings.Stories.DisableSwipeToRecord" = "Desactivar lliscar per enregistrar"; + +"Settings.Translation.QuickTranslateButton" = "Botó de Traducció Ràpida"; + +"Stories.Warning.Author" = "Autor"; +"Stories.Warning.ViewStory" = "Veure Història?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ PODRÀ VEURE que has vist la seva Història."; +"Stories.Warning.NoticeStealth" = "%@ no podrà veure que has vist la seva Història."; + +"Settings.Photo.Quality.Notice" = "Qualitat de les fotos sortints i històries de fotos."; +"Settings.Photo.SendLarge" = "Enviar fotos grans"; +"Settings.Photo.SendLarge.Notice" = "Incrementar el límit de mida en imatges comprimides a 2560px."; + +"Settings.VideoNotes.Header" = "VÍDEOS RODONS"; +"Settings.VideoNotes.StartWithRearCam" = "Començar amb càmera posterior"; + +"Settings.CustomColors.Header" = "COLORS DEL COMPTE"; +"Settings.CustomColors.Saturation" = "SATURACIÓ"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Estableix la saturació a 0%% per desactivar els colors del compte."; + +"Settings.UploadsBoost" = "Millora de càrregues"; +"Settings.DownloadsBoost" = "Millora de baixades"; +"Settings.DownloadsBoost.Notice" = "Augmenta el nombre de connexions paral·leles i la mida de les parts de fitxer. Si la teva xarxa no pot gestionar la càrrega, prova diferents opcions que s'adaptin a la teva connexió."; +"Settings.DownloadsBoost.none" = "Desactivat"; +"Settings.DownloadsBoost.medium" = "Mitjà"; +"Settings.DownloadsBoost.maximum" = "Màxim"; + +"Settings.ShowProfileID" = "Mostrar ID de perfil"; +"Settings.ShowDC" = "Mostrar Data Center"; +"Settings.ShowCreationDate" = "Mostrar Data de Creació de Xat"; +"Settings.ShowCreationDate.Notice" = "La data de creació pot ser desconeguda per alguns xats."; + +"Settings.ShowRegDate" = "Mostra la data d'inscripció"; +"Settings.ShowRegDate.Notice" = "La data d'inscripció és aproximada."; + +"Settings.SendWithReturnKey" = "Enviar amb clau \"retorn\""; +"Settings.HidePhoneInSettingsUI" = "Amagar telèfon en la interfície d'ajustos"; +"Settings.HidePhoneInSettingsUI.Notice" = "Això només amagarà el teu número de telèfon de la interfície d'ajustos. Per amagar-lo als altres, ves a Privadesa i Seguretat."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Si no hi ha en 5 segons"; + +"ProxySettings.UseSystemDNS" = "Utilitzar DNS del sistema"; +"ProxySettings.UseSystemDNS.Notice" = "Utilitzar DNS del sistema per evitar el temps d'espera si no tens accés a Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "No **necessites** %@!"; +"Common.RestartRequired" = "Reinici requerit"; +"Common.RestartNow" = "Reiniciar Ara"; +"Common.OpenTelegram" = "Obrir Telegram"; +"Common.UseTelegramForPremium" = "Recorda que per obtenir Telegram Premium, has d'utilitzar l'aplicació oficial de Telegram. Un cop hagis obtingut Telegram Premium, totes les seves funcions estaran disponibles a Swiftgram."; + +"Message.HoldToShowOrReport" = "Mantingues per Mostrar o Informar."; + +"Auth.AccountBackupReminder" = "Assegura't de tenir un mètode d'accés de reserva. Mantingues un SIM per a SMS o una sessió addicional registrada per evitar quedar bloquejat."; +"Auth.UnofficialAppCodeTitle" = "Només pots obtenir el codi amb l'aplicació oficial"; + +"Settings.SmallReactions" = "Petites reaccions"; +"Settings.HideReactions" = "Amaga les reaccions"; + +"ContextMenu.SaveToCloud" = "Desar al Núvol"; +"ContextMenu.SelectFromUser" = "Seleccionar de l'Autor"; + +"Settings.ContextMenu" = "MENÚ CONTEXTUAL"; +"Settings.ContextMenu.Notice" = "Les entrades desactivades estaran disponibles al submenú \"Swiftgram\"."; + + +"Settings.ChatSwipeOptions" = "Opcions desplaçament de la llista de xats"; +"Settings.DeleteChatSwipeOption" = "Desplaceu-vos per esborrar la conversa"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Arrossega cap al següent canal no llegit"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Arrosega cap al següent tema"; +"Settings.GalleryCamera" = "Càmera a la galeria"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" Botó"; +"Settings.SnapDeletionEffect" = "Efectes d'eliminació de missatges"; + +"Settings.Stickers.Size" = "GRANOR"; +"Settings.Stickers.Timestamp" = "Mostra l'estona"; + +"Settings.RecordingButton" = "Botó d'enregistrament de veu"; + +"Settings.DefaultEmojisFirst" = "Prioritzar emojis estàndard"; +"Settings.DefaultEmojisFirst.Notice" = "Mostra emojis estàndard abans que premium al teclat emoji"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "creada: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Unida a %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Inscrit"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Toqueu dues vegades per editar el missatge"; + +"Settings.wideChannelPosts" = "Entrades àmplies als canals"; +"Settings.ForceEmojiTab" = "Teclat d'emojis per defecte"; + +"Settings.forceBuiltInMic" = "Força el Micròfon del Dispositiu"; +"Settings.forceBuiltInMic.Notice" = "Si està habilitat, l'aplicació utilitzarà només el micròfon del dispositiu encara que estiguin connectats els auriculars."; + +"Settings.hideChannelBottomButton" = "Amaga el panell inferior del canal"; + +"Settings.CallConfirmation" = "Confirmació de trucada"; +"Settings.CallConfirmation.Notice" = "Swiftgram et demanarà la teva confirmació abans de fer una trucada."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Vols fer una trucada?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Vols fer una videotrucada?"; + +"MutualContact.Label" = "contacte mutu"; + +"Settings.swipeForVideoPIP" = "Vídeo PIP amb desplaçament"; +"Settings.swipeForVideoPIP.Notice" = "Si està habilitat, desplaçar el vídeo l'obrirà en mode Imatge en Imatge."; diff --git a/Swiftgram/SGStrings/Strings/cs.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/cs.lproj/SGLocalizable.strings new file mode 100644 index 00000000..05cf6ed4 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/cs.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Nastavení obsahu"; + +"Settings.Tabs.Header" = "ZÁLOŽKY"; +"Settings.Tabs.HideTabBar" = "Skrýt záložku"; +"Settings.Tabs.ShowContacts" = "Zobrazit záložku kontaktů"; +"Settings.Tabs.ShowNames" = "Zobrazit názvy záložek"; + +"Settings.Folders.BottomTab" = "Složky dole"; +"Settings.Folders.BottomTabStyle" = "Styl dolní složky"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Skrýt \"%@\""; +"Settings.Folders.RememberLast" = "Otevřít poslední složku"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram otevře poslední použitou složku po restartu nebo přepnutí účtu."; + +"Settings.Folders.CompactNames" = "Menší vzdálenost"; +"Settings.Folders.AllChatsTitle" = "Název \"Všechny chaty\""; +"Settings.Folders.AllChatsTitle.short" = "Krátký"; +"Settings.Folders.AllChatsTitle.long" = "Dlouhá"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Výchozí"; + + +"Settings.ChatList.Header" = "CHAT SEZNAM"; +"Settings.CompactChatList" = "Kompaktní seznam chatu"; + +"Settings.Profiles.Header" = "PROFILES"; + +"Settings.Stories.Hide" = "Skrýt příběhy"; +"Settings.Stories.WarnBeforeView" = "Upozornit před zobrazením"; +"Settings.Stories.DisableSwipeToRecord" = "Zakázat přejetí prstem pro nahrávání"; + +"Settings.Translation.QuickTranslateButton" = "Tlačítko pro rychlý překlad"; + +"Stories.Warning.Author" = "Autor"; +"Stories.Warning.ViewStory" = "Zobrazit příběh?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ BUDE VIDĚT, že jste si prohlédl jejich příběh."; +"Stories.Warning.NoticeStealth" = "%@ bude moci vidět, že jste si prohlédl jejich příběh."; + +"Settings.Photo.Quality.Notice" = "Kvalita odchozích fotografií a foto-příběhů."; +"Settings.Photo.SendLarge" = "Poslat velké fotografie"; +"Settings.Photo.SendLarge.Notice" = "Zvýšit limit velikosti komprimovaných obrázků na 2560px."; + +"Settings.VideoNotes.Header" = "KRUHOVÁ VIDEA"; +"Settings.VideoNotes.StartWithRearCam" = "Začít s zadní kamerou"; + +"Settings.CustomColors.Header" = "BARVY ÚČTU"; +"Settings.CustomColors.Saturation" = "SYTOST"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Nastavit sytost na 0%% pro vypnutí barev účtu."; + +"Settings.UploadsBoost" = "Zrychlení nahrávání"; +"Settings.DownloadsBoost" = "Zrychlení stahování"; +"Settings.DownloadsBoost.Notice" = "Zvyšuje počet paralelních připojení a velikost částí souboru. Pokud vaše síť nezvládá zátěž, vyzkoušejte různé možnosti, které vyhovují vašemu připojení."; +"Settings.DownloadsBoost.none" = "Vypnuto"; +"Settings.DownloadsBoost.medium" = "Střední"; +"Settings.DownloadsBoost.maximum" = "Maximální"; + +"Settings.ShowProfileID" = "Zobrazit ID profilu"; +"Settings.ShowDC" = "Zobrazit Data Center"; +"Settings.ShowCreationDate" = "Zobrazit datum vytvoření chatu"; +"Settings.ShowCreationDate.Notice" = "Datum vytvoření chatu může být neznámé pro některé chaty."; + +"Settings.ShowRegDate" = "Zobrazit datum registrace"; +"Settings.ShowRegDate.Notice" = "Datum registrace je přibližné."; + +"Settings.SendWithReturnKey" = "Poslat klávesou \"enter\""; +"Settings.HidePhoneInSettingsUI" = "Skrýt telefon v nastavení"; +"Settings.HidePhoneInSettingsUI.Notice" = "Toto skryje vaše telefonní číslo pouze v nastavení rozhraní. Chcete-li je skryt před ostatními, přejděte na Soukromí a bezpečnost."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Zamknout za 5 sekund"; + +"ProxySettings.UseSystemDNS" = "Použít systémové DNS"; +"ProxySettings.UseSystemDNS.Notice" = "Použít systémové DNS k obejití časového limitu, pokud nemáte přístup k Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Nepotřebujete **%@**!"; +"Common.RestartRequired" = "Vyžadován restart"; +"Common.RestartNow" = "Restartovat nyní"; +"Common.OpenTelegram" = "Otevřít Telegram"; +"Common.UseTelegramForPremium" = "Vezměte prosím na vědomí, že abyste získali Premium, musíte použít oficiální aplikaci Telegram . Jakmile získáte Telegram Premium, všechny jeho funkce budou k dispozici ve Swiftgramu."; + +"Message.HoldToShowOrReport" = "Podržte pro zobrazení nebo nahlášení."; + +"Auth.AccountBackupReminder" = "Ujistěte se, že máte záložní přístupovou metodu. Uchovávejte SIM pro SMS nebo další přihlášenou relaci, abyste předešli zamčení."; +"Auth.UnofficialAppCodeTitle" = "Kód můžete získat pouze s oficiální aplikací"; + +"Settings.SmallReactions" = "Malé reakce"; +"Settings.HideReactions" = "Skrýt reakce"; + +"ContextMenu.SaveToCloud" = "Uložit do cloudu"; +"ContextMenu.SelectFromUser" = "Vybrat od autora"; + +"Settings.ContextMenu" = "KONTEXTOVÉ MENU"; +"Settings.ContextMenu.Notice" = "Zakázané položky budou dostupné v podmenu \"Swiftgram\"."; + + +"Settings.ChatSwipeOptions" = "Možnosti potáhnutí v seznamu chatu"; +"Settings.DeleteChatSwipeOption" = "Přejeďte pro smazání chatu"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Táhnout na další nepřečtený kanál"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Přetáhněte na další téma"; +"Settings.GalleryCamera" = "Fotoaparát v galerii"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "Tlačítko \"%@\""; +"Settings.SnapDeletionEffect" = "Účinky odstranění zpráv"; + +"Settings.Stickers.Size" = "VELIKOST"; +"Settings.Stickers.Timestamp" = "Zobrazit časové razítko"; + +"Settings.RecordingButton" = "Tlačítko nahrávání hlasu"; + +"Settings.DefaultEmojisFirst" = "Upřednostněte standardní emoji"; +"Settings.DefaultEmojisFirst.Notice" = "Zobrazit standardní emoji před prémiovými na klávesnici s emoji"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "vytvořeno: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Připojeno k %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Registrováno"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Dvojitým klepnutím upravte zprávu"; + +"Settings.wideChannelPosts" = "Široké příspěvky ve skupinách"; +"Settings.ForceEmojiTab" = "Emoji klávesnice ve výchozím nastavení"; + +"Settings.forceBuiltInMic" = "Vynutit vestavěný mikrofon zařízení"; +"Settings.forceBuiltInMic.Notice" = "Pokud je povoleno, aplikace použije pouze mikrofon zařízení, i když jsou připojeny sluchátka."; + +"Settings.hideChannelBottomButton" = "Skrýt panel dolního kanálu"; + +"Settings.CallConfirmation" = "Potvrzení hovoru"; +"Settings.CallConfirmation.Notice" = "Swiftgram požádá o vaši potvrzení před uskutečněním hovoru."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Uskutečnit hovor?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Uskutečnit video hovor?"; + +"MutualContact.Label" = "vzájemný kontakt"; + +"Settings.swipeForVideoPIP" = "Video PIP s přetahováním"; +"Settings.swipeForVideoPIP.Notice" = "Pokud je povoleno, poslání videa jej otevře v režimu Obraz v obraze."; diff --git a/Swiftgram/SGStrings/Strings/da.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/da.lproj/SGLocalizable.strings new file mode 100644 index 00000000..cb0c4174 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/da.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Indholdindstillinger"; + +"Settings.Tabs.Header" = "Tabs"; +"Settings.Tabs.HideTabBar" = "Skjul Tabbjælke"; +"Settings.Tabs.ShowContacts" = "Kontakte Tab anzeigen"; +"Settings.Tabs.ShowNames" = "Tabnamen anzeigen"; + +"Settings.Folders.BottomTab" = "Ordner - unten"; +"Settings.Folders.BottomTabStyle" = "Bundmapper Stil"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Skjul \"%@\""; +"Settings.Folders.RememberLast" = "Åbn sidste mappe"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram vil åbne den sidst brugte mappe efter genstart eller konto skift."; + +"Settings.Folders.CompactNames" = "Mindre afstand"; +"Settings.Folders.AllChatsTitle" = "\"Alle Chats\" titel"; +"Settings.Folders.AllChatsTitle.short" = "Kort"; +"Settings.Folders.AllChatsTitle.long" = "Lang"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Standard"; + + +"Settings.ChatList.Header" = "CHAT LISTE"; +"Settings.CompactChatList" = "Kompakt Chatliste"; + +"Settings.Profiles.Header" = "PROFILES"; + +"Settings.Stories.Hide" = "Skjul Historier"; +"Settings.Stories.WarnBeforeView" = "Spørg før visning"; +"Settings.Stories.DisableSwipeToRecord" = "Deaktiver swipe for at optage"; + +"Settings.Translation.QuickTranslateButton" = "Schnellübersetzen-Schaltfläche"; + +"Stories.Warning.Author" = "Forfatter"; +"Stories.Warning.ViewStory" = "Se Historie?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ VIL KUNNE SE at du har set deres Historie."; +"Stories.Warning.NoticeStealth" = "%@ Vil ikke kunne se, at du har set deres Historie."; + +"Settings.Photo.Quality.Notice" = "Kvalitet af udgående fotos og foto-historier."; +"Settings.Photo.SendLarge" = "Send store fotos"; +"Settings.Photo.SendLarge.Notice" = "Forøg sidestørrelsesgrænsen på komprimerede billeder til 2560px."; + +"Settings.VideoNotes.Header" = "RUNDE VIDEOS"; +"Settings.VideoNotes.StartWithRearCam" = "Starte mit umgedrehter Kamera"; + +"Settings.CustomColors.Header" = "KONTOFARVER"; +"Settings.CustomColors.Saturation" = "MÆTNING"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Indstil mætning til 0%% for at deaktivere konto farver."; + +"Settings.UploadsBoost" = "Upload Boost"; +"Settings.DownloadsBoost" = "Download Boost"; +"Settings.DownloadsBoost.Notice" = "Øger antallet af parallelle forbindelser og størrelsen på filstykker. Hvis dit netværk ikke kan håndtere belastningen, kan du prøve forskellige muligheder, der passer til din forbindelse."; +"Settings.DownloadsBoost.none" = "Deaktiveret"; +"Settings.DownloadsBoost.medium" = "Mellem"; +"Settings.DownloadsBoost.maximum" = "Maksimum"; + +"Settings.ShowProfileID" = "Profil-ID anzeigen"; +"Settings.ShowDC" = "Vis Datacenter"; +"Settings.ShowCreationDate" = "Vis Chattens Oprettelsesdato"; +"Settings.ShowCreationDate.Notice" = "Oprettelsesdatoen kan være ukendt for nogle chats."; + +"Settings.ShowRegDate" = "Vis Registreringsdato"; +"Settings.ShowRegDate.Notice" = "Registreringsdatoen er omtrentlig."; + +"Settings.SendWithReturnKey" = "Send med \"return\" tasten"; +"Settings.HidePhoneInSettingsUI" = "Telefon in den Einstellungen ausblenden"; +"Settings.HidePhoneInSettingsUI.Notice" = "Deine Nummer wird nur in der Benutzeroberfläche versteckt. Um sie vor anderen zu verbergen, verwende bitte die Privatsphäre-Einstellungen."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Hvis væk i 5 sekunder"; + +"ProxySettings.UseSystemDNS" = "Brug system DNS"; +"ProxySettings.UseSystemDNS.Notice" = "Brug system DNS for at omgå timeout hvis du ikke har adgang til Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Du **behøver ikke** %@!"; +"Common.RestartRequired" = "Genstart krævet"; +"Common.RestartNow" = "Genstart Nu"; +"Common.OpenTelegram" = "Åben Telegram"; +"Common.UseTelegramForPremium" = "Bemærk venligst, at for at få Telegram Premium skal du bruge den officielle Telegram app. Når du har fået Telegram Premium, vil alle dens funktioner blive tilgængelige i Swiftgram."; + +"Message.HoldToShowOrReport" = "Hold for at Vise eller Rapportere."; + +"Auth.AccountBackupReminder" = "Sørg for, at du har en backup adgangsmetode. Behold et SIM til SMS eller en ekstra session logget ind for at undgå at blive låst ude."; +"Auth.UnofficialAppCodeTitle" = "Du kan kun få koden med den officielle app"; + +"Settings.SmallReactions" = "Små reaktioner"; +"Settings.HideReactions" = "Skjul Reaktioner"; + +"ContextMenu.SaveToCloud" = "In Cloud speichern"; +"ContextMenu.SelectFromUser" = "Vælg fra Forfatter"; + +"Settings.ContextMenu" = "KONTEKSTMENU"; +"Settings.ContextMenu.Notice" = "Deaktiverede indgange vil være tilgængelige i \"Swiftgram\" undermenuen."; + + +"Settings.ChatSwipeOptions" = "Chat List Swipe Options"; +"Settings.DeleteChatSwipeOption" = "Svejp for at slette chat"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Træk til Næste U’læst Kanal"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Træk for at gå til næste emne"; +"Settings.GalleryCamera" = "Kamera i Galleri"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" Knap"; +"Settings.SnapDeletionEffect" = "Besked Sletnings Effekter"; + +"Settings.Stickers.Size" = "STØRRELSE"; +"Settings.Stickers.Timestamp" = "Vis tidsstempel"; + +"Settings.RecordingButton" = "Lydoptageknap"; + +"Settings.DefaultEmojisFirst" = "Prioriter standard emojis"; +"Settings.DefaultEmojisFirst.Notice" = "Vis standard emojis før premium i emoji-tastaturet"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "oprettet: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Tilmeldt %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Registreret"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Dobbelt tryk for at redigere besked"; + +"Settings.wideChannelPosts" = "Brede indlæg i kanaler"; +"Settings.ForceEmojiTab" = "Emoji-tastatur som standard"; + +"Settings.forceBuiltInMic" = "Tving enhedsmikrofon"; +"Settings.forceBuiltInMic.Notice" = "Hvis aktiveret, vil appen kun bruge enhedens mikrofon, selvom hovedtelefoner er tilsluttet."; + +"Settings.hideChannelBottomButton" = "Skjul Kanal Bund Panel"; + +"Settings.CallConfirmation" = "Opkaldsbekræftelse"; +"Settings.CallConfirmation.Notice" = "Swiftgram vil bede om din bekræftelse, før der foretages et opkald."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Foretage et opkald?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Foretage et videoopkald?"; + +"MutualContact.Label" = "fælles kontakt"; + +"Settings.swipeForVideoPIP" = "Video PIP med Swipe"; +"Settings.swipeForVideoPIP.Notice" = "Hvis aktiveret, vil sletning af video åbne den i billede-i-billede-tilstand."; diff --git a/Swiftgram/SGStrings/Strings/de.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/de.lproj/SGLocalizable.strings new file mode 100644 index 00000000..726e485d --- /dev/null +++ b/Swiftgram/SGStrings/Strings/de.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Inhaltliche Einstellungen"; + +"Settings.Tabs.Header" = "Tabs"; +"Settings.Tabs.HideTabBar" = "Tab-Leiste ausblenden"; +"Settings.Tabs.ShowContacts" = "Kontakte Tab anzeigen"; +"Settings.Tabs.ShowNames" = "Tabnamen anzeigen"; + +"Settings.Folders.BottomTab" = "Ordner unten"; +"Settings.Folders.BottomTabStyle" = "Untere Ordner-Stil"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Verberge \"%@\""; +"Settings.Folders.RememberLast" = "Letzten Ordner öffnen"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram wird den zuletzt genutzten Order öffnen, wenn du den Account wechselst oder die App neustartest"; + +"Settings.Folders.CompactNames" = "Kleinerer Abstand"; +"Settings.Folders.AllChatsTitle" = "Titel \"Alle Chats\""; +"Settings.Folders.AllChatsTitle.short" = "Kurze"; +"Settings.Folders.AllChatsTitle.long" = "Lang"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Standard"; + + +"Settings.ChatList.Header" = "CHAT LISTE"; +"Settings.CompactChatList" = "Kompakte Chat-Liste"; + +"Settings.Profiles.Header" = "PROFILES"; + +"Settings.Stories.Hide" = "Stories verbergen"; +"Settings.Stories.WarnBeforeView" = "Vor dem Ansehen fragen"; +"Settings.Stories.DisableSwipeToRecord" = "Zum aufnehmen wischen deaktivieren"; + +"Settings.Translation.QuickTranslateButton" = "Schnellübersetzen-Button"; + +"Stories.Warning.Author" = "Autor"; +"Stories.Warning.ViewStory" = "Story ansehen?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ wird sehen können, dass du die Story angesehen hast."; +"Stories.Warning.NoticeStealth" = "%@ wird nicht sehen können, dass du die Story angesehen hast."; + +"Settings.Photo.Quality.Notice" = "Qualität der gesendeten Fotos und Fotostorys"; +"Settings.Photo.SendLarge" = "Sende große Fotos"; +"Settings.Photo.SendLarge.Notice" = "Seitenlimit für komprimierte Bilder auf 2560px erhöhen"; + +"Settings.VideoNotes.Header" = "RUNDE VIDEOS"; +"Settings.VideoNotes.StartWithRearCam" = "Starte mit umgedrehter Kamera"; + +"Settings.CustomColors.Header" = "ACCOUNT FARBEN"; +"Settings.CustomColors.Saturation" = "SÄTTIGUNG"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Setze Sättigung auf 0%% um Kontofarben zu deaktivieren"; + +"Settings.UploadsBoost" = "Upload Beschleuniger"; +"Settings.DownloadsBoost" = "Download Beschleuniger"; +"Settings.DownloadsBoost.Notice" = "Erhöht die Anzahl der parallelen Verbindungen und die Größe der Dateiabschnitte. Wenn Ihr Netzwerk die Last nicht bewältigen kann, versuchen Sie verschiedene Optionen, die zu Ihrer Verbindung passen."; +"Settings.DownloadsBoost.none" = "Deaktiviert"; +"Settings.DownloadsBoost.medium" = "Mittel"; +"Settings.DownloadsBoost.maximum" = "Maximum"; + +"Settings.ShowProfileID" = "Profil-ID anzeigen"; +"Settings.ShowDC" = "Data Center anzeigen"; +"Settings.ShowCreationDate" = "Chat-Erstellungsdatum anzeigen"; +"Settings.ShowCreationDate.Notice" = "Das Erstellungsdatum kann für einige Chats unbekannt sein."; + +"Settings.ShowRegDate" = "Anmeldedatum anzeigen"; +"Settings.ShowRegDate.Notice" = "Das Registrierungsdatum ist ungefähr."; + +"Settings.SendWithReturnKey" = "Mit \"Enter\" senden"; +"Settings.HidePhoneInSettingsUI" = "Telefon in den Einstellungen ausblenden"; +"Settings.HidePhoneInSettingsUI.Notice" = "Deine Nummer wird nur in der Benutzeroberfläche versteckt. Um sie vor anderen zu verbergen, verwende bitte die Privatsphäre-Einstellungen."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Falls 5 Sekunden inaktiv"; + +"ProxySettings.UseSystemDNS" = "Benutze System DNS"; +"ProxySettings.UseSystemDNS.Notice" = "Benutze System DNS um Timeout zu umgehen, wenn du keinen Zugriff auf Google DNS hast"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Du brauchst %@ nicht!"; +"Common.RestartRequired" = "Benötigt Neustart"; +"Common.RestartNow" = "Jetzt neustarten"; +"Common.OpenTelegram" = "Telegram öffnen"; +"Common.UseTelegramForPremium" = "Bitte beachten Sie, dass Sie die offizielle Telegram-App verwenden müssen, um Telegram Premium zu erhalten. Sobald Sie Telegram Premium erhalten haben, werden alle Funktionen in Swiftgram verfügbar."; + +"Message.HoldToShowOrReport" = "Halten, zum Ansehen oder melden."; + +"Auth.AccountBackupReminder" = "Stelle sicher, dass du eine weiter Möglichkeit hast auf den Account zuzugreifen. Behalte die SIM Karte im SMS zum Login empfangen zu können oder nutze weitere Apps/Geräte mit einer aktive Sitzung deines Accounts."; +"Auth.UnofficialAppCodeTitle" = "Du kannst den Code nur mit der offiziellen App erhalten"; + +"Settings.SmallReactions" = "Kleine Reaktionen"; +"Settings.HideReactions" = "Verberge Reaktionen"; + +"ContextMenu.SaveToCloud" = "In Cloud speichern"; +"ContextMenu.SelectFromUser" = "Vom Autor auswählen"; + +"Settings.ContextMenu" = "KONTEXTMENÜ"; +"Settings.ContextMenu.Notice" = "Deaktivierte Einträge sind im 'Swiftgram'-Untermenü verfügbar."; + + +"Settings.ChatSwipeOptions" = "Chatlisten-Wisch-Optionen"; +"Settings.DeleteChatSwipeOption" = "Wischen zum Löschen des Chats"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Ziehen zum nächsten Kanal"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Ziehen Sie zum nächsten Thema"; +"Settings.GalleryCamera" = "Kamera in der Galerie"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" Schaltfläche"; +"Settings.SnapDeletionEffect" = "Nachrichtenlösch-Effekte"; + +"Settings.Stickers.Size" = "GRÖSSE"; +"Settings.Stickers.Timestamp" = "Zeitstempel anzeigen"; + +"Settings.RecordingButton" = "Sprachaufnahme-Button"; + +"Settings.DefaultEmojisFirst" = "Priorisieren Sie Standard-Emojis"; +"Settings.DefaultEmojisFirst.Notice" = "Zeigen Sie Standard-Emojis vor Premium-Emojis in der Emoji-Tastatur"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "erstellt: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Beigetreten am %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Registriert"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Doppeltippen, um Nachricht zu bearbeiten"; + +"Settings.wideChannelPosts" = "Breite Beiträge in Kanälen"; +"Settings.ForceEmojiTab" = "Emoji-Tastatur standardmäßig"; + +"Settings.forceBuiltInMic" = "Erzwinge Geräte-Mikrofon"; +"Settings.forceBuiltInMic.Notice" = "Wenn aktiviert, verwendet die App nur das Geräte-Mikrofon, auch wenn Kopfhörer angeschlossen sind."; + +"Settings.hideChannelBottomButton" = "Kanalunteres Bedienfeld ausblenden"; + +"Settings.CallConfirmation" = "Anrufbestätigung"; +"Settings.CallConfirmation.Notice" = "Swiftgram wird um Ihre Bestätigung bitten, bevor ein Anruf getätigt wird."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Einen Anruf tätigen?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Einen Videoanruf tätigen?"; + +"MutualContact.Label" = "gemeinsamer Kontakt"; + +"Settings.swipeForVideoPIP" = "Video PIP mit Wischen"; +"Settings.swipeForVideoPIP.Notice" = "Wenn aktiviert, öffnet das Wischen des Videos es im Bild-in-Bild-Modus."; diff --git a/Swiftgram/SGStrings/Strings/el.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/el.lproj/SGLocalizable.strings new file mode 100644 index 00000000..010c2fd7 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/el.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Ρυθμίσεις Περιεχομένου"; + +"Settings.Tabs.Header" = "TABS"; +"Settings.Tabs.HideTabBar" = "Απόκρυψη γραμμής καρτελών"; +"Settings.Tabs.ShowContacts" = "Εμφάνιση Καρτέλας Επαφών"; +"Settings.Tabs.ShowNames" = "Show Tab Names"; + +"Settings.Folders.BottomTab" = "Φάκελοι στο κάτω μέρος"; +"Settings.Folders.BottomTabStyle" = "Ύφος Κάτω Φακέλων"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Απόκρυψη \"%@\""; +"Settings.Folders.RememberLast" = "Άνοιγμα Τελευταίου Φακέλου"; +"Settings.Folders.RememberLast.Notice" = "Το Swiftgram θα ανοίξει τον τελευταίο φάκελο όταν επανεκκινήσετε την εφαρμογή ή αλλάξετε λογαριασμούς."; + +"Settings.Folders.CompactNames" = "Μικρότερη απόσταση"; +"Settings.Folders.AllChatsTitle" = "\"Όλες οι συνομιλίες\" τίτλος"; +"Settings.Folders.AllChatsTitle.short" = "Σύντομο"; +"Settings.Folders.AllChatsTitle.long" = "Εκτενές"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Προεπιλογή"; + + +"Settings.ChatList.Header" = "ΚΑΤΑΛΟΓΟΣ ΤΥΠΟΥ"; +"Settings.CompactChatList" = "Συμπαγής Λίστα Συνομιλίας"; + +"Settings.Profiles.Header" = "PROFILES"; + +"Settings.Stories.Hide" = "Απόκρυψη Ιστοριών"; +"Settings.Stories.WarnBeforeView" = "Ερώτηση Πριν Την Προβολή"; +"Settings.Stories.DisableSwipeToRecord" = "Απενεργοποίηση ολίσθησης για εγγραφή"; + +"Settings.Translation.QuickTranslateButton" = "Γρήγορη μετάφραση κουμπί"; + +"Stories.Warning.Author" = "Συγγραφέας"; +"Stories.Warning.ViewStory" = "Προβολή Ιστορίας?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ ΘΑ ΠΡΕΠΕΙ ΝΑ ΒΛΕΠΕ ότι έχετε δει την Ιστορία τους."; +"Stories.Warning.NoticeStealth" = "%@ δεν θα είναι σε θέση να δείτε ότι έχετε δει την Ιστορία τους."; + +"Settings.Photo.Quality.Notice" = "Ποιότητα των ανεβασμένων φωτογραφιών και ιστοριών."; +"Settings.Photo.SendLarge" = "Αποστολή Μεγάλων Φωτογραφιών"; +"Settings.Photo.SendLarge.Notice" = "Αυξήστε το πλευρικό όριο στις συμπιεσμένες εικόνες στα 2560px."; + +"Settings.VideoNotes.Header" = "ΤΡΟΠΟΣ ΒΙΝΤΕΟ"; +"Settings.VideoNotes.StartWithRearCam" = "Έναρξη με πίσω κάμερα"; + +"Settings.CustomColors.Header" = "ΧΡΩΜΑΤΑ ΛΟΓΑΡΙΑΣΜΟΥ"; +"Settings.CustomColors.Saturation" = "ΑΣΦΑΛΙΣΗ"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Ορίστε σε 0%% για να απενεργοποιήσετε τα χρώματα του λογαριασμού."; + +"Settings.UploadsBoost" = "Ενίσχυση Αποστολής"; +"Settings.DownloadsBoost" = "Ενίσχυση Λήψης"; +"Settings.DownloadsBoost.Notice" = "Αυξάνει τον αριθμό των παράλληλων συνδέσεων και το μέγεθος των κομματιών αρχείου. Σε περίπτωση που το δίκτυό σας δεν μπορεί να διαχειριστεί το φορτίο, δοκιμάστε διαφορετικές επιλογές που ταιριάζουν στη σύνδεσή σας."; +"Settings.DownloadsBoost.none" = "Απενεργοποιημένο"; +"Settings.DownloadsBoost.medium" = "Μεσαίο"; +"Settings.DownloadsBoost.maximum" = "Μέγιστο"; + +"Settings.ShowProfileID" = "Εμφάνιση Αναγνωριστικού Προφίλ"; +"Settings.ShowDC" = "Εμφάνιση Κέντρου Δεδομένων"; +"Settings.ShowCreationDate" = "Εμφάνιση Ημερομηνίας Δημιουργίας Συνομιλίας"; +"Settings.ShowCreationDate.Notice" = "Η ημερομηνία δημιουργίας μπορεί να είναι άγνωστη για μερικές συνομιλίες."; + +"Settings.ShowRegDate" = "Εμφάνιση Ημερομηνίας Εγγραφής"; +"Settings.ShowRegDate.Notice" = "Η ημερομηνία εγγραφής είναι κατά προσέγγιση."; + +"Settings.SendWithReturnKey" = "Αποστολή με κλειδί \"επιστροφή\""; +"Settings.HidePhoneInSettingsUI" = "Απόκρυψη τηλεφώνου στις ρυθμίσεις"; +"Settings.HidePhoneInSettingsUI.Notice" = "Αυτό θα κρύψει μόνο τον αριθμό τηλεφώνου σας από τη διεπαφή ρυθμίσεων. Για να τον αποκρύψετε από άλλους, μεταβείτε στο Privacy and Security."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Εάν είναι μακριά για 5 δευτερόλεπτα"; + +"ProxySettings.UseSystemDNS" = "Χρήση συστήματος DNS"; +"ProxySettings.UseSystemDNS.Notice" = "Χρησιμοποιήστε το σύστημα DNS για να παρακάμψετε το χρονικό όριο αν δεν έχετε πρόσβαση στο Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Du **brauchst kein** %@!"; +"Common.RestartRequired" = "Απαιτείται επανεκκίνηση"; +"Common.RestartNow" = "Επανεκκίνηση Τώρα"; +"Common.OpenTelegram" = "Άνοιγμα Telegram"; +"Common.UseTelegramForPremium" = "Παρακαλώ σημειώστε ότι για να πάρετε Telegram Premium, θα πρέπει να χρησιμοποιήσετε την επίσημη εφαρμογή Telegram. Μόλις λάβετε Telegram Premium, όλα τα χαρακτηριστικά του θα είναι διαθέσιμα στο Swiftgram."; + +"Message.HoldToShowOrReport" = "Κρατήστε για προβολή ή αναφορά."; + +"Auth.AccountBackupReminder" = "Βεβαιωθείτε ότι έχετε μια μέθοδο πρόσβασης αντιγράφων ασφαλείας. Κρατήστε μια SIM για SMS ή μια πρόσθετη συνεδρία συνδεδεμένη για να αποφύγετε να κλειδωθεί."; +"Auth.UnofficialAppCodeTitle" = "Μπορείτε να πάρετε τον κωδικό μόνο με επίσημη εφαρμογή"; + +"Settings.SmallReactions" = "Μικρές Αντιδράσεις"; +"Settings.HideReactions" = "Απόκρυψη Αντιδράσεων"; + +"ContextMenu.SaveToCloud" = "Αποθήκευση στο σύννεφο"; +"ContextMenu.SelectFromUser" = "Επιλέξτε από τον Συγγραφέα"; + +"Settings.ContextMenu" = "KONTEXTMENÜ"; +"Settings.ContextMenu.Notice" = "Deaktivierte Einträge sind im 'Swiftgram'-Untermenü verfügbar."; + + +"Settings.ChatSwipeOptions" = "Επιλογές Συρσίματος Λίστας Συνομιλίας"; +"Settings.DeleteChatSwipeOption" = "Σύρετε για Διαγραφή Συνομιλίας"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Τραβήξτε στο επόμενο μη αναγνωσμένο κανάλι"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Τραβήξτε για το Επόμενο Θέμα"; +"Settings.GalleryCamera" = "Κάμερα στη Γκαλερί"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\" Κουμπί%@\""; +"Settings.SnapDeletionEffect" = "Εφέ Διαγραφής Μηνύματος"; + +"Settings.Stickers.Size" = "ΜΕΓΕΘΟΣ"; +"Settings.Stickers.Timestamp" = "Εμφάνιση Χρονοσήμανσης"; + +"Settings.RecordingButton" = "Πλήκτρο Ηχογράφησης Φωνής"; + +"Settings.DefaultEmojisFirst" = "Δώστε προτεραιότητα στα τυπικά emojis"; +"Settings.DefaultEmojisFirst.Notice" = "Εμφανίστε τυπικά emojis πριν από premium στο πληκτρολόγιο emojis"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "δημιουργήθηκε: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Εντάχθηκε στο %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Εγγεγραμμένος"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Διπλό Πάτημα για Επεξεργασία Μηνύματος"; + +"Settings.wideChannelPosts" = "Πλατείες αναρτήσεις στα κανάλια"; +"Settings.ForceEmojiTab" = "Πληκτρολόγιο Emoji από προεπιλογή"; + +"Settings.forceBuiltInMic" = "Εξαναγκασμός Μικροφώνου Συσκευής"; +"Settings.forceBuiltInMic.Notice" = "Εάν ενεργοποιηθεί, η εφαρμογή θα χρησιμοποιεί μόνο το μικρόφωνο της συσκευής ακόμα και αν είναι συνδεδεμένα ακουστικά."; + +"Settings.hideChannelBottomButton" = "Απόκρυψη Καναλιού Κάτω Πάνελ"; + +"Settings.CallConfirmation" = "Επιβεβαίωση Κλήσης"; +"Settings.CallConfirmation.Notice" = "Η Swiftgram θα ζητήσει την επιβεβαίωσή σας πριν πραγματοποιήσει μια κλήση."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Να κάνω μια Κλήση;"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Να κάνω μια Βιντεοκλήση;"; + +"MutualContact.Label" = "αμοιβαία επαφή"; + +"Settings.swipeForVideoPIP" = "Βίντεο PIP με Swipe"; +"Settings.swipeForVideoPIP.Notice" = "Αν είναι ενεργοποιημένο, το σ swipe video θα το ανοίξει σε λειτουργία Εικόνα μέσα στην Εικόνα."; diff --git a/Swiftgram/SGStrings/Strings/en.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/en.lproj/SGLocalizable.strings new file mode 100644 index 00000000..0383460b --- /dev/null +++ b/Swiftgram/SGStrings/Strings/en.lproj/SGLocalizable.strings @@ -0,0 +1,279 @@ +"Settings.ContentSettings" = "Content Settings"; + +"Settings.Tabs.Header" = "TABS"; +"Settings.Tabs.HideTabBar" = "Hide Tab bar"; +"Settings.Tabs.ShowContacts" = "Show Contacts Tab"; +"Settings.Tabs.ShowNames" = "Show Tab Names"; +"Settings.Tabs.SearchButton" = "Search Button"; +"Settings.Tabs.WideTabBar" = "Wide Tab bar"; +"Settings.Tabs.WideTabBar.Notice" = "Keeps the full width of Tab bar when some tabs are hidden."; + +"Settings.Folders.BottomTab" = "Folders at Bottom"; +"Settings.Folders.BottomTabStyle" = "Bottom Folders Style"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Hide \"%@\""; +"Settings.Folders.RememberLast" = "Open Last Folder"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram will open the last used folder when you restart the app or switch accounts."; + +"Settings.Folders.CompactNames" = "Smaller spacing"; +"Settings.Folders.AllChatsTitle" = "\"All Chats\" title"; +"Settings.Folders.AllChatsTitle.short" = "Short"; +"Settings.Folders.AllChatsTitle.long" = "Long"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Default"; + + +"Settings.ChatList.Header" = "CHAT LIST"; +"Settings.CompactChatList" = "Compact Chat List"; +"Settings.CompactMessagePreview" = "Compact Message Preview"; +"Settings.ChatList.Lines" = "Chat List Lines"; +"Settings.ChatList.Lines.1" = "1 line"; +"Settings.ChatList.Lines.2" = "2 lines"; +"Settings.ChatList.Lines.3" = "3 lines (Default)"; + +"Settings.Profiles.Header" = "PROFILES"; + +"Settings.Stories.Hide" = "Hide Stories"; +"Settings.Stories.WarnBeforeView" = "Ask Before Viewing"; +"Settings.Stories.DisableSwipeToRecord" = "Disable Swipe to Record"; + +"Settings.Translation.QuickTranslateButton" = "Quick Translate button"; +"Settings.Translation.Backend" = "Service"; +/* Do not translate */ +"Settings.Translation.Backend.default" = "Telegram"; +/* Do not translate */ +"Settings.Translation.Backend.gtranslate" = "GTranslate"; +"Settings.Translation.Backend.system" = "System"; +"Settings.Translation.Backend.Notice" = "Swiftgram will fallback to %@ if selected translation service is not available."; + +"Settings.Transcription.Header" = "VOICE-TO-TEXT"; +"Settings.Transcription.Backend" = "Service"; +/* Do not translate */ +"Settings.Transcription.Backend.default" = "Telegram"; +/* Do not translate */ +"Settings.Transcription.Backend.apple" = "Apple"; +"Settings.Transcription.Backend.Notice" = "Swiftgram will fallback to %@ if selected transcription service is not available."; + +"Stories.Warning.Author" = "Author"; +"Stories.Warning.ViewStory" = "View Story?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ WILL BE ABLE TO SEE that you viewed their Story."; +"Stories.Warning.NoticeStealth" = "%@ will not be able to see that you viewed their Story."; + +"Settings.Photo.Quality.Notice" = "Quality of uploaded photos and stories."; +"Settings.Photo.SendLarge" = "Send HD Photos"; +"Settings.Photo.SendLarge.Notice" = "Increase the side limit on compressed images to 2560px."; + +"Settings.VideoNotes.Header" = "ROUND VIDEOS"; +"Settings.VideoNotes.StartWithRearCam" = "Start with Rear Camera"; + +"Settings.CustomColors.Header" = "ACCOUNT COLORS"; +"Settings.CustomColors.Saturation" = "SATURATION"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Set to 0%% to disable account colors."; + +"Settings.UploadsBoost" = "Upload Boost"; +"Settings.DownloadsBoost" = "Download Boost"; +"Settings.DownloadsBoost.Notice" = "Increases number of parallel connections and size of file chunks. In case your network can't handle the load, try different options that suits your connection."; +"Settings.DownloadsBoost.none" = "Disabled"; +"Settings.DownloadsBoost.medium" = "Medium"; +"Settings.DownloadsBoost.maximum" = "Maximum"; + +"Settings.ShowProfileID" = "Show Profile ID"; +"Settings.ShowDC" = "Show Data Center"; +"Settings.ShowCreationDate" = "Show Chat Creation Date"; +"Settings.ShowCreationDate.Notice" = "The creation date may be unknown for some chats."; + +"Settings.ShowRegDate" = "Show Registration Date"; +"Settings.ShowRegDate.Notice" = "The registration date is approximate."; + +"Settings.SendWithReturnKey" = "Send with \"return\" key"; +"Settings.HidePhoneInSettingsUI" = "Hide Phone in Settings"; +"Settings.HidePhoneInSettingsUI.Notice" = "This will only hide your phone number from the settings interface. To hide it from others, go to Privacy and Security."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "If away for 5 seconds"; + +"ProxySettings.UseSystemDNS" = "Use system DNS"; +"ProxySettings.UseSystemDNS.Notice" = "Use system DNS to bypass timeout if you don't have access to Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "You **don't need** %@!"; +"Common.RestartRequired" = "Restart required"; +"Common.RestartNow" = "Restart Now"; +"Common.OpenTelegram" = "Open Telegram"; +"Common.UseTelegramForPremium" = "Please note that to get Telegram Premium, you must use the official Telegram app. Once you have obtained Telegram Premium, all its features will become available in Swiftgram."; +"Common.UpdateOS" = "iOS update required"; +"Common.KnowWhatYouDo" = "Please, change these settings only if you know what they do."; + +"Message.HoldToShowOrReport" = "Hold to Show or Report."; + +"Auth.AccountBackupReminder" = "Make sure you have a backup access method. Keep a SIM for SMS or an additional session logged in to avoid being locked out."; +"Auth.UnofficialAppCodeTitle" = "You can get the code only with official app"; + +"Settings.SmallReactions" = "Small Reactions"; +"Settings.HideReactions" = "Hide Reactions"; + +"ContextMenu.SaveToCloud" = "Save to Cloud"; +"ContextMenu.SelectFromUser" = "Select from Author"; + +"Settings.ContextMenu" = "CONTEXT MENU"; +"Settings.ContextMenu.Notice" = "Disabled entries will be available in \"Swiftgram\" sub-menu."; + + +"Settings.ChatSwipeOptions" = "Chat List Swipe Options"; +"Settings.DeleteChatSwipeOption" = "Swipe to Delete Chat"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Pull to Next Unread Channel"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Pull to Next Topic"; +"Settings.GalleryCamera" = "Camera in Gallery"; +"Settings.GalleryCameraPreview" = "Camera Preview in Gallery"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" Button"; +"Settings.SnapDeletionEffect" = "Message Deletion Effects"; + +"Settings.Stickers.Size" = "SIZE"; +"Settings.Stickers.Timestamp" = "Show Timestamp"; + +"Settings.RecordingButton" = "Voice Recording Button"; + +"Settings.DefaultEmojisFirst" = "Standard emojis first"; +"Settings.DefaultEmojisFirst.Notice" = "Show standard emojis before premium in emoji keyboard"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "created: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Joined %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Registered"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Double-tap to edit message"; + +"Settings.wideChannelPosts" = "Wide posts in channels"; +"Settings.ForceEmojiTab" = "Emoji tab first"; + +"Settings.forceBuiltInMic" = "Force Device Microphone"; +"Settings.forceBuiltInMic.Notice" = "If enabled, app will use only device microphone even if headphones are connected."; + +"Settings.showChannelBottomButton" = "Channel Bottom Panel"; + +"Settings.secondsInMessages" = "Seconds in Messages"; + +"Settings.CallConfirmation" = "Call Confirmation"; +"Settings.CallConfirmation.Notice" = "Swiftgram will ask for your confirmation before making a call."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Make a Call?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Make a Video Call?"; + +"MutualContact.Label" = "mutual contact"; + +"Settings.swipeForVideoPIP" = "Video PIP with Swipe"; +"Settings.swipeForVideoPIP.Notice" = "If enabled, swiping video will open it in Picture-in-Picture mode."; + +"SessionBackup.Title" = "Accounts Backup"; +"SessionBackup.Sessions.Title" = "Sessions"; +"SessionBackup.Actions.Backup" = "Backup to Keychain"; +"SessionBackup.Actions.Restore" = "Restore from Keychain"; +"SessionBackup.Actions.DeleteAll" = "Delete Keychain Backup"; +"SessionBackup.Actions.DeleteOne" = "Delete from Backup"; +"SessionBackup.Actions.RemoveFromApp" = "Remove from App"; +"SessionBackup.LastBackupAt" = "Last Backup: %@"; +"SessionBackup.RestoreOK" = "OK. Sessions restored: %@"; +"SessionBackup.LoggedIn" = "Logged In"; +"SessionBackup.LoggedOut" = "Logged Out"; +"SessionBackup.DeleteAll.Title" = "Delete All Sessions?"; +"SessionBackup.DeleteAll.Text" = "All sessions will be removed from Keychain.\n\nAccounts will not be logged out from Swiftgram."; +"SessionBackup.DeleteSingle.Title" = "Delete 1 (one) Session?"; +"SessionBackup.DeleteSingle.Text" = "%@ session will be removed from Keychain.\n\nAccount will not be logged out from Swiftgram."; +"SessionBackup.RemoveFromApp.Title" = "Remove account from App?"; +"SessionBackup.RemoveFromApp.Text" = "%@ session WILL BE REMOVED from Swiftgram! Session will remain active, so you can restore it later."; +"SessionBackup.Notice" = "Sessions are encrypted and stored in the device Keychain. Sessions never leave your device.\n\nIMPORTANT: To restore sessions on a new device or after an OS reset, you MUST enable encrypted backups, otherwise Keychain won't be transfered.\n\nNOTE: Sessions may still be revoked by Telegram or from another device."; + +"MessageFilter.Title" = "Message Filter"; +"MessageFilter.SubTitle" = "Remove distractions and reduce visibility of messages containing keywords below.\nKeywords are case-sensitive."; +"MessageFilter.Keywords.Title" = "Keywords"; +"MessageFilter.InputPlaceholder" = "Enter keyword"; + +"InputToolbar.Title" = "Formatting Panel"; + +"Notifications.MentionsAndReplies.Title" = "@Mentions and Replies"; +"Notifications.MentionsAndReplies.value.default" = "Default"; +"Notifications.MentionsAndReplies.value.silenced" = "Muted"; +"Notifications.MentionsAndReplies.value.disabled" = "Disabled"; +"Notifications.PinnedMessages.Title" = "Pinned Messages"; +"Notifications.PinnedMessages.value.default" = "Default"; +"Notifications.PinnedMessages.value.silenced" = "Muted"; +"Notifications.PinnedMessages.value.disabled" = "Disabled"; + + +"PayWall.Text" = "Supercharged with Pro features"; + +"PayWall.SessionBackup.Title" = "Accounts Backup"; +"PayWall.SessionBackup.Notice" = "Log-in to accounts without code, even after reinstall. Secure storage with on-device Keychain."; +"PayWall.SessionBackup.Description" = "Changing device or deleting Swiftgram is no longer an issue. Restore all Sessions that are still Active on Telegram servers."; + +"PayWall.MessageFilter.Title" = "Message Filter"; +"PayWall.MessageFilter.Notice" = "Reduce visibility of SPAM, promotions and annoying messages."; +"PayWall.MessageFilter.Description" = "Create a list of keywords you don't want to see often and Swiftgram will reduce distractions."; + +"PayWall.Notifications.Title" = "Disable @mentions and replies"; +"PayWall.Notifications.Notice" = "Hide or mute non-important notifications."; +"PayWall.Notifications.Description" = "No more Pinned Messages or @mentions when you need some peace of mind."; + +"PayWall.InputToolbar.Title" = "Formatting Panel"; +"PayWall.InputToolbar.Notice" = "Bold, Italic, Links? Formatting with just a single tap."; +"PayWall.InputToolbar.Description" = "Apply and clear Formatting or insert new lines like a Pro."; + +"PayWall.AppIcons.Title" = "Unique App Icons and Badges"; +"PayWall.AppIcons.Notice" = "Customize Swiftgram look on your home screen and screenshots."; + +"PayWall.About.Title" = "About Swiftgram Pro"; +"PayWall.About.Notice" = "Free version of Swiftgram provides dozens of features and improvements over Telegram app. Innovating and keeping Swiftgram in sync with monthly Telegram updates is a huge effort that requires a lot of time and expensive hardware.\n\nSwiftgram is an open-source app that respects your privacy and doesn't bother you with ads. Subscribing to Swiftgram Pro you get access to exclusive features and support an independent developer."; +/* DO NOT TRANSLATE */ +"PayWall.About.Signature" = "@Kylmakalle"; +/* DO NOT TRANSLATE */ +"PayWall.About.SignatureURL" = "https://t.me/Kylmakalle"; + +"PayWall.ProSupport.Title" = "Troubles with payment?"; +"PayWall.ProSupport.Contact" = "No worries!"; + +"PayWall.RestorePurchases" = "Restore Purchases"; +"PayWall.Terms" = "Terms of Service"; +"PayWall.Privacy" = "Privacy Policy"; +"PayWall.TermsURL" = "https://swiftgram.app/terms"; +"PayWall.PrivacyURL" = "https://swiftgram.app/privacy"; +"PayWall.Notice.Markdown" = "By subscribing to Swiftgram Pro you agree to the [Swiftgram Terms of Service](%1$@) and [Privacy Policy](%2$@)."; +"PayWall.Notice.Raw" = "By subscribing to Swiftgram Pro you agree to the Swiftgram Terms of Service and Privacy Policy."; + +"PayWall.Button.OpenPro" = "Use Pro features"; +"PayWall.Button.Purchasing" = "Purchasing..."; +"PayWall.Button.Restoring" = "Restoring Purchases..."; +"PayWall.Button.Validating" = "Validating Purchase..."; +"PayWall.Button.PaymentsUnavailable" = "Payments unavailable"; +"PayWall.Button.BuyInAppStore" = "Subscribe in App Store version"; +"PayWall.Button.Subscribe" = "Subscribe for %@ / month"; +"PayWall.Button.ContactingAppStore" = "Contacting App Store..."; + +"Paywall.Error.Title" = "Error"; +"PayWall.ValidationError" = "Validation Error"; +"PayWall.ValidationError.TryAgain" = "Something went wrong during purchase validation. No worries! Try to Restore Purchases a bit later."; +"PayWall.ValidationError.Expired" = "Your subscription expired. Subscribe again to regain access to Pro features."; + +"AppBadge.Title" = "App Badge"; +"AppBadge.Notice" = "Customize App Badge shown on screenshots"; + +"Settings.NY.Header" = "HOLIDAY EFFECTS"; +"Settings.NY.Style" = "Style"; +"Settings.NY.Style.default" = "Disabled"; +"Settings.NY.Style.snow" = "Snow"; +"Settings.NY.Style.lightning" = "Lightning"; +"Settings.NY.Notice" = "Available for a limited time only!"; diff --git a/Swiftgram/SGStrings/Strings/es.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/es.lproj/SGLocalizable.strings new file mode 100644 index 00000000..4fcb6aee --- /dev/null +++ b/Swiftgram/SGStrings/Strings/es.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Configuración de contenido"; + +"Settings.Tabs.Header" = "PESTAÑAS"; +"Settings.Tabs.HideTabBar" = "Ocultar barra de pestaña"; +"Settings.Tabs.ShowContacts" = "Mostrar pestaña de Contactos"; +"Settings.Tabs.ShowNames" = "Mostrar nombres de pestañas"; + +"Settings.Folders.BottomTab" = "Carpetas al fondo"; +"Settings.Folders.BottomTabStyle" = "Estilo de carpetas al fondo"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Ocultar \"%@\""; +"Settings.Folders.RememberLast" = "Abrir última carpeta"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram abrirá la última carpeta usada después de reiniciar o cambiar de cuenta"; + +"Settings.Folders.CompactNames" = "Espaciado más pequeño"; +"Settings.Folders.AllChatsTitle" = "Título \"Todos los Chats\""; +"Settings.Folders.AllChatsTitle.short" = "Corto"; +"Settings.Folders.AllChatsTitle.long" = "Largo"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Por defecto"; + + +"Settings.ChatList.Header" = "LISTA DE CHAT"; +"Settings.CompactChatList" = "Lista de Chat de Compacto"; + +"Settings.Profiles.Header" = "PROFILES"; + +"Settings.Stories.Hide" = "Ocultar Historias"; +"Settings.Stories.WarnBeforeView" = "Preguntar antes de ver"; +"Settings.Stories.DisableSwipeToRecord" = "Desactivar deslizar para grabar"; + +"Settings.Translation.QuickTranslateButton" = "Botón de traducción rápida"; + +"Stories.Warning.Author" = "Autor"; +"Stories.Warning.ViewStory" = "¿Ver historia?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ PODRÁ VER que viste su historia."; +"Stories.Warning.NoticeStealth" = "%@ no podrá ver que viste su historia."; + +"Settings.Photo.Quality.Notice" = "Calidad de las fotos y foto-historias enviadas"; +"Settings.Photo.SendLarge" = "Enviar fotos grandes"; +"Settings.Photo.SendLarge.Notice" = "Aumentar el límite de tamaño de las imágenes comprimidas a 2560px"; + +"Settings.VideoNotes.Header" = "VIDEOS REDONDOS"; +"Settings.VideoNotes.StartWithRearCam" = "Comenzar con la cámara trasera"; + +"Settings.CustomColors.Header" = "COLORES DE LA CUENTA"; +"Settings.CustomColors.Saturation" = "SATURACIÓN"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Establecer saturación en 0%% para desactivar los colores de la cuenta"; + +"Settings.UploadsBoost" = "Aumento de subida"; +"Settings.DownloadsBoost" = "Aumento de descargas"; +"Settings.DownloadsBoost.Notice" = "Aumenta el número de conexiones paralelas y el tamaño de las partes del archivo. Si tu red no puede manejar la carga, prueba diferentes opciones que se adapten a tu conexión."; +"Settings.DownloadsBoost.none" = "Desactivado"; +"Settings.DownloadsBoost.medium" = "Medio"; +"Settings.DownloadsBoost.maximum" = "Máximo"; + +"Settings.ShowProfileID" = "Mostrar ID del perfil"; +"Settings.ShowDC" = "Mostrar Centro de Datos"; +"Settings.ShowCreationDate" = "Mostrar fecha de creación del chat"; +"Settings.ShowCreationDate.Notice" = "La fecha de creación puede ser desconocida para algunos chats."; + +"Settings.ShowRegDate" = "Mostrar fecha de registro"; +"Settings.ShowRegDate.Notice" = "La fecha de inscripción es aproximada."; + +"Settings.SendWithReturnKey" = "Enviar con la tecla \"regresar\""; +"Settings.HidePhoneInSettingsUI" = "Ocultar número en Ajustes"; +"Settings.HidePhoneInSettingsUI.Notice" = "Tu número estará oculto en la interfaz de ajustes solamente. Ve a la configuración de privacidad para ocultarlo a otros."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Si está ausente durante 5 segundos"; + +"ProxySettings.UseSystemDNS" = "Usar DNS del sistema"; +"ProxySettings.UseSystemDNS.Notice" = "Usa el DNS del sistema para omitir el tiempo de espera si no tienes acceso a Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "¡**No necesitas** %@!"; +"Common.RestartRequired" = "Es necesario reiniciar"; +"Common.RestartNow" = "Reiniciar ahora"; +"Common.OpenTelegram" = "Abrir Telegram"; +"Common.UseTelegramForPremium" = "Ten en cuenta que para obtener Telegram Premium, debes usar la aplicación oficial de Telegram. Una vez que haya obtenido Telegram Premium, todas sus características estarán disponibles en Swiftgram."; + +"Message.HoldToShowOrReport" = "Mantenga presionado para mostrar o reportar."; + +"Auth.AccountBackupReminder" = "Asegúrate de que tienes un método de acceso de copia de seguridad. Mantenga una SIM para SMS o una sesión adicional conectada para evitar ser bloqueada."; +"Auth.UnofficialAppCodeTitle" = "Sólo puedes obtener el código con la app oficial"; + +"Settings.SmallReactions" = "Reacciones pequeñas"; +"Settings.HideReactions" = "Ocultar Reacciones"; + +"ContextMenu.SaveToCloud" = "Guardar en la nube"; +"ContextMenu.SelectFromUser" = "Seleccionar del autor"; + +"Settings.ContextMenu" = "MENÚ CONTEXTUAL"; +"Settings.ContextMenu.Notice" = "Las entradas desactivadas estarán disponibles en el submenú \"Swiftgram\"."; + + +"Settings.ChatSwipeOptions" = "Opciones de deslizamiento de la lista de chats"; +"Settings.DeleteChatSwipeOption" = "Deslizar para eliminar chat"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Saltar al siguiente canal no leído"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Deslizar para ir al siguiente tema"; +"Settings.GalleryCamera" = "Cámara en galería"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "Botón \"%@\""; +"Settings.SnapDeletionEffect" = "Efectos de eliminación de mensajes"; + +"Settings.Stickers.Size" = "TAMAÑO"; +"Settings.Stickers.Timestamp" = "Mostrar marca de tiempo"; + +"Settings.RecordingButton" = "Botón de grabación de voz"; + +"Settings.DefaultEmojisFirst" = "Priorizar emojis estándar"; +"Settings.DefaultEmojisFirst.Notice" = "Mostrar emojis estándar antes que premium en el teclado de emojis"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "creado: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Unido a %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Registrado"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Doble toque para editar mensaje"; + +"Settings.wideChannelPosts" = "Publicaciones amplias en canales"; +"Settings.ForceEmojiTab" = "Teclado de emojis por defecto"; + +"Settings.forceBuiltInMic" = "Forzar Micrófono del Dispositivo"; +"Settings.forceBuiltInMic.Notice" = "Si está habilitado, la aplicación utilizará solo el micrófono del dispositivo incluso si se conectan auriculares."; + +"Settings.hideChannelBottomButton" = "Ocultar Panel Inferior del Canal"; + +"Settings.CallConfirmation" = "Confirmación de llamada"; +"Settings.CallConfirmation.Notice" = "Swiftgram pedirá tu confirmación antes de realizar una llamada."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "¿Hacer una llamada?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "¿Hacer una videollamada?"; + +"MutualContact.Label" = "contacto mutuo"; + +"Settings.swipeForVideoPIP" = "Video PIP con deslizamiento"; +"Settings.swipeForVideoPIP.Notice" = "Si está habilitado, deslizar el video lo abrirá en modo imagen en imagen."; diff --git a/Swiftgram/SGStrings/Strings/fa.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/fa.lproj/SGLocalizable.strings new file mode 100644 index 00000000..1581d635 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/fa.lproj/SGLocalizable.strings @@ -0,0 +1,9 @@ +"Settings.Tabs.Header" = "زبانه ها"; +"Settings.Tabs.ShowContacts" = "نمایش برگه مخاطبین"; +"Settings.VideoNotes.Header" = "فیلم های round"; +"Settings.Tabs.ShowNames" = "نشان دادن برگه اسم ها"; +"Settings.HidePhoneInSettingsUI" = "پنهان کردن شماره موبایل در تنظیمات"; +"Settings.HidePhoneInSettingsUI.Notice" = "شماره شما فقط در رابط کاربری پنهان خواهد شد. برای پنهان کردن آن از دید دیگران ، لطفاً از تنظیمات حریم خصوصی استفاده کنید."; +"Settings.ShowProfileID" = "نمایش ایدی پروفایل"; +"Settings.Translation.QuickTranslateButton" = "دکمه ترجمه سریع"; +"ContextMenu.SaveToCloud" = "ذخیره در فضای ابری"; diff --git a/Swiftgram/SGStrings/Strings/fi.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/fi.lproj/SGLocalizable.strings new file mode 100644 index 00000000..3e7ea96f --- /dev/null +++ b/Swiftgram/SGStrings/Strings/fi.lproj/SGLocalizable.strings @@ -0,0 +1,230 @@ +"Settings.ContentSettings" = "Sisällön Asetukset"; + +"Settings.Tabs.Header" = "VÄLILEHDET"; +"Settings.Tabs.HideTabBar" = "Piilota Välilehtipalkki"; +"Settings.Tabs.ShowContacts" = "Näytä Yhteystiedot-välilehti"; +"Settings.Tabs.ShowNames" = "Näytä välilehtien nimet"; + +"Settings.Folders.BottomTab" = "Kansiot alhaalla"; +"Settings.Folders.BottomTabStyle" = "Alhaalla olevien kansioiden tyyli"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Piilota \"%@\""; +"Settings.Folders.RememberLast" = "Avaa viimeisin kansio"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram avaa viimeksi käytetyn kansion uudelleenkäynnistyksen tai tilin vaihdon jälkeen."; + +"Settings.Folders.CompactNames" = "Pienempi väli"; +"Settings.Folders.AllChatsTitle" = "\"Kaikki chatit\" otsikko"; +"Settings.Folders.AllChatsTitle.short" = "Lyhyt"; +"Settings.Folders.AllChatsTitle.long" = "Pitkä"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Oletus"; + + +"Settings.ChatList.Header" = "CHAT LIST"; +"Settings.CompactChatList" = "Kompakti Keskustelulista"; + +"Settings.Profiles.Header" = "PROFILES"; + +"Settings.Stories.Hide" = "Piilota Tarinat"; +"Settings.Stories.WarnBeforeView" = "Kysy ennen katsomista"; +"Settings.Stories.DisableSwipeToRecord" = "Poista pyyhkäisy tallennukseen käytöstä"; + +"Settings.Translation.QuickTranslateButton" = "Pikakäännöspainike"; + +"Stories.Warning.Author" = "Tekijä"; +"Stories.Warning.ViewStory" = "Katso Tarina?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ NÄKEE, että olet katsonut heidän Tarinansa."; +"Stories.Warning.NoticeStealth" = "%@ ei näe, että olet katsonut heidän Tarinansa."; + +"Settings.Photo.Quality.Notice" = "Lähtevien valokuvien ja valokuvatarinoiden laatu."; +"Settings.Photo.SendLarge" = "Lähetä suuria valokuvia"; +"Settings.Photo.SendLarge.Notice" = "Suurenna pakattujen kuvien sivurajaa 2560px:ään."; + +"Settings.VideoNotes.Header" = "PYÖREÄT VIDEOT"; +"Settings.VideoNotes.StartWithRearCam" = "Aloita takakameralla"; + +"Settings.CustomColors.Header" = "TILIN VÄRIT"; +"Settings.CustomColors.Saturation" = "KYLLÄISYYS"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Aseta kylläisyys 0%%:iin poistaaksesi tilin värit käytöstä."; + +"Settings.UploadsBoost" = "Latausten tehostus"; +"Settings.DownloadsBoost" = "Latausten tehostus"; +"Settings.DownloadsBoost.Notice" = "Lisää samanaikaisten yhteyksien määrää ja tiedostopalojen kokoa. Jos verkkoasi ei pysty käsittelemään kuormitusta, kokeile erilaisia vaihtoehtoja, jotka sopivat yhteyteesi."; +"Settings.DownloadsBoost.none" = "Ei käytössä"; +"Settings.DownloadsBoost.medium" = "Keskitaso"; +"Settings.DownloadsBoost.maximum" = "Maksimi"; + +"Settings.ShowProfileID" = "Näytä profiilin ID"; +"Settings.ShowDC" = "Näytä tietokeskus"; +"Settings.ShowCreationDate" = "Näytä keskustelun luontipäivä"; +"Settings.ShowCreationDate.Notice" = "Keskustelun luontipäivä voi olla tuntematon joillekin keskusteluille."; + +"Settings.ShowRegDate" = "Näytä Rekisteröintipäivä"; +"Settings.ShowRegDate.Notice" = "Rekisteröintipäivä on likimääräinen."; + +"Settings.SendWithReturnKey" = "Lähetä 'paluu'-näppäimellä"; +"Settings.HidePhoneInSettingsUI" = "Piilota puhelin asetuksissa"; +"Settings.HidePhoneInSettingsUI.Notice" = "Tämä piilottaa puhelinnumerosi vain asetukset-käyttöliittymästä. Piilottaaksesi sen muilta, siirry kohtaan Yksityisyys ja Turvallisuus."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Jos poissa 5 sekuntia"; + +"ProxySettings.UseSystemDNS" = "Käytä järjestelmän DNS:ää"; +"ProxySettings.UseSystemDNS.Notice" = "Käytä järjestelmän DNS:ää ohittaaksesi aikakatkaisun, jos sinulla ei ole pääsyä Google DNS:ään"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Et **tarvitse** %@!"; +"Common.RestartRequired" = "Uudelleenkäynnistys vaaditaan"; +"Common.RestartNow" = "Käynnistä uudelleen nyt"; +"Common.OpenTelegram" = "Avaa Telegram"; +"Common.UseTelegramForPremium" = "Huomioi, että saat Telegram Premiumin käyttämällä virallista Telegram-sovellusta. Kun olet hankkinut Telegram Premiumin, kaikki sen ominaisuudet ovat saatavilla Swiftgramissa."; +"Common.UpdateOS" = "iOS päivitys vaaditaan"; + +"Message.HoldToShowOrReport" = "Pidä esillä näyttääksesi tai ilmoittaaksesi."; + +"Auth.AccountBackupReminder" = "Varmista, että sinulla on varmuuskopio pääsymenetelmästä. Pidä SIM tekstiviestejä varten tai ylimääräinen istunto kirjautuneena välttääksesi lukkiutumisen."; +"Auth.UnofficialAppCodeTitle" = "Koodin voi saada vain virallisella sovelluksella"; + +"Settings.SmallReactions" = "Pienet reaktiot"; +"Settings.HideReactions" = "Piilota reaktiot"; + +"ContextMenu.SaveToCloud" = "Tallenna Pilveen"; +"ContextMenu.SelectFromUser" = "Valitse Tekijältä"; + +"Settings.ContextMenu" = "KONTEKSTIVALIKKO"; +"Settings.ContextMenu.Notice" = "Poistetut kohteet ovat saatavilla 'Swiftgram'-alavalikossa."; + + +"Settings.ChatSwipeOptions" = "Chat List Swipe Options"; +"Settings.DeleteChatSwipeOption" = "Vedä poistaaksesi keskustelu"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Vetää seuraavaan lukemattomaan kanavaan"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Vedä seuraava aihe"; +"Settings.GalleryCamera" = "Camera in Gallery"; +"Settings.GalleryCameraPreview" = "Kameran esikatselu galleriassa"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" Button"; +"Settings.SnapDeletionEffect" = "Message Deletion Effects"; + +"Settings.Stickers.Size" = "SIZE"; +"Settings.Stickers.Timestamp" = "Show Timestamp"; + +"Settings.RecordingButton" = "Voice Recording Button"; + +"Settings.DefaultEmojisFirst" = "Oletusemojit ensin"; +"Settings.DefaultEmojisFirst.Notice" = "Näytä vakiotunnukset ennen premium-tunnuksia tunnusnäppäimistössä"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "created: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Joined %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Rekisteröity"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Paina kahdesti muokataksesi viestiä"; + +"Settings.wideChannelPosts" = "Leveitä viestejä kanavissa"; +"Settings.ForceEmojiTab" = "Emojivälilehti ensin"; + +"Settings.forceBuiltInMic" = "Pakota laitteen mikrofoni"; +"Settings.forceBuiltInMic.Notice" = "Jos otettu käyttöön, sovellus käyttää vain laitteen mikrofonia, vaikka kuulokkeet olisivatkin liitettynä."; + +"Settings.showChannelBottomButton" = "Kanavan ala-paneeli"; + +"Settings.CallConfirmation" = "Puhelun vahvistus"; +"Settings.CallConfirmation.Notice" = "Swiftgram pyytää vahvistustasi ennen puhelun soittamista."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Soita puhelu?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Soita videopuhelu?"; + +"MutualContact.Label" = "yhteinen yhteys"; + +"Settings.swipeForVideoPIP" = "Video PIP pyyhkäisevällä toiminnolla"; +"Settings.swipeForVideoPIP.Notice" = "Jos se on käytössä, videon pyyhkäisy avaa sen kuvassa kuvassa -tilassa."; + +"SessionBackup.Title" = "Istunnon varmuuskopio"; +"SessionBackup.Sessions.Title" = "Istunnot"; +"SessionBackup.Actions.Backup" = "Varmenteet Keychainiin"; +"SessionBackup.Actions.Restore" = "Palauta Keychainista"; +"SessionBackup.Actions.DeleteAll" = "Poista Keychain-varmuuskopio"; +"SessionBackup.Actions.DeleteOne" = "Poista varmuuskopiosta"; +"SessionBackup.Actions.RemoveFromApp" = "Poista sovelluksesta"; +"SessionBackup.LastBackupAt" = "Viimeisin varmuuskopio: %@"; +"SessionBackup.RestoreOK" = "OK. Istunnot palautettu: %@"; +"SessionBackup.LoggedIn" = "Sisäänkirjautuneena"; +"SessionBackup.LoggedOut" = "Uloskirjautuneena"; +"SessionBackup.DeleteAll.Title" = "Poista kaikki istunnot?"; +"SessionBackup.DeleteAll.Text" = "Kaikki istunnot poistetaan Keychainista.\n\nTilejä ei kirjaudu ulos Swiftgramista."; +"SessionBackup.DeleteSingle.Title" = "Poista 1 (yksi) istunto?"; +"SessionBackup.DeleteSingle.Text" = "%@ istunto poistetaan Keychainista.\n\nTiliä ei kirjaudu ulos Swiftgramista."; +"SessionBackup.RemoveFromApp.Title" = "Poista tili sovelluksesta?"; +"SessionBackup.RemoveFromApp.Text" = "%@ istunto POISTETAAN Swiftgramista! Istunto pysyy aktiivisena, joten voit palauttaa sen myöhemmin."; +"SessionBackup.Notice" = "Istunnot on salattu ja tallennettu laitteen Keychain. Istunnot eivät koskaan jätä laitettasi.\n\nTÄRKEÄÄ: Voit palauttaa istunnot uudelle laitteelle tai käyttöjärjestelmän palautuksen jälkeen sinun TÄYTYY ottaa salatut varmuuskopiot käyttöön, muuten Keychain ei siirretä.\n\nHUOMAUTUS: Istunnot voidaan silti peruuttaa Telegramin tai toisen laitteen kautta."; + +"MessageFilter.Title" = "Viestisuoja"; +"MessageFilter.SubTitle" = "Poista häiriötekijät ja vähennä näkyvyyttä viesteistä, jotka sisältävät alla olevia avainsanoja.\nAvainsanat ovat erikoismerkkien suhteen herkkiä."; +"MessageFilter.Keywords.Title" = "Avainsanat"; +"MessageFilter.InputPlaceholder" = "Syötä avainsana"; + +"InputToolbar.Title" = "Muotoilupaneeli"; + +"Notifications.MentionsAndReplies.Title" = "@Maininnat ja vastaukset"; +"Notifications.MentionsAndReplies.value.default" = "Oletus"; +"Notifications.MentionsAndReplies.value.silenced" = "Mykistetty"; +"Notifications.MentionsAndReplies.value.disabled" = "Ei käytössä"; +"Notifications.PinnedMessages.Title" = "Kiinnitetyt viestit"; +"Notifications.PinnedMessages.value.default" = "Oletus"; +"Notifications.PinnedMessages.value.silenced" = "Mykistetty"; +"Notifications.PinnedMessages.value.disabled" = "Ei käytössä"; + + +"PayWall.Text" = "Tehostettu Pro-ominaisuuksilla"; + +"PayWall.SessionBackup.Title" = "Istunnon varmuuskopio"; +"PayWall.SessionBackup.Notice" = "Palauta istunnot salatusta paikallisesta Apple Keychain -varmuuskopiosta."; + +"PayWall.MessageFilter.Title" = "Viestisuodatin"; +"PayWall.MessageFilter.Notice" = "Vähennä roskapostin, mainosten ja ärsyttävien viestien näkyvyyttä."; + +"PayWall.Notifications.Title" = "Poista @maininnat ja vastaukset käytöstä"; +"PayWall.Notifications.Notice" = "Piilota tai mykistä ei-tärkeitä ilmoituksia."; + +"PayWall.InputToolbar.Title" = "Muotoilupaneeli"; +"PayWall.InputToolbar.Notice" = "Säästä aikaa valmistellessasi julkaisuja paneelilla juuri näppäimistösi yläpuolella."; + +"PayWall.AppIcons.Title" = "Ainutlaatuiset sovelluskuvakkeet"; +"PayWall.AppIcons.Notice" = "Mukauta Swiftgramin ulkoasu aloitusnäytölläsi."; + +"PayWall.About.Title" = "Tietoja Swiftgram Prosta"; +"PayWall.About.Notice" = "Swiftgramin ilmainen versio tarjoaa kymmeniä ominaisuuksia ja parannuksia Telegram-sovellukseen verrattuna. Innovointi ja Swiftgramin synkronointi kuukausittaisiin Telegram-päivityksiin vaatii valtavasti aikaa ja kallista laitteistoa.\n\nSwiftgram on avoimen lähdekoodin sovellus, joka kunnioittaa yksityisyyttäsi eikä vaivaa sinua mainoksilla. Tilatessasi Swiftgram Prota saat pääsyn eksklusiivisiin ominaisuuksiin ja tuet itsenäistä kehittäjää.\n\n- @Kylmakalle"; + +"PayWall.RestorePurchases" = "Palauta ostot"; +"PayWall.Terms" = "Käyttöehdot"; +"PayWall.Privacy" = "Tietosuojakäytäntö"; +"PayWall.TermsURL" = "https://swiftgram.app/ehtosuhteet"; +"PayWall.PrivacyURL" = "https://swiftgram.app/tietosuoja"; +"PayWall.Notice.Markdown" = "Tilatessasi Swiftgram Prota hyväksyt [Swiftgramin käyttöehdot](%1$@) ja [tietosuojakäytännön](%2$@)."; +"PayWall.Notice.Raw" = "Tilatessasi Swiftgram Prota hyväksyt Swiftgramin käyttöehdot ja tietosuojakäytännön."; + +"PayWall.Button.OpenPro" = "Käytä Pro-ominaisuuksia"; +"PayWall.Button.Purchasing" = "Ostetaan..."; +"PayWall.Button.Restoring" = "Palautetaan ostot..."; +"PayWall.Button.Validating" = "Ostosten vahvistaminen..."; +"PayWall.Button.PaymentsUnavailable" = "Maksut eivät saatavilla"; +"PayWall.Button.Subscribe" = "Tilaa %@ / kuukausi"; +"PayWall.Button.ContactingAppStore" = "Otetaan yhteyttä App Storeen..."; + +"Paywall.Error.Title" = "Virhe"; +"PayWall.ValidationError" = "Vahvistusvirhe"; +"PayWall.ValidationError.TryAgain" = "Ostovahvistuksessa tapahtui jokin virhe. Ei hätää! Yritä palauttaa ostot hieman myöhemmin."; diff --git a/Swiftgram/SGStrings/Strings/fr.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/fr.lproj/SGLocalizable.strings new file mode 100644 index 00000000..adc9a1b3 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/fr.lproj/SGLocalizable.strings @@ -0,0 +1,137 @@ +"Settings.ContentSettings" = "Paramètres du contenu"; + +"Settings.Tabs.Header" = "ONGLETS"; +"Settings.Tabs.HideTabBar" = "Masquer la barre d'onglets"; +"Settings.Tabs.ShowContacts" = "Afficher l'onglet Contacts"; +"Settings.Tabs.ShowNames" = "Afficher les noms des onglets"; + +"Settings.Folders.BottomTab" = "Dossiers en bas"; +"Settings.Folders.BottomTabStyle" = "Style des dossiers inférieurs"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Masquer \"%@\""; +"Settings.Folders.RememberLast" = "Ouvrir le dernier dossier"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram ouvrira le dernier dossier utilisé après le redémarrage ou changement de compte"; + +"Settings.Folders.CompactNames" = "Espacement plus petit"; +"Settings.Folders.AllChatsTitle" = "Titre \"Tous les Chats\""; +"Settings.Folders.AllChatsTitle.short" = "Courte"; +"Settings.Folders.AllChatsTitle.long" = "Longue"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Par défaut"; + + +"Settings.ChatList.Header" = "LISTE DE CHAT"; +"Settings.CompactChatList" = "Liste de discussion compacte"; + +"Settings.Profiles.Header" = "PROFILES"; + +"Settings.Stories.Hide" = "Cacher les histoires"; +"Settings.Stories.WarnBeforeView" = "Demander avant de visionner"; +"Settings.Stories.DisableSwipeToRecord" = "Désactiver le glissement pour enregistrer"; + +"Settings.Translation.QuickTranslateButton" = "Bouton de traduction rapide"; + +"Stories.Warning.Author" = "Auteur"; +"Stories.Warning.ViewStory" = "Voir l'histoire?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ SERA autorisé à voir que vous avez vu son histoire."; +"Stories.Warning.NoticeStealth" = "%@ ne sera pas en mesure de voir que vous avez vu leur Histoire."; + +"Settings.Photo.Quality.Notice" = "Qualité des photos et des récits photo sortants"; +"Settings.Photo.SendLarge" = "Envoyer de grandes photos"; +"Settings.Photo.SendLarge.Notice" = "Augmenter la limite latérale des images compressées à 2560px"; + +"Settings.VideoNotes.Header" = "VIDÉOS RONDES"; +"Settings.VideoNotes.StartWithRearCam" = "Commencer avec la caméra arrière"; + +"Settings.CustomColors.Header" = "COULEURS DU COMPTE"; +"Settings.CustomColors.Saturation" = "SATURATION"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Régler la saturation à 0%% pour désactiver les couleurs du compte"; + +"Settings.UploadsBoost" = "Chargements boost"; +"Settings.DownloadsBoost" = "Boost de téléchargements"; +"Settings.DownloadsBoost.none" = "Désactivé"; +"Settings.DownloadsBoost.medium" = "Moyenne"; +"Settings.DownloadsBoost.maximum" = "Maximum"; + +"Settings.ShowProfileID" = "Afficher l'identifiant du profil"; +"Settings.ShowDC" = "Afficher le centre de données"; +"Settings.ShowCreationDate" = "Afficher la date de création du chat"; +"Settings.ShowCreationDate.Notice" = "La date de création peut être inconnue pour certains chats."; + +"Settings.ShowRegDate" = "Afficher la date d'inscription"; +"Settings.ShowRegDate.Notice" = "La date d'inscription est approximative."; + +"Settings.SendWithReturnKey" = "Envoyer avec la clé \"return\""; +"Settings.HidePhoneInSettingsUI" = "Masquer le téléphone dans les paramètres"; +"Settings.HidePhoneInSettingsUI.Notice" = "Votre numéro sera masqué dans l'interface utilisateur uniquement. Pour le masquer aux autres, veuillez utiliser les paramètres de confidentialité."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Si absente pendant 5 secondes"; + +"ProxySettings.UseSystemDNS" = "Utiliser le DNS du système"; +"ProxySettings.UseSystemDNS.Notice" = "Utiliser le DNS système pour contourner le délai d'attente si vous n'avez pas accès à Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Vous **n'avez pas besoin** %@!"; +"Common.RestartRequired" = "Redémarrage nécessaire"; +"Common.RestartNow" = "Redémarrer maintenant"; +"Common.OpenTelegram" = "Ouvrir Telegram"; +"Common.UseTelegramForPremium" = "Veuillez noter que pour obtenir Telegram Premium, vous devez utiliser l'application Telegram officielle. Une fois que vous avez obtenu Telegram Premium, toutes ses fonctionnalités seront disponibles dans Swiftgram."; + +"Message.HoldToShowOrReport" = "Maintenir pour afficher ou rapporter."; + +"Auth.AccountBackupReminder" = "Assurez-vous d'avoir une méthode d'accès de sauvegarde. Gardez une carte SIM pour les SMS ou une session supplémentaire connectée pour éviter d'être bloquée."; +"Auth.UnofficialAppCodeTitle" = "Vous ne pouvez obtenir le code qu'avec l'application officielle"; + +"Settings.SmallReactions" = "Petites réactions"; +"Settings.HideReactions" = "Masquer les réactions"; + +"ContextMenu.SaveToCloud" = "Sauvegarder dans le cloud"; +"ContextMenu.SelectFromUser" = "Sélectionner de l'Auteur"; + +"Settings.ContextMenu" = "MENU CONTEXTUEL"; +"Settings.ContextMenu.Notice" = "Les entrées désactivées seront disponibles dans le sous-menu 'Swiftgram'."; + + +"Settings.ChatSwipeOptions" = "Options de balayage de la liste de chat"; +"Settings.DeleteChatSwipeOption" = "Glisser pour supprimer la conversation"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Tirer vers le prochain canal non lu"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Tirer pour le sujet suivant"; +"Settings.GalleryCamera" = "Appareil photo dans la galerie"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "Bouton \"%@\""; +"Settings.SnapDeletionEffect" = "Effets de suppression de message"; + +"Settings.Stickers.Size" = "TAILLE"; +"Settings.Stickers.Timestamp" = "Afficher l'horodatage"; + +"Settings.RecordingButton" = "Bouton d'enregistrement vocal"; + +"Settings.DefaultEmojisFirst" = "Prioriser les emojis standard"; +"Settings.DefaultEmojisFirst.Notice" = "Afficher les emojis standard avant les emojis premium dans le clavier emoji"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "créé: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Rejoint %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Enregistré"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Appuyez deux fois pour modifier le message"; + +"Settings.wideChannelPosts" = "Messages larges dans les canaux"; +"Settings.ForceEmojiTab" = "Clavier emoji par défaut"; + +"Settings.forceBuiltInMic" = "Forcer le microphone de l'appareil"; +"Settings.forceBuiltInMic.Notice" = "Si activé, l'application utilisera uniquement le microphone de l'appareil même si des écouteurs sont connectés."; + +"Settings.hideChannelBottomButton" = "Masquer le panneau inférieur du canal"; diff --git a/Swiftgram/SGStrings/Strings/he.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/he.lproj/SGLocalizable.strings new file mode 100644 index 00000000..eb4562b7 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/he.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "הגדרות תוכן"; + +"Settings.Tabs.Header" = "כרטיסיות"; +"Settings.Tabs.HideTabBar" = "הסתר סרגל לשוניים"; +"Settings.Tabs.ShowContacts" = "הצג כרטיסיית אנשי קשר"; +"Settings.Tabs.ShowNames" = "הצג שמות כרטיסיות"; + +"Settings.Folders.BottomTab" = "תיקיות בתחתית"; +"Settings.Folders.BottomTabStyle" = "סגנון תיקיות תחתון"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "טלגרם"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "להסתיר \"%@\""; +"Settings.Folders.RememberLast" = "פתח את התיקיה האחרונה"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram תפתח את התיקיה שנעשה בה שימוש לאחרונה לאחר הפעלה מחדש או החלפת חשבון"; + +"Settings.Folders.CompactNames" = "ריווח קטן יותר"; +"Settings.Folders.AllChatsTitle" = "כותרת \"כל הצ'אטים\""; +"Settings.Folders.AllChatsTitle.short" = "קצר"; +"Settings.Folders.AllChatsTitle.long" = "ארוך"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "ברירת מחדל"; + + +"Settings.ChatList.Header" = "רשימת צ'אטים"; +"Settings.CompactChatList" = "רשימת צ'אטים קומפקטית"; + +"Settings.Profiles.Header" = "פרופילים"; + +"Settings.Stories.Hide" = "הסתר סיפורים"; +"Settings.Stories.WarnBeforeView" = "שאל לפני צפייה"; +"Settings.Stories.DisableSwipeToRecord" = "בטל החלקה להקלטה"; + +"Settings.Translation.QuickTranslateButton" = "כפתור תרגום מהיר"; + +"Stories.Warning.Author" = "מחבר"; +"Stories.Warning.ViewStory" = "לצפות בסיפור?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ יוכל לראות שצפית בסיפור שלו."; +"Stories.Warning.NoticeStealth" = "%@ לא יוכל לראות שצפית בסיפור שלו."; + +"Settings.Photo.Quality.Notice" = "איכות התמונות היוצאות והסיפורים בתמונות"; +"Settings.Photo.SendLarge" = "שלח תמונות גדולות"; +"Settings.Photo.SendLarge.Notice" = "הגדל את הגבול הצידי של תמונות מודחקות ל-2560px"; + +"Settings.VideoNotes.Header" = "וידאו מעוגלים"; +"Settings.VideoNotes.StartWithRearCam" = "התחל עם מצלמה אחורית"; + +"Settings.CustomColors.Header" = "צבעי חשבון"; +"Settings.CustomColors.Saturation" = "רווי"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "קבע רווי ל-0%% כדי לבטל צבעי חשבון"; + +"Settings.UploadsBoost" = "תוספת העלאות"; +"Settings.DownloadsBoost" = "תוספת הורדות"; +"Settings.DownloadsBoost.Notice" = "מגביר את מספר החיבורים המקביליים וגודל חלקי הקבצים. אם הרשת שלך לא יכולה להתמודד עם העומס, נסה אפשרויות שונות שמתאימות לחיבור שלך."; +"Settings.DownloadsBoost.none" = "מבוטל"; +"Settings.DownloadsBoost.medium" = "בינוני"; +"Settings.DownloadsBoost.maximum" = "מרבי"; + +"Settings.ShowProfileID" = "הצג מזהה פרופיל"; +"Settings.ShowDC" = "הצג מרכז מידע"; +"Settings.ShowCreationDate" = "הצג תאריך יצירת צ'אט"; +"Settings.ShowCreationDate.Notice" = "ייתכן שתאריך היצירה אינו ידוע עבור חלק מהצ'אטים."; + +"Settings.ShowRegDate" = "הצג תאריך רישום"; +"Settings.ShowRegDate.Notice" = "תאריך הרישום הוא אופציונלי."; + +"Settings.SendWithReturnKey" = "שלח עם מקש \"חזור\""; +"Settings.HidePhoneInSettingsUI" = "הסתר טלפון בהגדרות"; +"Settings.HidePhoneInSettingsUI.Notice" = "המספר שלך יהיה מוסתר בממשק ההגדרות בלבד. עבור להגדרות פרטיות כדי להסתיר אותו מאחרים."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "נעל אוטומטית אחרי 5 שניות"; + +"ProxySettings.UseSystemDNS" = "השתמש ב-DNS של המערכת"; +"ProxySettings.UseSystemDNS.Notice" = "השתמש ב-DNS של המערכת כדי לעקוף זמן תגובה אם אין לך גישה ל-Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "אין **צורך** ב%@!"; +"Common.RestartRequired" = "נדרש הפעלה מחדש"; +"Common.RestartNow" = "הפעל מחדש עכשיו"; +"Common.OpenTelegram" = "פתח טלגרם"; +"Common.UseTelegramForPremium" = "שים לב כי כדי לקבל Telegram Premium, עליך להשתמש באפליקציית Telegram הרשמית. לאחר שקיבלת טלגרם פרימיום, כל התכונות שלו יהיו זמינות ב־Swiftgram."; + +"Message.HoldToShowOrReport" = "החזק כדי להציג או לדווח."; + +"Auth.AccountBackupReminder" = "ודא שיש לך שיטת גישה לגיבוי. שמור כרטיס SIM ל-SMS או פתח סשן נוסף כדי למנוע חסימה."; +"Auth.UnofficialAppCodeTitle" = "תוכל לקבל את הקוד רק דרך האפליקציה הרשמית"; + +"Settings.SmallReactions" = "תגובות קטנות"; +"Settings.HideReactions" = "הסתר תגובות"; + +"ContextMenu.SaveToCloud" = "שמור בענן"; +"ContextMenu.SelectFromUser" = "בחר מהמשתמש"; + +"Settings.ContextMenu" = "תפריט הקשר"; +"Settings.ContextMenu.Notice" = "פריטים מבוטלים יהיו זמינים בתת-תפריט 'Swiftgram'."; + + +"Settings.ChatSwipeOptions" = "אפשרויות גלילה ברשימת צ'אטים"; +"Settings.DeleteChatSwipeOption" = "החלק למחיקת הצ'אט"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "משוך לערוץ לא נקרא הבא"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "משוך כדי להמשיך לנושא הבא"; +"Settings.GalleryCamera" = "מצלמה בגלריה"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "כפתור \"%@\""; +"Settings.SnapDeletionEffect" = "אפקטים של מחיקת הודעות"; + +"Settings.Stickers.Size" = "גודל"; +"Settings.Stickers.Timestamp" = "הצג חותמת זמן"; + +"Settings.RecordingButton" = "כפתור הקלטת קול"; + +"Settings.DefaultEmojisFirst" = "העדף רמזי פנים סטנדרטיים"; +"Settings.DefaultEmojisFirst.Notice" = "הצג רמזי פנים סטנדרטיים לפני פרימיום במקלדת רמזי פנים"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "נוצר: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "הצטרף/הצטרפה ב־%@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "נרשם"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "לחץ פעמיים לעריכת הודעה"; + +"Settings.wideChannelPosts" = "פוסטים רחבים בערוצים"; +"Settings.ForceEmojiTab" = "מקלדת Emoji כברירת מחדל"; + +"Settings.forceBuiltInMic" = "כוח מיקרופון המכשיר"; +"Settings.forceBuiltInMic.Notice" = "אם מופעל, האפליקציה תשתמש רק במיקרופון המכשיר גם כאשר אוזניות מחוברות."; + +"Settings.hideChannelBottomButton" = "הסתר פאנל תחתון של ערוץ"; + +"Settings.CallConfirmation" = "אישור שיחה"; +"Settings.CallConfirmation.Notice" = "Swiftgram יבקש את אישורך לפני ביצוע שיחה."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "לבצע שיחה?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "לבצע שיחת וידאו?"; + +"MutualContact.Label" = "איש קשר משותף"; + +"Settings.swipeForVideoPIP" = "וידאו PIP עם החלקה"; +"Settings.swipeForVideoPIP.Notice" = "אם מופעל, החלקת הווידאו תפתח אותו במצב תמונה בתוך תמונה."; diff --git a/Swiftgram/SGStrings/Strings/hi.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/hi.lproj/SGLocalizable.strings new file mode 100644 index 00000000..6adc148a --- /dev/null +++ b/Swiftgram/SGStrings/Strings/hi.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "कंटेंट सेटिंग्स"; + +"Settings.Tabs.Header" = "टैब"; +"Settings.Tabs.HideTabBar" = "टैब बार छिपाएं"; +"Settings.Tabs.ShowContacts" = "संपर्क टैब दिखाएँ"; +"Settings.Tabs.ShowNames" = "टैब नाम दिखाएं"; + +"Settings.Folders.BottomTab" = "निचले टैब में फोल्डर्स"; +"Settings.Folders.BottomTabStyle" = "बॉटम फोल्डर स्टाइल है"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "आईओएस"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "टेलीग्राम"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "\"%@\" छिपाएं"; +"Settings.Folders.RememberLast" = "आखिरी फोल्डर खोलें"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram पुनः आरंभ या खाता स्विच करने के बाद अंतिम प्रयुक्त फोल्डर को खोलेगा"; + +"Settings.Folders.CompactNames" = "कम अंतराल"; +"Settings.Folders.AllChatsTitle" = "\"सभी चैट\" शीर्षक"; +"Settings.Folders.AllChatsTitle.short" = "संक्षिप्त"; +"Settings.Folders.AllChatsTitle.long" = "लंबा"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "डिफ़ॉल्ट"; + + +"Settings.ChatList.Header" = "चैट सूची"; +"Settings.CompactChatList" = "संक्षिप्त चैट सूची"; + +"Settings.Profiles.Header" = "प्रोफाइल"; + +"Settings.Stories.Hide" = "कहानियाँ छुपाएं"; +"Settings.Stories.WarnBeforeView" = "देखने से पहले पूछें"; +"Settings.Stories.DisableSwipeToRecord" = "रिकॉर्ड करने के लिए स्वाइप को अक्षम करें"; + +"Settings.Translation.QuickTranslateButton" = "त्वरित अनुवाद बटन"; + +"Stories.Warning.Author" = "लेखक"; +"Stories.Warning.ViewStory" = "कहानी देखें"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ देख सकते हैं कि आपने उनकी कहानी देखी है।"; +"Stories.Warning.NoticeStealth" = "%@ नहीं देख सकते कि आपने उनकी कहानी देखी है।"; + +"Settings.Photo.Quality.Notice" = "भेजे गए फोटो और फोटो-कहानियों की गुणवत्ता"; +"Settings.Photo.SendLarge" = "बड़े फोटो भेजें"; +"Settings.Photo.SendLarge.Notice" = "संकुचित छवियों पर साइड सीमा को 2560px तक बढ़ाएं"; + +"Settings.VideoNotes.Header" = "गोल वीडियो"; +"Settings.VideoNotes.StartWithRearCam" = "रियर कैमरा के साथ शुरू करें"; + +"Settings.CustomColors.Header" = "खाता रंग"; +"Settings.CustomColors.Saturation" = "संतृप्ति"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "खाता रंगों को निष्क्रिय करने के लिए संतृप्ति को 0%% पर सेट करें"; + +"Settings.UploadsBoost" = "अपलोड बूस्ट"; +"Settings.DownloadsBoost" = "डाउनलोड बूस्ट"; +"Settings.DownloadsBoost.Notice" = "पैरलेल कनेक्शनों की संख्या और फ़ाइल फ़्रैगमेंट का आकार बढ़ाता है। अगर आपका नेटवर्क लोड को संभाल नहीं सकता है, तो अपने कनेक्शन के अनुरूप अलग-अलग विकल्प आजमाएं।"; +"Settings.DownloadsBoost.none" = "निष्क्रिय"; +"Settings.DownloadsBoost.medium" = "माध्यम"; +"Settings.DownloadsBoost.maximum" = "अधिकतम"; + +"Settings.ShowProfileID" = "प्रोफ़ाइल ID दिखाएं"; +"Settings.ShowDC" = "डेटा सेंटर दिखाएं"; +"Settings.ShowCreationDate" = "चैट निर्माण तिथि दिखाएं"; +"Settings.ShowCreationDate.Notice" = "कुछ चैट के लिए निर्माण तिथि अज्ञात हो सकती है।"; + +"Settings.ShowRegDate" = "पंजीकरण दिनांक दिखाएं"; +"Settings.ShowRegDate.Notice" = "पंजीकरण दिनांक अनुमानित हो सकती है।"; + +"Settings.SendWithReturnKey" = "\"वापसी\" कुंजी के साथ भेजें"; +"Settings.HidePhoneInSettingsUI" = "सेटिंग्स में फोन छिपाएं"; +"Settings.HidePhoneInSettingsUI.Notice" = "आपका नंबर केवल सेटिंग्स UI में छिपा होगा। इसे दूसरों से छिपाने के लिए गोपनीयता सेटिंग्स में जाएं।"; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "5 सेकंड के लिए दूर रहने पर"; + +"ProxySettings.UseSystemDNS" = "सिस्टम डीएनएस का प्रयोग करें"; +"ProxySettings.UseSystemDNS.Notice" = "यदि आपके पास Google DNS तक पहुँच नहीं है तो टाइमआउट से बचने के लिए सिस्टम DNS का उपयोग करें"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "आपको %@ की **आवश्यकता नहीं** है!"; +"Common.RestartRequired" = "पुनः आरंभ की आवश्यकता"; +"Common.RestartNow" = "अभी रीस्टार्ट करें"; +"Common.OpenTelegram" = "टेलीग्राम खोलें"; +"Common.UseTelegramForPremium" = "कृपया ध्यान दें कि टेलीग्राम प्रीमियम प्राप्त करने के लिए आपको आधिकारिक टेलीग्राम ऐप का उपयोग करना होगा। एक बार जब आप टेलीग्राम प्रीमियम प्राप्त कर लेंगे, तो इसकी सभी सुविधाएं स्विफ्टग्राम में उपलब्ध हो जाएंगी।"; + +"Message.HoldToShowOrReport" = "दिखाने या रिपोर्ट करने के लिए दबाए रखें।"; + +"Auth.AccountBackupReminder" = "सुनिश्चित करें कि आपके पास बैकअप एक्सेस विधि है। एसएमएस के लिए एक सिम रखें या बाहर निकलने से बचने के लिए एक अतिरिक्त सत्र में लॉग इन करें।"; +"Auth.UnofficialAppCodeTitle" = "आप केवल आधिकारिक ऐप से ही कोड प्राप्त कर सकते हैं"; + +"Settings.SmallReactions" = "छोटी-छोटी प्रतिक्रियाएँ"; +"Settings.HideReactions" = "प्रतिक्रियाएँ छिपाएं"; + +"ContextMenu.SaveToCloud" = "क्लाउड में सहेजें"; +"ContextMenu.SelectFromUser" = "लेखक में से चुनें"; + +"Settings.ContextMenu" = "संदर्भ मेनू"; +"Settings.ContextMenu.Notice" = "अक्षम प्रविष्टियाँ \"स्विफ्टग्राम\" उप-मेनू में उपलब्ध होंगी।"; + + +"Settings.ChatSwipeOptions" = "चैटलिस्ट स्वाइप विकल्प"; +"Settings.DeleteChatSwipeOption" = "चैट हटाने के लिए स्वैप करें"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "अगले अपठित चैनल पर खींचें"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "अगले विषय को खींचें"; +"Settings.GalleryCamera" = "गैलरी में कैमरा"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" बटन"; +"Settings.SnapDeletionEffect" = "संदेश विलोपन प्रभाव"; + +"Settings.Stickers.Size" = "आकार"; +"Settings.Stickers.Timestamp" = "टाइमस्टैंप दिखाएं"; + +"Settings.RecordingButton" = "वॉयस रिकॉर्डिंग बटन"; + +"Settings.DefaultEmojisFirst" = "मुख्यत: मानक इमोजी को प्राथमिकता दें"; +"Settings.DefaultEmojisFirst.Notice" = "इमोजी कीबोर्ड में प्रीमियम से पहले मानक इमोजी दिखाएं"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "बनाया गया: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "%@ में शामिल हो गया"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "पंजीकृत"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "संदेश संपादित करने के लिए दो बार टैप करें"; + +"Settings.wideChannelPosts" = "चैनल में चौड़े पोस्ट"; +"Settings.ForceEmojiTab" = "डिफ़ॉल्ट ईमोजी कुंजीपटल"; + +"Settings.forceBuiltInMic" = "फ़ोर्स डिवाइस माइक्रोफ़ोन"; +"Settings.forceBuiltInMic.Notice" = "यदि सक्षम है, ऐप केवल उपकरण का माइक्रोफ़ोन उपयोग करेगा भले ही हेडफ़ोन कनेक्ट किए हों।"; + +"Settings.hideChannelBottomButton" = "चैनल बॉटम पैनल छिपाएँ"; + +"Settings.CallConfirmation" = "कॉल पुष्टि"; +"Settings.CallConfirmation.Notice" = "Swiftgram कॉल करने से पहले आपकी पुष्टि मांगेगा।"; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "कॉल करें?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "वीडियो कॉल करें?"; + +"MutualContact.Label" = "आपसी संपर्क"; + +"Settings.swipeForVideoPIP" = "वीडियो PIP स्वाइप के साथ"; +"Settings.swipeForVideoPIP.Notice" = "यदि सक्षम है, तो वीडियो को स्वाइप करने से यह चित्र-इन-चित्र मोड में खोला जाएगा।"; diff --git a/Swiftgram/SGStrings/Strings/hu.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/hu.lproj/SGLocalizable.strings new file mode 100644 index 00000000..d357bb69 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/hu.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Tartalombeállítások"; + +"Settings.Tabs.Header" = "FÜLEK"; +"Settings.Tabs.HideTabBar" = "Feliratcsík elrejtése"; +"Settings.Tabs.ShowContacts" = "Kapcsolatok fül megjelenítése"; +"Settings.Tabs.ShowNames" = "Feliratcsík nevek megjelenítése"; + +"Settings.Folders.BottomTab" = "Könyvtárak az alján"; +"Settings.Folders.BottomTabStyle" = "Alsó könyvtár stílus"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Elrejtése \"%@\""; +"Settings.Folders.RememberLast" = "Utolsó mappa megnyitása"; +"Settings.Folders.RememberLast.Notice" = "A Swiftgram az utoljára használt mappát fogja megnyitni, amikor újraindítja az alkalmazást vagy fiókok között vált."; + +"Settings.Folders.CompactNames" = "Kisebb térköz"; +"Settings.Folders.AllChatsTitle" = "\"Minden Beszélgetés\" cím"; +"Settings.Folders.AllChatsTitle.short" = "Rövid"; +"Settings.Folders.AllChatsTitle.long" = "Hosszú"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Alapértelmezett"; + + +"Settings.ChatList.Header" = "BESZÉLGETÉS LISTA"; +"Settings.CompactChatList" = "Kompakt Beszélgetés Lista"; + +"Settings.Profiles.Header" = "PROFIL"; + +"Settings.Stories.Hide" = "Történetek elrejtése"; +"Settings.Stories.WarnBeforeView" = "Kérdezzen megtekintés előtt"; +"Settings.Stories.DisableSwipeToRecord" = "Húzás letiltása felvételhez"; + +"Settings.Translation.QuickTranslateButton" = "Gyors Fordítás gomb"; + +"Stories.Warning.Author" = "Szerző"; +"Stories.Warning.ViewStory" = "Történet megtekintése?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ LÁTNI FOGJA, hogy megtekintetted a történetüket."; +"Stories.Warning.NoticeStealth" = "%@ nem fogja látni, hogy megtekintetted a történetüket."; + +"Settings.Photo.Quality.Notice" = "Feltöltött fényképek és történetek minősége."; +"Settings.Photo.SendLarge" = "Nagy fényképek küldése"; +"Settings.Photo.SendLarge.Notice" = "Növelje a tömörített képek oldalméretének határát 2560px-re."; + +"Settings.VideoNotes.Header" = "KEREK VIDEÓK"; +"Settings.VideoNotes.StartWithRearCam" = "Kezdje a hátsó kamerával"; + +"Settings.CustomColors.Header" = "FIÓK SZÍNEI"; +"Settings.CustomColors.Saturation" = "TELÍTETTSÉG"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Színértéket 0%%-ra állítva az fiókszíneket letiltja."; + +"Settings.UploadsBoost" = "Feltöltés fokozása"; +"Settings.DownloadsBoost" = "Letöltés fokozása"; +"Settings.DownloadsBoost.Notice" = "Növeli a párhuzamos kapcsolatok számát és a fájlok darabjainak méretét. Ha a hálózatod nem képes kezelni a terhelést, próbálj ki különböző opciókat, amelyek illeszkednek a kapcsolatodhoz."; +"Settings.DownloadsBoost.none" = "Kikapcsolva"; +"Settings.DownloadsBoost.medium" = "Közepes"; +"Settings.DownloadsBoost.maximum" = "Maximális"; + +"Settings.ShowProfileID" = "Profil azonosító megjelenítése"; +"Settings.ShowDC" = "Adatközpont megjelenítése"; +"Settings.ShowCreationDate" = "Beszélgetés létrehozásának dátumának megjelenítése"; +"Settings.ShowCreationDate.Notice" = "A beszélgetés létrehozásának dátuma ismeretlen lehet néhány csevegésnél."; + +"Settings.ShowRegDate" = "Regisztrációs Dátum Megjelenítése"; +"Settings.ShowRegDate.Notice" = "A regisztrációs dátum csak hozzávetőleges."; + +"Settings.SendWithReturnKey" = "Küldés 'vissza' gombbal"; +"Settings.HidePhoneInSettingsUI" = "Telefonszám elrejtése a beállításokban"; +"Settings.HidePhoneInSettingsUI.Notice" = "Ezzel csak a telefonszámát rejti el a beállítások felületen. Ha mások számára is el akarja rejteni, menjen a Adatvédelem és biztonság menübe."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Ha 5 másodpercig távol van"; + +"ProxySettings.UseSystemDNS" = "Rendszer DNS használata"; +"ProxySettings.UseSystemDNS.Notice" = "Használja a rendszer DNS-t, ha nem fér hozzá a Google DNS-hez"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Nem **szükséges** %@!"; +"Common.RestartRequired" = "Újraindítás szükséges"; +"Common.RestartNow" = "Újraindítás most"; +"Common.OpenTelegram" = "Telegram megnyitása"; +"Common.UseTelegramForPremium" = "Kérjük vegye figyelembe, hogy a Telegram Prémiumhoz az hivatalos Telegram appot kell használnia. Amint megkapta a Telegram Prémiumot, Swiftgram összes funkciója elérhető lesz."; + +"Message.HoldToShowOrReport" = "Tartsa lenyomva a Megjelenítéshez vagy Jelentéshez."; + +"Auth.AccountBackupReminder" = "Győződjön meg róla, hogy van biztonsági másolat hozzáférési módszere. Tartsa meg a SMS-hez használt SIM-et vagy egy másik bejelentkezett munkamenetet, hogy elkerülje a kizárást."; +"Auth.UnofficialAppCodeTitle" = "A kódot csak a hivatalos alkalmazással szerezheti meg"; + +"Settings.SmallReactions" = "Kis reakciók"; +"Settings.HideReactions" = "Reakciók Elrejtése"; + +"ContextMenu.SaveToCloud" = "Mentés a Felhőbe"; +"ContextMenu.SelectFromUser" = "Kiválasztás a Szerzőtől"; + +"Settings.ContextMenu" = "KONTEXTUS MENÜ"; +"Settings.ContextMenu.Notice" = "A kikapcsolt bejegyzések elérhetők lesznek a 'Swiftgram' almenüjében."; + + +"Settings.ChatSwipeOptions" = "Csevegőlista húzás opciók"; +"Settings.DeleteChatSwipeOption" = "Húzza át az üzenet törléséhez"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Húzza a következő olvasatlan csatornához"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Húzza le a következő témához"; +"Settings.GalleryCamera" = "Kamera a Galériában"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" Gomb"; +"Settings.SnapDeletionEffect" = "Üzenet törlés hatások"; + +"Settings.Stickers.Size" = "MÉRET"; +"Settings.Stickers.Timestamp" = "Időbélyeg Megjelenítése"; + +"Settings.RecordingButton" = "Hangrögzítés Gomb"; + +"Settings.DefaultEmojisFirst" = "Prioritize standard emojis"; +"Settings.DefaultEmojisFirst.Notice" = "Mutassa az alap emojisokat az emoji billentyűzet előtt a prémiumok helyett"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "létrehozva: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Csatlakozott %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Regisztrált"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Dupla koppintás a üzenet szerkesztéséhez"; + +"Settings.wideChannelPosts" = "Széles posztok csatornákban"; +"Settings.ForceEmojiTab" = "Alapértelmezett Emoji billentyűzet"; + +"Settings.forceBuiltInMic" = "Eszköz mikrofonjának kényszerítése"; +"Settings.forceBuiltInMic.Notice" = "Ha engedélyezve van, az alkalmazás csak az eszköz mikrofonját fogja használni, még akkor is, ha a fejhallgató csatlakoztatva van."; + +"Settings.hideChannelBottomButton" = "Kanal Alsó Panel Elrejtése"; + +"Settings.CallConfirmation" = "Hívás megerősítése"; +"Settings.CallConfirmation.Notice" = "A Swiftgram megkéri a megerősítését, mielőtt hívást indítana."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Hívást kezdeni?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Videóhívást kezdeni?"; + +"MutualContact.Label" = "közöns kontakt"; + +"Settings.swipeForVideoPIP" = "Videó PIP a húzással"; +"Settings.swipeForVideoPIP.Notice" = "Ha engedélyezve van, a videó húzása képet-képben üzemmódban nyitja meg."; diff --git a/Swiftgram/SGStrings/Strings/id.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/id.lproj/SGLocalizable.strings new file mode 100644 index 00000000..44ba7a11 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/id.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Pengaturan Konten"; + +"Settings.Tabs.Header" = "TABS"; +"Settings.Tabs.HideTabBar" = "Sembunyikan Tab bar"; +"Settings.Tabs.ShowContacts" = "Tampilkan Tab Kontak"; +"Settings.Tabs.ShowNames" = "Tampilkan Nama Tab"; + +"Settings.Folders.BottomTab" = "Folder di bawah"; +"Settings.Folders.BottomTabStyle" = "Gaya folder bawah"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Sembunyikan \"%@\""; +"Settings.Folders.RememberLast" = "Buka folder terakhir"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram akan membuka folder yang terakhir digunakan setelah restart atau pergantian akun"; + +"Settings.Folders.CompactNames" = "Pemisahan yang Lebih Kecil"; +"Settings.Folders.AllChatsTitle" = "Judul \"Semua Obrolan\""; +"Settings.Folders.AllChatsTitle.short" = "Pendek"; +"Settings.Folders.AllChatsTitle.long" = "Panjang"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Default"; + + +"Settings.ChatList.Header" = "DAFTAR OBROLAN"; +"Settings.CompactChatList" = "Daftar Obrolan Kompak"; + +"Settings.Profiles.Header" = "PROFIL"; + +"Settings.Stories.Hide" = "Sembunyikan Cerita"; +"Settings.Stories.WarnBeforeView" = "Tanyakan sebelum melihat"; +"Settings.Stories.DisableSwipeToRecord" = "Nonaktifkan geser untuk merekam"; + +"Settings.Translation.QuickTranslateButton" = "Bottone di traduzione rapida"; + +"Stories.Warning.Author" = "Penulis"; +"Stories.Warning.ViewStory" = "Lihat Cerita?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ AKAN TAHU bahwa Anda telah melihat Cerita mereka."; +"Stories.Warning.NoticeStealth" = "%@ tidak akan tahu bahwa Anda telah melihat Cerita mereka."; + +"Settings.Photo.Quality.Notice" = "Kualitas foto keluar dan cerita foto"; +"Settings.Photo.SendLarge" = "Kirim foto berukuran besar"; +"Settings.Photo.SendLarge.Notice" = "Tingkatkan batas sisi pada gambar terkompresi menjadi 2560px"; + +"Settings.VideoNotes.Header" = "VIDEO BULAT"; +"Settings.VideoNotes.StartWithRearCam" = "Mulai dengan kamera belakang"; + +"Settings.CustomColors.Header" = "WARNA AKUN"; +"Settings.CustomColors.Saturation" = "SATURASI"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Setel saturasi menjadi 0%% untuk menonaktifkan warna akun"; + +"Settings.UploadsBoost" = "Peningkatan Unggahan"; +"Settings.DownloadsBoost" = "Peningkatan Unduhan"; +"Settings.DownloadsBoost.Notice" = "Meningkatkan jumlah koneksi paralel dan ukuran potongan file. Jika jaringan Anda tidak dapat menangani bebannya, coba berbagai opsi yang sesuai dengan sambungan Anda."; +"Settings.DownloadsBoost.none" = "Nonaktif"; +"Settings.DownloadsBoost.medium" = "Sedang"; +"Settings.DownloadsBoost.maximum" = "Maksimal"; + +"Settings.ShowProfileID" = "Tampilkan ID Profil"; +"Settings.ShowDC" = "Tampilkan Pusat Data"; +"Settings.ShowCreationDate" = "Tampilkan Tanggal Pembuatan Obrolan"; +"Settings.ShowCreationDate.Notice" = "Tanggal pembuatan mungkin tidak diketahui untuk beberapa obrolan."; + +"Settings.ShowRegDate" = "Tampilkan Tanggal Pendaftaran"; +"Settings.ShowRegDate.Notice" = "Tanggal pendaftaran adalah perkiraan."; + +"Settings.SendWithReturnKey" = "Kirim dengan kunci \"kembali\""; +"Settings.HidePhoneInSettingsUI" = "Sembunyikan nomor telepon di pengaturan"; +"Settings.HidePhoneInSettingsUI.Notice" = "Nomor Anda akan disembunyikan hanya di UI Pengaturan. Kunjungi Pengaturan Privasi untuk menyembunyikannya dari orang lain."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Jika menjauh selama 5 detik"; + +"ProxySettings.UseSystemDNS" = "Gunakan DNS sistem"; +"ProxySettings.UseSystemDNS.Notice" = "Gunakan DNS sistem untuk menghindari timeout jika Anda tidak memiliki akses ke Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Anda **tidak memerlukan** %@!"; +"Common.RestartRequired" = "Diperlukan restart"; +"Common.RestartNow" = "Restart Sekarang"; +"Common.OpenTelegram" = "Buka Telegram"; +"Common.UseTelegramForPremium" = "Harap dicatat bahwa untuk mendapatkan Telegram Premium, Anda harus menggunakan aplikasi Telegram resmi. Setelah Anda mendapatkan Telegram Premium, semua fiturnya akan tersedia di Swiftgram."; + +"Message.HoldToShowOrReport" = "Tahan untuk Menampilkan atau Melaporkan."; + +"Auth.AccountBackupReminder" = "Pastikan Anda memiliki metode akses cadangan. Simpan SIM untuk SMS atau sesi tambahan yang masuk untuk menghindari terkunci."; +"Auth.UnofficialAppCodeTitle" = "Anda hanya dapat mendapatkan kode dengan aplikasi resmi"; + +"Settings.SmallReactions" = "Reaksi kecil"; +"Settings.HideReactions" = "Sembunyikan Reaksi"; + +"ContextMenu.SaveToCloud" = "Simpan ke Cloud"; +"ContextMenu.SelectFromUser" = "Pilih dari Penulis"; + +"Settings.ContextMenu" = "MENU KONTEKS"; +"Settings.ContextMenu.Notice" = "Entri yang dinonaktifkan akan tersedia di sub-menu \"Swiftgram\"."; + + +"Settings.ChatSwipeOptions" = "Opsi gesek daftar obrolan"; +"Settings.DeleteChatSwipeOption" = "Geser untuk Menghapus Obrolan"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Tarik untuk obrolan berikutnya"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Tarik ke Topik Berikutnya"; +"Settings.GalleryCamera" = "Kamera di galeri"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "Tombol \"%@\""; +"Settings.SnapDeletionEffect" = "Efek penghapusan pesan"; + +"Settings.Stickers.Size" = "UKURAN"; +"Settings.Stickers.Timestamp" = "Tampilkan Timestamp"; + +"Settings.RecordingButton" = "Tombol Perekaman Suara"; + +"Settings.DefaultEmojisFirst" = "Berikan prioritas pada emoji standar"; +"Settings.DefaultEmojisFirst.Notice" = "Tampilkan emoji standar sebelum emoji premium di papan tombol emoji"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "dibuat: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Bergabung %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Terdaftar"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Ketuk dua kali untuk mengedit pesan"; + +"Settings.wideChannelPosts" = "Pos Luas di Saluran"; +"Settings.ForceEmojiTab" = "Papan emoji secara default"; + +"Settings.forceBuiltInMic" = "Paksa Mikrofon Perangkat"; +"Settings.forceBuiltInMic.Notice" = "Jika diaktifkan, aplikasi akan menggunakan hanya mikrofon perangkat bahkan jika headphone terhubung."; + +"Settings.hideChannelBottomButton" = "Sembunyikan Panel Bawah Saluran"; + +"Settings.CallConfirmation" = "Konfirmasi Panggilan"; +"Settings.CallConfirmation.Notice" = "Swiftgram akan meminta konfirmasi Anda sebelum melakukan panggilan."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Buat Panggilan?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Buat Panggilan Video?"; + +"MutualContact.Label" = "kontak mutual"; + +"Settings.swipeForVideoPIP" = "Video PIP dengan Geser"; +"Settings.swipeForVideoPIP.Notice" = "Jika diaktifkan, menggeser video akan membukanya dalam mode Gambar-dalam-Gambar."; diff --git a/Swiftgram/SGStrings/Strings/it.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/it.lproj/SGLocalizable.strings new file mode 100644 index 00000000..ca32eafb --- /dev/null +++ b/Swiftgram/SGStrings/Strings/it.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Impostazioni Contenuto"; + +"Settings.Tabs.Header" = "TAB"; +"Settings.Tabs.HideTabBar" = "Nascondi barra della tab"; +"Settings.Tabs.ShowContacts" = "Mostra tab contatti"; +"Settings.Tabs.ShowNames" = "Mostra nomi tab"; + +"Settings.Folders.BottomTab" = "Cartelle in basso"; +"Settings.Folders.BottomTabStyle" = "Stile cartelle in basso"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Swiftgram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Nascondi \"%@\""; +"Settings.Folders.RememberLast" = "Apri l'ultima cartella"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram aprirà l'ultima cartella utilizzata dopo il riavvio o il cambio account"; + +"Settings.Folders.CompactNames" = "Spaziatura minore"; +"Settings.Folders.AllChatsTitle" = "Titolo \"Tutte le chat\""; +"Settings.Folders.AllChatsTitle.short" = "Breve"; +"Settings.Folders.AllChatsTitle.long" = "Lungo"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Predefinito"; + + +"Settings.ChatList.Header" = "ELENCO CHAT"; +"Settings.CompactChatList" = "Lista chat compatta"; + +"Settings.Profiles.Header" = "PROFILI"; + +"Settings.Stories.Hide" = "Nascondi Storie"; +"Settings.Stories.WarnBeforeView" = "Chiedi prima di visualizzare"; +"Settings.Stories.DisableSwipeToRecord" = "Disabilita lo scorrimento per registrare"; + +"Settings.Translation.QuickTranslateButton" = "Pulsante traduzione rapida"; + +"Stories.Warning.Author" = "Autore"; +"Stories.Warning.ViewStory" = "Visualizzare la storia?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ SAPRÀ CHE HAI VISTO la storia."; +"Stories.Warning.NoticeStealth" = "%@ non saprà che hai visto la storia."; + +"Settings.Photo.Quality.Notice" = "Qualità delle foto inviate e foto nelle storie"; +"Settings.Photo.SendLarge" = "Invia foto di grandi dimensioni"; +"Settings.Photo.SendLarge.Notice" = "Aumenta il limite sulla compressione delle foto a 2560px"; + +"Settings.VideoNotes.Header" = "Videomessaggi"; +"Settings.VideoNotes.StartWithRearCam" = "Inizia con la camera posteriore"; + +"Settings.CustomColors.Header" = "COLORI ACCOUNT"; +"Settings.CustomColors.Saturation" = "SATURAZIONE"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Imposta la saturazione a 0%% per disabilitare i colori dell'account"; + +"Settings.UploadsBoost" = "Potenziamento del caricamento"; +"Settings.DownloadsBoost" = "Potenziamento dello scaricamento"; +"Settings.DownloadsBoost.Notice" = "Aumenta il numero di connessioni parallele e le dimensioni dei frammenti di file. Se la tua rete non riesce a gestire il carico, prova diverse opzioni che si adattano alla tua connessione."; +"Settings.DownloadsBoost.none" = "Disabilitato"; +"Settings.DownloadsBoost.medium" = "Intermedio"; +"Settings.DownloadsBoost.maximum" = "Massimo"; + +"Settings.ShowProfileID" = "Mostra l'ID del profilo"; +"Settings.ShowDC" = "Mostra Data Center"; +"Settings.ShowCreationDate" = "Mostra data di creazione della chat"; +"Settings.ShowCreationDate.Notice" = "La data di creazione potrebbe essere sconosciuta per alcune chat."; + +"Settings.ShowRegDate" = "Mostra data di registrazione"; +"Settings.ShowRegDate.Notice" = "La data di registrazione è approssimativa."; + +"Settings.SendWithReturnKey" = "Pulsante \"Invia\" per inviare"; +"Settings.HidePhoneInSettingsUI" = "Nascondi il numero di telefono nelle impostazioni"; +"Settings.HidePhoneInSettingsUI.Notice" = "Il tuo numero verrà nascosto solo nell'interfaccia. Per nasconderlo dagli altri, apri le impostazioni della Privacy."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Se assente per 5 secondi"; + +"ProxySettings.UseSystemDNS" = "Usa DNS di sistema"; +"ProxySettings.UseSystemDNS.Notice" = "Usa DNS di sistema per bypassare il timeout se non hai accesso al DNS di Google"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "**Non hai bisogno** di %@!"; +"Common.RestartRequired" = "Riavvio richiesto"; +"Common.RestartNow" = "Riavvia Adesso"; +"Common.OpenTelegram" = "Apri Telegram"; +"Common.UseTelegramForPremium" = "Si prega di notare che per ottenere Telegram Premium, è necessario utilizzare l'app ufficiale Telegram. Una volta ottenuto Telegram Premium, tutte le sue funzionalità saranno disponibili su Swiftgram."; + +"Message.HoldToShowOrReport" = "Tieni premuto per mostrare o segnalare."; + +"Auth.AccountBackupReminder" = "Assicurati di avere un metodo di accesso di backup. Tieni una SIM per gli SMS o delle sessioni aperte su altri dispositivi per evitare di essere bloccato fuori."; +"Auth.UnofficialAppCodeTitle" = "Puoi ottenere il codice solo con l'applicazione ufficiale"; + +"Settings.SmallReactions" = "Reazioni piccole"; +"Settings.HideReactions" = "Nascondi Reazioni"; + +"ContextMenu.SaveToCloud" = "Salva sul cloud"; +"ContextMenu.SelectFromUser" = "Seleziona dall'autore"; + +"Settings.ContextMenu" = "MENU CONTESTUALE"; +"Settings.ContextMenu.Notice" = "Le voci disabilitate saranno disponibili nel sottomenu \"Swiftgram\"."; + + +"Settings.ChatSwipeOptions" = "Opzioni scorrimento nella lista delle chat"; +"Settings.DeleteChatSwipeOption" = "Swipe per eliminare chat"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Tira per il prossimo canale non letto"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Scorri per il prossimo topic"; +"Settings.GalleryCamera" = "Fotocamera nella galleria"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "Pulsante \"%@\""; +"Settings.SnapDeletionEffect" = "Effetti eliminazione messaggi"; + +"Settings.Stickers.Size" = "DIMENSIONE"; +"Settings.Stickers.Timestamp" = "Mostra timestamp"; + +"Settings.RecordingButton" = "Pulsante per la registrazione vocale"; + +"Settings.DefaultEmojisFirst" = "Dare priorità agli emoji standard"; +"Settings.DefaultEmojisFirst.Notice" = "Mostra gli emoji standard prima dei premium nella tastiera degli emoji"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "creato il: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Sì è unito a %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Registrato"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Doppio tap per modificare il messaggio"; + +"Settings.wideChannelPosts" = "Ampie colonne nei canali"; +"Settings.ForceEmojiTab" = "Tastiera emoji predefinita"; + +"Settings.forceBuiltInMic" = "Forza Microfono Dispositivo"; +"Settings.forceBuiltInMic.Notice" = "Se abilitato, l'app utilizzerà solo il microfono del dispositivo anche se sono collegate le cuffie."; + +"Settings.hideChannelBottomButton" = "Nascondi Pannello Inferiore del Canale"; + +"Settings.CallConfirmation" = "Conferma di chiamata"; +"Settings.CallConfirmation.Notice" = "Swiftgram chiederà la tua conferma prima di effettuare una chiamata."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Effettuare una chiamata?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Effettuare una videochiamata?"; + +"MutualContact.Label" = "contatto reciproco"; + +"Settings.swipeForVideoPIP" = "Video PIP con scorrimento"; +"Settings.swipeForVideoPIP.Notice" = "Se abilitato, scorrendo il video si aprirà in modalità Picture-in-Picture."; diff --git a/Swiftgram/SGStrings/Strings/ja.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/ja.lproj/SGLocalizable.strings new file mode 100644 index 00000000..afe45d65 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/ja.lproj/SGLocalizable.strings @@ -0,0 +1,246 @@ +"Settings.ContentSettings" = "コンテンツの設定"; + +"Settings.Tabs.Header" = "タブ"; +"Settings.Tabs.HideTabBar" = "タブバーを非表示にする"; +"Settings.Tabs.ShowContacts" = "連絡先のタブを表示"; +"Settings.Tabs.ShowNames" = "タブの名前を隠す"; + +"Settings.Folders.BottomTab" = "フォルダーを下に表示"; +"Settings.Folders.BottomTabStyle" = "チャットフォルダーのスタイル"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "\"%@\"を非表示"; +"Settings.Folders.RememberLast" = "最後に開いたフォルダを開く"; +"Settings.Folders.RememberLast.Notice" = "Swiftgramは再起動またはアカウント切替後に最後に使用したフォルダを開きます"; + +"Settings.Folders.CompactNames" = "より小さい間隔"; +"Settings.Folders.AllChatsTitle" = "「すべてのチャット」タイトル"; +"Settings.Folders.AllChatsTitle.short" = "Short"; +"Settings.Folders.AllChatsTitle.long" = "長い順"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "デフォルト"; + + +"Settings.ChatList.Header" = "チャットリスト"; +"Settings.CompactChatList" = "コンパクトなチャットリスト"; + +"Settings.Profiles.Header" = "PROFILES"; + +"Settings.Stories.Hide" = "ストーリーを隠す"; +"Settings.Stories.WarnBeforeView" = "視聴前に確認"; +"Settings.Stories.DisableSwipeToRecord" = "スワイプで録画を無効にする"; + +"Settings.Translation.QuickTranslateButton" = "クイック翻訳ボタン"; + +"Stories.Warning.Author" = "投稿者"; +"Stories.Warning.ViewStory" = "ストーリーを表示?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@はあなたがそのストーリーを見たことを確認できます。"; +"Stories.Warning.NoticeStealth" = "%@はあなたがそのストーリーを見たことを確認できません。"; + +"Settings.Photo.Quality.Notice" = "送信する写真とフォトストーリーの品質"; +"Settings.Photo.SendLarge" = "大きな写真を送信"; +"Settings.Photo.SendLarge.Notice" = "圧縮画像のサイド制限を2560pxに増加"; + +"Settings.VideoNotes.Header" = "丸いビデオ"; +"Settings.VideoNotes.StartWithRearCam" = "リアカメラで開始"; + +"Settings.CustomColors.Header" = "アカウントの色"; +"Settings.CustomColors.Saturation" = "彩度"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "彩度を0%%に設定してアカウントの色を無効にする"; + +"Settings.UploadsBoost" = "アップロードブースト"; +"Settings.DownloadsBoost" = "ダウンロードブースト"; +"Settings.DownloadsBoost.Notice" = "並行接続の数とファイルチャンクのサイズを増やします。ネットワークが負荷に耐えられない場合は、接続に適した別のオプションを試してください。"; +"Settings.DownloadsBoost.none" = "無効"; +"Settings.DownloadsBoost.medium" = "中程度"; +"Settings.DownloadsBoost.maximum" = "最大"; + +"Settings.ShowProfileID" = "プロフィールIDを表示"; +"Settings.ShowDC" = "データセンターを表示"; +"Settings.ShowCreationDate" = "チャットの作成日を表示"; +"Settings.ShowCreationDate.Notice" = "作成日が不明なチャットがあります。"; + +"Settings.ShowRegDate" = "登録日を表示"; +"Settings.ShowRegDate.Notice" = "登録日はおおよその日です。"; + +"Settings.SendWithReturnKey" = "\"return\" キーで送信"; +"Settings.HidePhoneInSettingsUI" = "設定で電話番号を隠す"; +"Settings.HidePhoneInSettingsUI.Notice" = "あなたの番号は設定UIでのみ隠されます。他の人から隠すにはプライバシー設定に移動してください。"; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "5秒間離れると自動ロック"; + +"ProxySettings.UseSystemDNS" = "システムDNSを使用"; +"ProxySettings.UseSystemDNS.Notice" = "Google DNSにアクセスできない場合はシステムDNSを使用してタイムアウトを回避"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "** %@は必要ありません**!"; +"Common.RestartRequired" = "再起動が必要です"; +"Common.RestartNow" = "今すぐ再実行"; +"Common.OpenTelegram" = "Telegram を開く"; +"Common.UseTelegramForPremium" = "Telegram Premiumを登録するには、公式のTelegramアプリが必要です。 +登録すると、Swiftgram等の非公式アプリ含め、Telegram Premiumをサポートする全てのアプリでプレミアムメソッドを利用できます。"; +"Common.UpdateOS" = "iOSの更新が必要です"; + +"Message.HoldToShowOrReport" = "表示または報告するために押し続ける。"; + +"Auth.AccountBackupReminder" = "バックアップアクセス方法があることを確認してください。SMS用のSIMを保持するか、追加のセッションにログインしてロックアウトを避けてください。"; +"Auth.UnofficialAppCodeTitle" = "テレグラムの公式アプリでのみログインコードを取得できます"; + +"Settings.SmallReactions" = "小さいリアクション"; +"Settings.HideReactions" = "リアクションを非表示"; + +"ContextMenu.SaveToCloud" = "メッセージを保存"; +"ContextMenu.SelectFromUser" = "全て選択"; + +"Settings.ContextMenu" = "コンテキスト メニュー"; +"Settings.ContextMenu.Notice" = "無効化されたエントリは、「Swiftgram」サブメニューから利用できます。"; + + +"Settings.ChatSwipeOptions" = "チャットリストのスワイプ設定"; +"Settings.DeleteChatSwipeOption" = "チャットを削除するにはスワイプしてください"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "次の未読チャンネルまでプルする"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "次のトピックに移動する"; +"Settings.GalleryCamera" = "ギャラリーのカメラを隠す"; +"Settings.GalleryCameraPreview" = "ギャラリーのカメラプレビュー"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" ボタン"; +"Settings.SnapDeletionEffect" = "メッセージ削除のエフェクト"; + +"Settings.Stickers.Size" = "サイズ"; +"Settings.Stickers.Timestamp" = "タイムスタンプを表示"; + +"Settings.RecordingButton" = "音声録音ボタン"; + +"Settings.DefaultEmojisFirst" = "標準エモジを優先"; +"Settings.DefaultEmojisFirst.Notice" = "絵文字キーボードでプレミアムより前に標準エモジを表示"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "作成済み: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "%@ に参加しました"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "登録済み"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "メッセージを編集するにはタップをダブルタップ"; + +"Settings.wideChannelPosts" = "チャンネル内の幅広い投稿"; +"Settings.ForceEmojiTab" = "デフォルトで絵文字キーボード"; + +"Settings.forceBuiltInMic" = "デバイスのマイクを強制"; +"Settings.forceBuiltInMic.Notice" = "有効にすると、ヘッドフォンが接続されていてもアプリはデバイスのマイクのみを使用します。"; + +"Settings.showChannelBottomButton" = "チャンネルボトムパネル"; + +"Settings.secondsInMessages" = "メッセージ内の秒数"; + +"Settings.CallConfirmation" = "コール確認"; +"Settings.CallConfirmation.Notice" = "Swiftgram は、通話を行う前にあなたの確認を求めます。"; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "通話をかけますか?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "ビデオ通話をかけますか?"; + +"MutualContact.Label" = "相互連絡先"; + +"Settings.swipeForVideoPIP" = "ビデオ PIP スワイプ"; +"Settings.swipeForVideoPIP.Notice" = "有効になっている場合、ビデオをスワイプするとピクチャーインピクチャーモードで開きます。"; + +"SessionBackup.Title" = "アカウントのバックアップ"; +"SessionBackup.Sessions.Title" = "セッション"; +"SessionBackup.Actions.Backup" = "キーチェーンにバックアップ"; +"SessionBackup.Actions.Restore" = "キーチェーンから復元"; +"SessionBackup.Actions.DeleteAll" = "キーチェーンのバックアップを削除"; +"SessionBackup.Actions.DeleteOne" = "バックアップから削除"; +"SessionBackup.Actions.RemoveFromApp" = "アプリから削除"; +"SessionBackup.LastBackupAt" = "最終バックアップ: %@"; +"SessionBackup.RestoreOK" = "OK。復元されたセッション: %@"; +"SessionBackup.LoggedIn" = "ログイン中"; +"SessionBackup.LoggedOut" = "ログアウトしました"; +"SessionBackup.DeleteAll.Title" = "すべてのセッションを削除しますか?"; +"SessionBackup.DeleteAll.Text" = "すべてのセッションがキーチェーンから削除されます。\n\nアカウントはSwiftgramからログアウトされません。"; +"SessionBackup.DeleteSingle.Title" = "1つのセッションを削除しますか?"; +"SessionBackup.DeleteSingle.Text" = "%@のセッションがキーチェーンから削除されます。\n\nアカウントはSwiftgramからログアウトされません。"; +"SessionBackup.RemoveFromApp.Title" = "アプリからアカウントを削除しますか?"; +"SessionBackup.RemoveFromApp.Text" = "%@のセッションがSwiftgramから削除されます!セッションはアクティブなままなので、後で復元できます。"; +"SessionBackup.Notice" = "セッションは暗号化され、デバイスのキーチェーンに保存されます。セッションはあなたのデバイスを離れることはありません。\n\n重要: 新しいデバイスまたはOSのリセット後にセッションを復元するには、暗号化されたバックアップを有効にする必要があります。さもなければキーチェーンは移行されません。\n\n注意: セッションはTelegramや他のデバイスからも取り消される可能性があります。"; + +"MessageFilter.Title" = "メッセージフィルター"; +"MessageFilter.SubTitle" = "下記のキーワードを含むメッセージの可視性を減少させ、気を散らさないようにします。\nキーワードは大文字と小文字を区別します。"; +"MessageFilter.Keywords.Title" = "キーワード"; +"MessageFilter.InputPlaceholder" = "キーワードを入力してください"; + +"InputToolbar.Title" = "フォーマットパネル"; + +"Notifications.MentionsAndReplies.Title" = "@メンションと返信"; +"Notifications.MentionsAndReplies.value.default" = "デフォルト"; +"Notifications.MentionsAndReplies.value.silenced" = "ミュート"; +"Notifications.MentionsAndReplies.value.disabled" = "無効"; +"Notifications.PinnedMessages.Title" = "固定メッセージ"; +"Notifications.PinnedMessages.value.default" = "デフォルト"; +"Notifications.PinnedMessages.value.silenced" = "ミュート"; +"Notifications.PinnedMessages.value.disabled" = "無効"; + + +"PayWall.Text" = "プロ機能で強化"; + +"PayWall.SessionBackup.Title" = "アカウントのバックアップ"; +"PayWall.SessionBackup.Notice" = "コードなしでアカウントにログインできます。再インストール後も可能です。デバイス上のキーチェーンで安全に保存されています"; +"PayWall.SessionBackup.Description" = "デバイスを変更したりSwiftgramを削除したりしても、もはや問題にはなりません。Telegramサーバー上でまだアクティブなすべてのセッションを復元します"; + +"PayWall.MessageFilter.Title" = "メッセージフィルター"; +"PayWall.MessageFilter.Notice" = "SPAM、プロモーション、および煩わしいメッセージの可視性を減少させます。"; +"PayWall.MessageFilter.Description" = "見たくないキーワードのリストを作成すると、Swiftgramがそのキーワードを非表示にします"; + +"PayWall.Notifications.Title" = "@メンションと返信を無効にする"; +"PayWall.Notifications.Notice" = "重要でない通知を隠したりミュートしたりします。"; +"PayWall.Notifications.Description" = "気分を落ち着けたいときは、固定メッセージやメンションを非表示にできます"; + +"PayWall.InputToolbar.Title" = "フォーマットパネル"; +"PayWall.InputToolbar.Notice" = "ワンタップでメッセージの書式設定を短縮"; +"PayWall.InputToolbar.Description" = "書式を適用・解除したり、新しい行を挿入したりと、プロのように操作できます"; + +"PayWall.AppIcons.Title" = "ユニークなアプリアイコン"; +"PayWall.AppIcons.Notice" = "ホーム画面でSwiftgramの外観をカスタマイズします。"; + +"PayWall.About.Title" = "Swiftgram Proについて"; +"PayWall.About.Notice" = "Swiftgramの無料版は、Telegramアプリ上で数十の機能と改善を提供します。 毎月のTelegramのアップデートとSwiftgramの同期を革新し、維持することは多くの時間と高価なハードウェアを必要とする膨大な努力です。\n\nSwiftgramはプライバシーを尊重し、広告を気にしないオープンソースのアプリです。 Swiftgram Proに登録すると、排他的な機能にアクセスでき、独立した開発者をサポートできます。"; +/* DO NOT TRANSLATE */ +"PayWall.About.Signature" = "@Kylmakalle"; +/* DO NOT TRANSLATE */ +"PayWall.About.SignatureURL" = "https://t.me/Kylmakalle"; + +"PayWall.ProSupport.Title" = "お支払いに問題がありますか?"; +"PayWall.ProSupport.Contact" = "心配ないさ!"; + +"PayWall.RestorePurchases" = "購入を復元する"; +"PayWall.Terms" = "利用規約"; +"PayWall.Privacy" = "プライバシーポリシー"; +"PayWall.TermsURL" = "https://swiftgram.app/terms"; +"PayWall.PrivacyURL" = "https://swiftgram.app/privacy"; +"PayWall.Notice.Markdown" = "Swiftgram Proに購読することで、[Swiftgram利用規約](%1$@)と[プライバシーポリシー](%2$@)に同意したことになります。"; +"PayWall.Notice.Raw" = "Swiftgram Proに購読することで、Swiftgramの利用規約とプライバシーポリシーに同意したことになります。"; + +"PayWall.Button.OpenPro" = "プロ機能を使用する"; +"PayWall.Button.Purchasing" = "購入中…"; +"PayWall.Button.Restoring" = "購入を復元中…"; +"PayWall.Button.Validating" = "購入を検証中…"; +"PayWall.Button.PaymentsUnavailable" = "支払い不可"; +"PayWall.Button.BuyInAppStore" = "App Store版で登録"; +"PayWall.Button.Subscribe" = "%@ / 月で購読"; +"PayWall.Button.ContactingAppStore" = "App Storeに連絡中…"; + +"Paywall.Error.Title" = "エラー"; +"PayWall.ValidationError" = "検証エラー"; +"PayWall.ValidationError.TryAgain" = "購入の検証中に問題が発生しました。心配しないでください!後で購入を復元してみてください。"; +"PayWall.ValidationError.Expired" = "サブスクリプションの有効期限が切れました。Pro機能へのアクセスを取り戻すには、再度サブスクリプションを登録してください。"; diff --git a/Swiftgram/SGStrings/Strings/km.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/km.lproj/SGLocalizable.strings new file mode 100644 index 00000000..928cf393 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/km.lproj/SGLocalizable.strings @@ -0,0 +1,8 @@ +"Settings.Tabs.Header" = "ថេប"; +"Settings.Tabs.ShowContacts" = "បង្ហាញថេបទំនាក់ទំនង"; +"Settings.VideoNotes.Header" = "រង្វង់វីដេអូ"; +"Settings.VideoNotes.StartWithRearCam" = "ចាប់ផ្ដើមជាមួយកាមេរ៉ាក្រោយ"; +"Settings.Tabs.ShowNames" = "បង្ហាញឈ្មោះថេប"; +"Settings.HidePhoneInSettingsUI" = "លាក់លេខទូរសព្ទក្នុងការកំណត់"; +"Settings.Folders.BottomTab" = "ថតឯបាត"; +"ContextMenu.SaveToCloud" = "រក្សាទុកទៅពពក"; diff --git a/Swiftgram/SGStrings/Strings/ko.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/ko.lproj/SGLocalizable.strings new file mode 100644 index 00000000..501a5f64 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/ko.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "콘텐츠 설정"; + +"Settings.Tabs.Header" = "탭"; +"Settings.Tabs.HideTabBar" = "탭바숨기기"; +"Settings.Tabs.ShowContacts" = "연락처 탭 보이기"; +"Settings.Tabs.ShowNames" = "탭 이름 표시"; + +"Settings.Folders.BottomTab" = "폴더를 하단에 표시"; +"Settings.Folders.BottomTabStyle" = "탭위치아래"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "\"%@\" 숨기기"; +"Settings.Folders.RememberLast" = "마지막 폴더 열기"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram은 재시작하거나 계정을 전환한 후 마지막으로 사용한 폴더를 엽니다"; + +"Settings.Folders.CompactNames" = "간격 작게"; +"Settings.Folders.AllChatsTitle" = "\"모든 채팅\" 제목"; +"Settings.Folders.AllChatsTitle.short" = "단축"; +"Settings.Folders.AllChatsTitle.long" = "긴"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "기본"; + + +"Settings.ChatList.Header" = "채팅 목록"; +"Settings.CompactChatList" = "간략한 채팅 목록"; + +"Settings.Profiles.Header" = "프로필"; + +"Settings.Stories.Hide" = "스토리 숨기기"; +"Settings.Stories.WarnBeforeView" = "보기 전에 묻기"; +"Settings.Stories.DisableSwipeToRecord" = "녹화를 위한 스와이프 비활성화"; + +"Settings.Translation.QuickTranslateButton" = "빠른 번역 버튼"; + +"Stories.Warning.Author" = "작성자"; +"Stories.Warning.ViewStory" = "스토리 보기?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@님은 당신이 그들의 스토리를 봤는지 알 수 있습니다."; +"Stories.Warning.NoticeStealth" = "%@님은 당신이 그들의 스토리를 봤는지 알 수 없습니다."; + +"Settings.Photo.Quality.Notice" = "보낸 사진과 포토스토리의 품질"; +"Settings.Photo.SendLarge" = "큰 사진 보내기"; +"Settings.Photo.SendLarge.Notice" = "압축 이미지의 크기 제한을 2560px로 증가"; + +"Settings.VideoNotes.Header" = "라운드 비디오"; +"Settings.VideoNotes.StartWithRearCam" = "후면 카메라로 시작"; + +"Settings.CustomColors.Header" = "계정 색상"; +"Settings.CustomColors.Saturation" = "채도"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "계정 색상을 비활성화하려면 채도를 0%%로 설정하세요"; + +"Settings.UploadsBoost" = "업로드 향상"; +"Settings.DownloadsBoost" = "다운로드 향상"; +"Settings.DownloadsBoost.Notice" = "병렬 연결 수와 파일 조각 크기를 증가시킵니다. 네트워크가 부하를 처리할 수 없는 경우, 연결에 적합한 다양한 옵션을 시도해 보세요."; +"Settings.DownloadsBoost.none" = "비활성화"; +"Settings.DownloadsBoost.medium" = "중간"; +"Settings.DownloadsBoost.maximum" = "최대"; + +"Settings.ShowProfileID" = "프로필 ID 표시"; +"Settings.ShowDC" = "데이터센터보기"; +"Settings.ShowCreationDate" = "채팅 생성 날짜 표시"; +"Settings.ShowCreationDate.Notice" = "몇몇 채팅에 대해서는 생성 날짜를 알 수 없을 수 있습니다."; + +"Settings.ShowRegDate" = "가입 날짜 표시"; +"Settings.ShowRegDate.Notice" = "가입 날짜는 대략적입니다."; + +"Settings.SendWithReturnKey" = "\"리턴\" 키로 보내기"; +"Settings.HidePhoneInSettingsUI" = "설정에서 전화번호 숨기기"; +"Settings.HidePhoneInSettingsUI.Notice" = "전화 번호는 UI에서만 숨겨집니다. 다른 사람에게 숨기려면 개인 정보 설정을 사용하세요."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "5초 동안 떨어져 있으면"; + +"ProxySettings.UseSystemDNS" = "시스템 DNS 사용"; +"ProxySettings.UseSystemDNS.Notice" = "Google DNS에 접근할 수 없는 경우 시스템 DNS를 사용하여 타임아웃 우회"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "%@이(가) **필요하지 않습니다**!"; +"Common.RestartRequired" = "재시작 필요"; +"Common.RestartNow" = "지금 재시작"; +"Common.OpenTelegram" = "텔레그램 열기"; +"Common.UseTelegramForPremium" = "텔레그램 프리미엄을 받으려면 공식 텔레그램 앱을 사용해야 합니다. 텔레그램 프리미엄을 획득하면 모든 기능이 Swiftgram에서 사용 가능해집니다."; + +"Message.HoldToShowOrReport" = "보여주거나 신고하기 위해 길게 누르세요."; + +"Auth.AccountBackupReminder" = "백업 접근 방법을 확보하세요. SMS용 SIM 카드를 보관하거나 추가 세션에 로그인하여 잠금을 피하세요."; +"Auth.UnofficialAppCodeTitle" = "코드는 공식 앱으로만 받을 수 있습니다"; + +"Settings.SmallReactions" = "작은 반응들"; +"Settings.HideReactions" = "반응 숨기기"; + +"ContextMenu.SaveToCloud" = "클라우드에 저장"; +"ContextMenu.SelectFromUser" = "사용자에서 선택"; + +"Settings.ContextMenu" = "컨텍스트 메뉴"; +"Settings.ContextMenu.Notice" = "'Swiftgram' 하위 메뉴에서 비활성화된 항목을 사용할 수 있습니다."; + + +"Settings.ChatSwipeOptions" = "채팅 목록 스와이프 옵션"; +"Settings.DeleteChatSwipeOption" = "채팅 삭제를 위해 스와이프하세요"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "다음 읽지 않은 채널까지 당겨서 보기"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "다음 주제로 끌어당기기"; +"Settings.GalleryCamera" = "갤러리 내 카메라"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" 버튼"; +"Settings.SnapDeletionEffect" = "메시지 삭제 효과"; + +"Settings.Stickers.Size" = "크기"; +"Settings.Stickers.Timestamp" = "시간 표시 표시"; + +"Settings.RecordingButton" = "음성 녹음 버튼"; + +"Settings.DefaultEmojisFirst" = "표준 이모지 우선순위 설정"; +"Settings.DefaultEmojisFirst.Notice" = "이모지 키보드에서 프리미엄 이모지보다 표준 이모지 우선 표시"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "생성됨: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "%@에 가입함"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "가입함"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "메시지 수정을 위해 두 번 탭"; + +"Settings.wideChannelPosts" = "채널의 넓은 게시물"; +"Settings.ForceEmojiTab" = "기본으로 이모티콘 키보드"; + +"Settings.forceBuiltInMic" = "장치 마이크 강제"; +"Settings.forceBuiltInMic.Notice" = "만약 활성화되면, 앱은 헤드폰이 연결되어 있더라도 장치 마이크만 사용합니다."; + +"Settings.hideChannelBottomButton" = "채널 하단 패널 숨기기"; + +"Settings.CallConfirmation" = "통화 확인"; +"Settings.CallConfirmation.Notice" = "Swiftgram은 전화를 걸기 전에 귀하의 확인을 요청할 것입니다."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "통화를 하시겠습니까?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "영상 통화를 하시겠습니까?"; + +"MutualContact.Label" = "상호 연락처"; + +"Settings.swipeForVideoPIP" = "비디오 PIP 스와이프"; +"Settings.swipeForVideoPIP.Notice" = "설정이 활성화되면 비디오를 스와이프하면 화면 속 화면 모드로 열립니다."; diff --git a/Swiftgram/SGStrings/Strings/ku.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/ku.lproj/SGLocalizable.strings new file mode 100644 index 00000000..62ac20a8 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/ku.lproj/SGLocalizable.strings @@ -0,0 +1,10 @@ +"Settings.Tabs.Header" = "تابەکان"; +"Settings.Tabs.ShowContacts" = "نیشاندانی تابی کۆنتاکتەکان"; +"Settings.VideoNotes.Header" = "ڤیدیۆ بازنەییەکان"; +"Settings.VideoNotes.StartWithRearCam" = "دەستپێکردن بە کامێرای پشتەوە"; +"Settings.Tabs.ShowNames" = "نیشاندانی ناوی تابەکان"; +"Settings.HidePhoneInSettingsUI" = "شاردنەوەی تەلەفۆن لە ڕێکخستنەکان"; +"Settings.HidePhoneInSettingsUI.Notice" = "ژمارەکەت تەنها لە ڕووکارەکە دەرناکەوێت. بۆ ئەوەی لە ئەوانەی دیکەی بشاریتەوە، تکایە ڕێکخستنەکانی پارێزراوی بەکاربێنە."; +"Settings.Translation.QuickTranslateButton" = "دوگمەی وەرگێڕانی خێرا"; +"Settings.Folders.BottomTab" = "بوخچەکان لە خوارەوە"; +"ContextMenu.SaveToCloud" = "هەڵگرتن لە کڵاود"; diff --git a/Swiftgram/SGStrings/Strings/nl.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/nl.lproj/SGLocalizable.strings new file mode 100644 index 00000000..d80e6ca4 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/nl.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Inhoudsinstellingen"; + +"Settings.Tabs.Header" = "TABS"; +"Settings.Tabs.HideTabBar" = "Tabbladbalk verbergen"; +"Settings.Tabs.ShowContacts" = "Toon Contacten Tab"; +"Settings.Tabs.ShowNames" = "Show Tab Names"; + +"Settings.Folders.BottomTab" = "Mappen onderaan"; +"Settings.Folders.BottomTabStyle" = "Onderste mappenstijl"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Verberg \"%@\""; +"Settings.Folders.RememberLast" = "Laatste map openen"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram zal de laatst gebruikte map openen wanneer u de app herstart of van account wisselt."; + +"Settings.Folders.CompactNames" = "Kleinere afstand"; +"Settings.Folders.AllChatsTitle" = "\"Alle Chats\" titel"; +"Settings.Folders.AllChatsTitle.short" = "Kort"; +"Settings.Folders.AllChatsTitle.long" = "Lang"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Standaard"; + + +"Settings.ChatList.Header" = "CHAT LIJST"; +"Settings.CompactChatList" = "Compacte Chat Lijst"; + +"Settings.Profiles.Header" = "PROFILES"; + +"Settings.Stories.Hide" = "Verberg Verhalen"; +"Settings.Stories.WarnBeforeView" = "Vragen voor bekijken"; +"Settings.Stories.DisableSwipeToRecord" = "Swipe om op te nemen uitschakelen"; + +"Settings.Translation.QuickTranslateButton" = "Snelle Vertaalknop"; + +"Stories.Warning.Author" = "Auteur"; +"Stories.Warning.ViewStory" = "Bekijk Verhaal?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ ZAL KUNNEN ZIEN dat je hun Verhaal hebt bekeken."; +"Stories.Warning.NoticeStealth" = "%@ zal niet kunnen zien dat je hun Verhaal hebt bekeken."; + +"Settings.Photo.Quality.Notice" = "Kwaliteit van geüploade foto's en verhalen."; +"Settings.Photo.SendLarge" = "Verstuur grote foto's"; +"Settings.Photo.SendLarge.Notice" = "Verhoog de zijlimiet bij gecomprimeerde afbeeldingen naar 2560px."; + +"Settings.VideoNotes.Header" = "RONDE VIDEO'S"; +"Settings.VideoNotes.StartWithRearCam" = "Start met achtercamera"; + +"Settings.CustomColors.Header" = "ACCOUNTKLEUREN"; +"Settings.CustomColors.Saturation" = "VERZADIGING"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Zet op 0%% om accountkleuren uit te schakelen."; + +"Settings.UploadsBoost" = "Upload Boost"; +"Settings.DownloadsBoost" = "Download Boost"; +"Settings.DownloadsBoost.Notice" = "Verhoogt het aantal gelijktijdige verbindingen en de grootte van bestandsgedeelten. Als uw netwerk de belasting niet aankan, probeer dan verschillende opties die geschikt zijn voor uw verbinding."; +"Settings.DownloadsBoost.none" = "Uitgeschakeld"; +"Settings.DownloadsBoost.medium" = "Gemiddeld"; +"Settings.DownloadsBoost.maximum" = "Maximaal"; + +"Settings.ShowProfileID" = "Toon profiel ID"; +"Settings.ShowDC" = "Toon datacentrum"; +"Settings.ShowCreationDate" = "Toon Chat Aanmaakdatum"; +"Settings.ShowCreationDate.Notice" = "De aanmaakdatum kan onbekend zijn voor sommige chatten."; + +"Settings.ShowRegDate" = "Toon registratiedatum"; +"Settings.ShowRegDate.Notice" = "De registratiedatum is ongeveer hetzelfde."; + +"Settings.SendWithReturnKey" = "Verstuur met 'return'-toets"; +"Settings.HidePhoneInSettingsUI" = "Verberg telefoon in Instellingen"; +"Settings.HidePhoneInSettingsUI.Notice" = "Dit verbergt alleen je telefoonnummer in de instellingen interface. Ga naar Privacy en Beveiliging om het voor anderen te verbergen."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Automatisch vergrendelen na 5 seconden"; + +"ProxySettings.UseSystemDNS" = "Gebruik systeem DNS"; +"ProxySettings.UseSystemDNS.Notice" = "Gebruik systeem DNS om time-out te omzeilen als je geen toegang hebt tot Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Je hebt **geen %@ nodig**!"; +"Common.RestartRequired" = "Herstart vereist"; +"Common.RestartNow" = "Nu herstarten"; +"Common.OpenTelegram" = "Open Telegram"; +"Common.UseTelegramForPremium" = "Om Telegram Premium te krijgen moet je de officiële Telegram app gebruiken. Zodra je Telegram Premium hebt ontvangen, zullen alle functies ervan beschikbaar komen in Swiftgram."; + +"Message.HoldToShowOrReport" = "Houd vast om te Tonen of te Rapporteren."; + +"Auth.AccountBackupReminder" = "Zorg ervoor dat je een back-up toegangsmethode hebt. Houd een SIM voor SMS of een extra sessie ingelogd om buitensluiting te voorkomen."; +"Auth.UnofficialAppCodeTitle" = "Je kunt de code alleen krijgen met de officiële app"; + +"Settings.SmallReactions" = "Kleine reacties"; +"Settings.HideReactions" = "Verberg Reacties"; + +"ContextMenu.SaveToCloud" = "Opslaan in de Cloud"; +"ContextMenu.SelectFromUser" = "Selecteer van Auteur"; + +"Settings.ContextMenu" = "CONTEXTMENU"; +"Settings.ContextMenu.Notice" = "Uitgeschakelde items zijn beschikbaar in het 'Swiftgram'-submenu."; + + +"Settings.ChatSwipeOptions" = "Veegopties voor chatlijst"; +"Settings.DeleteChatSwipeOption" = "Veeg om Chat te Verwijderen"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Trek naar het volgende ongelezen kanaal"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Trek naar Volgend Onderwerp"; +"Settings.GalleryCamera" = "Camera in Galerij"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" knop"; +"Settings.SnapDeletionEffect" = "Verwijderde Berichten Effecten"; + +"Settings.Stickers.Size" = "GROOTTE"; +"Settings.Stickers.Timestamp" = "Tijdstempel weergeven"; + +"Settings.RecordingButton" = "Spraakopname knop"; + +"Settings.DefaultEmojisFirst" = "Standaardemoji's prioriteren"; +"Settings.DefaultEmojisFirst.Notice" = "Toon standaardemoji's vóór premium in emoji-toetsenbord"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "aangemaakt: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Lid geworden %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Geregistreerd"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Dubbelklik om bericht te bewerken"; + +"Settings.wideChannelPosts" = "Brede berichten in kanalen"; +"Settings.ForceEmojiTab" = "Emoji-toetsenbord standaard"; + +"Settings.forceBuiltInMic" = "Forceer Apparaatmicrofoon"; +"Settings.forceBuiltInMic.Notice" = "Indien ingeschakeld, zal de app alleen de apparaatmicrofoon gebruiken, zelfs als er hoofdtelefoons zijn aangesloten."; + +"Settings.hideChannelBottomButton" = "Verberg Kanaal Onderste Paneel"; + +"Settings.CallConfirmation" = "Belbevestiging"; +"Settings.CallConfirmation.Notice" = "Swiftgram zal om uw bevestiging vragen voordat er een oproep wordt gedaan."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Een oproep maken?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Een video-oproep maken?"; + +"MutualContact.Label" = "gemeenschappelijke contactpersoon"; + +"Settings.swipeForVideoPIP" = "Video PIP met veeg"; +"Settings.swipeForVideoPIP.Notice" = "Als ingeschakeld, opent het swipen van video het in de modus Beeld-in-Beeld."; diff --git a/Swiftgram/SGStrings/Strings/no.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/no.lproj/SGLocalizable.strings new file mode 100644 index 00000000..5fd16d5c --- /dev/null +++ b/Swiftgram/SGStrings/Strings/no.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Innholdsinnstillinger"; + +"Settings.Tabs.Header" = "FANER"; +"Settings.Tabs.HideTabBar" = "Skjul fanelinjen"; +"Settings.Tabs.ShowContacts" = "Vis kontakter-fane"; +"Settings.Tabs.ShowNames" = "Show Tab Names"; + +"Settings.Folders.BottomTab" = "Mapper på bunnen"; +"Settings.Folders.BottomTabStyle" = "Stil for nedre mapper"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Skjul \"%@\""; +"Settings.Folders.RememberLast" = "Åpne siste mappe"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram vil åpne den sist brukte mappen når du starter appen på nytt eller bytter kontoer."; + +"Settings.Folders.CompactNames" = "Mindre avstand"; +"Settings.Folders.AllChatsTitle" = "\"Alle chater\" tittel"; +"Settings.Folders.AllChatsTitle.short" = "Kort"; +"Settings.Folders.AllChatsTitle.long" = "Lang"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Standard"; + + +"Settings.ChatList.Header" = "CHAT LIST"; +"Settings.CompactChatList" = "Kompakt liste"; + +"Settings.Profiles.Header" = "PROFILES"; + +"Settings.Stories.Hide" = "Skjul Historier"; +"Settings.Stories.WarnBeforeView" = "Spør før visning"; +"Settings.Stories.DisableSwipeToRecord" = "Deaktiver sveip for å ta opp"; + +"Settings.Translation.QuickTranslateButton" = "Hurtigoversettelsesknapp"; + +"Stories.Warning.Author" = "Forfatter"; +"Stories.Warning.ViewStory" = "Se Historie?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ VIL SE at du har sett deres Historie."; +"Stories.Warning.NoticeStealth" = "%@ vil ikke kunne se at du har sett deres Historie."; + +"Settings.Photo.Quality.Notice" = "Kvalitet på opplastede bilder og historier."; +"Settings.Photo.SendLarge" = "Send store bilder"; +"Settings.Photo.SendLarge.Notice" = "Øk grensen for komprimerte bilder til 2560 piksler."; + +"Settings.VideoNotes.Header" = "RUNDE VIDEOER"; +"Settings.VideoNotes.StartWithRearCam" = "Start med bakkamera"; + +"Settings.CustomColors.Header" = "KONTOFARGER"; +"Settings.CustomColors.Saturation" = "METNING"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Satt til 0%% for å deaktivere kontofarger."; + +"Settings.UploadsBoost" = "Ã k opplastingshastighet"; +"Settings.DownloadsBoost" = "Last ned boost"; +"Settings.DownloadsBoost.Notice" = "Øker antallet av parallelle forbindelser og størrelsen på filbiter. Hvis nettverket ditt ikke kan håndtere belastningen, prøv forskjellige alternativer som passer til tilkoblingen din."; +"Settings.DownloadsBoost.none" = "Deaktivert"; +"Settings.DownloadsBoost.medium" = "Middels"; +"Settings.DownloadsBoost.maximum" = "Maksimum"; + +"Settings.ShowProfileID" = "Vis profil-ID"; +"Settings.ShowDC" = "Vis datasenter"; +"Settings.ShowCreationDate" = "Vis chat opprettet dato"; +"Settings.ShowCreationDate.Notice" = "Opprettelsesdatoen kan være ukjent for noen chat."; + +"Settings.ShowRegDate" = "Vis registreringsdato"; +"Settings.ShowRegDate.Notice" = "Registreringsdatoen er ca."; + +"Settings.SendWithReturnKey" = "Send med 'retur'-tasten"; +"Settings.HidePhoneInSettingsUI" = "Skjul telefonen i innstillinger"; +"Settings.HidePhoneInSettingsUI.Notice" = "Dette vil bare skjule ditt telefonnummer for instillinger. For å skjule det for andre, gå til Personvern og Sikkerhet."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Hvis borte i 5 sekunder"; + +"ProxySettings.UseSystemDNS" = "Bruk system DNS"; +"ProxySettings.UseSystemDNS.Notice" = "Bruk system DNS for å omgå timeout hvis du ikke har tilgang til Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Du **trenger ikke** %@!"; +"Common.RestartRequired" = "Omstart kreves"; +"Common.RestartNow" = "Omstart Nå"; +"Common.OpenTelegram" = "Åpne Telegram"; +"Common.UseTelegramForPremium" = "Vær oppmerksom på at for å få Telegram Premium, må du bruke den offisielle Telegram-appen. Når du har tatt Telegram Premium, vil alle funksjonene bli tilgjengelige i Swiftgram."; + +"Message.HoldToShowOrReport" = "Hold for å vise eller rapportere."; + +"Auth.AccountBackupReminder" = "Sørg for at du har en sikkerhetskopiert tilgangsmetode. Oppretthold en SIM for SMS eller en ekstra økt logget inn for å unngå å bli låst ute."; +"Auth.UnofficialAppCodeTitle" = "Du kan bare få koden med den offisielle appen"; + +"Settings.SmallReactions" = "Liten Reaksjon"; +"Settings.HideReactions" = "Skjul Reaksjoner"; + +"ContextMenu.SaveToCloud" = "Lagre til skyen"; +"ContextMenu.SelectFromUser" = "Velg fra forfatter"; + +"Settings.ContextMenu" = "KONTEKSTMENY"; +"Settings.ContextMenu.Notice" = "Deaktiverte oppføringer vil være tilgjengelige i 'Swiftgram'-undermenyen."; + + +"Settings.ChatSwipeOptions" = "Chat liste sveip alternativer"; +"Settings.DeleteChatSwipeOption" = "Sveip for å slette samtalen"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Dra til neste uleste kanal"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Dra til neste emne"; +"Settings.GalleryCamera" = "Kamera i galleri"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" knapp"; +"Settings.SnapDeletionEffect" = "Sletting av melding effekter"; + +"Settings.Stickers.Size" = "STØRRELSE"; +"Settings.Stickers.Timestamp" = "Vis tidsstempel"; + +"Settings.RecordingButton" = "Tale opptaksknapp"; + +"Settings.DefaultEmojisFirst" = "Prioriter standard emojis"; +"Settings.DefaultEmojisFirst.Notice" = "Vis standard emojis før premium på emoji-tastaturet"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "opprettet: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Ble med %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Registrert"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Dobbelttrykk for å redigere meldingen"; + +"Settings.wideChannelPosts" = "Brede innlegg i kanaler"; +"Settings.ForceEmojiTab" = "Emoji-tastatur som standard"; + +"Settings.forceBuiltInMic" = "Tving Mikrofon på enheten"; +"Settings.forceBuiltInMic.Notice" = "Hvis aktivert, vil appen bare bruke enhetens mikrofon selv om hodetelefoner er tilkoblet."; + +"Settings.hideChannelBottomButton" = "Skjul Kanal Bunnerpanel"; + +"Settings.CallConfirmation" = "Ringebekreftelse"; +"Settings.CallConfirmation.Notice" = "Swiftgram vil spørre om din bekreftelse før det foretas et anrop."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Vil du ringe?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Vil du ta en videosamtale?"; + +"MutualContact.Label" = "gjensidig kontakt"; + +"Settings.swipeForVideoPIP" = "Video PIP med sveip"; +"Settings.swipeForVideoPIP.Notice" = "Hvis aktivert, vil sveipingen av video åpne den i bilde-i-bilde-modus."; diff --git a/Swiftgram/SGStrings/Strings/pl.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/pl.lproj/SGLocalizable.strings new file mode 100644 index 00000000..9efb5c22 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/pl.lproj/SGLocalizable.strings @@ -0,0 +1,245 @@ +"Settings.ContentSettings" = "Ustawienia zawartości"; + +"Settings.Tabs.Header" = "ZAKŁADKI"; +"Settings.Tabs.HideTabBar" = "Ukryj pasek zakładek"; +"Settings.Tabs.ShowContacts" = "Pokaż zakładkę kontakty"; +"Settings.Tabs.ShowNames" = "Pokaż nazwy zakładek"; + +"Settings.Folders.BottomTab" = "Foldery na dole"; +"Settings.Folders.BottomTabStyle" = "Styl folderów na dole"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Ukryj \"%@\""; +"Settings.Folders.RememberLast" = "Otwórz ostatni folder"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram otworzy ostatnio używany folder po ponownym uruchomieniu lub zmianie konta"; + +"Settings.Folders.CompactNames" = "Mniejszy odstęp"; +"Settings.Folders.AllChatsTitle" = "Tytuł \"Wszystkie czaty\""; +"Settings.Folders.AllChatsTitle.short" = "Krótki"; +"Settings.Folders.AllChatsTitle.long" = "Długi"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Domyślny"; + + +"Settings.ChatList.Header" = "LISTA CZATU"; +"Settings.CompactChatList" = "Kompaktowa lista czatów"; + +"Settings.Profiles.Header" = "PROFILE"; + +"Settings.Stories.Hide" = "Ukryj relacje"; +"Settings.Stories.WarnBeforeView" = "Pytaj przed wyświetleniem"; +"Settings.Stories.DisableSwipeToRecord" = "Wyłącz przeciągnij, aby nagrać"; + +"Settings.Translation.QuickTranslateButton" = "Przycisk Szybkie tłumaczenie"; + +"Stories.Warning.Author" = "Autor"; +"Stories.Warning.ViewStory" = "Pokazać relację?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ BĘDZIE WIEDZIAŁ, że obejrzano jego relację."; +"Stories.Warning.NoticeStealth" = "%@ nie będzie wiedział, że obejrzano jego relację."; + +"Settings.Photo.Quality.Notice" = "Jakość wysyłanych zdjęć i fotorelacji"; +"Settings.Photo.SendLarge" = "Wyślij duże zdjęcia"; +"Settings.Photo.SendLarge.Notice" = "Zwiększ limit rozmiaru skompresowanych obrazów do 2560px"; + +"Settings.VideoNotes.Header" = "OKRĄGŁE WIDEO"; +"Settings.VideoNotes.StartWithRearCam" = "Uruchom z tylną kamerą"; + +"Settings.CustomColors.Header" = "KOLORY KONTA"; +"Settings.CustomColors.Saturation" = "NASYCENIE"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Ustaw nasycenie na 0%%, aby wyłączyć kolory konta"; + +"Settings.UploadsBoost" = "Przyśpieszenie wysyłania"; +"Settings.DownloadsBoost" = "Przyśpieszenie pobierania"; +"Settings.DownloadsBoost.Notice" = "Zwiększa liczbę równoległych połączeń oraz rozmiar fragmentów plików. Jeśli twoja sieć nie jest w stanie znieść obciążenia, wypróbuj różne opcje, które pasują do twojego połączenia."; +"Settings.DownloadsBoost.none" = "Wyłączone"; +"Settings.DownloadsBoost.medium" = "Średnie"; +"Settings.DownloadsBoost.maximum" = "Maksymalne"; + +"Settings.ShowProfileID" = "Pokaż ID"; +"Settings.ShowDC" = "Pokaż centrum danych"; +"Settings.ShowCreationDate" = "Pokaż datę utworzenia czatu"; +"Settings.ShowCreationDate.Notice" = "Dla niektórych czatów data utworzenia może być nieznana."; + +"Settings.ShowRegDate" = "Pokaż datę rejestracji"; +"Settings.ShowRegDate.Notice" = "Data rejestracji jest przybliżona."; + +"Settings.SendWithReturnKey" = "Wyślij klawiszem „return”"; +"Settings.HidePhoneInSettingsUI" = "Ukryj numer telefonu w ustawieniach"; +"Settings.HidePhoneInSettingsUI.Notice" = "Twój numer zostanie ukryty tylko w interfejsie użytkownika. Aby ukryć go przed innymi, użyj ustawień prywatności."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Jeśli nieobecny przez 5 sekund"; + +"ProxySettings.UseSystemDNS" = "Użyj systemowego DNS"; +"ProxySettings.UseSystemDNS.Notice" = "Użyj systemowego DNS, aby ominąć limit czasu, jeśli nie masz dostępu do Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Nie **potrzebujesz** %@!"; +"Common.RestartRequired" = "Wymagany restart"; +"Common.RestartNow" = "Uruchom teraz ponownie"; +"Common.OpenTelegram" = "Otwórz Telegram"; +"Common.UseTelegramForPremium" = "Aby otrzymać Telegram Premium, musisz skorzystać z oficjalnej aplikacji Telegram. Po uzyskaniu Telegram Premium wszystkie jego funkcje staną się dostępne w Swiftgram."; +"Common.UpdateOS" = "Wymagana aktualizacja iOS"; + +"Message.HoldToShowOrReport" = "Przytrzymaj, aby Pokazać lub Zgłosić."; + +"Auth.AccountBackupReminder" = "Upewnij się, że masz zapasową metodę dostępu. Zachowaj SIM do SMS-ów lub zalogowaną dodatkową sesję, aby uniknąć zablokowania."; +"Auth.UnofficialAppCodeTitle" = "Kod można uzyskać tylko za pomocą oficjalnej aplikacji"; + +"Settings.SmallReactions" = "Małe reakcje"; +"Settings.HideReactions" = "Ukryj reakcje"; + +"ContextMenu.SaveToCloud" = "Zapisz w chmurze"; +"ContextMenu.SelectFromUser" = "Zaznacz od autora"; + +"Settings.ContextMenu" = "MENU KONTEKSTOWE"; +"Settings.ContextMenu.Notice" = "Wyłączone wpisy będą dostępne w podmenu „Swiftgram”."; + + +"Settings.ChatSwipeOptions" = "Opcje przesuwania listy czatów"; +"Settings.DeleteChatSwipeOption" = "Przesuń, aby usunąć czat"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Pociągnij ➝ następny kanał"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Przeciągnij, aby przejść do następnego tematu"; +"Settings.GalleryCamera" = "Aparat w galerii"; +"Settings.GalleryCameraPreview" = "Podgląd aparatu w galerii"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "Przycisk „%@”"; +"Settings.SnapDeletionEffect" = "Efekty usuwania wiadomości"; + +"Settings.Stickers.Size" = "WIELKOŚĆ"; +"Settings.Stickers.Timestamp" = "Pokaż znak czasu"; + +"Settings.RecordingButton" = "Przycisk głośności nagrywania"; + +"Settings.DefaultEmojisFirst" = "Wybierz standardowe emoji"; +"Settings.DefaultEmojisFirst.Notice" = "Na klawiaturze emoji pokaż standardowe emoji przed Premium"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "utworzony: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Dołączono %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Zarejestrowano"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Podwójne stuknięcie, aby edytować wiadomość"; + +"Settings.wideChannelPosts" = "Szerokie wpisy w kanałach"; +"Settings.ForceEmojiTab" = "Klawiatura emoji domyślnie"; + +"Settings.forceBuiltInMic" = "Wymuś mikrofon urządzenia"; +"Settings.forceBuiltInMic.Notice" = "Jeśli ta opcja jest włączona, aplikacja będzie korzystać tylko z mikrofonu urządzenia, nawet jeśli są podłączone słuchawki."; + +"Settings.showChannelBottomButton" = "Dolny panel kanału"; + +"Settings.secondsInMessages" = "Sekundy w wiadomościach"; + +"Settings.CallConfirmation" = "Potwierdzenie połączenia"; +"Settings.CallConfirmation.Notice" = "Swiftgram poprosi o twoje potwierdzenie przed wykonaniem połączenia."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Wykonać połączenie?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Wykonać połączenie wideo?"; + +"MutualContact.Label" = "wzajemny kontakt"; + +"Settings.swipeForVideoPIP" = "Wideo PIP po przesunięciu"; +"Settings.swipeForVideoPIP.Notice" = "Jeśli włączone, przesunięcie palcem otworzy film w trybie obrazu w obrazie."; + +"SessionBackup.Title" = "Kopia zapasowa kont"; +"SessionBackup.Sessions.Title" = "Sesje"; +"SessionBackup.Actions.Backup" = "Kopia zapasowa do pęku kluczy"; +"SessionBackup.Actions.Restore" = "Przywróć z pęku kluczy"; +"SessionBackup.Actions.DeleteAll" = "Usuń kopię zapasową pęku kluczy"; +"SessionBackup.Actions.DeleteOne" = "Usuń z kopii zapasowej"; +"SessionBackup.Actions.RemoveFromApp" = "Usuń z aplikacji"; +"SessionBackup.LastBackupAt" = "Ostatnia kopia zapasowa: %@"; +"SessionBackup.RestoreOK" = "OK. Przywrócono sesje: %@"; +"SessionBackup.LoggedIn" = "Zalogowano"; +"SessionBackup.LoggedOut" = "Wylogowano"; +"SessionBackup.DeleteAll.Title" = "Usunąć wszystkie sesje?"; +"SessionBackup.DeleteAll.Text" = "Wszystkie sesje zostaną usunięte z pęku kluczy.\n\nKonta nie zostaną wylogowane ze Swiftgram."; +"SessionBackup.DeleteSingle.Title" = "Usunąć 1 (jedną) sesję?"; +"SessionBackup.DeleteSingle.Text" = "%@ sesja zostanie usunięta z pęku kluczy.\n\nKonto nie zostanie wylogowane ze Swiftgram."; +"SessionBackup.RemoveFromApp.Title" = "Usunąć konto z aplikacji?"; +"SessionBackup.RemoveFromApp.Text" = "%@ sesja ZOSTANIE USUNIĘTA ze Swiftgram! Sesja pozostanie aktywna, więc możesz ją później przywrócić."; +"SessionBackup.Notice" = "Sesje są szyfrowane i przechowywane w pęku kluczy urządzenia. Sesje nigdy nie opuszczają urządzenia.\n\nWAŻNE: Aby przywrócić sesje na nowym urządzeniu lub po zresetowaniu systemu operacyjnego, MUSISZ włączyć szyfrowane kopie zapasowe, w przeciwnym razie pęk kluczy nie zostanie przeniesiony.\n\nUWAGA: Sesje mogą zostać unieważnione przez Telegram lub z innego urządzenia."; + +"MessageFilter.Title" = "Filtr wiadomości"; +"MessageFilter.SubTitle" = "Usuń elementy rozpraszające uwagę i zmniejsz widoczność wiadomości zawierających poniższe słowa kluczowe.\nW słowach kluczowych rozróżniana jest wielkość liter."; +"MessageFilter.Keywords.Title" = "Słowa kluczowe"; +"MessageFilter.InputPlaceholder" = "Wpisz słowo kluczowe"; + +"InputToolbar.Title" = "Panel formatowania"; + +"Notifications.MentionsAndReplies.Title" = "@Wzmianki i odpowiedzi"; +"Notifications.MentionsAndReplies.value.default" = "Domyślne"; +"Notifications.MentionsAndReplies.value.silenced" = "Wyciszone"; +"Notifications.MentionsAndReplies.value.disabled" = "Wyłączone"; +"Notifications.PinnedMessages.Title" = "Przypięte wiadomości"; +"Notifications.PinnedMessages.value.default" = "Domyślne"; +"Notifications.PinnedMessages.value.silenced" = "Wyciszone"; +"Notifications.PinnedMessages.value.disabled" = "Wyłączone"; + + +"PayWall.Text" = "Doładowany funkcjami Pro"; + +"PayWall.SessionBackup.Title" = "Kopia zapasowa sesji"; +"PayWall.SessionBackup.Notice" = "Przywróć sesje z zaszyfrowanej lokalnej kopii zapasowej pęku kluczy Apple."; +"PayWall.SessionBackup.Description" = "Zmiana urządzenia lub usunięcie Swiftgrama nie jest już problemem. Przywróć wszystkie sesje, które są nadal aktywne na serwerach Telegrama."; + +"PayWall.MessageFilter.Title" = "Filtr wiadomości"; +"PayWall.MessageFilter.Notice" = "Zmniejsz widoczność SPAM-u, promocji i irytujących wiadomości."; +"PayWall.MessageFilter.Description" = "Utwórz listę słów kluczowych, których nie chcesz często widzieć, a Swiftgram zredukuje liczbę elementów rozpraszających uwagę."; + +"PayWall.Notifications.Title" = "Wyłącz @wzmianki i odpowiedzi"; +"PayWall.Notifications.Notice" = "Ukryj lub wycisz nieistotne powiadomienia."; +"PayWall.Notifications.Description" = "Koniec z przypietymi wiadomościami i @wzmiankami, gdy potrzebujesz odrobiny spokoju."; + +"PayWall.InputToolbar.Title" = "Panel formatowania"; +"PayWall.InputToolbar.Notice" = "Oszczędź czas na przygotowywaniu wpisów dzięki panelowi tuż nad klawiaturą."; +"PayWall.InputToolbar.Description" = "Zastosuj i wyczyść formatowanie lub wstaw nowe wiersze jak profesjonalista."; + +"PayWall.AppIcons.Title" = "Unikalne ikony aplikacji"; +"PayWall.AppIcons.Notice" = "Dostosuj wygląd Swiftgram na ekranie głównym."; + +"PayWall.About.Title" = "O Swiftgram Pro"; +"PayWall.About.Notice" = "Bezpłatna wersja Swiftgram oferuje dziesiątki funkcji i ulepszeń w stosunku do aplikacji Telegram. Innowacje i synchronizacja Swiftgram z miesięcznymi aktualizacjami Telegram to ogromny wysiłek, który wymaga dużo czasu i drogiego sprzętu.\n\nSwiftgram to aplikacja typu open source, która szanuje twoją prywatność i nie przeszkadza ci reklamami. Subskrybując Swiftgram Pro uzyskujesz dostęp do ekskluzywnych funkcji i wspierasz niezależnego programistę."; +/* DO NOT TRANSLATE */ +"PayWall.About.Signature" = "@Kylmakalle"; +/* DO NOT TRANSLATE */ +"PayWall.About.SignatureURL" = "https://t.me/Kylmakalle"; + +"PayWall.ProSupport.Title" = "Problemy z płatnością?"; +"PayWall.ProSupport.Contact" = "Nie martw się!"; + +"PayWall.RestorePurchases" = "Przywróć zakup"; +"PayWall.Terms" = "Warunki korzystania z usługi"; +"PayWall.Privacy" = "Polityka prywatności"; +"PayWall.TermsURL" = "https://swiftgram.app/terms"; +"PayWall.PrivacyURL" = "https://swiftgram.app/privacy"; +"PayWall.Notice.Markdown" = "Subskrybując Swiftgram Pro akceptujesz [Warunki korzystania z usługi](%1$@) i [Politykę prywatności](%2$@) Swiftgram."; +"PayWall.Notice.Raw" = "Subskrybując Swiftgram Pro akceptujesz Warunki korzystania z usługi i Politykę prywatności Swiftgram."; + +"PayWall.Button.OpenPro" = "Używaj funkcji Pro"; +"PayWall.Button.Purchasing" = "Kupowanie…"; +"PayWall.Button.Restoring" = "Przywracanie zakupu…"; +"PayWall.Button.Validating" = "Weryfikacja zakupu…"; +"PayWall.Button.PaymentsUnavailable" = "Płatności niedostępne"; +"PayWall.Button.BuyInAppStore" = "Subskrybuj w wersji z App Store"; +"PayWall.Button.Subscribe" = "Subskrybuj za %@ / miesiąc"; +"PayWall.Button.ContactingAppStore" = "Kontakt z App Store…"; + +"Paywall.Error.Title" = "Błąd"; +"PayWall.ValidationError" = "Błąd weryfikacji"; +"PayWall.ValidationError.TryAgain" = "Coś poszło nie tak podczas weryfikacji zakupu. Nie martw się! Spróbuj przywrócić zakupy trochę później."; +"PayWall.ValidationError.Expired" = "Twoja subskrypcja wygasła. Subskrybuj ponownie, aby odzyskać dostęp do funkcji Pro."; diff --git a/Swiftgram/SGStrings/Strings/pt.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/pt.lproj/SGLocalizable.strings new file mode 100644 index 00000000..6f8830a3 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/pt.lproj/SGLocalizable.strings @@ -0,0 +1,263 @@ +"Settings.ContentSettings" = "Configurações de Conteúdo"; + +"Settings.Tabs.Header" = "ABAS"; +"Settings.Tabs.HideTabBar" = "Ocultar Abas de Guias"; +"Settings.Tabs.ShowContacts" = "Mostrar Aba dos Contatos"; +"Settings.Tabs.ShowNames" = "Mostrar nomes das abas"; + +"Settings.Folders.BottomTab" = "Pastas embaixo"; +"Settings.Folders.BottomTabStyle" = "Estilos de Pastas Inferiores"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Ocultar \"%@\""; +"Settings.Folders.RememberLast" = "Abrir última pasta"; +"Settings.Folders.RememberLast.Notice" = "O Swiftgram abrirá a última pasta usada após reiniciar ou trocar de conta"; + +"Settings.Folders.CompactNames" = "Espaçamento Menor"; +"Settings.Folders.AllChatsTitle" = "Título \"Todos os bate-papos\""; +"Settings.Folders.AllChatsTitle.short" = "Curto"; +"Settings.Folders.AllChatsTitle.long" = "Longas"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Padrão"; + + +"Settings.ChatList.Header" = "LISTA DE CHAT"; +"Settings.CompactChatList" = "Lista de Bate-Papo Compacta"; + +"Settings.Profiles.Header" = "Perfis"; + +"Settings.Stories.Hide" = "Ocultar Stories"; +"Settings.Stories.WarnBeforeView" = "Perguntar antes de visualizar"; +"Settings.Stories.DisableSwipeToRecord" = "Desativar deslize para gravar"; + +"Settings.Translation.QuickTranslateButton" = "Botão de Tradução Rápida"; +"Settings.Translation.Backend" = "Serviço"; +/* Do not translate */ +"Settings.Translation.Backend.default" = "Telegram"; +/* Do not translate */ +"Settings.Translation.Backend.gtranslate" = "GTranslate"; +"Settings.Translation.Backend.system" = "Sistema"; +"Settings.Translation.Backend.Notice" = "O Swiftgram usará %@ caso o serviço de tradução selecionado não esteja disponível."; + +"Settings.Transcription.Header" = "VOZ PARA TEXTO"; +"Settings.Transcription.Backend" = "Serviço"; +/* Do not translate */ +"Settings.Transcription.Backend.default" = "Telegram"; +/* Do not translate */ +"Settings.Transcription.Backend.apple" = "Apple"; +"Settings.Transcription.Backend.Notice" = "O Swiftgram usará %@ caso o serviço de transcrição selecionado não esteja disponível."; + +"Stories.Warning.Author" = "Autor"; +"Stories.Warning.ViewStory" = "Ver Story?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ SABERÁ que você viu a Story dele."; +"Stories.Warning.NoticeStealth" = "%@ não saberá que você viu a Story dele."; + +"Settings.Photo.Quality.Notice" = "Qualidade de fotos enviadas e photo-stories"; +"Settings.Photo.SendLarge" = "Enviar fotos grandes"; +"Settings.Photo.SendLarge.Notice" = "Aumentar o limite de tamanho de imagens comprimidas para 2560px"; + +"Settings.VideoNotes.Header" = "VÍDEOS REDONDOS"; +"Settings.VideoNotes.StartWithRearCam" = "Iniciar com a câmera traseira"; + +"Settings.CustomColors.Header" = "CORES DA CONTA"; +"Settings.CustomColors.Saturation" = "SATURAÇÃO"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Defina a saturação para 0%% para desativar as cores da conta"; + +"Settings.UploadsBoost" = "Aceleração de Uploads"; +"Settings.DownloadsBoost" = "Aceleração de Downloads"; +"Settings.DownloadsBoost.Notice" = "Aumenta o número de conexões paralelas e o tamanho dos pedaços de arquivo. Se sua rede não conseguir lidar com a carga, tente diferentes opções que se adequem à sua conexão."; +"Settings.DownloadsBoost.none" = "Desativado"; +"Settings.DownloadsBoost.medium" = "Médio"; +"Settings.DownloadsBoost.maximum" = "Máximo"; + +"Settings.ShowProfileID" = "Mostrar perfil"; +"Settings.ShowDC" = "Mostrar Centro de Dados"; +"Settings.ShowCreationDate" = "Mostrar data de criação do chat"; +"Settings.ShowCreationDate.Notice" = "A data de criação pode ser desconhecida para alguns chats."; + +"Settings.ShowRegDate" = "Mostrar data de registro"; +"Settings.ShowRegDate.Notice" = "A data de registo é aproximada."; + +"Settings.SendWithReturnKey" = "Enviar com a tecla \"retorno\""; +"Settings.HidePhoneInSettingsUI" = "Ocultar telefone nas configurações"; +"Settings.HidePhoneInSettingsUI.Notice" = "Seu número ficará oculto apenas na interface do usuário. Para ocultá-lo de outras pessoas, use as configurações de privacidade."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Se ausente por 5 segundos"; + +"ProxySettings.UseSystemDNS" = "Usar DNS do sistema"; +"ProxySettings.UseSystemDNS.Notice" = "Use o DNS do sistema para evitar tempo limite se você não tiver acesso ao DNS do Google"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Você **não precisa** de %@!"; +"Common.RestartRequired" = "Reinício necessário"; +"Common.RestartNow" = "Reiniciar agora"; +"Common.OpenTelegram" = "Abrir Telegram"; +"Common.UseTelegramForPremium" = "Observe que para obter o Telegram Premium, você precisa usar o aplicativo oficial do Telegram. Depois de obter o Telegram Premium, todos os seus recursos ficarão disponíveis no Swiftgram."; +"Common.UpdateOS" = "Atualização do iOS necessária"; + +"Message.HoldToShowOrReport" = "Segure para Mostrar ou Denunciar."; + +"Auth.AccountBackupReminder" = "Certifique-se de ter um método de acesso de backup. Mantenha um SIM para SMS ou uma sessão adicional logada para evitar ser bloqueado."; +"Auth.UnofficialAppCodeTitle" = "Você só pode obter o código com o aplicativo oficial"; + +"Settings.SmallReactions" = "Pequenas reações"; +"Settings.HideReactions" = "Esconder Reações"; + +"ContextMenu.SaveToCloud" = "Salvar na Nuvem"; +"ContextMenu.SelectFromUser" = "Selecionar do Autor"; + +"Settings.ContextMenu" = "MENU DE CONTEXTO"; +"Settings.ContextMenu.Notice" = "Entradas desativadas estarão disponíveis no sub-menu 'Swiftgram'."; + + +"Settings.ChatSwipeOptions" = "Opções de deslizar Lista de Chat"; +"Settings.DeleteChatSwipeOption" = "Deslize para excluir o bate-papo"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Puxe para o próximo canal não lido"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Arraste para o Próximo Tópico"; +"Settings.GalleryCamera" = "Câmera na Galeria"; +"Settings.GalleryCameraPreview" = "Pré-visualização da câmara na galeria"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "Botão \"%@\""; +"Settings.SnapDeletionEffect" = "Efeitos de exclusão de mensagens"; + +"Settings.Stickers.Size" = "TAMANHO"; +"Settings.Stickers.Timestamp" = "Mostrar Data/Hora"; + +"Settings.RecordingButton" = "Botão de gravação de voz"; + +"Settings.DefaultEmojisFirst" = "Priorizar emojis padrão"; +"Settings.DefaultEmojisFirst.Notice" = "Mostrar emojis padrão antes dos premium no teclado de emojis"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "criado: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Entrou em %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Registrado"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Toque duplo para editar mensagem"; + +"Settings.wideChannelPosts" = "Postagens amplas nos canais"; +"Settings.ForceEmojiTab" = "Teclado de emojis por padrão"; + +"Settings.forceBuiltInMic" = "Forçar Microfone do Dispositivo"; +"Settings.forceBuiltInMic.Notice" = "Se ativado, o aplicativo usará apenas o microfone do dispositivo mesmo se os fones de ouvido estiverem conectados."; + +"Settings.showChannelBottomButton" = "Painel Inferior do Canal"; + +"Settings.secondsInMessages" = "Segundos em Mensagens"; + +"Settings.CallConfirmation" = "Confirmação de chamada"; +"Settings.CallConfirmation.Notice" = "O Swiftgram pedirá sua confirmação antes de fazer uma chamada."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Fazer uma Chamada?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Fazer uma Chamada de Vídeo?"; + +"MutualContact.Label" = "contato mútuo"; + +"Settings.swipeForVideoPIP" = "Vídeo PIP com Deslizar"; +"Settings.swipeForVideoPIP.Notice" = "Se habilitado, deslizar o vídeo o abrirá em modo Picture-in-Picture."; + +"SessionBackup.Title" = "Backup de Sessão"; +"SessionBackup.Sessions.Title" = "Sessões"; +"SessionBackup.Actions.Backup" = "Backup para o Keychain"; +"SessionBackup.Actions.Restore" = "Restaurar do Keychain"; +"SessionBackup.Actions.DeleteAll" = "Excluir Backup do Keychain"; +"SessionBackup.Actions.DeleteOne" = "Excluir do Backup"; +"SessionBackup.Actions.RemoveFromApp" = "Remover do App"; +"SessionBackup.LastBackupAt" = "Último Backup: %@"; +"SessionBackup.RestoreOK" = "OK. Sessões restauradas: %@"; +"SessionBackup.LoggedIn" = "Conectado"; +"SessionBackup.LoggedOut" = "Desconectado"; +"SessionBackup.DeleteAll.Title" = "Excluir Todas as Sessões?"; +"SessionBackup.DeleteAll.Text" = "Todas as sessões serão removidas do Keychain.\n\nAs contas não serão desconectadas do Swiftgram."; +"SessionBackup.DeleteSingle.Title" = "Excluir 1 (uma) Sessão?"; +"SessionBackup.DeleteSingle.Text" = "%@ sessão será removida do Keychain.\n\nA conta não será desconectada do Swiftgram."; +"SessionBackup.RemoveFromApp.Title" = "Remover conta do App?"; +"SessionBackup.RemoveFromApp.Text" = "%@ sessão SERÁ REMOVIDA do Swiftgram! A sessão permanecerá ativa, para que você possa restaurá-la mais tarde."; +"SessionBackup.Notice" = "As sessões são criptografadas e armazenadas no Acesso às Chaves do dispositivo. As sessões nunca saem do seu dispositivo.\n\nIMPORTANTE: Para restaurar sessões em um novo dispositivo ou após a redefinição do sistema operacional, você DEVE habilitar backups criptografados, caso contrário o Keychain não será transferido.\n\nNOTA: as sessões ainda podem ser revogadas pelo Telegram ou de outro dispositivo."; + +"MessageFilter.Title" = "Filtro de Mensagens"; +"MessageFilter.SubTitle" = "Remova distrações e reduza a visibilidade de mensagens contendo palavras-chave abaixo.\nAs palavras-chave são sensíveis a maiúsculas e minúsculas."; +"MessageFilter.Keywords.Title" = "Palavras-chave"; +"MessageFilter.InputPlaceholder" = "Insira a palavra-chave"; + +"InputToolbar.Title" = "Painel de Formatação"; + +"Notifications.MentionsAndReplies.Title" = "@Menções e Respostas"; +"Notifications.MentionsAndReplies.value.default" = "Padrão"; +"Notifications.MentionsAndReplies.value.silenced" = "Silenciado"; +"Notifications.MentionsAndReplies.value.disabled" = "Desativado"; +"Notifications.PinnedMessages.Title" = "Mensagens Fixadas"; +"Notifications.PinnedMessages.value.default" = "Padrão"; +"Notifications.PinnedMessages.value.silenced" = "Silenciado"; +"Notifications.PinnedMessages.value.disabled" = "Desativado"; + + +"PayWall.Text" = "Supercarregado com recursos Pro"; + +"PayWall.SessionBackup.Title" = "Backup de Sessão"; +"PayWall.SessionBackup.Notice" = "Faça login em contas sem código, mesmo depois de reinstalar. Armazenamento seguro com Keychain no dispositivo."; +"PayWall.SessionBackup.Description" = "Alterar o dispositivo ou excluir o Swiftgram não é mais um problema. Restaure todas as sessões que ainda estão ativas nos servidores do Telegram."; + +"PayWall.MessageFilter.Title" = "Filtro de Mensagens"; +"PayWall.MessageFilter.Notice" = "Reduza a visibilidade de SPAM, promoções e mensagens irritantes."; +"PayWall.MessageFilter.Description" = "Crie uma lista de palavras-chave que você não quer ver frequentemente e o Swiftgram reduzirá as distrações."; + +"PayWall.Notifications.Title" = "Desativar @menções e respostas"; +"PayWall.Notifications.Notice" = "Oculte ou silencie notificações não importantes."; +"PayWall.Notifications.Description" = "Não há mais mensagens fixadas ou @menções quando você precisa de alguma coisa."; + +"PayWall.InputToolbar.Title" = "Painel de Formatação"; +"PayWall.InputToolbar.Notice" = "Economize tempo formatando as mensagens com apenas um único toque."; +"PayWall.InputToolbar.Description" = "Aplique e limpe a formatação ou insira novas linhas como um profissional."; + +"PayWall.AppIcons.Title" = "Ícones de Aplicativos Exclusivos"; +"PayWall.AppIcons.Notice" = "Personalize a aparência do Swiftgram na sua tela inicial."; + +"PayWall.About.Title" = "Sobre o Swiftgram Pro"; +"PayWall.About.Notice" = "A versão gratuita do Swiftgram oferece dezenas de recursos e melhorias em relação ao aplicativo Telegram. Inovar e manter o Swiftgram em sincronia com as atualizações mensais do Telegram é um grande esforço que requer muito tempo e hardware caro.\n\nO Swiftgram é um aplicativo de código aberto que respeita sua privacidade e não incomoda você com anúncios. Ao se inscrever no Swiftgram Pro, você obtém acesso a recursos exclusivos e apoia um desenvolvedor independente."; +/* DO NOT TRANSLATE */ +"PayWall.About.Signature" = "@Kylmakalle"; +/* DO NOT TRANSLATE */ +"PayWall.About.SignatureURL" = "https://t.me/Kylmakalle"; + +"PayWall.ProSupport.Title" = "Problemas com pagamento?"; +"PayWall.ProSupport.Contact" = "Não se preocupe!"; + +"PayWall.RestorePurchases" = "Restaurar Compras"; +"PayWall.Terms" = "Termos de Serviço"; +"PayWall.Privacy" = "Política de Privacidade"; +"PayWall.TermsURL" = "https://swiftgram.app/terms"; +"PayWall.PrivacyURL" = "https://swiftgram.app/privacy"; +"PayWall.Notice.Markdown" = "Ao se inscrever no Swiftgram Pro, você concorda com os [Termos de Serviço do Swiftgram](%1$@) e com a [Política de Privacidade](%2$@)."; +"PayWall.Notice.Raw" = "Ao se inscrever no Swiftgram Pro, você concorda com os Termos de Serviço e Política de Privacidade do Swiftgram."; + +"PayWall.Button.OpenPro" = "Usar recursos Pro"; +"PayWall.Button.Purchasing" = "Adquirindo..."; +"PayWall.Button.Restoring" = "Restaurando Compras..."; +"PayWall.Button.Validating" = "Validando Compra..."; +"PayWall.Button.PaymentsUnavailable" = "Pagamentos indisponíveis"; +"PayWall.Button.BuyInAppStore" = "Inscrever-se na versão da App Store"; +"PayWall.Button.Subscribe" = "Assinar por %@ / mês"; +"PayWall.Button.ContactingAppStore" = "Contatando App Store..."; + +"Paywall.Error.Title" = "Erro"; +"PayWall.ValidationError" = "Erro de Validação"; +"PayWall.ValidationError.TryAgain" = "Algo deu errado durante a validação da compra. Sem problemas! Tente Restaurar Compras um pouco mais tarde."; +"PayWall.ValidationError.Expired" = "Sua assinatura expirou. Inscreva-se novamente para recuperar o acesso aos recursos Pro."; + +"AppBadge.Title" = "Emblema do Aplicativo"; +"AppBadge.Notice" = "Personalizar Emblema do Aplicativo Exibido nas capturas de tela"; diff --git a/Swiftgram/SGStrings/Strings/ro.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/ro.lproj/SGLocalizable.strings new file mode 100644 index 00000000..ccb2ad1e --- /dev/null +++ b/Swiftgram/SGStrings/Strings/ro.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Setări Conținut"; + +"Settings.Tabs.Header" = "FERESTRE"; +"Settings.Tabs.HideTabBar" = "Ascunde bara de filă"; +"Settings.Tabs.ShowContacts" = "Vizualizare contacte"; +"Settings.Tabs.ShowNames" = "Arată Fereastra cu Numele"; + +"Settings.Folders.BottomTab" = "Dosare de jos"; +"Settings.Folders.BottomTabStyle" = "Stil directoare de jos"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegramă"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Ascundeți „%@\""; +"Settings.Folders.RememberLast" = "Deschideți ultimul dosar"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram va deschide ultimul folder utilizat atunci când reporniți aplicația sau schimbați conturile."; + +"Settings.Folders.CompactNames" = "Spațiere mai mică"; +"Settings.Folders.AllChatsTitle" = "Titlul \"Toate conversațiile\""; +"Settings.Folders.AllChatsTitle.short" = "Scurt"; +"Settings.Folders.AllChatsTitle.long" = "Lungă"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Implicit"; + + +"Settings.ChatList.Header" = "LISTA CHAT"; +"Settings.CompactChatList" = "Lista compactă de Chat"; + +"Settings.Profiles.Header" = "PROFILES"; + +"Settings.Stories.Hide" = "Ascunde povestiri"; +"Settings.Stories.WarnBeforeView" = "Întreabă înainte de vizualizare"; +"Settings.Stories.DisableSwipeToRecord" = "Dezactivează glisarea pentru înregistrare"; + +"Settings.Translation.QuickTranslateButton" = "Butonul Traducere Rapidă"; + +"Stories.Warning.Author" = "Autor"; +"Stories.Warning.ViewStory" = "Vezi povestirea?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ VOR FI ACĂ SĂ VEDEȚI că le-ați văzut povestea lor."; +"Stories.Warning.NoticeStealth" = "%@ nu va putea vedea povestea lor."; + +"Settings.Photo.Quality.Notice" = "Calitatea fotografiilor și povestirilor încărcate."; +"Settings.Photo.SendLarge" = "Trimite fotografii mari"; +"Settings.Photo.SendLarge.Notice" = "Crește limita laterală a imaginilor comprimate la 2560px."; + +"Settings.VideoNotes.Header" = "VIDEO ROTUND"; +"Settings.VideoNotes.StartWithRearCam" = "Începe cu camera posterioară"; + +"Settings.CustomColors.Header" = "COLORTURI DE CONT"; +"Settings.CustomColors.Saturation" = "SATURARE"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Setați la 0%% pentru a dezactiva culorile contului."; + +"Settings.UploadsBoost" = "Accelerare Încărcare"; +"Settings.DownloadsBoost" = "Impuls descărcare"; +"Settings.DownloadsBoost.Notice" = "Crește numărul de conexiuni paralele și dimensiunea fragmentelor de fișier. Dacă rețeaua ta nu poate gestiona încărcătura, încearcă diferite opțiuni care se potrivesc conexiunii tale."; +"Settings.DownloadsBoost.none" = "Dezactivat"; +"Settings.DownloadsBoost.medium" = "Medie"; +"Settings.DownloadsBoost.maximum" = "Maxim"; + +"Settings.ShowProfileID" = "Arată ID-ul profilului"; +"Settings.ShowDC" = "Arată Centrul de date"; +"Settings.ShowCreationDate" = "Arată data creării chat-ului"; +"Settings.ShowCreationDate.Notice" = "Data creării poate fi necunoscută pentru unele conversații."; + +"Settings.ShowRegDate" = "Arată data înregistrării"; +"Settings.ShowRegDate.Notice" = "Data înregistrării este aproximativă."; + +"Settings.SendWithReturnKey" = "Trimite cu cheia \"Returnare\""; +"Settings.HidePhoneInSettingsUI" = "Ascunde telefonul din setări"; +"Settings.HidePhoneInSettingsUI.Notice" = "Acest lucru va ascunde numărul de telefon din interfața de setări. Pentru a-l ascunde de alții, mergi la confidențialitate și securitate."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Dacă este plecat timp de 5 secunde"; + +"ProxySettings.UseSystemDNS" = "Utilizați DNS sistem"; +"ProxySettings.UseSystemDNS.Notice" = "Utilizați DNS pentru a ocoli timeout-ul dacă nu aveți acces la Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Nu ai nevoie de ** %@!"; +"Common.RestartRequired" = "Repornire necesară"; +"Common.RestartNow" = "Repornește acum"; +"Common.OpenTelegram" = "Deschide telegrama"; +"Common.UseTelegramForPremium" = "Vă rugăm să reţineţi că, pentru a obţine Telegram Premium, trebuie să utilizaţi aplicaţia oficială Telegram. Odată ce ai obţinut Telegram Premium, toate caracteristicile sale vor deveni disponibile în Swiftgram."; + +"Message.HoldToShowOrReport" = "Țineți apăsat pentru a afișa sau raporta."; + +"Auth.AccountBackupReminder" = "Asigurați-vă că aveți o metodă de acces de rezervă. Păstrați un SIM pentru SMS sau o sesiune adițională conectată pentru a evita blocarea."; +"Auth.UnofficialAppCodeTitle" = "Poți obține codul doar cu aplicația oficială"; + +"Settings.SmallReactions" = "Reacţii mici"; +"Settings.HideReactions" = "Ascunde Reacțiile"; + +"ContextMenu.SaveToCloud" = "Salvează în Cloud"; +"ContextMenu.SelectFromUser" = "Selectați din autor"; + +"Settings.ContextMenu" = "MENIU CONTEXTUAL"; +"Settings.ContextMenu.Notice" = "Intrările dezactivate vor fi disponibile în submeniul 'Swiftgram'."; + + +"Settings.ChatSwipeOptions" = "Opțiuni de glisare a chatului"; +"Settings.DeleteChatSwipeOption" = "Glisați pentru ștergere chat"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Trageţi pentru următorul canal necitit"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Trageți către Următorul Subiect"; +"Settings.GalleryCamera" = "Cameră foto în Galerie"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "Butonul \"%@\""; +"Settings.SnapDeletionEffect" = "Efecte ștergere mesaj"; + +"Settings.Stickers.Size" = "MISIUNE"; +"Settings.Stickers.Timestamp" = "Arată Ora"; + +"Settings.RecordingButton" = "Butonul Înregistrare Voce"; + +"Settings.DefaultEmojisFirst" = "Prioritize emoticoanele standard"; +"Settings.DefaultEmojisFirst.Notice" = "Afișați emoticoanele standard înainte de cele premium în tastatura emoji"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "creat: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "S-a alăturat %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Înregistrat"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Apăsați de două ori pentru a edita mesajul"; + +"Settings.wideChannelPosts" = "Postări late în canale"; +"Settings.ForceEmojiTab" = "Tastatură emoji implicită"; + +"Settings.forceBuiltInMic" = "Forțează Microfon Dispozitiv"; +"Settings.forceBuiltInMic.Notice" = "Dacă este activat, aplicația va folosi doar microfonul dispozitivului chiar dacă sunt conectate căștile."; + +"Settings.hideChannelBottomButton" = "Ascundeți panoul de jos al canalului"; + +"Settings.CallConfirmation" = "Confirmare apel"; +"Settings.CallConfirmation.Notice" = "Swiftgram va solicita confirmarea dumneavoastră înainte de a efectua un apel."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Ești sigur că vrei să faci un apel?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Ești sigur că vrei să faci un apel video?"; + +"MutualContact.Label" = "contact mutual"; + +"Settings.swipeForVideoPIP" = "Video PIP cu gestul de glisare"; +"Settings.swipeForVideoPIP.Notice" = "Dacă este activat, glisarea video va deschide în modul imagine în imagine."; diff --git a/Swiftgram/SGStrings/Strings/ru.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/ru.lproj/SGLocalizable.strings new file mode 100644 index 00000000..0488ecf5 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/ru.lproj/SGLocalizable.strings @@ -0,0 +1,274 @@ +"Settings.ContentSettings" = "Настройки контента"; + +"Settings.Tabs.Header" = "ВКЛАДКИ"; +"Settings.Tabs.HideTabBar" = "Скрыть панель вкладок"; +"Settings.Tabs.ShowContacts" = "Вкладка «Контакты»"; +"Settings.Tabs.ShowNames" = "Имена вкладок"; +"Settings.Tabs.SearchButton" = "Кнопка поиска"; +"Settings.Tabs.WideTabBar" = "Широкая панель"; +"Settings.Tabs.WideTabBar.Notice" = "Сохраняет полную ширину панели вкладок, когда некоторые вкладки скрыты."; + +"Settings.Folders.BottomTab" = "Папки снизу"; +"Settings.Folders.BottomTabStyle" = "Стиль папок внизу"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Скрыть \"%@\""; +"Settings.Folders.RememberLast" = "Открывать последнюю папку"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram откроет последнюю использованную папку после перезапуска или переключения учетной записи"; + +"Settings.Folders.CompactNames" = "Уменьшенные расстояния"; +"Settings.Folders.AllChatsTitle" = "Название \"Все чаты\""; +"Settings.Folders.AllChatsTitle.short" = "Короткое"; +"Settings.Folders.AllChatsTitle.long" = "Длинное"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "По умолчанию"; + + +"Settings.ChatList.Header" = "СПИСОК ЧАТОВ"; +"Settings.CompactChatList" = "Компактный список чатов"; +"Settings.CompactMessagePreview" = "Компактное превью сообщений"; +"Settings.Profiles.Header" = "ПРОФИЛИ"; + +"Settings.Stories.Hide" = "Скрыть истории"; +"Settings.Stories.WarnBeforeView" = "Спросить перед просмотром"; +"Settings.Stories.DisableSwipeToRecord" = "Отключить свайп для записи"; + +"Settings.Translation.QuickTranslateButton" = "Кнопка быстрого перевода"; +"Settings.Translation.Backend" = "Сервис"; +/* Do not translate */ +"Settings.Translation.Backend.default" = "Telegram"; +/* Do not translate */ +"Settings.Translation.Backend.gtranslate" = "GTranslate"; +"Settings.Translation.Backend.system" = "Система"; +"Settings.Translation.Backend.Notice" = "Swiftgram будет использовать %@, если выбранный сервис перевода недоступен."; + +"Settings.Transcription.Header" = "ГОЛОС В ТЕКСТ"; +"Settings.Transcription.Backend" = "Сервис"; +/* Do not translate */ +"Settings.Transcription.Backend.default" = "Telegram"; +/* Do not translate */ +"Settings.Transcription.Backend.apple" = "Apple"; +"Settings.Transcription.Backend.Notice" = "Swiftgram будет использовать %@, если выбранный сервис транскрипции недоступен."; + +"Stories.Warning.Author" = "Автор"; +"Stories.Warning.ViewStory" = "Просмотреть историю?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ СМОЖЕТ УВИДЕТЬ, что вы просмотрели историю."; +"Stories.Warning.NoticeStealth" = "%@ не сможет увидеть, что вы просмотрели историю."; + +"Settings.Photo.Quality.Notice" = "Качество исходящих фото и фото-историй"; +"Settings.Photo.SendLarge" = "Отправлять большие фото"; +"Settings.Photo.SendLarge.Notice" = "Увеличить лимит сторон для сжатых фото до 2560пкс"; + +"Settings.VideoNotes.Header" = "КРУГЛЫЕ ВИДЕО"; +"Settings.VideoNotes.StartWithRearCam" = "На заднюю камеру"; + +"Settings.CustomColors.Header" = "ПЕРСОНАЛЬНЫЕ ЦВЕТА"; +"Settings.CustomColors.Saturation" = "НАСЫЩЕННОСТЬ"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Установите насыщенность на 0%%, чтобы отключить персональные цвета"; + +"Settings.UploadsBoost" = "Ускорение загрузки"; +"Settings.DownloadsBoost" = "Ускорение скачивания"; +"Settings.DownloadsBoost.Notice" = "Увеличивает количество параллельных соединений и размер частей файлов. Если ваша сеть не может справиться с нагрузкой, попробуйте разные опции, которые подойдут для вашего соединения."; +"Settings.DownloadsBoost.none" = "Выключено"; +"Settings.DownloadsBoost.medium" = "Средне"; +"Settings.DownloadsBoost.maximum" = "Максимум"; + +"Settings.ShowProfileID" = "ID профилей"; +"Settings.ShowDC" = "Показать дата-центр (DC)"; +"Settings.ShowCreationDate" = "Показать дату создания чата"; +"Settings.ShowCreationDate.Notice" = "Дата создания может быть неизвестна для некоторых чатов."; + +"Settings.ShowRegDate" = "Показать дату регистрации"; +"Settings.ShowRegDate.Notice" = "Дата регистрации приблизительная."; + +"Settings.SendWithReturnKey" = "Отправка кнопкой \"Ввод\""; +"Settings.HidePhoneInSettingsUI" = "Скрыть номер"; +"Settings.HidePhoneInSettingsUI.Notice" = "Ваш номер будет скрыт только в интерфейсе настроек. Используйте настройки Конфиденциальности, чтобы скрыть его от других."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Через 5 секунд"; + +"ProxySettings.UseSystemDNS" = "Системный DNS"; +"ProxySettings.UseSystemDNS.Notice" = "Используйте системный DNS, чтобы избежать задержки, если у вас нет доступа к DNS Google"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Вам **не нужен** %@!"; +"Common.RestartRequired" = "Необходим перезапуск"; +"Common.RestartNow" = "Перезапустить Сейчас"; +"Common.OpenTelegram" = "Открыть Telegram"; +"Common.UseTelegramForPremium" = "Обратите внимание, что для получения Telegram Premium, вы должны использовать официальное приложение Telegram. Как только вы получите Telegram Premium, все его функции станут доступны в Swiftgram."; +"Common.UpdateOS" = "Требуется обновление iOS"; +"Common.KnowWhatYouDo" = "Пожалуйста, меняйте эти настройки только если вы знаете, что они делают."; + +"Message.HoldToShowOrReport" = "Удерживайте для Показа или Жалобы."; + +"Auth.AccountBackupReminder" = "Убедитесь, что у вас есть запасной вариант входа: Активная SIM-карта или дополнительная сессия, чтобы не потерять доступ к аккаунту."; +"Auth.UnofficialAppCodeTitle" = "Вы можете получить код только в официальном приложении"; + +"Settings.SmallReactions" = "Маленькие реакции"; +"Settings.HideReactions" = "Скрыть реакции"; + +"ContextMenu.SaveToCloud" = "Сохранить в Избранное"; +"ContextMenu.SelectFromUser" = "Выбрать от Автора"; + +"Settings.ContextMenu" = "КОНТЕКСТНОЕ МЕНЮ"; +"Settings.ContextMenu.Notice" = "Выключенные пункты будут доступны в подменю «Swiftgram»."; + + +"Settings.ChatSwipeOptions" = "Опции чатов при свайпе"; +"Settings.DeleteChatSwipeOption" = "Свайп для удаления чата"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Свайп между каналами"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Свайп между топиками"; +"Settings.GalleryCamera" = "Камера в галерее"; +"Settings.GalleryCameraPreview" = "Превью камеры в галерее"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "Кнопка \"%@\""; +"Settings.SnapDeletionEffect" = "Эффекты удаления сообщений"; + +"Settings.Stickers.Size" = "РАЗМЕР"; +"Settings.Stickers.Timestamp" = "Показывать время"; + +"Settings.RecordingButton" = "Кнопка записи голоса"; + +"Settings.DefaultEmojisFirst" = "Сначала стандартные смайлы"; +"Settings.DefaultEmojisFirst.Notice" = "Показывать стандартные эмодзи перед Premium в эмодзи-клавиатуре"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "создан: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Присоединился к %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Дата регистрации"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Редактирование двойным тапом"; + +"Settings.wideChannelPosts" = "Широкие посты в каналах"; +"Settings.ForceEmojiTab" = "Сначала вкладка смайлов"; + +"Settings.forceBuiltInMic" = "Микрофон устройства"; +"Settings.forceBuiltInMic.Notice" = "Если включено, то приложение будет использовать только встроенный микрофон устройства, даже если подключены наушники."; + +"Settings.showChannelBottomButton" = "Нижняя панель канала"; + +"Settings.secondsInMessages" = "Секунды в Сообщениях"; + +"Settings.CallConfirmation" = "Подтверждение вызова"; +"Settings.CallConfirmation.Notice" = "Swiftgram запросит подтверждение перед совершением звонка."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Позвонить?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Позвонить с видео?"; + +"MutualContact.Label" = "взаимный контакт"; + +"Settings.swipeForVideoPIP" = "Видео PIP свайпом"; +"Settings.swipeForVideoPIP.Notice" = "Если включено, свайп видео откроет его в режиме «Картинка в картинке»."; + +"SessionBackup.Title" = "Бэкап аккаунтов"; +"SessionBackup.Sessions.Title" = "Сессии"; +"SessionBackup.Actions.Backup" = "Бэкап в Keychain"; +"SessionBackup.Actions.Restore" = "Восстановить из Keychain"; +"SessionBackup.Actions.DeleteAll" = "Удалить Бэкап из Keychain"; +"SessionBackup.Actions.DeleteOne" = "Удалить из Бэкапа"; +"SessionBackup.Actions.RemoveFromApp" = "Удалить из приложения"; +"SessionBackup.LastBackupAt" = "Последний бэкап: %@"; +"SessionBackup.RestoreOK" = "ОК. Восстановлено: %@"; +"SessionBackup.LoggedIn" = "Залогинен"; +"SessionBackup.LoggedOut" = "Разлогинен"; +"SessionBackup.DeleteAll.Title" = "Удалить все сессии?"; +"SessionBackup.DeleteAll.Text" = "Все сессии будут удалены из Keychain.\n\nАккаунты не будут разлогинены из Swiftgram."; +"SessionBackup.DeleteSingle.Title" = "Удалить 1 (одну) сессию?"; +"SessionBackup.DeleteSingle.Text" = "%@ сессия будет удалена из Keychain.\n\nАккаунт не будет разлогинен из Swiftgram."; +"SessionBackup.RemoveFromApp.Title" = "Удалить аккаунт из приложения?"; +"SessionBackup.RemoveFromApp.Text" = "%@ сессия БУДЕТ УДАЛЕНА из Swiftgram! Сессия останется активной, чтобы вы могли восстановить ее позже."; +"SessionBackup.Notice" = "Сессии шифруются и хранятся в Keychain устройства. Сессии никогда не покидают ваше устройство.\n\nВАЖНО: Чтобы восстановить сессии на новом устройстве или после сброса системы, ОБЯЗАТЕЛЬНО включите шифрование резервных копий ОС, иначе Keychain будет утерян при восстановлении.\n\nПРИМЕЧАНИЕ: Сессии всё ещё могут быть разлогинены самим Telegram или с другого устройства."; + +"MessageFilter.Title" = "Фильтр сообщений"; +"MessageFilter.SubTitle" = "Убирает отвлекающие факторы и уменьшает видимость сообщений, содержащих ключевые слова ниже.\nКлючевые слова чувствительны к регистру."; +"MessageFilter.Keywords.Title" = "Ключевые слова"; +"MessageFilter.InputPlaceholder" = "Введите слово"; + +"InputToolbar.Title" = "Панель форматирования"; + +"Notifications.MentionsAndReplies.Title" = "@Упоминания и ответы"; +"Notifications.MentionsAndReplies.value.default" = "По умолчанию"; +"Notifications.MentionsAndReplies.value.silenced" = "Без звука"; +"Notifications.MentionsAndReplies.value.disabled" = "Выключено"; +"Notifications.PinnedMessages.Title" = "Сообщение закреплено"; +"Notifications.PinnedMessages.value.default" = "По умолчанию"; +"Notifications.PinnedMessages.value.silenced" = "Без звука"; +"Notifications.PinnedMessages.value.disabled" = "Выключено"; + + +"PayWall.Text" = "Заряжен Pro функциями"; + +"PayWall.SessionBackup.Title" = "Бэкап Аккаунтов"; +"PayWall.SessionBackup.Notice" = "Вход в аккаунты без кода, даже после переустановки. Безопасное хранение в Keychain на устройстве."; +"PayWall.SessionBackup.Description" = "Смена устройства или удаление Swiftgram больше не проблема. Восстановите все ваши Сессии, которые активны на серверах Telegram."; + +"PayWall.MessageFilter.Title" = "Фильтр сообщений"; +"PayWall.MessageFilter.Notice" = "Уменьшает видимость навязчивых сообщений со СПАМом или рекламой."; +"PayWall.MessageFilter.Description" = "Создайте список ключевых слов, которые вы не хотите встречать, и Swiftgram снизит их видимость."; + +"PayWall.Notifications.Title" = "Отключение @тэгов и ответов"; +"PayWall.Notifications.Notice" = "Скрывает или приглушает неважные уведомления."; +"PayWall.Notifications.Description" = "Никаких больше Закрепов или @тэгов, когда нужно побыть в тишине."; + +"PayWall.InputToolbar.Title" = "Панель форматирования"; +"PayWall.InputToolbar.Notice" = "Экономит время, форматируя сообщения всего одним касанием."; +"PayWall.InputToolbar.Description" = "Применяйте и очищайте форматирование, переносите абзацы как Pro."; + +"PayWall.AppIcons.Title" = "Уникальные иконки приложения"; +"PayWall.AppIcons.Notice" = "Настройка внешнего вида Swiftgram на главном экране."; + +"PayWall.About.Title" = "О Swiftgram Pro"; +"PayWall.About.Notice" = "Бесплатная версия Swiftgram предлагает десятки функций и улучшений по сравнению с приложением Telegram. Новые функции и синхронизация Swiftgram с ежемесячными обновлениями Telegram — это огромные усилия, требующие много времени и дорогой техники.\n\nSwiftgram — это приложение с открытым исходным кодом, которое уважает вашу конфиденциальность и не беспокоит вас рекламой. Подписываясь на Swiftgram Pro, вы получаете доступ к эксклюзивным функциям и поддерживаете независимого разработчика."; +/* DO NOT TRANSLATE */ +"PayWall.About.Signature" = "@Kylmakalle"; +/* DO NOT TRANSLATE */ +"PayWall.About.SignatureURL" = "https://t.me/Kylmakalle"; + +"PayWall.ProSupport.Title" = "Проблемы с оплатой?"; +"PayWall.ProSupport.Contact" = "Не беда!"; + +"PayWall.RestorePurchases" = "Восстановить покупки"; +"PayWall.Terms" = "Условия использования"; +"PayWall.Privacy" = "Политика конфиденциальности"; +"PayWall.TermsURL" = "https://swiftgram.app/terms"; +"PayWall.PrivacyURL" = "https://swiftgram.app/privacy"; +"PayWall.Notice.Markdown" = "Подписываясь на Swiftgram Pro, вы соглашаетесь с [Условиями использования Swiftgram](%1$@) и [Политикой конфиденциальности](%2$@)."; +"PayWall.Notice.Raw" = "Подписываясь на Swiftgram Pro, вы соглашаетесь с Условиями использования и Политикой конфиденциальности Swiftgram."; + +"PayWall.Button.OpenPro" = "Pro функции"; +"PayWall.Button.Purchasing" = "Покупка..."; +"PayWall.Button.Restoring" = "Восстановление покупок..."; +"PayWall.Button.Validating" = "Проверка покупки..."; +"PayWall.Button.PaymentsUnavailable" = "Платежи недоступны"; +"PayWall.Button.BuyInAppStore" = "Подписаться в App Store версии"; +"PayWall.Button.Subscribe" = "Подписаться за %@ / месяц"; +"PayWall.Button.ContactingAppStore" = "Подключение к App Store..."; + +"Paywall.Error.Title" = "Ошибка"; +"PayWall.ValidationError" = "Ошибка проверки"; +"PayWall.ValidationError.TryAgain" = "Что-то пошло не так во время проверки оплаты. Не волнуйтесь! Попробуйте Восстановить Покупки чуть позже."; +"PayWall.ValidationError.Expired" = "Ваша подписка истекла. Подпишитесь снова, чтобы восстановить доступ к Pro функциям."; + +"AppBadge.Title" = "Бэйдж приложения"; +"AppBadge.Notice" = "Настройка Бэйджа приложения на скриншотах"; + +"Settings.NY.Header" = "НОВОГОДНИЕ ЭФФЕКТЫ"; +"Settings.NY.Style" = "Стиль"; +"Settings.NY.Style.default" = "Выключено"; +"Settings.NY.Style.snow" = "Снег"; +"Settings.NY.Style.lightning" = "Молнии"; +"Settings.NY.Notice" = "Доступны только на ограниченное время!"; diff --git a/Swiftgram/SGStrings/Strings/si.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/si.lproj/SGLocalizable.strings new file mode 100644 index 00000000..869c70ba --- /dev/null +++ b/Swiftgram/SGStrings/Strings/si.lproj/SGLocalizable.strings @@ -0,0 +1,2 @@ +"Settings.Tabs.Header" = "පටිති"; +"ContextMenu.SaveToCloud" = "මේඝයට සුරකින්න"; diff --git a/Swiftgram/SGStrings/Strings/sk.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/sk.lproj/SGLocalizable.strings new file mode 100644 index 00000000..77376339 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/sk.lproj/SGLocalizable.strings @@ -0,0 +1,4 @@ +"Settings.Tabs.Header" = "ZÁLOŽKY"; +"Settings.Tabs.ShowContacts" = "Zobraziť kontakty"; +"Settings.Tabs.ShowNames" = "Zobraziť názvy záložiek"; +"ContextMenu.SaveToCloud" = "Uložiť na Cloud"; diff --git a/Swiftgram/SGStrings/Strings/sr.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/sr.lproj/SGLocalizable.strings new file mode 100644 index 00000000..c71efa9f --- /dev/null +++ b/Swiftgram/SGStrings/Strings/sr.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Подешавања садржаја"; + +"Settings.Tabs.Header" = "ТАБОВИ"; +"Settings.Tabs.HideTabBar" = "Сакриј Таб бар"; +"Settings.Tabs.ShowContacts" = "Прикажи таб Контакти"; +"Settings.Tabs.ShowNames" = "Прикажи имена табова"; + +"Settings.Folders.BottomTab" = "Фасцикле у дну"; +"Settings.Folders.BottomTabStyle" = "Стил фасцикли у дну"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Телеграм"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Сакриј \"%@\""; +"Settings.Folders.RememberLast" = "Отвори последњу фасциклу"; +"Settings.Folders.RememberLast.Notice" = "Свифтграм ће отворити последње коришћену фасциклу када поново покренете апликацију или измените налоге."; + +"Settings.Folders.CompactNames" = "Мањи размак"; +"Settings.Folders.AllChatsTitle" = "Наслов \"Сви Четови\""; +"Settings.Folders.AllChatsTitle.short" = "Кратко"; +"Settings.Folders.AllChatsTitle.long" = "Дуго"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Подразумевано"; + + +"Settings.ChatList.Header" = "ЛИСТА ЧЕТОВА"; +"Settings.CompactChatList" = "Компактна листа чета"; + +"Settings.Profiles.Header" = "ПРОФИЛИ"; + +"Settings.Stories.Hide" = "Сакриј приче"; +"Settings.Stories.WarnBeforeView" = "Питај пре прегледања"; +"Settings.Stories.DisableSwipeToRecord" = "Онемогући превлачење за снимање"; + +"Settings.Translation.QuickTranslateButton" = "Дугме за брзо превођење"; + +"Stories.Warning.Author" = "Аутор"; +"Stories.Warning.ViewStory" = "Погледај причу?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ ЋЕ ВИДЕТИ да сте видели њихову причу."; +"Stories.Warning.NoticeStealth" = "%@ неће моћи видети да сте видели њихову причу."; + +"Settings.Photo.Quality.Notice" = "Квалитет постављених фотографија и приказа."; +"Settings.Photo.SendLarge" = "Пошаљи велике фотографије"; +"Settings.Photo.SendLarge.Notice" = "Повећај лимит величине за компресоване слике на 2560пкс."; + +"Settings.VideoNotes.Header" = "КРУГ ВИДЕО"; +"Settings.VideoNotes.StartWithRearCam" = "Почни са задњом камером"; + +"Settings.CustomColors.Header" = "БОЈЕ НАЛОГА"; +"Settings.CustomColors.Saturation" = "ЗАСИЋЕЊЕ"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Поставите на 0%% да онемогућите боје налога."; + +"Settings.UploadsBoost" = "Појачај поставке поставки"; +"Settings.DownloadsBoost" = "Преузми појачање"; +"Settings.DownloadsBoost.Notice" = "Увећава број паралелних веза и величину делова фајлова. Уколико ваша мрежа не може да поднесе оптерећење, испробајте различите опције које одговарају вашој вези."; +"Settings.DownloadsBoost.none" = "Онемогућено"; +"Settings.DownloadsBoost.medium" = "Средње"; +"Settings.DownloadsBoost.maximum" = "Максимално"; + +"Settings.ShowProfileID" = "Прикажи идентификациони број профила"; +"Settings.ShowDC" = "Прикажи центар података"; +"Settings.ShowCreationDate" = "Прикажи датум креирања чата"; +"Settings.ShowCreationDate.Notice" = "Можда није познат датум креирања за неке разговоре."; + +"Settings.ShowRegDate" = "Прикажи датум регистрације"; +"Settings.ShowRegDate.Notice" = "Датум регистрације је приближан."; + +"Settings.SendWithReturnKey" = "Пошаљи са 'повратак' тастером"; +"Settings.HidePhoneInSettingsUI" = "Сакриј телефон у поставкама"; +"Settings.HidePhoneInSettingsUI.Notice" = "Ово само ће скрити ваш број телефона из интерфејса поставки. Да бисте га скрили од других, идите на Приватност и безбедност."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Ако је одсутан 5 секунди"; + +"ProxySettings.UseSystemDNS" = "Користи системски DNS"; +"ProxySettings.UseSystemDNS.Notice" = "Користи системски DNS да заобиђеш временски лимит ако немаш приступ Google DNS-у"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Не треба вам **%@**!"; +"Common.RestartRequired" = "Потребно поновно покретање"; +"Common.RestartNow" = "Поново покрени сада"; +"Common.OpenTelegram" = "Отвори Телеграм"; +"Common.UseTelegramForPremium" = "Обратите пажњу да бисте добили Телеграм Премијум, морате користити официјалну Телеграм апликацију. Након што стечете Телеграм Премијум, све његове функције ће бити доступне у Свифтграму."; + +"Message.HoldToShowOrReport" = "Држи да би показао или пријавио."; + +"Auth.AccountBackupReminder" = "Обезбеди да имаш методу приступа за резерву. Задржи СИМ за СМС или додатну сесију пријављену да избегнеш блокирање."; +"Auth.UnofficialAppCodeTitle" = "Код можете добити само са званичном апликацијом"; + +"Settings.SmallReactions" = "Мале реакције"; +"Settings.HideReactions" = "Сакриј реакције"; + +"ContextMenu.SaveToCloud" = "Сачувај у облак"; +"ContextMenu.SelectFromUser" = "Изабери од аутора"; + +"Settings.ContextMenu" = "КОНТЕКСТ МЕНИ"; +"Settings.ContextMenu.Notice" = "Онемогућени уноси ће бити доступни у 'Swiftgram' подменују."; + + +"Settings.ChatSwipeOptions" = "Опције превлачења списка разговора"; +"Settings.DeleteChatSwipeOption" = "Превучите за брисање чет"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Повуци на следећи непрочитан канал"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Повуци на следећу тему"; +"Settings.GalleryCamera" = "Камера у галерији"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" Дугме"; +"Settings.SnapDeletionEffect" = "Ефекти брисања поруке"; + +"Settings.Stickers.Size" = "ВЕЛИЧИНА"; +"Settings.Stickers.Timestamp" = "Прикажи временски линку"; + +"Settings.RecordingButton" = "Дугме за гласовно снимање"; + +"Settings.DefaultEmojisFirst" = "Приоритизовати стандардне емотиконе"; +"Settings.DefaultEmojisFirst.Notice" = "Прикажи стандардне емотиконе пре премијумских на тастатури емотикона"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "креирано: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Придружен: %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Регистрован"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Двоструки додир за уређивање поруке"; + +"Settings.wideChannelPosts" = "Широки постови у каналима"; +"Settings.ForceEmojiTab" = "Емоџи тастатура по подразумеваној подешавања"; + +"Settings.forceBuiltInMic" = "Наметни микрофон уређаја"; +"Settings.forceBuiltInMic.Notice" = "Ако је омогућено, апликација ће користити само микрофон уређаја чак и ако су прикључене слушалице."; + +"Settings.hideChannelBottomButton" = "Сакриј донји панел канала"; + +"Settings.CallConfirmation" = "Потврда позива"; +"Settings.CallConfirmation.Notice" = "Swiftgram ће затражити вашу потврду пре него што направи позив."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Направити позив?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Направити видео позив?"; + +"MutualContact.Label" = "заједнички контакт"; + +"Settings.swipeForVideoPIP" = "Видео PIP са свлачење"; +"Settings.swipeForVideoPIP.Notice" = "Ако је омогућено, померање видеа ће га отворити у режиму слике у слици."; diff --git a/Swiftgram/SGStrings/Strings/sv.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/sv.lproj/SGLocalizable.strings new file mode 100644 index 00000000..de9ed082 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/sv.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Innehållsinställningar"; + +"Settings.Tabs.Header" = "Flikar"; +"Settings.Tabs.HideTabBar" = "Dölj flikfält"; +"Settings.Tabs.ShowContacts" = "Visa Kontakter-flik"; +"Settings.Tabs.ShowNames" = "Show Tab Names"; + +"Settings.Folders.BottomTab" = "Mappar längst ner"; +"Settings.Folders.BottomTabStyle" = "Stil på nedre mappar"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Dölj \"%@\""; +"Settings.Folders.RememberLast" = "Öppna senaste mapp"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram öppnar den senast använda mappen när du startar om appen eller byter konton."; + +"Settings.Folders.CompactNames" = "Mindre avstånd"; +"Settings.Folders.AllChatsTitle" = "\"Alla chattar\" titel"; +"Settings.Folders.AllChatsTitle.short" = "Kort"; +"Settings.Folders.AllChatsTitle.long" = "Lång"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Standard"; + + +"Settings.ChatList.Header" = "CHATT LISTA"; +"Settings.CompactChatList" = "Kompakt chattlista"; + +"Settings.Profiles.Header" = "PROFILES"; + +"Settings.Stories.Hide" = "Dölj Berättelser"; +"Settings.Stories.WarnBeforeView" = "Fråga innan du tittar"; +"Settings.Stories.DisableSwipeToRecord" = "Inaktivera svep för att spela in"; + +"Settings.Translation.QuickTranslateButton" = "Snabböversättningsknapp"; + +"Stories.Warning.Author" = "Författare"; +"Stories.Warning.ViewStory" = "Visa Berättelse?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ KOMMER ATT SE att du har sett deras Berättelse."; +"Stories.Warning.NoticeStealth" = "%@ kommer inte att se att du har sett deras Berättelse."; + +"Settings.Photo.Quality.Notice" = "Kvaliteten på uppladdade bilder och berättelser."; +"Settings.Photo.SendLarge" = "Skicka stora foton"; +"Settings.Photo.SendLarge.Notice" = "Öka sidogränsen för komprimerade bilder till 2560px."; + +"Settings.VideoNotes.Header" = "RUND VIDEO"; +"Settings.VideoNotes.StartWithRearCam" = "Börja med bakre kamera"; + +"Settings.CustomColors.Header" = "KONTOFÄRGER"; +"Settings.CustomColors.Saturation" = "MÄTTNING"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Sätt till 0%% för att inaktivera kontofärger."; + +"Settings.UploadsBoost" = "Uppladdningshastighet"; +"Settings.DownloadsBoost" = "Ladda ner Boost"; +"Settings.DownloadsBoost.Notice" = "Ökar antalet parallella anslutningar och storleken på filbitar. Om ditt nätverk inte kan hantera belastningen, prova olika alternativ som passar din anslutning."; +"Settings.DownloadsBoost.none" = "Inaktiverad"; +"Settings.DownloadsBoost.medium" = "Medium"; +"Settings.DownloadsBoost.maximum" = "Maximal"; + +"Settings.ShowProfileID" = "Visa profil-ID"; +"Settings.ShowDC" = "Visa datacenter"; +"Settings.ShowCreationDate" = "Visa datum för att skapa chatt"; +"Settings.ShowCreationDate.Notice" = "Skapandedatumet kan vara okänt för vissa chattar."; + +"Settings.ShowRegDate" = "Visa registreringsdatum"; +"Settings.ShowRegDate.Notice" = "Registreringsdatumet är ungefärligt."; + +"Settings.SendWithReturnKey" = "Skicka med 'retur'-tangenten"; +"Settings.HidePhoneInSettingsUI" = "Dölj telefon i inställningar"; +"Settings.HidePhoneInSettingsUI.Notice" = "Detta döljer endast ditt telefonnummer från inställningsgränssnittet. För att dölja det från andra, gå till Sekretess och säkerhet."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Om borta i 5 sekunder"; + +"ProxySettings.UseSystemDNS" = "Använd system-DNS"; +"ProxySettings.UseSystemDNS.Notice" = "Använd system-DNS för att kringgå timeout om du inte har tillgång till Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Du **behöver inte** %@!"; +"Common.RestartRequired" = "Omstart krävs"; +"Common.RestartNow" = "Starta om Nu"; +"Common.OpenTelegram" = "Öppna Telegram"; +"Common.UseTelegramForPremium" = "Observera att för att få Telegram Premium måste du använda den officiella Telegram-appen. När du har fått Telegram Premium, kommer alla dess funktioner att bli tillgängliga i Swiftgram."; + +"Message.HoldToShowOrReport" = "Håll in för att Visa eller Rapportera."; + +"Auth.AccountBackupReminder" = "Se till att du har en backup-åtkomstmetod. Behåll ett SIM för SMS eller en extra session inloggad för att undvika att bli utelåst."; +"Auth.UnofficialAppCodeTitle" = "Du kan endast få koden med den officiella appen"; + +"Settings.SmallReactions" = "Små reaktioner"; +"Settings.HideReactions" = "Dölj Reaktioner"; + +"ContextMenu.SaveToCloud" = "Spara till Molnet"; +"ContextMenu.SelectFromUser" = "Välj från Författaren"; + +"Settings.ContextMenu" = "KONTEXTMENY"; +"Settings.ContextMenu.Notice" = "Inaktiverade poster kommer att vara tillgängliga i 'Swiftgram'-undermenyn."; + + +"Settings.ChatSwipeOptions" = "Svepalternativ för chattlistan"; +"Settings.DeleteChatSwipeOption" = "Svep för att ta bort chatt"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Dra till nästa olästa kanal"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Dra till Nästa Ämne"; +"Settings.GalleryCamera" = "Kamera i galleriet"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" Knapp"; +"Settings.SnapDeletionEffect" = "Effekter på meddelandet"; + +"Settings.Stickers.Size" = "SIZE"; +"Settings.Stickers.Timestamp" = "Visa tidsstämpel"; + +"Settings.RecordingButton" = "Röstinspelningsknapp"; + +"Settings.DefaultEmojisFirst" = "Prioritera standardemojis"; +"Settings.DefaultEmojisFirst.Notice" = "Visa standardemojis innan premium i emoji-tangentbordet"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "skapad: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Gick med %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Registrerad"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Dubbeltryck för att redigera meddelandet"; + +"Settings.wideChannelPosts" = "Bredda inlägg i kanaler"; +"Settings.ForceEmojiTab" = "Emoji-tangentbord som standard"; + +"Settings.forceBuiltInMic" = "Tvinga enhetsmikrofonen"; +"Settings.forceBuiltInMic.Notice" = "Om aktiverat, kommer appen endast använda enhetens mikrofon även om hörlurar är anslutna."; + +"Settings.hideChannelBottomButton" = "Dölj kanalle bottenpanel"; + +"Settings.CallConfirmation" = "Samtalsbekräftelse"; +"Settings.CallConfirmation.Notice" = "Swiftgram kommer att be om din bekräftelse innan ett samtal görs."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Vill du ringa ett samtal?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Vill du göra ett videosamtal?"; + +"MutualContact.Label" = "ömsesidig kontakt"; + +"Settings.swipeForVideoPIP" = "Video PIP med svep"; +"Settings.swipeForVideoPIP.Notice" = "Om aktiverat, kommer svepning av video att öppna det i bild-i-bild-läge."; diff --git a/Swiftgram/SGStrings/Strings/tr.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/tr.lproj/SGLocalizable.strings new file mode 100644 index 00000000..7f1b643e --- /dev/null +++ b/Swiftgram/SGStrings/Strings/tr.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "İçerik Ayarları"; + +"Settings.Tabs.Header" = "SEKMELER"; +"Settings.Tabs.HideTabBar" = "Sekme çubuğunu gizle"; +"Settings.Tabs.ShowContacts" = "Kişiler Sekmesini Göster"; +"Settings.Tabs.ShowNames" = "Sekme isimlerini göster"; + +"Settings.Folders.BottomTab" = "Altta klasörler"; +"Settings.Folders.BottomTabStyle" = "Alt klasör stili"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "\"%@\" Gizle"; +"Settings.Folders.RememberLast" = "Son klasörü aç"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram, yeniden başlatıldıktan ya da hesap değişiminden sonra son kullanılan klasörü açacaktır"; + +"Settings.Folders.CompactNames" = "Daha küçük aralık"; +"Settings.Folders.AllChatsTitle" = "\"Tüm Sohbetler\" başlığı"; +"Settings.Folders.AllChatsTitle.short" = "Kısa"; +"Settings.Folders.AllChatsTitle.long" = "Uzun"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Varsayılan"; + + +"Settings.ChatList.Header" = "SOHBET LİSTESİ"; +"Settings.CompactChatList" = "Kompakt Sohbet Listesi"; + +"Settings.Profiles.Header" = "PROFİLLER"; + +"Settings.Stories.Hide" = "Hikayeleri Gizle"; +"Settings.Stories.WarnBeforeView" = "Görüntülemeden önce sor"; +"Settings.Stories.DisableSwipeToRecord" = "Kaydetmek için kaydırmayı devre dışı bırak"; + +"Settings.Translation.QuickTranslateButton" = "Hızlı Çeviri butonu"; + +"Stories.Warning.Author" = "Yazar"; +"Stories.Warning.ViewStory" = "Hikayeyi Görüntüle?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@, Hikayesini görüntülediğinizi GÖREBİLECEK."; +"Stories.Warning.NoticeStealth" = "%@, hikayesini görüntülediğinizi göremeyecek."; + +"Settings.Photo.Quality.Notice" = "Gönderilen fotoğrafların ve foto-hikayelerin kalitesi"; +"Settings.Photo.SendLarge" = "Büyük fotoğraflar gönder"; +"Settings.Photo.SendLarge.Notice" = "Sıkıştırılmış resimlerdeki kenar sınırını 2560 piksele çıkar"; + +"Settings.VideoNotes.Header" = "YUVARLAK VİDEOLAR"; +"Settings.VideoNotes.StartWithRearCam" = "Arka kamerayla başlat"; + +"Settings.CustomColors.Header" = "HESAP RENKLERİ"; +"Settings.CustomColors.Saturation" = "DOYUM"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Hesap renklerini devre dışı bırakmak için doyumu 0%%'a ayarlayın"; + +"Settings.UploadsBoost" = "Karşıya yüklemeleri hızlandır"; +"Settings.DownloadsBoost" = "İndirmeleri hızlandır"; +"Settings.DownloadsBoost.Notice" = "Paralel bağlantıların sayısını ve dosya parçalarının boyutunu artırır. Ağa yük bindiğinde eağa diğer bağlantı seçeneklerini deneyin."; +"Settings.DownloadsBoost.none" = "Devre dışı"; +"Settings.DownloadsBoost.medium" = "Orta"; +"Settings.DownloadsBoost.maximum" = "En fazla"; + +"Settings.ShowProfileID" = "Profil ID'sini Göster"; +"Settings.ShowDC" = "Veri Merkezini Göster"; +"Settings.ShowCreationDate" = "Sohbet Oluşturma Tarihini Göster"; +"Settings.ShowCreationDate.Notice" = "Bazı sohbetler için oluşturma tarihi bilinmeyebilir."; + +"Settings.ShowRegDate" = "Kaydolma Tarihini Göster"; +"Settings.ShowRegDate.Notice" = "Kaydolma tarihi yaklaşık olarak belirtilmiştir."; + +"Settings.SendWithReturnKey" = "\"enter\" tuşu ile gönder"; +"Settings.HidePhoneInSettingsUI" = "Ayarlarda numarayı gizle"; +"Settings.HidePhoneInSettingsUI.Notice" = "Numaranız sadece arayüzde gizlenecek. Diğerlerinden gizlemek için, lütfen Gizlilik ayarlarını kullanın."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "5 saniye uzakta kalırsanız"; + +"ProxySettings.UseSystemDNS" = "Sistem DNS'sini kullan"; +"ProxySettings.UseSystemDNS.Notice" = "Google DNS'ye erişiminiz yoksa, zaman aşımını aşmak için sistem DNS'sini kullanın"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "%@ **gerekmez**!"; +"Common.RestartRequired" = "Yeniden başlatma gerekli"; +"Common.RestartNow" = "Şimdi Yeniden Başlat"; +"Common.OpenTelegram" = "Telegram'ı Aç"; +"Common.UseTelegramForPremium" = "Unutmayın ki Telegram Premium'u edinmek için resmî Telegram uygulamasını kullanmanız gerekmektedir. Telegram Premium sahibi olduktan sonra onun tüm özellikleri Swiftgram'da mevcut olacaktır."; + +"Message.HoldToShowOrReport" = "Göstermek veya Bildirmek için Basılı Tutun."; + +"Auth.AccountBackupReminder" = "Yedek erişim yönteminiz olduğundan emin olun. Kilitlenmeden kaçınmak için bir SIM kartı saklayın veya ek bir oturum açın."; +"Auth.UnofficialAppCodeTitle" = "Kodu yalnızca resmi uygulamadan edinebilirsiniz"; + +"Settings.SmallReactions" = "Küçük tepkiler"; +"Settings.HideReactions" = "Tepkileri Gizle"; + +"ContextMenu.SaveToCloud" = "Buluta Kaydet"; +"ContextMenu.SelectFromUser" = "Yazardan Seç"; + +"Settings.ContextMenu" = "BAĞLAM MENÜSÜ"; +"Settings.ContextMenu.Notice" = "Devre dışı bırakılmış girişler \"Swiftgram\" alt menüsünde mevcut olacaktır."; + + +"Settings.ChatSwipeOptions" = "Sohbet listesi kaydırma seçenekleri"; +"Settings.DeleteChatSwipeOption" = "Sohbete Silmek İçin Kaydırın"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Sonraki okunmamış kanal için çekin"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Bir Sonraki Konuya Çek"; +"Settings.GalleryCamera" = "Galeride kamera"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" butonu"; +"Settings.SnapDeletionEffect" = "Mesaj silme efektleri"; + +"Settings.Stickers.Size" = "BOYUT"; +"Settings.Stickers.Timestamp" = "Zaman Damgasını Göster"; + +"Settings.RecordingButton" = "Ses Kaydı Düğmesi"; + +"Settings.DefaultEmojisFirst" = "Standart emojileri önceliklendirin"; +"Settings.DefaultEmojisFirst.Notice" = "Emoji klavyesinde premiumdan önce standart emojileri göster"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "oluşturuldu: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Katıldı: %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Kayıtlı"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Mesajı düzenlemek için çift dokunun"; + +"Settings.wideChannelPosts" = "Kanallardaki geniş gönderiler"; +"Settings.ForceEmojiTab" = "Varsayılan olarak Emoji klavyesi"; + +"Settings.forceBuiltInMic" = "Cihaz Mikrofonunu Zorla"; +"Settings.forceBuiltInMic.Notice" = "Etkinleştirildiğinde, uygulama kulaklıklar bağlı olsa bile sadece cihaz mikrofonunu kullanacaktır."; + +"Settings.hideChannelBottomButton" = "Kanal Alt Panelini Gizle"; + +"Settings.CallConfirmation" = "Arama Onayı"; +"Settings.CallConfirmation.Notice" = "Swiftgram, arama yapmadan önce onayınızı isteyecek."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Arama Yapmak mı?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Video Araması Yapmak mı?"; + +"MutualContact.Label" = "karşılıklı iletişim"; + +"Settings.swipeForVideoPIP" = "Videoyu kaydırarak PIP"; +"Settings.swipeForVideoPIP.Notice" = "Eğer etkinleştirildi ise videoyu kaydırmak, Piksel içinde Piksel modunda açılacaktır."; diff --git a/Swiftgram/SGStrings/Strings/uk.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/uk.lproj/SGLocalizable.strings new file mode 100644 index 00000000..405fcfb8 --- /dev/null +++ b/Swiftgram/SGStrings/Strings/uk.lproj/SGLocalizable.strings @@ -0,0 +1,245 @@ +"Settings.ContentSettings" = "Налаштування контенту"; + +"Settings.Tabs.Header" = "ВКЛАДКИ"; +"Settings.Tabs.HideTabBar" = "Приховати панель вкладок"; +"Settings.Tabs.ShowContacts" = "Вкладка \"Контакти\""; +"Settings.Tabs.ShowNames" = "Показувати назви вкладок"; + +"Settings.Folders.BottomTab" = "Папки знизу"; +"Settings.Folders.BottomTabStyle" = "Стиль нижніх папок"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Приховати \"%@\""; +"Settings.Folders.RememberLast" = "Відкривати останню папку"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram відкриє останню папку після перезапуску застосунку або зміни акаунту."; + +"Settings.Folders.CompactNames" = "Зменшити відступи"; +"Settings.Folders.AllChatsTitle" = "Заголовок \"Усі чати\""; +"Settings.Folders.AllChatsTitle.short" = "Короткий"; +"Settings.Folders.AllChatsTitle.long" = "Довгий"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Типовий"; + + +"Settings.ChatList.Header" = "СПИСОК ЧАТІВ"; +"Settings.CompactChatList" = "Компактний список чатів"; + +"Settings.Profiles.Header" = "ПРОФІЛІ"; + +"Settings.Stories.Hide" = "Приховувати історії"; +"Settings.Stories.WarnBeforeView" = "Питати перед переглядом"; +"Settings.Stories.DisableSwipeToRecord" = "Вимкнути \"Свайп для запису\""; + +"Settings.Translation.QuickTranslateButton" = "Кнопка швидкого перекладу"; + +"Stories.Warning.Author" = "Автор"; +"Stories.Warning.ViewStory" = "Переглянути історію?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ ЗМОЖЕ ПОБАЧИТИ, що ви переглянули їх історію."; +"Stories.Warning.NoticeStealth" = "%@ не побачить, що ви переглянули їх історію."; + +"Settings.Photo.Quality.Notice" = "Якість відправлених фото та історій"; +"Settings.Photo.SendLarge" = "Надсилати великі фотографії"; +"Settings.Photo.SendLarge.Notice" = "Збільшити ліміт розміру стиснутих зображень до 2560px"; + +"Settings.VideoNotes.Header" = "КРУГЛІ ВІДЕО"; +"Settings.VideoNotes.StartWithRearCam" = "Починати запис з задньої камери"; + +"Settings.CustomColors.Header" = "КОЛЬОРИ АККАУНТУ"; +"Settings.CustomColors.Saturation" = "НАСИЧЕНІСТЬ"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Встановіть насиченість на 0%%, щоб вимкнути персональні кольори"; + +"Settings.UploadsBoost" = "Прискорення вивантаження"; +"Settings.DownloadsBoost" = "Прискорення завантаження"; +"Settings.DownloadsBoost.Notice" = "Збільшує кількість паралельних з'єднань та розмір частин файлів. Якщо ваша мережа не може витримати навантаження, спробуйте різні опції, які підходять вашому з'єднанню."; +"Settings.DownloadsBoost.none" = "Відключено"; +"Settings.DownloadsBoost.medium" = "Середнє"; +"Settings.DownloadsBoost.maximum" = "Максимальне"; + +"Settings.ShowProfileID" = "Показувати ID профілю"; +"Settings.ShowDC" = "Показувати дата-центр"; +"Settings.ShowCreationDate" = "Показувати дату створення чату"; +"Settings.ShowCreationDate.Notice" = "Дата створення може бути невідома для деяких чатів."; + +"Settings.ShowRegDate" = "Показувати дату реєстрації"; +"Settings.ShowRegDate.Notice" = "Дата реєстрації є приблизною."; + +"Settings.SendWithReturnKey" = "Надсилати кнопкою \"Введення\""; +"Settings.HidePhoneInSettingsUI" = "Приховати телефон у налаштуваннях"; +"Settings.HidePhoneInSettingsUI.Notice" = "Номер буде прихований тільки в налаштуваннях. Перейдіть в \"Приватність і безпека\", щоб приховати його від інших."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "За 5 сек"; + +"ProxySettings.UseSystemDNS" = "Використовувати системні налаштування DNS"; +"ProxySettings.UseSystemDNS.Notice" = "Використовувати системний DNS для обходу тайм-ауту, якщо у вас немає доступу до Google DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Вам **не потрібен** %@!"; +"Common.RestartRequired" = "Потрібен перезапуск"; +"Common.RestartNow" = "Перезавантажити"; +"Common.OpenTelegram" = "Відкрити Telegram"; +"Common.UseTelegramForPremium" = "Зверніть увагу, що для отримання Telegram Premium вам потрібен офіційний застосунок Telegram. Після отримання Telegram Premium, усі переваги стануть доступними у Swiftgram."; +"Common.UpdateOS" = "Необхідне оновлення iOS"; + +"Message.HoldToShowOrReport" = "Затисніть, щоб переглянути або поскаржитись."; + +"Auth.AccountBackupReminder" = "Переконайтеся, що у вас є резервний метод доступу. Тримайте SIM-карту для SMS або додаткову сесію, щоб не втратити доступ до акаунту."; +"Auth.UnofficialAppCodeTitle" = "Ви можете отримати код тільки з офіційним додатком"; + +"Settings.SmallReactions" = "Малі реакції"; +"Settings.HideReactions" = "Приховувати реакції"; + +"ContextMenu.SaveToCloud" = "Переслати в Збережене"; +"ContextMenu.SelectFromUser" = "Вибрати від автора"; + +"Settings.ContextMenu" = "КОНТЕКСТНЕ МЕНЮ"; +"Settings.ContextMenu.Notice" = "Вимкнені елементи будуть доступні в підменю \"Swiftgram\"."; + + +"Settings.ChatSwipeOptions" = "Опції свайпу у списку чатів"; +"Settings.DeleteChatSwipeOption" = "Потягнути для видалення чату"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Потягнути до наступного каналу"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Потягнути до наступної гілки"; +"Settings.GalleryCamera" = "Камера в галереї"; +"Settings.GalleryCameraPreview" = "Попередній перегляд камери в галереї"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "Кнопка \"%@\""; +"Settings.SnapDeletionEffect" = "Ефекти видалення повідомлення"; + +"Settings.Stickers.Size" = "РОЗМІР"; +"Settings.Stickers.Timestamp" = "Показувати час"; + +"Settings.RecordingButton" = "Кнопка запису голосу"; + +"Settings.DefaultEmojisFirst" = "Пріоритизувати звичайні емодзі"; +"Settings.DefaultEmojisFirst.Notice" = "Показувати звичайні емодзі перед преміум у клавіатурі емодзі"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "створено: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Приєднався до %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Реєстрація"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Ред. повідомлення подвійним дотиком"; + +"Settings.wideChannelPosts" = "Широкі пости в каналах"; +"Settings.ForceEmojiTab" = "Клавіатура емодзі за замовчуванням"; + +"Settings.forceBuiltInMic" = "Використовувати мікрофон пристрою"; +"Settings.forceBuiltInMic.Notice" = "Якщо увімкнено, застосунок використовуватиме лише мікрофон пристрою, навіть якщо підключені навушники."; + +"Settings.showChannelBottomButton" = "Нижня панель у каналах"; + +"Settings.secondsInMessages" = "Секунди в повідомленнях"; + +"Settings.CallConfirmation" = "Підтвердження викликів"; +"Settings.CallConfirmation.Notice" = "Swiftgram запитуватиме дозвіл перед здійсненням виклику."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Здійснити виклик?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Здійснити відеовиклик?"; + +"MutualContact.Label" = "взаємний контакт"; + +"Settings.swipeForVideoPIP" = "Відео PIP зі змахуванням"; +"Settings.swipeForVideoPIP.Notice" = "Якщо увімкнено, змахування відео відкриє його в режимі «Картинка в картинці»."; + +"SessionBackup.Title" = "Резервне копіювання сесії"; +"SessionBackup.Sessions.Title" = "Сесії"; +"SessionBackup.Actions.Backup" = "Резервне копіювання в Keychain"; +"SessionBackup.Actions.Restore" = "Відновлення з Keychain"; +"SessionBackup.Actions.DeleteAll" = "Видалити резервну копію Keychain"; +"SessionBackup.Actions.DeleteOne" = "Видалити з резервної копії"; +"SessionBackup.Actions.RemoveFromApp" = "Видалити з додатку"; +"SessionBackup.LastBackupAt" = "Останнє резервне копіювання: %@"; +"SessionBackup.RestoreOK" = "ОК. Сесії відновлено: %@"; +"SessionBackup.LoggedIn" = "Увійшли"; +"SessionBackup.LoggedOut" = "Вийшли"; +"SessionBackup.DeleteAll.Title" = "Видалити всі сесії?"; +"SessionBackup.DeleteAll.Text" = "Всі сесії будуть видалені з Keychain.\n\nОблікові записи не будуть вийшли зі Swiftgram."; +"SessionBackup.DeleteSingle.Title" = "Видалити 1 (одну) сесію?"; +"SessionBackup.DeleteSingle.Text" = "%@ сесія буде видалена з Keychain.\n\nОбліковий запис не буде вийшов зі Swiftgram."; +"SessionBackup.RemoveFromApp.Title" = "Видалити обліковий запис з додатку?"; +"SessionBackup.RemoveFromApp.Text" = "%@ сесія БУДЕ ВИДАЛЕНА з Swiftgram! Сесія залишиться активною, щоб ви могли відновити її пізніше."; +"SessionBackup.Notice" = "Сесії зашифровані та зберігаються на пристрої. Сесії ніколи не залишають ваш пристрій.\n\nВАЖЛИВО: Для відновлення сесій на іншому пристрої або після скидання налаштувань, ви повинні ввімкнути шифрування резервних копій, в іншому випадку ключі не будуть перенесені.\n\nТАКОЖ: Сесії можуть бути відкликані Telegram або з іншого пристрою."; + +"MessageFilter.Title" = "Фільтр повідомлень"; +"MessageFilter.SubTitle" = "Приховати відволікання та зменшити видимість повідомлень, що містять нижчевказані ключові слова.\nКлючові слова чутливі до регістру."; +"MessageFilter.Keywords.Title" = "Ключові слова"; +"MessageFilter.InputPlaceholder" = "Введіть ключове слово"; + +"InputToolbar.Title" = "Панель форматування"; + +"Notifications.MentionsAndReplies.Title" = "@Згадай та відповіді"; +"Notifications.MentionsAndReplies.value.default" = "Типовий"; +"Notifications.MentionsAndReplies.value.silenced" = "Приглушено"; +"Notifications.MentionsAndReplies.value.disabled" = "Відключено"; +"Notifications.PinnedMessages.Title" = "Закріплені повідомлення"; +"Notifications.PinnedMessages.value.default" = "Типовий"; +"Notifications.PinnedMessages.value.silenced" = "Приглушено"; +"Notifications.PinnedMessages.value.disabled" = "Відключено"; + + +"PayWall.Text" = "Посилений функціями Pro"; + +"PayWall.SessionBackup.Title" = "Резервне копіювання сесії"; +"PayWall.SessionBackup.Notice" = "Вхід до облікових записів без коду, навіть після перевстановлення. Безпечне сховище з Ключарем пристрою."; +"PayWall.SessionBackup.Description" = "Зміна пристрою або видалення Swiftgram більше не проблема. Відновити всі сеанси, які досі активні на серверах Telegram."; + +"PayWall.MessageFilter.Title" = "Фільтр повідомлень"; +"PayWall.MessageFilter.Notice" = "Зменшити видимість СПАМу, реклам та набридливих повідомлень."; +"PayWall.MessageFilter.Description" = "Створити список ключових слів, які ви не хочете бачити часто, а Swiftgram зменшить відволікання."; + +"PayWall.Notifications.Title" = "Вимкнути @згадки та відповіді"; +"PayWall.Notifications.Notice" = "Сховати або приглушити непотрібні сповіщення."; +"PayWall.Notifications.Description" = "Більше не потрібно використовувати прикріплені повідомлення або @згадки, коли ви потребуєте розуму."; + +"PayWall.InputToolbar.Title" = "Панель форматування"; +"PayWall.InputToolbar.Notice" = "Зберігати час форматування повідомлень одним дотиком."; +"PayWall.InputToolbar.Description" = "Застосувати і очистити форматування або вставити нові лінії, як Pro."; + +"PayWall.AppIcons.Title" = "Унікальні значки додатків"; +"PayWall.AppIcons.Notice" = "Налаштуйте вигляд Swiftgram на вашому домашньому екрані."; + +"PayWall.About.Title" = "Про Swiftgram Pro"; +"PayWall.About.Notice" = "Безкоштовна версія Swiftgram надає десятки функцій та покращень у порівнянні з додатком Telegram. Інновації та підтримка Swiftgram в актуальному стані з місячними оновленнями Telegram потребує величезних зусиль, що вимагають багато часу та дорогого обладнання.\n\nSwiftgram — це додаток з відкритим кодом, який поважає вашу конфіденційність і не турбує вас рекламою. Підписуючись на Swiftgram Pro, ви отримуєте доступ до ексклюзивних функцій і підтримуєте незалежного розробника.\n\n- @Kylmakalle"; +/* DO NOT TRANSLATE */ +"PayWall.About.Signature" = "@Kylmakalle"; +/* DO NOT TRANSLATE */ +"PayWall.About.SignatureURL" = "https://t.me/Kylmakalle"; + +"PayWall.ProSupport.Title" = "Проблеми з оплатою?"; +"PayWall.ProSupport.Contact" = "Не хвилюйтеся!"; + +"PayWall.RestorePurchases" = "Відновити покупки"; +"PayWall.Terms" = "Умови обслуговування"; +"PayWall.Privacy" = "Політика конфіденційності"; +"PayWall.TermsURL" = "https://swiftgram.app/terms"; +"PayWall.PrivacyURL" = "https://swiftgram.app/privacy"; +"PayWall.Notice.Markdown" = "Підписуючись на Swiftgram Pro, ви погоджуєтеся з [Умовами обслуговування Swiftgram](%1$@) та [Політикою конфіденційності](%2$@)."; +"PayWall.Notice.Raw" = "Підписуючись на Swiftgram Pro, ви погоджуєтеся з Умовами обслуговування Swiftgram та Політикою конфіденційності."; + +"PayWall.Button.OpenPro" = "Використовувати функції Pro"; +"PayWall.Button.Purchasing" = "Придбання..."; +"PayWall.Button.Restoring" = "Відновлення покупок..."; +"PayWall.Button.Validating" = "Перевірка покупки..."; +"PayWall.Button.PaymentsUnavailable" = "Платежі недоступні"; +"PayWall.Button.BuyInAppStore" = "Підписатися на версію в App Store"; +"PayWall.Button.Subscribe" = "Підписатися за %@ / місяць"; +"PayWall.Button.ContactingAppStore" = "Зв'язок з App Store..."; + +"Paywall.Error.Title" = "Помилка"; +"PayWall.ValidationError" = "Помилка валідації"; +"PayWall.ValidationError.TryAgain" = "Щось пішло не так під час перевірки покупки. Не хвилюйтеся! Спробуйте відновити покупки трохи пізніше."; +"PayWall.ValidationError.Expired" = "Ваша підписка застаріла. Підпишіться, щоб відновити доступ до Pro-можливостей."; diff --git a/Swiftgram/SGStrings/Strings/uz.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/uz.lproj/SGLocalizable.strings new file mode 100644 index 00000000..cfab47bc --- /dev/null +++ b/Swiftgram/SGStrings/Strings/uz.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Kontent sozlamalari"; + +"Settings.Tabs.Header" = "Oynalar"; +"Settings.Tabs.HideTabBar" = "Oynalarni yashirish"; +"Settings.Tabs.ShowContacts" = "Kontaktlarni oynasini ko'rsatish"; +"Settings.Tabs.ShowNames" = "Oyna nomini ko'rsatish"; + +"Settings.Folders.BottomTab" = "Qurollar pastda"; +"Settings.Folders.BottomTabStyle" = "Pastki Qurollar uslubi"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iPhone"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "\"%@\"ni yashirish"; +"Settings.Folders.RememberLast" = "Oxirgi Jildni ochish"; +"Settings.Folders.RememberLast.Notice" = "Ilovani qayta ishga tushirganingizda yoki hisoblarni almashtirganingizda Swiftgram oxirgi foydalanilgan jildni ochadi."; + +"Settings.Folders.CompactNames" = "Kichik bo'sh joy"; +"Settings.Folders.AllChatsTitle" = "\"Barcha Chatlar\" nomi"; +"Settings.Folders.AllChatsTitle.short" = "Qisqa"; +"Settings.Folders.AllChatsTitle.long" = "Uzoq"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Standart"; + + +"Settings.ChatList.Header" = "CHAT RO'YXI"; +"Settings.CompactChatList" = "Qisqa Chat Ro'yxi"; + +"Settings.Profiles.Header" = "PROFILLAR"; + +"Settings.Stories.Hide" = "Hikoyalarni yashirish"; +"Settings.Stories.WarnBeforeView" = "Ko'rishdan avval tasdiqlash"; +"Settings.Stories.DisableSwipeToRecord" = "Kayd qilishni o'chirish"; + +"Settings.Translation.QuickTranslateButton" = "Tezkor tarjima tugmasi"; + +"Stories.Warning.Author" = "Muallif"; +"Stories.Warning.ViewStory" = "Hikoyani ko'rasizmi?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ hatto siz ularning Hikoyasini ko'rganini ko'rsatishadi."; +"Stories.Warning.NoticeStealth" = "%@ ularning Hikoyasini ko'rgani ko'rsatmaydi."; + +"Settings.Photo.Quality.Notice" = "Yuklanadigan fotosuratlar va hikoyalarning sifati."; +"Settings.Photo.SendLarge" = "Katta rasmlarni yuborish"; +"Settings.Photo.SendLarge.Notice" = "Tasodifiy rasmlarni to'g'rilangan hajmini 2560px ga oshiring."; + +"Settings.VideoNotes.Header" = "Aylana video"; +"Settings.VideoNotes.StartWithRearCam" = "Orqa kamerada boshlash"; + +"Settings.CustomColors.Header" = "Hisob ranglari"; +"Settings.CustomColors.Saturation" = "SATURATSIYA"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Hisob ranglarini o'chirish uchun 0%% ga sozlang."; + +"Settings.UploadsBoost" = "Yuklashni kuchaytirish"; +"Settings.DownloadsBoost" = "Yuklab olishni kuchaytirish"; +"Settings.DownloadsBoost.Notice" = "Parallel ulanishlar sonini va fayl bo'laklari o'lchamini oshiradi. Agar sizning tarmog'ingiz yuklamani boshqarolmasa, ulanishingizga mos keladigan boshqa variantlarni sinab ko'ring."; +"Settings.DownloadsBoost.none" = "O'chirilgan"; +"Settings.DownloadsBoost.medium" = "O'rtacha"; +"Settings.DownloadsBoost.maximum" = "Maksimum"; + +"Settings.ShowProfileID" = "Profil Id'ni ko'rsatish"; +"Settings.ShowDC" = "Ma'lumotlar bazasini ko'rsatish"; +"Settings.ShowCreationDate" = "Suxbat yaratilgan sanani ko'rsatish"; +"Settings.ShowCreationDate.Notice" = "Ba'zi sahifalarning yaratilish sanasi ma'lum emas."; + +"Settings.ShowRegDate" = "Ro'yhatdan o'tish sanasini ko'rsatish"; +"Settings.ShowRegDate.Notice" = "Ro'yhatdan o'tgan sana yakunlanmagan."; + +"Settings.SendWithReturnKey" = "Enter orqali yuborish"; +"Settings.HidePhoneInSettingsUI" = "Telefonni sozlamalarda yashirish"; +"Settings.HidePhoneInSettingsUI.Notice" = "Bu faqat sozlamalardan telefon raqamingizni yashiradi. Uni boshqalar dan yashirish uchun, Farovonlik va Xavfsizlik ga o'ting."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "5 soniya uzoq bo'lsa"; + +"ProxySettings.UseSystemDNS" = "Tizim DNSni ishlat"; +"ProxySettings.UseSystemDNS.Notice" = "Agar sizda Google DNS guruhlaringiz bo'lmasa, istisnodan o'tish uchun tizim DNS ni ishlatishingiz kerak."; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Sizga %@ kerak emas!"; +"Common.RestartRequired" = "Qayta ishga tushirish lozim"; +"Common.RestartNow" = "Hozir qayta ishlash"; +"Common.OpenTelegram" = "Telegramni ochish"; +"Common.UseTelegramForPremium" = "Iltimos, Telegram Premiumni olish uchun rasmiy Telegram ilovasidan foydalaning. Telegram Premiumni olinganidan so'ng, barcha xususiyatlar Swiftgram da mavjud bo'ladi."; + +"Message.HoldToShowOrReport" = "Ko'rsatish yoki hisobga olish uchun tuting."; + +"Auth.AccountBackupReminder" = "Oldin saqlash usulini to'g'riroq o'rnatganingizni tekshiring. Alockli qilish uchun SMS uchun SIM kartni yoki qo'shimcha sessiyani tarqatib turish uchun qo'shimcha kirish usuliga kirish olib qo'ying."; +"Auth.UnofficialAppCodeTitle" = "Siz faqat rasmiy ilovadan faqat kodingizni olasiz"; + +"Settings.SmallReactions" = "Kichik Reaktsiyalar"; +"Settings.HideReactions" = "Reaksiyalarni yashirish"; + +"ContextMenu.SaveToCloud" = "Bulutga saqlash"; +"ContextMenu.SelectFromUser" = "Avtordan tanlash"; + +"Settings.ContextMenu" = "KONTEKS MENYU"; +"Settings.ContextMenu.Notice" = "O'chirilgan kirishlar \"Swiftgram\" pastki menudasiga o'tkaziladi."; + + +"Settings.ChatSwipeOptions" = "Chat Ro'yxati Sürüş variantlari"; +"Settings.DeleteChatSwipeOption" = "Sohbetni o'chirish uchun sug'urta"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Keyingi O'qilmagan Kanalga burilish"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Keyingi mavzuga torting"; +"Settings.GalleryCamera" = "Galereyadagi Kamera"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" Tugma"; +"Settings.SnapDeletionEffect" = "Xabar O'chirish O'zgartirishlari"; + +"Settings.Stickers.Size" = "OLCHAM"; +"Settings.Stickers.Timestamp" = "Vaqtni Ko'rsatish"; + +"Settings.RecordingButton" = "Ovozni Yozish Tugmasi"; + +"Settings.DefaultEmojisFirst" = "Standart emoyilarni prioritetga qo'ying"; +"Settings.DefaultEmojisFirst.Notice" = "Emojilar klaviaturasida premiumdan oldin standart alifbo emoyilarni ko'rsating"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "yaratildi: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "%@\" ga qo'shildi"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Ro'yhatga olingan"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Xabarni tahrirlash uchun ikki marta bosing"; + +"Settings.wideChannelPosts" = "Keng postlar kanallarda"; +"Settings.ForceEmojiTab" = "Emoji klaviatura sukutiga"; + +"Settings.forceBuiltInMic" = "Qurilma Mikrofonini Kuchaytirish"; +"Settings.forceBuiltInMic.Notice" = "Agar yoqilsa, ilova faqat qurilma mikrofonidan foydalanadi, hattoki naushnik bog'langan bo'lsa ham."; + +"Settings.hideChannelBottomButton" = "Kanal Pastki Panellini yashirish"; + +"Settings.CallConfirmation" = "Qo'ng'iroq tasdiqlanishi"; +"Settings.CallConfirmation.Notice" = "Swiftgram sizdan qo'ng'iroq qilishdan oldin tasdiqlashni so'raydi."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Qo'ng'iroq qilish?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Video qo'ng'iroq qilish?"; + +"MutualContact.Label" = "o'zaro aloqa"; + +"Settings.swipeForVideoPIP" = "Video PIP bilan Surish"; +"Settings.swipeForVideoPIP.Notice" = "Agar yoqilgan bo'lsa, videoni surish uni Tasvir ichida Tasvir rejimida ochadi."; diff --git a/Swiftgram/SGStrings/Strings/vi.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/vi.lproj/SGLocalizable.strings new file mode 100644 index 00000000..8878463b --- /dev/null +++ b/Swiftgram/SGStrings/Strings/vi.lproj/SGLocalizable.strings @@ -0,0 +1,152 @@ +"Settings.ContentSettings" = "Cài đặt nội dung"; + +"Settings.Tabs.Header" = "THẺ"; +"Settings.Tabs.HideTabBar" = "Ẩn thanh Tab"; +"Settings.Tabs.ShowContacts" = "Hiện Liên hệ"; +"Settings.Tabs.ShowNames" = "Hiện tên các thẻ"; + +"Settings.Folders.BottomTab" = "Đặt thư mục tin nhắn ở dưới cùng"; +"Settings.Folders.BottomTabStyle" = "Kiểu Thư mục dưới cùng"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "Ẩn \"%@\""; +"Settings.Folders.RememberLast" = "Mở thư mục gần đây"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram sẽ mở thư mục gần nhất sau khi khởi động lại hoặc chuyển tài khoản"; + +"Settings.Folders.CompactNames" = "Khoảng cách nhỏ hơn"; +"Settings.Folders.AllChatsTitle" = "Tiêu đề \"Tất cả Chat\""; +"Settings.Folders.AllChatsTitle.short" = "Ngắn"; +"Settings.Folders.AllChatsTitle.long" = "Dài"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "Mặc định"; + + +"Settings.ChatList.Header" = "DANH SÁCH CHAT"; +"Settings.CompactChatList" = "Danh sách Chat Nhỏ gọn"; + +"Settings.Profiles.Header" = "HỒ SƠ"; + +"Settings.Stories.Hide" = "Ẩn Tin"; +"Settings.Stories.WarnBeforeView" = "Hỏi trước khi xem"; +"Settings.Stories.DisableSwipeToRecord" = "Tắt vuốt để quay"; + +"Settings.Translation.QuickTranslateButton" = "Hiện nút dịch nhanh"; + +"Stories.Warning.Author" = "Tác giả"; +"Stories.Warning.ViewStory" = "Xem Tin?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ SẼ CÓ THỂ THẤY bạn đã xem Tin của họ."; +"Stories.Warning.NoticeStealth" = "%@ sẽ không biết bạn đã xem Tin của họ."; + +"Settings.Photo.Quality.Notice" = "Chất lượng của ảnh gửi đi và ảnh Tin"; +"Settings.Photo.SendLarge" = "Gửi ảnh lớn"; +"Settings.Photo.SendLarge.Notice" = "Tăng giới hạn kích thước bên trên của hình ảnh nén lên 2560px"; + +"Settings.VideoNotes.Header" = "VIDEO TRÒN"; +"Settings.VideoNotes.StartWithRearCam" = "Bắt đầu với camera sau"; + +"Settings.CustomColors.Header" = "MÀU TÀI KHOẢN"; +"Settings.CustomColors.Saturation" = "ĐỘ BÃO HÒA"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "Đặt độ bão hòa thành 0%% để tắt màu tài khoản"; + +"Settings.UploadsBoost" = "Tăng tốc tải lên"; +"Settings.DownloadsBoost" = "Tăng tốc tải xuống"; +"Settings.DownloadsBoost.Notice" = "Tăng số lượng kết nối song song và kích thước các khối tệp. Nếu mạng của bạn không thể xử lý tải, hãy thử các tùy chọn khác phù hợp với kết nối của bạn."; +"Settings.DownloadsBoost.none" = "Tắt"; +"Settings.DownloadsBoost.medium" = "Trung bình"; +"Settings.DownloadsBoost.maximum" = "Tối đa"; + +"Settings.ShowProfileID" = "Hiện ID hồ sơ"; +"Settings.ShowDC" = "Hiển thị Trung tâm Dữ liệu"; +"Settings.ShowCreationDate" = "Hiển thị Ngày Tạo Chat"; +"Settings.ShowCreationDate.Notice" = "Ngày tạo có thể không biết được đối với một số cuộc trò chuyện."; + +"Settings.ShowRegDate" = "Hiển thị Ngày Đăng ký"; +"Settings.ShowRegDate.Notice" = "Ngày đăng ký là xấp xỉ."; + +"Settings.SendWithReturnKey" = "Gửi tín nhắn bằng nút \"Nhập\""; +"Settings.HidePhoneInSettingsUI" = "Ẩn số điện thoại trong cài đặt"; +"Settings.HidePhoneInSettingsUI.Notice" = "Số điện thoại của bạn sẽ chỉ ẩn đi trong cài đặt. Đến cài đặt \"Riêng tư và Bảo mật\" để ẩn đối với người khác\"."; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "Nếu rời đi trong 5 giây"; + +"ProxySettings.UseSystemDNS" = "Sử dụng DNS hệ thống"; +"ProxySettings.UseSystemDNS.Notice" = "Sử dụng DNS hệ thống để bỏ qua thời gian chờ nếu bạn không có quyền truy cập vào DNS của Google"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "Bạn **không cần** %@!"; +"Common.RestartRequired" = "Yêu cầu khởi động lại"; +"Common.RestartNow" = "Khởi động lại"; +"Common.OpenTelegram" = "Mở Telegram"; +"Common.UseTelegramForPremium" = "Vui lòng lưu ý rằng để có được Telegram Premium, bạn phải sử dụng ứng dụng Telegram chính thức. Sau khi bạn đã có Telegram Premium, tất cả các tính năng của nó sẽ trở nên có sẵn trong Swiftgram."; + +"Message.HoldToShowOrReport" = "Nhấn giữ để Hiển thị hoặc Báo cáo."; + +"Auth.AccountBackupReminder" = "Hãy đảm bảo bạn có một phương pháp truy cập dự phòng. Giữ lại một SIM để nhận SMS hoặc một phiên đăng nhập bổ sung để tránh bị khóa tài khoản."; +"Auth.UnofficialAppCodeTitle" = "Bạn chỉ có thể nhận được mã thông qua ứng dụng chính thức"; + +"Settings.SmallReactions" = "Thu nhỏ biểu tượng cảm xúc"; +"Settings.HideReactions" = "Ẩn Biểu tượng cảm xúc"; + +"ContextMenu.SaveToCloud" = "Lưu vào Đám mây"; +"ContextMenu.SelectFromUser" = "Chọn từ Tác giả"; + +"Settings.ContextMenu" = "MENU NGỮ CẢNH"; +"Settings.ContextMenu.Notice" = "Mục nhập đã vô hiệu hóa sẽ có sẵn trong menu phụ 'Swiftgram'."; + + +"Settings.ChatSwipeOptions" = "Tuỳ chọn Lướt Danh sách Chat"; +"Settings.DeleteChatSwipeOption" = "Vuốt để xóa Cuộc trò chuyện"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "Kéo xuống đến kênh chưa đọc"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "Kéo Để Đến Chủ Đề Tiếp Theo"; +"Settings.GalleryCamera" = "Máy ảnh trong thư viện"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" Nút"; +"Settings.SnapDeletionEffect" = "Hiệu Ứng Xóa Tin Nhắn"; + +"Settings.Stickers.Size" = "KÍCH THƯỚC"; +"Settings.Stickers.Timestamp" = "Hiện mốc thời gian"; + +"Settings.RecordingButton" = "Nút Ghi Âm Giọng Nói"; + +"Settings.DefaultEmojisFirst" = "Ưu tiên biểu tượng cảm xúc tiêu chuẩn"; +"Settings.DefaultEmojisFirst.Notice" = "Hiển thị biểu tượng cảm xúc tiêu chuẩn trước biểu tượng cảm xúc cao cấp trên bàn phím biểu tượng cảm xúc"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "đã tạo: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "Đã tham gia %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "Đã đăng ký"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "Double-tap để chỉnh sửa tin nhắn"; + +"Settings.wideChannelPosts" = "Bài đăng rộng trong các kênh"; +"Settings.ForceEmojiTab" = "Bàn phím Emoji mặc định"; + +"Settings.forceBuiltInMic" = "Buộc Micro Điện Thoại"; +"Settings.forceBuiltInMic.Notice" = "Nếu được kích hoạt, ứng dụng sẽ chỉ sử dụng micro điện thoại của thiết bị ngay cả khi tai nghe được kết nối."; + +"Settings.hideChannelBottomButton" = "Ẩn thanh dưới cùng của kênh"; + +"Settings.CallConfirmation" = "Xác nhận cuộc gọi"; +"Settings.CallConfirmation.Notice" = "Swiftgram sẽ yêu cầu bạn xác nhận trước khi thực hiện cuộc gọi."; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "Thực hiện cuộc gọi?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "Thực hiện cuộc gọi video?"; + +"MutualContact.Label" = "liên hệ chung"; + +"Settings.swipeForVideoPIP" = "Video PIP với Vuốt"; +"Settings.swipeForVideoPIP.Notice" = "Nếu được kích hoạt, việc vuốt video sẽ mở nó ở chế độ Hình trong hình."; diff --git a/Swiftgram/SGStrings/Strings/zh-hans.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/zh-hans.lproj/SGLocalizable.strings new file mode 100644 index 00000000..460aabbf --- /dev/null +++ b/Swiftgram/SGStrings/Strings/zh-hans.lproj/SGLocalizable.strings @@ -0,0 +1,249 @@ +"Settings.ContentSettings" = "敏感内容设置"; + +"Settings.Tabs.Header" = "标签"; +"Settings.Tabs.HideTabBar" = "隐藏底部导航栏"; +"Settings.Tabs.ShowContacts" = "显示联系人标签"; +"Settings.Tabs.ShowNames" = "显示标签名称"; + +"Settings.Folders.BottomTab" = "底部分组"; +"Settings.Folders.BottomTabStyle" = "底部分组样式"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS样式"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram样式"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "隐藏 \"%@\""; +"Settings.Folders.RememberLast" = "打开上次分组"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram 将在重启或切换账户后打开最后使用的分组"; + +"Settings.Folders.CompactNames" = "缩小分组间距"; +"Settings.Folders.AllChatsTitle" = "\"所有对话\"标题"; +"Settings.Folders.AllChatsTitle.short" = "短标题"; +"Settings.Folders.AllChatsTitle.long" = "长标题"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "默认"; + + +"Settings.ChatList.Header" = "对话列表"; +"Settings.CompactChatList" = "紧凑型对话列表"; +"Settings.ChatList.Lines" = "对话列表行数"; +"Settings.ChatList.Lines.1" = "1 行"; +"Settings.ChatList.Lines.2" = "2 行"; +"Settings.ChatList.Lines.3" = "3 行(默认)"; + +"Settings.Profiles.Header" = "资料"; + +"Settings.Stories.Hide" = "隐藏动态"; +"Settings.Stories.WarnBeforeView" = "查看前询问"; +"Settings.Stories.DisableSwipeToRecord" = "禁用侧滑拍摄"; + +"Settings.Translation.QuickTranslateButton" = "快速翻译按钮"; + +"Stories.Warning.Author" = "作者"; +"Stories.Warning.ViewStory" = "要查看动态吗?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ 将能够看到你查看了他们的动态"; +"Stories.Warning.NoticeStealth" = "%@ 将无法看到您查看他们的动态"; + +"Settings.Photo.Quality.Notice" = "发送图片的质量"; +"Settings.Photo.SendLarge" = "发送大尺寸照片"; +"Settings.Photo.SendLarge.Notice" = "将压缩图片的尺寸限制提高到 2560px"; + +"Settings.VideoNotes.Header" = "圆形视频"; +"Settings.VideoNotes.StartWithRearCam" = "默认使用后置相机"; + +"Settings.CustomColors.Header" = "账户颜色"; +"Settings.CustomColors.Saturation" = "饱和度"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "设置饱和度为 0%% 以禁用账户颜色"; + +"Settings.UploadsBoost" = "上传加速"; +"Settings.DownloadsBoost" = "下载加速"; +"Settings.DownloadsBoost.Notice" = "增加并行连接的数量和文件块的大小。如果您的网络无法承受负载,请尝试不同适合您连接的选项。"; +"Settings.DownloadsBoost.none" = "停用"; +"Settings.DownloadsBoost.medium" = "中等"; +"Settings.DownloadsBoost.maximum" = "最大"; + +"Settings.ShowProfileID" = "显示用户 UID"; +"Settings.ShowDC" = "显示数据中心"; +"Settings.ShowCreationDate" = "显示群组或频道的创建日期"; +"Settings.ShowCreationDate.Notice" = "某些群组或频道可能缺少创建日期"; + +"Settings.ShowRegDate" = "显示注册日期"; +"Settings.ShowRegDate.Notice" = "这是大概的注册日期"; + +"Settings.SendWithReturnKey" = "使用返回键发送"; +"Settings.HidePhoneInSettingsUI" = "在设置中隐藏电话号码"; +"Settings.HidePhoneInSettingsUI.Notice" = "您的电话号码只会在设置界面中隐藏。要对其他人隐藏,可进入隐私设置调整。"; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "离开 5 秒后"; + +"ProxySettings.UseSystemDNS" = "使用系统DNS"; +"ProxySettings.UseSystemDNS.Notice" = "如果您无法使用 Google DNS,请使用系统 DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "此功能**无需** %@ 订阅!"; +"Common.RestartRequired" = "需要重启"; +"Common.RestartNow" = "立即重启"; +"Common.OpenTelegram" = "打开 Telegram"; +"Common.UseTelegramForPremium" = "请注意,您必须使用官方的 Telegram 客户端才可购买 Telegram Premium,一旦您获得 Telegram Premium,其所有功能也将在 Swiftgram 中生效。"; +"Common.UpdateOS" = "需要 iOS 更新"; + +"Message.HoldToShowOrReport" = "长按显示或举报"; + +"Auth.AccountBackupReminder" = "请确保您有一个备用的访问方式。保留一张用于接收短信的 SIM 卡或多登录一个会话,以免被锁定。"; +"Auth.UnofficialAppCodeTitle" = "您只能通过官方应用程序获得代码"; + +"Settings.SmallReactions" = "缩小表情回应"; +"Settings.HideReactions" = "隐藏回应"; + +"ContextMenu.SaveToCloud" = "保存到收藏夹"; +"ContextMenu.SelectFromUser" = "选择此人所有消息"; + +"Settings.ContextMenu" = "消息菜单"; +"Settings.ContextMenu.Notice" = "已禁用的项目可在 Swiftgram 子菜单中找到"; + + +"Settings.ChatSwipeOptions" = "对话列表滑动选项"; +"Settings.DeleteChatSwipeOption" = "滑动删除对话"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "上滑到下一未读频道"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "上滑到下一个主题"; +"Settings.GalleryCamera" = "图库中的相机"; +"Settings.GalleryCameraPreview" = "图库中的相机预览"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" 按钮"; +"Settings.SnapDeletionEffect" = "删除消息的特效"; + +"Settings.Stickers.Size" = "尺寸"; +"Settings.Stickers.Timestamp" = "显示时间"; + +"Settings.RecordingButton" = "录音按钮"; + +"Settings.DefaultEmojisFirst" = "优先使用标准表情符号"; +"Settings.DefaultEmojisFirst.Notice" = "在表情列表中将标准表情符号置于高级表情符号之前"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "创建日期: %@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "加入 %@ 的日期"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "注册日期"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "双击编辑消息"; + +"Settings.wideChannelPosts" = "在频道中以更宽的版面显示消息"; +"Settings.ForceEmojiTab" = "默认展示表情符号"; + +"Settings.forceBuiltInMic" = "强制使用设备麦克风"; +"Settings.forceBuiltInMic.Notice" = "若启用,即使已连接耳机,应用也只使用设备自身的麦克风。"; + +"Settings.showChannelBottomButton" = "频道底部面板"; + +"Settings.secondsInMessages" = "消息中的秒数"; + +"Settings.CallConfirmation" = "通话确认"; +"Settings.CallConfirmation.Notice" = "Swiftgram 将在拨打电话前征求您的确认"; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "拨打语音通话?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "拨打视频通话?"; + +"MutualContact.Label" = "双向联系人"; + +"Settings.swipeForVideoPIP" = "上滑打开画中画"; +"Settings.swipeForVideoPIP.Notice" = "如果启用,滑动视频将以画中画模式打开。"; + +"SessionBackup.Title" = "会话备份"; +"SessionBackup.Sessions.Title" = "会话"; +"SessionBackup.Actions.Backup" = "备份到钥匙串"; +"SessionBackup.Actions.Restore" = "从钥匙串恢复"; +"SessionBackup.Actions.DeleteAll" = "删除钥匙串备份"; +"SessionBackup.Actions.DeleteOne" = "从备份中删除"; +"SessionBackup.Actions.RemoveFromApp" = "从应用程序中移除"; +"SessionBackup.LastBackupAt" = "最后备份:%@"; +"SessionBackup.RestoreOK" = "确定。已恢复会话:%@"; +"SessionBackup.LoggedIn" = "已登录"; +"SessionBackup.LoggedOut" = "已登出"; +"SessionBackup.DeleteAll.Title" = "删除所有会话?"; +"SessionBackup.DeleteAll.Text" = "所有会话将从钥匙串中删除。\n\n帐号将不会从 Swiftgram 登出。"; +"SessionBackup.DeleteSingle.Title" = "删除 1 个会话?"; +"SessionBackup.DeleteSingle.Text" = "%@ 会话将从钥匙串中删除。\n\n帐号将不会从 Swiftgram 登出。"; +"SessionBackup.RemoveFromApp.Title" = "从应用程序中移除帐户?"; +"SessionBackup.RemoveFromApp.Text" = "%@ 会话将从 Swiftgram 中移除!会话将保持活动状态,以便稍后恢复。"; +"SessionBackup.Notice" = "会话已加密并存储在设备的钥匙串中。会话永远不会离开您的设备。\n\n重要提示:要在新设备或操作系统重置后恢复会话,您必须启用加密备份,否则钥匙串将无法转移。\n\n注意:会话仍可能被Telegram或另一台设备撤销。"; + +"MessageFilter.Title" = "消息过滤器"; +"MessageFilter.SubTitle" = "移除干扰,减少包含以下关键字的消息的可见性。\n关键字区分大小写。"; +"MessageFilter.Keywords.Title" = "关键字"; +"MessageFilter.InputPlaceholder" = "输入关键字"; + +"InputToolbar.Title" = "格式面板"; + +"Notifications.MentionsAndReplies.Title" = "@提及和回复"; +"Notifications.MentionsAndReplies.value.default" = "默认"; +"Notifications.MentionsAndReplies.value.silenced" = "已静音"; +"Notifications.MentionsAndReplies.value.disabled" = "停用"; +"Notifications.PinnedMessages.Title" = "置顶消息"; +"Notifications.PinnedMessages.value.default" = "默认"; +"Notifications.PinnedMessages.value.silenced" = "已静音"; +"Notifications.PinnedMessages.value.disabled" = "停用"; + + +"PayWall.Text" = "增强了专业功能"; + +"PayWall.SessionBackup.Title" = "账号备份"; +"PayWall.SessionBackup.Notice" = "即使在重新安装后也可以登录到没有代码的帐户。使用设备上的密钥链来安全存储。"; +"PayWall.SessionBackup.Description" = "更改设备或删除 Swiftgram 已不再是一个问题。还原在Telegram 服务器上仍然活跃的所有会话。"; + +"PayWall.MessageFilter.Title" = "消息过滤器"; +"PayWall.MessageFilter.Notice" = "减少 SPAM、促销和令人烦恼的消息的可见性。"; +"PayWall.MessageFilter.Description" = "创建一个您不想经常看到的关键字列表,而Swiftgram 会减少干扰。"; + +"PayWall.Notifications.Title" = "禁用 @提及和回复"; +"PayWall.Notifications.Notice" = "隐藏或静音不重要的通知。"; +"PayWall.Notifications.Description" = "当你需要一点心情时,不再有固定的消息或 @reference."; + +"PayWall.InputToolbar.Title" = "格式面板"; +"PayWall.InputToolbar.Notice" = "只需单击即可节省时间格式化消息。"; +"PayWall.InputToolbar.Description" = "应用并清除格式化或插入像专业版这样的新行。"; + +"PayWall.AppIcons.Title" = "独特的应用图标"; +"PayWall.AppIcons.Notice" = "自定义 Swiftgram 在主屏幕上的外观。"; + +"PayWall.About.Title" = "关于 Swiftgram Pro"; +"PayWall.About.Notice" = "Swiftgram 的免费版本提供超过 Telegram 应用的多个功能和改进。创新并保持 Swiftgram 与每月的 Telegram 更新同步是一项庞大的工作,需要耗费大量的时间和昂贵的硬件。\n\nSwiftgram 是一个开源应用,尊重您的隐私,并且不打扰您广告。订阅 Swiftgram Pro,您将获得独享特性并支持独立开发者。\n\n- @Kylmakalle"; +/* DO NOT TRANSLATE */ +"PayWall.About.Signature" = "@Kylmakalle"; +/* DO NOT TRANSLATE */ +"PayWall.About.SignatureURL" = "https://t.me/Kylmakalle"; + +"PayWall.ProSupport.Title" = "支付问题?"; +"PayWall.ProSupport.Contact" = "不用担心!"; + +"PayWall.RestorePurchases" = "恢复购买"; +"PayWall.Terms" = "服务条款"; +"PayWall.Privacy" = "隐私政策"; +"PayWall.TermsURL" = "https://swiftgram.app/terms"; +"PayWall.PrivacyURL" = "https://swiftgram.app/privacy"; +"PayWall.Notice.Markdown" = "通过订阅 Swiftgram Pro,您同意 [Swiftgram 服务条款](%1$@) 和 [隐私政策](%2$@)。"; +"PayWall.Notice.Raw" = "通过订阅 Swiftgram Pro,您同意 Swiftgram 服务条款和隐私政策。"; + +"PayWall.Button.OpenPro" = "使用专业功能"; +"PayWall.Button.Purchasing" = "正在购买……"; +"PayWall.Button.Restoring" = "正在恢复购买……"; +"PayWall.Button.Validating" = "正在验证购买……"; +"PayWall.Button.PaymentsUnavailable" = "付款不可用"; +"PayWall.Button.BuyInAppStore" = "订阅 App Store 版本"; +"PayWall.Button.Subscribe" = "订阅 %@ / 月"; +"PayWall.Button.ContactingAppStore" = "正在联系 App Store……"; + +"Paywall.Error.Title" = "错误"; +"PayWall.ValidationError" = "验证错误"; +"PayWall.ValidationError.TryAgain" = "购买验证过程中出现问题。不用担心!稍后再试恢复购买。"; +"PayWall.ValidationError.Expired" = "您的订阅已过期。再次订阅以重新获得专业版功能。"; diff --git a/Swiftgram/SGStrings/Strings/zh-hant.lproj/SGLocalizable.strings b/Swiftgram/SGStrings/Strings/zh-hant.lproj/SGLocalizable.strings new file mode 100644 index 00000000..cc3963ac --- /dev/null +++ b/Swiftgram/SGStrings/Strings/zh-hant.lproj/SGLocalizable.strings @@ -0,0 +1,249 @@ +"Settings.ContentSettings" = "敏感內容設定"; + +"Settings.Tabs.Header" = "頁籤"; +"Settings.Tabs.HideTabBar" = "隱藏導航列"; +"Settings.Tabs.ShowContacts" = "顯示聯絡人頁籤"; +"Settings.Tabs.ShowNames" = "顯示頁籤名稱"; + +"Settings.Folders.BottomTab" = "底部頁籤"; +"Settings.Folders.BottomTabStyle" = "底部對話盒樣式"; + +/* Do not translate */ +"Settings.Folders.BottomTabStyle.ios" = "iOS"; +/* Do not translate */ +"Settings.Folders.BottomTabStyle.telegram" = "Telegram"; +/* Example: Hide "All Chats" */ +"Settings.Folders.AllChatsHidden" = "隱藏 \"%@\""; +"Settings.Folders.RememberLast" = "開啟最後瀏覽的對話盒"; +"Settings.Folders.RememberLast.Notice" = "Swiftgram 會在重啟或帳號切換後開啟最後瀏覽的對話盒"; + +"Settings.Folders.CompactNames" = "縮小間距"; +"Settings.Folders.AllChatsTitle" = "\"所有對話\"標題"; +"Settings.Folders.AllChatsTitle.short" = "短"; +"Settings.Folders.AllChatsTitle.long" = "長"; +/* Default behaviour for All Chats Folder Title. "All Chats" title: Default */ +"Settings.Folders.AllChatsTitle.none" = "預設"; + + +"Settings.ChatList.Header" = "對話列表"; +"Settings.CompactChatList" = "緊湊型對話列表"; +"Settings.ChatList.Lines" = "對話列表行數"; +"Settings.ChatList.Lines.1" = "1 行"; +"Settings.ChatList.Lines.2" = "2 行"; +"Settings.ChatList.Lines.3" = "3 行(預設)"; + +"Settings.Profiles.Header" = "配置文件"; + +"Settings.Stories.Hide" = "隱藏限時動態"; +"Settings.Stories.WarnBeforeView" = "瀏覽前確認"; +"Settings.Stories.DisableSwipeToRecord" = "停用滑動錄製"; + +"Settings.Translation.QuickTranslateButton" = "快速翻譯按鈕"; + +"Stories.Warning.Author" = "來自"; +"Stories.Warning.ViewStory" = "查看限時動態?"; +/* Author will be able to see that you viewed their Story */ +"Stories.Warning.Notice" = "%@ 將會看到您瀏覽了限時動態"; +"Stories.Warning.NoticeStealth" = "%@ 將無法看到您瀏覽了限時動態"; + +"Settings.Photo.Quality.Notice" = "傳送影像畫質"; +"Settings.Photo.SendLarge" = "傳送大尺寸影像"; +"Settings.Photo.SendLarge.Notice" = "將壓縮影像的尺寸限制增加到 2560px"; + +"Settings.VideoNotes.Header" = "圓形影片"; +"Settings.VideoNotes.StartWithRearCam" = "預設使用後置鏡頭"; + +"Settings.CustomColors.Header" = "帳號顏色"; +"Settings.CustomColors.Saturation" = "飽和度"; +/* Make sure to escape Percentage sign % */ +"Settings.CustomColors.Saturation.Notice" = "將飽和度設為 0%% 以停用帳戶顏色"; + +"Settings.UploadsBoost" = "上傳加速"; +"Settings.DownloadsBoost" = "下載加速"; +"Settings.DownloadsBoost.Notice" = "增加並行連接的數量和文件區塊的大小。如果您的網路無法承受負載,請嘗試不同適合您連接的選項。"; +"Settings.DownloadsBoost.none" = "已停用"; +"Settings.DownloadsBoost.medium" = "中等"; +"Settings.DownloadsBoost.maximum" = "最大"; + +"Settings.ShowProfileID" = "顯示用戶 UID"; +"Settings.ShowDC" = "顯示資料中心 (DC)"; +"Settings.ShowCreationDate" = "顯示對話建立日期"; +"Settings.ShowCreationDate.Notice" = "某些對話可能會缺少建立日期"; + +"Settings.ShowRegDate" = "顯示註冊日期"; +"Settings.ShowRegDate.Notice" = "大約註冊日期"; + +"Settings.SendWithReturnKey" = "使用「換行」鍵傳送"; +"Settings.HidePhoneInSettingsUI" = "在設定頁中隱藏電話號碼"; +"Settings.HidePhoneInSettingsUI.Notice" = "您的電話在「設定頁」中不再顯示,可到「隱私與安全性」設定來對其他人隱藏。"; + +"PasscodeSettings.AutoLock.InFiveSeconds" = "離開5秒後"; + +"ProxySettings.UseSystemDNS" = "使用系統 DNS"; +"ProxySettings.UseSystemDNS.Notice" = "如果您無法使用 Google DNS,請使用系統 DNS"; + +/* Preserve markdown asterisks! Example: You **don't** need Telegram Premium! */ +"Common.NoTelegramPremiumNeeded" = "您 **不需要** %@!"; +"Common.RestartRequired" = "需要重新啟動"; +"Common.RestartNow" = "立即重啟"; +"Common.OpenTelegram" = "開啟 Telegram"; +"Common.UseTelegramForPremium" = "要獲得 Telegram Premium,您必須使用官方 Telegram App。一旦您擁有 Telegram Premium,其所有功能都將在 Swiftgram 中可用。"; +"Common.UpdateOS" = "需要 iOS 更新"; + +"Message.HoldToShowOrReport" = "按住以顯示訊息或報告"; + +"Auth.AccountBackupReminder" = "請確保您有備用訪問方法。保留用於接收簡訊的 SIM 卡或其他登入狀態以避免被鎖定。"; +"Auth.UnofficialAppCodeTitle" = "您只能透過官方 App 取得驗證碼"; + +"Settings.SmallReactions" = "縮小回應圖示"; +"Settings.HideReactions" = "隱藏回應"; + +"ContextMenu.SaveToCloud" = "轉傳到儲存的訊息"; +"ContextMenu.SelectFromUser" = "選取此人的所有訊息"; + +"Settings.ContextMenu" = "內容選單"; +"Settings.ContextMenu.Notice" = "停用的選項可在 Swiftgram 選單中使用"; + + +"Settings.ChatSwipeOptions" = "對話列表滑動選項"; +"Settings.DeleteChatSwipeOption" = "滑動刪除聊天記錄"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextChannelSameLocationSwipeProgress */ +"Settings.PullToNextChannel" = "頻道瀑布流"; +/* Re-word like this string on offical app https://translations.telegram.org/en/ios/groups_and_channels/Chat.NextUnreadTopicSwipeProgress */ +"Settings.PullToNextTopic" = "下拉以查看下一話題"; +"Settings.GalleryCamera" = "相簿圖庫"; +"Settings.GalleryCameraPreview" = "照片預覽"; +/* "Send Message As..." button */ +"Settings.SendAsButton" = "\"%@\" 按鈕"; +"Settings.SnapDeletionEffect" = "訊息刪除效果"; + +"Settings.Stickers.Size" = "尺寸"; +"Settings.Stickers.Timestamp" = "顯示時間戳"; + +"Settings.RecordingButton" = "錄音按鈕"; + +"Settings.DefaultEmojisFirst" = "優先顯示標準表情符號"; +"Settings.DefaultEmojisFirst.Notice" = "在表情符號鍵盤中,先顯示標準表情符號,再顯示 Premium 的"; + +/* Date when chat was created. "created: 24 May 2016" */ +"Chat.Created" = "建立於:%@"; + +/* Date when user joined the chat. "Joined Swiftgram Chat" */ +"Chat.JoinedDateTitle" = "已加入 %@"; +/* Date when user registered in Telegram. Will be shown like "Registered\n24 May 2016" */ +"Chat.RegDate" = "註冊日期"; + +"Settings.messageDoubleTapActionOutgoingEdit" = "雙擊以編輯訊息"; + +"Settings.wideChannelPosts" = "在頻道中以更寬的樣式顯示訊息"; +"Settings.ForceEmojiTab" = "預設表情符號鍵盤"; + +"Settings.forceBuiltInMic" = "強制使用裝置麥克風"; +"Settings.forceBuiltInMic.Notice" = "如果啟用,應用程式將只會使用設備麥克風。"; + +"Settings.showChannelBottomButton" = "頻道底部面板"; + +"Settings.secondsInMessages" = "消息中的秒數"; + +"Settings.CallConfirmation" = "撥號確認"; +"Settings.CallConfirmation.Notice" = "Swiftgram 在撥打電話之前會要求您確認。"; + +/* Confirmation before making a Call */ +"CallConfirmation.Audio.Title" = "打電話?"; + +/* Confirmation before making a Video Call */ +"CallConfirmation.Video.Title" = "進行視訊通話?"; + +"MutualContact.Label" = "雙向聯絡人"; + +"Settings.swipeForVideoPIP" = "影片 PIP 及滑動"; +"Settings.swipeForVideoPIP.Notice" = "如果啟用,滑動視頻將以畫中畫模式打開。"; + +"SessionBackup.Title" = "帳號備份"; +"SessionBackup.Sessions.Title" = "會話"; +"SessionBackup.Actions.Backup" = "備份到鑰匙串"; +"SessionBackup.Actions.Restore" = "從鑰匙串還原"; +"SessionBackup.Actions.DeleteAll" = "刪除鑰匙串備份"; +"SessionBackup.Actions.DeleteOne" = "從備份刪除"; +"SessionBackup.Actions.RemoveFromApp" = "從應用中移除"; +"SessionBackup.LastBackupAt" = "最後備份時間: %@"; +"SessionBackup.RestoreOK" = "確定。還原的會話: %@"; +"SessionBackup.LoggedIn" = "已登錄"; +"SessionBackup.LoggedOut" = "已登出"; +"SessionBackup.DeleteAll.Title" = "刪除所有會話?"; +"SessionBackup.DeleteAll.Text" = "所有會話將從鑰匙串中移除。\n\n帳戶將不會從 Swiftgram 登出。"; +"SessionBackup.DeleteSingle.Title" = "刪除 1 (一) 會話?"; +"SessionBackup.DeleteSingle.Text" = "%@ 會話將從鑰匙串中移除。\n\n帳戶將不會從 Swiftgram 登出。"; +"SessionBackup.RemoveFromApp.Title" = "從應用中移除帳戶?"; +"SessionBackup.RemoveFromApp.Text" = "%@ 會話將從 Swiftgram 中移除!會話將保持活躍,以便您稍後恢復。"; +"SessionBackup.Notice" = "會話會被加密並儲存在設備的鑰匙圈中。會話從不離開您的設備。\n\n重要提示:要在新設備上或在操作系統重置後恢復會話,您必須啟用加密備份,否則鑰匙圈將無法轉移。\n\n注意:會話仍然可能被 Telegram 或其他設備撤銷。"; + +"MessageFilter.Title" = "訊息過濾器"; +"MessageFilter.SubTitle" = "移除干擾並減少包含以下關鍵字的訊息的可見性。\n關鍵字區分大小寫。"; +"MessageFilter.Keywords.Title" = "關鍵字"; +"MessageFilter.InputPlaceholder" = "輸入關鍵字"; + +"InputToolbar.Title" = "格式化面板"; + +"Notifications.MentionsAndReplies.Title" = "@提及和回覆"; +"Notifications.MentionsAndReplies.value.default" = "預設"; +"Notifications.MentionsAndReplies.value.silenced" = "靜音"; +"Notifications.MentionsAndReplies.value.disabled" = "已停用"; +"Notifications.PinnedMessages.Title" = "置頂訊息"; +"Notifications.PinnedMessages.value.default" = "預設"; +"Notifications.PinnedMessages.value.silenced" = "靜音"; +"Notifications.PinnedMessages.value.disabled" = "已停用"; + + +"PayWall.Text" = "以 Pro 功能強化"; + +"PayWall.SessionBackup.Title" = "帳號備份"; +"PayWall.SessionBackup.Notice" = "即使在重新安裝後也可以登錄到沒有代碼的帳戶。使用設備上的密鑰鏈來安全存儲。"; +"PayWall.SessionBackup.Description" = "更改設備或刪除 Swiftgram 不再是問題。恢復 Telegram 伺服器上仍然活躍的所有會話。"; + +"PayWall.MessageFilter.Title" = "訊息過濾器"; +"PayWall.MessageFilter.Notice" = "減少 SPAM、促銷和煩人的訊息的可見性。"; +"PayWall.MessageFilter.Description" = "建立一個不想經常看到的關鍵字列表,Swiftgram 將減少干擾。"; + +"PayWall.Notifications.Title" = "禁用 @提及和回覆"; +"PayWall.Notifications.Notice" = "隱藏或靜音不重要的通知。"; +"PayWall.Notifications.Description" = "當你需要一些心情時,不再有固定的訊息或 @提及。"; + +"PayWall.InputToolbar.Title" = "格式化面板"; +"PayWall.InputToolbar.Notice" = "只需輕點即可節省時間格式化訊息。"; +"PayWall.InputToolbar.Description" = "像專業人士一樣應用或清除格式化,或插入新行。"; + +"PayWall.AppIcons.Title" = "獨特的應用圖標"; +"PayWall.AppIcons.Notice" = "自訂 Swiftgram 在您的主屏幕上的外觀。"; + +"PayWall.About.Title" = "關於 Swiftgram Pro"; +"PayWall.About.Notice" = "Swiftgram 免費版本提供比 Telegram 應用更多的功能和改進。創新和保持 Swiftgram 與 Telegram 更新同步是一項巨大的努力,需要大量的時間和昂貴的硬體。\n\nSwiftgram 是一個尊重您隱私且不會打擾您廣告的開源應用。訂閱 Swiftgram Pro,您可以訪問獨家功能並支持獨立開發者。"; +/* DO NOT TRANSLATE */ +"PayWall.About.Signature" = "@Kylmakalle"; +/* DO NOT TRANSLATE */ +"PayWall.About.SignatureURL" = "https://t.me/Kylmakalle"; + +"PayWall.ProSupport.Title" = "支付問題?"; +"PayWall.ProSupport.Contact" = "不用擔心!"; + +"PayWall.RestorePurchases" = "恢復購買"; +"PayWall.Terms" = "服務條款"; +"PayWall.Privacy" = "隱私政策"; +"PayWall.TermsURL" = "https://swiftgram.app/terms"; +"PayWall.PrivacyURL" = "https://swiftgram.app/privacy"; +"PayWall.Notice.Markdown" = "通過訂閱 Swiftgram Pro,您同意[Swiftgram 服務條款](%1$@)和[隱私政策](%2$@)。"; +"PayWall.Notice.Raw" = "通過訂閱 Swiftgram Pro,您同意 Swiftgram 服務條款和隱私政策。"; + +"PayWall.Button.OpenPro" = "使用 Pro 功能"; +"PayWall.Button.Purchasing" = "購買中……"; +"PayWall.Button.Restoring" = "恢復購買中……"; +"PayWall.Button.Validating" = "驗證購買中……"; +"PayWall.Button.PaymentsUnavailable" = "付款不可用"; +"PayWall.Button.BuyInAppStore" = "訂閱 App Store 版本"; +"PayWall.Button.Subscribe" = "訂閱 %@ / 月"; +"PayWall.Button.ContactingAppStore" = "正在聯繫 App Store……"; + +"Paywall.Error.Title" = "錯誤"; +"PayWall.ValidationError" = "驗證錯誤"; +"PayWall.ValidationError.TryAgain" = "在購買驗證過程中出錯。別擔心!稍後再試恢復購買。"; +"PayWall.ValidationError.Expired" = "您的訂閱已過期。請重新訂閱以恢復訪問 Pro 功能。"; diff --git a/Swiftgram/SGSwiftSignalKit/BUILD b/Swiftgram/SGSwiftSignalKit/BUILD new file mode 100644 index 00000000..597686fe --- /dev/null +++ b/Swiftgram/SGSwiftSignalKit/BUILD @@ -0,0 +1,15 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGSwiftSignalKit", + module_name = "SGSwiftSignalKit", + srcs = glob([ + "Sources/**/*.swift", + ]), + deps = [ + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGSwiftSignalKit/Sources/SGSwiftSignalKit.swift b/Swiftgram/SGSwiftSignalKit/Sources/SGSwiftSignalKit.swift new file mode 100644 index 00000000..60661007 --- /dev/null +++ b/Swiftgram/SGSwiftSignalKit/Sources/SGSwiftSignalKit.swift @@ -0,0 +1,191 @@ +import Foundation +import SwiftSignalKit + +public func transformValue(_ f: @escaping(T) -> R) -> (Signal) -> Signal { + return map(f) +} + +public func transformValueToSignal(_ f: @escaping(T) -> Signal) -> (Signal) -> Signal { + return mapToSignal(f) +} + +public func convertSignalWithNoErrorToSignalWithError(_ f: @escaping(T) -> Signal) -> (Signal) -> Signal { + return mapToSignalPromotingError(f) +} + +public func ignoreSignalErrors(onError: ((E) -> Void)? = nil) -> (Signal) -> Signal { + return { signal in + return signal |> `catch` { error in + // Log the error using the provided callback, if any + onError?(error) + + // Returning a signal that completes without errors + return Signal { subscriber in + subscriber.putCompletion() + return EmptyDisposable + } + } + } +} + +// Wrapper for non-Error types +public struct SignalError: Error { + public let error: E + + public init(_ error: E) { + self.error = error + } +} + +public struct SignalCompleted: Error {} + +// Extension for Signals +// NoError can be marked a +// try? await signal.awaitable() +public extension Signal { + func awaitable(file: String = #file, line: Int = #line) async throws -> T { + return try await withCheckedThrowingContinuation { continuation in + var disposable: Disposable? + let hasResumed = Atomic(value: false) + disposable = self.start( + next: { value in + if !hasResumed.with({ $0 }) { + let _ = hasResumed.swap(true) + continuation.resume(returning: value) + } else { + #if DEBUG + // Consider using awaitableStream() or |> take(1) + assertionFailure("awaitable Signal emitted more than one value. \(file):\(line)") + #endif + } + disposable?.dispose() + }, + error: { error in + if !hasResumed.with({ $0 }) { + let _ = hasResumed.swap(true) + if let error = error as? Error { + continuation.resume(throwing: error) + } else { + continuation.resume(throwing: SignalError(error)) + } + } else { + #if DEBUG + // I don't even know what we should consider here. awaitableStream? + assertionFailure("awaitable Signal emitted an error after a value. \(file):\(line)") + #endif + } + disposable?.dispose() + }, + completed: { + if !hasResumed.with({ $0 }) { + let _ = hasResumed.swap(true) + continuation.resume(throwing: SignalCompleted()) + } + disposable?.dispose() + } + ) + } + } + + func task() async throws -> T { + let disposable = MetaDisposable() + return try await withTaskCancellationHandler(operation: { + return try await withCheckedThrowingContinuation { continuation in + disposable.set((self |> take(1)).startStandalone( + next: { value in + continuation.resume(returning: value) + }, + error: { err in + continuation.resume(throwing: SignalError(err)) + } + )) + } + }, onCancel: { + disposable.dispose() + }) + } + + func stream() -> AsyncThrowingStream { + return AsyncThrowingStream { continuation in + let disposable = self.startStandalone( + next: { value in + continuation.yield(value) + }, + error: { err in + continuation.finish(throwing: SignalError(err)) + }, + completed: { + continuation.finish() + } + ) + continuation.onTermination = { _ in + disposable.dispose() + } + } + } +} + +public extension Signal where E == NoError { + func task() async -> T { + return await self.get() + } + + func stream() -> AsyncStream { + return AsyncStream { continuation in + let disposable = self.startStandalone( + next: { value in + continuation.yield(value) + }, + completed: { + continuation.finish() + } + ) + continuation.onTermination = { _ in + disposable.dispose() + } + } + } +} + +// Extension for general Signal types - AsyncStream support +public extension Signal { + func awaitableStream() -> AsyncStream { + return AsyncStream { continuation in + let disposable = self.start( + next: { value in + continuation.yield(value) + }, + error: { _ in + continuation.finish() + }, + completed: { + continuation.finish() + } + ) + + continuation.onTermination = { @Sendable _ in + disposable.dispose() + } + } + } +} + +// Extension for NoError Signal types - AsyncStream support +public extension Signal where E == NoError { + func awaitableStream() -> AsyncStream { + return AsyncStream { continuation in + let disposable = self.start( + next: { value in + continuation.yield(value) + }, + completed: { + continuation.finish() + } + ) + + continuation.onTermination = { @Sendable _ in + disposable.dispose() + } + } + } +} diff --git a/Swiftgram/SGSwiftUI/BUILD b/Swiftgram/SGSwiftUI/BUILD new file mode 100644 index 00000000..9437ba2d --- /dev/null +++ b/Swiftgram/SGSwiftUI/BUILD @@ -0,0 +1,20 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGSwiftUI", + module_name = "SGSwiftUI", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + # "-warnings-as-errors", + ], + deps = [ + "//submodules/LegacyUI:LegacyUI", + "//submodules/Display:Display", + "//submodules/TelegramPresentationData:TelegramPresentationData" + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SGSwiftUI/Sources/SGSwiftUI.swift b/Swiftgram/SGSwiftUI/Sources/SGSwiftUI.swift new file mode 100644 index 00000000..ba8d3574 --- /dev/null +++ b/Swiftgram/SGSwiftUI/Sources/SGSwiftUI.swift @@ -0,0 +1,507 @@ +import Display +import Foundation +import LegacyUI +import SwiftUI +import TelegramPresentationData + + +@available(iOS 13.0, *) +public class ObservedValue: ObservableObject { + @Published public var value: T + + public init(_ value: T) { + self.value = value + } +} + +@available(iOS 13.0, *) +public struct NavigationBarHeightKey: EnvironmentKey { + public static let defaultValue: CGFloat = 0 +} + +@available(iOS 13.0, *) +public struct ContainerViewLayoutKey: EnvironmentKey { + public static let defaultValue: ContainerViewLayout? = nil +} + +@available(iOS 13.0, *) +public struct LangKey: EnvironmentKey { + public static let defaultValue: String = "en" +} + +// Perhaps, affects Performance a lot +//@available(iOS 13.0, *) +//public struct ContainerViewLayoutUpdateCountKey: EnvironmentKey { +// public static let defaultValue: ObservedValue = ObservedValue(0) +//} + +@available(iOS 13.0, *) +public extension EnvironmentValues { + var navigationBarHeight: CGFloat { + get { self[NavigationBarHeightKey.self] } + set { self[NavigationBarHeightKey.self] = newValue } + } + + var containerViewLayout: ContainerViewLayout? { + get { self[ContainerViewLayoutKey.self] } + set { self[ContainerViewLayoutKey.self] = newValue } + } + + var lang: String { + get { self[LangKey.self] } + set { self[LangKey.self] = newValue } + } + +// var containerViewLayoutUpdateCount: ObservedValue { +// get { self[ContainerViewLayoutUpdateCountKey.self] } +// set { self[ContainerViewLayoutUpdateCountKey.self] = newValue } +// } +} + + +@available(iOS 13.0, *) +public struct SGSwiftUIView: View { + public let content: Content + public let manageSafeArea: Bool + + @ObservedObject var navigationBarHeight: ObservedValue + @ObservedObject var containerViewLayout: ObservedValue +// @ObservedObject var containerViewLayoutUpdateCount: ObservedValue + + private var lang: String + + public init( + legacyController: LegacySwiftUIController, + manageSafeArea: Bool = false, + @ViewBuilder content: () -> Content + ) { + #if DEBUG + if manageSafeArea { + print("WARNING SGSwiftUIView: manageSafeArea is deprecated, use @Environment(\\.navigationBarHeight) and @Environment(\\.containerViewLayout)") + } + #endif + self.navigationBarHeight = legacyController.navigationBarHeightModel + self.containerViewLayout = legacyController.containerViewLayoutModel + self.lang = legacyController.lang +// self.containerViewLayoutUpdateCount = legacyController.containerViewLayoutUpdateCountModel + self.manageSafeArea = manageSafeArea + self.content = content() + } + + public var body: some View { + content + .if(manageSafeArea) { $0.modifier(CustomSafeArea()) } + .environment(\.navigationBarHeight, navigationBarHeight.value) + .environment(\.containerViewLayout, containerViewLayout.value) + .environment(\.lang, lang) +// .environment(\.containerViewLayoutUpdateCount, containerViewLayoutUpdateCount) +// .onReceive(containerViewLayoutUpdateCount.$value) { _ in +// // Make sure View is updated when containerViewLayoutUpdateCount changes, +// // in case it does not depend on containerViewLayout +// } + } + +} + +@available(iOS 13.0, *) +public struct CustomSafeArea: ViewModifier { + @Environment(\.navigationBarHeight) var navigationBarHeight: CGFloat + @Environment(\.containerViewLayout) var containerViewLayout: ContainerViewLayout? + + public func body(content: Content) -> some View { + content + .edgesIgnoringSafeArea(.all) +// .padding(.top, /*totalTopSafeArea > navigationBarHeight.value ? totalTopSafeArea :*/ navigationBarHeight.value) + .padding(.top, topInset) + .padding(.bottom, bottomInset) + .padding(.leading, leftInset) + .padding(.trailing, rightInset) + } + + private var topInset: CGFloat { + max( + (containerViewLayout?.safeInsets.top ?? 0) + (containerViewLayout?.intrinsicInsets.top ?? 0), + navigationBarHeight + ) + } + + private var bottomInset: CGFloat { + (containerViewLayout?.safeInsets.bottom ?? 0) +// DEPRECATED, do not change +// + (containerViewLayout.value?.intrinsicInsets.bottom ?? 0) + } + + private var leftInset: CGFloat { + containerViewLayout?.safeInsets.left ?? 0 + } + + private var rightInset: CGFloat { + containerViewLayout?.safeInsets.right ?? 0 + } +} + +@available(iOS 13.0, *) +public extension View { + func sgTopSafeAreaInset(_ containerViewLayout: ContainerViewLayout?, _ navigationBarHeight: CGFloat) -> CGFloat { + return max( + (containerViewLayout?.safeInsets.top ?? 0) + (containerViewLayout?.intrinsicInsets.top ?? 0), + navigationBarHeight + ) + } + + func sgBottomSafeAreaInset(_ containerViewLayout: ContainerViewLayout?) -> CGFloat { + return (containerViewLayout?.safeInsets.bottom ?? 0) + (containerViewLayout?.intrinsicInsets.bottom ?? 0) + } + + func sgLeftSafeAreaInset(_ containerViewLayout: ContainerViewLayout?) -> CGFloat { + return containerViewLayout?.safeInsets.left ?? 0 + } + + func sgRightSafeAreaInset(_ containerViewLayout: ContainerViewLayout?) -> CGFloat { + return containerViewLayout?.safeInsets.right ?? 0 + } + +} + + +@available(iOS 13.0, *) +public final class LegacySwiftUIController: LegacyController { + public var navigationBarHeightModel: ObservedValue + public var containerViewLayoutModel: ObservedValue + public var inputHeightModel: ObservedValue + public let lang: String +// public var containerViewLayoutUpdateCountModel: ObservedValue + + override public init(presentation: LegacyControllerPresentation, theme: PresentationTheme? = nil, strings: PresentationStrings? = nil, initialLayout: ContainerViewLayout? = nil) { + navigationBarHeightModel = ObservedValue(0.0) + containerViewLayoutModel = ObservedValue(initialLayout) + inputHeightModel = ObservedValue(nil) + lang = strings?.baseLanguageCode ?? "en" +// containerViewLayoutUpdateCountModel = ObservedValue(0) + super.init(presentation: presentation, theme: theme, strings: strings, initialLayout: initialLayout) + } + + override public func containerLayoutUpdated(_ layout: ContainerViewLayout, transition: ContainedViewLayoutTransition) { + super.containerLayoutUpdated(layout, transition: transition) +// containerViewLayoutUpdateCountModel.value += 1 + + var newNavigationBarHeight = navigationLayout(layout: layout).navigationFrame.maxY + if !self.displayNavigationBar || self.navigationPresentation == .modal { + newNavigationBarHeight = 0.0 + } + if navigationBarHeightModel.value != newNavigationBarHeight { + navigationBarHeightModel.value = newNavigationBarHeight + } + if containerViewLayoutModel.value != layout { + containerViewLayoutModel.value = layout + } + if inputHeightModel.value != layout.inputHeight { + inputHeightModel.value = layout.inputHeight + } + } + + @available(*, unavailable) + public required init(coder _: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +@available(iOS 13.0, *) +extension UIHostingController { + public convenience init(rootView: Content, ignoreSafeArea: Bool) { + self.init(rootView: rootView) + + if ignoreSafeArea { + disableSafeArea() + } + } + + func disableSafeArea() { + guard let viewClass = object_getClass(view) else { + return + } + + func encodeText(string: String, key: Int16) -> String { + let nsString = string as NSString + let result = NSMutableString() + for i in 0 ..< nsString.length { + var c: unichar = nsString.character(at: i) + c = unichar(Int16(c) + key) + result.append(NSString(characters: &c, length: 1) as String) + } + return result as String + } + + let viewSubclassName = String(cString: class_getName(viewClass)).appending(encodeText(string: "`JhopsfTbgfBsfb", key: -1)) + + if let viewSubclass = NSClassFromString(viewSubclassName) { + object_setClass(view, viewSubclass) + } else { + guard + let viewClassNameUtf8 = (viewSubclassName as NSString).utf8String, + let viewSubclass = objc_allocateClassPair(viewClass, viewClassNameUtf8, 0) + else { + return + } + + if let method = class_getInstanceMethod(UIView.self, #selector(getter: UIView.safeAreaInsets)) { + let safeAreaInsets: @convention(block) (AnyObject) -> UIEdgeInsets = { _ in + .zero + } + + class_addMethod( + viewSubclass, + #selector(getter: UIView.safeAreaInsets), + imp_implementationWithBlock(safeAreaInsets), + method_getTypeEncoding(method) + ) + } + + objc_registerClassPair(viewSubclass) + object_setClass(view, viewSubclass) + } + } +} + + +@available(iOS 13.0, *) +public struct TGNavigationBackButtonModifier: ViewModifier { + weak var wrapperController: LegacyController? + + public func body(content: Content) -> some View { + content + .navigationBarBackButtonHidden(true) + .navigationBarItems(leading: + NavigationBarBackButton(action: { + wrapperController?.dismiss() + }) + .padding(.leading, -8) + ) + } +} + +@available(iOS 13.0, *) +public extension View { + func tgNavigationBackButton(wrapperController: LegacyController?) -> some View { + modifier(TGNavigationBackButtonModifier(wrapperController: wrapperController)) + } +} + + +@available(iOS 13.0, *) +public struct NavigationBarBackButton: View { + let text: String + let color: Color + let action: () -> Void + + public init(text: String = "Back", color: Color = .accentColor, action: @escaping () -> Void) { + self.text = text + self.color = color + self.action = action + } + + public var body: some View { + Button(action: action) { + HStack(spacing: 6) { + if let customBackArrow = navigationBarBackArrowImage(color: color.uiColor()) { + Image(uiImage: customBackArrow) + } else { + Image(systemName: "chevron.left") + .font(Font.body.weight(.bold)) + .foregroundColor(color) + } + Text(text) + .foregroundColor(color) + } + .contentShape(Rectangle()) + } + } +} + +@available(iOS 13.0, *) +public extension View { + func apply(@ViewBuilder _ block: (Self) -> V) -> V { block(self) } + + @ViewBuilder + func `if`(_ condition: Bool, transform: (Self) -> Content) -> some View { + if condition { + transform(self) + } else { + self + } + } + + @ViewBuilder + func `if`(_ condition: @escaping () -> Bool, transform: (Self) -> Content) -> some View { + if condition() { + transform(self) + } else { + self + } + } +} + +@available(iOS 13.0, *) +public extension Color { + + func uiColor() -> UIColor { + + if #available(iOS 14.0, *) { + return UIColor(self) + } + + let components = self.components() + return UIColor(red: components.r, green: components.g, blue: components.b, alpha: components.a) + } + + private func components() -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { + + let scanner = Scanner(string: self.description.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)) + var hexNumber: UInt64 = 0 + var r: CGFloat = 0.0, g: CGFloat = 0.0, b: CGFloat = 0.0, a: CGFloat = 0.0 + + let result = scanner.scanHexInt64(&hexNumber) + if result { + r = CGFloat((hexNumber & 0xff000000) >> 24) / 255 + g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255 + b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255 + a = CGFloat(hexNumber & 0x000000ff) / 255 + } + return (r, g, b, a) + } + + init(hex: String) { + let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted) + var int: UInt64 = 0 + Scanner(string: hex).scanHexInt64(&int) + let a, r, g, b: UInt64 + switch hex.count { + case 6: // RGB (No alpha) + (a, r, g, b) = (255, (int >> 16) & 0xff, (int >> 8) & 0xff, int & 0xff) + case 8: // ARGB + (a, r, g, b) = ((int >> 24) & 0xff, (int >> 16) & 0xff, (int >> 8) & 0xff, int & 0xff) + default: + (a, r, g, b) = (255, 0, 0, 0) + } + self.init(.sRGB, red: Double(r) / 255, green: Double(g) / 255, blue: Double(b) / 255, opacity: Double(a) / 255) + } +} + + +public enum BackgroundMaterial { + case ultraThinMaterial + case thinMaterial + case regularMaterial + case thickMaterial + case ultraThickMaterial + + @available(iOS 15.0, *) + var material: Material { + switch self { + case .ultraThinMaterial: return .ultraThinMaterial + case .thinMaterial: return .thinMaterial + case .regularMaterial: return .regularMaterial + case .thickMaterial: return .thickMaterial + case .ultraThickMaterial: return .ultraThickMaterial + } + } +} + +public enum BounceBehavior { + case automatic + case always + case basedOnSize + + @available(iOS 16.4, *) + var behavior: ScrollBounceBehavior { + switch self { + case .automatic: return .automatic + case .always: return .always + case .basedOnSize: return .basedOnSize + } + } +} + + +@available(iOS 13.0, *) +public extension View { + func fontWeightIfAvailable(_ weight: SwiftUI.Font.Weight) -> some View { + if #available(iOS 16.0, *) { + return self.fontWeight(weight) + } else { + return self + } + } + + func backgroundIfAvailable(material: BackgroundMaterial) -> some View { + if #available(iOS 15.0, *) { + return self.background(material.material) + } else { + return self.background( + Color(.systemBackground) + .opacity(0.75) + .blur(radius: 3) + .overlay(Color.white.opacity(0.1)) + ) + } + } +} + +@available(iOS 13.0, *) +public extension View { + func scrollBounceBehaviorIfAvailable(_ behavior: BounceBehavior) -> some View { + if #available(iOS 16.4, *) { + return self.scrollBounceBehavior(behavior.behavior) + } else { + return self + } + } +} + +@available(iOS 13.0, *) +public extension View { + func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View { + clipShape(RoundedCorner(radius: radius, corners: corners)) + } +} + +@available(iOS 13.0, *) +public struct RoundedCorner: Shape { + var radius: CGFloat = .infinity + var corners: UIRectCorner = .allCorners + + public func path(in rect: CGRect) -> Path { + let path = UIBezierPath( + roundedRect: rect, + byRoundingCorners: corners, + cornerRadii: CGSize(width: radius, height: radius) + ) + return Path(path.cgPath) + } +} + +@available(iOS 13.0, *) +public struct ContentSizeModifier: ViewModifier { + @Binding var size: CGSize + + public func body(content: Content) -> some View { + content + .background( + GeometryReader { geometry -> Color in + if geometry.size != size { + DispatchQueue.main.async { + self.size = geometry.size + } + } + return Color.clear + } + ) + } +} + +@available(iOS 13.0, *) +public extension View { + func trackSize(_ size: Binding) -> some View { + self.modifier(ContentSizeModifier(size: size)) + } +} diff --git a/Swiftgram/SGTabBarHeightModifier/BUILD b/Swiftgram/SGTabBarHeightModifier/BUILD new file mode 100644 index 00000000..6beaa484 --- /dev/null +++ b/Swiftgram/SGTabBarHeightModifier/BUILD @@ -0,0 +1,9 @@ +filegroup( + name = "SGTabBarHeightModifier", + srcs = glob([ + "Sources/**/*.swift", + ]), + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGTabBarHeightModifier/Sources/SGTabBarHeightModifier.swift b/Swiftgram/SGTabBarHeightModifier/Sources/SGTabBarHeightModifier.swift new file mode 100644 index 00000000..a9a0b587 --- /dev/null +++ b/Swiftgram/SGTabBarHeightModifier/Sources/SGTabBarHeightModifier.swift @@ -0,0 +1,27 @@ +import Foundation +import Display +import SGSimpleSettings + +public func sgTabBarHeightModifier(tabBarHeight: CGFloat, layout: ContainerViewLayout, defaultBarSmaller: Bool) -> CGFloat { + var tabBarHeight = tabBarHeight + guard !SGSimpleSettings.shared.showTabNames else { + return tabBarHeight + } + + if defaultBarSmaller { + tabBarHeight -= 6.0 + } else { + tabBarHeight -= 12.0 + } + + if layout.intrinsicInsets.bottom.isZero { + // Devices with home button need a bit more space + if defaultBarSmaller { + tabBarHeight += 3.0 + } else { + tabBarHeight += 6.0 + } + } + + return tabBarHeight +} diff --git a/Swiftgram/SGTranslationLangFix/BUILD b/Swiftgram/SGTranslationLangFix/BUILD new file mode 100644 index 00000000..70f7354e --- /dev/null +++ b/Swiftgram/SGTranslationLangFix/BUILD @@ -0,0 +1,17 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGTranslationLangFix", + module_name = "SGTranslationLangFix", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGTranslationLangFix/Sources/SGTranslationLangFix.swift b/Swiftgram/SGTranslationLangFix/Sources/SGTranslationLangFix.swift new file mode 100644 index 00000000..f308de08 --- /dev/null +++ b/Swiftgram/SGTranslationLangFix/Sources/SGTranslationLangFix.swift @@ -0,0 +1,9 @@ +public func sgTranslationLangFix(_ language: String) -> String { + if language.hasPrefix("de-") { + return "de" + } else if language.hasPrefix("zh-") { + return "zh" + } else { + return language + } +} \ No newline at end of file diff --git a/Swiftgram/SGWebAppExtensions/BUILD b/Swiftgram/SGWebAppExtensions/BUILD new file mode 100644 index 00000000..1d581760 --- /dev/null +++ b/Swiftgram/SGWebAppExtensions/BUILD @@ -0,0 +1,17 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGWebAppExtensions", + module_name = "SGWebAppExtensions", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGWebAppExtensions/Sources/LocationHashParser.swift b/Swiftgram/SGWebAppExtensions/Sources/LocationHashParser.swift new file mode 100644 index 00000000..355a5664 --- /dev/null +++ b/Swiftgram/SGWebAppExtensions/Sources/LocationHashParser.swift @@ -0,0 +1,58 @@ +import Foundation + +func urlSafeDecode(_ urlencoded: String) -> String { + return urlencoded.replacingOccurrences(of: "+", with: "%20").removingPercentEncoding ?? urlencoded +} + +public func urlParseHashParams(_ locationHash: String) -> [String: String?] { + var params = [String: String?]() + var localLocationHash = locationHash.removePrefix("#") // Remove leading '#' + + if localLocationHash.isEmpty { + return params + } + + if !localLocationHash.contains("=") && !localLocationHash.contains("?") { + params["_path"] = urlSafeDecode(localLocationHash) + return params + } + + let qIndex = localLocationHash.firstIndex(of: "?") + if let qIndex = qIndex { + let pathParam = String(localLocationHash[.. [String: String?] { + var params = [String: String?]() + + if queryString.isEmpty { + return params + } + + let queryStringParams = queryString.split(separator: "&") + for param in queryStringParams { + let parts = param.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false) + let paramName = urlSafeDecode(String(parts[0])) + let paramValue = parts.count > 1 ? urlSafeDecode(String(parts[1])) : nil + params[paramName] = paramValue + } + + return params +} + +extension String { + func removePrefix(_ prefix: String) -> String { + guard self.hasPrefix(prefix) else { return self } + return String(self.dropFirst(prefix.count)) + } +} diff --git a/Swiftgram/SGWebSettings/BUILD b/Swiftgram/SGWebSettings/BUILD new file mode 100644 index 00000000..ef1ee762 --- /dev/null +++ b/Swiftgram/SGWebSettings/BUILD @@ -0,0 +1,17 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGWebSettings", + module_name = "SGWebSettings", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGWebSettings/Sources/File.swift b/Swiftgram/SGWebSettings/Sources/File.swift new file mode 100644 index 00000000..e69de29b diff --git a/Swiftgram/SGWebSettingsScheme/BUILD b/Swiftgram/SGWebSettingsScheme/BUILD new file mode 100644 index 00000000..7bec1071 --- /dev/null +++ b/Swiftgram/SGWebSettingsScheme/BUILD @@ -0,0 +1,17 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SGWebSettingsScheme", + module_name = "SGWebSettingsScheme", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + ], + visibility = [ + "//visibility:public", + ], +) \ No newline at end of file diff --git a/Swiftgram/SGWebSettingsScheme/Sources/File.swift b/Swiftgram/SGWebSettingsScheme/Sources/File.swift new file mode 100644 index 00000000..981676a8 --- /dev/null +++ b/Swiftgram/SGWebSettingsScheme/Sources/File.swift @@ -0,0 +1,56 @@ +import Foundation + +public struct SGWebSettings: Codable, Equatable { + public let global: SGGlobalSettings + public let user: SGUserSettings + + public static var defaultValue: SGWebSettings { + return SGWebSettings(global: SGGlobalSettings(ytPip: true, qrLogin: true, storiesAvailable: false, canViewMessages: true, canEditSettings: false, canShowTelescope: false, announcementsData: nil, regdateFormat: "month", botMonkeys: [], forceReasons: [], unforceReasons: [], paymentsEnabled: true, duckyAppIconAvailable: true, canGrant: false, proSupportUrl: nil, nyAvailable: false), user: SGUserSettings(contentReasons: [], canSendTelescope: false, canBuyInBeta: true)) + } +} + +public struct SGGlobalSettings: Codable, Equatable { + public let ytPip: Bool + public let qrLogin: Bool + public let storiesAvailable: Bool + public let canViewMessages: Bool + public let canEditSettings: Bool + public let canShowTelescope: Bool + public let announcementsData: String? + public let regdateFormat: String + public let botMonkeys: [SGBotMonkeys] + public let forceReasons: [Int64] + public let unforceReasons: [Int64] + public let paymentsEnabled: Bool + public let duckyAppIconAvailable: Bool + public let canGrant: Bool + public let proSupportUrl: String? + public let nyAvailable: Bool +} + +public struct SGBotMonkeys: Codable, Equatable { + public let botId: Int64 + public let src: String + public let enable: String + public let disable: String +} + + +public struct SGUserSettings: Codable, Equatable { + public let contentReasons: [String] + public let canSendTelescope: Bool + public let canBuyInBeta: Bool +} + + +public extension SGUserSettings { + func expandedContentReasons() -> [String] { + return contentReasons.compactMap { base64String in + guard let data = Data(base64Encoded: base64String), + let decodedString = String(data: data, encoding: .utf8) else { + return nil + } + return decodedString + } + } +} diff --git a/Swiftgram/SwiftSoup/BUILD b/Swiftgram/SwiftSoup/BUILD new file mode 100644 index 00000000..a4eeb901 --- /dev/null +++ b/Swiftgram/SwiftSoup/BUILD @@ -0,0 +1,17 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "SwiftSoup", + module_name = "SwiftSoup", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + # "-warnings-as-errors", + ], + deps = [ + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/SwiftSoup/Sources/ArrayExt.swift b/Swiftgram/SwiftSoup/Sources/ArrayExt.swift new file mode 100644 index 00000000..a3b329f0 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/ArrayExt.swift @@ -0,0 +1,21 @@ +// +// ArrayExt.swift +// SwifSoup +// +// Created by Nabil Chatbi on 05/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +extension Array where Element : Equatable { + func lastIndexOf(_ e: Element) -> Int { + for pos in (0.. String { + return key + } + + /** + Set the attribute key; case is preserved. + @param key the new key; must not be null + */ + open func setKey(key: String) throws { + try Validate.notEmpty(string: key) + self.key = key.trim() + } + + /** + Get the attribute value. + @return the attribute value + */ + open func getValue() -> String { + return value + } + + /** + Set the attribute value. + @param value the new attribute value; must not be null + */ + @discardableResult + open func setValue(value: String) -> String { + let old = self.value + self.value = value + return old + } + + /** + Get the HTML representation of this attribute; e.g. {@code href="index.html"}. + @return HTML + */ + public func html() -> String { + let accum = StringBuilder() + html(accum: accum, out: (Document("")).outputSettings()) + return accum.toString() + } + + public func html(accum: StringBuilder, out: OutputSettings ) { + accum.append(key) + if (!shouldCollapseAttribute(out: out)) { + accum.append("=\"") + Entities.escape(accum, value, out, true, false, false) + accum.append("\"") + } + } + + /** + Get the string representation of this attribute, implemented as {@link #html()}. + @return string + */ + open func toString() -> String { + return html() + } + + /** + * Create a new Attribute from an unencoded key and a HTML attribute encoded value. + * @param unencodedKey assumes the key is not encoded, as can be only run of simple \w chars. + * @param encodedValue HTML attribute encoded value + * @return attribute + */ + public static func createFromEncoded(unencodedKey: String, encodedValue: String) throws ->Attribute { + let value = try Entities.unescape(string: encodedValue, strict: true) + return try Attribute(key: unencodedKey, value: value) + } + + public func isDataAttribute() -> Bool { + return key.startsWith(Attributes.dataPrefix) && key.count > Attributes.dataPrefix.count + } + + /** + * Collapsible if it's a boolean attribute and value is empty or same as name + * + * @param out Outputsettings + * @return Returns whether collapsible or not + */ + public final func shouldCollapseAttribute(out: OutputSettings) -> Bool { + return ("" == value || value.equalsIgnoreCase(string: key)) + && out.syntax() == OutputSettings.Syntax.html + && isBooleanAttribute() + } + + public func isBooleanAttribute() -> Bool { + return Attribute.booleanAttributes.contains(key.lowercased()) + } + + public func hashCode() -> Int { + var result = key.hashValue + result = 31 * result + value.hashValue + return result + } + + public func clone() -> Attribute { + do { + return try Attribute(key: key, value: value) + } catch Exception.Error( _, let msg) { + print(msg) + } catch { + + } + return try! Attribute(key: "", value: "") + } +} + +extension Attribute: Equatable { + static public func == (lhs: Attribute, rhs: Attribute) -> Bool { + return lhs.value == rhs.value && lhs.key == rhs.key + } + +} diff --git a/Swiftgram/SwiftSoup/Sources/Attributes.swift b/Swiftgram/SwiftSoup/Sources/Attributes.swift new file mode 100644 index 00000000..2ffa006a --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/Attributes.swift @@ -0,0 +1,235 @@ +// +// Attributes.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * The attributes of an Element. + *

+ * Attributes are treated as a map: there can be only one value associated with an attribute key/name. + *

+ *

+ * Attribute name and value comparisons are case sensitive. By default for HTML, attribute names are + * normalized to lower-case on parsing. That means you should use lower-case strings when referring to attributes by + * name. + *

+ * + * + */ +open class Attributes: NSCopying { + + public static var dataPrefix: String = "data-" + + // Stored by lowercased key, but key case is checked against the copy inside + // the Attribute on retrieval. + var attributes: [Attribute] = [] + + public init() {} + + /** + Get an attribute value by key. + @param key the (case-sensitive) attribute key + @return the attribute value if set; or empty string if not set. + @see #hasKey(String) + */ + open func get(key: String) -> String { + if let attr = attributes.first(where: { $0.getKey() == key }) { + return attr.getValue() + } + return "" + } + + /** + * Get an attribute's value by case-insensitive key + * @param key the attribute name + * @return the first matching attribute value if set; or empty string if not set. + */ + open func getIgnoreCase(key: String )throws -> String { + try Validate.notEmpty(string: key) + if let attr = attributes.first(where: { $0.getKey().caseInsensitiveCompare(key) == .orderedSame }) { + return attr.getValue() + } + return "" + } + + /** + Set a new attribute, or replace an existing one by key. + @param key attribute key + @param value attribute value + */ + open func put(_ key: String, _ value: String) throws { + let attr = try Attribute(key: key, value: value) + put(attribute: attr) + } + + /** + Set a new boolean attribute, remove attribute if value is false. + @param key attribute key + @param value attribute value + */ + open func put(_ key: String, _ value: Bool) throws { + if (value) { + try put(attribute: BooleanAttribute(key: key)) + } else { + try remove(key: key) + } + } + + /** + Set a new attribute, or replace an existing one by (case-sensitive) key. + @param attribute attribute + */ + open func put(attribute: Attribute) { + let key = attribute.getKey() + if let ix = attributes.firstIndex(where: { $0.getKey() == key }) { + attributes[ix] = attribute + } else { + attributes.append(attribute) + } + } + + /** + Remove an attribute by key. Case sensitive. + @param key attribute key to remove + */ + open func remove(key: String)throws { + try Validate.notEmpty(string: key) + if let ix = attributes.firstIndex(where: { $0.getKey() == key }) { + attributes.remove(at: ix) } + } + + /** + Remove an attribute by key. Case insensitive. + @param key attribute key to remove + */ + open func removeIgnoreCase(key: String ) throws { + try Validate.notEmpty(string: key) + if let ix = attributes.firstIndex(where: { $0.getKey().caseInsensitiveCompare(key) == .orderedSame}) { + attributes.remove(at: ix) + } + } + + /** + Tests if these attributes contain an attribute with this key. + @param key case-sensitive key to check for + @return true if key exists, false otherwise + */ + open func hasKey(key: String) -> Bool { + return attributes.contains(where: { $0.getKey() == key }) + } + + /** + Tests if these attributes contain an attribute with this key. + @param key key to check for + @return true if key exists, false otherwise + */ + open func hasKeyIgnoreCase(key: String) -> Bool { + return attributes.contains(where: { $0.getKey().caseInsensitiveCompare(key) == .orderedSame}) + } + + /** + Get the number of attributes in this set. + @return size + */ + open func size() -> Int { + return attributes.count + } + + /** + Add all the attributes from the incoming set to this set. + @param incoming attributes to add to these attributes. + */ + open func addAll(incoming: Attributes?) { + guard let incoming = incoming else { return } + for attr in incoming.attributes { + put(attribute: attr) + } + } + + /** + Get the attributes as a List, for iteration. Do not modify the keys of the attributes via this view, as changes + to keys will not be recognised in the containing set. + @return an view of the attributes as a List. + */ + open func asList() -> [Attribute] { + return attributes + } + + /** + * Retrieves a filtered view of attributes that are HTML5 custom data attributes; that is, attributes with keys + * starting with {@code data-}. + * @return map of custom data attributes. + */ + open func dataset() -> [String: String] { + let prefixLength = Attributes.dataPrefix.count + let pairs = attributes.filter { $0.isDataAttribute() } + .map { ($0.getKey().substring(prefixLength), $0.getValue()) } + return Dictionary(uniqueKeysWithValues: pairs) + } + + /** + Get the HTML representation of these attributes. + @return HTML + @throws SerializationException if the HTML representation of the attributes cannot be constructed. + */ + open func html()throws -> String { + let accum = StringBuilder() + try html(accum: accum, out: Document("").outputSettings()) // output settings a bit funky, but this html() seldom used + return accum.toString() + } + + public func html(accum: StringBuilder, out: OutputSettings ) throws { + for attr in attributes { + accum.append(" ") + attr.html(accum: accum, out: out) + } + } + + open func toString()throws -> String { + return try html() + } + + /** + * Checks if these attributes are equal to another set of attributes, by comparing the two sets + * @param o attributes to compare with + * @return if both sets of attributes have the same content + */ + open func equals(o: AnyObject?) -> Bool { + if(o == nil) {return false} + if (self === o.self) {return true} + guard let that = o as? Attributes else {return false} + return (attributes == that.attributes) + } + + open func lowercaseAllKeys() { + for ix in attributes.indices { + attributes[ix].key = attributes[ix].key.lowercased() + } + } + + public func copy(with zone: NSZone? = nil) -> Any { + let clone = Attributes() + clone.attributes = attributes + return clone + } + + open func clone() -> Attributes { + return self.copy() as! Attributes + } + + fileprivate static func dataKey(key: String) -> String { + return dataPrefix + key + } + +} + +extension Attributes: Sequence { + public func makeIterator() -> AnyIterator { + return AnyIterator(attributes.makeIterator()) + } +} diff --git a/Swiftgram/SwiftSoup/Sources/BinarySearch.swift b/Swiftgram/SwiftSoup/Sources/BinarySearch.swift new file mode 100644 index 00000000..fb98c577 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/BinarySearch.swift @@ -0,0 +1,95 @@ +// +// BinarySearch.swift +// SwiftSoup-iOS +// +// Created by Garth Snyder on 2/28/19. +// Copyright © 2019 Nabil Chatbi. All rights reserved. +// +// Adapted from https://stackoverflow.com/questions/31904396/swift-binary-search-for-standard-array +// + +import Foundation + +extension Collection { + + /// Generalized binary search algorithm for ordered Collections + /// + /// Behavior is undefined if the collection is not properly sorted. + /// + /// This is only O(logN) for RandomAccessCollections; Collections in + /// general may implement offsetting of indexes as an O(K) operation. (E.g., + /// Strings are like this). + /// + /// - Note: If you are using this for searching only (not insertion), you + /// must always test the element at the returned index to ensure that + /// it's a genuine match. If the element is not present in the array, + /// you will still get a valid index back that represents the location + /// where it should be inserted. Also check to be sure the returned + /// index isn't off the end of the collection. + /// + /// - Parameter predicate: Reports the ordering of a given Element relative + /// to the desired Element. Typically, this is <. + /// + /// - Returns: Index N such that the predicate is true for all elements up to + /// but not including N, and is false for all elements N and beyond + + func binarySearch(predicate: (Element) -> Bool) -> Index { + var low = startIndex + var high = endIndex + while low != high { + let mid = index(low, offsetBy: distance(from: low, to: high)/2) + if predicate(self[mid]) { + low = index(after: mid) + } else { + high = mid + } + } + return low + } + + /// Binary search lookup for ordered Collections using a KeyPath + /// relative to Element. + /// + /// Behavior is undefined if the collection is not properly sorted. + /// + /// This is only O(logN) for RandomAccessCollections; Collections in + /// general may implement offsetting of indexes as an O(K) operation. (E.g., + /// Strings are like this). + /// + /// - Note: If you are using this for searching only (not insertion), you + /// must always test the element at the returned index to ensure that + /// it's a genuine match. If the element is not present in the array, + /// you will still get a valid index back that represents the location + /// where it should be inserted. Also check to be sure the returned + /// index isn't off the end of the collection. + /// + /// - Parameter keyPath: KeyPath that extracts the Element value on which + /// the Collection is presorted. Must be Comparable and Equatable. + /// ordering is presumed to be <, however that is defined for the type. + /// + /// - Returns: The index of a matching element, or nil if not found. If + /// the return value is non-nil, it is always a valid index. + + func indexOfElement(withValue value: T, atKeyPath keyPath: KeyPath) -> Index? where T: Comparable & Equatable { + let ix = binarySearch { $0[keyPath: keyPath] < value } + guard ix < endIndex else { return nil } + guard self[ix][keyPath: keyPath] == value else { return nil } + return ix + } + + func element(withValue value: T, atKeyPath keyPath: KeyPath) -> Element? where T: Comparable & Equatable { + if let ix = indexOfElement(withValue: value, atKeyPath: keyPath) { + return self[ix] + } + return nil + } + + func elements(withValue value: T, atKeyPath keyPath: KeyPath) -> [Element] where T: Comparable & Equatable { + guard let start = indexOfElement(withValue: value, atKeyPath: keyPath) else { return [] } + var end = index(after: start) + while end < endIndex && self[end][keyPath: keyPath] == value { + end = index(after: end) + } + return Array(self[start.. Bool { + return true + } +} diff --git a/Swiftgram/SwiftSoup/Sources/CharacterExt.swift b/Swiftgram/SwiftSoup/Sources/CharacterExt.swift new file mode 100644 index 00000000..2cab2b56 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/CharacterExt.swift @@ -0,0 +1,81 @@ +// +// CharacterExt.swift +// SwifSoup +// +// Created by Nabil Chatbi on 08/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +extension Character { + + public static let space: Character = " " + public static let BackslashT: Character = "\t" + public static let BackslashN: Character = "\n" + public static let BackslashF: Character = Character(UnicodeScalar(12)) + public static let BackslashR: Character = "\r" + public static let BackshashRBackslashN: Character = "\r\n" + + //http://www.unicode.org/glossary/#supplementary_code_point + public static let MIN_SUPPLEMENTARY_CODE_POINT: UInt32 = 0x010000 + + /// True for any space character, and the control characters \t, \n, \r, \f, \v. + + var isWhitespace: Bool { + switch self { + case Character.space, Character.BackslashT, Character.BackslashN, Character.BackslashF, Character.BackslashR: return true + case Character.BackshashRBackslashN: return true + default: return false + + } + } + + /// `true` if `self` normalized contains a single code unit that is in the category of Decimal Numbers. + var isDigit: Bool { + + return isMemberOfCharacterSet(CharacterSet.decimalDigits) + + } + + /// Lowercase `self`. + var lowercase: Character { + + let str = String(self).lowercased() + return str[str.startIndex] + + } + + /// Return `true` if `self` normalized contains a single code unit that is a member of the supplied character set. + /// + /// - parameter set: The `NSCharacterSet` used to test for membership. + /// - returns: `true` if `self` normalized contains a single code unit that is a member of the supplied character set. + func isMemberOfCharacterSet(_ set: CharacterSet) -> Bool { + + let normalized = String(self).precomposedStringWithCanonicalMapping + let unicodes = normalized.unicodeScalars + + guard unicodes.count == 1 else { return false } + return set.contains(UnicodeScalar(unicodes.first!.value)!) + + } + + static func convertFromIntegerLiteral(value: IntegerLiteralType) -> Character { + return Character(UnicodeScalar(value)!) + } + + static func isLetter(_ char: Character) -> Bool { + return char.isLetter() + } + func isLetter() -> Bool { + return self.isMemberOfCharacterSet(CharacterSet.letters) + } + + static func isLetterOrDigit(_ char: Character) -> Bool { + return char.isLetterOrDigit() + } + func isLetterOrDigit() -> Bool { + if(self.isLetter()) {return true} + return self.isDigit + } +} diff --git a/Swiftgram/SwiftSoup/Sources/CharacterReader.swift b/Swiftgram/SwiftSoup/Sources/CharacterReader.swift new file mode 100644 index 00000000..d53c7950 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/CharacterReader.swift @@ -0,0 +1,320 @@ +// +// CharacterReader.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 10/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + CharacterReader consumes tokens off a string. To replace the old TokenQueue. + */ +public final class CharacterReader { + private static let empty = "" + public static let EOF: UnicodeScalar = "\u{FFFF}"//65535 + private let input: String.UnicodeScalarView + private var pos: String.UnicodeScalarView.Index + private var mark: String.UnicodeScalarView.Index + //private let stringCache: Array // holds reused strings in this doc, to lessen garbage + + public init(_ input: String) { + self.input = input.unicodeScalars + self.pos = input.startIndex + self.mark = input.startIndex + } + + public func getPos() -> Int { + return input.distance(from: input.startIndex, to: pos) + } + + public func isEmpty() -> Bool { + return pos >= input.endIndex + } + + public func current() -> UnicodeScalar { + return (pos >= input.endIndex) ? CharacterReader.EOF : input[pos] + } + + @discardableResult + public func consume() -> UnicodeScalar { + guard pos < input.endIndex else { + return CharacterReader.EOF + } + let val = input[pos] + pos = input.index(after: pos) + return val + } + + public func unconsume() { + guard pos > input.startIndex else { return } + pos = input.index(before: pos) + } + + public func advance() { + guard pos < input.endIndex else { return } + pos = input.index(after: pos) + } + + public func markPos() { + mark = pos + } + + public func rewindToMark() { + pos = mark + } + + public func consumeAsString() -> String { + guard pos < input.endIndex else { return "" } + let str = String(input[pos]) + pos = input.index(after: pos) + return str + } + + /** + * Locate the next occurrence of a Unicode scalar + * + * - Parameter c: scan target + * - Returns: offset between current position and next instance of target. -1 if not found. + */ + public func nextIndexOf(_ c: UnicodeScalar) -> String.UnicodeScalarView.Index? { + // doesn't handle scanning for surrogates + return input[pos...].firstIndex(of: c) + } + + /** + * Locate the next occurence of a target string + * + * - Parameter seq: scan target + * - Returns: index of next instance of target. nil if not found. + */ + public func nextIndexOf(_ seq: String) -> String.UnicodeScalarView.Index? { + // doesn't handle scanning for surrogates + var start = pos + let targetScalars = seq.unicodeScalars + guard let firstChar = targetScalars.first else { return pos } // search for "" -> current place + MATCH: while true { + // Match on first scalar + guard let firstCharIx = input[start...].firstIndex(of: firstChar) else { return nil } + var current = firstCharIx + // Then manually match subsequent scalars + for scalar in targetScalars.dropFirst() { + current = input.index(after: current) + guard current < input.endIndex else { return nil } + if input[current] != scalar { + start = input.index(after: firstCharIx) + continue MATCH + } + } + // full match; current is at position of last matching character + return firstCharIx + } + } + + public func consumeTo(_ c: UnicodeScalar) -> String { + guard let targetIx = nextIndexOf(c) else { + return consumeToEnd() + } + let consumed = cacheString(pos, targetIx) + pos = targetIx + return consumed + } + + public func consumeTo(_ seq: String) -> String { + guard let targetIx = nextIndexOf(seq) else { + return consumeToEnd() + } + let consumed = cacheString(pos, targetIx) + pos = targetIx + return consumed + } + + public func consumeToAny(_ chars: UnicodeScalar...) -> String { + return consumeToAny(chars) + } + + public func consumeToAny(_ chars: [UnicodeScalar]) -> String { + let start = pos + while pos < input.endIndex { + if chars.contains(input[pos]) { + break + } + pos = input.index(after: pos) + } + return cacheString(start, pos) + } + + public func consumeToAnySorted(_ chars: UnicodeScalar...) -> String { + return consumeToAny(chars) + } + + public func consumeToAnySorted(_ chars: [UnicodeScalar]) -> String { + return consumeToAny(chars) + } + + static let dataTerminators: [UnicodeScalar] = [.Ampersand, .LessThan, TokeniserStateVars.nullScalr] + // read to &, <, or null + public func consumeData() -> String { + return consumeToAny(CharacterReader.dataTerminators) + } + + static let tagNameTerminators: [UnicodeScalar] = [.BackslashT, .BackslashN, .BackslashR, .BackslashF, .Space, .Slash, .GreaterThan, TokeniserStateVars.nullScalr] + // read to '\t', '\n', '\r', '\f', ' ', '/', '>', or nullChar + public func consumeTagName() -> String { + return consumeToAny(CharacterReader.tagNameTerminators) + } + + public func consumeToEnd() -> String { + let consumed = cacheString(pos, input.endIndex) + pos = input.endIndex + return consumed + } + + public func consumeLetterSequence() -> String { + let start = pos + while pos < input.endIndex { + let c = input[pos] + if ((c >= "A" && c <= "Z") || (c >= "a" && c <= "z") || c.isMemberOfCharacterSet(CharacterSet.letters)) { + pos = input.index(after: pos) + } else { + break + } + } + return cacheString(start, pos) + } + + public func consumeLetterThenDigitSequence() -> String { + let start = pos + while pos < input.endIndex { + let c = input[pos] + if ((c >= "A" && c <= "Z") || (c >= "a" && c <= "z") || c.isMemberOfCharacterSet(CharacterSet.letters)) { + pos = input.index(after: pos) + } else { + break + } + } + while pos < input.endIndex { + let c = input[pos] + if (c >= "0" && c <= "9") { + pos = input.index(after: pos) + } else { + break + } + } + return cacheString(start, pos) + } + + public func consumeHexSequence() -> String { + let start = pos + while pos < input.endIndex { + let c = input[pos] + if ((c >= "0" && c <= "9") || (c >= "A" && c <= "F") || (c >= "a" && c <= "f")) { + pos = input.index(after: pos) + } else { + break + } + } + return cacheString(start, pos) + } + + public func consumeDigitSequence() -> String { + let start = pos + while pos < input.endIndex { + let c = input[pos] + if (c >= "0" && c <= "9") { + pos = input.index(after: pos) + } else { + break + } + } + return cacheString(start, pos) + } + + public func matches(_ c: UnicodeScalar) -> Bool { + return !isEmpty() && input[pos] == c + + } + + public func matches(_ seq: String, ignoreCase: Bool = false, consume: Bool = false) -> Bool { + var current = pos + let scalars = seq.unicodeScalars + for scalar in scalars { + guard current < input.endIndex else { return false } + if ignoreCase { + guard input[current].uppercase == scalar.uppercase else { return false } + } else { + guard input[current] == scalar else { return false } + } + current = input.index(after: current) + } + if consume { + pos = current + } + return true + } + + public func matchesIgnoreCase(_ seq: String ) -> Bool { + return matches(seq, ignoreCase: true) + } + + public func matchesAny(_ seq: UnicodeScalar...) -> Bool { + return matchesAny(seq) + } + + public func matchesAny(_ seq: [UnicodeScalar]) -> Bool { + guard pos < input.endIndex else { return false } + return seq.contains(input[pos]) + } + + public func matchesAnySorted(_ seq: [UnicodeScalar]) -> Bool { + return matchesAny(seq) + } + + public func matchesLetter() -> Bool { + guard pos < input.endIndex else { return false } + let c = input[pos] + return (c >= "A" && c <= "Z") || (c >= "a" && c <= "z") || c.isMemberOfCharacterSet(CharacterSet.letters) + } + + public func matchesDigit() -> Bool { + guard pos < input.endIndex else { return false } + let c = input[pos] + return c >= "0" && c <= "9" + } + + @discardableResult + public func matchConsume(_ seq: String) -> Bool { + return matches(seq, consume: true) + } + + @discardableResult + public func matchConsumeIgnoreCase(_ seq: String) -> Bool { + return matches(seq, ignoreCase: true, consume: true) + } + + public func containsIgnoreCase(_ seq: String ) -> Bool { + // used to check presence of , . only finds consistent case. + let loScan = seq.lowercased(with: Locale(identifier: "en")) + let hiScan = seq.uppercased(with: Locale(identifier: "eng")) + return nextIndexOf(loScan) != nil || nextIndexOf(hiScan) != nil + } + + public func toString() -> String { + return String(input[pos...]) + } + + /** + * Originally intended as a caching mechanism for strings, but caching doesn't + * seem to improve performance. Now just a stub. + */ + private func cacheString(_ start: String.UnicodeScalarView.Index, _ end: String.UnicodeScalarView.Index) -> String { + return String(input[start..` and `` using the supplied whitelist. + /// - Parameters: + /// - headWhitelist: Whitelist to clean the head with + /// - bodyWhitelist: Whitelist to clean the body with + public init(headWhitelist: Whitelist?, bodyWhitelist: Whitelist) { + self.headWhitelist = headWhitelist + self.bodyWhitelist = bodyWhitelist + } + + /// Create a new cleaner, that sanitizes documents' `` using the supplied whitelist. + /// - Parameter whitelist: Whitelist to clean the body with + convenience init(_ whitelist: Whitelist) { + self.init(headWhitelist: nil, bodyWhitelist: whitelist) + } + + /// Creates a new, clean document, from the original dirty document, containing only elements allowed by the whitelist. + /// The original document is not modified. Only elements from the dirt document's `` are used. + /// - Parameter dirtyDocument: Untrusted base document to clean. + /// - Returns: A cleaned document. + public func clean(_ dirtyDocument: Document) throws -> Document { + let clean = Document.createShell(dirtyDocument.getBaseUri()) + if let headWhitelist, let dirtHead = dirtyDocument.head(), let cleanHead = clean.head() { // frameset documents won't have a head. the clean doc will have empty head. + try copySafeNodes(dirtHead, cleanHead, whitelist: headWhitelist) + } + if let dirtBody = dirtyDocument.body(), let cleanBody = clean.body() { // frameset documents won't have a body. the clean doc will have empty body. + try copySafeNodes(dirtBody, cleanBody, whitelist: bodyWhitelist) + } + return clean + } + + /// Determines if the input document is valid, against the whitelist. It is considered valid if all the tags and attributes + /// in the input HTML are allowed by the whitelist. + /// + /// This method can be used as a validator for user input forms. An invalid document will still be cleaned successfully + /// using the ``clean(_:)`` document. If using as a validator, it is recommended to still clean the document + /// to ensure enforced attributes are set correctly, and that the output is tidied. + /// - Parameter dirtyDocument: document to test + /// - Returns: true if no tags or attributes need to be removed; false if they do + public func isValid(_ dirtyDocument: Document) throws -> Bool { + let clean = Document.createShell(dirtyDocument.getBaseUri()) + let numDiscarded = try copySafeNodes(dirtyDocument.body()!, clean.body()!, whitelist: bodyWhitelist) + return numDiscarded == 0 + } + + @discardableResult + fileprivate func copySafeNodes(_ source: Element, _ dest: Element, whitelist: Whitelist) throws -> Int { + let cleaningVisitor = Cleaner.CleaningVisitor(source, dest, whitelist) + try NodeTraversor(cleaningVisitor).traverse(source) + return cleaningVisitor.numDiscarded + } +} + +extension Cleaner { + fileprivate final class CleaningVisitor: NodeVisitor { + private(set) var numDiscarded = 0 + + private let root: Element + private var destination: Element? // current element to append nodes to + + private let whitelist: Whitelist + + public init(_ root: Element, _ destination: Element, _ whitelist: Whitelist) { + self.root = root + self.destination = destination + self.whitelist = whitelist + } + + public func head(_ source: Node, _ depth: Int) throws { + if let sourceEl = source as? Element { + if whitelist.isSafeTag(sourceEl.tagName()) { // safe, clone and copy safe attrs + let meta = try createSafeElement(sourceEl) + let destChild = meta.el + try destination?.appendChild(destChild) + + numDiscarded += meta.numAttribsDiscarded + destination = destChild + } else if source != root { // not a safe tag, so don't add. don't count root against discarded. + numDiscarded += 1 + } + } else if let sourceText = source as? TextNode { + let destText = TextNode(sourceText.getWholeText(), source.getBaseUri()) + try destination?.appendChild(destText) + } else if let sourceData = source as? DataNode { + if sourceData.parent() != nil && whitelist.isSafeTag(sourceData.parent()!.nodeName()) { + let destData = DataNode(sourceData.getWholeData(), source.getBaseUri()) + try destination?.appendChild(destData) + } else { + numDiscarded += 1 + } + } else { // else, we don't care about comments, xml proc instructions, etc + numDiscarded += 1 + } + } + + public func tail(_ source: Node, _ depth: Int) throws { + if let x = source as? Element { + if whitelist.isSafeTag(x.nodeName()) { + // would have descended, so pop destination stack + destination = destination?.parent() + } + } + } + + private func createSafeElement(_ sourceEl: Element) throws -> ElementMeta { + let sourceTag = sourceEl.tagName() + let destAttrs = Attributes() + var numDiscarded = 0 + + if let sourceAttrs = sourceEl.getAttributes() { + for sourceAttr in sourceAttrs { + if try whitelist.isSafeAttribute(sourceTag, sourceEl, sourceAttr) { + destAttrs.put(attribute: sourceAttr) + } else { + numDiscarded += 1 + } + } + } + let enforcedAttrs = try whitelist.getEnforcedAttributes(sourceTag) + destAttrs.addAll(incoming: enforcedAttrs) + + let dest = try Element(Tag.valueOf(sourceTag), sourceEl.getBaseUri(), destAttrs) + return ElementMeta(dest, numDiscarded) + } + } +} + +extension Cleaner { + fileprivate struct ElementMeta { + let el: Element + let numAttribsDiscarded: Int + + init(_ el: Element, _ numAttribsDiscarded: Int) { + self.el = el + self.numAttribsDiscarded = numAttribsDiscarded + } + } +} diff --git a/Swiftgram/SwiftSoup/Sources/Collector.swift b/Swiftgram/SwiftSoup/Sources/Collector.swift new file mode 100644 index 00000000..7bb6feb5 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/Collector.swift @@ -0,0 +1,59 @@ +// +// Collector.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 22/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * Collects a list of elements that match the supplied criteria. + * + */ +open class Collector { + + private init() { + } + + /** + Build a list of elements, by visiting root and every descendant of root, and testing it against the evaluator. + @param eval Evaluator to test elements against + @param root root of tree to descend + @return list of matches; empty if none + */ + public static func collect (_ eval: Evaluator, _ root: Element)throws->Elements { + let elements: Elements = Elements() + try NodeTraversor(Accumulator(root, elements, eval)).traverse(root) + return elements + } + +} + +private final class Accumulator: NodeVisitor { + private let root: Element + private let elements: Elements + private let eval: Evaluator + + init(_ root: Element, _ elements: Elements, _ eval: Evaluator) { + self.root = root + self.elements = elements + self.eval = eval + } + + public func head(_ node: Node, _ depth: Int) { + guard let el = node as? Element else { + return + } + do { + if try eval.matches(root, el) { + elements.add(el) + } + } catch {} + } + + public func tail(_ node: Node, _ depth: Int) { + // void + } +} diff --git a/Swiftgram/SwiftSoup/Sources/CombiningEvaluator.swift b/Swiftgram/SwiftSoup/Sources/CombiningEvaluator.swift new file mode 100644 index 00000000..fdeb0aeb --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/CombiningEvaluator.swift @@ -0,0 +1,127 @@ +// +// CombiningEvaluator.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 23/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * Base combining (and, or) evaluator. + */ +public class CombiningEvaluator: Evaluator { + + public private(set) var evaluators: Array + var num: Int = 0 + + public override init() { + evaluators = Array() + super.init() + } + + public init(_ evaluators: Array) { + self.evaluators = evaluators + super.init() + updateNumEvaluators() + } + + public init(_ evaluators: Evaluator...) { + self.evaluators = evaluators + super.init() + updateNumEvaluators() + } + + func rightMostEvaluator() -> Evaluator? { + return num > 0 && evaluators.count > 0 ? evaluators[num - 1] : nil + } + + func replaceRightMostEvaluator(_ replacement: Evaluator) { + evaluators[num - 1] = replacement + } + + func updateNumEvaluators() { + // used so we don't need to bash on size() for every match test + num = evaluators.count + } + + public final class And: CombiningEvaluator { + public override init(_ evaluators: [Evaluator]) { + super.init(evaluators) + } + + public override init(_ evaluators: Evaluator...) { + super.init(evaluators) + } + + public override func matches(_ root: Element, _ node: Element) -> Bool { + for index in 0.. String { + let array: [String] = evaluators.map { String($0.toString()) } + return StringUtil.join(array, sep: " ") + } + } + + public final class Or: CombiningEvaluator { + /** + * Create a new Or evaluator. The initial evaluators are ANDed together and used as the first clause of the OR. + * @param evaluators initial OR clause (these are wrapped into an AND evaluator). + */ + public override init(_ evaluators: [Evaluator]) { + super.init() + if num > 1 { + self.evaluators.append(And(evaluators)) + } else { // 0 or 1 + self.evaluators.append(contentsOf: evaluators) + } + updateNumEvaluators() + } + + override init(_ evaluators: Evaluator...) { + super.init() + if num > 1 { + self.evaluators.append(And(evaluators)) + } else { // 0 or 1 + self.evaluators.append(contentsOf: evaluators) + } + updateNumEvaluators() + } + + override init() { + super.init() + } + + public func add(_ evaluator: Evaluator) { + evaluators.append(evaluator) + updateNumEvaluators() + } + + public override func matches(_ root: Element, _ node: Element) -> Bool { + for index in 0.. String { + return ":or\(evaluators.map {String($0.toString())})" + } + } +} diff --git a/Swiftgram/SwiftSoup/Sources/Comment.swift b/Swiftgram/SwiftSoup/Sources/Comment.swift new file mode 100644 index 00000000..0892cad3 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/Comment.swift @@ -0,0 +1,66 @@ +// +// Comment.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 22/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + A comment node. + */ +public class Comment: Node { + private static let COMMENT_KEY: String = "comment" + + /** + Create a new comment node. + @param data The contents of the comment + @param baseUri base URI + */ + public init(_ data: String, _ baseUri: String) { + super.init(baseUri) + do { + try attributes?.put(Comment.COMMENT_KEY, data) + } catch {} + } + + public override func nodeName() -> String { + return "#comment" + } + + /** + Get the contents of the comment. + @return comment content + */ + public func getData() -> String { + return attributes!.get(key: Comment.COMMENT_KEY) + } + + override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) { + if (out.prettyPrint()) { + indent(accum, depth, out) + } + accum + .append("") + } + + override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {} + + public override func copy(with zone: NSZone? = nil) -> Any { + let clone = Comment(attributes!.get(key: Comment.COMMENT_KEY), baseUri!) + return copy(clone: clone) + } + + public override func copy(parent: Node?) -> Node { + let clone = Comment(attributes!.get(key: Comment.COMMENT_KEY), baseUri!) + return copy(clone: clone, parent: parent) + } + + public override func copy(clone: Node, parent: Node?) -> Node { + return super.copy(clone: clone, parent: parent) + } +} diff --git a/Swiftgram/SwiftSoup/Sources/Connection.swift b/Swiftgram/SwiftSoup/Sources/Connection.swift new file mode 100644 index 00000000..7b309a53 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/Connection.swift @@ -0,0 +1,10 @@ +// +// Connection.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation +//TODO: diff --git a/Swiftgram/SwiftSoup/Sources/CssSelector.swift b/Swiftgram/SwiftSoup/Sources/CssSelector.swift new file mode 100644 index 00000000..c8129220 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/CssSelector.swift @@ -0,0 +1,166 @@ +// +// CssSelector.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 21/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * CSS-like element selector, that finds elements matching a query. + * + *

CssSelector syntax

+ *

+ * A selector is a chain of simple selectors, separated by combinators. Selectors are case insensitive (including against + * elements, attributes, and attribute values). + *

+ *

+ * The universal selector (*) is implicit when no element selector is supplied (i.e. {@code *.header} and {@code .header} + * is equivalent). + *

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
PatternMatchesExample
*any element*
tagelements with the given tag namediv
*|Eelements of type E in any namespace ns*|name finds <fb:name> elements
ns|Eelements of type E in the namespace nsfb|name finds <fb:name> elements
#idelements with attribute ID of "id"div#wrap, #logo
.classelements with a class name of "class"div.left, .result
[attr]elements with an attribute named "attr" (with any value)a[href], [title]
[^attrPrefix]elements with an attribute name starting with "attrPrefix". Use to find elements with HTML5 datasets[^data-], div[^data-]
[attr=val]elements with an attribute named "attr", and value equal to "val"img[width=500], a[rel=nofollow]
[attr="val"]elements with an attribute named "attr", and value equal to "val"span[hello="Cleveland"][goodbye="Columbus"], a[rel="nofollow"]
[attr^=valPrefix]elements with an attribute named "attr", and value starting with "valPrefix"a[href^=http:]
[attr$=valSuffix]elements with an attribute named "attr", and value ending with "valSuffix"img[src$=.png]
[attr*=valContaining]elements with an attribute named "attr", and value containing "valContaining"a[href*=/search/]
[attr~=regex]elements with an attribute named "attr", and value matching the regular expressionimg[src~=(?i)\\.(png|jpe?g)]
The above may be combined in any orderdiv.header[title]

Combinators

E Fan F element descended from an E elementdiv a, .logo h1
E {@literal >} Fan F direct child of Eol {@literal >} li
E + Fan F element immediately preceded by sibling Eli + li, div.head + div
E ~ Fan F element preceded by sibling Eh1 ~ p
E, F, Gall matching elements E, F, or Ga[href], div, h3

Pseudo selectors

:lt(n)elements whose sibling index is less than ntd:lt(3) finds the first 3 cells of each row
:gt(n)elements whose sibling index is greater than ntd:gt(1) finds cells after skipping the first two
:eq(n)elements whose sibling index is equal to ntd:eq(0) finds the first cell of each row
:has(selector)elements that contains at least one element matching the selectordiv:has(p) finds divs that contain p elements
:not(selector)elements that do not match the selector. See also {@link Elements#not(String)}div:not(.logo) finds all divs that do not have the "logo" class.

div:not(:has(div)) finds divs that do not contain divs.

:contains(text)elements that contains the specified text. The search is case insensitive. The text may appear in the found element, or any of its descendants.p:contains(SwiftSoup) finds p elements containing the text "SwiftSoup".
:matches(regex)elements whose text matches the specified regular expression. The text may appear in the found element, or any of its descendants.td:matches(\\d+) finds table cells containing digits. div:matches((?i)login) finds divs containing the text, case insensitively.
:containsOwn(text)elements that directly contain the specified text. The search is case insensitive. The text must appear in the found element, not any of its descendants.p:containsOwn(SwiftSoup) finds p elements with own text "SwiftSoup".
:matchesOwn(regex)elements whose own text matches the specified regular expression. The text must appear in the found element, not any of its descendants.td:matchesOwn(\\d+) finds table cells directly containing digits. div:matchesOwn((?i)login) finds divs containing the text, case insensitively.
The above may be combined in any order and with other selectors.light:contains(name):eq(0)

Structural pseudo selectors

:rootThe element that is the root of the document. In HTML, this is the html element:root
:nth-child(an+b)

elements that have an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element. For values of a and b greater than zero, this effectively divides the element's children into groups of a elements (the last group taking the remainder), and selecting the bth element of each group. For example, this allows the selectors to address every other row in a table, and could be used to alternate the color of paragraph text in a cycle of four. The a and b values must be integers (positive, negative, or zero). The index of the first child of an element is 1.

+ * In addition to this, :nth-child() can take odd and even as arguments instead. odd has the same signification as 2n+1, and even has the same signification as 2n.
tr:nth-child(2n+1) finds every odd row of a table. :nth-child(10n-1) the 9th, 19th, 29th, etc, element. li:nth-child(5) the 5h li
:nth-last-child(an+b)elements that have an+b-1 siblings after it in the document tree. Otherwise like :nth-child()tr:nth-last-child(-n+2) the last two rows of a table
:nth-of-type(an+b)pseudo-class notation represents an element that has an+b-1 siblings with the same expanded element name before it in the document tree, for any zero or positive integer value of n, and has a parent elementimg:nth-of-type(2n+1)
:nth-last-of-type(an+b)pseudo-class notation represents an element that has an+b-1 siblings with the same expanded element name after it in the document tree, for any zero or positive integer value of n, and has a parent elementimg:nth-last-of-type(2n+1)
:first-childelements that are the first child of some other element.div {@literal >} p:first-child
:last-childelements that are the last child of some other element.ol {@literal >} li:last-child
:first-of-typeelements that are the first sibling of its type in the list of children of its parent elementdl dt:first-of-type
:last-of-typeelements that are the last sibling of its type in the list of children of its parent elementtr {@literal >} td:last-of-type
:only-childelements that have a parent element and whose parent element hasve no other element children
:only-of-type an element that has a parent element and whose parent element has no other element children with the same expanded element name
:emptyelements that have no children at all
+ * + * @see Element#select(String) + */ +@available(*, deprecated, renamed: "CssSelector") +typealias Selector = CssSelector + +open class CssSelector { + private let evaluator: Evaluator + private let root: Element + + private init(_ query: String, _ root: Element)throws { + let query = query.trim() + try Validate.notEmpty(string: query) + + self.evaluator = try QueryParser.parse(query) + + self.root = root + } + + private init(_ evaluator: Evaluator, _ root: Element) { + self.evaluator = evaluator + self.root = root + } + + /** + * Find elements matching selector. + * + * @param query CSS selector + * @param root root element to descend into + * @return matching elements, empty if none + * @throws CssSelector.SelectorParseException (unchecked) on an invalid CSS query. + */ + public static func select(_ query: String, _ root: Element)throws->Elements { + return try CssSelector(query, root).select() + } + + /** + * Find elements matching selector. + * + * @param evaluator CSS selector + * @param root root element to descend into + * @return matching elements, empty if none + */ + public static func select(_ evaluator: Evaluator, _ root: Element)throws->Elements { + return try CssSelector(evaluator, root).select() + } + + /** + * Find elements matching selector. + * + * @param query CSS selector + * @param roots root elements to descend into + * @return matching elements, empty if none + */ + public static func select(_ query: String, _ roots: Array)throws->Elements { + try Validate.notEmpty(string: query) + let evaluator: Evaluator = try QueryParser.parse(query) + var elements: Array = Array() + var seenElements: Array = Array() + // dedupe elements by identity, not equality + + for root: Element in roots { + let found: Elements = try select(evaluator, root) + for el: Element in found.array() { + if (!seenElements.contains(el)) { + elements.append(el) + seenElements.append(el) + } + } + } + return Elements(elements) + } + + private func select()throws->Elements { + return try Collector.collect(evaluator, root) + } + + // exclude set. package open so that Elements can implement .not() selector. + static func filterOut(_ elements: Array, _ outs: Array) -> Elements { + let output: Elements = Elements() + for el: Element in elements { + var found: Bool = false + for out: Element in outs { + if (el.equals(out)) { + found = true + break + } + } + if (!found) { + output.add(el) + } + } + return output + } +} diff --git a/Swiftgram/SwiftSoup/Sources/DataNode.swift b/Swiftgram/SwiftSoup/Sources/DataNode.swift new file mode 100644 index 00000000..37f7199f --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/DataNode.swift @@ -0,0 +1,85 @@ +// +// DataNode.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + A data node, for contents of style, script tags etc, where contents should not show in text(). + */ +open class DataNode: Node { + private static let DATA_KEY: String = "data" + + /** + Create a new DataNode. + @param data data contents + @param baseUri base URI + */ + public init(_ data: String, _ baseUri: String) { + super.init(baseUri) + do { + try attributes?.put(DataNode.DATA_KEY, data) + } catch {} + + } + + open override func nodeName() -> String { + return "#data" + } + + /** + Get the data contents of this node. Will be unescaped and with original new lines, space etc. + @return data + */ + open func getWholeData() -> String { + return attributes!.get(key: DataNode.DATA_KEY) + } + + /** + * Set the data contents of this node. + * @param data unencoded data + * @return this node, for chaining + */ + @discardableResult + open func setWholeData(_ data: String) -> DataNode { + do { + try attributes?.put(DataNode.DATA_KEY, data) + } catch {} + return self + } + + override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings)throws { + accum.append(getWholeData()) // data is not escaped in return from data nodes, so " in script, style is plain + } + + override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {} + + /** + Create a new DataNode from HTML encoded data. + @param encodedData encoded data + @param baseUri bass URI + @return new DataNode + */ + public static func createFromEncoded(_ encodedData: String, _ baseUri: String)throws->DataNode { + let data = try Entities.unescape(encodedData) + return DataNode(data, baseUri) + } + + public override func copy(with zone: NSZone? = nil) -> Any { + let clone = DataNode(attributes!.get(key: DataNode.DATA_KEY), baseUri!) + return copy(clone: clone) + } + + public override func copy(parent: Node?) -> Node { + let clone = DataNode(attributes!.get(key: DataNode.DATA_KEY), baseUri!) + return copy(clone: clone, parent: parent) + } + + public override func copy(clone: Node, parent: Node?) -> Node { + return super.copy(clone: clone, parent: parent) + } +} diff --git a/Swiftgram/SwiftSoup/Sources/DataUtil.swift b/Swiftgram/SwiftSoup/Sources/DataUtil.swift new file mode 100644 index 00000000..f2d0deec --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/DataUtil.swift @@ -0,0 +1,24 @@ +// +// DataUtil.swift +// SwifSoup +// +// Created by Nabil Chatbi on 02/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * Internal static utilities for handling data. + * + */ +class DataUtil { + + static let charsetPattern = "(?i)\\bcharset=\\s*(?:\"|')?([^\\s,;\"']*)" + static let defaultCharset = "UTF-8" // used if not found in header or meta charset + static let bufferSize = 0x20000 // ~130K. + static let UNICODE_BOM = 0xFEFF + static let mimeBoundaryChars = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + static let boundaryLength = 32 + +} diff --git a/Swiftgram/SwiftSoup/Sources/Document.swift b/Swiftgram/SwiftSoup/Sources/Document.swift new file mode 100644 index 00000000..12e29cb5 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/Document.swift @@ -0,0 +1,562 @@ +// +// Document.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +open class Document: Element { + public enum QuirksMode { + case noQuirks, quirks, limitedQuirks + } + + private var _outputSettings: OutputSettings = OutputSettings() + private var _quirksMode: Document.QuirksMode = QuirksMode.noQuirks + private let _location: String + private var updateMetaCharset: Bool = false + + /** + Create a new, empty Document. + @param baseUri base URI of document + @see SwiftSoup#parse + @see #createShell + */ + public init(_ baseUri: String) { + self._location = baseUri + super.init(try! Tag.valueOf("#root", ParseSettings.htmlDefault), baseUri) + } + + /** + Create a valid, empty shell of a document, suitable for adding more elements to. + @param baseUri baseUri of document + @return document with html, head, and body elements. + */ + static public func createShell(_ baseUri: String) -> Document { + let doc: Document = Document(baseUri) + let html: Element = try! doc.appendElement("html") + try! html.appendElement("head") + try! html.appendElement("body") + + return doc + } + + /** + * Get the URL this Document was parsed from. If the starting URL is a redirect, + * this will return the final URL from which the document was served from. + * @return location + */ + public func location() -> String { + return _location + } + + /** + Accessor to the document's {@code head} element. + @return {@code head} + */ + public func head() -> Element? { + return findFirstElementByTagName("head", self) + } + + /** + Accessor to the document's {@code body} element. + @return {@code body} + */ + public func body() -> Element? { + return findFirstElementByTagName("body", self) + } + + /** + Get the string contents of the document's {@code title} element. + @return Trimmed title, or empty string if none set. + */ + public func title()throws->String { + // title is a preserve whitespace tag (for document output), but normalised here + let titleEl: Element? = try getElementsByTag("title").first() + return titleEl != nil ? try StringUtil.normaliseWhitespace(titleEl!.text()).trim() : "" + } + + /** + Set the document's {@code title} element. Updates the existing element, or adds {@code title} to {@code head} if + not present + @param title string to set as title + */ + public func title(_ title: String)throws { + let titleEl: Element? = try getElementsByTag("title").first() + if (titleEl == nil) { // add to head + try head()?.appendElement("title").text(title) + } else { + try titleEl?.text(title) + } + } + + /** + Create a new Element, with this document's base uri. Does not make the new element a child of this document. + @param tagName element tag name (e.g. {@code a}) + @return new element + */ + public func createElement(_ tagName: String)throws->Element { + return try Element(Tag.valueOf(tagName, ParseSettings.preserveCase), self.getBaseUri()) + } + + /** + Normalise the document. This happens after the parse phase so generally does not need to be called. + Moves any text content that is not in the body element into the body. + @return this document after normalisation + */ + @discardableResult + public func normalise()throws->Document { + var htmlE: Element? = findFirstElementByTagName("html", self) + if (htmlE == nil) { + htmlE = try appendElement("html") + } + let htmlEl: Element = htmlE! + + if (head() == nil) { + try htmlEl.prependElement("head") + } + if (body() == nil) { + try htmlEl.appendElement("body") + } + + // pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care + // of. do in inverse order to maintain text order. + try normaliseTextNodes(head()!) + try normaliseTextNodes(htmlEl) + try normaliseTextNodes(self) + + try normaliseStructure("head", htmlEl) + try normaliseStructure("body", htmlEl) + + try ensureMetaCharsetElement() + + return self + } + + // does not recurse. + private func normaliseTextNodes(_ element: Element)throws { + var toMove: Array = Array() + for node: Node in element.childNodes { + if let tn = (node as? TextNode) { + if (!tn.isBlank()) { + toMove.append(tn) + } + } + } + + for i in (0.. or contents into one, delete the remainder, and ensure they are owned by + private func normaliseStructure(_ tag: String, _ htmlEl: Element)throws { + let elements: Elements = try self.getElementsByTag(tag) + let master: Element? = elements.first() // will always be available as created above if not existent + if (elements.size() > 1) { // dupes, move contents to master + var toMove: Array = Array() + for i in 1.. + if (!(master != nil && master!.parent() != nil && master!.parent()!.equals(htmlEl))) { + try htmlEl.appendChild(master!) // includes remove() + } + } + + // fast method to get first by tag name, used for html, head, body finders + private func findFirstElementByTagName(_ tag: String, _ node: Node) -> Element? { + if (node.nodeName()==tag) { + return node as? Element + } else { + for child: Node in node.childNodes { + let found: Element? = findFirstElementByTagName(tag, child) + if (found != nil) { + return found + } + } + } + return nil + } + + open override func outerHtml()throws->String { + return try super.html() // no outer wrapper tag + } + + /** + Set the text of the {@code body} of this document. Any existing nodes within the body will be cleared. + @param text unencoded text + @return this document + */ + @discardableResult + public override func text(_ text: String)throws->Element { + try body()?.text(text) // overridden to not nuke doc structure + return self + } + + open override func nodeName() -> String { + return "#document" + } + + /** + * Sets the charset used in this document. This method is equivalent + * to {@link OutputSettings#charset(java.nio.charset.Charset) + * OutputSettings.charset(Charset)} but in addition it updates the + * charset / encoding element within the document. + * + *

This enables + * {@link #updateMetaCharsetElement(boolean) meta charset update}.

+ * + *

If there's no element with charset / encoding information yet it will + * be created. Obsolete charset / encoding definitions are removed!

+ * + *

Elements used:

+ * + *
    + *
  • Html: <meta charset="CHARSET">
  • + *
  • Xml: <?xml version="1.0" encoding="CHARSET">
  • + *
+ * + * @param charset Charset + * + * @see #updateMetaCharsetElement(boolean) + * @see OutputSettings#charset(java.nio.charset.Charset) + */ + public func charset(_ charset: String.Encoding)throws { + updateMetaCharsetElement(true) + _outputSettings.charset(charset) + try ensureMetaCharsetElement() + } + + /** + * Returns the charset used in this document. This method is equivalent + * to {@link OutputSettings#charset()}. + * + * @return Current Charset + * + * @see OutputSettings#charset() + */ + public func charset()->String.Encoding { + return _outputSettings.charset() + } + + /** + * Sets whether the element with charset information in this document is + * updated on changes through {@link #charset(java.nio.charset.Charset) + * Document.charset(Charset)} or not. + * + *

If set to false (default) there are no elements + * modified.

+ * + * @param update If true the element updated on charset + * changes, false if not + * + * @see #charset(java.nio.charset.Charset) + */ + public func updateMetaCharsetElement(_ update: Bool) { + self.updateMetaCharset = update + } + + /** + * Returns whether the element with charset information in this document is + * updated on changes through {@link #charset(java.nio.charset.Charset) + * Document.charset(Charset)} or not. + * + * @return Returns true if the element is updated on charset + * changes, false if not + */ + public func updateMetaCharsetElement() -> Bool { + return updateMetaCharset + } + + /** + * Ensures a meta charset (html) or xml declaration (xml) with the current + * encoding used. This only applies with + * {@link #updateMetaCharsetElement(boolean) updateMetaCharset} set to + * true, otherwise this method does nothing. + * + *
    + *
  • An exsiting element gets updated with the current charset
  • + *
  • If there's no element yet it will be inserted
  • + *
  • Obsolete elements are removed
  • + *
+ * + *

Elements used:

+ * + *
    + *
  • Html: <meta charset="CHARSET">
  • + *
  • Xml: <?xml version="1.0" encoding="CHARSET">
  • + *
+ */ + private func ensureMetaCharsetElement()throws { + if (updateMetaCharset) { + let syntax: OutputSettings.Syntax = outputSettings().syntax() + + if (syntax == OutputSettings.Syntax.html) { + let metaCharset: Element? = try select("meta[charset]").first() + + if (metaCharset != nil) { + try metaCharset?.attr("charset", charset().displayName()) + } else { + let head: Element? = self.head() + + if (head != nil) { + try head?.appendElement("meta").attr("charset", charset().displayName()) + } + } + + // Remove obsolete elements + let s = try select("meta[name=charset]") + try s.remove() + + } else if (syntax == OutputSettings.Syntax.xml) { + let node: Node = getChildNodes()[0] + + if let decl = (node as? XmlDeclaration) { + + if (decl.name()=="xml") { + try decl.attr("encoding", charset().displayName()) + + _ = try decl.attr("version") + try decl.attr("version", "1.0") + } else { + try Validate.notNull(obj: baseUri) + let decl = XmlDeclaration("xml", baseUri!, false) + try decl.attr("version", "1.0") + try decl.attr("encoding", charset().displayName()) + + try prependChild(decl) + } + } else { + try Validate.notNull(obj: baseUri) + let decl = XmlDeclaration("xml", baseUri!, false) + try decl.attr("version", "1.0") + try decl.attr("encoding", charset().displayName()) + + try prependChild(decl) + } + } + } + } + + /** + * Get the document's current output settings. + * @return the document's current output settings. + */ + public func outputSettings() -> OutputSettings { + return _outputSettings + } + + /** + * Set the document's output settings. + * @param outputSettings new output settings. + * @return this document, for chaining. + */ + @discardableResult + public func outputSettings(_ outputSettings: OutputSettings) -> Document { + self._outputSettings = outputSettings + return self + } + + public func quirksMode()->Document.QuirksMode { + return _quirksMode + } + + @discardableResult + public func quirksMode(_ quirksMode: Document.QuirksMode) -> Document { + self._quirksMode = quirksMode + return self + } + + public override func copy(with zone: NSZone? = nil) -> Any { + let clone = Document(_location) + return copy(clone: clone) + } + + public override func copy(parent: Node?) -> Node { + let clone = Document(_location) + return copy(clone: clone, parent: parent) + } + + public override func copy(clone: Node, parent: Node?) -> Node { + let clone = clone as! Document + clone._outputSettings = _outputSettings.copy() as! OutputSettings + clone._quirksMode = _quirksMode + clone.updateMetaCharset = updateMetaCharset + return super.copy(clone: clone, parent: parent) + } + +} + +public class OutputSettings: NSCopying { + /** + * The output serialization syntax. + */ + public enum Syntax {case html, xml} + + private var _escapeMode: Entities.EscapeMode = Entities.EscapeMode.base + private var _encoder: String.Encoding = String.Encoding.utf8 // Charset.forName("UTF-8") + private var _prettyPrint: Bool = true + private var _outline: Bool = false + private var _indentAmount: UInt = 1 + private var _syntax = Syntax.html + + public init() {} + + /** + * Get the document's current HTML escape mode: base, which provides a limited set of named HTML + * entities and escapes other characters as numbered entities for maximum compatibility; or extended, + * which uses the complete set of HTML named entities. + *

+ * The default escape mode is base. + * @return the document's current escape mode + */ + public func escapeMode() -> Entities.EscapeMode { + return _escapeMode + } + + /** + * Set the document's escape mode, which determines how characters are escaped when the output character set + * does not support a given character:- using either a named or a numbered escape. + * @param escapeMode the new escape mode to use + * @return the document's output settings, for chaining + */ + @discardableResult + public func escapeMode(_ escapeMode: Entities.EscapeMode) -> OutputSettings { + self._escapeMode = escapeMode + return self + } + + /** + * Get the document's current output charset, which is used to control which characters are escaped when + * generating HTML (via the html() methods), and which are kept intact. + *

+ * Where possible (when parsing from a URL or File), the document's output charset is automatically set to the + * input charset. Otherwise, it defaults to UTF-8. + * @return the document's current charset. + */ + public func encoder() -> String.Encoding { + return _encoder + } + public func charset() -> String.Encoding { + return _encoder + } + + /** + * Update the document's output charset. + * @param charset the new charset to use. + * @return the document's output settings, for chaining + */ + @discardableResult + public func encoder(_ encoder: String.Encoding) -> OutputSettings { + self._encoder = encoder + return self + } + + @discardableResult + public func charset(_ e: String.Encoding) -> OutputSettings { + return encoder(e) + } + + /** + * Get the document's current output syntax. + * @return current syntax + */ + public func syntax() -> Syntax { + return _syntax + } + + /** + * Set the document's output syntax. Either {@code html}, with empty tags and boolean attributes (etc), or + * {@code xml}, with self-closing tags. + * @param syntax serialization syntax + * @return the document's output settings, for chaining + */ + @discardableResult + public func syntax(syntax: Syntax) -> OutputSettings { + _syntax = syntax + return self + } + + /** + * Get if pretty printing is enabled. Default is true. If disabled, the HTML output methods will not re-format + * the output, and the output will generally look like the input. + * @return if pretty printing is enabled. + */ + public func prettyPrint() -> Bool { + return _prettyPrint + } + + /** + * Enable or disable pretty printing. + * @param pretty new pretty print setting + * @return this, for chaining + */ + @discardableResult + public func prettyPrint(pretty: Bool) -> OutputSettings { + _prettyPrint = pretty + return self + } + + /** + * Get if outline mode is enabled. Default is false. If enabled, the HTML output methods will consider + * all tags as block. + * @return if outline mode is enabled. + */ + public func outline() -> Bool { + return _outline + } + + /** + * Enable or disable HTML outline mode. + * @param outlineMode new outline setting + * @return this, for chaining + */ + @discardableResult + public func outline(outlineMode: Bool) -> OutputSettings { + _outline = outlineMode + return self + } + + /** + * Get the current tag indent amount, used when pretty printing. + * @return the current indent amount + */ + public func indentAmount() -> UInt { + return _indentAmount + } + + /** + * Set the indent amount for pretty printing + * @param indentAmount number of spaces to use for indenting each level. Must be {@literal >=} 0. + * @return this, for chaining + */ + @discardableResult + public func indentAmount(indentAmount: UInt) -> OutputSettings { + _indentAmount = indentAmount + return self + } + + public func copy(with zone: NSZone? = nil) -> Any { + let clone: OutputSettings = OutputSettings() + clone.charset(_encoder) // new charset and charset encoder + clone._escapeMode = _escapeMode//Entities.EscapeMode.valueOf(escapeMode.name()) + // indentAmount, prettyPrint are primitives so object.clone() will handle + return clone + } + +} diff --git a/Swiftgram/SwiftSoup/Sources/DocumentType.swift b/Swiftgram/SwiftSoup/Sources/DocumentType.swift new file mode 100644 index 00000000..95f9b10d --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/DocumentType.swift @@ -0,0 +1,129 @@ +// +// DocumentType.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * A {@code } node. + */ +public class DocumentType: Node { + static let PUBLIC_KEY: String = "PUBLIC" + static let SYSTEM_KEY: String = "SYSTEM" + private static let NAME: String = "name" + private static let PUB_SYS_KEY: String = "pubSysKey"; // PUBLIC or SYSTEM + private static let PUBLIC_ID: String = "publicId" + private static let SYSTEM_ID: String = "systemId" + // todo: quirk mode from publicId and systemId + + /** + * Create a new doctype element. + * @param name the doctype's name + * @param publicId the doctype's public ID + * @param systemId the doctype's system ID + * @param baseUri the doctype's base URI + */ + public init(_ name: String, _ publicId: String, _ systemId: String, _ baseUri: String) { + super.init(baseUri) + do { + try attr(DocumentType.NAME, name) + try attr(DocumentType.PUBLIC_ID, publicId) + if (has(DocumentType.PUBLIC_ID)) { + try attr(DocumentType.PUB_SYS_KEY, DocumentType.PUBLIC_KEY) + } + try attr(DocumentType.SYSTEM_ID, systemId) + } catch {} + } + + /** + * Create a new doctype element. + * @param name the doctype's name + * @param publicId the doctype's public ID + * @param systemId the doctype's system ID + * @param baseUri the doctype's base URI + */ + public init(_ name: String, _ pubSysKey: String?, _ publicId: String, _ systemId: String, _ baseUri: String) { + super.init(baseUri) + do { + try attr(DocumentType.NAME, name) + if(pubSysKey != nil) { + try attr(DocumentType.PUB_SYS_KEY, pubSysKey!) + } + try attr(DocumentType.PUBLIC_ID, publicId) + try attr(DocumentType.SYSTEM_ID, systemId) + } catch {} + } + + public override func nodeName() -> String { + return "#doctype" + } + + override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) { + if (out.syntax() == OutputSettings.Syntax.html && !has(DocumentType.PUBLIC_ID) && !has(DocumentType.SYSTEM_ID)) { + // looks like a html5 doctype, go lowercase for aesthetics + accum.append("") + } + + override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) { + } + + private func has(_ attribute: String) -> Bool { + do { + return !StringUtil.isBlank(try attr(attribute)) + } catch {return false} + } + + public override func copy(with zone: NSZone? = nil) -> Any { + let clone = DocumentType(attributes!.get(key: DocumentType.NAME), + attributes!.get(key: DocumentType.PUBLIC_ID), + attributes!.get(key: DocumentType.SYSTEM_ID), + baseUri!) + return copy(clone: clone) + } + + public override func copy(parent: Node?) -> Node { + let clone = DocumentType(attributes!.get(key: DocumentType.NAME), + attributes!.get(key: DocumentType.PUBLIC_ID), + attributes!.get(key: DocumentType.SYSTEM_ID), + baseUri!) + return copy(clone: clone, parent: parent) + } + + public override func copy(clone: Node, parent: Node?) -> Node { + return super.copy(clone: clone, parent: parent) + } + +} diff --git a/Swiftgram/SwiftSoup/Sources/Element.swift b/Swiftgram/SwiftSoup/Sources/Element.swift new file mode 100644 index 00000000..630b9914 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/Element.swift @@ -0,0 +1,1316 @@ +// +// Element.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +open class Element: Node { + var _tag: Tag + + private static let classString = "class" + private static let emptyString = "" + private static let idString = "id" + private static let rootString = "#root" + + //private static let classSplit : Pattern = Pattern("\\s+") + private static let classSplit = "\\s+" + + /** + * Create a new, standalone Element. (Standalone in that is has no parent.) + * + * @param tag tag of this element + * @param baseUri the base URI + * @param attributes initial attributes + * @see #appendChild(Node) + * @see #appendElement(String) + */ + public init(_ tag: Tag, _ baseUri: String, _ attributes: Attributes) { + self._tag = tag + super.init(baseUri, attributes) + } + /** + * Create a new Element from a tag and a base URI. + * + * @param tag element tag + * @param baseUri the base URI of this element. It is acceptable for the base URI to be an empty + * string, but not null. + * @see Tag#valueOf(String, ParseSettings) + */ + public init(_ tag: Tag, _ baseUri: String) { + self._tag = tag + super.init(baseUri, Attributes()) + } + + open override func nodeName() -> String { + return _tag.getName() + } + /** + * Get the name of the tag for this element. E.g. {@code div} + * + * @return the tag name + */ + open func tagName() -> String { + return _tag.getName() + } + open func tagNameNormal() -> String { + return _tag.getNameNormal() + } + + /** + * Change the tag of this element. For example, convert a {@code } to a {@code

} with + * {@code el.tagName("div")}. + * + * @param tagName new tag name for this element + * @return this element, for chaining + */ + @discardableResult + public func tagName(_ tagName: String)throws->Element { + try Validate.notEmpty(string: tagName, msg: "Tag name must not be empty.") + _tag = try Tag.valueOf(tagName, ParseSettings.preserveCase) // preserve the requested tag case + return self + } + + /** + * Get the Tag for this element. + * + * @return the tag object + */ + open func tag() -> Tag { + return _tag + } + + /** + * Test if this element is a block-level element. (E.g. {@code
== true} or an inline element + * {@code

== false}). + * + * @return true if block, false if not (and thus inline) + */ + open func isBlock() -> Bool { + return _tag.isBlock() + } + + /** + * Get the {@code id} attribute of this element. + * + * @return The id attribute, if present, or an empty string if not. + */ + open func id() -> String { + guard let attributes = attributes else {return Element.emptyString} + do { + return try attributes.getIgnoreCase(key: Element.idString) + } catch {} + return Element.emptyString + } + + /** + * Set an attribute value on this element. If this element already has an attribute with the + * key, its value is updated; otherwise, a new attribute is added. + * + * @return this element + */ + @discardableResult + open override func attr(_ attributeKey: String, _ attributeValue: String)throws->Element { + try super.attr(attributeKey, attributeValue) + return self + } + + /** + * Set a boolean attribute value on this element. Setting to true sets the attribute value to "" and + * marks the attribute as boolean so no value is written out. Setting to false removes the attribute + * with the same key if it exists. + * + * @param attributeKey the attribute key + * @param attributeValue the attribute value + * + * @return this element + */ + @discardableResult + open func attr(_ attributeKey: String, _ attributeValue: Bool)throws->Element { + try attributes?.put(attributeKey, attributeValue) + return self + } + + /** + * Get this element's HTML5 custom data attributes. Each attribute in the element that has a key + * starting with "data-" is included the dataset. + *

+ * E.g., the element {@code

...} has the dataset + * {@code package=SwiftSoup, language=java}. + *

+ * This map is a filtered view of the element's attribute map. Changes to one map (add, remove, update) are reflected + * in the other map. + *

+ * You can find elements that have data attributes using the {@code [^data-]} attribute key prefix selector. + * @return a map of {@code key=value} custom data attributes. + */ + open func dataset()->Dictionary { + return attributes!.dataset() + } + + open override func parent() -> Element? { + return parentNode as? Element + } + + /** + * Get this element's parent and ancestors, up to the document root. + * @return this element's stack of parents, closest first. + */ + open func parents() -> Elements { + let parents: Elements = Elements() + Element.accumulateParents(self, parents) + return parents + } + + private static func accumulateParents(_ el: Element, _ parents: Elements) { + let parent: Element? = el.parent() + if (parent != nil && !(parent!.tagName() == Element.rootString)) { + parents.add(parent!) + accumulateParents(parent!, parents) + } + } + + /** + * Get a child element of this element, by its 0-based index number. + *

+ * Note that an element can have both mixed Nodes and Elements as children. This method inspects + * a filtered list of children that are elements, and the index is based on that filtered list. + *

+ * + * @param index the index number of the element to retrieve + * @return the child element, if it exists, otherwise throws an {@code IndexOutOfBoundsException} + * @see #childNode(int) + */ + open func child(_ index: Int) -> Element { + return children().get(index) + } + + /** + * Get this element's child elements. + *

+ * This is effectively a filter on {@link #childNodes()} to get Element nodes. + *

+ * @return child elements. If this element has no children, returns an + * empty list. + * @see #childNodes() + */ + open func children() -> Elements { + // create on the fly rather than maintaining two lists. if gets slow, memoize, and mark dirty on change + var elements = Array() + for node in childNodes { + if let n = node as? Element { + elements.append(n) + } + } + return Elements(elements) + } + + /** + * Get this element's child text nodes. The list is unmodifiable but the text nodes may be manipulated. + *

+ * This is effectively a filter on {@link #childNodes()} to get Text nodes. + * @return child text nodes. If this element has no text nodes, returns an + * empty list. + *

+ * For example, with the input HTML: {@code

One Two Three
Four

} with the {@code p} element selected: + *
    + *
  • {@code p.text()} = {@code "One Two Three Four"}
  • + *
  • {@code p.ownText()} = {@code "One Three Four"}
  • + *
  • {@code p.children()} = {@code Elements[,
    ]}
  • + *
  • {@code p.childNodes()} = {@code List["One ", , " Three ",
    , " Four"]}
  • + *
  • {@code p.textNodes()} = {@code List["One ", " Three ", " Four"]}
  • + *
+ */ + open func textNodes()->Array { + var textNodes = Array() + for node in childNodes { + if let n = node as? TextNode { + textNodes.append(n) + } + } + return textNodes + } + + /** + * Get this element's child data nodes. The list is unmodifiable but the data nodes may be manipulated. + *

+ * This is effectively a filter on {@link #childNodes()} to get Data nodes. + *

+ * @return child data nodes. If this element has no data nodes, returns an + * empty list. + * @see #data() + */ + open func dataNodes()->Array { + var dataNodes = Array() + for node in childNodes { + if let n = node as? DataNode { + dataNodes.append(n) + } + } + return dataNodes + } + + /** + * Find elements that match the {@link CssSelector} CSS query, with this element as the starting context. Matched elements + * may include this element, or any of its children. + *

+ * This method is generally more powerful to use than the DOM-type {@code getElementBy*} methods, because + * multiple filters can be combined, e.g.: + *

+ *
    + *
  • {@code el.select("a[href]")} - finds links ({@code a} tags with {@code href} attributes) + *
  • {@code el.select("a[href*=example.com]")} - finds links pointing to example.com (loosely) + *
+ *

+ * See the query syntax documentation in {@link CssSelector}. + *

+ * + * @param cssQuery a {@link CssSelector} CSS-like query + * @return elements that match the query (empty if none match) + * @see CssSelector + * @throws CssSelector.SelectorParseException (unchecked) on an invalid CSS query. + */ + public func select(_ cssQuery: String)throws->Elements { + return try CssSelector.select(cssQuery, self) + } + + /** + * Check if this element matches the given {@link CssSelector} CSS query. + * @param cssQuery a {@link CssSelector} CSS query + * @return if this element matches the query + */ + public func iS(_ cssQuery: String)throws->Bool { + return try iS(QueryParser.parse(cssQuery)) + } + + /** + * Check if this element matches the given {@link CssSelector} CSS query. + * @param cssQuery a {@link CssSelector} CSS query + * @return if this element matches the query + */ + public func iS(_ evaluator: Evaluator)throws->Bool { + guard let od = self.ownerDocument() else { + return false + } + return try evaluator.matches(od, self) + } + + /** + * Add a node child node to this element. + * + * @param child node to add. + * @return this element, so that you can add more child nodes or elements. + */ + @discardableResult + public func appendChild(_ child: Node)throws->Element { + // was - Node#addChildren(child). short-circuits an array create and a loop. + try reparentChild(child) + ensureChildNodes() + childNodes.append(child) + child.setSiblingIndex(childNodes.count - 1) + return self + } + + /** + * Add a node to the start of this element's children. + * + * @param child node to add. + * @return this element, so that you can add more child nodes or elements. + */ + @discardableResult + public func prependChild(_ child: Node)throws->Element { + try addChildren(0, child) + return self + } + + /** + * Inserts the given child nodes into this element at the specified index. Current nodes will be shifted to the + * right. The inserted nodes will be moved from their current parent. To prevent moving, copy the nodes first. + * + * @param index 0-based index to insert children at. Specify {@code 0} to insert at the start, {@code -1} at the + * end + * @param children child nodes to insert + * @return this element, for chaining. + */ + @discardableResult + public func insertChildren(_ index: Int, _ children: Array)throws->Element { + //Validate.notNull(children, "Children collection to be inserted must not be null.") + var index = index + let currentSize: Int = childNodeSize() + if (index < 0) { index += currentSize + 1} // roll around + try Validate.isTrue(val: index >= 0 && index <= currentSize, msg: "Insert position out of bounds.") + + try addChildren(index, children) + return self + } + + /** + * Create a new element by tag name, and add it as the last child. + * + * @param tagName the name of the tag (e.g. {@code div}). + * @return the new element, to allow you to add content to it, e.g.: + * {@code parent.appendElement("h1").attr("id", "header").text("Welcome")} + */ + @discardableResult + public func appendElement(_ tagName: String)throws->Element { + let child: Element = Element(try Tag.valueOf(tagName), getBaseUri()) + try appendChild(child) + return child + } + + /** + * Create a new element by tag name, and add it as the first child. + * + * @param tagName the name of the tag (e.g. {@code div}). + * @return the new element, to allow you to add content to it, e.g.: + * {@code parent.prependElement("h1").attr("id", "header").text("Welcome")} + */ + @discardableResult + public func prependElement(_ tagName: String)throws->Element { + let child: Element = Element(try Tag.valueOf(tagName), getBaseUri()) + try prependChild(child) + return child + } + + /** + * Create and append a new TextNode to this element. + * + * @param text the unencoded text to add + * @return this element + */ + @discardableResult + public func appendText(_ text: String)throws->Element { + let node: TextNode = TextNode(text, getBaseUri()) + try appendChild(node) + return self + } + + /** + * Create and prepend a new TextNode to this element. + * + * @param text the unencoded text to add + * @return this element + */ + @discardableResult + public func prependText(_ text: String)throws->Element { + let node: TextNode = TextNode(text, getBaseUri()) + try prependChild(node) + return self + } + + /** + * Add inner HTML to this element. The supplied HTML will be parsed, and each node appended to the end of the children. + * @param html HTML to add inside this element, after the existing HTML + * @return this element + * @see #html(String) + */ + @discardableResult + public func append(_ html: String)throws->Element { + let nodes: Array = try Parser.parseFragment(html, self, getBaseUri()) + try addChildren(nodes) + return self + } + + /** + * Add inner HTML into this element. The supplied HTML will be parsed, and each node prepended to the start of the element's children. + * @param html HTML to add inside this element, before the existing HTML + * @return this element + * @see #html(String) + */ + @discardableResult + public func prepend(_ html: String)throws->Element { + let nodes: Array = try Parser.parseFragment(html, self, getBaseUri()) + try addChildren(0, nodes) + return self + } + + /** + * Insert the specified HTML into the DOM before this element (as a preceding sibling). + * + * @param html HTML to add before this element + * @return this element, for chaining + * @see #after(String) + */ + @discardableResult + open override func before(_ html: String)throws->Element { + return try super.before(html) as! Element + } + + /** + * Insert the specified node into the DOM before this node (as a preceding sibling). + * @param node to add before this element + * @return this Element, for chaining + * @see #after(Node) + */ + @discardableResult + open override func before(_ node: Node)throws->Element { + return try super.before(node) as! Element + } + + /** + * Insert the specified HTML into the DOM after this element (as a following sibling). + * + * @param html HTML to add after this element + * @return this element, for chaining + * @see #before(String) + */ + @discardableResult + open override func after(_ html: String)throws->Element { + return try super.after(html) as! Element + } + + /** + * Insert the specified node into the DOM after this node (as a following sibling). + * @param node to add after this element + * @return this element, for chaining + * @see #before(Node) + */ + open override func after(_ node: Node)throws->Element { + return try super.after(node) as! Element + } + + /** + * Remove all of the element's child nodes. Any attributes are left as-is. + * @return this element + */ + @discardableResult + public func empty() -> Element { + childNodes.removeAll() + return self + } + + /** + * Wrap the supplied HTML around this element. + * + * @param html HTML to wrap around this element, e.g. {@code
}. Can be arbitrarily deep. + * @return this element, for chaining. + */ + @discardableResult + open override func wrap(_ html: String)throws->Element { + return try super.wrap(html) as! Element + } + + /** + * Get a CSS selector that will uniquely select this element. + *

+ * If the element has an ID, returns #id; + * otherwise returns the parent (if any) CSS selector, followed by {@literal '>'}, + * followed by a unique selector for the element (tag.class.class:nth-child(n)). + *

+ * + * @return the CSS Path that can be used to retrieve the element in a selector. + */ + public func cssSelector()throws->String { + let elementId = id() + if (elementId.count > 0) { + return "#" + elementId + } + + // Translate HTML namespace ns:tag to CSS namespace syntax ns|tag + let tagName: String = self.tagName().replacingOccurrences(of: ":", with: "|") + var selector: String = tagName + let cl = try classNames() + let classes: String = cl.joined(separator: ".") + if (classes.count > 0) { + selector.append(".") + selector.append(classes) + } + + if (parent() == nil || ((parent() as? Document) != nil)) // don't add Document to selector, as will always have a html node + { + return selector + } + + selector.insert(contentsOf: " > ", at: selector.startIndex) + if (try parent()!.select(selector).array().count > 1) { + selector.append(":nth-child(\(try elementSiblingIndex() + 1))") + } + + return try parent()!.cssSelector() + (selector) + } + + /** + * Get sibling elements. If the element has no sibling elements, returns an empty list. An element is not a sibling + * of itself, so will not be included in the returned list. + * @return sibling elements + */ + public func siblingElements() -> Elements { + if (parentNode == nil) {return Elements()} + + let elements: Array? = parent()?.children().array() + let siblings: Elements = Elements() + if let elements = elements { + for el: Element in elements { + if (el != self) { + siblings.add(el) + } + } + } + return siblings + } + + /** + * Gets the next sibling element of this element. E.g., if a {@code div} contains two {@code p}s, + * the {@code nextElementSibling} of the first {@code p} is the second {@code p}. + *

+ * This is similar to {@link #nextSibling()}, but specifically finds only Elements + *

+ * @return the next element, or null if there is no next element + * @see #previousElementSibling() + */ + public func nextElementSibling()throws->Element? { + if (parentNode == nil) {return nil} + let siblings: Array? = parent()?.children().array() + let index: Int? = try Element.indexInList(self, siblings) + try Validate.notNull(obj: index) + if let siblings = siblings { + if (siblings.count > index!+1) { + return siblings[index!+1] + } else { + return nil} + } + return nil + } + + /** + * Gets the previous element sibling of this element. + * @return the previous element, or null if there is no previous element + * @see #nextElementSibling() + */ + public func previousElementSibling()throws->Element? { + if (parentNode == nil) {return nil} + let siblings: Array? = parent()?.children().array() + let index: Int? = try Element.indexInList(self, siblings) + try Validate.notNull(obj: index) + if (index! > 0) { + return siblings?[index!-1] + } else { + return nil + } + } + + /** + * Gets the first element sibling of this element. + * @return the first sibling that is an element (aka the parent's first element child) + */ + public func firstElementSibling() -> Element? { + // todo: should firstSibling() exclude this? + let siblings: Array? = parent()?.children().array() + return (siblings != nil && siblings!.count > 1) ? siblings![0] : nil + } + + /* + * Get the list index of this element in its element sibling list. I.e. if this is the first element + * sibling, returns 0. + * @return position in element sibling list + */ + public func elementSiblingIndex()throws->Int { + if (parent() == nil) {return 0} + let x = try Element.indexInList(self, parent()?.children().array()) + return x == nil ? 0 : x! + } + + /** + * Gets the last element sibling of this element + * @return the last sibling that is an element (aka the parent's last element child) + */ + public func lastElementSibling() -> Element? { + let siblings: Array? = parent()?.children().array() + return (siblings != nil && siblings!.count > 1) ? siblings![siblings!.count - 1] : nil + } + + private static func indexInList(_ search: Element, _ elements: Array?)throws->Int? { + try Validate.notNull(obj: elements) + if let elements = elements { + for i in 0..Elements { + try Validate.notEmpty(string: tagName) + let tagName = tagName.lowercased().trim() + + return try Collector.collect(Evaluator.Tag(tagName), self) + } + + /** + * Find an element by ID, including or under this element. + *

+ * Note that this finds the first matching ID, starting with this element. If you search down from a different + * starting point, it is possible to find a different element by ID. For unique element by ID within a Document, + * use {@link Document#getElementById(String)} + * @param id The ID to search for. + * @return The first matching element by ID, starting with this element, or null if none found. + */ + public func getElementById(_ id: String)throws->Element? { + try Validate.notEmpty(string: id) + + let elements: Elements = try Collector.collect(Evaluator.Id(id), self) + if (elements.array().count > 0) { + return elements.get(0) + } else { + return nil + } + } + + /** + * Find elements that have this class, including or under this element. Case insensitive. + *

+ * Elements can have multiple classes (e.g. {@code

}. This method + * checks each class, so you can find the above with {@code el.getElementsByClass("header")}. + * + * @param className the name of the class to search for. + * @return elements with the supplied class name, empty if none + * @see #hasClass(String) + * @see #classNames() + */ + public func getElementsByClass(_ className: String)throws->Elements { + try Validate.notEmpty(string: className) + + return try Collector.collect(Evaluator.Class(className), self) + } + + /** + * Find elements that have a named attribute set. Case insensitive. + * + * @param key name of the attribute, e.g. {@code href} + * @return elements that have this attribute, empty if none + */ + public func getElementsByAttribute(_ key: String)throws->Elements { + try Validate.notEmpty(string: key) + let key = key.trim() + + return try Collector.collect(Evaluator.Attribute(key), self) + } + + /** + * Find elements that have an attribute name starting with the supplied prefix. Use {@code data-} to find elements + * that have HTML5 datasets. + * @param keyPrefix name prefix of the attribute e.g. {@code data-} + * @return elements that have attribute names that start with with the prefix, empty if none. + */ + public func getElementsByAttributeStarting(_ keyPrefix: String)throws->Elements { + try Validate.notEmpty(string: keyPrefix) + let keyPrefix = keyPrefix.trim() + + return try Collector.collect(Evaluator.AttributeStarting(keyPrefix), self) + } + + /** + * Find elements that have an attribute with the specific value. Case insensitive. + * + * @param key name of the attribute + * @param value value of the attribute + * @return elements that have this attribute with this value, empty if none + */ + public func getElementsByAttributeValue(_ key: String, _ value: String)throws->Elements { + return try Collector.collect(Evaluator.AttributeWithValue(key, value), self) + } + + /** + * Find elements that either do not have this attribute, or have it with a different value. Case insensitive. + * + * @param key name of the attribute + * @param value value of the attribute + * @return elements that do not have a matching attribute + */ + public func getElementsByAttributeValueNot(_ key: String, _ value: String)throws->Elements { + return try Collector.collect(Evaluator.AttributeWithValueNot(key, value), self) + } + + /** + * Find elements that have attributes that start with the value prefix. Case insensitive. + * + * @param key name of the attribute + * @param valuePrefix start of attribute value + * @return elements that have attributes that start with the value prefix + */ + public func getElementsByAttributeValueStarting(_ key: String, _ valuePrefix: String)throws->Elements { + return try Collector.collect(Evaluator.AttributeWithValueStarting(key, valuePrefix), self) + } + + /** + * Find elements that have attributes that end with the value suffix. Case insensitive. + * + * @param key name of the attribute + * @param valueSuffix end of the attribute value + * @return elements that have attributes that end with the value suffix + */ + public func getElementsByAttributeValueEnding(_ key: String, _ valueSuffix: String)throws->Elements { + return try Collector.collect(Evaluator.AttributeWithValueEnding(key, valueSuffix), self) + } + + /** + * Find elements that have attributes whose value contains the match string. Case insensitive. + * + * @param key name of the attribute + * @param match substring of value to search for + * @return elements that have attributes containing this text + */ + public func getElementsByAttributeValueContaining(_ key: String, _ match: String)throws->Elements { + return try Collector.collect(Evaluator.AttributeWithValueContaining(key, match), self) + } + + /** + * Find elements that have attributes whose values match the supplied regular expression. + * @param key name of the attribute + * @param pattern compiled regular expression to match against attribute values + * @return elements that have attributes matching this regular expression + */ + public func getElementsByAttributeValueMatching(_ key: String, _ pattern: Pattern)throws->Elements { + return try Collector.collect(Evaluator.AttributeWithValueMatching(key, pattern), self) + + } + + /** + * Find elements that have attributes whose values match the supplied regular expression. + * @param key name of the attribute + * @param regex regular expression to match against attribute values. You can use embedded flags (such as (?i) and (?m) to control regex options. + * @return elements that have attributes matching this regular expression + */ + public func getElementsByAttributeValueMatching(_ key: String, _ regex: String)throws->Elements { + var pattern: Pattern + do { + pattern = Pattern.compile(regex) + try pattern.validate() + } catch { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "Pattern syntax error: \(regex)") + } + return try getElementsByAttributeValueMatching(key, pattern) + } + + /** + * Find elements whose sibling index is less than the supplied index. + * @param index 0-based index + * @return elements less than index + */ + public func getElementsByIndexLessThan(_ index: Int)throws->Elements { + return try Collector.collect(Evaluator.IndexLessThan(index), self) + } + + /** + * Find elements whose sibling index is greater than the supplied index. + * @param index 0-based index + * @return elements greater than index + */ + public func getElementsByIndexGreaterThan(_ index: Int)throws->Elements { + return try Collector.collect(Evaluator.IndexGreaterThan(index), self) + } + + /** + * Find elements whose sibling index is equal to the supplied index. + * @param index 0-based index + * @return elements equal to index + */ + public func getElementsByIndexEquals(_ index: Int)throws->Elements { + return try Collector.collect(Evaluator.IndexEquals(index), self) + } + + /** + * Find elements that contain the specified string. The search is case insensitive. The text may appear directly + * in the element, or in any of its descendants. + * @param searchText to look for in the element's text + * @return elements that contain the string, case insensitive. + * @see Element#text() + */ + public func getElementsContainingText(_ searchText: String)throws->Elements { + return try Collector.collect(Evaluator.ContainsText(searchText), self) + } + + /** + * Find elements that directly contain the specified string. The search is case insensitive. The text must appear directly + * in the element, not in any of its descendants. + * @param searchText to look for in the element's own text + * @return elements that contain the string, case insensitive. + * @see Element#ownText() + */ + public func getElementsContainingOwnText(_ searchText: String)throws->Elements { + return try Collector.collect(Evaluator.ContainsOwnText(searchText), self) + } + + /** + * Find elements whose text matches the supplied regular expression. + * @param pattern regular expression to match text against + * @return elements matching the supplied regular expression. + * @see Element#text() + */ + public func getElementsMatchingText(_ pattern: Pattern)throws->Elements { + return try Collector.collect(Evaluator.Matches(pattern), self) + } + + /** + * Find elements whose text matches the supplied regular expression. + * @param regex regular expression to match text against. You can use embedded flags (such as (?i) and (?m) to control regex options. + * @return elements matching the supplied regular expression. + * @see Element#text() + */ + public func getElementsMatchingText(_ regex: String)throws->Elements { + let pattern: Pattern + do { + pattern = Pattern.compile(regex) + try pattern.validate() + } catch { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "Pattern syntax error: \(regex)") + } + return try getElementsMatchingText(pattern) + } + + /** + * Find elements whose own text matches the supplied regular expression. + * @param pattern regular expression to match text against + * @return elements matching the supplied regular expression. + * @see Element#ownText() + */ + public func getElementsMatchingOwnText(_ pattern: Pattern)throws->Elements { + return try Collector.collect(Evaluator.MatchesOwn(pattern), self) + } + + /** + * Find elements whose text matches the supplied regular expression. + * @param regex regular expression to match text against. You can use embedded flags (such as (?i) and (?m) to control regex options. + * @return elements matching the supplied regular expression. + * @see Element#ownText() + */ + public func getElementsMatchingOwnText(_ regex: String)throws->Elements { + let pattern: Pattern + do { + pattern = Pattern.compile(regex) + try pattern.validate() + } catch { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "Pattern syntax error: \(regex)") + } + return try getElementsMatchingOwnText(pattern) + } + + /** + * Find all elements under this element (including self, and children of children). + * + * @return all elements + */ + public func getAllElements()throws->Elements { + return try Collector.collect(Evaluator.AllElements(), self) + } + + /** + * Gets the combined text of this element and all its children. Whitespace is normalized and trimmed. + *

+ * For example, given HTML {@code

Hello there now!

}, {@code p.text()} returns {@code "Hello there now!"} + * + * @return unencoded text, or empty string if none. + * @see #ownText() + * @see #textNodes() + */ + class textNodeVisitor: NodeVisitor { + let accum: StringBuilder + let trimAndNormaliseWhitespace: Bool + init(_ accum: StringBuilder, trimAndNormaliseWhitespace: Bool) { + self.accum = accum + self.trimAndNormaliseWhitespace = trimAndNormaliseWhitespace + } + public func head(_ node: Node, _ depth: Int) { + if let textNode = (node as? TextNode) { + if trimAndNormaliseWhitespace { + Element.appendNormalisedText(accum, textNode) + } else { + accum.append(textNode.getWholeText()) + } + } else if let element = (node as? Element) { + if !accum.isEmpty && + (element.isBlock() || element._tag.getName() == "br") && + !TextNode.lastCharIsWhitespace(accum) { + accum.append(" ") + } + } + } + + public func tail(_ node: Node, _ depth: Int) { + } + } + public func text(trimAndNormaliseWhitespace: Bool = true)throws->String { + let accum: StringBuilder = StringBuilder() + try NodeTraversor(textNodeVisitor(accum, trimAndNormaliseWhitespace: trimAndNormaliseWhitespace)).traverse(self) + let text = accum.toString() + if trimAndNormaliseWhitespace { + return text.trim() + } + return text + } + + /** + * Gets the text owned by this element only; does not get the combined text of all children. + *

+ * For example, given HTML {@code

Hello there now!

}, {@code p.ownText()} returns {@code "Hello now!"}, + * whereas {@code p.text()} returns {@code "Hello there now!"}. + * Note that the text within the {@code b} element is not returned, as it is not a direct child of the {@code p} element. + * + * @return unencoded text, or empty string if none. + * @see #text() + * @see #textNodes() + */ + public func ownText() -> String { + let sb: StringBuilder = StringBuilder() + ownText(sb) + return sb.toString().trim() + } + + private func ownText(_ accum: StringBuilder) { + for child: Node in childNodes { + if let textNode = (child as? TextNode) { + Element.appendNormalisedText(accum, textNode) + } else if let child = (child as? Element) { + Element.appendWhitespaceIfBr(child, accum) + } + } + } + + private static func appendNormalisedText(_ accum: StringBuilder, _ textNode: TextNode) { + let text: String = textNode.getWholeText() + + if (Element.preserveWhitespace(textNode.parentNode)) { + accum.append(text) + } else { + StringUtil.appendNormalisedWhitespace(accum, string: text, stripLeading: TextNode.lastCharIsWhitespace(accum)) + } + } + + private static func appendWhitespaceIfBr(_ element: Element, _ accum: StringBuilder) { + if (element._tag.getName() == "br" && !TextNode.lastCharIsWhitespace(accum)) { + accum.append(" ") + } + } + + static func preserveWhitespace(_ node: Node?) -> Bool { + // looks only at this element and one level up, to prevent recursion & needless stack searches + if let element = (node as? Element) { + return element._tag.preserveWhitespace() || element.parent() != nil && element.parent()!._tag.preserveWhitespace() + } + return false + } + + /** + * Set the text of this element. Any existing contents (text or elements) will be cleared + * @param text unencoded text + * @return this element + */ + @discardableResult + public func text(_ text: String)throws->Element { + empty() + let textNode: TextNode = TextNode(text, baseUri) + try appendChild(textNode) + return self + } + + /** + Test if this element has any text content (that is not just whitespace). + @return true if element has non-blank text content. + */ + public func hasText() -> Bool { + for child: Node in childNodes { + if let textNode = (child as? TextNode) { + if (!textNode.isBlank()) { + return true + } + } else if let el = (child as? Element) { + if (el.hasText()) { + return true + } + } + } + return false + } + + /** + * Get the combined data of this element. Data is e.g. the inside of a {@code script} tag. + * @return the data, or empty string if none + * + * @see #dataNodes() + */ + public func data() -> String { + let sb: StringBuilder = StringBuilder() + + for childNode: Node in childNodes { + if let data = (childNode as? DataNode) { + sb.append(data.getWholeData()) + } else if let element = (childNode as? Element) { + let elementData: String = element.data() + sb.append(elementData) + } + } + return sb.toString() + } + + /** + * Gets the literal value of this element's "class" attribute, which may include multiple class names, space + * separated. (E.g. on <div class="header gray"> returns, "header gray") + * @return The literal class attribute, or empty string if no class attribute set. + */ + public func className()throws->String { + return try attr(Element.classString).trim() + } + + /** + * Get all of the element's class names. E.g. on element {@code
}, + * returns a set of two elements {@code "header", "gray"}. Note that modifications to this set are not pushed to + * the backing {@code class} attribute; use the {@link #classNames(java.util.Set)} method to persist them. + * @return set of classnames, empty if no class attribute + */ + public func classNames()throws->OrderedSet { + let fitted = try className().replaceAll(of: Element.classSplit, with: " ", options: .caseInsensitive) + let names: [String] = fitted.components(separatedBy: " ") + let classNames: OrderedSet = OrderedSet(sequence: names) + classNames.remove(Element.emptyString) // if classNames() was empty, would include an empty class + return classNames + } + + /** + Set the element's {@code class} attribute to the supplied class names. + @param classNames set of classes + @return this element, for chaining + */ + @discardableResult + public func classNames(_ classNames: OrderedSet)throws->Element { + try attributes?.put(Element.classString, StringUtil.join(classNames, sep: " ")) + return self + } + + /** + * Tests if this element has a class. Case insensitive. + * @param className name of class to check for + * @return true if it does, false if not + */ + // performance sensitive + public func hasClass(_ className: String) -> Bool { + let classAtt: String? = attributes?.get(key: Element.classString) + let len: Int = (classAtt != nil) ? classAtt!.count : 0 + let wantLen: Int = className.count + + if (len == 0 || len < wantLen) { + return false + } + let classAttr = classAtt! + + // if both lengths are equal, only need compare the className with the attribute + if (len == wantLen) { + return className.equalsIgnoreCase(string: classAttr) + } + + // otherwise, scan for whitespace and compare regions (with no string or arraylist allocations) + var inClass: Bool = false + var start: Int = 0 + for i in 0..Element { + let classes: OrderedSet = try classNames() + classes.append(className) + try classNames(classes) + return self + } + + /** + Remove a class name from this element's {@code class} attribute. + @param className class name to remove + @return this element + */ + @discardableResult + public func removeClass(_ className: String)throws->Element { + let classes: OrderedSet = try classNames() + classes.remove(className) + try classNames(classes) + return self + } + + /** + Toggle a class name on this element's {@code class} attribute: if present, remove it; otherwise add it. + @param className class name to toggle + @return this element + */ + @discardableResult + public func toggleClass(_ className: String)throws->Element { + let classes: OrderedSet = try classNames() + if (classes.contains(className)) {classes.remove(className) + } else { + classes.append(className) + } + try classNames(classes) + + return self + } + + /** + * Get the value of a form element (input, textarea, etc). + * @return the value of the form element, or empty string if not set. + */ + public func val()throws->String { + if (tagName()=="textarea") { + return try text() + } else { + return try attr("value") + } + } + + /** + * Set the value of a form element (input, textarea, etc). + * @param value value to set + * @return this element (for chaining) + */ + @discardableResult + public func val(_ value: String)throws->Element { + if (tagName() == "textarea") { + try text(value) + } else { + try attr("value", value) + } + return self + } + + override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings)throws { + if (out.prettyPrint() && (_tag.formatAsBlock() || (parent() != nil && parent()!.tag().formatAsBlock()) || out.outline())) { + if !accum.isEmpty { + indent(accum, depth, out) + } + } + accum + .append("<") + .append(tagName()) + try attributes?.html(accum: accum, out: out) + + // selfclosing includes unknown tags, isEmpty defines tags that are always empty + if (childNodes.isEmpty && _tag.isSelfClosing()) { + if (out.syntax() == OutputSettings.Syntax.html && _tag.isEmpty()) { + accum.append(">") + } else { + accum.append(" />") // in html, in xml + } + } else { + accum.append(">") + } + } + + override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) { + if (!(childNodes.isEmpty && _tag.isSelfClosing())) { + if (out.prettyPrint() && (!childNodes.isEmpty && ( + _tag.formatAsBlock() || (out.outline() && (childNodes.count>1 || (childNodes.count==1 && !(((childNodes[0] as? TextNode) != nil))))) + ))) { + indent(accum, depth, out) + } + accum.append("") + } + } + + /** + * Retrieves the element's inner HTML. E.g. on a {@code
} with one empty {@code

}, would return + * {@code

}. (Whereas {@link #outerHtml()} would return {@code

}.) + * + * @return String of HTML. + * @see #outerHtml() + */ + public func html()throws->String { + let accum: StringBuilder = StringBuilder() + try html2(accum) + return getOutputSettings().prettyPrint() ? accum.toString().trim() : accum.toString() + } + + private func html2(_ accum: StringBuilder)throws { + for node in childNodes { + try node.outerHtml(accum) + } + } + + /** + * {@inheritDoc} + */ + open override func html(_ appendable: StringBuilder)throws->StringBuilder { + for node in childNodes { + try node.outerHtml(appendable) + } + return appendable + } + + /** + * Set this element's inner HTML. Clears the existing HTML first. + * @param html HTML to parse and set into this element + * @return this element + * @see #append(String) + */ + @discardableResult + public func html(_ html: String)throws->Element { + empty() + try append(html) + return self + } + + public override func copy(with zone: NSZone? = nil) -> Any { + let clone = Element(_tag, baseUri!, attributes!) + return copy(clone: clone) + } + + public override func copy(parent: Node?) -> Node { + let clone = Element(_tag, baseUri!, attributes!) + return copy(clone: clone, parent: parent) + } + public override func copy(clone: Node, parent: Node?) -> Node { + return super.copy(clone: clone, parent: parent) + } + + public static func ==(lhs: Element, rhs: Element) -> Bool { + guard lhs as Node == rhs as Node else { + return false + } + + return lhs._tag == rhs._tag + } + + override public func hash(into hasher: inout Hasher) { + super.hash(into: &hasher) + hasher.combine(_tag) + } +} diff --git a/Swiftgram/SwiftSoup/Sources/Elements.swift b/Swiftgram/SwiftSoup/Sources/Elements.swift new file mode 100644 index 00000000..b8e3852f --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/Elements.swift @@ -0,0 +1,657 @@ +// +// Elements.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 20/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// +/** +A list of {@link Element}s, with methods that act on every element in the list. +

+To get an {@code Elements} object, use the {@link Element#select(String)} method. +

+*/ + +import Foundation + +//open typealias Elements = Array +//typealias E = Element +open class Elements: NSCopying { + fileprivate var this: Array = Array() + + ///base init + public init() { + } + ///Initialized with an array + public init(_ a: Array) { + this = a + } + ///Initialized with an order set + public init(_ a: OrderedSet) { + this.append(contentsOf: a) + } + + /** + * Creates a deep copy of these elements. + * @return a deep copy + */ + public func copy(with zone: NSZone? = nil) -> Any { + let clone: Elements = Elements() + for e: Element in this { + clone.add(e.copy() as! Element) + } + return clone + } + + // attribute methods + /** + Get an attribute value from the first matched element that has the attribute. + @param attributeKey The attribute key. + @return The attribute value from the first matched element that has the attribute.. If no elements were matched (isEmpty() == true), + or if the no elements have the attribute, returns empty string. + @see #hasAttr(String) + */ + open func attr(_ attributeKey: String)throws->String { + for element in this { + if (element.hasAttr(attributeKey)) { + return try element.attr(attributeKey) + } + } + return "" + } + + /** + Checks if any of the matched elements have this attribute set. + @param attributeKey attribute key + @return true if any of the elements have the attribute; false if none do. + */ + open func hasAttr(_ attributeKey: String) -> Bool { + for element in this { + if element.hasAttr(attributeKey) {return true} + } + return false + } + + /** + * Set an attribute on all matched elements. + * @param attributeKey attribute key + * @param attributeValue attribute value + * @return this + */ + @discardableResult + open func attr(_ attributeKey: String, _ attributeValue: String)throws->Elements { + for element in this { + try element.attr(attributeKey, attributeValue) + } + return self + } + + /** + * Remove an attribute from every matched element. + * @param attributeKey The attribute to remove. + * @return this (for chaining) + */ + @discardableResult + open func removeAttr(_ attributeKey: String)throws->Elements { + for element in this { + try element.removeAttr(attributeKey) + } + return self + } + + /** + Add the class name to every matched element's {@code class} attribute. + @param className class name to add + @return this + */ + @discardableResult + open func addClass(_ className: String)throws->Elements { + for element in this { + try element.addClass(className) + } + return self + } + + /** + Remove the class name from every matched element's {@code class} attribute, if present. + @param className class name to remove + @return this + */ + @discardableResult + open func removeClass(_ className: String)throws->Elements { + for element: Element in this { + try element.removeClass(className) + } + return self + } + + /** + Toggle the class name on every matched element's {@code class} attribute. + @param className class name to add if missing, or remove if present, from every element. + @return this + */ + @discardableResult + open func toggleClass(_ className: String)throws->Elements { + for element: Element in this { + try element.toggleClass(className) + } + return self + } + + /** + Determine if any of the matched elements have this class name set in their {@code class} attribute. + @param className class name to check for + @return true if any do, false if none do + */ + + open func hasClass(_ className: String) -> Bool { + for element: Element in this { + if (element.hasClass(className)) { + return true + } + } + return false + } + + /** + * Get the form element's value of the first matched element. + * @return The form element's value, or empty if not set. + * @see Element#val() + */ + open func val()throws->String { + if (size() > 0) { + return try first()!.val() + } + return "" + } + + /** + * Set the form element's value in each of the matched elements. + * @param value The value to set into each matched element + * @return this (for chaining) + */ + @discardableResult + open func val(_ value: String)throws->Elements { + for element: Element in this { + try element.val(value) + } + return self + } + + /** + * Get the combined text of all the matched elements. + *

+ * Note that it is possible to get repeats if the matched elements contain both parent elements and their own + * children, as the Element.text() method returns the combined text of a parent and all its children. + * @return string of all text: unescaped and no HTML. + * @see Element#text() + */ + open func text(trimAndNormaliseWhitespace: Bool = true)throws->String { + let sb: StringBuilder = StringBuilder() + for element: Element in this { + if !sb.isEmpty { + sb.append(" ") + } + sb.append(try element.text(trimAndNormaliseWhitespace: trimAndNormaliseWhitespace)) + } + return sb.toString() + } + + /// Check if an element has text + open func hasText() -> Bool { + for element: Element in this { + if (element.hasText()) { + return true + } + } + return false + } + + /** + * Get the text content of each of the matched elements. If an element has no text, then it is not included in the + * result. + * @return A list of each matched element's text content. + * @see Element#text() + * @see Element#hasText() + * @see #text() + */ + public func eachText()throws->Array { + var texts: Array = Array() + for el: Element in this { + if (el.hasText()){ + texts.append(try el.text()) + } + } + return texts; + } + + /** + * Get the combined inner HTML of all matched elements. + * @return string of all element's inner HTML. + * @see #text() + * @see #outerHtml() + */ + open func html()throws->String { + let sb: StringBuilder = StringBuilder() + for element: Element in this { + if !sb.isEmpty { + sb.append("\n") + } + sb.append(try element.html()) + } + return sb.toString() + } + + /** + * Get the combined outer HTML of all matched elements. + * @return string of all element's outer HTML. + * @see #text() + * @see #html() + */ + open func outerHtml()throws->String { + let sb: StringBuilder = StringBuilder() + for element in this { + if !sb.isEmpty { + sb.append("\n") + } + sb.append(try element.outerHtml()) + } + return sb.toString() + } + + /** + * Get the combined outer HTML of all matched elements. Alias of {@link #outerHtml()}. + * @return string of all element's outer HTML. + * @see #text() + * @see #html() + */ + + open func toString()throws->String { + return try outerHtml() + } + + /** + * Update the tag name of each matched element. For example, to change each {@code } to a {@code }, do + * {@code doc.select("i").tagName("em");} + * @param tagName the new tag name + * @return this, for chaining + * @see Element#tagName(String) + */ + @discardableResult + open func tagName(_ tagName: String)throws->Elements { + for element: Element in this { + try element.tagName(tagName) + } + return self + } + + /** + * Set the inner HTML of each matched element. + * @param html HTML to parse and set into each matched element. + * @return this, for chaining + * @see Element#html(String) + */ + @discardableResult + open func html(_ html: String)throws->Elements { + for element: Element in this { + try element.html(html) + } + return self + } + + /** + * Add the supplied HTML to the start of each matched element's inner HTML. + * @param html HTML to add inside each element, before the existing HTML + * @return this, for chaining + * @see Element#prepend(String) + */ + @discardableResult + open func prepend(_ html: String)throws->Elements { + for element: Element in this { + try element.prepend(html) + } + return self + } + + /** + * Add the supplied HTML to the end of each matched element's inner HTML. + * @param html HTML to add inside each element, after the existing HTML + * @return this, for chaining + * @see Element#append(String) + */ + @discardableResult + open func append(_ html: String)throws->Elements { + for element: Element in this { + try element.append(html) + } + return self + } + + /** + * Insert the supplied HTML before each matched element's outer HTML. + * @param html HTML to insert before each element + * @return this, for chaining + * @see Element#before(String) + */ + @discardableResult + open func before(_ html: String)throws->Elements { + for element: Element in this { + try element.before(html) + } + return self + } + + /** + * Insert the supplied HTML after each matched element's outer HTML. + * @param html HTML to insert after each element + * @return this, for chaining + * @see Element#after(String) + */ + @discardableResult + open func after(_ html: String)throws->Elements { + for element: Element in this { + try element.after(html) + } + return self + } + + /** + Wrap the supplied HTML around each matched elements. For example, with HTML + {@code

This is SwiftSoup

}, + doc.select("b").wrap("<i></i>"); + becomes {@code

This is SwiftSoup

} + @param html HTML to wrap around each element, e.g. {@code
}. Can be arbitrarily deep. + @return this (for chaining) + @see Element#wrap + */ + @discardableResult + open func wrap(_ html: String)throws->Elements { + try Validate.notEmpty(string: html) + for element: Element in this { + try element.wrap(html) + } + return self + } + + /** + * Removes the matched elements from the DOM, and moves their children up into their parents. This has the effect of + * dropping the elements but keeping their children. + *

+ * This is useful for e.g removing unwanted formatting elements but keeping their contents. + *

+ * + * E.g. with HTML:

{@code

One Two
}

+ *

{@code doc.select("font").unwrap();}

+ *

HTML = {@code

One Two
}

+ * + * @return this (for chaining) + * @see Node#unwrap + */ + @discardableResult + open func unwrap()throws->Elements { + for element: Element in this { + try element.unwrap() + } + return self + } + + /** + * Empty (remove all child nodes from) each matched element. This is similar to setting the inner HTML of each + * element to nothing. + *

+ * E.g. HTML: {@code

Hello there

now

}
+ * doc.select("p").empty();
+ * HTML = {@code

} + * @return this, for chaining + * @see Element#empty() + * @see #remove() + */ + @discardableResult + open func empty() -> Elements { + for element: Element in this { + element.empty() + } + return self + } + + /** + * Remove each matched element from the DOM. This is similar to setting the outer HTML of each element to nothing. + *

+ * E.g. HTML: {@code

Hello

there

}
+ * doc.select("p").remove();
+ * HTML = {@code
} + *

+ * Note that this method should not be used to clean user-submitted HTML; rather, use {@link Cleaner} to clean HTML. + * @return this, for chaining + * @see Element#empty() + * @see #empty() + */ + @discardableResult + open func remove()throws->Elements { + for element in this { + try element.remove() + } + return self + } + + // filters + + /** + * Find matching elements within this element list. + * @param query A {@link CssSelector} query + * @return the filtered list of elements, or an empty list if none match. + */ + open func select(_ query: String)throws->Elements { + return try CssSelector.select(query, this) + } + + /** + * Remove elements from this list that match the {@link CssSelector} query. + *

+ * E.g. HTML: {@code

Two
}
+ * Elements divs = doc.select("div").not(".logo");
+ * Result: {@code divs: [
Two
]} + *

+ * @param query the selector query whose results should be removed from these elements + * @return a new elements list that contains only the filtered results + */ + open func not(_ query: String)throws->Elements { + let out: Elements = try CssSelector.select(query, this) + return CssSelector.filterOut(this, out.this) + } + + /** + * Get the nth matched element as an Elements object. + *

+ * See also {@link #get(int)} to retrieve an Element. + * @param index the (zero-based) index of the element in the list to retain + * @return Elements containing only the specified element, or, if that element did not exist, an empty list. + */ + open func eq(_ index: Int) -> Elements { + return size() > index ? Elements([get(index)]) : Elements() + } + + /** + * Test if any of the matched elements match the supplied query. + * @param query A selector + * @return true if at least one element in the list matches the query. + */ + open func iS(_ query: String)throws->Bool { + let eval: Evaluator = try QueryParser.parse(query) + for e: Element in this { + if (try e.iS(eval)) { + return true + } + } + return false + + } + + /** + * Get all of the parents and ancestor elements of the matched elements. + * @return all of the parents and ancestor elements of the matched elements + */ + + open func parents() -> Elements { + let combo: OrderedSet = OrderedSet() + for e: Element in this { + combo.append(contentsOf: e.parents().array()) + } + return Elements(combo) + } + + // list-like methods + /** + Get the first matched element. + @return The first matched element, or null if contents is empty. + */ + open func first() -> Element? { + return isEmpty() ? nil : get(0) + } + + /// Check if no element stored + open func isEmpty() -> Bool { + return array().count == 0 + } + + /// Count + open func size() -> Int { + return array().count + } + + /** + Get the last matched element. + @return The last matched element, or null if contents is empty. + */ + open func last() -> Element? { + return isEmpty() ? nil : get(size() - 1) + } + + /** + * Perform a depth-first traversal on each of the selected elements. + * @param nodeVisitor the visitor callbacks to perform on each node + * @return this, for chaining + */ + @discardableResult + open func traverse(_ nodeVisitor: NodeVisitor)throws->Elements { + let traversor: NodeTraversor = NodeTraversor(nodeVisitor) + for el: Element in this { + try traversor.traverse(el) + } + return self + } + + /** + * Get the {@link FormElement} forms from the selected elements, if any. + * @return a list of {@link FormElement}s pulled from the matched elements. The list will be empty if the elements contain + * no forms. + */ + open func forms()->Array { + var forms: Array = Array() + for el: Element in this { + if let el = el as? FormElement { + forms.append(el) + } + } + return forms + } + + /** + * Appends the specified element to the end of this list. + * + * @param e element to be appended to this list + * @return true (as specified by {@link Collection#add}) + */ + open func add(_ e: Element) { + this.append(e) + } + + /** + * Insert the specified element at index. + */ + open func add(_ index: Int, _ element: Element) { + this.insert(element, at: index) + } + + /// Return element at index + open func get(_ i: Int) -> Element { + return this[i] + } + + /// Returns all elements + open func array()->Array { + return this + } +} + +/** +* Elements extension Equatable. +*/ +extension Elements: Equatable { + /// Returns a Boolean value indicating whether two values are equal. + /// + /// Equality is the inverse of inequality. For any values `a` and `b`, + /// `a == b` implies that `a != b` is `false`. + /// + /// - Parameters: + /// - lhs: A value to compare. + /// - rhs: Another value to compare. + public static func ==(lhs: Elements, rhs: Elements) -> Bool { + return lhs.this == rhs.this + } +} + +/** +* Elements RandomAccessCollection +*/ +extension Elements: RandomAccessCollection { + public subscript(position: Int) -> Element { + return this[position] + } + + public var startIndex: Int { + return this.startIndex + } + + public var endIndex: Int { + return this.endIndex + } + + /// The number of Element objects in the collection. + /// Equivalent to `size()` + public var count: Int { + return this.count + } +} + +/** +* Elements IteratorProtocol. +*/ +public struct ElementsIterator: IteratorProtocol { + /// Elements reference + let elements: Elements + //current element index + var index = 0 + + /// Initializer + init(_ countdown: Elements) { + self.elements = countdown + } + + /// Advances to the next element and returns it, or `nil` if no next element + mutating public func next() -> Element? { + let result = index < elements.size() ? elements.get(index) : nil + index += 1 + return result + } +} + +/** +* Elements Extension Sequence. +*/ +extension Elements: Sequence { + /// Returns an iterator over the elements of this sequence. + public func makeIterator() -> ElementsIterator { + return ElementsIterator(self) + } +} diff --git a/Swiftgram/SwiftSoup/Sources/Entities.swift b/Swiftgram/SwiftSoup/Sources/Entities.swift new file mode 100644 index 00000000..b513301c --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/Entities.swift @@ -0,0 +1,338 @@ +// +// Entities.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * HTML entities, and escape routines. + * Source: W3C HTML + * named character references. + */ +public class Entities { + private static let empty = -1 + private static let emptyName = "" + private static let codepointRadix: Int = 36 + + public class EscapeMode: Equatable { + + /** Restricted entities suitable for XHTML output: lt, gt, amp, and quot only. */ + public static let xhtml: EscapeMode = EscapeMode(string: Entities.xhtml, size: 4, id: 0) + /** Default HTML output entities. */ + public static let base: EscapeMode = EscapeMode(string: Entities.base, size: 106, id: 1) + /** Complete HTML entities. */ + public static let extended: EscapeMode = EscapeMode(string: Entities.full, size: 2125, id: 2) + + fileprivate let value: Int + + struct NamedCodepoint { + let scalar: UnicodeScalar + let name: String + } + + // Array of named references, sorted by name for binary search. built by BuildEntities. + // The few entities that map to a multi-codepoint sequence go into multipoints. + fileprivate var entitiesByName: [NamedCodepoint] = [] + + // Array of entities in first-codepoint order. We don't currently support + // multicodepoints to single named value currently. Lazy because this index + // is used only when generating HTML text. + fileprivate lazy var entitiesByCodepoint = entitiesByName.sorted() { a, b in a.scalar < b.scalar } + + public static func == (left: EscapeMode, right: EscapeMode) -> Bool { + return left.value == right.value + } + + static func != (left: EscapeMode, right: EscapeMode) -> Bool { + return left.value != right.value + } + + private static let codeDelims: [UnicodeScalar] = [",", ";"] + + init(string: String, size: Int, id: Int) { + + value = id + let reader: CharacterReader = CharacterReader(string) + + entitiesByName.reserveCapacity(size) + while !reader.isEmpty() { + let name: String = reader.consumeTo("=") + reader.advance() + let cp1: Int = Int(reader.consumeToAny(EscapeMode.codeDelims), radix: codepointRadix) ?? 0 + let codeDelim: UnicodeScalar = reader.current() + reader.advance() + let cp2: Int + if (codeDelim == ",") { + cp2 = Int(reader.consumeTo(";"), radix: codepointRadix) ?? 0 + reader.advance() + } else { + cp2 = empty + } + let _ = Int(reader.consumeTo("\n"), radix: codepointRadix) ?? 0 + reader.advance() + + entitiesByName.append(NamedCodepoint(scalar: UnicodeScalar(cp1)!, name: name)) + + if (cp2 != empty) { + multipointsLock.lock() + multipoints[name] = [UnicodeScalar(cp1)!, UnicodeScalar(cp2)!] + multipointsLock.unlock() + } + } + // Entities should start in name order, but better safe than sorry... + entitiesByName.sort() { a, b in a.name < b.name } + } + + // Only returns the first of potentially multiple codepoints + public func codepointForName(_ name: String) -> UnicodeScalar? { + let ix = entitiesByName.binarySearch { $0.name < name } + guard ix < entitiesByName.endIndex else { return nil } + let entity = entitiesByName[ix] + guard entity.name == name else { return nil } + return entity.scalar + } + + // Search by first codepoint only + public func nameForCodepoint(_ codepoint: UnicodeScalar ) -> String? { + var ix = entitiesByCodepoint.binarySearch { $0.scalar < codepoint } + var matches: [String] = [] + while ix < entitiesByCodepoint.endIndex && entitiesByCodepoint[ix].scalar == codepoint { + matches.append(entitiesByCodepoint[ix].name) + ix = entitiesByCodepoint.index(after: ix) + } + return matches.isEmpty ? nil : matches.sorted().last! + } + + private func size() -> Int { + return entitiesByName.count + } + + } + + private static var multipoints: [String: [UnicodeScalar]] = [:] // name -> multiple character references + private static var multipointsLock = MutexLock() + + /** + * Check if the input is a known named entity + * @param name the possible entity name (e.g. "lt" or "amp") + * @return true if a known named entity + */ + public static func isNamedEntity(_ name: String ) -> Bool { + return (EscapeMode.extended.codepointForName(name) != nil) + } + + /** + * Check if the input is a known named entity in the base entity set. + * @param name the possible entity name (e.g. "lt" or "amp") + * @return true if a known named entity in the base set + * @see #isNamedEntity(String) + */ + public static func isBaseNamedEntity(_ name: String) -> Bool { + return EscapeMode.base.codepointForName(name) != nil + } + + /** + * Get the character(s) represented by the named entitiy + * @param name entity (e.g. "lt" or "amp") + * @return the string value of the character(s) represented by this entity, or "" if not defined + */ + public static func getByName(name: String) -> String? { + if let scalars = codepointsForName(name) { + return String(String.UnicodeScalarView(scalars)) + } + return nil + } + + public static func codepointsForName(_ name: String) -> [UnicodeScalar]? { + multipointsLock.lock() + if let scalars = multipoints[name] { + multipointsLock.unlock() + return scalars + } + multipointsLock.unlock() + + if let scalar = EscapeMode.extended.codepointForName(name) { + return [scalar] + } + return nil + } + + public static func escape(_ string: String, _ encode: String.Encoding = .utf8 ) -> String { + return Entities.escape(string, OutputSettings().charset(encode).escapeMode(Entities.EscapeMode.extended)) + } + + public static func escape(_ string: String, _ out: OutputSettings) -> String { + let accum = StringBuilder()//string.characters.count * 2 + escape(accum, string, out, false, false, false) + // try { + // + // } catch (IOException e) { + // throw new SerializationException(e) // doesn't happen + // } + return accum.toString() + } + + // this method is ugly, and does a lot. but other breakups cause rescanning and stringbuilder generations + static func escape(_ accum: StringBuilder, _ string: String, _ out: OutputSettings, _ inAttribute: Bool, _ normaliseWhite: Bool, _ stripLeadingWhite: Bool ) { + var lastWasWhite = false + var reachedNonWhite = false + let escapeMode: EscapeMode = out.escapeMode() + let encoder: String.Encoding = out.encoder() + //let length = UInt32(string.characters.count) + + var codePoint: UnicodeScalar + for ch in string.unicodeScalars { + codePoint = ch + + if (normaliseWhite) { + if (codePoint.isWhitespace) { + if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite) { + continue + } + accum.append(UnicodeScalar.Space) + lastWasWhite = true + continue + } else { + lastWasWhite = false + reachedNonWhite = true + } + } + + // surrogate pairs, split implementation for efficiency on single char common case (saves creating strings, char[]): + if (codePoint.value < Character.MIN_SUPPLEMENTARY_CODE_POINT) { + let c = codePoint + // html specific and required escapes: + switch (codePoint) { + case UnicodeScalar.Ampersand: + accum.append("&") + break + case UnicodeScalar(UInt32(0xA0))!: + if (escapeMode != EscapeMode.xhtml) { + accum.append(" ") + } else { + accum.append(" ") + } + break + case UnicodeScalar.LessThan: + // escape when in character data or when in a xml attribue val; not needed in html attr val + if (!inAttribute || escapeMode == EscapeMode.xhtml) { + accum.append("<") + } else { + accum.append(c) + } + break + case UnicodeScalar.GreaterThan: + if (!inAttribute) { + accum.append(">") + } else { + accum.append(c)} + break + case "\"": + if (inAttribute) { + accum.append(""") + } else { + accum.append(c) + } + break + default: + if (canEncode(c, encoder)) { + accum.append(c) + } else { + appendEncoded(accum: accum, escapeMode: escapeMode, codePoint: codePoint) + } + } + } else { + if (encoder.canEncode(String(codePoint))) // uses fallback encoder for simplicity + { + accum.append(String(codePoint)) + } else { + appendEncoded(accum: accum, escapeMode: escapeMode, codePoint: codePoint) + } + } + } + } + + private static func appendEncoded(accum: StringBuilder, escapeMode: EscapeMode, codePoint: UnicodeScalar) { + if let name = escapeMode.nameForCodepoint(codePoint) { + // ok for identity check + accum.append(UnicodeScalar.Ampersand).append(name).append(";") + } else { + accum.append("&#x").append(String.toHexString(n: Int(codePoint.value)) ).append(";") + } + } + + public static func unescape(_ string: String)throws-> String { + return try unescape(string: string, strict: false) + } + + /** + * Unescape the input string. + * @param string to un-HTML-escape + * @param strict if "strict" (that is, requires trailing ';' char, otherwise that's optional) + * @return unescaped string + */ + public static func unescape(string: String, strict: Bool)throws -> String { + return try Parser.unescapeEntities(string, strict) + } + + /* + * Provides a fast-path for Encoder.canEncode, which drastically improves performance on Android post JellyBean. + * After KitKat, the implementation of canEncode degrades to the point of being useless. For non ASCII or UTF, + * performance may be bad. We can add more encoders for common character sets that are impacted by performance + * issues on Android if required. + * + * Benchmarks: * + * OLD toHtml() impl v New (fastpath) in millis + * Wiki: 1895, 16 + * CNN: 6378, 55 + * Alterslash: 3013, 28 + * Jsoup: 167, 2 + */ + private static func canEncode(_ c: UnicodeScalar, _ fallback: String.Encoding) -> Bool { + // todo add more charset tests if impacted by Android's bad perf in canEncode + switch (fallback) { + case String.Encoding.ascii: + return c.value < 0x80 + case String.Encoding.utf8: + return true // real is:!(Character.isLowSurrogate(c) || Character.isHighSurrogate(c)) - but already check above + default: + return fallback.canEncode(String(Character(c))) + } + } + + static let xhtml: String = "amp=12;1\ngt=1q;3\nlt=1o;2\nquot=y;0" + + static let base: String = "AElig=5i;1c\nAMP=12;2\nAacute=5d;17\nAcirc=5e;18\nAgrave=5c;16\nAring=5h;1b\nAtilde=5f;19\nAuml=5g;1a\nCOPY=4p;h\nCcedil=5j;1d\nETH=5s;1m\nEacute=5l;1f\nEcirc=5m;1g\nEgrave=5k;1e\nEuml=5n;1h\nGT=1q;6\nIacute=5p;1j\nIcirc=5q;1k\nIgrave=5o;1i\nIuml=5r;1l\nLT=1o;4\nNtilde=5t;1n\nOacute=5v;1p\nOcirc=5w;1q\nOgrave=5u;1o\nOslash=60;1u\nOtilde=5x;1r\nOuml=5y;1s\nQUOT=y;0\nREG=4u;n\nTHORN=66;20\nUacute=62;1w\nUcirc=63;1x\nUgrave=61;1v\nUuml=64;1y\nYacute=65;1z\naacute=69;23\nacirc=6a;24\nacute=50;u\naelig=6e;28\nagrave=68;22\namp=12;3\naring=6d;27\natilde=6b;25\nauml=6c;26\nbrvbar=4m;e\nccedil=6f;29\ncedil=54;y\ncent=4i;a\ncopy=4p;i\ncurren=4k;c\ndeg=4w;q\ndivide=6v;2p\neacute=6h;2b\necirc=6i;2c\negrave=6g;2a\neth=6o;2i\neuml=6j;2d\nfrac12=59;13\nfrac14=58;12\nfrac34=5a;14\ngt=1q;7\niacute=6l;2f\nicirc=6m;2g\niexcl=4h;9\nigrave=6k;2e\niquest=5b;15\niuml=6n;2h\nlaquo=4r;k\nlt=1o;5\nmacr=4v;p\nmicro=51;v\nmiddot=53;x\nnbsp=4g;8\nnot=4s;l\nntilde=6p;2j\noacute=6r;2l\nocirc=6s;2m\nograve=6q;2k\nordf=4q;j\nordm=56;10\noslash=6w;2q\notilde=6t;2n\nouml=6u;2o\npara=52;w\nplusmn=4x;r\npound=4j;b\nquot=y;1\nraquo=57;11\nreg=4u;o\nsect=4n;f\nshy=4t;m\nsup1=55;z\nsup2=4y;s\nsup3=4z;t\nszlig=67;21\nthorn=72;2w\ntimes=5z;1t\nuacute=6y;2s\nucirc=6z;2t\nugrave=6x;2r\numl=4o;g\nuuml=70;2u\nyacute=71;2v\nyen=4l;d\nyuml=73;2x" + + static let full: String = "AElig=5i;2v\nAMP=12;8\nAacute=5d;2p\nAbreve=76;4k\nAcirc=5e;2q\nAcy=sw;av\nAfr=2kn8;1kh\nAgrave=5c;2o\nAlpha=pd;8d\nAmacr=74;4i\nAnd=8cz;1e1\nAogon=78;4m\nAopf=2koo;1ls\nApplyFunction=6e9;ew\nAring=5h;2t\nAscr=2kkc;1jc\nAssign=6s4;s6\nAtilde=5f;2r\nAuml=5g;2s\nBackslash=6qe;o1\nBarv=8h3;1it\nBarwed=6x2;120\nBcy=sx;aw\nBecause=6r9;pw\nBernoullis=6jw;gn\nBeta=pe;8e\nBfr=2kn9;1ki\nBopf=2kop;1lt\nBreve=k8;82\nBscr=6jw;gp\nBumpeq=6ry;ro\nCHcy=tj;bi\nCOPY=4p;1q\nCacute=7a;4o\nCap=6vm;zz\nCapitalDifferentialD=6kl;h8\nCayleys=6jx;gq\nCcaron=7g;4u\nCcedil=5j;2w\nCcirc=7c;4q\nCconint=6r4;pn\nCdot=7e;4s\nCedilla=54;2e\nCenterDot=53;2b\nCfr=6jx;gr\nChi=pz;8y\nCircleDot=6u1;x8\nCircleMinus=6ty;x3\nCirclePlus=6tx;x1\nCircleTimes=6tz;x5\nClockwiseContourIntegral=6r6;pp\nCloseCurlyDoubleQuote=6cd;e0\nCloseCurlyQuote=6c9;dt\nColon=6rb;q1\nColone=8dw;1en\nCongruent=6sh;sn\nConint=6r3;pm\nContourIntegral=6r2;pi\nCopf=6iq;f7\nCoproduct=6q8;nq\nCounterClockwiseContourIntegral=6r7;pr\nCross=8bz;1d8\nCscr=2kke;1jd\nCup=6vn;100\nCupCap=6rx;rk\nDD=6kl;h9\nDDotrahd=841;184\nDJcy=si;ai\nDScy=sl;al\nDZcy=sv;au\nDagger=6ch;e7\nDarr=6n5;j5\nDashv=8h0;1ir\nDcaron=7i;4w\nDcy=t0;az\nDel=6pz;n9\nDelta=pg;8g\nDfr=2knb;1kj\nDiacriticalAcute=50;27\nDiacriticalDot=k9;84\nDiacriticalDoubleAcute=kd;8a\nDiacriticalGrave=2o;13\nDiacriticalTilde=kc;88\nDiamond=6v8;za\nDifferentialD=6km;ha\nDopf=2kor;1lu\nDot=4o;1n\nDotDot=6ho;f5\nDotEqual=6s0;rw\nDoubleContourIntegral=6r3;pl\nDoubleDot=4o;1m\nDoubleDownArrow=6oj;m0\nDoubleLeftArrow=6og;lq\nDoubleLeftRightArrow=6ok;m3\nDoubleLeftTee=8h0;1iq\nDoubleLongLeftArrow=7w8;17g\nDoubleLongLeftRightArrow=7wa;17m\nDoubleLongRightArrow=7w9;17j\nDoubleRightArrow=6oi;lw\nDoubleRightTee=6ug;xz\nDoubleUpArrow=6oh;lt\nDoubleUpDownArrow=6ol;m7\nDoubleVerticalBar=6qt;ov\nDownArrow=6mr;i8\nDownArrowBar=843;186\nDownArrowUpArrow=6ph;mn\nDownBreve=lt;8c\nDownLeftRightVector=85s;198\nDownLeftTeeVector=866;19m\nDownLeftVector=6nx;ke\nDownLeftVectorBar=85y;19e\nDownRightTeeVector=867;19n\nDownRightVector=6o1;kq\nDownRightVectorBar=85z;19f\nDownTee=6uc;xs\nDownTeeArrow=6nb;jh\nDownarrow=6oj;m1\nDscr=2kkf;1je\nDstrok=7k;4y\nENG=96;6g\nETH=5s;35\nEacute=5l;2y\nEcaron=7u;56\nEcirc=5m;2z\nEcy=tp;bo\nEdot=7q;52\nEfr=2knc;1kk\nEgrave=5k;2x\nElement=6q0;na\nEmacr=7m;50\nEmptySmallSquare=7i3;15x\nEmptyVerySmallSquare=7fv;150\nEogon=7s;54\nEopf=2kos;1lv\nEpsilon=ph;8h\nEqual=8dx;1eo\nEqualTilde=6rm;qp\nEquilibrium=6oc;li\nEscr=6k0;gu\nEsim=8dv;1em\nEta=pj;8j\nEuml=5n;30\nExists=6pv;mz\nExponentialE=6kn;hc\nFcy=tg;bf\nFfr=2knd;1kl\nFilledSmallSquare=7i4;15y\nFilledVerySmallSquare=7fu;14w\nFopf=2kot;1lw\nForAll=6ps;ms\nFouriertrf=6k1;gv\nFscr=6k1;gw\nGJcy=sj;aj\nGT=1q;r\nGamma=pf;8f\nGammad=rg;a5\nGbreve=7y;5a\nGcedil=82;5e\nGcirc=7w;58\nGcy=sz;ay\nGdot=80;5c\nGfr=2kne;1km\nGg=6vt;10c\nGopf=2kou;1lx\nGreaterEqual=6sl;sv\nGreaterEqualLess=6vv;10i\nGreaterFullEqual=6sn;t6\nGreaterGreater=8f6;1gh\nGreaterLess=6t3;ul\nGreaterSlantEqual=8e6;1f5\nGreaterTilde=6sz;ub\nGscr=2kki;1jf\nGt=6sr;tr\nHARDcy=tm;bl\nHacek=jr;80\nHat=2m;10\nHcirc=84;5f\nHfr=6j0;fe\nHilbertSpace=6iz;fa\nHopf=6j1;fg\nHorizontalLine=7b4;13i\nHscr=6iz;fc\nHstrok=86;5h\nHumpDownHump=6ry;rn\nHumpEqual=6rz;rs\nIEcy=t1;b0\nIJlig=8i;5s\nIOcy=sh;ah\nIacute=5p;32\nIcirc=5q;33\nIcy=t4;b3\nIdot=8g;5p\nIfr=6j5;fq\nIgrave=5o;31\nIm=6j5;fr\nImacr=8a;5l\nImaginaryI=6ko;hf\nImplies=6oi;ly\nInt=6r0;pf\nIntegral=6qz;pd\nIntersection=6v6;z4\nInvisibleComma=6eb;f0\nInvisibleTimes=6ea;ey\nIogon=8e;5n\nIopf=2kow;1ly\nIota=pl;8l\nIscr=6j4;fn\nItilde=88;5j\nIukcy=sm;am\nIuml=5r;34\nJcirc=8k;5u\nJcy=t5;b4\nJfr=2knh;1kn\nJopf=2kox;1lz\nJscr=2kkl;1jg\nJsercy=so;ao\nJukcy=sk;ak\nKHcy=th;bg\nKJcy=ss;as\nKappa=pm;8m\nKcedil=8m;5w\nKcy=t6;b5\nKfr=2kni;1ko\nKopf=2koy;1m0\nKscr=2kkm;1jh\nLJcy=sp;ap\nLT=1o;m\nLacute=8p;5z\nLambda=pn;8n\nLang=7vu;173\nLaplacetrf=6j6;fs\nLarr=6n2;j1\nLcaron=8t;63\nLcedil=8r;61\nLcy=t7;b6\nLeftAngleBracket=7vs;16x\nLeftArrow=6mo;hu\nLeftArrowBar=6p0;mj\nLeftArrowRightArrow=6o6;l3\nLeftCeiling=6x4;121\nLeftDoubleBracket=7vq;16t\nLeftDownTeeVector=869;19p\nLeftDownVector=6o3;kw\nLeftDownVectorBar=861;19h\nLeftFloor=6x6;125\nLeftRightArrow=6ms;ib\nLeftRightVector=85q;196\nLeftTee=6ub;xq\nLeftTeeArrow=6n8;ja\nLeftTeeVector=862;19i\nLeftTriangle=6uq;ya\nLeftTriangleBar=89b;1c0\nLeftTriangleEqual=6us;yg\nLeftUpDownVector=85t;199\nLeftUpTeeVector=868;19o\nLeftUpVector=6nz;kk\nLeftUpVectorBar=860;19g\nLeftVector=6nw;kb\nLeftVectorBar=85u;19a\nLeftarrow=6og;lr\nLeftrightarrow=6ok;m4\nLessEqualGreater=6vu;10e\nLessFullEqual=6sm;t0\nLessGreater=6t2;ui\nLessLess=8f5;1gf\nLessSlantEqual=8e5;1ez\nLessTilde=6sy;u8\nLfr=2knj;1kp\nLl=6vs;109\nLleftarrow=6oq;me\nLmidot=8v;65\nLongLeftArrow=7w5;177\nLongLeftRightArrow=7w7;17d\nLongRightArrow=7w6;17a\nLongleftarrow=7w8;17h\nLongleftrightarrow=7wa;17n\nLongrightarrow=7w9;17k\nLopf=2koz;1m1\nLowerLeftArrow=6mx;iq\nLowerRightArrow=6mw;in\nLscr=6j6;fu\nLsh=6nk;jv\nLstrok=8x;67\nLt=6sq;tl\nMap=83p;17v\nMcy=t8;b7\nMediumSpace=6e7;eu\nMellintrf=6k3;gx\nMfr=2knk;1kq\nMinusPlus=6qb;nv\nMopf=2kp0;1m2\nMscr=6k3;gz\nMu=po;8o\nNJcy=sq;aq\nNacute=8z;69\nNcaron=93;6d\nNcedil=91;6b\nNcy=t9;b8\nNegativeMediumSpace=6bv;dc\nNegativeThickSpace=6bv;dd\nNegativeThinSpace=6bv;de\nNegativeVeryThinSpace=6bv;db\nNestedGreaterGreater=6sr;tq\nNestedLessLess=6sq;tk\nNewLine=a;1\nNfr=2knl;1kr\nNoBreak=6e8;ev\nNonBreakingSpace=4g;1d\nNopf=6j9;fx\nNot=8h8;1ix\nNotCongruent=6si;sp\nNotCupCap=6st;tv\nNotDoubleVerticalBar=6qu;p0\nNotElement=6q1;ne\nNotEqual=6sg;sk\nNotEqualTilde=6rm,mw;qn\nNotExists=6pw;n1\nNotGreater=6sv;tz\nNotGreaterEqual=6sx;u5\nNotGreaterFullEqual=6sn,mw;t3\nNotGreaterGreater=6sr,mw;tn\nNotGreaterLess=6t5;uq\nNotGreaterSlantEqual=8e6,mw;1f2\nNotGreaterTilde=6t1;ug\nNotHumpDownHump=6ry,mw;rl\nNotHumpEqual=6rz,mw;rq\nNotLeftTriangle=6wa;113\nNotLeftTriangleBar=89b,mw;1bz\nNotLeftTriangleEqual=6wc;119\nNotLess=6su;tw\nNotLessEqual=6sw;u2\nNotLessGreater=6t4;uo\nNotLessLess=6sq,mw;th\nNotLessSlantEqual=8e5,mw;1ew\nNotLessTilde=6t0;ue\nNotNestedGreaterGreater=8f6,mw;1gg\nNotNestedLessLess=8f5,mw;1ge\nNotPrecedes=6tc;vb\nNotPrecedesEqual=8fj,mw;1gv\nNotPrecedesSlantEqual=6w0;10p\nNotReverseElement=6q4;nl\nNotRightTriangle=6wb;116\nNotRightTriangleBar=89c,mw;1c1\nNotRightTriangleEqual=6wd;11c\nNotSquareSubset=6tr,mw;wh\nNotSquareSubsetEqual=6w2;10t\nNotSquareSuperset=6ts,mw;wl\nNotSquareSupersetEqual=6w3;10v\nNotSubset=6te,6he;vh\nNotSubsetEqual=6tk;w0\nNotSucceeds=6td;ve\nNotSucceedsEqual=8fk,mw;1h1\nNotSucceedsSlantEqual=6w1;10r\nNotSucceedsTilde=6tb,mw;v7\nNotSuperset=6tf,6he;vm\nNotSupersetEqual=6tl;w3\nNotTilde=6rl;ql\nNotTildeEqual=6ro;qv\nNotTildeFullEqual=6rr;r1\nNotTildeTilde=6rt;r9\nNotVerticalBar=6qs;or\nNscr=2kkp;1ji\nNtilde=5t;36\nNu=pp;8p\nOElig=9e;6m\nOacute=5v;38\nOcirc=5w;39\nOcy=ta;b9\nOdblac=9c;6k\nOfr=2knm;1ks\nOgrave=5u;37\nOmacr=98;6i\nOmega=q1;90\nOmicron=pr;8r\nOopf=2kp2;1m3\nOpenCurlyDoubleQuote=6cc;dy\nOpenCurlyQuote=6c8;dr\nOr=8d0;1e2\nOscr=2kkq;1jj\nOslash=60;3d\nOtilde=5x;3a\nOtimes=8c7;1df\nOuml=5y;3b\nOverBar=6da;em\nOverBrace=732;13b\nOverBracket=71w;134\nOverParenthesis=730;139\nPartialD=6pu;mx\nPcy=tb;ba\nPfr=2knn;1kt\nPhi=py;8x\nPi=ps;8s\nPlusMinus=4x;22\nPoincareplane=6j0;fd\nPopf=6jd;g3\nPr=8fv;1hl\nPrecedes=6t6;us\nPrecedesEqual=8fj;1gy\nPrecedesSlantEqual=6t8;uy\nPrecedesTilde=6ta;v4\nPrime=6cz;eg\nProduct=6q7;no\nProportion=6rb;q0\nProportional=6ql;oa\nPscr=2kkr;1jk\nPsi=q0;8z\nQUOT=y;3\nQfr=2kno;1ku\nQopf=6je;g5\nQscr=2kks;1jl\nRBarr=840;183\nREG=4u;1x\nRacute=9g;6o\nRang=7vv;174\nRarr=6n4;j4\nRarrtl=846;187\nRcaron=9k;6s\nRcedil=9i;6q\nRcy=tc;bb\nRe=6jg;gb\nReverseElement=6q3;nh\nReverseEquilibrium=6ob;le\nReverseUpEquilibrium=86n;1a4\nRfr=6jg;ga\nRho=pt;8t\nRightAngleBracket=7vt;170\nRightArrow=6mq;i3\nRightArrowBar=6p1;ml\nRightArrowLeftArrow=6o4;ky\nRightCeiling=6x5;123\nRightDoubleBracket=7vr;16v\nRightDownTeeVector=865;19l\nRightDownVector=6o2;kt\nRightDownVectorBar=85x;19d\nRightFloor=6x7;127\nRightTee=6ua;xo\nRightTeeArrow=6na;je\nRightTeeVector=863;19j\nRightTriangle=6ur;yd\nRightTriangleBar=89c;1c2\nRightTriangleEqual=6ut;yk\nRightUpDownVector=85r;197\nRightUpTeeVector=864;19k\nRightUpVector=6ny;kh\nRightUpVectorBar=85w;19c\nRightVector=6o0;kn\nRightVectorBar=85v;19b\nRightarrow=6oi;lx\nRopf=6jh;gd\nRoundImplies=86o;1a6\nRrightarrow=6or;mg\nRscr=6jf;g7\nRsh=6nl;jx\nRuleDelayed=8ac;1cb\nSHCHcy=tl;bk\nSHcy=tk;bj\nSOFTcy=to;bn\nSacute=9m;6u\nSc=8fw;1hm\nScaron=9s;70\nScedil=9q;6y\nScirc=9o;6w\nScy=td;bc\nSfr=2knq;1kv\nShortDownArrow=6mr;i7\nShortLeftArrow=6mo;ht\nShortRightArrow=6mq;i2\nShortUpArrow=6mp;hy\nSigma=pv;8u\nSmallCircle=6qg;o6\nSopf=2kp6;1m4\nSqrt=6qi;o9\nSquare=7fl;14t\nSquareIntersection=6tv;ww\nSquareSubset=6tr;wi\nSquareSubsetEqual=6tt;wp\nSquareSuperset=6ts;wm\nSquareSupersetEqual=6tu;ws\nSquareUnion=6tw;wz\nSscr=2kku;1jm\nStar=6va;zf\nSub=6vk;zw\nSubset=6vk;zv\nSubsetEqual=6ti;vu\nSucceeds=6t7;uv\nSucceedsEqual=8fk;1h4\nSucceedsSlantEqual=6t9;v1\nSucceedsTilde=6tb;v8\nSuchThat=6q3;ni\nSum=6q9;ns\nSup=6vl;zy\nSuperset=6tf;vp\nSupersetEqual=6tj;vx\nSupset=6vl;zx\nTHORN=66;3j\nTRADE=6jm;gf\nTSHcy=sr;ar\nTScy=ti;bh\nTab=9;0\nTau=pw;8v\nTcaron=9w;74\nTcedil=9u;72\nTcy=te;bd\nTfr=2knr;1kw\nTherefore=6r8;pt\nTheta=pk;8k\nThickSpace=6e7,6bu;et\nThinSpace=6bt;d7\nTilde=6rg;q9\nTildeEqual=6rn;qs\nTildeFullEqual=6rp;qy\nTildeTilde=6rs;r4\nTopf=2kp7;1m5\nTripleDot=6hn;f3\nTscr=2kkv;1jn\nTstrok=9y;76\nUacute=62;3f\nUarr=6n3;j2\nUarrocir=85l;193\nUbrcy=su;at\nUbreve=a4;7c\nUcirc=63;3g\nUcy=tf;be\nUdblac=a8;7g\nUfr=2kns;1kx\nUgrave=61;3e\nUmacr=a2;7a\nUnderBar=2n;11\nUnderBrace=733;13c\nUnderBracket=71x;136\nUnderParenthesis=731;13a\nUnion=6v7;z8\nUnionPlus=6tq;wf\nUogon=aa;7i\nUopf=2kp8;1m6\nUpArrow=6mp;hz\nUpArrowBar=842;185\nUpArrowDownArrow=6o5;l1\nUpDownArrow=6mt;ie\nUpEquilibrium=86m;1a2\nUpTee=6ud;xv\nUpTeeArrow=6n9;jc\nUparrow=6oh;lu\nUpdownarrow=6ol;m8\nUpperLeftArrow=6mu;ih\nUpperRightArrow=6mv;ik\nUpsi=r6;9z\nUpsilon=px;8w\nUring=a6;7e\nUscr=2kkw;1jo\nUtilde=a0;78\nUuml=64;3h\nVDash=6uj;y3\nVbar=8h7;1iw\nVcy=sy;ax\nVdash=6uh;y1\nVdashl=8h2;1is\nVee=6v5;z3\nVerbar=6c6;dp\nVert=6c6;dq\nVerticalBar=6qr;on\nVerticalLine=3g;18\nVerticalSeparator=7rs;16o\nVerticalTilde=6rk;qi\nVeryThinSpace=6bu;d9\nVfr=2knt;1ky\nVopf=2kp9;1m7\nVscr=2kkx;1jp\nVvdash=6ui;y2\nWcirc=ac;7k\nWedge=6v4;z0\nWfr=2knu;1kz\nWopf=2kpa;1m8\nWscr=2kky;1jq\nXfr=2knv;1l0\nXi=pq;8q\nXopf=2kpb;1m9\nXscr=2kkz;1jr\nYAcy=tr;bq\nYIcy=sn;an\nYUcy=tq;bp\nYacute=65;3i\nYcirc=ae;7m\nYcy=tn;bm\nYfr=2knw;1l1\nYopf=2kpc;1ma\nYscr=2kl0;1js\nYuml=ag;7o\nZHcy=t2;b1\nZacute=ah;7p\nZcaron=al;7t\nZcy=t3;b2\nZdot=aj;7r\nZeroWidthSpace=6bv;df\nZeta=pi;8i\nZfr=6js;gl\nZopf=6jo;gi\nZscr=2kl1;1jt\naacute=69;3m\nabreve=77;4l\nac=6ri;qg\nacE=6ri,mr;qe\nacd=6rj;qh\nacirc=6a;3n\nacute=50;28\nacy=ts;br\naelig=6e;3r\naf=6e9;ex\nafr=2kny;1l2\nagrave=68;3l\nalefsym=6k5;h3\naleph=6k5;h4\nalpha=q9;92\namacr=75;4j\namalg=8cf;1dm\namp=12;9\nand=6qv;p6\nandand=8d1;1e3\nandd=8d8;1e9\nandslope=8d4;1e6\nandv=8d6;1e7\nang=6qo;oj\nange=884;1b1\nangle=6qo;oi\nangmsd=6qp;ol\nangmsdaa=888;1b5\nangmsdab=889;1b6\nangmsdac=88a;1b7\nangmsdad=88b;1b8\nangmsdae=88c;1b9\nangmsdaf=88d;1ba\nangmsdag=88e;1bb\nangmsdah=88f;1bc\nangrt=6qn;og\nangrtvb=6v2;yw\nangrtvbd=87x;1b0\nangsph=6qq;om\nangst=5h;2u\nangzarr=70c;12z\naogon=79;4n\naopf=2kpe;1mb\nap=6rs;r8\napE=8ds;1ej\napacir=8dr;1eh\nape=6ru;rd\napid=6rv;rf\napos=13;a\napprox=6rs;r5\napproxeq=6ru;rc\naring=6d;3q\nascr=2kl2;1ju\nast=16;e\nasymp=6rs;r6\nasympeq=6rx;rj\natilde=6b;3o\nauml=6c;3p\nawconint=6r7;ps\nawint=8b5;1cr\nbNot=8h9;1iy\nbackcong=6rw;rg\nbackepsilon=s6;af\nbackprime=6d1;ei\nbacksim=6rh;qc\nbacksimeq=6vh;zp\nbarvee=6v1;yv\nbarwed=6x1;11y\nbarwedge=6x1;11x\nbbrk=71x;137\nbbrktbrk=71y;138\nbcong=6rw;rh\nbcy=tt;bs\nbdquo=6ce;e4\nbecaus=6r9;py\nbecause=6r9;px\nbemptyv=88g;1bd\nbepsi=s6;ag\nbernou=6jw;go\nbeta=qa;93\nbeth=6k6;h5\nbetween=6ss;tt\nbfr=2knz;1l3\nbigcap=6v6;z5\nbigcirc=7hr;15s\nbigcup=6v7;z7\nbigodot=8ao;1cd\nbigoplus=8ap;1cf\nbigotimes=8aq;1ch\nbigsqcup=8au;1cl\nbigstar=7id;15z\nbigtriangledown=7gd;15e\nbigtriangleup=7g3;154\nbiguplus=8as;1cj\nbigvee=6v5;z1\nbigwedge=6v4;yy\nbkarow=83x;17x\nblacklozenge=8a3;1c9\nblacksquare=7fu;14x\nblacktriangle=7g4;156\nblacktriangledown=7ge;15g\nblacktriangleleft=7gi;15k\nblacktriangleright=7g8;15a\nblank=74z;13f\nblk12=7f6;14r\nblk14=7f5;14q\nblk34=7f7;14s\nblock=7ew;14p\nbne=1p,6hx;o\nbnequiv=6sh,6hx;sm\nbnot=6xc;12d\nbopf=2kpf;1mc\nbot=6ud;xx\nbottom=6ud;xu\nbowtie=6vc;zi\nboxDL=7dj;141\nboxDR=7dg;13y\nboxDl=7di;140\nboxDr=7df;13x\nboxH=7dc;13u\nboxHD=7dy;14g\nboxHU=7e1;14j\nboxHd=7dw;14e\nboxHu=7dz;14h\nboxUL=7dp;147\nboxUR=7dm;144\nboxUl=7do;146\nboxUr=7dl;143\nboxV=7dd;13v\nboxVH=7e4;14m\nboxVL=7dv;14d\nboxVR=7ds;14a\nboxVh=7e3;14l\nboxVl=7du;14c\nboxVr=7dr;149\nboxbox=895;1bw\nboxdL=7dh;13z\nboxdR=7de;13w\nboxdl=7bk;13m\nboxdr=7bg;13l\nboxh=7b4;13j\nboxhD=7dx;14f\nboxhU=7e0;14i\nboxhd=7cc;13r\nboxhu=7ck;13s\nboxminus=6u7;xi\nboxplus=6u6;xg\nboxtimes=6u8;xk\nboxuL=7dn;145\nboxuR=7dk;142\nboxul=7bs;13o\nboxur=7bo;13n\nboxv=7b6;13k\nboxvH=7e2;14k\nboxvL=7dt;14b\nboxvR=7dq;148\nboxvh=7cs;13t\nboxvl=7c4;13q\nboxvr=7bw;13p\nbprime=6d1;ej\nbreve=k8;83\nbrvbar=4m;1k\nbscr=2kl3;1jv\nbsemi=6dr;er\nbsim=6rh;qd\nbsime=6vh;zq\nbsol=2k;x\nbsolb=891;1bv\nbsolhsub=7uw;16r\nbull=6ci;e9\nbullet=6ci;e8\nbump=6ry;rp\nbumpE=8fi;1gu\nbumpe=6rz;ru\nbumpeq=6rz;rt\ncacute=7b;4p\ncap=6qx;pa\ncapand=8ck;1dq\ncapbrcup=8cp;1dv\ncapcap=8cr;1dx\ncapcup=8cn;1dt\ncapdot=8cg;1dn\ncaps=6qx,1e68;p9\ncaret=6dd;eo\ncaron=jr;81\nccaps=8ct;1dz\nccaron=7h;4v\nccedil=6f;3s\nccirc=7d;4r\nccups=8cs;1dy\nccupssm=8cw;1e0\ncdot=7f;4t\ncedil=54;2f\ncemptyv=88i;1bf\ncent=4i;1g\ncenterdot=53;2c\ncfr=2ko0;1l4\nchcy=uf;ce\ncheck=7pv;16j\ncheckmark=7pv;16i\nchi=qv;9s\ncir=7gr;15q\ncirE=88z;1bt\ncirc=jq;7z\ncirceq=6s7;sc\ncirclearrowleft=6nu;k6\ncirclearrowright=6nv;k8\ncircledR=4u;1w\ncircledS=79k;13g\ncircledast=6u3;xc\ncircledcirc=6u2;xa\ncircleddash=6u5;xe\ncire=6s7;sd\ncirfnint=8b4;1cq\ncirmid=8hb;1j0\ncirscir=88y;1bs\nclubs=7kz;168\nclubsuit=7kz;167\ncolon=1m;j\ncolone=6s4;s7\ncoloneq=6s4;s5\ncomma=18;g\ncommat=1s;u\ncomp=6pt;mv\ncompfn=6qg;o7\ncomplement=6pt;mu\ncomplexes=6iq;f6\ncong=6rp;qz\ncongdot=8dp;1ef\nconint=6r2;pj\ncopf=2kpg;1md\ncoprod=6q8;nr\ncopy=4p;1r\ncopysr=6jb;fz\ncrarr=6np;k1\ncross=7pz;16k\ncscr=2kl4;1jw\ncsub=8gf;1id\ncsube=8gh;1if\ncsup=8gg;1ie\ncsupe=8gi;1ig\nctdot=6wf;11g\ncudarrl=854;18x\ncudarrr=851;18u\ncuepr=6vy;10m\ncuesc=6vz;10o\ncularr=6nq;k3\ncularrp=859;190\ncup=6qy;pc\ncupbrcap=8co;1du\ncupcap=8cm;1ds\ncupcup=8cq;1dw\ncupdot=6tp;we\ncupor=8cl;1dr\ncups=6qy,1e68;pb\ncurarr=6nr;k5\ncurarrm=858;18z\ncurlyeqprec=6vy;10l\ncurlyeqsucc=6vz;10n\ncurlyvee=6vi;zr\ncurlywedge=6vj;zt\ncurren=4k;1i\ncurvearrowleft=6nq;k2\ncurvearrowright=6nr;k4\ncuvee=6vi;zs\ncuwed=6vj;zu\ncwconint=6r6;pq\ncwint=6r5;po\ncylcty=6y5;12u\ndArr=6oj;m2\ndHar=86d;19t\ndagger=6cg;e5\ndaleth=6k8;h7\ndarr=6mr;ia\ndash=6c0;dl\ndashv=6ub;xr\ndbkarow=83z;180\ndblac=kd;8b\ndcaron=7j;4x\ndcy=tw;bv\ndd=6km;hb\nddagger=6ch;e6\nddarr=6oa;ld\nddotseq=8dz;1ep\ndeg=4w;21\ndelta=qc;95\ndemptyv=88h;1be\ndfisht=873;1aj\ndfr=2ko1;1l5\ndharl=6o3;kx\ndharr=6o2;ku\ndiam=6v8;zc\ndiamond=6v8;zb\ndiamondsuit=7l2;16b\ndiams=7l2;16c\ndie=4o;1o\ndigamma=rh;a6\ndisin=6wi;11j\ndiv=6v;49\ndivide=6v;48\ndivideontimes=6vb;zg\ndivonx=6vb;zh\ndjcy=uq;co\ndlcorn=6xq;12n\ndlcrop=6x9;12a\ndollar=10;6\ndopf=2kph;1me\ndot=k9;85\ndoteq=6s0;rx\ndoteqdot=6s1;rz\ndotminus=6rc;q2\ndotplus=6qc;ny\ndotsquare=6u9;xm\ndoublebarwedge=6x2;11z\ndownarrow=6mr;i9\ndowndownarrows=6oa;lc\ndownharpoonleft=6o3;kv\ndownharpoonright=6o2;ks\ndrbkarow=840;182\ndrcorn=6xr;12p\ndrcrop=6x8;129\ndscr=2kl5;1jx\ndscy=ut;cr\ndsol=8ae;1cc\ndstrok=7l;4z\ndtdot=6wh;11i\ndtri=7gf;15j\ndtrif=7ge;15h\nduarr=6ph;mo\nduhar=86n;1a5\ndwangle=886;1b3\ndzcy=v3;d0\ndzigrarr=7wf;17r\neDDot=8dz;1eq\neDot=6s1;s0\neacute=6h;3u\neaster=8dq;1eg\necaron=7v;57\necir=6s6;sb\necirc=6i;3v\necolon=6s5;s9\necy=ul;ck\nedot=7r;53\nee=6kn;he\nefDot=6s2;s2\nefr=2ko2;1l6\neg=8ey;1g9\negrave=6g;3t\negs=8eu;1g5\negsdot=8ew;1g7\nel=8ex;1g8\nelinters=73b;13e\nell=6j7;fv\nels=8et;1g3\nelsdot=8ev;1g6\nemacr=7n;51\nempty=6px;n7\nemptyset=6px;n5\nemptyv=6px;n6\nemsp=6bn;d2\nemsp13=6bo;d3\nemsp14=6bp;d4\neng=97;6h\nensp=6bm;d1\neogon=7t;55\neopf=2kpi;1mf\nepar=6vp;103\neparsl=89v;1c6\neplus=8dt;1ek\nepsi=qd;97\nepsilon=qd;96\nepsiv=s5;ae\neqcirc=6s6;sa\neqcolon=6s5;s8\neqsim=6rm;qq\neqslantgtr=8eu;1g4\neqslantless=8et;1g2\nequals=1p;p\nequest=6sf;sj\nequiv=6sh;so\nequivDD=8e0;1er\neqvparsl=89x;1c8\nerDot=6s3;s4\nerarr=86p;1a7\nescr=6jz;gs\nesdot=6s0;ry\nesim=6rm;qr\neta=qf;99\neth=6o;41\neuml=6j;3w\neuro=6gc;f2\nexcl=x;2\nexist=6pv;n0\nexpectation=6k0;gt\nexponentiale=6kn;hd\nfallingdotseq=6s2;s1\nfcy=uc;cb\nfemale=7k0;163\nffilig=1dkz;1ja\nfflig=1dkw;1j7\nffllig=1dl0;1jb\nffr=2ko3;1l7\nfilig=1dkx;1j8\nfjlig=2u,2y;15\nflat=7l9;16e\nfllig=1dky;1j9\nfltns=7g1;153\nfnof=b6;7v\nfopf=2kpj;1mg\nforall=6ps;mt\nfork=6vo;102\nforkv=8gp;1in\nfpartint=8b1;1cp\nfrac12=59;2k\nfrac13=6kz;hh\nfrac14=58;2j\nfrac15=6l1;hj\nfrac16=6l5;hn\nfrac18=6l7;hp\nfrac23=6l0;hi\nfrac25=6l2;hk\nfrac34=5a;2m\nfrac35=6l3;hl\nfrac38=6l8;hq\nfrac45=6l4;hm\nfrac56=6l6;ho\nfrac58=6l9;hr\nfrac78=6la;hs\nfrasl=6dg;eq\nfrown=6xu;12r\nfscr=2kl7;1jy\ngE=6sn;t8\ngEl=8ek;1ft\ngacute=dx;7x\ngamma=qb;94\ngammad=rh;a7\ngap=8ee;1fh\ngbreve=7z;5b\ngcirc=7x;59\ngcy=tv;bu\ngdot=81;5d\nge=6sl;sx\ngel=6vv;10k\ngeq=6sl;sw\ngeqq=6sn;t7\ngeqslant=8e6;1f6\nges=8e6;1f7\ngescc=8fd;1gn\ngesdot=8e8;1f9\ngesdoto=8ea;1fb\ngesdotol=8ec;1fd\ngesl=6vv,1e68;10h\ngesles=8es;1g1\ngfr=2ko4;1l8\ngg=6sr;ts\nggg=6vt;10b\ngimel=6k7;h6\ngjcy=ur;cp\ngl=6t3;un\nglE=8eq;1fz\ngla=8f9;1gj\nglj=8f8;1gi\ngnE=6sp;tg\ngnap=8ei;1fp\ngnapprox=8ei;1fo\ngne=8eg;1fl\ngneq=8eg;1fk\ngneqq=6sp;tf\ngnsim=6w7;10y\ngopf=2kpk;1mh\ngrave=2o;14\ngscr=6iy;f9\ngsim=6sz;ud\ngsime=8em;1fv\ngsiml=8eo;1fx\ngt=1q;s\ngtcc=8fb;1gl\ngtcir=8e2;1et\ngtdot=6vr;107\ngtlPar=87p;1aw\ngtquest=8e4;1ev\ngtrapprox=8ee;1fg\ngtrarr=86w;1ad\ngtrdot=6vr;106\ngtreqless=6vv;10j\ngtreqqless=8ek;1fs\ngtrless=6t3;um\ngtrsim=6sz;uc\ngvertneqq=6sp,1e68;td\ngvnE=6sp,1e68;te\nhArr=6ok;m5\nhairsp=6bu;da\nhalf=59;2l\nhamilt=6iz;fb\nhardcy=ui;ch\nharr=6ms;id\nharrcir=85k;192\nharrw=6nh;js\nhbar=6j3;fl\nhcirc=85;5g\nhearts=7l1;16a\nheartsuit=7l1;169\nhellip=6cm;eb\nhercon=6ux;yr\nhfr=2ko5;1l9\nhksearow=84l;18i\nhkswarow=84m;18k\nhoarr=6pr;mr\nhomtht=6rf;q5\nhookleftarrow=6nd;jj\nhookrightarrow=6ne;jl\nhopf=2kpl;1mi\nhorbar=6c5;do\nhscr=2kl9;1jz\nhslash=6j3;fi\nhstrok=87;5i\nhybull=6df;ep\nhyphen=6c0;dk\niacute=6l;3y\nic=6eb;f1\nicirc=6m;3z\nicy=u0;bz\niecy=tx;bw\niexcl=4h;1f\niff=6ok;m6\nifr=2ko6;1la\nigrave=6k;3x\nii=6ko;hg\niiiint=8b0;1cn\niiint=6r1;pg\niinfin=89o;1c3\niiota=6jt;gm\nijlig=8j;5t\nimacr=8b;5m\nimage=6j5;fp\nimagline=6j4;fm\nimagpart=6j5;fo\nimath=8h;5r\nimof=6uv;yo\nimped=c5;7w\nin=6q0;nd\nincare=6it;f8\ninfin=6qm;of\ninfintie=89p;1c4\ninodot=8h;5q\nint=6qz;pe\nintcal=6uy;yt\nintegers=6jo;gh\nintercal=6uy;ys\nintlarhk=8bb;1cx\nintprod=8cc;1dk\niocy=up;cn\niogon=8f;5o\niopf=2kpm;1mj\niota=qh;9b\niprod=8cc;1dl\niquest=5b;2n\niscr=2kla;1k0\nisin=6q0;nc\nisinE=6wp;11r\nisindot=6wl;11n\nisins=6wk;11l\nisinsv=6wj;11k\nisinv=6q0;nb\nit=6ea;ez\nitilde=89;5k\niukcy=uu;cs\niuml=6n;40\njcirc=8l;5v\njcy=u1;c0\njfr=2ko7;1lb\njmath=fr;7y\njopf=2kpn;1mk\njscr=2klb;1k1\njsercy=uw;cu\njukcy=us;cq\nkappa=qi;9c\nkappav=s0;a9\nkcedil=8n;5x\nkcy=u2;c1\nkfr=2ko8;1lc\nkgreen=8o;5y\nkhcy=ud;cc\nkjcy=v0;cy\nkopf=2kpo;1ml\nkscr=2klc;1k2\nlAarr=6oq;mf\nlArr=6og;ls\nlAtail=84b;18a\nlBarr=83y;17z\nlE=6sm;t2\nlEg=8ej;1fr\nlHar=86a;19q\nlacute=8q;60\nlaemptyv=88k;1bh\nlagran=6j6;ft\nlambda=qj;9d\nlang=7vs;16z\nlangd=87l;1as\nlangle=7vs;16y\nlap=8ed;1ff\nlaquo=4r;1t\nlarr=6mo;hx\nlarrb=6p0;mk\nlarrbfs=84f;18e\nlarrfs=84d;18c\nlarrhk=6nd;jk\nlarrlp=6nf;jo\nlarrpl=855;18y\nlarrsim=86r;1a9\nlarrtl=6n6;j7\nlat=8ff;1gp\nlatail=849;188\nlate=8fh;1gt\nlates=8fh,1e68;1gs\nlbarr=83w;17w\nlbbrk=7si;16p\nlbrace=3f;16\nlbrack=2j;v\nlbrke=87f;1am\nlbrksld=87j;1aq\nlbrkslu=87h;1ao\nlcaron=8u;64\nlcedil=8s;62\nlceil=6x4;122\nlcub=3f;17\nlcy=u3;c2\nldca=852;18v\nldquo=6cc;dz\nldquor=6ce;e3\nldrdhar=86f;19v\nldrushar=85n;195\nldsh=6nm;jz\nle=6sk;st\nleftarrow=6mo;hv\nleftarrowtail=6n6;j6\nleftharpoondown=6nx;kd\nleftharpoonup=6nw;ka\nleftleftarrows=6o7;l6\nleftrightarrow=6ms;ic\nleftrightarrows=6o6;l4\nleftrightharpoons=6ob;lf\nleftrightsquigarrow=6nh;jr\nleftthreetimes=6vf;zl\nleg=6vu;10g\nleq=6sk;ss\nleqq=6sm;t1\nleqslant=8e5;1f0\nles=8e5;1f1\nlescc=8fc;1gm\nlesdot=8e7;1f8\nlesdoto=8e9;1fa\nlesdotor=8eb;1fc\nlesg=6vu,1e68;10d\nlesges=8er;1g0\nlessapprox=8ed;1fe\nlessdot=6vq;104\nlesseqgtr=6vu;10f\nlesseqqgtr=8ej;1fq\nlessgtr=6t2;uj\nlesssim=6sy;u9\nlfisht=870;1ag\nlfloor=6x6;126\nlfr=2ko9;1ld\nlg=6t2;uk\nlgE=8ep;1fy\nlhard=6nx;kf\nlharu=6nw;kc\nlharul=86i;19y\nlhblk=7es;14o\nljcy=ux;cv\nll=6sq;tm\nllarr=6o7;l7\nllcorner=6xq;12m\nllhard=86j;19z\nlltri=7i2;15w\nlmidot=8w;66\nlmoust=71s;131\nlmoustache=71s;130\nlnE=6so;tc\nlnap=8eh;1fn\nlnapprox=8eh;1fm\nlne=8ef;1fj\nlneq=8ef;1fi\nlneqq=6so;tb\nlnsim=6w6;10x\nloang=7vw;175\nloarr=6pp;mp\nlobrk=7vq;16u\nlongleftarrow=7w5;178\nlongleftrightarrow=7w7;17e\nlongmapsto=7wc;17p\nlongrightarrow=7w6;17b\nlooparrowleft=6nf;jn\nlooparrowright=6ng;jp\nlopar=879;1ak\nlopf=2kpp;1mm\nloplus=8bx;1d6\nlotimes=8c4;1dc\nlowast=6qf;o5\nlowbar=2n;12\nloz=7gq;15p\nlozenge=7gq;15o\nlozf=8a3;1ca\nlpar=14;b\nlparlt=87n;1au\nlrarr=6o6;l5\nlrcorner=6xr;12o\nlrhar=6ob;lg\nlrhard=86l;1a1\nlrm=6by;di\nlrtri=6v3;yx\nlsaquo=6d5;ek\nlscr=2kld;1k3\nlsh=6nk;jw\nlsim=6sy;ua\nlsime=8el;1fu\nlsimg=8en;1fw\nlsqb=2j;w\nlsquo=6c8;ds\nlsquor=6ca;dw\nlstrok=8y;68\nlt=1o;n\nltcc=8fa;1gk\nltcir=8e1;1es\nltdot=6vq;105\nlthree=6vf;zm\nltimes=6vd;zj\nltlarr=86u;1ac\nltquest=8e3;1eu\nltrPar=87q;1ax\nltri=7gj;15n\nltrie=6us;yi\nltrif=7gi;15l\nlurdshar=85m;194\nluruhar=86e;19u\nlvertneqq=6so,1e68;t9\nlvnE=6so,1e68;ta\nmDDot=6re;q4\nmacr=4v;20\nmale=7k2;164\nmalt=7q8;16m\nmaltese=7q8;16l\nmap=6na;jg\nmapsto=6na;jf\nmapstodown=6nb;ji\nmapstoleft=6n8;jb\nmapstoup=6n9;jd\nmarker=7fy;152\nmcomma=8bt;1d4\nmcy=u4;c3\nmdash=6c4;dn\nmeasuredangle=6qp;ok\nmfr=2koa;1le\nmho=6jr;gj\nmicro=51;29\nmid=6qr;oq\nmidast=16;d\nmidcir=8hc;1j1\nmiddot=53;2d\nminus=6qa;nu\nminusb=6u7;xj\nminusd=6rc;q3\nminusdu=8bu;1d5\nmlcp=8gr;1ip\nmldr=6cm;ec\nmnplus=6qb;nw\nmodels=6uf;xy\nmopf=2kpq;1mn\nmp=6qb;nx\nmscr=2kle;1k4\nmstpos=6ri;qf\nmu=qk;9e\nmultimap=6uw;yp\nmumap=6uw;yq\nnGg=6vt,mw;10a\nnGt=6sr,6he;tp\nnGtv=6sr,mw;to\nnLeftarrow=6od;lk\nnLeftrightarrow=6oe;lm\nnLl=6vs,mw;108\nnLt=6sq,6he;tj\nnLtv=6sq,mw;ti\nnRightarrow=6of;lo\nnVDash=6un;y7\nnVdash=6um;y6\nnabla=6pz;n8\nnacute=90;6a\nnang=6qo,6he;oh\nnap=6rt;rb\nnapE=8ds,mw;1ei\nnapid=6rv,mw;re\nnapos=95;6f\nnapprox=6rt;ra\nnatur=7la;16g\nnatural=7la;16f\nnaturals=6j9;fw\nnbsp=4g;1e\nnbump=6ry,mw;rm\nnbumpe=6rz,mw;rr\nncap=8cj;1dp\nncaron=94;6e\nncedil=92;6c\nncong=6rr;r2\nncongdot=8dp,mw;1ee\nncup=8ci;1do\nncy=u5;c4\nndash=6c3;dm\nne=6sg;sl\nneArr=6on;mb\nnearhk=84k;18h\nnearr=6mv;im\nnearrow=6mv;il\nnedot=6s0,mw;rv\nnequiv=6si;sq\nnesear=84o;18n\nnesim=6rm,mw;qo\nnexist=6pw;n3\nnexists=6pw;n2\nnfr=2kob;1lf\nngE=6sn,mw;t4\nnge=6sx;u7\nngeq=6sx;u6\nngeqq=6sn,mw;t5\nngeqslant=8e6,mw;1f3\nnges=8e6,mw;1f4\nngsim=6t1;uh\nngt=6sv;u1\nngtr=6sv;u0\nnhArr=6oe;ln\nnharr=6ni;ju\nnhpar=8he;1j3\nni=6q3;nk\nnis=6ws;11u\nnisd=6wq;11s\nniv=6q3;nj\nnjcy=uy;cw\nnlArr=6od;ll\nnlE=6sm,mw;sy\nnlarr=6my;iu\nnldr=6cl;ea\nnle=6sw;u4\nnleftarrow=6my;it\nnleftrightarrow=6ni;jt\nnleq=6sw;u3\nnleqq=6sm,mw;sz\nnleqslant=8e5,mw;1ex\nnles=8e5,mw;1ey\nnless=6su;tx\nnlsim=6t0;uf\nnlt=6su;ty\nnltri=6wa;115\nnltrie=6wc;11b\nnmid=6qs;ou\nnopf=2kpr;1mo\nnot=4s;1u\nnotin=6q1;ng\nnotinE=6wp,mw;11q\nnotindot=6wl,mw;11m\nnotinva=6q1;nf\nnotinvb=6wn;11p\nnotinvc=6wm;11o\nnotni=6q4;nn\nnotniva=6q4;nm\nnotnivb=6wu;11w\nnotnivc=6wt;11v\nnpar=6qu;p4\nnparallel=6qu;p2\nnparsl=8hp,6hx;1j5\nnpart=6pu,mw;mw\nnpolint=8b8;1cu\nnpr=6tc;vd\nnprcue=6w0;10q\nnpre=8fj,mw;1gw\nnprec=6tc;vc\nnpreceq=8fj,mw;1gx\nnrArr=6of;lp\nnrarr=6mz;iw\nnrarrc=84z,mw;18s\nnrarrw=6n1,mw;ix\nnrightarrow=6mz;iv\nnrtri=6wb;118\nnrtrie=6wd;11e\nnsc=6td;vg\nnsccue=6w1;10s\nnsce=8fk,mw;1h2\nnscr=2klf;1k5\nnshortmid=6qs;os\nnshortparallel=6qu;p1\nnsim=6rl;qm\nnsime=6ro;qx\nnsimeq=6ro;qw\nnsmid=6qs;ot\nnspar=6qu;p3\nnsqsube=6w2;10u\nnsqsupe=6w3;10w\nnsub=6tg;vs\nnsubE=8g5,mw;1hv\nnsube=6tk;w2\nnsubset=6te,6he;vi\nnsubseteq=6tk;w1\nnsubseteqq=8g5,mw;1hw\nnsucc=6td;vf\nnsucceq=8fk,mw;1h3\nnsup=6th;vt\nnsupE=8g6,mw;1hz\nnsupe=6tl;w5\nnsupset=6tf,6he;vn\nnsupseteq=6tl;w4\nnsupseteqq=8g6,mw;1i0\nntgl=6t5;ur\nntilde=6p;42\nntlg=6t4;up\nntriangleleft=6wa;114\nntrianglelefteq=6wc;11a\nntriangleright=6wb;117\nntrianglerighteq=6wd;11d\nnu=ql;9f\nnum=z;5\nnumero=6ja;fy\nnumsp=6br;d5\nnvDash=6ul;y5\nnvHarr=83o;17u\nnvap=6rx,6he;ri\nnvdash=6uk;y4\nnvge=6sl,6he;su\nnvgt=1q,6he;q\nnvinfin=89q;1c5\nnvlArr=83m;17s\nnvle=6sk,6he;sr\nnvlt=1o,6he;l\nnvltrie=6us,6he;yf\nnvrArr=83n;17t\nnvrtrie=6ut,6he;yj\nnvsim=6rg,6he;q6\nnwArr=6om;ma\nnwarhk=84j;18g\nnwarr=6mu;ij\nnwarrow=6mu;ii\nnwnear=84n;18m\noS=79k;13h\noacute=6r;44\noast=6u3;xd\nocir=6u2;xb\nocirc=6s;45\nocy=u6;c5\nodash=6u5;xf\nodblac=9d;6l\nodiv=8c8;1dg\nodot=6u1;x9\nodsold=88s;1bn\noelig=9f;6n\nofcir=88v;1bp\nofr=2koc;1lg\nogon=kb;87\nograve=6q;43\nogt=88x;1br\nohbar=88l;1bi\nohm=q1;91\noint=6r2;pk\nolarr=6nu;k7\nolcir=88u;1bo\nolcross=88r;1bm\noline=6da;en\nolt=88w;1bq\nomacr=99;6j\nomega=qx;9u\nomicron=qn;9h\nomid=88m;1bj\nominus=6ty;x4\noopf=2kps;1mp\nopar=88n;1bk\noperp=88p;1bl\noplus=6tx;x2\nor=6qw;p8\norarr=6nv;k9\nord=8d9;1ea\norder=6k4;h1\norderof=6k4;h0\nordf=4q;1s\nordm=56;2h\norigof=6uu;yn\noror=8d2;1e4\norslope=8d3;1e5\norv=8d7;1e8\noscr=6k4;h2\noslash=6w;4a\nosol=6u0;x7\notilde=6t;46\notimes=6tz;x6\notimesas=8c6;1de\nouml=6u;47\novbar=6yl;12x\npar=6qt;oz\npara=52;2a\nparallel=6qt;ox\nparsim=8hf;1j4\nparsl=8hp;1j6\npart=6pu;my\npcy=u7;c6\npercnt=11;7\nperiod=1a;h\npermil=6cw;ed\nperp=6ud;xw\npertenk=6cx;ee\npfr=2kod;1lh\nphi=qu;9r\nphiv=r9;a2\nphmmat=6k3;gy\nphone=7im;162\npi=qo;9i\npitchfork=6vo;101\npiv=ra;a4\nplanck=6j3;fj\nplanckh=6j2;fh\nplankv=6j3;fk\nplus=17;f\nplusacir=8bn;1cz\nplusb=6u6;xh\npluscir=8bm;1cy\nplusdo=6qc;nz\nplusdu=8bp;1d1\npluse=8du;1el\nplusmn=4x;23\nplussim=8bq;1d2\nplustwo=8br;1d3\npm=4x;24\npointint=8b9;1cv\npopf=2kpt;1mq\npound=4j;1h\npr=6t6;uu\nprE=8fn;1h7\nprap=8fr;1he\nprcue=6t8;v0\npre=8fj;1h0\nprec=6t6;ut\nprecapprox=8fr;1hd\npreccurlyeq=6t8;uz\npreceq=8fj;1gz\nprecnapprox=8ft;1hh\nprecneqq=8fp;1h9\nprecnsim=6w8;10z\nprecsim=6ta;v5\nprime=6cy;ef\nprimes=6jd;g2\nprnE=8fp;1ha\nprnap=8ft;1hi\nprnsim=6w8;110\nprod=6q7;np\nprofalar=6y6;12v\nprofline=6xe;12e\nprofsurf=6xf;12f\nprop=6ql;oe\npropto=6ql;oc\nprsim=6ta;v6\nprurel=6uo;y8\npscr=2klh;1k6\npsi=qw;9t\npuncsp=6bs;d6\nqfr=2koe;1li\nqint=8b0;1co\nqopf=2kpu;1mr\nqprime=6dz;es\nqscr=2kli;1k7\nquaternions=6j1;ff\nquatint=8ba;1cw\nquest=1r;t\nquesteq=6sf;si\nquot=y;4\nrAarr=6or;mh\nrArr=6oi;lz\nrAtail=84c;18b\nrBarr=83z;181\nrHar=86c;19s\nrace=6rh,mp;qb\nracute=9h;6p\nradic=6qi;o8\nraemptyv=88j;1bg\nrang=7vt;172\nrangd=87m;1at\nrange=885;1b2\nrangle=7vt;171\nraquo=57;2i\nrarr=6mq;i6\nrarrap=86t;1ab\nrarrb=6p1;mm\nrarrbfs=84g;18f\nrarrc=84z;18t\nrarrfs=84e;18d\nrarrhk=6ne;jm\nrarrlp=6ng;jq\nrarrpl=85h;191\nrarrsim=86s;1aa\nrarrtl=6n7;j9\nrarrw=6n1;iz\nratail=84a;189\nratio=6ra;pz\nrationals=6je;g4\nrbarr=83x;17y\nrbbrk=7sj;16q\nrbrace=3h;1b\nrbrack=2l;y\nrbrke=87g;1an\nrbrksld=87i;1ap\nrbrkslu=87k;1ar\nrcaron=9l;6t\nrcedil=9j;6r\nrceil=6x5;124\nrcub=3h;1c\nrcy=u8;c7\nrdca=853;18w\nrdldhar=86h;19x\nrdquo=6cd;e2\nrdquor=6cd;e1\nrdsh=6nn;k0\nreal=6jg;g9\nrealine=6jf;g6\nrealpart=6jg;g8\nreals=6jh;gc\nrect=7fx;151\nreg=4u;1y\nrfisht=871;1ah\nrfloor=6x7;128\nrfr=2kof;1lj\nrhard=6o1;kr\nrharu=6o0;ko\nrharul=86k;1a0\nrho=qp;9j\nrhov=s1;ab\nrightarrow=6mq;i4\nrightarrowtail=6n7;j8\nrightharpoondown=6o1;kp\nrightharpoonup=6o0;km\nrightleftarrows=6o4;kz\nrightleftharpoons=6oc;lh\nrightrightarrows=6o9;la\nrightsquigarrow=6n1;iy\nrightthreetimes=6vg;zn\nring=ka;86\nrisingdotseq=6s3;s3\nrlarr=6o4;l0\nrlhar=6oc;lj\nrlm=6bz;dj\nrmoust=71t;133\nrmoustache=71t;132\nrnmid=8ha;1iz\nroang=7vx;176\nroarr=6pq;mq\nrobrk=7vr;16w\nropar=87a;1al\nropf=2kpv;1ms\nroplus=8by;1d7\nrotimes=8c5;1dd\nrpar=15;c\nrpargt=87o;1av\nrppolint=8b6;1cs\nrrarr=6o9;lb\nrsaquo=6d6;el\nrscr=2klj;1k8\nrsh=6nl;jy\nrsqb=2l;z\nrsquo=6c9;dv\nrsquor=6c9;du\nrthree=6vg;zo\nrtimes=6ve;zk\nrtri=7g9;15d\nrtrie=6ut;ym\nrtrif=7g8;15b\nrtriltri=89a;1by\nruluhar=86g;19w\nrx=6ji;ge\nsacute=9n;6v\nsbquo=6ca;dx\nsc=6t7;ux\nscE=8fo;1h8\nscap=8fs;1hg\nscaron=9t;71\nsccue=6t9;v3\nsce=8fk;1h6\nscedil=9r;6z\nscirc=9p;6x\nscnE=8fq;1hc\nscnap=8fu;1hk\nscnsim=6w9;112\nscpolint=8b7;1ct\nscsim=6tb;va\nscy=u9;c8\nsdot=6v9;zd\nsdotb=6u9;xn\nsdote=8di;1ec\nseArr=6oo;mc\nsearhk=84l;18j\nsearr=6mw;ip\nsearrow=6mw;io\nsect=4n;1l\nsemi=1n;k\nseswar=84p;18p\nsetminus=6qe;o2\nsetmn=6qe;o4\nsext=7qu;16n\nsfr=2kog;1lk\nsfrown=6xu;12q\nsharp=7lb;16h\nshchcy=uh;cg\nshcy=ug;cf\nshortmid=6qr;oo\nshortparallel=6qt;ow\nshy=4t;1v\nsigma=qr;9n\nsigmaf=qq;9l\nsigmav=qq;9m\nsim=6rg;qa\nsimdot=8dm;1ed\nsime=6rn;qu\nsimeq=6rn;qt\nsimg=8f2;1gb\nsimgE=8f4;1gd\nsiml=8f1;1ga\nsimlE=8f3;1gc\nsimne=6rq;r0\nsimplus=8bo;1d0\nsimrarr=86q;1a8\nslarr=6mo;hw\nsmallsetminus=6qe;o0\nsmashp=8c3;1db\nsmeparsl=89w;1c7\nsmid=6qr;op\nsmile=6xv;12t\nsmt=8fe;1go\nsmte=8fg;1gr\nsmtes=8fg,1e68;1gq\nsoftcy=uk;cj\nsol=1b;i\nsolb=890;1bu\nsolbar=6yn;12y\nsopf=2kpw;1mt\nspades=7kw;166\nspadesuit=7kw;165\nspar=6qt;oy\nsqcap=6tv;wx\nsqcaps=6tv,1e68;wv\nsqcup=6tw;x0\nsqcups=6tw,1e68;wy\nsqsub=6tr;wk\nsqsube=6tt;wr\nsqsubset=6tr;wj\nsqsubseteq=6tt;wq\nsqsup=6ts;wo\nsqsupe=6tu;wu\nsqsupset=6ts;wn\nsqsupseteq=6tu;wt\nsqu=7fl;14v\nsquare=7fl;14u\nsquarf=7fu;14y\nsquf=7fu;14z\nsrarr=6mq;i5\nsscr=2klk;1k9\nssetmn=6qe;o3\nssmile=6xv;12s\nsstarf=6va;ze\nstar=7ie;161\nstarf=7id;160\nstraightepsilon=s5;ac\nstraightphi=r9;a0\nstrns=4v;1z\nsub=6te;vl\nsubE=8g5;1hy\nsubdot=8fx;1hn\nsube=6ti;vw\nsubedot=8g3;1ht\nsubmult=8g1;1hr\nsubnE=8gb;1i8\nsubne=6tm;w9\nsubplus=8fz;1hp\nsubrarr=86x;1ae\nsubset=6te;vk\nsubseteq=6ti;vv\nsubseteqq=8g5;1hx\nsubsetneq=6tm;w8\nsubsetneqq=8gb;1i7\nsubsim=8g7;1i3\nsubsub=8gl;1ij\nsubsup=8gj;1ih\nsucc=6t7;uw\nsuccapprox=8fs;1hf\nsucccurlyeq=6t9;v2\nsucceq=8fk;1h5\nsuccnapprox=8fu;1hj\nsuccneqq=8fq;1hb\nsuccnsim=6w9;111\nsuccsim=6tb;v9\nsum=6q9;nt\nsung=7l6;16d\nsup=6tf;vr\nsup1=55;2g\nsup2=4y;25\nsup3=4z;26\nsupE=8g6;1i2\nsupdot=8fy;1ho\nsupdsub=8go;1im\nsupe=6tj;vz\nsupedot=8g4;1hu\nsuphsol=7ux;16s\nsuphsub=8gn;1il\nsuplarr=86z;1af\nsupmult=8g2;1hs\nsupnE=8gc;1ic\nsupne=6tn;wd\nsupplus=8g0;1hq\nsupset=6tf;vq\nsupseteq=6tj;vy\nsupseteqq=8g6;1i1\nsupsetneq=6tn;wc\nsupsetneqq=8gc;1ib\nsupsim=8g8;1i4\nsupsub=8gk;1ii\nsupsup=8gm;1ik\nswArr=6op;md\nswarhk=84m;18l\nswarr=6mx;is\nswarrow=6mx;ir\nswnwar=84q;18r\nszlig=67;3k\ntarget=6xi;12h\ntau=qs;9o\ntbrk=71w;135\ntcaron=9x;75\ntcedil=9v;73\ntcy=ua;c9\ntdot=6hn;f4\ntelrec=6xh;12g\ntfr=2koh;1ll\nthere4=6r8;pv\ntherefore=6r8;pu\ntheta=qg;9a\nthetasym=r5;9v\nthetav=r5;9x\nthickapprox=6rs;r3\nthicksim=6rg;q7\nthinsp=6bt;d8\nthkap=6rs;r7\nthksim=6rg;q8\nthorn=72;4g\ntilde=kc;89\ntimes=5z;3c\ntimesb=6u8;xl\ntimesbar=8c1;1da\ntimesd=8c0;1d9\ntint=6r1;ph\ntoea=84o;18o\ntop=6uc;xt\ntopbot=6ye;12w\ntopcir=8hd;1j2\ntopf=2kpx;1mu\ntopfork=8gq;1io\ntosa=84p;18q\ntprime=6d0;eh\ntrade=6jm;gg\ntriangle=7g5;158\ntriangledown=7gf;15i\ntriangleleft=7gj;15m\ntrianglelefteq=6us;yh\ntriangleq=6sc;sg\ntriangleright=7g9;15c\ntrianglerighteq=6ut;yl\ntridot=7ho;15r\ntrie=6sc;sh\ntriminus=8ca;1di\ntriplus=8c9;1dh\ntrisb=899;1bx\ntritime=8cb;1dj\ntrpezium=736;13d\ntscr=2kll;1ka\ntscy=ue;cd\ntshcy=uz;cx\ntstrok=9z;77\ntwixt=6ss;tu\ntwoheadleftarrow=6n2;j0\ntwoheadrightarrow=6n4;j3\nuArr=6oh;lv\nuHar=86b;19r\nuacute=6y;4c\nuarr=6mp;i1\nubrcy=v2;cz\nubreve=a5;7d\nucirc=6z;4d\nucy=ub;ca\nudarr=6o5;l2\nudblac=a9;7h\nudhar=86m;1a3\nufisht=872;1ai\nufr=2koi;1lm\nugrave=6x;4b\nuharl=6nz;kl\nuharr=6ny;ki\nuhblk=7eo;14n\nulcorn=6xo;12j\nulcorner=6xo;12i\nulcrop=6xb;12c\nultri=7i0;15u\numacr=a3;7b\numl=4o;1p\nuogon=ab;7j\nuopf=2kpy;1mv\nuparrow=6mp;i0\nupdownarrow=6mt;if\nupharpoonleft=6nz;kj\nupharpoonright=6ny;kg\nuplus=6tq;wg\nupsi=qt;9q\nupsih=r6;9y\nupsilon=qt;9p\nupuparrows=6o8;l8\nurcorn=6xp;12l\nurcorner=6xp;12k\nurcrop=6xa;12b\nuring=a7;7f\nurtri=7i1;15v\nuscr=2klm;1kb\nutdot=6wg;11h\nutilde=a1;79\nutri=7g5;159\nutrif=7g4;157\nuuarr=6o8;l9\nuuml=70;4e\nuwangle=887;1b4\nvArr=6ol;m9\nvBar=8h4;1iu\nvBarv=8h5;1iv\nvDash=6ug;y0\nvangrt=87w;1az\nvarepsilon=s5;ad\nvarkappa=s0;a8\nvarnothing=6px;n4\nvarphi=r9;a1\nvarpi=ra;a3\nvarpropto=6ql;ob\nvarr=6mt;ig\nvarrho=s1;aa\nvarsigma=qq;9k\nvarsubsetneq=6tm,1e68;w6\nvarsubsetneqq=8gb,1e68;1i5\nvarsupsetneq=6tn,1e68;wa\nvarsupsetneqq=8gc,1e68;1i9\nvartheta=r5;9w\nvartriangleleft=6uq;y9\nvartriangleright=6ur;yc\nvcy=tu;bt\nvdash=6ua;xp\nvee=6qw;p7\nveebar=6uz;yu\nveeeq=6sa;sf\nvellip=6we;11f\nverbar=3g;19\nvert=3g;1a\nvfr=2koj;1ln\nvltri=6uq;yb\nvnsub=6te,6he;vj\nvnsup=6tf,6he;vo\nvopf=2kpz;1mw\nvprop=6ql;od\nvrtri=6ur;ye\nvscr=2kln;1kc\nvsubnE=8gb,1e68;1i6\nvsubne=6tm,1e68;w7\nvsupnE=8gc,1e68;1ia\nvsupne=6tn,1e68;wb\nvzigzag=87u;1ay\nwcirc=ad;7l\nwedbar=8db;1eb\nwedge=6qv;p5\nwedgeq=6s9;se\nweierp=6jc;g0\nwfr=2kok;1lo\nwopf=2kq0;1mx\nwp=6jc;g1\nwr=6rk;qk\nwreath=6rk;qj\nwscr=2klo;1kd\nxcap=6v6;z6\nxcirc=7hr;15t\nxcup=6v7;z9\nxdtri=7gd;15f\nxfr=2kol;1lp\nxhArr=7wa;17o\nxharr=7w7;17f\nxi=qm;9g\nxlArr=7w8;17i\nxlarr=7w5;179\nxmap=7wc;17q\nxnis=6wr;11t\nxodot=8ao;1ce\nxopf=2kq1;1my\nxoplus=8ap;1cg\nxotime=8aq;1ci\nxrArr=7w9;17l\nxrarr=7w6;17c\nxscr=2klp;1ke\nxsqcup=8au;1cm\nxuplus=8as;1ck\nxutri=7g3;155\nxvee=6v5;z2\nxwedge=6v4;yz\nyacute=71;4f\nyacy=un;cm\nycirc=af;7n\nycy=uj;ci\nyen=4l;1j\nyfr=2kom;1lq\nyicy=uv;ct\nyopf=2kq2;1mz\nyscr=2klq;1kf\nyucy=um;cl\nyuml=73;4h\nzacute=ai;7q\nzcaron=am;7u\nzcy=tz;by\nzdot=ak;7s\nzeetrf=6js;gk\nzeta=qe;98\nzfr=2kon;1lr\nzhcy=ty;bx\nzigrarr=6ot;mi\nzopf=2kq3;1n0\nzscr=2klr;1kg\nzwj=6bx;dh\nzwnj=6bw;dg" + +} + +final class MutexLock: NSLocking { + + private let locker: NSLocking + + init() { + #if os(iOS) || os(macOS) || os(watchOS) || os(tvOS) + if #available(iOS 10.0, macOS 10.12, watchOS 3.0, tvOS 10.0, *) { + locker = UnfairLock() + } else { + locker = Mutex() + } + #else + locker = Mutex() + #endif + } + + func lock() { + locker.lock() + } + + func unlock() { + locker.unlock() + } +} diff --git a/Swiftgram/SwiftSoup/Sources/Evaluator.swift b/Swiftgram/SwiftSoup/Sources/Evaluator.swift new file mode 100644 index 00000000..0ecf2153 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/Evaluator.swift @@ -0,0 +1,720 @@ +// +// Evaluator.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 22/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * Evaluates that an element matches the selector. + */ +open class Evaluator { + public init () {} + + /** + * Test if the element meets the evaluator's requirements. + * + * @param root Root of the matching subtree + * @param element tested element + * @return Returns true if the requirements are met or + * false otherwise + */ + open func matches(_ root: Element, _ element: Element)throws->Bool { + preconditionFailure("self method must be overridden") + } + + open func toString() -> String { + preconditionFailure("self method must be overridden") + } + + /** + * Evaluator for tag name + */ + public class Tag: Evaluator { + private let tagName: String + private let tagNameNormal: String + + public init(_ tagName: String) { + self.tagName = tagName + self.tagNameNormal = tagName.lowercased() + } + + open override func matches(_ root: Element, _ element: Element)throws->Bool { + return element.tagNameNormal() == tagNameNormal + } + + open override func toString() -> String { + return String(tagName) + } + } + + /** + * Evaluator for tag name that ends with + */ + public final class TagEndsWith: Evaluator { + private let tagName: String + + public init(_ tagName: String) { + self.tagName = tagName + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return (element.tagName().hasSuffix(tagName)) + } + + public override func toString() -> String { + return String(tagName) + } + } + + /** + * Evaluator for element id + */ + public final class Id: Evaluator { + private let id: String + + public init(_ id: String) { + self.id = id + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return (id == element.id()) + } + + public override func toString() -> String { + return "#\(id)" + } + + } + + /** + * Evaluator for element class + */ + public final class Class: Evaluator { + private let className: String + + public init(_ className: String) { + self.className = className + } + + public override func matches(_ root: Element, _ element: Element) -> Bool { + return (element.hasClass(className)) + } + + public override func toString() -> String { + return ".\(className)" + } + + } + + /** + * Evaluator for attribute name matching + */ + public final class Attribute: Evaluator { + private let key: String + + public init(_ key: String) { + self.key = key + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return element.hasAttr(key) + } + + public override func toString() -> String { + return "[\(key)]" + } + + } + + /** + * Evaluator for attribute name prefix matching + */ + public final class AttributeStarting: Evaluator { + private let keyPrefix: String + + public init(_ keyPrefix: String)throws { + try Validate.notEmpty(string: keyPrefix) + self.keyPrefix = keyPrefix.lowercased() + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + if let values = element.getAttributes() { + for attribute in values where attribute.getKey().lowercased().hasPrefix(keyPrefix) { + return true + } + } + return false + } + + public override func toString() -> String { + return "[^\(keyPrefix)]" + } + + } + + /** + * Evaluator for attribute name/value matching + */ + public final class AttributeWithValue: AttributeKeyPair { + public override init(_ key: String, _ value: String)throws { + try super.init(key, value) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + if element.hasAttr(key) { + let string = try element.attr(key) + return value.equalsIgnoreCase(string: string.trim()) + } + return false + } + + public override func toString() -> String { + return "[\(key)=\(value)]" + } + + } + + /** + * Evaluator for attribute name != value matching + */ + public final class AttributeWithValueNot: AttributeKeyPair { + public override init(_ key: String, _ value: String)throws { + try super.init(key, value) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let string = try element.attr(key) + return !value.equalsIgnoreCase(string: string) + } + + public override func toString() -> String { + return "[\(key)!=\(value)]" + } + + } + + /** + * Evaluator for attribute name/value matching (value prefix) + */ + public final class AttributeWithValueStarting: AttributeKeyPair { + public override init(_ key: String, _ value: String)throws { + try super.init(key, value) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + if element.hasAttr(key) { + return try element.attr(key).lowercased().hasPrefix(value) // value is lower case already + } + return false + } + + public override func toString() -> String { + return "[\(key)^=\(value)]" + } + + } + + /** + * Evaluator for attribute name/value matching (value ending) + */ + public final class AttributeWithValueEnding: AttributeKeyPair { + public override init(_ key: String, _ value: String)throws { + try super.init(key, value) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + if element.hasAttr(key) { + return try element.attr(key).lowercased().hasSuffix(value) // value is lower case + } + return false + } + + public override func toString() -> String { + return "[\(key)$=\(value)]" + } + + } + + /** + * Evaluator for attribute name/value matching (value containing) + */ + public final class AttributeWithValueContaining: AttributeKeyPair { + public override init(_ key: String, _ value: String)throws { + try super.init(key, value) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + if element.hasAttr(key) { + return try element.attr(key).lowercased().contains(value) // value is lower case + } + return false + } + + public override func toString() -> String { + return "[\(key)*=\(value)]" + } + + } + + /** + * Evaluator for attribute name/value matching (value regex matching) + */ + public final class AttributeWithValueMatching: Evaluator { + let key: String + let pattern: Pattern + + public init(_ key: String, _ pattern: Pattern) { + self.key = key.trim().lowercased() + self.pattern = pattern + super.init() + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + if element.hasAttr(key) { + let string = try element.attr(key) + return pattern.matcher(in: string).find() + } + return false + } + + public override func toString() -> String { + return "[\(key)~=\(pattern.toString())]" + } + + } + + /** + * Abstract evaluator for attribute name/value matching + */ + public class AttributeKeyPair: Evaluator { + let key: String + var value: String + + public init(_ key: String, _ value2: String)throws { + var value2 = value2 + try Validate.notEmpty(string: key) + try Validate.notEmpty(string: value2) + + self.key = key.trim().lowercased() + if value2.startsWith("\"") && value2.hasSuffix("\"") || value2.startsWith("'") && value2.hasSuffix("'") { + value2 = value2.substring(1, value2.count-2) + } + self.value = value2.trim().lowercased() + } + + open override func matches(_ root: Element, _ element: Element)throws->Bool { + preconditionFailure("self method must be overridden") + } + } + + /** + * Evaluator for any / all element matching + */ + public final class AllElements: Evaluator { + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return true + } + + public override func toString() -> String { + return "*" + } + } + + /** + * Evaluator for matching by sibling index number (e {@literal <} idx) + */ + public final class IndexLessThan: IndexEvaluator { + public override init(_ index: Int) { + super.init(index) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return try element.elementSiblingIndex() < index + } + + public override func toString() -> String { + return ":lt(\(index))" + } + + } + + /** + * Evaluator for matching by sibling index number (e {@literal >} idx) + */ + public final class IndexGreaterThan: IndexEvaluator { + public override init(_ index: Int) { + super.init(index) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return try element.elementSiblingIndex() > index + } + + public override func toString() -> String { + return ":gt(\(index))" + } + + } + + /** + * Evaluator for matching by sibling index number (e = idx) + */ + public final class IndexEquals: IndexEvaluator { + public override init(_ index: Int) { + super.init(index) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return try element.elementSiblingIndex() == index + } + + public override func toString() -> String { + return ":eq(\(index))" + } + + } + + /** + * Evaluator for matching the last sibling (css :last-child) + */ + public final class IsLastChild: Evaluator { + public override func matches(_ root: Element, _ element: Element)throws->Bool { + + if let parent = element.parent() { + let index = try element.elementSiblingIndex() + return !(parent is Document) && index == (parent.getChildNodes().count - 1) + } + return false + } + + public override func toString() -> String { + return ":last-child" + } + } + + public final class IsFirstOfType: IsNthOfType { + public init() { + super.init(0, 1) + } + public override func toString() -> String { + return ":first-of-type" + } + } + + public final class IsLastOfType: IsNthLastOfType { + public init() { + super.init(0, 1) + } + public override func toString() -> String { + return ":last-of-type" + } + } + + public class CssNthEvaluator: Evaluator { + public let a: Int + public let b: Int + + public init(_ a: Int, _ b: Int) { + self.a = a + self.b = b + } + public init(_ b: Int) { + self.a = 0 + self.b = b + } + + open override func matches(_ root: Element, _ element: Element)throws->Bool { + let p: Element? = element.parent() + if (p == nil || (((p as? Document) != nil))) {return false} + + let pos: Int = try calculatePosition(root, element) + if (a == 0) {return pos == b} + + return (pos-b)*a >= 0 && (pos-b)%a==0 + } + + open override func toString() -> String { + if (a == 0) { + return ":\(getPseudoClass())(\(b))" + } + if (b == 0) { + return ":\(getPseudoClass())(\(a))" + } + return ":\(getPseudoClass())(\(a)\(b))" + } + + open func getPseudoClass() -> String { + preconditionFailure("self method must be overridden") + } + open func calculatePosition(_ root: Element, _ element: Element)throws->Int { + preconditionFailure("self method must be overridden") + } + } + + /** + * css-compatible Evaluator for :eq (css :nth-child) + * + * @see IndexEquals + */ + public final class IsNthChild: CssNthEvaluator { + + public override init(_ a: Int, _ b: Int) { + super.init(a, b) + } + + public override func calculatePosition(_ root: Element, _ element: Element)throws->Int { + return try element.elementSiblingIndex()+1 + } + + public override func getPseudoClass() -> String { + return "nth-child" + } + } + + /** + * css pseudo class :nth-last-child) + * + * @see IndexEquals + */ + public final class IsNthLastChild: CssNthEvaluator { + public override init(_ a: Int, _ b: Int) { + super.init(a, b) + } + + public override func calculatePosition(_ root: Element, _ element: Element)throws->Int { + var i = 0 + + if let l = element.parent() { + i = l.children().array().count + } + return i - (try element.elementSiblingIndex()) + } + + public override func getPseudoClass() -> String { + return "nth-last-child" + } + } + + /** + * css pseudo class nth-of-type + * + */ + public class IsNthOfType: CssNthEvaluator { + public override init(_ a: Int, _ b: Int) { + super.init(a, b) + } + + open override func calculatePosition(_ root: Element, _ element: Element) -> Int { + var pos = 0 + let family: Elements? = element.parent()?.children() + if let array = family?.array() { + for el in array { + if (el.tag() == element.tag()) {pos+=1} + if (el === element) {break} + } + } + + return pos + } + + open override func getPseudoClass() -> String { + return "nth-of-type" + } + } + + public class IsNthLastOfType: CssNthEvaluator { + + public override init(_ a: Int, _ b: Int) { + super.init(a, b) + } + + open override func calculatePosition(_ root: Element, _ element: Element)throws->Int { + var pos = 0 + if let family = element.parent()?.children() { + let x = try element.elementSiblingIndex() + for i in x.. String { + return "nth-last-of-type" + } + } + + /** + * Evaluator for matching the first sibling (css :first-child) + */ + public final class IsFirstChild: Evaluator { + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let p = element.parent() + if(p != nil && !(((p as? Document) != nil))) { + return (try element.elementSiblingIndex()) == 0 + } + return false + } + + public override func toString() -> String { + return ":first-child" + } + } + + /** + * css3 pseudo-class :root + * @see :root selector + * + */ + public final class IsRoot: Evaluator { + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let r: Element = ((root as? Document) != nil) ? root.child(0) : root + return element === r + } + public override func toString() -> String { + return ":root" + } + } + + public final class IsOnlyChild: Evaluator { + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let p = element.parent() + return p != nil && !((p as? Document) != nil) && element.siblingElements().array().count == 0 + } + public override func toString() -> String { + return ":only-child" + } + } + + public final class IsOnlyOfType: Evaluator { + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let p = element.parent() + if (p == nil || (p as? Document) != nil) {return false} + + var pos = 0 + if let family = p?.children().array() { + for el in family { + if (el.tag() == element.tag()) {pos+=1} + } + } + return pos == 1 + } + + public override func toString() -> String { + return ":only-of-type" + } + } + + public final class IsEmpty: Evaluator { + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let family: Array = element.getChildNodes() + for n in family { + if (!((n as? Comment) != nil || (n as? XmlDeclaration) != nil || (n as? DocumentType) != nil)) {return false} + } + return true + } + + public override func toString() -> String { + return ":empty" + } + } + + /** + * Abstract evaluator for sibling index matching + * + * @author ant + */ + public class IndexEvaluator: Evaluator { + let index: Int + + public init(_ index: Int) { + self.index = index + } + } + + /** + * Evaluator for matching Element (and its descendants) text + */ + public final class ContainsText: Evaluator { + private let searchText: String + + public init(_ searchText: String) { + self.searchText = searchText.lowercased() + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return (try element.text().lowercased().contains(searchText)) + } + + public override func toString() -> String { + return ":contains(\(searchText)" + } + } + + /** + * Evaluator for matching Element's own text + */ + public final class ContainsOwnText: Evaluator { + private let searchText: String + + public init(_ searchText: String) { + self.searchText = searchText.lowercased() + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return (element.ownText().lowercased().contains(searchText)) + } + + public override func toString() -> String { + return ":containsOwn(\(searchText)" + } + } + + /** + * Evaluator for matching Element (and its descendants) text with regex + */ + public final class Matches: Evaluator { + private let pattern: Pattern + + public init(_ pattern: Pattern) { + self.pattern = pattern + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let m = try pattern.matcher(in: element.text()) + return m.find() + } + + public override func toString() -> String { + return ":matches(\(pattern)" + } + } + + /** + * Evaluator for matching Element's own text with regex + */ + public final class MatchesOwn: Evaluator { + private let pattern: Pattern + + public init(_ pattern: Pattern) { + self.pattern = pattern + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let m = pattern.matcher(in: element.ownText()) + return m.find() + } + + public override func toString() -> String { + return ":matchesOwn(\(pattern.toString())" + } + } +} diff --git a/Swiftgram/SwiftSoup/Sources/Exception.swift b/Swiftgram/SwiftSoup/Sources/Exception.swift new file mode 100644 index 00000000..a4ab97ab --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/Exception.swift @@ -0,0 +1,22 @@ +// +// Exception.swift +// SwifSoup +// +// Created by Nabil Chatbi on 02/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +public enum ExceptionType { + case IllegalArgumentException + case IOException + case XmlDeclaration + case MalformedURLException + case CloneNotSupportedException + case SelectorParseException +} + +public enum Exception: Error { + case Error(type:ExceptionType, Message: String) +} diff --git a/Swiftgram/SwiftSoup/Sources/FormElement.swift b/Swiftgram/SwiftSoup/Sources/FormElement.swift new file mode 100644 index 00000000..a15754fa --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/FormElement.swift @@ -0,0 +1,125 @@ +// +// FormElement.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * A HTML Form Element provides ready access to the form fields/controls that are associated with it. It also allows a + * form to easily be submitted. + */ +public class FormElement: Element { + private let _elements: Elements = Elements() + + /** + * Create a new, standalone form element. + * + * @param tag tag of this element + * @param baseUri the base URI + * @param attributes initial attributes + */ + public override init(_ tag: Tag, _ baseUri: String, _ attributes: Attributes) { + super.init(tag, baseUri, attributes) + } + + /** + * Get the list of form control elements associated with this form. + * @return form controls associated with this element. + */ + public func elements() -> Elements { + return _elements + } + + /** + * Add a form control element to this form. + * @param element form control to add + * @return this form element, for chaining + */ + @discardableResult + public func addElement(_ element: Element) -> FormElement { + _elements.add(element) + return self + } + + //todo: + /** + * Prepare to submit this form. A Connection object is created with the request set up from the form values. You + * can then set up other options (like user-agent, timeout, cookies), then execute it. + * @return a connection prepared from the values of this form. + * @throws IllegalArgumentException if the form's absolute action URL cannot be determined. Make sure you pass the + * document's base URI when parsing. + */ +// public func submit()throws->Connection { +// let action: String = hasAttr("action") ? try absUrl("action") : try baseUri() +// Validate.notEmpty(action, "Could not determine a form action URL for submit. Ensure you set a base URI when parsing.") +// Connection.Method method = attr("method").toUpperCase().equals("POST") ? +// Connection.Method.POST : Connection.Method.GET +// +// return Jsoup.connect(action) +// .data(formData()) +// .method(method) +// } + + //todo: + /** + * Get the data that this form submits. The returned list is a copy of the data, and changes to the contents of the + * list will not be reflected in the DOM. + * @return a list of key vals + */ +// public List formData() { +// ArrayList data = new ArrayList(); +// +// // iterate the form control elements and accumulate their values +// for (Element el: elements) { +// if (!el.tag().isFormSubmittable()) continue; // contents are form listable, superset of submitable +// if (el.hasAttr("disabled")) continue; // skip disabled form inputs +// String name = el.attr("name"); +// if (name.length() == 0) continue; +// String type = el.attr("type"); +// +// if ("select".equals(el.tagName())) { +// Elements options = el.select("option[selected]"); +// boolean set = false; +// for (Element option: options) { +// data.add(HttpConnection.KeyVal.create(name, option.val())); +// set = true; +// } +// if (!set) { +// Element option = el.select("option").first(); +// if (option != null) +// data.add(HttpConnection.KeyVal.create(name, option.val())); +// } +// } else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) { +// // only add checkbox or radio if they have the checked attribute +// if (el.hasAttr("checked")) { +// final String val = el.val().length() > 0 ? el.val() : "on"; +// data.add(HttpConnection.KeyVal.create(name, val)); +// } +// } else { +// data.add(HttpConnection.KeyVal.create(name, el.val())); +// } +// } +// return data; +// } + + public override func copy(with zone: NSZone? = nil) -> Any { + let clone = FormElement(_tag, baseUri!, attributes!) + return copy(clone: clone) + } + + public override func copy(parent: Node?) -> Node { + let clone = FormElement(_tag, baseUri!, attributes!) + return copy(clone: clone, parent: parent) + } + public override func copy(clone: Node, parent: Node?) -> Node { + let clone = clone as! FormElement + for att in _elements.array() { + clone._elements.add(att) + } + return super.copy(clone: clone, parent: parent) + } +} diff --git a/Swiftgram/SwiftSoup/Sources/HtmlTreeBuilder.swift b/Swiftgram/SwiftSoup/Sources/HtmlTreeBuilder.swift new file mode 100644 index 00000000..4f0fb9ec --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/HtmlTreeBuilder.swift @@ -0,0 +1,781 @@ +// +// HtmlTreeBuilder.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 24/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * HTML Tree Builder; creates a DOM from Tokens. + */ +class HtmlTreeBuilder: TreeBuilder { + + private enum TagSets { + // tag searches + static let inScope = ["applet", "caption", "html", "table", "td", "th", "marquee", "object"] + static let list = ["ol", "ul"] + static let button = ["button"] + static let tableScope = ["html", "table"] + static let selectScope = ["optgroup", "option"] + static let endTags = ["dd", "dt", "li", "option", "optgroup", "p", "rp", "rt"] + static let titleTextarea = ["title", "textarea"] + static let frames = ["iframe", "noembed", "noframes", "style", "xmp"] + + static let special: Set = ["address", "applet", "area", "article", "aside", "base", "basefont", "bgsound", + "blockquote", "body", "br", "button", "caption", "center", "col", "colgroup", "command", "dd", + "details", "dir", "div", "dl", "dt", "embed", "fieldset", "figcaption", "figure", "footer", "form", + "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", + "iframe", "img", "input", "isindex", "li", "link", "listing", "marquee", "menu", "meta", "nav", + "noembed", "noframes", "noscript", "object", "ol", "p", "param", "plaintext", "pre", "script", + "section", "select", "style", "summary", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", + "title", "tr", "ul", "wbr", "xmp"] + } + + private var _state: HtmlTreeBuilderState = HtmlTreeBuilderState.Initial // the current state + private var _originalState: HtmlTreeBuilderState = HtmlTreeBuilderState.Initial // original / marked state + + private var baseUriSetFromDoc: Bool = false + private var headElement: Element? // the current head element + private var formElement: FormElement? // the current form element + private var contextElement: Element? // fragment parse context -- could be null even if fragment parsing + private var formattingElements: Array = Array() // active (open) formatting elements + private var pendingTableCharacters: Array = Array() // chars in table to be shifted out + private var emptyEnd: Token.EndTag = Token.EndTag() // reused empty end tag + + private var _framesetOk: Bool = true // if ok to go into frameset + private var fosterInserts: Bool = false // if next inserts should be fostered + private var fragmentParsing: Bool = false // if parsing a fragment of html + + public override init() { + super.init() + } + + public override func defaultSettings() -> ParseSettings { + return ParseSettings.htmlDefault + } + + override func parse(_ input: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings)throws->Document { + _state = HtmlTreeBuilderState.Initial + baseUriSetFromDoc = false + return try super.parse(input, baseUri, errors, settings) + } + + func parseFragment(_ inputFragment: String, _ context: Element?, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings)throws->Array { + // context may be null + _state = HtmlTreeBuilderState.Initial + initialiseParse(inputFragment, baseUri, errors, settings) + contextElement = context + fragmentParsing = true + var root: Element? = nil + + if let context = context { + if let d = context.ownerDocument() { // quirks setup: + doc.quirksMode(d.quirksMode()) + } + + // initialise the tokeniser state: + switch context.tagName() { + case TagSets.titleTextarea: + tokeniser.transition(TokeniserState.Rcdata) + case TagSets.frames: + tokeniser.transition(TokeniserState.Rawtext) + case "script": + tokeniser.transition(TokeniserState.ScriptData) + case "noscript": + tokeniser.transition(TokeniserState.Data) // if scripting enabled, rawtext + case "plaintext": + tokeniser.transition(TokeniserState.Data) + default: + tokeniser.transition(TokeniserState.Data) + } + + root = try Element(Tag.valueOf("html", settings), baseUri) + try Validate.notNull(obj: root) + try doc.appendChild(root!) + stack.append(root!) + resetInsertionMode() + + // setup form element to nearest form on context (up ancestor chain). ensures form controls are associated + // with form correctly + let contextChain: Elements = context.parents() + contextChain.add(0, context) + for parent: Element in contextChain.array() { + if let x = (parent as? FormElement) { + formElement = x + break + } + } + } + + try runParser() + if (context != nil && root != nil) { + return root!.getChildNodes() + } else { + return doc.getChildNodes() + } + } + + @discardableResult + public override func process(_ token: Token)throws->Bool { + currentToken = token + return try self._state.process(token, self) + } + + @discardableResult + func process(_ token: Token, _ state: HtmlTreeBuilderState)throws->Bool { + currentToken = token + return try state.process(token, self) + } + + func transition(_ state: HtmlTreeBuilderState) { + self._state = state + } + + func state() -> HtmlTreeBuilderState { + return _state + } + + func markInsertionMode() { + _originalState = _state + } + + func originalState() -> HtmlTreeBuilderState { + return _originalState + } + + func framesetOk(_ framesetOk: Bool) { + self._framesetOk = framesetOk + } + + func framesetOk() -> Bool { + return _framesetOk + } + + func getDocument() -> Document { + return doc + } + + func getBaseUri() -> String { + return baseUri + } + + func maybeSetBaseUri(_ base: Element)throws { + if (baseUriSetFromDoc) { // only listen to the first in parse + return + } + + let href: String = try base.absUrl("href") + if (href.count != 0) { // ignore etc + baseUri = href + baseUriSetFromDoc = true + try doc.setBaseUri(href) // set on the doc so doc.createElement(Tag) will get updated base, and to update all descendants + } + } + + func isFragmentParsing() -> Bool { + return fragmentParsing + } + + func error(_ state: HtmlTreeBuilderState) { + if (errors.canAddError() && currentToken != nil) { + errors.add(ParseError(reader.getPos(), "Unexpected token [\(currentToken!.tokenType())] when in state [\(state.rawValue)]")) + } + } + + @discardableResult + func insert(_ startTag: Token.StartTag)throws->Element { + // handle empty unknown tags + // when the spec expects an empty tag, will directly hit insertEmpty, so won't generate this fake end tag. + if (startTag.isSelfClosing()) { + let el: Element = try insertEmpty(startTag) + stack.append(el) + tokeniser.transition(TokeniserState.Data) // handles + + var tagPending: Token.Tag = Token.Tag() // tag we are building up + let startPending: Token.StartTag = Token.StartTag() + let endPending: Token.EndTag = Token.EndTag() + let charPending: Token.Char = Token.Char() + let doctypePending: Token.Doctype = Token.Doctype() // doctype building up + let commentPending: Token.Comment = Token.Comment() // comment building up + private var lastStartTag: String? // the last start tag emitted, to test appropriate end tag + private var selfClosingFlagAcknowledged: Bool = true + + init(_ reader: CharacterReader, _ errors: ParseErrorList?) { + self.reader = reader + self.errors = errors + } + + func read()throws->Token { + if (!selfClosingFlagAcknowledged) { + error("Self closing flag not acknowledged") + selfClosingFlagAcknowledged = true + } + + while (!isEmitPending) { + try state.read(self, reader) + } + + // if emit is pending, a non-character token was found: return any chars in buffer, and leave token for next read: + if !charsBuilder.isEmpty { + let str: String = charsBuilder.toString() + charsBuilder.clear() + charsString = nil + return charPending.data(str) + } else if (charsString != nil) { + let token: Token = charPending.data(charsString!) + charsString = nil + return token + } else { + isEmitPending = false + return emitPending! + } + } + + func emit(_ token: Token)throws { + try Validate.isFalse(val: isEmitPending, msg: "There is an unread token pending!") + + emitPending = token + isEmitPending = true + + if (token.type == Token.TokenType.StartTag) { + let startTag: Token.StartTag = token as! Token.StartTag + lastStartTag = startTag._tagName! + if (startTag._selfClosing) { + selfClosingFlagAcknowledged = false + } + } else if (token.type == Token.TokenType.EndTag) { + let endTag: Token.EndTag = token as! Token.EndTag + if (endTag._attributes.size() != 0) { + error("Attributes incorrectly present on end tag") + } + } + } + + func emit(_ str: String ) { + // buffer strings up until last string token found, to emit only one token for a run of character refs etc. + // does not set isEmitPending; read checks that + if (charsString == nil) { + charsString = str + } else { + if charsBuilder.isEmpty { // switching to string builder as more than one emit before read + charsBuilder.append(charsString!) + } + charsBuilder.append(str) + } + } + + func emit(_ chars: [UnicodeScalar]) { + emit(String(chars.map {Character($0)})) + } + + // func emit(_ codepoints: [Int]) { + // emit(String(codepoints, 0, codepoints.length)); + // } + + func emit(_ c: UnicodeScalar) { + emit(String(c)) + } + + func getState() -> TokeniserState { + return state + } + + func transition(_ state: TokeniserState) { + self.state = state + } + + func advanceTransition(_ state: TokeniserState) { + reader.advance() + self.state = state + } + + func acknowledgeSelfClosingFlag() { + selfClosingFlagAcknowledged = true + } + + func consumeCharacterReference(_ additionalAllowedCharacter: UnicodeScalar?, _ inAttribute: Bool)throws->[UnicodeScalar]? { + if (reader.isEmpty()) { + return nil + } + if (additionalAllowedCharacter != nil && additionalAllowedCharacter == reader.current()) { + return nil + } + if (reader.matchesAnySorted(Tokeniser.notCharRefCharsSorted)) { + return nil + } + + reader.markPos() + if (reader.matchConsume("#")) { // numbered + let isHexMode: Bool = reader.matchConsumeIgnoreCase("X") + let numRef: String = isHexMode ? reader.consumeHexSequence() : reader.consumeDigitSequence() + if (numRef.unicodeScalars.count == 0) { // didn't match anything + characterReferenceError("numeric reference with no numerals") + reader.rewindToMark() + return nil + } + if (!reader.matchConsume(";")) { + characterReferenceError("missing semicolon") // missing semi + } + var charval: Int = -1 + + let base: Int = isHexMode ? 16 : 10 + if let num = Int(numRef, radix: base) { + charval = num + } + + if (charval == -1 || (charval >= 0xD800 && charval <= 0xDFFF) || charval > 0x10FFFF) { + characterReferenceError("character outside of valid range") + return [Tokeniser.replacementChar] + } else { + // todo: implement number replacement table + // todo: check for extra illegal unicode points as parse errors + return [UnicodeScalar(charval)!] + } + } else { // named + // get as many letters as possible, and look for matching entities. + let nameRef: String = reader.consumeLetterThenDigitSequence() + let looksLegit: Bool = reader.matches(";") + // found if a base named entity without a ;, or an extended entity with the ;. + let found: Bool = (Entities.isBaseNamedEntity(nameRef) || (Entities.isNamedEntity(nameRef) && looksLegit)) + + if (!found) { + reader.rewindToMark() + if (looksLegit) { // named with semicolon + characterReferenceError("invalid named referenece '\(nameRef)'") + } + return nil + } + if (inAttribute && (reader.matchesLetter() || reader.matchesDigit() || reader.matchesAny("=", "-", "_"))) { + // don't want that to match + reader.rewindToMark() + return nil + } + if (!reader.matchConsume(";")) { + characterReferenceError("missing semicolon") // missing semi + } + if let points = Entities.codepointsForName(nameRef) { + if points.count > 2 { + try Validate.fail(msg: "Unexpected characters returned for \(nameRef) num: \(points.count)") + } + return points + } + try Validate.fail(msg: "Entity name not found: \(nameRef)") + return [] + } + } + + @discardableResult + func createTagPending(_ start: Bool)->Token.Tag { + tagPending = start ? startPending.reset() : endPending.reset() + return tagPending + } + + func emitTagPending()throws { + try tagPending.finaliseTag() + try emit(tagPending) + } + + func createCommentPending() { + commentPending.reset() + } + + func emitCommentPending()throws { + try emit(commentPending) + } + + func createDoctypePending() { + doctypePending.reset() + } + + func emitDoctypePending()throws { + try emit(doctypePending) + } + + func createTempBuffer() { + Token.reset(dataBuffer) + } + + func isAppropriateEndTagToken()throws->Bool { + if(lastStartTag != nil) { + let s = try tagPending.name() + return s.equalsIgnoreCase(string: lastStartTag!) + } + return false + } + + func appropriateEndTagName() -> String? { + if (lastStartTag == nil) { + return nil + } + return lastStartTag + } + + func error(_ state: TokeniserState) { + if (errors != nil && errors!.canAddError()) { + errors?.add(ParseError(reader.getPos(), "Unexpected character '\(String(reader.current()))' in input state [\(state.description)]")) + } + } + + func eofError(_ state: TokeniserState) { + if (errors != nil && errors!.canAddError()) { + errors?.add(ParseError(reader.getPos(), "Unexpectedly reached end of file (EOF) in input state [\(state.description)]")) + } + } + + private func characterReferenceError(_ message: String) { + if (errors != nil && errors!.canAddError()) { + errors?.add(ParseError(reader.getPos(), "Invalid character reference: \(message)")) + } + } + + private func error(_ errorMsg: String) { + if (errors != nil && errors!.canAddError()) { + errors?.add(ParseError(reader.getPos(), errorMsg)) + } + } + + func currentNodeInHtmlNS() -> Bool { + // todo: implement namespaces correctly + return true + // Element currentNode = currentNode() + // return currentNode != null && currentNode.namespace().equals("HTML") + } + + /** + * Utility method to consume reader and unescape entities found within. + * @param inAttribute + * @return unescaped string from reader + */ + func unescapeEntities(_ inAttribute: Bool)throws->String { + let builder: StringBuilder = StringBuilder() + while (!reader.isEmpty()) { + builder.append(reader.consumeTo(UnicodeScalar.Ampersand)) + if (reader.matches(UnicodeScalar.Ampersand)) { + reader.consume() + if let c = try consumeCharacterReference(nil, inAttribute) { + if (c.count==0) { + builder.append(UnicodeScalar.Ampersand) + } else { + builder.appendCodePoint(c[0]) + if (c.count == 2) { + builder.appendCodePoint(c[1]) + } + } + } else { + builder.append(UnicodeScalar.Ampersand) + } + } + } + return builder.toString() + } + +} diff --git a/Swiftgram/SwiftSoup/Sources/TokeniserState.swift b/Swiftgram/SwiftSoup/Sources/TokeniserState.swift new file mode 100644 index 00000000..707248a8 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/TokeniserState.swift @@ -0,0 +1,1644 @@ +// +// TokeniserState.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 12/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +protocol TokeniserStateProtocol { + func read(_ t: Tokeniser, _ r: CharacterReader)throws +} + +public class TokeniserStateVars { + public static let nullScalr: UnicodeScalar = "\u{0000}" + + static let attributeSingleValueCharsSorted = ["'", UnicodeScalar.Ampersand, nullScalr].sorted() + static let attributeDoubleValueCharsSorted = ["\"", UnicodeScalar.Ampersand, nullScalr].sorted() + static let attributeNameCharsSorted = [UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ", "/", "=", ">", nullScalr, "\"", "'", UnicodeScalar.LessThan].sorted() + static let attributeValueUnquoted = [UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ", UnicodeScalar.Ampersand, ">", nullScalr, "\"", "'", UnicodeScalar.LessThan, "=", "`"].sorted() + + static let replacementChar: UnicodeScalar = Tokeniser.replacementChar + static let replacementStr: String = String(Tokeniser.replacementChar) + static let eof: UnicodeScalar = CharacterReader.EOF +} + +enum TokeniserState: TokeniserStateProtocol { + case Data + case CharacterReferenceInData + case Rcdata + case CharacterReferenceInRcdata + case Rawtext + case ScriptData + case PLAINTEXT + case TagOpen + case EndTagOpen + case TagName + case RcdataLessthanSign + case RCDATAEndTagOpen + case RCDATAEndTagName + case RawtextLessthanSign + case RawtextEndTagOpen + case RawtextEndTagName + case ScriptDataLessthanSign + case ScriptDataEndTagOpen + case ScriptDataEndTagName + case ScriptDataEscapeStart + case ScriptDataEscapeStartDash + case ScriptDataEscaped + case ScriptDataEscapedDash + case ScriptDataEscapedDashDash + case ScriptDataEscapedLessthanSign + case ScriptDataEscapedEndTagOpen + case ScriptDataEscapedEndTagName + case ScriptDataDoubleEscapeStart + case ScriptDataDoubleEscaped + case ScriptDataDoubleEscapedDash + case ScriptDataDoubleEscapedDashDash + case ScriptDataDoubleEscapedLessthanSign + case ScriptDataDoubleEscapeEnd + case BeforeAttributeName + case AttributeName + case AfterAttributeName + case BeforeAttributeValue + case AttributeValue_doubleQuoted + case AttributeValue_singleQuoted + case AttributeValue_unquoted + case AfterAttributeValue_quoted + case SelfClosingStartTag + case BogusComment + case MarkupDeclarationOpen + case CommentStart + case CommentStartDash + case Comment + case CommentEndDash + case CommentEnd + case CommentEndBang + case Doctype + case BeforeDoctypeName + case DoctypeName + case AfterDoctypeName + case AfterDoctypePublicKeyword + case BeforeDoctypePublicIdentifier + case DoctypePublicIdentifier_doubleQuoted + case DoctypePublicIdentifier_singleQuoted + case AfterDoctypePublicIdentifier + case BetweenDoctypePublicAndSystemIdentifiers + case AfterDoctypeSystemKeyword + case BeforeDoctypeSystemIdentifier + case DoctypeSystemIdentifier_doubleQuoted + case DoctypeSystemIdentifier_singleQuoted + case AfterDoctypeSystemIdentifier + case BogusDoctype + case CdataSection + + internal func read(_ t: Tokeniser, _ r: CharacterReader)throws { + switch self { + case .Data: + switch (r.current()) { + case UnicodeScalar.Ampersand: + t.advanceTransition(.CharacterReferenceInData) + break + case UnicodeScalar.LessThan: + t.advanceTransition(.TagOpen) + break + case TokeniserStateVars.nullScalr: + t.error(self) // NOT replacement character (oddly?) + t.emit(r.consume()) + break + case TokeniserStateVars.eof: + try t.emit(Token.EOF()) + break + default: + let data: String = r.consumeData() + t.emit(data) + break + } + break + case .CharacterReferenceInData: + try TokeniserState.readCharRef(t, .Data) + break + case .Rcdata: + switch (r.current()) { + case UnicodeScalar.Ampersand: + t.advanceTransition(.CharacterReferenceInRcdata) + break + case UnicodeScalar.LessThan: + t.advanceTransition(.RcdataLessthanSign) + break + case TokeniserStateVars.nullScalr: + t.error(self) + r.advance() + t.emit(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + try t.emit(Token.EOF()) + break + default: + let data = r.consumeToAny(UnicodeScalar.Ampersand, UnicodeScalar.LessThan, TokeniserStateVars.nullScalr) + t.emit(data) + break + } + break + case .CharacterReferenceInRcdata: + try TokeniserState.readCharRef(t, .Rcdata) + break + case .Rawtext: + try TokeniserState.readData(t, r, self, .RawtextLessthanSign) + break + case .ScriptData: + try TokeniserState.readData(t, r, self, .ScriptDataLessthanSign) + break + case .PLAINTEXT: + switch (r.current()) { + case TokeniserStateVars.nullScalr: + t.error(self) + r.advance() + t.emit(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + try t.emit(Token.EOF()) + break + default: + let data = r.consumeTo(TokeniserStateVars.nullScalr) + t.emit(data) + break + } + break + case .TagOpen: + // from < in data + switch (r.current()) { + case "!": + t.advanceTransition(.MarkupDeclarationOpen) + break + case "/": + t.advanceTransition(.EndTagOpen) + break + case "?": + t.advanceTransition(.BogusComment) + break + default: + if (r.matchesLetter()) { + t.createTagPending(true) + t.transition(.TagName) + } else { + t.error(self) + t.emit(UnicodeScalar.LessThan) // char that got us here + t.transition(.Data) + } + break + } + break + case .EndTagOpen: + if (r.isEmpty()) { + t.eofError(self) + t.emit("")) { + t.error(self) + t.advanceTransition(.Data) + } else { + t.error(self) + t.advanceTransition(.BogusComment) + } + break + case .TagName: + // from < or ": + try t.emitTagPending() + t.transition(.Data) + break + case TokeniserStateVars.nullScalr: // replacement + t.tagPending.appendTagName(TokeniserStateVars.replacementStr) + break + case TokeniserStateVars.eof: // should emit pending tag? + t.eofError(self) + t.transition(.Data) + // no default, as covered with above consumeToAny + default: + break + } + case .RcdataLessthanSign: + if (r.matches("/")) { + t.createTempBuffer() + t.advanceTransition(.RCDATAEndTagOpen) + } else if (r.matchesLetter() && t.appropriateEndTagName() != nil && !r.containsIgnoreCase("), so rather than + // consuming to EOF break out here + t.tagPending = t.createTagPending(false).name(t.appropriateEndTagName()!) + try t.emitTagPending() + r.unconsume() // undo UnicodeScalar.LessThan + t.transition(.Data) + } else { + t.emit(UnicodeScalar.LessThan) + t.transition(.Rcdata) + } + break + case .RCDATAEndTagOpen: + if (r.matchesLetter()) { + t.createTagPending(false) + t.tagPending.appendTagName(r.current()) + t.dataBuffer.append(r.current()) + t.advanceTransition(.RCDATAEndTagName) + } else { + t.emit("": + if (try t.isAppropriateEndTagToken()) { + try t.emitTagPending() + t.transition(.Data) + } else {anythingElse(t, r)} + break + default: + anythingElse(t, r) + break + } + break + case .RawtextLessthanSign: + if (r.matches("/")) { + t.createTempBuffer() + t.advanceTransition(.RawtextEndTagOpen) + } else { + t.emit(UnicodeScalar.LessThan) + t.transition(.Rawtext) + } + break + case .RawtextEndTagOpen: + TokeniserState.readEndTag(t, r, .RawtextEndTagName, .Rawtext) + break + case .RawtextEndTagName: + try TokeniserState.handleDataEndTag(t, r, .Rawtext) + break + case .ScriptDataLessthanSign: + switch (r.consume()) { + case "/": + t.createTempBuffer() + t.transition(.ScriptDataEndTagOpen) + break + case "!": + t.emit("": + t.emit(c) + t.transition(.ScriptData) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.emit(TokeniserStateVars.replacementChar) + t.transition(.ScriptDataEscaped) + break + default: + t.emit(c) + t.transition(.ScriptDataEscaped) + } + break + case .ScriptDataEscapedLessthanSign: + if (r.matchesLetter()) { + t.createTempBuffer() + t.dataBuffer.append(r.current()) + t.emit("<" + String(r.current())) + t.advanceTransition(.ScriptDataDoubleEscapeStart) + } else if (r.matches("/")) { + t.createTempBuffer() + t.advanceTransition(.ScriptDataEscapedEndTagOpen) + } else { + t.emit(UnicodeScalar.LessThan) + t.transition(.ScriptDataEscaped) + } + break + case .ScriptDataEscapedEndTagOpen: + if (r.matchesLetter()) { + t.createTagPending(false) + t.tagPending.appendTagName(r.current()) + t.dataBuffer.append(r.current()) + t.advanceTransition(.ScriptDataEscapedEndTagName) + } else { + t.emit("": + t.emit(c) + t.transition(.ScriptData) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.emit(TokeniserStateVars.replacementChar) + t.transition(.ScriptDataDoubleEscaped) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + default: + t.emit(c) + t.transition(.ScriptDataDoubleEscaped) + } + break + case .ScriptDataDoubleEscapedLessthanSign: + if (r.matches("/")) { + t.emit("/") + t.createTempBuffer() + t.advanceTransition(.ScriptDataDoubleEscapeEnd) + } else { + t.transition(.ScriptDataDoubleEscaped) + } + break + case .ScriptDataDoubleEscapeEnd: + TokeniserState.handleDataDoubleEscapeTag(t, r, .ScriptDataEscaped, .ScriptDataDoubleEscaped) + break + case .BeforeAttributeName: + // from tagname ": + try t.emitTagPending() + t.transition(.Data) + break + case TokeniserStateVars.nullScalr: + t.error(self) + try t.tagPending.newAttribute() + r.unconsume() + t.transition(.AttributeName) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + case "\"", "'", UnicodeScalar.LessThan, "=": + t.error(self) + try t.tagPending.newAttribute() + t.tagPending.appendAttributeName(c) + t.transition(.AttributeName) + break + default: // A-Z, anything else + try t.tagPending.newAttribute() + r.unconsume() + t.transition(.AttributeName) + } + break + case .AttributeName: + let name = r.consumeToAnySorted(TokeniserStateVars.attributeNameCharsSorted) + t.tagPending.appendAttributeName(name) + + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT: + t.transition(.AfterAttributeName) + break + case "\n": + t.transition(.AfterAttributeName) + break + case "\r": + t.transition(.AfterAttributeName) + break + case UnicodeScalar.BackslashF: + t.transition(.AfterAttributeName) + break + case " ": + t.transition(.AfterAttributeName) + break + case "/": + t.transition(.SelfClosingStartTag) + break + case "=": + t.transition(.BeforeAttributeValue) + break + case ">": + try t.emitTagPending() + t.transition(.Data) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.tagPending.appendAttributeName(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + case "\"": + t.error(self) + t.tagPending.appendAttributeName(c) + case "'": + t.error(self) + t.tagPending.appendAttributeName(c) + case UnicodeScalar.LessThan: + t.error(self) + t.tagPending.appendAttributeName(c) + // no default, as covered in consumeToAny + default: + break + } + break + case .AfterAttributeName: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + // ignore + break + case "/": + t.transition(.SelfClosingStartTag) + break + case "=": + t.transition(.BeforeAttributeValue) + break + case ">": + try t.emitTagPending() + t.transition(.Data) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.tagPending.appendAttributeName(TokeniserStateVars.replacementChar) + t.transition(.AttributeName) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + case "\"", "'", UnicodeScalar.LessThan: + t.error(self) + try t.tagPending.newAttribute() + t.tagPending.appendAttributeName(c) + t.transition(.AttributeName) + break + default: // A-Z, anything else + try t.tagPending.newAttribute() + r.unconsume() + t.transition(.AttributeName) + } + break + case .BeforeAttributeValue: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + // ignore + break + case "\"": + t.transition(.AttributeValue_doubleQuoted) + break + case UnicodeScalar.Ampersand: + r.unconsume() + t.transition(.AttributeValue_unquoted) + break + case "'": + t.transition(.AttributeValue_singleQuoted) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.tagPending.appendAttributeValue(TokeniserStateVars.replacementChar) + t.transition(.AttributeValue_unquoted) + break + case TokeniserStateVars.eof: + t.eofError(self) + try t.emitTagPending() + t.transition(.Data) + break + case ">": + t.error(self) + try t.emitTagPending() + t.transition(.Data) + break + case UnicodeScalar.LessThan, "=", "`": + t.error(self) + t.tagPending.appendAttributeValue(c) + t.transition(.AttributeValue_unquoted) + break + default: + r.unconsume() + t.transition(.AttributeValue_unquoted) + } + break + case .AttributeValue_doubleQuoted: + let value = r.consumeToAny(TokeniserStateVars.attributeDoubleValueCharsSorted) + if (value.count > 0) { + t.tagPending.appendAttributeValue(value) + } else { + t.tagPending.setEmptyAttributeValue() + } + + let c = r.consume() + switch (c) { + case "\"": + t.transition(.AfterAttributeValue_quoted) + break + case UnicodeScalar.Ampersand: + + if let ref = try t.consumeCharacterReference("\"", true) { + t.tagPending.appendAttributeValue(ref) + } else { + t.tagPending.appendAttributeValue(UnicodeScalar.Ampersand) + } + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.tagPending.appendAttributeValue(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + // no default, handled in consume to any above + default: + break + } + break + case .AttributeValue_singleQuoted: + let value = r.consumeToAny(TokeniserStateVars.attributeSingleValueCharsSorted) + if (value.count > 0) { + t.tagPending.appendAttributeValue(value) + } else { + t.tagPending.setEmptyAttributeValue() + } + + let c = r.consume() + switch (c) { + case "'": + t.transition(.AfterAttributeValue_quoted) + break + case UnicodeScalar.Ampersand: + + if let ref = try t.consumeCharacterReference("'", true) { + t.tagPending.appendAttributeValue(ref) + } else { + t.tagPending.appendAttributeValue(UnicodeScalar.Ampersand) + } + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.tagPending.appendAttributeValue(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + // no default, handled in consume to any above + default: + break + } + break + case .AttributeValue_unquoted: + let value = r.consumeToAnySorted(TokeniserStateVars.attributeValueUnquoted) + if (value.count > 0) { + t.tagPending.appendAttributeValue(value) + } + + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(.BeforeAttributeName) + break + case UnicodeScalar.Ampersand: + if let ref = try t.consumeCharacterReference(">", true) { + t.tagPending.appendAttributeValue(ref) + } else { + t.tagPending.appendAttributeValue(UnicodeScalar.Ampersand) + } + break + case ">": + try t.emitTagPending() + t.transition(.Data) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.tagPending.appendAttributeValue(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + case "\"", "'", UnicodeScalar.LessThan, "=", "`": + t.error(self) + t.tagPending.appendAttributeValue(c) + break + // no default, handled in consume to any above + default: + break + } + break + case .AfterAttributeValue_quoted: + // CharacterReferenceInAttributeValue state handled inline + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(.BeforeAttributeName) + break + case "/": + t.transition(.SelfClosingStartTag) + break + case ">": + try t.emitTagPending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + default: + t.error(self) + r.unconsume() + t.transition(.BeforeAttributeName) + } + break + case .SelfClosingStartTag: + let c = r.consume() + switch (c) { + case ">": + t.tagPending._selfClosing = true + try t.emitTagPending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + default: + t.error(self) + r.unconsume() + t.transition(.BeforeAttributeName) + } + break + case .BogusComment: + // todo: handle bogus comment starting from eof. when does that trigger? + // rewind to capture character that lead us here + r.unconsume() + let comment: Token.Comment = Token.Comment() + comment.bogus = true + comment.data.append(r.consumeTo(">")) + // todo: replace nullChar with replaceChar + try t.emit(comment) + t.advanceTransition(.Data) + break + case .MarkupDeclarationOpen: + if (r.matchConsume("--")) { + t.createCommentPending() + t.transition(.CommentStart) + } else if (r.matchConsumeIgnoreCase("DOCTYPE")) { + t.transition(.Doctype) + } else if (r.matchConsume("[CDATA[")) { + // todo: should actually check current namepspace, and only non-html allows cdata. until namespace + // is implemented properly, keep handling as cdata + //} else if (!t.currentNodeInHtmlNS() && r.matchConsume("[CDATA[")) { + t.transition(.CdataSection) + } else { + t.error(self) + t.advanceTransition(.BogusComment) // advance so self character gets in bogus comment data's rewind + } + break + case .CommentStart: + let c = r.consume() + switch (c) { + case "-": + t.transition(.CommentStartDash) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.commentPending.data.append(TokeniserStateVars.replacementChar) + t.transition(.Comment) + break + case ">": + t.error(self) + try t.emitCommentPending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + try t.emitCommentPending() + t.transition(.Data) + break + default: + t.commentPending.data.append(c) + t.transition(.Comment) + } + break + case .CommentStartDash: + let c = r.consume() + switch (c) { + case "-": + t.transition(.CommentStartDash) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.commentPending.data.append(TokeniserStateVars.replacementChar) + t.transition(.Comment) + break + case ">": + t.error(self) + try t.emitCommentPending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + try t.emitCommentPending() + t.transition(.Data) + break + default: + t.commentPending.data.append(c) + t.transition(.Comment) + } + break + case .Comment: + let c = r.current() + switch (c) { + case "-": + t.advanceTransition(.CommentEndDash) + break + case TokeniserStateVars.nullScalr: + t.error(self) + r.advance() + t.commentPending.data.append(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + t.eofError(self) + try t.emitCommentPending() + t.transition(.Data) + break + default: + t.commentPending.data.append(r.consumeToAny("-", TokeniserStateVars.nullScalr)) + } + break + case .CommentEndDash: + let c = r.consume() + switch (c) { + case "-": + t.transition(.CommentEnd) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.commentPending.data.append("-").append(TokeniserStateVars.replacementChar) + t.transition(.Comment) + break + case TokeniserStateVars.eof: + t.eofError(self) + try t.emitCommentPending() + t.transition(.Data) + break + default: + t.commentPending.data.append("-").append(c) + t.transition(.Comment) + } + break + case .CommentEnd: + let c = r.consume() + switch (c) { + case ">": + try t.emitCommentPending() + t.transition(.Data) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.commentPending.data.append("--").append(TokeniserStateVars.replacementChar) + t.transition(.Comment) + break + case "!": + t.error(self) + t.transition(.CommentEndBang) + break + case "-": + t.error(self) + t.commentPending.data.append("-") + break + case TokeniserStateVars.eof: + t.eofError(self) + try t.emitCommentPending() + t.transition(.Data) + break + default: + t.error(self) + t.commentPending.data.append("--").append(c) + t.transition(.Comment) + } + break + case .CommentEndBang: + let c = r.consume() + switch (c) { + case "-": + t.commentPending.data.append("--!") + t.transition(.CommentEndDash) + break + case ">": + try t.emitCommentPending() + t.transition(.Data) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.commentPending.data.append("--!").append(TokeniserStateVars.replacementChar) + t.transition(.Comment) + break + case TokeniserStateVars.eof: + t.eofError(self) + try t.emitCommentPending() + t.transition(.Data) + break + default: + t.commentPending.data.append("--!").append(c) + t.transition(.Comment) + } + break + case .Doctype: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(.BeforeDoctypeName) + break + case TokeniserStateVars.eof: + t.eofError(self) + // note: fall through to > case + case ">": // catch invalid + t.error(self) + t.createDoctypePending() + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.transition(.BeforeDoctypeName) + } + break + case .BeforeDoctypeName: + if (r.matchesLetter()) { + t.createDoctypePending() + t.transition(.DoctypeName) + return + } + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + break // ignore whitespace + case TokeniserStateVars.nullScalr: + t.error(self) + t.createDoctypePending() + t.doctypePending.name.append(TokeniserStateVars.replacementChar) + t.transition(.DoctypeName) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.createDoctypePending() + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.createDoctypePending() + t.doctypePending.name.append(c) + t.transition(.DoctypeName) + } + break + case .DoctypeName: + if (r.matchesLetter()) { + let name = r.consumeLetterSequence() + t.doctypePending.name.append(name) + return + } + let c = r.consume() + switch (c) { + case ">": + try t.emitDoctypePending() + t.transition(.Data) + break + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(.AfterDoctypeName) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.doctypePending.name.append(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.doctypePending.name.append(c) + } + break + case .AfterDoctypeName: + if (r.isEmpty()) { + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + return + } + if (r.matchesAny(UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ")) { + r.advance() // ignore whitespace + } else if (r.matches(">")) { + try t.emitDoctypePending() + t.advanceTransition(.Data) + } else if (r.matchConsumeIgnoreCase(DocumentType.PUBLIC_KEY)) { + t.doctypePending.pubSysKey = DocumentType.PUBLIC_KEY + t.transition(.AfterDoctypePublicKeyword) + } else if (r.matchConsumeIgnoreCase(DocumentType.SYSTEM_KEY)) { + t.doctypePending.pubSysKey = DocumentType.SYSTEM_KEY + t.transition(.AfterDoctypeSystemKeyword) + } else { + t.error(self) + t.doctypePending.forceQuirks = true + t.advanceTransition(.BogusDoctype) + } + break + case .AfterDoctypePublicKeyword: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(.BeforeDoctypePublicIdentifier) + break + case "\"": + t.error(self) + // set public id to empty string + t.transition(.DoctypePublicIdentifier_doubleQuoted) + break + case "'": + t.error(self) + // set public id to empty string + t.transition(.DoctypePublicIdentifier_singleQuoted) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.doctypePending.forceQuirks = true + t.transition(.BogusDoctype) + } + break + case .BeforeDoctypePublicIdentifier: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + break + case "\"": + // set public id to empty string + t.transition(.DoctypePublicIdentifier_doubleQuoted) + break + case "'": + // set public id to empty string + t.transition(.DoctypePublicIdentifier_singleQuoted) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.doctypePending.forceQuirks = true + t.transition(.BogusDoctype) + } + break + case .DoctypePublicIdentifier_doubleQuoted: + let c = r.consume() + switch (c) { + case "\"": + t.transition(.AfterDoctypePublicIdentifier) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.doctypePending.publicIdentifier.append(TokeniserStateVars.replacementChar) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.doctypePending.publicIdentifier.append(c) + } + break + case .DoctypePublicIdentifier_singleQuoted: + let c = r.consume() + switch (c) { + case "'": + t.transition(.AfterDoctypePublicIdentifier) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.doctypePending.publicIdentifier.append(TokeniserStateVars.replacementChar) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.doctypePending.publicIdentifier.append(c) + } + break + case .AfterDoctypePublicIdentifier: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(.BetweenDoctypePublicAndSystemIdentifiers) + break + case ">": + try t.emitDoctypePending() + t.transition(.Data) + break + case "\"": + t.error(self) + // system id empty + t.transition(.DoctypeSystemIdentifier_doubleQuoted) + break + case "'": + t.error(self) + // system id empty + t.transition(.DoctypeSystemIdentifier_singleQuoted) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.doctypePending.forceQuirks = true + t.transition(.BogusDoctype) + } + break + case .BetweenDoctypePublicAndSystemIdentifiers: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + break + case ">": + try t.emitDoctypePending() + t.transition(.Data) + break + case "\"": + t.error(self) + // system id empty + t.transition(.DoctypeSystemIdentifier_doubleQuoted) + break + case "'": + t.error(self) + // system id empty + t.transition(.DoctypeSystemIdentifier_singleQuoted) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.doctypePending.forceQuirks = true + t.transition(.BogusDoctype) + } + break + case .AfterDoctypeSystemKeyword: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(.BeforeDoctypeSystemIdentifier) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case "\"": + t.error(self) + // system id empty + t.transition(.DoctypeSystemIdentifier_doubleQuoted) + break + case "'": + t.error(self) + // system id empty + t.transition(.DoctypeSystemIdentifier_singleQuoted) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + } + break + case .BeforeDoctypeSystemIdentifier: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + break + case "\"": + // set system id to empty string + t.transition(.DoctypeSystemIdentifier_doubleQuoted) + break + case "'": + // set public id to empty string + t.transition(.DoctypeSystemIdentifier_singleQuoted) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.doctypePending.forceQuirks = true + t.transition(.BogusDoctype) + } + break + case .DoctypeSystemIdentifier_doubleQuoted: + let c = r.consume() + switch (c) { + case "\"": + t.transition(.AfterDoctypeSystemIdentifier) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.doctypePending.systemIdentifier.append(TokeniserStateVars.replacementChar) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.doctypePending.systemIdentifier.append(c) + } + break + case .DoctypeSystemIdentifier_singleQuoted: + let c = r.consume() + switch (c) { + case "'": + t.transition(.AfterDoctypeSystemIdentifier) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.doctypePending.systemIdentifier.append(TokeniserStateVars.replacementChar) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.doctypePending.systemIdentifier.append(c) + } + break + case .AfterDoctypeSystemIdentifier: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + break + case ">": + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.transition(.BogusDoctype) + // NOT force quirks + } + break + case .BogusDoctype: + let c = r.consume() + switch (c) { + case ">": + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + try t.emitDoctypePending() + t.transition(.Data) + break + default: + // ignore char + break + } + break + case .CdataSection: + let data = r.consumeTo("]]>") + t.emit(data) + r.matchConsume("]]>") + t.transition(.Data) + break + } + } + + var description: String {return String(describing: type(of: self))} + /** + * Handles RawtextEndTagName, ScriptDataEndTagName, and ScriptDataEscapedEndTagName. Same body impl, just + * different else exit transitions. + */ + private static func handleDataEndTag(_ t: Tokeniser, _ r: CharacterReader, _ elseTransition: TokeniserState)throws { + if (r.matchesLetter()) { + let name = r.consumeLetterSequence() + t.tagPending.appendTagName(name) + t.dataBuffer.append(name) + return + } + + var needsExitTransition = false + if (try t.isAppropriateEndTagToken() && !r.isEmpty()) { + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(BeforeAttributeName) + break + case "/": + t.transition(SelfClosingStartTag) + break + case ">": + try t.emitTagPending() + t.transition(Data) + break + default: + t.dataBuffer.append(c) + needsExitTransition = true + } + } else { + needsExitTransition = true + } + + if (needsExitTransition) { + t.emit("": + if (t.dataBuffer.toString() == "script") { + t.transition(primary) + } else { + t.transition(fallback) + } + t.emit(c) + break + default: + r.unconsume() + t.transition(fallback) + } + } + +} diff --git a/Swiftgram/SwiftSoup/Sources/TreeBuilder.swift b/Swiftgram/SwiftSoup/Sources/TreeBuilder.swift new file mode 100644 index 00000000..a8b9ac0e --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/TreeBuilder.swift @@ -0,0 +1,98 @@ +// +// TreeBuilder.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 24/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +public class TreeBuilder { + public var reader: CharacterReader + var tokeniser: Tokeniser + public var doc: Document // current doc we are building into + public var stack: Array // the stack of open elements + public var baseUri: String // current base uri, for creating new elements + public var currentToken: Token? // currentToken is used only for error tracking. + public var errors: ParseErrorList // null when not tracking errors + public var settings: ParseSettings + + private let start: Token.StartTag = Token.StartTag() // start tag to process + private let end: Token.EndTag = Token.EndTag() + + public func defaultSettings() -> ParseSettings {preconditionFailure("This method must be overridden")} + + public init() { + doc = Document("") + reader = CharacterReader("") + tokeniser = Tokeniser(reader, nil) + stack = Array() + baseUri = "" + errors = ParseErrorList(0, 0) + settings = ParseSettings(false, false) + } + + public func initialiseParse(_ input: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings) { + doc = Document(baseUri) + self.settings = settings + reader = CharacterReader(input) + self.errors = errors + tokeniser = Tokeniser(reader, errors) + stack = Array() + self.baseUri = baseUri + } + + func parse(_ input: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings)throws->Document { + initialiseParse(input, baseUri, errors, settings) + try runParser() + return doc + } + + public func runParser()throws { + while (true) { + let token: Token = try tokeniser.read() + try process(token) + token.reset() + + if (token.type == Token.TokenType.EOF) { + break + } + } + } + + @discardableResult + public func process(_ token: Token)throws->Bool {preconditionFailure("This method must be overridden")} + + @discardableResult + public func processStartTag(_ name: String)throws->Bool { + if (currentToken === start) { // don't recycle an in-use token + return try process(Token.StartTag().name(name)) + } + return try process(start.reset().name(name)) + } + + @discardableResult + public func processStartTag(_ name: String, _ attrs: Attributes)throws->Bool { + if (currentToken === start) { // don't recycle an in-use token + return try process(Token.StartTag().nameAttr(name, attrs)) + } + start.reset() + start.nameAttr(name, attrs) + return try process(start) + } + + @discardableResult + public func processEndTag(_ name: String)throws->Bool { + if (currentToken === end) { // don't recycle an in-use token + return try process(Token.EndTag().name(name)) + } + + return try process(end.reset().name(name)) + } + + public func currentElement() -> Element? { + let size: Int = stack.count + return size > 0 ? stack[size-1] : nil + } +} diff --git a/Swiftgram/SwiftSoup/Sources/UnfairLock.swift b/Swiftgram/SwiftSoup/Sources/UnfairLock.swift new file mode 100644 index 00000000..0ef99f0a --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/UnfairLock.swift @@ -0,0 +1,38 @@ +// +// UnfairLock.swift +// SwiftSoup +// +// Created by xukun on 2022/3/31. +// Copyright © 2022 Nabil Chatbi. All rights reserved. +// + +import Foundation + +#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) +@available(iOS 10.0, macOS 10.12, watchOS 3.0, tvOS 10.0, *) +final class UnfairLock: NSLocking { + + private let unfairLock: UnsafeMutablePointer = { + let pointer = UnsafeMutablePointer.allocate(capacity: 1) + pointer.initialize(to: os_unfair_lock()) + return pointer + }() + + deinit { + unfairLock.deinitialize(count: 1) + unfairLock.deallocate() + } + + func lock() { + os_unfair_lock_lock(unfairLock) + } + + func tryLock() -> Bool { + return os_unfair_lock_trylock(unfairLock) + } + + func unlock() { + os_unfair_lock_unlock(unfairLock) + } +} +#endif diff --git a/Swiftgram/SwiftSoup/Sources/UnicodeScalar.swift b/Swiftgram/SwiftSoup/Sources/UnicodeScalar.swift new file mode 100644 index 00000000..0a527098 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/UnicodeScalar.swift @@ -0,0 +1,67 @@ +// +// UnicodeScalar.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 14/11/16. +// Copyright © 2016 Nabil Chatbi. All rights reserved. +// + +import Foundation + +private let uppercaseSet = CharacterSet.uppercaseLetters +private let lowercaseSet = CharacterSet.lowercaseLetters +private let alphaSet = CharacterSet.letters +private let alphaNumericSet = CharacterSet.alphanumerics +private let symbolSet = CharacterSet.symbols +private let digitSet = CharacterSet.decimalDigits + +extension UnicodeScalar { + public static let Ampersand: UnicodeScalar = "&" + public static let LessThan: UnicodeScalar = "<" + public static let GreaterThan: UnicodeScalar = ">" + + public static let Space: UnicodeScalar = " " + public static let BackslashF: UnicodeScalar = UnicodeScalar(12) + public static let BackslashT: UnicodeScalar = "\t" + public static let BackslashN: UnicodeScalar = "\n" + public static let BackslashR: UnicodeScalar = "\r" + public static let Slash: UnicodeScalar = "/" + + public static let FormFeed: UnicodeScalar = "\u{000B}"// Form Feed + public static let VerticalTab: UnicodeScalar = "\u{000C}"// vertical tab + + func isMemberOfCharacterSet(_ set: CharacterSet) -> Bool { + return set.contains(self) + } + + /// True for any space character, and the control characters \t, \n, \r, \f, \v. + var isWhitespace: Bool { + + switch self { + + case UnicodeScalar.Space, UnicodeScalar.BackslashT, UnicodeScalar.BackslashN, UnicodeScalar.BackslashR, UnicodeScalar.BackslashF: return true + + case UnicodeScalar.FormFeed, UnicodeScalar.VerticalTab: return true // Form Feed, vertical tab + + default: return false + + } + + } + + /// `true` if `self` normalized contains a single code unit that is in the categories of Uppercase and Titlecase Letters. + var isUppercase: Bool { + return isMemberOfCharacterSet(uppercaseSet) + } + + /// `true` if `self` normalized contains a single code unit that is in the category of Lowercase Letters. + var isLowercase: Bool { + return isMemberOfCharacterSet(lowercaseSet) + + } + + var uppercase: UnicodeScalar { + let str = String(self).uppercased() + return str.unicodeScalar(0) + } +} diff --git a/Swiftgram/SwiftSoup/Sources/Validate.swift b/Swiftgram/SwiftSoup/Sources/Validate.swift new file mode 100644 index 00000000..2e6e864e --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/Validate.swift @@ -0,0 +1,133 @@ +// +// Validate.swift +// SwifSoup +// +// Created by Nabil Chatbi on 02/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +struct Validate { + + /** + * Validates that the object is not null + * @param obj object to test + */ + public static func notNull(obj: Any?) throws { + if (obj == nil) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "Object must not be null") + } + } + + /** + * Validates that the object is not null + * @param obj object to test + * @param msg message to output if validation fails + */ + public static func notNull(obj: AnyObject?, msg: String) throws { + if (obj == nil) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: msg) + } + } + + /** + * Validates that the value is true + * @param val object to test + */ + public static func isTrue(val: Bool) throws { + if (!val) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "Must be true") + } + } + + /** + * Validates that the value is true + * @param val object to test + * @param msg message to output if validation fails + */ + public static func isTrue(val: Bool, msg: String) throws { + if (!val) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: msg) + } + } + + /** + * Validates that the value is false + * @param val object to test + */ + public static func isFalse(val: Bool) throws { + if (val) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "Must be false") + } + } + + /** + * Validates that the value is false + * @param val object to test + * @param msg message to output if validation fails + */ + public static func isFalse(val: Bool, msg: String) throws { + if (val) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: msg) + } + } + + /** + * Validates that the array contains no null elements + * @param objects the array to test + */ + public static func noNullElements(objects: [AnyObject?]) throws { + try noNullElements(objects: objects, msg: "Array must not contain any null objects") + } + + /** + * Validates that the array contains no null elements + * @param objects the array to test + * @param msg message to output if validation fails + */ + public static func noNullElements(objects: [AnyObject?], msg: String) throws { + for obj in objects { + if (obj == nil) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: msg) + } + } + } + + /** + * Validates that the string is not empty + * @param string the string to test + */ + public static func notEmpty(string: String?) throws { + if (string == nil || string?.count == 0) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "String must not be empty") + } + + } + + /** + * Validates that the string is not empty + * @param string the string to test + * @param msg message to output if validation fails + */ + public static func notEmpty(string: String?, msg: String ) throws { + if (string == nil || string?.count == 0) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: msg) + } + } + + /** + Cause a failure. + @param msg message to output. + */ + public static func fail(msg: String) throws { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: msg) + } + + /** + Helper + */ + public static func exception(msg: String) throws { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: msg) + } +} diff --git a/Swiftgram/SwiftSoup/Sources/Whitelist.swift b/Swiftgram/SwiftSoup/Sources/Whitelist.swift new file mode 100644 index 00000000..c3951707 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/Whitelist.swift @@ -0,0 +1,650 @@ +// +// Whitelist.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 14/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +/* + Thank you to Ryan Grove (wonko.com) for the Ruby HTML cleaner http://github.com/rgrove/sanitize/, which inspired + this whitelist configuration, and the initial defaults. + */ + +/** + Whitelists define what HTML (elements and attributes) to allow through the cleaner. Everything else is removed. +

+ Start with one of the defaults: +

+
    +
  • {@link #none} +
  • {@link #simpleText} +
  • {@link #basic} +
  • {@link #basicWithImages} +
  • {@link #relaxed} +
+

+ If you need to allow more through (please be careful!), tweak a base whitelist with: +

+
    +
  • {@link #addTags} +
  • {@link #addAttributes} +
  • {@link #addEnforcedAttribute} +
  • {@link #addProtocols} +
+

+ You can remove any setting from an existing whitelist with: +

+
    +
  • {@link #removeTags} +
  • {@link #removeAttributes} +
  • {@link #removeEnforcedAttribute} +
  • {@link #removeProtocols} +
+ +

+ The cleaner and these whitelists assume that you want to clean a body fragment of HTML (to add user + supplied HTML into a templated page), and not to clean a full HTML document. If the latter is the case, either wrap the + document HTML around the cleaned body HTML, or create a whitelist that allows html and head + elements as appropriate. +

+

+ If you are going to extend a whitelist, please be very careful. Make sure you understand what attributes may lead to + XSS attack vectors. URL attributes are particularly vulnerable and require careful validation. See + http://ha.ckers.org/xss.html for some XSS attack examples. +

+ */ + +import Foundation + +public class Whitelist { + private var tagNames: Set // tags allowed, lower case. e.g. [p, br, span] + private var attributes: Dictionary> // tag -> attribute[]. allowed attributes [href] for a tag. + private var enforcedAttributes: Dictionary> // always set these attribute values + private var protocols: Dictionary>> // allowed URL protocols for attributes + private var preserveRelativeLinks: Bool // option to preserve relative links + + /** + This whitelist allows only text nodes: all HTML will be stripped. + + @return whitelist + */ + public static func none() -> Whitelist { + return Whitelist() + } + + /** + This whitelist allows only simple text formatting: b, em, i, strong, u. All other HTML (tags and + attributes) will be removed. + + @return whitelist + */ + public static func simpleText()throws ->Whitelist { + return try Whitelist().addTags("b", "em", "i", "strong", "u") + } + + /** +

+ This whitelist allows a fuller range of text nodes: a, b, blockquote, br, cite, code, dd, dl, dt, em, i, li, + ol, p, pre, q, small, span, strike, strong, sub, sup, u, ul, and appropriate attributes. +

+

+ Links (a elements) can point to http, https, ftp, mailto, and have an enforced + rel=nofollow attribute. +

+

+ Does not allow images. +

+ + @return whitelist + */ + public static func basic()throws->Whitelist { + return try Whitelist() + .addTags( + "a", "b", "blockquote", "br", "cite", "code", "dd", "dl", "dt", "em", + "i", "li", "ol", "p", "pre", "q", "small", "span", "strike", "strong", "sub", + "sup", "u", "ul") + + .addAttributes("a", "href") + .addAttributes("blockquote", "cite") + .addAttributes("q", "cite") + + .addProtocols("a", "href", "ftp", "http", "https", "mailto") + .addProtocols("blockquote", "cite", "http", "https") + .addProtocols("cite", "cite", "http", "https") + + .addEnforcedAttribute("a", "rel", "nofollow") + } + + /** + This whitelist allows the same text tags as {@link #basic}, and also allows img tags, with appropriate + attributes, with src pointing to http or https. + + @return whitelist + */ + public static func basicWithImages()throws->Whitelist { + return try basic() + .addTags("img") + .addAttributes("img", "align", "alt", "height", "src", "title", "width") + .addProtocols("img", "src", "http", "https") + + } + + /** + This whitelist allows a full range of text and structural body HTML: a, b, blockquote, br, caption, cite, + code, col, colgroup, dd, div, dl, dt, em, h1, h2, h3, h4, h5, h6, i, img, li, ol, p, pre, q, small, span, strike, strong, sub, + sup, table, tbody, td, tfoot, th, thead, tr, u, ul +

+ Links do not have an enforced rel=nofollow attribute, but you can add that if desired. +

+ + @return whitelist + */ + public static func relaxed()throws->Whitelist { + return try Whitelist() + .addTags( + "a", "b", "blockquote", "br", "caption", "cite", "code", "col", + "colgroup", "dd", "div", "dl", "dt", "em", "h1", "h2", "h3", "h4", "h5", "h6", + "i", "img", "li", "ol", "p", "pre", "q", "small", "span", "strike", "strong", + "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "u", + "ul") + + .addAttributes("a", "href", "title") + .addAttributes("blockquote", "cite") + .addAttributes("col", "span", "width") + .addAttributes("colgroup", "span", "width") + .addAttributes("img", "align", "alt", "height", "src", "title", "width") + .addAttributes("ol", "start", "type") + .addAttributes("q", "cite") + .addAttributes("table", "summary", "width") + .addAttributes("td", "abbr", "axis", "colspan", "rowspan", "width") + .addAttributes( + "th", "abbr", "axis", "colspan", "rowspan", "scope", + "width") + .addAttributes("ul", "type") + + .addProtocols("a", "href", "ftp", "http", "https", "mailto") + .addProtocols("blockquote", "cite", "http", "https") + .addProtocols("cite", "cite", "http", "https") + .addProtocols("img", "src", "http", "https") + .addProtocols("q", "cite", "http", "https") + } + + /** + Create a new, empty whitelist. Generally it will be better to start with a default prepared whitelist instead. + + @see #basic() + @see #basicWithImages() + @see #simpleText() + @see #relaxed() + */ + init() { + tagNames = Set() + attributes = Dictionary>() + enforcedAttributes = Dictionary>() + protocols = Dictionary>>() + preserveRelativeLinks = false + } + + /** + Add a list of allowed elements to a whitelist. (If a tag is not allowed, it will be removed from the HTML.) + + @param tags tag names to allow + @return this (for chaining) + */ + @discardableResult + open func addTags(_ tags: String...)throws ->Whitelist { + for tagName in tags { + try Validate.notEmpty(string: tagName) + tagNames.insert(TagName.valueOf(tagName)) + } + return self + } + + /** + Remove a list of allowed elements from a whitelist. (If a tag is not allowed, it will be removed from the HTML.) + + @param tags tag names to disallow + @return this (for chaining) + */ + @discardableResult + open func removeTags(_ tags: String...)throws ->Whitelist { + try Validate.notNull(obj: tags) + + for tag in tags { + try Validate.notEmpty(string: tag) + let tagName: TagName = TagName.valueOf(tag) + + if(tagNames.contains(tagName)) { // Only look in sub-maps if tag was allowed + tagNames.remove(tagName) + attributes.removeValue(forKey: tagName) + enforcedAttributes.removeValue(forKey: tagName) + protocols.removeValue(forKey: tagName) + } + } + return self + } + + /** + Add a list of allowed attributes to a tag. (If an attribute is not allowed on an element, it will be removed.) +

+ E.g.: addAttributes("a", "href", "class") allows href and class attributes + on a tags. +

+

+ To make an attribute valid for all tags, use the pseudo tag :all, e.g. + addAttributes(":all", "class"). +

+ + @param tag The tag the attributes are for. The tag will be added to the allowed tag list if necessary. + @param keys List of valid attributes for the tag + @return this (for chaining) + */ + @discardableResult + open func addAttributes(_ tag: String, _ keys: String...)throws->Whitelist { + try Validate.notEmpty(string: tag) + try Validate.isTrue(val: keys.count > 0, msg: "No attributes supplied.") + + let tagName = TagName.valueOf(tag) + if (!tagNames.contains(tagName)) { + tagNames.insert(tagName) + } + var attributeSet = Set() + for key in keys { + try Validate.notEmpty(string: key) + attributeSet.insert(AttributeKey.valueOf(key)) + } + + if var currentSet = attributes[tagName] { + for at in attributeSet { + currentSet.insert(at) + } + attributes[tagName] = currentSet + } else { + attributes[tagName] = attributeSet + } + + return self + } + + /** + Remove a list of allowed attributes from a tag. (If an attribute is not allowed on an element, it will be removed.) +

+ E.g.: removeAttributes("a", "href", "class") disallows href and class + attributes on a tags. +

+

+ To make an attribute invalid for all tags, use the pseudo tag :all, e.g. + removeAttributes(":all", "class"). +

+ + @param tag The tag the attributes are for. + @param keys List of invalid attributes for the tag + @return this (for chaining) + */ + @discardableResult + open func removeAttributes(_ tag: String, _ keys: String...)throws->Whitelist { + try Validate.notEmpty(string: tag) + try Validate.isTrue(val: keys.count > 0, msg: "No attributes supplied.") + + let tagName: TagName = TagName.valueOf(tag) + var attributeSet = Set() + for key in keys { + try Validate.notEmpty(string: key) + attributeSet.insert(AttributeKey.valueOf(key)) + } + + if(tagNames.contains(tagName)) { // Only look in sub-maps if tag was allowed + if var currentSet = attributes[tagName] { + for l in attributeSet { + currentSet.remove(l) + } + attributes[tagName] = currentSet + if(currentSet.isEmpty) { // Remove tag from attribute map if no attributes are allowed for tag + attributes.removeValue(forKey: tagName) + } + } + + } + + if(tag == ":all") { // Attribute needs to be removed from all individually set tags + for name in attributes.keys { + var currentSet: Set = attributes[name]! + for l in attributeSet { + currentSet.remove(l) + } + attributes[name] = currentSet + if(currentSet.isEmpty) { // Remove tag from attribute map if no attributes are allowed for tag + attributes.removeValue(forKey: name) + } + } + } + return self + } + + /** + Add an enforced attribute to a tag. An enforced attribute will always be added to the element. If the element + already has the attribute set, it will be overridden. +

+ E.g.: addEnforcedAttribute("a", "rel", "nofollow") will make all a tags output as + <a href="..." rel="nofollow"> +

+ + @param tag The tag the enforced attribute is for. The tag will be added to the allowed tag list if necessary. + @param key The attribute key + @param value The enforced attribute value + @return this (for chaining) + */ + @discardableResult + open func addEnforcedAttribute(_ tag: String, _ key: String, _ value: String)throws->Whitelist { + try Validate.notEmpty(string: tag) + try Validate.notEmpty(string: key) + try Validate.notEmpty(string: value) + + let tagName: TagName = TagName.valueOf(tag) + if (!tagNames.contains(tagName)) { + tagNames.insert(tagName) + } + let attrKey: AttributeKey = AttributeKey.valueOf(key) + let attrVal: AttributeValue = AttributeValue.valueOf(value) + + if (enforcedAttributes[tagName] != nil) { + enforcedAttributes[tagName]?[attrKey] = attrVal + } else { + var attrMap: Dictionary = Dictionary() + attrMap[attrKey] = attrVal + enforcedAttributes[tagName] = attrMap + } + return self + } + + /** + Remove a previously configured enforced attribute from a tag. + + @param tag The tag the enforced attribute is for. + @param key The attribute key + @return this (for chaining) + */ + @discardableResult + open func removeEnforcedAttribute(_ tag: String, _ key: String)throws->Whitelist { + try Validate.notEmpty(string: tag) + try Validate.notEmpty(string: key) + + let tagName: TagName = TagName.valueOf(tag) + if(tagNames.contains(tagName) && (enforcedAttributes[tagName] != nil)) { + let attrKey: AttributeKey = AttributeKey.valueOf(key) + var attrMap: Dictionary = enforcedAttributes[tagName]! + attrMap.removeValue(forKey: attrKey) + enforcedAttributes[tagName] = attrMap + + if(attrMap.isEmpty) { // Remove tag from enforced attribute map if no enforced attributes are present + enforcedAttributes.removeValue(forKey: tagName) + } + } + return self + } + + /** + * Configure this Whitelist to preserve relative links in an element's URL attribute, or convert them to absolute + * links. By default, this is false: URLs will be made absolute (e.g. start with an allowed protocol, like + * e.g. {@code http://}. + *

+ * Note that when handling relative links, the input document must have an appropriate {@code base URI} set when + * parsing, so that the link's protocol can be confirmed. Regardless of the setting of the {@code preserve relative + * links} option, the link must be resolvable against the base URI to an allowed protocol; otherwise the attribute + * will be removed. + *

+ * + * @param preserve {@code true} to allow relative links, {@code false} (default) to deny + * @return this Whitelist, for chaining. + * @see #addProtocols + */ + @discardableResult + open func preserveRelativeLinks(_ preserve: Bool) -> Whitelist { + preserveRelativeLinks = preserve + return self + } + + /** + Add allowed URL protocols for an element's URL attribute. This restricts the possible values of the attribute to + URLs with the defined protocol. +

+ E.g.: addProtocols("a", "href", "ftp", "http", "https") +

+

+ To allow a link to an in-page URL anchor (i.e. <a href="#anchor">, add a #:
+ E.g.: addProtocols("a", "href", "#") +

+ + @param tag Tag the URL protocol is for + @param key Attribute key + @param protocols List of valid protocols + @return this, for chaining + */ + @discardableResult + open func addProtocols(_ tag: String, _ key: String, _ protocols: String...)throws->Whitelist { + try Validate.notEmpty(string: tag) + try Validate.notEmpty(string: key) + + let tagName: TagName = TagName.valueOf(tag) + let attrKey: AttributeKey = AttributeKey.valueOf(key) + var attrMap: Dictionary> + var protSet: Set + + if (self.protocols[tagName] != nil) { + attrMap = self.protocols[tagName]! + } else { + attrMap = Dictionary>() + self.protocols[tagName] = attrMap + } + + if (attrMap[attrKey] != nil) { + protSet = attrMap[attrKey]! + } else { + protSet = Set() + attrMap[attrKey] = protSet + self.protocols[tagName] = attrMap + } + for ptl in protocols { + try Validate.notEmpty(string: ptl) + let prot: Protocol = Protocol.valueOf(ptl) + protSet.insert(prot) + } + attrMap[attrKey] = protSet + self.protocols[tagName] = attrMap + + return self + } + + /** + Remove allowed URL protocols for an element's URL attribute. +

+ E.g.: removeProtocols("a", "href", "ftp") +

+ + @param tag Tag the URL protocol is for + @param key Attribute key + @param protocols List of invalid protocols + @return this, for chaining + */ + @discardableResult + open func removeProtocols(_ tag: String, _ key: String, _ protocols: String...)throws->Whitelist { + try Validate.notEmpty(string: tag) + try Validate.notEmpty(string: key) + + let tagName: TagName = TagName.valueOf(tag) + let attrKey: AttributeKey = AttributeKey.valueOf(key) + + if(self.protocols[tagName] != nil) { + var attrMap: Dictionary> = self.protocols[tagName]! + if(attrMap[attrKey] != nil) { + var protSet: Set = attrMap[attrKey]! + for ptl in protocols { + try Validate.notEmpty(string: ptl) + let prot: Protocol = Protocol.valueOf(ptl) + protSet.remove(prot) + } + attrMap[attrKey] = protSet + + if(protSet.isEmpty) { // Remove protocol set if empty + attrMap.removeValue(forKey: attrKey) + if(attrMap.isEmpty) { // Remove entry for tag if empty + self.protocols.removeValue(forKey: tagName) + } + + } + } + self.protocols[tagName] = attrMap + } + return self + } + + /** + * Test if the supplied tag is allowed by this whitelist + * @param tag test tag + * @return true if allowed + */ + public func isSafeTag(_ tag: String) -> Bool { + return tagNames.contains(TagName.valueOf(tag)) + } + + /** + * Test if the supplied attribute is allowed by this whitelist for this tag + * @param tagName tag to consider allowing the attribute in + * @param el element under test, to confirm protocol + * @param attr attribute under test + * @return true if allowed + */ + public func isSafeAttribute(_ tagName: String, _ el: Element, _ attr: Attribute)throws -> Bool { + let tag: TagName = TagName.valueOf(tagName) + let key: AttributeKey = AttributeKey.valueOf(attr.getKey()) + + if (attributes[tag] != nil) { + if (attributes[tag]?.contains(key))! { + if (protocols[tag] != nil) { + let attrProts: Dictionary> = protocols[tag]! + // ok if not defined protocol; otherwise test + return try (attrProts[key] == nil) || testValidProtocol(el, attr, attrProts[key]!) + } else { // attribute found, no protocols defined, so OK + return true + } + } + } + // no attributes defined for tag, try :all tag + return try !(tagName == ":all") && isSafeAttribute(":all", el, attr) + } + + private func testValidProtocol(_ el: Element, _ attr: Attribute, _ protocols: Set)throws->Bool { + // try to resolve relative urls to abs, and optionally update the attribute so output html has abs. + // rels without a baseuri get removed + var value: String = try el.absUrl(attr.getKey()) + if (value.count == 0) { + value = attr.getValue() + }// if it could not be made abs, run as-is to allow custom unknown protocols + if (!preserveRelativeLinks) { + attr.setValue(value: value) + } + + for ptl in protocols { + var prot: String = ptl.toString() + + if (prot=="#") { // allows anchor links + if (isValidAnchor(value)) { + return true + } else { + continue + } + } + + prot += ":" + + if (value.lowercased().hasPrefix(prot)) { + return true + } + + } + + return false + } + + private func isValidAnchor(_ value: String) -> Bool { + return value.startsWith("#") && !(Pattern(".*\\s.*").matcher(in: value).count > 0) + } + + public func getEnforcedAttributes(_ tagName: String)throws->Attributes { + let attrs: Attributes = Attributes() + let tag: TagName = TagName.valueOf(tagName) + if let keyVals: Dictionary = enforcedAttributes[tag] { + for entry in keyVals { + try attrs.put(entry.key.toString(), entry.value.toString()) + } + } + return attrs + } + +} + +// named types for config. All just hold strings, but here for my sanity. + +open class TagName: TypedValue { + override init(_ value: String) { + super.init(value) + } + + static func valueOf(_ value: String) -> TagName { + return TagName(value) + } +} + +open class AttributeKey: TypedValue { + override init(_ value: String) { + super.init(value) + } + + static func valueOf(_ value: String) -> AttributeKey { + return AttributeKey(value) + } +} + +open class AttributeValue: TypedValue { + override init(_ value: String) { + super.init(value) + } + + static func valueOf(_ value: String) -> AttributeValue { + return AttributeValue(value) + } +} + +open class Protocol: TypedValue { + override init(_ value: String) { + super.init(value) + } + + static func valueOf(_ value: String) -> Protocol { + return Protocol(value) + } +} + +open class TypedValue { + fileprivate let value: String + + init(_ value: String) { + self.value = value + } + + public func toString() -> String { + return value + } +} + +extension TypedValue: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(value) + } +} + +public func == (lhs: TypedValue, rhs: TypedValue) -> Bool { + if(lhs === rhs) {return true} + return lhs.value == rhs.value +} diff --git a/Swiftgram/SwiftSoup/Sources/XmlDeclaration.swift b/Swiftgram/SwiftSoup/Sources/XmlDeclaration.swift new file mode 100644 index 00000000..5f1032b6 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/XmlDeclaration.swift @@ -0,0 +1,77 @@ +// +// XmlDeclaration.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + An XML Declaration. + */ +public class XmlDeclaration: Node { + private let _name: String + private let isProcessingInstruction: Bool // String { + return "#declaration" + } + + /** + * Get the name of this declaration. + * @return name of this declaration. + */ + public func name() -> String { + return _name + } + + /** + Get the unencoded XML declaration. + @return XML declaration + */ + public func getWholeDeclaration()throws->String { + return try attributes!.html().trim() // attr html starts with a " " + } + + override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) { + accum + .append("<") + .append(isProcessingInstruction ? "!" : "?") + .append(_name) + do { + try attributes?.html(accum: accum, out: out) + } catch {} + accum + .append(isProcessingInstruction ? "!" : "?") + .append(">") + } + + override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {} + + public override func copy(with zone: NSZone? = nil) -> Any { + let clone = XmlDeclaration(_name, baseUri!, isProcessingInstruction) + return copy(clone: clone) + } + + public override func copy(parent: Node?) -> Node { + let clone = XmlDeclaration(_name, baseUri!, isProcessingInstruction) + return copy(clone: clone, parent: parent) + } + public override func copy(clone: Node, parent: Node?) -> Node { + return super.copy(clone: clone, parent: parent) + } +} diff --git a/Swiftgram/SwiftSoup/Sources/XmlTreeBuilder.swift b/Swiftgram/SwiftSoup/Sources/XmlTreeBuilder.swift new file mode 100644 index 00000000..785a68b8 --- /dev/null +++ b/Swiftgram/SwiftSoup/Sources/XmlTreeBuilder.swift @@ -0,0 +1,146 @@ +// +// XmlTreeBuilder.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 14/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * Use the {@code XmlTreeBuilder} when you want to parse XML without any of the HTML DOM rules being applied to the + * document. + *

Usage example: {@code Document xmlDoc = Jsoup.parse(html, baseUrl, Parser.xmlParser())}

+ * + */ +public class XmlTreeBuilder: TreeBuilder { + + public override init() { + super.init() + } + + public override func defaultSettings() -> ParseSettings { + return ParseSettings.preserveCase + } + + public func parse(_ input: String, _ baseUri: String)throws->Document { + return try parse(input, baseUri, ParseErrorList.noTracking(), ParseSettings.preserveCase) + } + + override public func initialiseParse(_ input: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings) { + super.initialiseParse(input, baseUri, errors, settings) + stack.append(doc) // place the document onto the stack. differs from HtmlTreeBuilder (not on stack) + doc.outputSettings().syntax(syntax: OutputSettings.Syntax.xml) + } + + override public func process(_ token: Token)throws->Bool { + // start tag, end tag, doctype, comment, character, eof + switch (token.type) { + case .StartTag: + try insert(token.asStartTag()) + break + case .EndTag: + try popStackToClose(token.asEndTag()) + break + case .Comment: + try insert(token.asComment()) + break + case .Char: + try insert(token.asCharacter()) + break + case .Doctype: + try insert(token.asDoctype()) + break + case .EOF: // could put some normalisation here if desired + break +// default: +// try Validate.fail(msg: "Unexpected token type: " + token.tokenType()) + } + return true + } + + private func insertNode(_ node: Node)throws { + try currentElement()?.appendChild(node) + } + + @discardableResult + func insert(_ startTag: Token.StartTag)throws->Element { + let tag: Tag = try Tag.valueOf(startTag.name(), settings) + // todo: wonder if for xml parsing, should treat all tags as unknown? because it's not html. + let el: Element = try Element(tag, baseUri, settings.normalizeAttributes(startTag._attributes)) + try insertNode(el) + if (startTag.isSelfClosing()) { + tokeniser.acknowledgeSelfClosingFlag() + if (!tag.isKnownTag()) // unknown tag, remember this is self closing for output. see above. + { + tag.setSelfClosing() + } + } else { + stack.append(el) + } + return el + } + + func insert(_ commentToken: Token.Comment)throws { + let comment: Comment = Comment(commentToken.getData(), baseUri) + var insert: Node = comment + if (commentToken.bogus) { // xml declarations are emitted as bogus comments (which is right for html, but not xml) + // so we do a bit of a hack and parse the data as an element to pull the attributes out + let data: String = comment.getData() + if (data.count > 1 && (data.startsWith("!") || data.startsWith("?"))) { + let doc: Document = try SwiftSoup.parse("<" + data.substring(1, data.count - 2) + ">", baseUri, Parser.xmlParser()) + let el: Element = doc.child(0) + insert = XmlDeclaration(settings.normalizeTag(el.tagName()), comment.getBaseUri(), data.startsWith("!")) + insert.getAttributes()?.addAll(incoming: el.getAttributes()) + } + } + try insertNode(insert) + } + + func insert(_ characterToken: Token.Char)throws { + let node: Node = TextNode(characterToken.getData()!, baseUri) + try insertNode(node) + } + + func insert(_ d: Token.Doctype)throws { + let doctypeNode = DocumentType(settings.normalizeTag(d.getName()), d.getPubSysKey(), d.getPublicIdentifier(), d.getSystemIdentifier(), baseUri) + try insertNode(doctypeNode) + } + + /** + * If the stack contains an element with this tag's name, pop up the stack to remove the first occurrence. If not + * found, skips. + * + * @param endTag + */ + private func popStackToClose(_ endTag: Token.EndTag)throws { + let elName: String = try endTag.name() + var firstFound: Element? = nil + + for pos in (0..Array { + initialiseParse(inputFragment, baseUri, errors, settings) + try runParser() + return doc.getChildNodes() + } +} diff --git a/Swiftgram/Wrap/BUILD b/Swiftgram/Wrap/BUILD new file mode 100644 index 00000000..2a1b4a85 --- /dev/null +++ b/Swiftgram/Wrap/BUILD @@ -0,0 +1,17 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "Wrap", + module_name = "Wrap", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + # "-warnings-as-errors", + ], + deps = [ + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/Swiftgram/Wrap/Sources/Wrap.swift b/Swiftgram/Wrap/Sources/Wrap.swift new file mode 100644 index 00000000..055ab2b8 --- /dev/null +++ b/Swiftgram/Wrap/Sources/Wrap.swift @@ -0,0 +1,568 @@ +/** + * Wrap - the easy to use Swift JSON encoder + * + * For usage, see documentation of the classes/symbols listed in this file, as well + * as the guide available at: github.com/johnsundell/wrap + * + * Copyright (c) 2015 - 2017 John Sundell. Licensed under the MIT license, as follows: + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import Foundation + +/// Type alias defining what type of Dictionary that Wrap produces +public typealias WrappedDictionary = [String : Any] + +/** + * Wrap any object or value, encoding it into a JSON compatible Dictionary + * + * - Parameter object: The object to encode + * - Parameter context: An optional contextual object that will be available throughout + * the wrapping process. Can be used to inject extra information or objects needed to + * perform the wrapping. + * - Parameter dateFormatter: Optionally pass in a date formatter to use to encode any + * `NSDate` values found while encoding the object. If this is `nil`, any found date + * values will be encoded using the "yyyy-MM-dd HH:mm:ss" format. + * + * All the type's stored properties (both public & private) will be recursively + * encoded with their property names as the key. For example, given the following + * Struct as input: + * + * ``` + * struct User { + * let name = "John" + * let age = 28 + * } + * ``` + * + * This function will produce the following output: + * + * ``` + * [ + * "name" : "John", + * "age" : 28 + * ] + * ``` + * + * The object passed to this function must be an instance of a Class, or a value + * based on a Struct. Standard library values, such as Ints, Strings, etc are not + * valid input. + * + * Throws a WrapError if the operation could not be completed. + * + * For more customization options, make your type conform to `WrapCustomizable`, + * that lets you override encoding keys and/or the whole wrapping process. + * + * See also `WrappableKey` (for dictionary keys) and `WrappableEnum` for Enum values. + */ +public func wrap(_ object: T, context: Any? = nil, dateFormatter: DateFormatter? = nil) throws -> WrappedDictionary { + return try Wrapper(context: context, dateFormatter: dateFormatter).wrap(object: object, enableCustomizedWrapping: true) +} + +/** + * Alternative `wrap()` overload that returns JSON-based `Data` + * + * See the documentation for the dictionary-based `wrap()` function for more information + */ +public func wrap(_ object: T, writingOptions: JSONSerialization.WritingOptions? = nil, context: Any? = nil, dateFormatter: DateFormatter? = nil) throws -> Data { + return try Wrapper(context: context, dateFormatter: dateFormatter).wrap(object: object, writingOptions: writingOptions ?? []) +} + +/** + * Alternative `wrap()` overload that encodes an array of objects into an array of dictionaries + * + * See the documentation for the dictionary-based `wrap()` function for more information + */ +public func wrap(_ objects: [T], context: Any? = nil, dateFormatter: DateFormatter? = nil) throws -> [WrappedDictionary] { + return try objects.map { try wrap($0, context: context, dateFormatter: dateFormatter) } +} + +/** + * Alternative `wrap()` overload that encodes an array of objects into JSON-based `Data` + * + * See the documentation for the dictionary-based `wrap()` function for more information + */ +public func wrap(_ objects: [T], writingOptions: JSONSerialization.WritingOptions? = nil, context: Any? = nil, dateFormatter: DateFormatter? = nil) throws -> Data { + let dictionaries: [WrappedDictionary] = try wrap(objects, context: context, dateFormatter: dateFormatter) + return try JSONSerialization.data(withJSONObject: dictionaries, options: writingOptions ?? []) +} + +// Enum describing various styles of keys in a wrapped dictionary +public enum WrapKeyStyle { + /// The keys in a dictionary produced by Wrap should match their property name (default) + case matchPropertyName + /// The keys in a dictionary produced by Wrap should be converted to snake_case. + /// For example, "myProperty" will be converted to "my_property". All keys will be lowercased. + case convertToSnakeCase +} + +/** + * Protocol providing the main customization point for Wrap + * + * It's optional to implement all of the methods in this protocol, as Wrap + * supplies default implementations of them. + */ +public protocol WrapCustomizable { + /** + * The style that wrap should apply to the keys of a wrapped dictionary + * + * The value of this property is ignored if a type provides a custom + * implementation of the `keyForWrapping(propertyNamed:)` method. + */ + var wrapKeyStyle: WrapKeyStyle { get } + /** + * Override the wrapping process for this type + * + * All top-level types should return a `WrappedDictionary` from this method. + * + * You may use the default wrapping implementation by using a `Wrapper`, but + * never call `wrap()` from an implementation of this method, since that might + * cause an infinite recursion. + * + * The context & dateFormatter passed to this method is any formatter that you + * supplied when initiating the wrapping process by calling `wrap()`. + * + * Returning nil from this method will be treated as an error, and cause + * a `WrapError.wrappingFailedForObject()` error to be thrown. + */ + func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? + /** + * Override the key that will be used when encoding a certain property + * + * Returning nil from this method will cause Wrap to skip the property + */ + func keyForWrapping(propertyNamed propertyName: String) -> String? + /** + * Override the wrapping of any property of this type + * + * The original value passed to this method will be the original value that the + * type is currently storing for the property. You can choose to either use this, + * or just access the property in question directly. + * + * The dateFormatter passed to this method is any formatter that you supplied + * when initiating the wrapping process by calling `wrap()`. + * + * Returning nil from this method will cause Wrap to use the default + * wrapping mechanism for the property, so you can choose which properties + * you want to customize the wrapping for. + * + * If you encounter an error while attempting to wrap the property in question, + * you can choose to throw. This will cause a WrapError.WrappingFailedForObject + * to be thrown from the main `wrap()` call that started the process. + */ + func wrap(propertyNamed propertyName: String, originalValue: Any, context: Any?, dateFormatter: DateFormatter?) throws -> Any? +} + +/// Protocol implemented by types that may be used as keys in a wrapped Dictionary +public protocol WrappableKey { + /// Convert this type into a key that can be used in a wrapped Dictionary + func toWrappedKey() -> String +} + +/** + * Protocol implemented by Enums to enable them to be directly wrapped + * + * If an Enum implementing this protocol conforms to `RawRepresentable` (it's based + * on a raw type), no further implementation is required. If you wish to customize + * how the Enum is wrapped, you can use the APIs in `WrapCustomizable`. + */ +public protocol WrappableEnum: WrapCustomizable {} + +/// Protocol implemented by Date types to enable them to be wrapped +public protocol WrappableDate { + /// Wrap the date using a date formatter, generating a string representation + func wrap(dateFormatter: DateFormatter) -> String +} + +/** + * Class used to wrap an object or value. Use this in any custom `wrap()` implementations + * in case you only want to add on top of the default implementation. + * + * You normally don't have to interact with this API. Use the `wrap()` function instead + * to wrap an object from top-level code. + */ +public class Wrapper { + fileprivate let context: Any? + fileprivate var dateFormatter: DateFormatter? + + /** + * Initialize an instance of this class + * + * - Parameter context: An optional contextual object that will be available throughout the + * wrapping process. Can be used to inject extra information or objects needed to perform + * the wrapping. + * - Parameter dateFormatter: Any specific date formatter to use to encode any found `NSDate` + * values. If this is `nil`, any found date values will be encoded using the "yyyy-MM-dd + * HH:mm:ss" format. + */ + public init(context: Any? = nil, dateFormatter: DateFormatter? = nil) { + self.context = context + self.dateFormatter = dateFormatter + } + + /// Perform automatic wrapping of an object or value. For more information, see `Wrap()`. + public func wrap(object: Any) throws -> WrappedDictionary { + return try self.wrap(object: object, enableCustomizedWrapping: false) + } +} + +/// Error type used by Wrap +public enum WrapError: Error { + /// Thrown when an invalid top level object (such as a String or Int) was passed to `Wrap()` + case invalidTopLevelObject(Any) + /// Thrown when an object couldn't be wrapped. This is a last resort error. + case wrappingFailedForObject(Any) +} + +// MARK: - Default protocol implementations + +/// Extension containing default implementations of `WrapCustomizable`. Override as you see fit. +public extension WrapCustomizable { + var wrapKeyStyle: WrapKeyStyle { + return .matchPropertyName + } + + func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? { + return try? Wrapper(context: context, dateFormatter: dateFormatter).wrap(object: self) + } + + func keyForWrapping(propertyNamed propertyName: String) -> String? { + switch self.wrapKeyStyle { + case .matchPropertyName: + return propertyName + case .convertToSnakeCase: + return self.convertPropertyNameToSnakeCase(propertyName: propertyName) + } + } + + func wrap(propertyNamed propertyName: String, originalValue: Any, context: Any?, dateFormatter: DateFormatter?) throws -> Any? { + return try Wrapper(context: context, dateFormatter: dateFormatter).wrap(value: originalValue, propertyName: propertyName) + } +} + +/// Extension adding convenience APIs to `WrapCustomizable` types +public extension WrapCustomizable { + /// Convert a given property name (assumed to be camelCased) to snake_case + func convertPropertyNameToSnakeCase(propertyName: String) -> String { + let regex = try! NSRegularExpression(pattern: "(?<=[a-z])([A-Z])|([A-Z])(?=[a-z])", options: []) + let range = NSRange(location: 0, length: propertyName.count) + let camelCasePropertyName = regex.stringByReplacingMatches(in: propertyName, options: [], range: range, withTemplate: "_$1$2") + return camelCasePropertyName.lowercased() + } +} + +/// Extension providing a default wrapping implementation for `RawRepresentable` Enums +public extension WrappableEnum where Self: RawRepresentable { + public func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? { + return self.rawValue + } +} + +/// Extension customizing how Arrays are wrapped +extension Array: WrapCustomizable { + public func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? { + return try? Wrapper(context: context, dateFormatter: dateFormatter).wrap(collection: self) + } +} + +/// Extension customizing how Dictionaries are wrapped +extension Dictionary: WrapCustomizable { + public func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? { + return try? Wrapper(context: context, dateFormatter: dateFormatter).wrap(dictionary: self) + } +} + +/// Extension customizing how Sets are wrapped +extension Set: WrapCustomizable { + public func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? { + return try? Wrapper(context: context, dateFormatter: dateFormatter).wrap(collection: self) + } +} + +/// Extension customizing how Int64s are wrapped, ensuring compatbility with 32 bit systems +extension Int64: WrapCustomizable { + public func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? { + return NSNumber(value: self) + } +} + +/// Extension customizing how UInt64s are wrapped, ensuring compatbility with 32 bit systems +extension UInt64: WrapCustomizable { + public func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? { + return NSNumber(value: self) + } +} + +/// Extension customizing how NSStrings are wrapped +extension NSString: WrapCustomizable { + public func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? { + return self + } +} + +/// Extension customizing how NSURLs are wrapped +extension NSURL: WrapCustomizable { + public func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? { + return self.absoluteString + } +} + +/// Extension customizing how URLs are wrapped +extension URL: WrapCustomizable { + public func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? { + return self.absoluteString + } +} + + +/// Extension customizing how NSArrays are wrapped +extension NSArray: WrapCustomizable { + public func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? { + return try? Wrapper(context: context, dateFormatter: dateFormatter).wrap(collection: Array(self)) + } +} + +#if !os(Linux) +/// Extension customizing how NSDictionaries are wrapped +extension NSDictionary: WrapCustomizable { + public func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? { + return try? Wrapper(context: context, dateFormatter: dateFormatter).wrap(dictionary: self as [NSObject : AnyObject]) + } +} +#endif + +/// Extension making Int a WrappableKey +extension Int: WrappableKey { + public func toWrappedKey() -> String { + return String(self) + } +} + +/// Extension making Date a WrappableDate +extension Date: WrappableDate { + public func wrap(dateFormatter: DateFormatter) -> String { + return dateFormatter.string(from: self) + } +} + +#if !os(Linux) +/// Extension making NSdate a WrappableDate +extension NSDate: WrappableDate { + public func wrap(dateFormatter: DateFormatter) -> String { + return dateFormatter.string(from: self as Date) + } +} +#endif + +// MARK: - Private + +private extension Wrapper { + func wrap(object: T, enableCustomizedWrapping: Bool) throws -> WrappedDictionary { + if enableCustomizedWrapping { + if let customizable = object as? WrapCustomizable { + let wrapped = try self.performCustomWrapping(object: customizable) + + guard let wrappedDictionary = wrapped as? WrappedDictionary else { + throw WrapError.invalidTopLevelObject(object) + } + + return wrappedDictionary + } + } + + var mirrors = [Mirror]() + var currentMirror: Mirror? = Mirror(reflecting: object) + + while let mirror = currentMirror { + mirrors.append(mirror) + currentMirror = mirror.superclassMirror + } + + return try self.performWrapping(object: object, mirrors: mirrors.reversed()) + } + + func wrap(object: T, writingOptions: JSONSerialization.WritingOptions) throws -> Data { + let dictionary = try self.wrap(object: object, enableCustomizedWrapping: true) + return try JSONSerialization.data(withJSONObject: dictionary, options: writingOptions) + } + + func wrap(value: T, propertyName: String? = nil) throws -> Any? { + if let customizable = value as? WrapCustomizable { + return try self.performCustomWrapping(object: customizable) + } + + if let date = value as? WrappableDate { + return self.wrap(date: date) + } + + let mirror = Mirror(reflecting: value) + + if mirror.children.isEmpty { + if let displayStyle = mirror.displayStyle { + switch displayStyle { + case .enum: + if let wrappableEnum = value as? WrappableEnum { + if let wrapped = wrappableEnum.wrap(context: self.context, dateFormatter: self.dateFormatter) { + return wrapped + } + + throw WrapError.wrappingFailedForObject(value) + } + + return "\(value)" + case .struct: + return [:] + default: + return value + } + } + + if !(value is CustomStringConvertible) { + if String(describing: value) == "(Function)" { + return nil + } + } + + return value + } else if value is ExpressibleByNilLiteral && mirror.children.count == 1 { + if let firstMirrorChild = mirror.children.first { + return try self.wrap(value: firstMirrorChild.value, propertyName: propertyName) + } + } + + return try self.wrap(object: value, enableCustomizedWrapping: false) + } + + func wrap(collection: T) throws -> [Any] { + var wrappedArray = [Any]() + let wrapper = Wrapper(context: self.context, dateFormatter: self.dateFormatter) + + for element in collection { + if let wrapped = try wrapper.wrap(value: element) { + wrappedArray.append(wrapped) + } + } + + return wrappedArray + } + + func wrap(dictionary: [K : V]) throws -> WrappedDictionary { + var wrappedDictionary = WrappedDictionary() + let wrapper = Wrapper(context: self.context, dateFormatter: self.dateFormatter) + + for (key, value) in dictionary { + let wrappedKey: String? + + if let stringKey = key as? String { + wrappedKey = stringKey + } else if let wrappableKey = key as? WrappableKey { + wrappedKey = wrappableKey.toWrappedKey() + } else if let stringConvertible = key as? CustomStringConvertible { + wrappedKey = stringConvertible.description + } else { + wrappedKey = nil + } + + if let wrappedKey = wrappedKey { + wrappedDictionary[wrappedKey] = try wrapper.wrap(value: value, propertyName: wrappedKey) + } + } + + return wrappedDictionary + } + + func wrap(date: WrappableDate) -> String { + let dateFormatter: DateFormatter + + if let existingFormatter = self.dateFormatter { + dateFormatter = existingFormatter + } else { + dateFormatter = DateFormatter() + dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" + self.dateFormatter = dateFormatter + } + + return date.wrap(dateFormatter: dateFormatter) + } + + func performWrapping(object: T, mirrors: [Mirror]) throws -> WrappedDictionary { + let customizable = object as? WrapCustomizable + var wrappedDictionary = WrappedDictionary() + + for mirror in mirrors { + for property in mirror.children { + + if (property.value as? WrapOptional)?.isNil == true { + continue + } + + guard let propertyName = property.label else { + continue + } + + let wrappingKey: String? + + if let customizable = customizable { + wrappingKey = customizable.keyForWrapping(propertyNamed: propertyName) + } else { + wrappingKey = propertyName + } + + if let wrappingKey = wrappingKey { + if let wrappedProperty = try customizable?.wrap(propertyNamed: propertyName, originalValue: property.value, context: self.context, dateFormatter: self.dateFormatter) { + wrappedDictionary[wrappingKey] = wrappedProperty + } else { + wrappedDictionary[wrappingKey] = try self.wrap(value: property.value, propertyName: propertyName) + } + } + } + } + + return wrappedDictionary + } + + func performCustomWrapping(object: WrapCustomizable) throws -> Any { + guard let wrapped = object.wrap(context: self.context, dateFormatter: self.dateFormatter) else { + throw WrapError.wrappingFailedForObject(object) + } + + return wrapped + } +} + +// MARK: - Nil Handling + +private protocol WrapOptional { + var isNil: Bool { get } +} + +extension Optional : WrapOptional { + var isNil: Bool { + switch self { + case .none: + return true + case .some(let wrapped): + if let nillable = wrapped as? WrapOptional { + return nillable.isNil + } + return false + } + } +} \ No newline at end of file diff --git a/Telegram/BUILD b/Telegram/BUILD index 4247f058..9e0ffe8d 100644 --- a/Telegram/BUILD +++ b/Telegram/BUILD @@ -245,6 +245,7 @@ filegroup( name = "AppStringResources", srcs = [ "Telegram-iOS/en.lproj/Localizable.strings", + "//Swiftgram/SGStrings:SGLocalizableStrings", ] + [ "{}.lproj/Localizable.strings".format(language) for language in empty_languages ], @@ -349,6 +350,10 @@ swift_library( "Telegram-iOS/Application.swift", ]), data = [ + "//Swiftgram/SGSettingsUI:SGUIAssets", + "//Swiftgram/SGPayWall:SGPayWallAssets", + "//Swiftgram/SGAppBadgeAssets:SGAppBadgeAssets", + "//Swiftgram/SGNY:SGNYAssets", ":Icons", ":AppResources", ":AppIntentVocabularyResources", diff --git a/Telegram/NotificationService/BUILD b/Telegram/NotificationService/BUILD index 6327b76b..23061e64 100644 --- a/Telegram/NotificationService/BUILD +++ b/Telegram/NotificationService/BUILD @@ -23,6 +23,7 @@ swift_library( "//submodules/PersistentStringHash:PersistentStringHash", "//submodules/Utils/RangeSet", "//submodules/Media/ConvertOpusToAAC", + "//Swiftgram/SGStatus:SGStatus", ], visibility = [ "//visibility:public", diff --git a/Telegram/NotificationService/Sources/NotificationService.swift b/Telegram/NotificationService/Sources/NotificationService.swift index deb4e1a3..d7af0b71 100644 --- a/Telegram/NotificationService/Sources/NotificationService.swift +++ b/Telegram/NotificationService/Sources/NotificationService.swift @@ -1,3 +1,5 @@ +import SGAppGroupIdentifier +import SGStatus import Foundation import UserNotifications import SwiftSignalKit @@ -17,6 +19,16 @@ import AppLockState import NotificationsPresentationData import RangeSet import ConvertOpusToAAC +import CoreServices +import ImageIO +import UniformTypeIdentifiers + +private let groupUserDefaults: UserDefaults? = UserDefaults(suiteName: sgAppGroupIdentifier()) +private let LEGACY_NOTIFICATIONS_FIX: Bool = groupUserDefaults?.bool(forKey: "legacyNotificationsFix") ?? false +private let PINNED_MESSAGE_ACTION: String = groupUserDefaults?.string(forKey: "pinnedMessageNotifications") ?? "default" +private let PINNED_MESSAGE_ACTION_EXCEPTIONS: [String: String] = (groupUserDefaults?.dictionary(forKey: "pinnedMessageNotificationsExceptions") as? [String: String]) ?? [:] +private let MENTION_AND_REPLY_ACTION: String = groupUserDefaults?.string(forKey: "mentionsAndRepliesNotifications") ?? "default" +private let MENTION_AND_REPLY_ACTION_EXCEPTIONS: [String: String] = (groupUserDefaults?.dictionary(forKey: "mentionsAndRepliesNotificationsExceptions") as? [String: String]) ?? [:] private let queue = Queue() @@ -275,13 +287,18 @@ private extension CGSize { } } -private func convertLottieImage(data: Data) -> UIImage? { +private func convertLottieImage(data: Data, size: CGSize, forceSquare: Bool) -> UIImage? { let decompressedData = TGGUnzipData(data, 512 * 1024) ?? data guard let animation = LottieInstance(data: decompressedData, fitzModifier: .none, colorReplacements: nil, cacheKey: "") else { return nil } - let size = animation.dimensions.fitted(CGSize(width: 200.0, height: 200.0)) - let context = DrawingContext(size: size, scale: 1.0, opaque: false, clear: true) + let actualSize: CGSize + if forceSquare { + actualSize = animation.dimensions.fitted(size) + } else { + actualSize = size + } + let context = DrawingContext(size: actualSize, scale: 1.0, opaque: false, clear: true) animation.renderFrame(with: 0, into: context.bytes.assumingMemoryBound(to: UInt8.self), width: Int32(context.scaledSize.width), height: Int32(context.scaledSize.height), bytesPerRow: Int32(context.bytesPerRow)) return context.generateImage() } @@ -486,9 +503,21 @@ private func peerAvatar(mediaBox: MediaBox, accountPeerId: PeerId, peer: Peer, i @available(iOSApplicationExtension 10.0, iOS 10.0, *) private struct NotificationContent: CustomStringConvertible { + struct CustomEmoji { + var range: Range + var fileId: Int64 + + init(range: Range, fileId: Int64) { + self.range = range + self.fileId = fileId + } + } + var title: String? var subtitle: String? var body: String? + var customEmoji: [CustomEmoji] = [] + var resolvedEmojiFiles: [Int64: String] = [:] var threadId: String? var sound: String? var badge: Int? @@ -496,14 +525,24 @@ private struct NotificationContent: CustomStringConvertible { var userInfo: [AnyHashable: Any] = [:] var attachments: [UNNotificationAttachment] = [] var silent = false + // MARK: Swiftgram + var isEmpty: Bool + var isMentionOrReply: Bool + var isPinned: Bool = false + let chatId: Int64? + let sgStatus: SGStatus var senderPerson: INPerson? var senderImage: INImage? var isLockedMessage: String? - init(isLockedMessage: String?) { + init(sgStatus: SGStatus, isLockedMessage: String?, isEmpty: Bool = false, isMentionOrReply: Bool = false, chatId: Int64? = nil) { + self.sgStatus = sgStatus self.isLockedMessage = isLockedMessage + self.isEmpty = isEmpty + self.isMentionOrReply = isMentionOrReply + self.chatId = chatId } var description: String { @@ -519,6 +558,14 @@ private struct NotificationContent: CustomStringConvertible { string += " senderImage: \(self.senderImage != nil ? "non-empty" : "empty"),\n" string += " isLockedMessage: \(String(describing: self.isLockedMessage)),\n" string += " attachments: \(self.attachments),\n" + string += " resolvedEmojiFiles: \(self.resolvedEmojiFiles.count) files,\n" + string += " isEmpty: \(self.isEmpty),\n" + string += " chatId: \(String(describing: self.chatId)),\n" + string += " isMentionOrReply: \(self.isMentionOrReply),\n" + string += " isPinned: \(self.isPinned),\n" + string += " forceIsEmpty: \(self.forceIsEmpty),\n" + string += " forceIsSilent: \(self.forceIsSilent),\n" + string += " sgStatus: \(self.sgStatus.status),\n" string += "}" return string } @@ -533,7 +580,7 @@ private struct NotificationContent: CustomStringConvertible { if let topicTitle { displayName = "\(topicTitle) (\(displayName))" } - if self.silent { + if self.silent || self.forceIsSilent { displayName = "\(displayName) 🔕" } @@ -557,19 +604,65 @@ private struct NotificationContent: CustomStringConvertible { var content = UNMutableNotificationContent() //Logger.shared.log("NotificationService", "Generating final content: \(self.description)") - + // MARK: Swiftgram + #if DEBUG + print("body:\(content.body) silent:\(self.silent) isMentionOrReply:\(self.isMentionOrReply) MENTION_AND_REPLY_ACTION:\(MENTION_AND_REPLY_ACTION) isPinned:\(self.isPinned) PINNED_MESSAGE_ACTION:\(PINNED_MESSAGE_ACTION)" + " forceIsEmpty:\(self.forceIsEmpty) forceIsSilent:\(self.forceIsSilent)") + #endif + if self.forceIsEmpty && !LEGACY_NOTIFICATIONS_FIX { + return UNNotificationContent() + } if let title = self.title { - if self.silent { + if self.silent || self.forceIsSilent { content.title = "\(title) 🔕" } else { content.title = title } } + if let subtitle = self.subtitle { content.subtitle = subtitle } if let body = self.body { - content.body = body + if #available(iOS 18.0, *) { + if !self.resolvedEmojiFiles.isEmpty { + let attributedString = NSMutableAttributedString(string: body) + + let sortedEmoji = self.customEmoji.sorted(by: { $0.range.lowerBound < $1.range.lowerBound }) + + for emoji in sortedEmoji.reversed() { + if emoji.range.lowerBound < 0 || emoji.range.upperBound > attributedString.length { + continue + } + guard let filePath = self.resolvedEmojiFiles[emoji.fileId] else { + continue + } + guard let fileData = try? Data(contentsOf: URL(fileURLWithPath: filePath)) else { + continue + } + let image: UIImage + if let lottieImage = convertLottieImage(data: fileData, size: CGSize(width: 40.0, height: 40.0), forceSquare: false) { + image = lottieImage + } else if let webpImage = WebP.convert(fromWebP: fileData) { + image = webpImage + } else { + continue + } + + let emojiRange = NSRange(location: emoji.range.lowerBound, length: emoji.range.upperBound - emoji.range.lowerBound) + let substring = attributedString.attributedSubstring(from: emojiRange) + + let glyph = try! Customoji.makeGlyph(from: image, description: substring.string, tileSizes: [40], cropToSquare: false) + let imageString = NSAttributedString(adaptiveImageGlyph: glyph, attributes: [:]) + attributedString.replaceCharacters(in: emojiRange, with: "") + attributedString.insert(imageString, at: emojiRange.lowerBound) + } + content.setValue(attributedString, forKey: "attributedBody") + } else { + content.body = body + } + } else { + content.body = body + } } if !content.title.isEmpty || !content.subtitle.isEmpty || !content.body.isEmpty { @@ -638,7 +731,20 @@ private struct NotificationContent: CustomStringConvertible { } } } - + + // MARK: Swiftgram + if (self.isEmpty || self.forceIsEmpty) && LEGACY_NOTIFICATIONS_FIX { + content.title = " " + content.threadIdentifier = "empty-notification" + if #available(iOSApplicationExtension 15.0, iOS 15.0, *) { + content.interruptionLevel = .passive + content.relevanceScore = 0.0 + } + } + + if self.forceIsSilent { + content.sound = nil + } return content } } @@ -787,7 +893,8 @@ private final class NotificationServiceHandler { ApplicationSpecificSharedDataKeys.inAppNotificationSettings, ApplicationSpecificSharedDataKeys.voiceCallSettings, ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings, - SharedDataKeys.loggingSettings + SharedDataKeys.loggingSettings, + ApplicationSpecificSharedDataKeys.sgStatus ]) ) |> take(1) @@ -820,6 +927,7 @@ private final class NotificationServiceHandler { } let inAppNotificationSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.inAppNotificationSettings]?.get(InAppNotificationSettings.self) ?? InAppNotificationSettings.defaultSettings + let sgStatus = sharedData.entries[ApplicationSpecificSharedDataKeys.sgStatus]?.get(SGStatus.self) ?? SGStatus.default let voiceCallSettings: VoiceCallSettings if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.voiceCallSettings]?.get(VoiceCallSettings.self) { @@ -831,7 +939,7 @@ private final class NotificationServiceHandler { guard let strongSelf = self, let recordId = recordId else { Logger.shared.log("NotificationService \(episode)", "Couldn't find a matching decryption key") - let content = NotificationContent(isLockedMessage: nil) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil) updateCurrentContent(content) completed() @@ -853,7 +961,7 @@ private final class NotificationServiceHandler { guard let stateManager = stateManager else { Logger.shared.log("NotificationService \(episode)", "Didn't receive stateManager") - let content = NotificationContent(isLockedMessage: nil) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil) updateCurrentContent(content) completed() return @@ -871,7 +979,7 @@ private final class NotificationServiceHandler { settings ) |> deliverOn(strongSelf.queue)).start(next: { notificationsKey, notificationSoundList in guard let strongSelf = self else { - let content = NotificationContent(isLockedMessage: nil) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil) updateCurrentContent(content) completed() @@ -880,7 +988,7 @@ private final class NotificationServiceHandler { guard let notificationsKey = notificationsKey else { Logger.shared.log("NotificationService \(episode)", "Didn't receive decryption key") - let content = NotificationContent(isLockedMessage: nil) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil) updateCurrentContent(content) completed() @@ -889,7 +997,7 @@ private final class NotificationServiceHandler { guard let decryptedPayload = decryptedNotificationPayload(key: notificationsKey, data: payloadData) else { Logger.shared.log("NotificationService \(episode)", "Couldn't decrypt payload") - let content = NotificationContent(isLockedMessage: nil) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil) updateCurrentContent(content) completed() @@ -898,12 +1006,17 @@ private final class NotificationServiceHandler { guard let payloadJson = try? JSONSerialization.jsonObject(with: decryptedPayload, options: []) as? [String: Any] else { Logger.shared.log("NotificationService \(episode)", "Couldn't process payload as JSON") - let content = NotificationContent(isLockedMessage: nil) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil) updateCurrentContent(content) completed() return } + let isMentionOrReply: Bool = payloadJson["mention"] as? String == "1" + var chatId: Int64? = nil + if let chatIdString = payloadJson["chat_id"] as? String { + chatId = Int64(chatIdString) + } Logger.shared.log("NotificationService \(episode)", "Decrypted payload: \(payloadJson)") @@ -1018,7 +1131,7 @@ private final class NotificationServiceHandler { enum Action { case logout - case poll(peerId: PeerId, content: NotificationContent, messageId: MessageId?, reportDelivery: Bool) + case poll(peerId: PeerId, content: NotificationContent, messageId: MessageId?, reportDelivery: Bool, enableInlineEmoji: Bool) case pollStories(peerId: PeerId, content: NotificationContent, storyId: Int32, isReaction: Bool) case deleteMessage([MessageId]) case readReactions([MessageId]) @@ -1040,7 +1153,7 @@ private final class NotificationServiceHandler { action = .logout case "MESSAGE_MUTED": if let peerId = peerId { - action = .poll(peerId: peerId, content: NotificationContent(isLockedMessage: nil), messageId: nil, reportDelivery: false) + action = .poll(peerId: peerId, content: NotificationContent(sgStatus: sgStatus, isLockedMessage: nil, isEmpty: true, isMentionOrReply: isMentionOrReply, chatId: chatId), messageId: nil, reportDelivery: false, enableInlineEmoji: false) } case "MESSAGE_DELETED": if let peerId = peerId { @@ -1091,7 +1204,7 @@ private final class NotificationServiceHandler { } } else { if let aps = payloadJson["aps"] as? [String: Any], var peerId = peerId { - var content: NotificationContent = NotificationContent(isLockedMessage: isLockedMessage) + var content: NotificationContent = NotificationContent(sgStatus: sgStatus, isLockedMessage: isLockedMessage, isMentionOrReply: isMentionOrReply, chatId: chatId) if let alert = aps["alert"] as? [String: Any] { if let topicTitleValue = payloadJson["topic_title"] as? String { topicTitle = topicTitleValue @@ -1231,7 +1344,11 @@ private final class NotificationServiceHandler { reportDelivery = true } } - action = .poll(peerId: peerId, content: content, messageId: messageIdValue, reportDelivery: reportDelivery) + var enableInlineEmoji = true + if let _ = aps["_ddie"] { + enableInlineEmoji = false + } + action = .poll(peerId: peerId, content: content, messageId: messageIdValue, reportDelivery: reportDelivery, enableInlineEmoji: enableInlineEmoji) } updateCurrentContent(content) @@ -1242,7 +1359,7 @@ private final class NotificationServiceHandler { switch action { case let .call(callData): if let stateManager = strongSelf.stateManager { - let content = NotificationContent(isLockedMessage: nil) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil) updateCurrentContent(content) let _ = (stateManager.postbox.transaction { transaction -> String? in @@ -1265,7 +1382,7 @@ private final class NotificationServiceHandler { if #available(iOS 14.5, *), voiceCallSettings.enableSystemIntegration { Logger.shared.log("NotificationService \(episode)", "Will report voip notification") - let content = NotificationContent(isLockedMessage: nil) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil) updateCurrentContent(content) CXProvider.reportNewIncomingVoIPPushPayload(voipPayload, completion: { error in @@ -1274,7 +1391,7 @@ private final class NotificationServiceHandler { completed() }) } else { - var content = NotificationContent(isLockedMessage: nil) + var content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil) if let peer = callData.peer { content.title = peer.debugDisplayTitle content.body = incomingCallMessage @@ -1289,7 +1406,7 @@ private final class NotificationServiceHandler { } case let .groupCall(groupCallData): if let stateManager = strongSelf.stateManager { - let content = NotificationContent(isLockedMessage: nil) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil) updateCurrentContent(content) let _ = (stateManager.postbox.transaction { transaction -> TelegramUser? in @@ -1310,7 +1427,7 @@ private final class NotificationServiceHandler { if #available(iOS 14.5, *), voiceCallSettings.enableSystemIntegration { Logger.shared.log("NotificationService \(episode)", "Will report voip notification") - let content = NotificationContent(isLockedMessage: nil) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil) updateCurrentContent(content) CXProvider.reportNewIncomingVoIPPushPayload(voipPayload, completion: { error in @@ -1319,7 +1436,7 @@ private final class NotificationServiceHandler { completed() }) } else { - var content = NotificationContent(isLockedMessage: nil) + var content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil) if let peer = fromPeer { content.title = peer.debugDisplayTitle content.body = incomingCallMessage @@ -1335,10 +1452,10 @@ private final class NotificationServiceHandler { case .logout: Logger.shared.log("NotificationService \(episode)", "Will logout") - let content = NotificationContent(isLockedMessage: nil) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil, isEmpty: true) updateCurrentContent(content) completed() - case let .poll(peerId, initialContent, messageId, reportDelivery): + case let .poll(peerId, initialContent, messageId, reportDelivery, enableInlineEmoji): Logger.shared.log("NotificationService \(episode)", "Will poll") if let stateManager = strongSelf.stateManager { let shouldKeepConnection = stateManager.network.shouldKeepConnection @@ -1346,9 +1463,14 @@ private final class NotificationServiceHandler { let pollCompletion: (NotificationContent, Media?) -> Void = { content, customMedia in var content = content + // MARK: Swiftgram + if let mediaAction = customMedia as? TelegramMediaAction, case .pinnedMessageUpdated = mediaAction.action { + content.isPinned = true + } + queue.async { guard let strongSelf = self, let stateManager = strongSelf.stateManager else { - let content = NotificationContent(isLockedMessage: isLockedMessage) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: isLockedMessage) updateCurrentContent(content) completed() return @@ -1357,7 +1479,7 @@ private final class NotificationServiceHandler { let mediaAttachment = mediaAttachment ?? customMedia var fetchMediaSignal: Signal = .single(nil) - if let mediaAttachment = mediaAttachment { + if let mediaAttachment { var contentType: MediaResourceUserContentType = .other var fetchResource: TelegramMultipartFetchableResource? if let image = mediaAttachment as? TelegramMediaImage, let representation = largestImageRepresentation(image.representations), let resource = representation.resource as? TelegramMultipartFetchableResource { @@ -1524,10 +1646,146 @@ private final class NotificationServiceHandler { } let wasDisplayed = stateManager.postbox.transaction { transaction -> Bool in + var wasDisplayed = false if let messageId { - return _internal_getMessageNotificationWasDisplayed(transaction: transaction, id: messageId) - } else { - return false + wasDisplayed = _internal_getMessageNotificationWasDisplayed(transaction: transaction, id: messageId) + } + + return wasDisplayed + } + + let maxEmojiCount: Int = 10 + var uniqueEmojiIds: [Int64] = [] + for emoji in content.customEmoji { + if !uniqueEmojiIds.contains(emoji.fileId) { + uniqueEmojiIds.append(emoji.fileId) + if uniqueEmojiIds.count >= maxEmojiCount { + break + } + } + } + + let resolvedEmojiFiles: Signal<[Int64: String], NoError> = _internal_resolveInlineStickers(postbox: stateManager.postbox, network: stateManager.network, fileIds: uniqueEmojiIds) + |> mapToSignal { files -> Signal<[Int64: String], NoError> in + var fetchSignals: [Signal<(Int64, String?), NoError>] = [] + + for (_, file) in files { + if let resource = file.resource as? TelegramMultipartFetchableResource { + let fetchSignal: Signal<(Int64, String?), NoError> + if let path = stateManager.postbox.mediaBox.completedResourcePath(resource) { + fetchSignal = .single((file.fileId.id, path)) + } else { + let intervals: Signal<[(Range, MediaBoxFetchPriority)], NoError> = .single([(0 ..< Int64.max, MediaBoxFetchPriority.maximum)]) + let fetchDataSignal: Signal = Signal { subscriber in + final class DataValue { + var data = Data() + var missingRanges = RangeSet(0 ..< Int64.max) + } + + let collectedData = Atomic(value: DataValue()) + + return standaloneMultipartFetch( + accountPeerId: stateManager.accountPeerId, + postbox: stateManager.postbox, + network: stateManager.network, + resource: resource, + datacenterId: resource.datacenterId, + size: nil, + intervals: intervals, + parameters: MediaResourceFetchParameters( + tag: nil, + info: resourceFetchInfo(resource: resource), + location: messageId.flatMap { messageId in + return MediaResourceStorageLocation( + peerId: peerId, + messageId: messageId + ) + }, + contentType: .sticker, + isRandomAccessAllowed: true + ), + encryptionKey: nil, + decryptedSize: nil, + continueInBackground: false, + useMainConnection: true + ).start(next: { result in + switch result { + case let .dataPart(offset, data, dataRange, _): + var isCompleted = false + let _ = collectedData.modify { current in + let current = current + + let fillRange = Int(offset) ..< (Int(offset) + data.count) + if current.data.count < fillRange.upperBound { + current.data.count = fillRange.upperBound + } + current.data.withUnsafeMutableBytes { buffer -> Void in + let bytes = buffer.baseAddress!.assumingMemoryBound(to: UInt8.self) + data.copyBytes(to: bytes.advanced(by: Int(offset)), from: Int(dataRange.lowerBound) ..< Int(dataRange.upperBound)) + } + current.missingRanges.remove(contentsOf: Int64(fillRange.lowerBound) ..< Int64(fillRange.upperBound)) + + if current.missingRanges.isEmpty { + isCompleted = true + } + return current + } + if isCompleted { + let data = collectedData.with({ $0.data }) + subscriber.putNext( data) + subscriber.putCompletion() + } + case let .resourceSizeUpdated(size): + var isCompleted = false + let _ = collectedData.modify { current in + let current = current + current.missingRanges.remove(contentsOf: size ..< Int64.max) + if current.missingRanges.isEmpty { + isCompleted = true + } + return current + } + if isCompleted { + let data = collectedData.with({ $0.data }) + subscriber.putNext(data) + subscriber.putCompletion() + } + default: + break + } + }, error: { _ in + subscriber.putNext(nil) + subscriber.putCompletion() + }, completed: { + let data = collectedData.with({ $0.data }) + subscriber.putNext(data) + subscriber.putCompletion() + }) + } + fetchSignal = fetchDataSignal |> map { data -> (Int64, String?) in + guard let data else { + return (file.fileId.id, nil) + } + stateManager.postbox.mediaBox.storeResourceData(resource.id, data: data, synchronous: true) + if let path = stateManager.postbox.mediaBox.completedResourcePath(resource) { + return (file.fileId.id, path) + } else { + return (file.fileId.id, nil) + } + } + } + fetchSignals.append(fetchSignal) + } + } + return combineLatest(fetchSignals) + |> map { results -> [Int64: String] in + var result: [Int64: String] = [:] + for (id, path) in results { + if let path { + result[id] = path + } + } + return result } } @@ -1537,9 +1795,11 @@ private final class NotificationServiceHandler { |> timeout(10.0, queue: queue, alternate: .single(nil)), fetchNotificationSoundSignal |> timeout(10.0, queue: queue, alternate: .single(nil)), - wasDisplayed + wasDisplayed, + resolvedEmojiFiles + |> timeout(10.0, queue: queue, alternate: .single([:])), ) - |> deliverOn(queue)).start(next: { mediaData, notificationSoundData, wasDisplayed in + |> deliverOn(queue)).start(next: { mediaData, notificationSoundData, wasDisplayed, resolvedEmojiFiles in guard let strongSelf = self, let stateManager = strongSelf.stateManager else { completed() return @@ -1611,7 +1871,7 @@ private final class NotificationServiceHandler { stateManager.postbox.mediaBox.storeResourceData(resource.id, data: mediaData, synchronous: true) } if let storedPath = stateManager.postbox.mediaBox.completedResourcePath(resource) { - if let data = try? Data(contentsOf: URL(fileURLWithPath: storedPath)), let image = convertLottieImage(data: data) { + if let data = try? Data(contentsOf: URL(fileURLWithPath: storedPath)), let image = convertLottieImage(data: data, size: CGSize(width: 200.0, height: 200.0), forceSquare: false) { let tempFile = TempBox.shared.tempFile(fileName: "image.png") let _ = try? image.pngData()?.write(to: URL(fileURLWithPath: tempFile.path)) if let attachment = try? UNNotificationAttachment(identifier: "image", url: URL(fileURLWithPath: tempFile.path), options: nil) { @@ -1650,11 +1910,13 @@ private final class NotificationServiceHandler { } } } + + content.resolvedEmojiFiles = resolvedEmojiFiles Logger.shared.log("NotificationService \(episode)", "Updating content to \(content)") if wasDisplayed { - content = NotificationContent(isLockedMessage: nil) + content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil, isMentionOrReply: isMentionOrReply, chatId: chatId) Logger.shared.log("NotificationService \(episode)", "Was already displayed, skipping content") } else if let messageId { let _ = (stateManager.postbox.transaction { transaction -> Void in @@ -1745,7 +2007,7 @@ private final class NotificationServiceHandler { case let .idBased(maxIncomingReadId, _, _, _, _): if maxIncomingReadId >= messageId.id { Logger.shared.log("NotificationService \(episode)", "maxIncomingReadId: \(maxIncomingReadId), messageId: \(messageId.id), skipping") - content = NotificationContent(isLockedMessage: nil) + content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil, isMentionOrReply: isMentionOrReply, chatId: chatId) } else { Logger.shared.log("NotificationService \(episode)", "maxIncomingReadId: \(maxIncomingReadId), messageId: \(messageId.id), not skipping") } @@ -1766,11 +2028,26 @@ private final class NotificationServiceHandler { |> takeLast |> mapToSignal { content, _ -> Signal<(NotificationContent, Media?), NoError> in return stateManager.postbox.transaction { transaction -> (NotificationContent, Media?) in + var content = content + var parsedMedia: Media? if let messageId, let message = transaction.getMessage(messageId), !message.containsSecretMedia, !message.attributes.contains(where: { $0 is MediaSpoilerMessageAttribute }) { if let media = message.media.first { parsedMedia = media } + if enableInlineEmoji, let textEntitiesAttribute = message.textEntitiesAttribute, let author = message.author { + let authorTitle = author.debugDisplayTitle + let messagePrefix = "\(authorTitle): " + let messagePrefixLength = (messagePrefix as NSString).length + for entity in textEntitiesAttribute.entities { + if case let .CustomEmoji(_, fileId) = entity.type { + content.customEmoji.append(NotificationContent.CustomEmoji(range: (entity.range.lowerBound + messagePrefixLength) ..< (entity.range.upperBound + messagePrefixLength), fileId: fileId)) + } + } + if !content.customEmoji.isEmpty { + content.body = messagePrefix + message.text + } + } } return (content, parsedMedia) @@ -1808,7 +2085,7 @@ private final class NotificationServiceHandler { queue.async { guard let strongSelf = self, let stateManager = strongSelf.stateManager else { - let content = NotificationContent(isLockedMessage: isLockedMessage) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: isLockedMessage, isEmpty: true) updateCurrentContent(content) completed() return @@ -2008,7 +2285,7 @@ private final class NotificationServiceHandler { var content = content if wasDisplayed { - content = NotificationContent(isLockedMessage: nil) + content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil) } else { let _ = (stateManager.postbox.transaction { transaction -> Void in _internal_setStoryNotificationWasDisplayed(transaction: transaction, id: StoryId(peerId: peerId, id: storyId)) @@ -2100,7 +2377,7 @@ private final class NotificationServiceHandler { postbox: stateManager.postbox ) |> deliverOn(strongSelf.queue)).start(next: { value in - var content = NotificationContent(isLockedMessage: nil) + var content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil, isEmpty: true) if isCurrentAccount { content.badge = Int(value.0) } @@ -2142,7 +2419,7 @@ private final class NotificationServiceHandler { } let completeRemoval: () -> Void = { - let content = NotificationContent(isLockedMessage: nil) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil, isEmpty: true) Logger.shared.log("NotificationService \(episode)", "Updating content to \(content)") updateCurrentContent(content) @@ -2194,7 +2471,7 @@ private final class NotificationServiceHandler { postbox: stateManager.postbox ) |> deliverOn(strongSelf.queue)).start(next: { value in - var content = NotificationContent(isLockedMessage: nil) + var content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil, isEmpty: true) if isCurrentAccount { content.badge = Int(value.0) } @@ -2235,7 +2512,7 @@ private final class NotificationServiceHandler { } let completeRemoval: () -> Void = { - let content = NotificationContent(isLockedMessage: nil) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil, isEmpty: true) updateCurrentContent(content) completed() @@ -2254,7 +2531,7 @@ private final class NotificationServiceHandler { }) } } else { - let content = NotificationContent(isLockedMessage: nil) + let content = NotificationContent(sgStatus: sgStatus, isLockedMessage: nil) updateCurrentContent(content) completed() @@ -2288,11 +2565,70 @@ final class NotificationService: UNNotificationServiceExtension { private let content = Atomic(value: nil) private var contentHandler: ((UNNotificationContent) -> Void)? private var episode: String? + // MARK: Swiftgram + private var emptyNotificationsRemoved: Bool = false + private var notificationRemovalTries: Int32 = 0 + private let maxNotificationRemovalTries: Int32 = 30 override init() { super.init() } + // MARK: Swiftgram + func removeEmptyNotificationsOnce() { + if !LEGACY_NOTIFICATIONS_FIX { + return + } + var emptyNotifications: [String] = [] + UNUserNotificationCenter.current().getDeliveredNotifications(completionHandler: { notifications in + for notification in notifications { + if notification.request.content.threadIdentifier == "empty-notification" { + emptyNotifications.append(notification.request.identifier) + } + } + if !emptyNotifications.isEmpty { + UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: emptyNotifications) + #if DEBUG + NSLog("Empty notifications removed once. Count \(emptyNotifications.count)") + #endif + } + }) + } + + func removeEmptyNotifications() { + if !LEGACY_NOTIFICATIONS_FIX { + return + } + self.notificationRemovalTries += 1 + if self.emptyNotificationsRemoved || self.notificationRemovalTries > self.maxNotificationRemovalTries { + #if DEBUG + NSLog("Notification removal try rejected \(self.notificationRemovalTries)") + #endif + return + } + var emptyNotifications: [String] = [] + #if DEBUG + NSLog("Notification removal try \(notificationRemovalTries)") + #endif + UNUserNotificationCenter.current().getDeliveredNotifications(completionHandler: { notifications in + for notification in notifications { + if notification.request.content.threadIdentifier == "empty-notification" { + emptyNotifications.append(notification.request.identifier) + } + } + if !emptyNotifications.isEmpty { + UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: emptyNotifications) + self.emptyNotificationsRemoved = true + #if DEBUG + NSLog("Empty notifications removed on try \(self.notificationRemovalTries). Count \(emptyNotifications.count)") + #endif + } else { + self.removeEmptyNotifications() + } + }) + + } + override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { let episode = String(UInt32.random(in: 0 ..< UInt32.max), radix: 16) self.episode = episode @@ -2323,7 +2659,12 @@ final class NotificationService: UNNotificationServiceExtension { strongSelf.contentHandler = nil if let content = content.with({ $0 }) { + // MARK: Swiftgram + strongSelf.removeEmptyNotificationsOnce() contentHandler(content.generate()) + if content.isEmpty { + strongSelf.removeEmptyNotifications() + } } else if let initialContent = strongSelf.initialContent { contentHandler(initialContent) } @@ -2350,3 +2691,479 @@ final class NotificationService: UNNotificationServiceExtension { } } } + +typealias CMJImage = UIImage + +// MARK: - Public Namespace + +/// A lightweight utility for turning ordinary bitmap images into ``NSAdaptiveImageGlyph`` (Apple “Genmoji”) objects. +/// +/// ## Overview +/// The public API is minimal — a single call to generate a glyph and helper utilities for +/// de/serialising attributed strings. +/// +/// ```swift +/// // Synchronous usage +/// let glyph = try Customoji.makeGlyph( +/// from: image, +/// description: "alt text", +/// cropToSquare: true +/// ) +/// let attr = NSAttributedString(adaptiveImageGlyph: glyph, attributes: [:]) +/// ``` +/// +/// ## Requirements +/// * iOS 18 / macOS 15 +/// * Swift 5.10+ +/// +/// ## Topics +/// - Generating glyphs: ``makeGlyph(from:description:identifier:tileSizes:cropToSquare:heicQuality:)`` +/// - Generating glyphs asynchronously: ``makeGlyphAsync(from:description:identifier:tileSizes:cropToSquare:heicQuality:)`` +/// - Serialising: ``decompose(_:)`` / ``recompose(plain:ranges:blobs:)`` +/// +public struct Customoji { + + // MARK: Library-scoped Errors + /// Errors that can be thrown by ``Customoji``. + public enum Error: Swift.Error, LocalizedError { + /// The input image is not square and ``makeGlyph(from:description:identifier:tileSizes:cropToSquare:heicQuality:)`` was called with `cropToSquare == false`. + case nonSquare + /// The longest side of the input image exceeds ``maxSide`` pixels (defaults to 4096). + case imageTooLarge + /// Failed to create an in-memory HEIC container via *Image I/O*. + case heicDestinationCreationFailed + /// Failed to finalise the HEIC container after writing all tiles. + case heicFinalizeFailed + /// Internal resize operation failed when generating a tile. + case imageScaleFailed + /// A `CGImage` representation could not be extracted from the source image. + case cgImageUnavailable + /// The `tileSizes` parameter was empty, not strictly ascending, contained duplicates, or exceeded the source size. + case invalidTileSizes + /// No tiles were generated — normally unreachable unless all requested sizes were invalid. + case noTilesGenerated + /// The current platform is neither UIKit- nor AppKit-based (unlikely in practice). + case unsupportedPlatform + /// The `heicQuality` parameter was outside the 0.0 … 1.0 range. + case invalidHeicQuality + /// Cropping or scaling to a square failed. + case squareCropFailed + + /// Textual description suitable for presenting to users. + public var errorDescription: String? { + switch self { + case .nonSquare: return "Input image must be square." + case .imageTooLarge: + return "Source image is too large to process safely." + case .heicDestinationCreationFailed: + return + "Failed to create an in-memory HEIC destination container." + case .heicFinalizeFailed: return "Failed to finalize HEIC encoding." + case .imageScaleFailed: return "Failed to rescale CGImage tile." + case .cgImageUnavailable: + return "Unable to obtain CGImage from the source image." + case .invalidTileSizes: + return + "Tile sizes must be unique, strictly ascending, and not exceed the source size." + case .noTilesGenerated: + return "No tiles were generated from the source image." + case .unsupportedPlatform: + return + "Unsupported platform when attempting to extract CGImage." + case .invalidHeicQuality: + return "HEIC quality must be between 0.0 and 1.0." + case .squareCropFailed: + return "Failed to create a square crop of the input image." + } + } + } + + /// Default tile sizes (in pixels) officially used by Apple for Genmoji. + public static let defaultTileSizes = [40, 64, 96, 160, 320] + + /// Maximum allowed side length (in pixels) to guard against excessive memory consumption. + private static let maxSide = 4_096 + + // MARK: - Synchronous Builder + #if swift(>=5.10) + @available(iOS 18.0, macCatalyst 18.0, macOS 15.0, *) + /// Generates an ``NSAdaptiveImageGlyph`` synchronously on the **current** thread. + /// + /// - Parameters: + /// - image: Source image. Can be rectangular; see `cropToSquare`. + /// - description: A human-readable accessibility description (VoiceOver/Narrator). + /// - identifier: A globally unique content identifier. Defaults to a fresh UUID. + /// - tileSizes: Desired tile sizes, in pixels. Must be strictly ascending. Defaults to ``defaultTileSizes``. + /// - cropToSquare: When `true`, the central square area is cropped if the input image is not square. + /// - heicQuality: Lossy compression quality between `0.0` and `1.0`. Defaults to `0.8`. + /// - Throws: ``Customoji/Error`` if validation or encoding fails. + /// - Returns: A fully-formed glyph ready for attribution. + static func makeGlyph( + from image: CMJImage, + description: String, + identifier: String = UUID().uuidString, + tileSizes: [Int] = defaultTileSizes, + cropToSquare: Bool = false, + heicQuality: CGFloat = 0.8 + ) throws -> NSAdaptiveImageGlyph { + try validatePixelSide(of: image) + let cg = try extractCGImage(from: image) + + return try coreMakeGlyph( + from: cg, + description: description, + identifier: identifier, + tileSizes: tileSizes, + cropToSquare: cropToSquare, + heicQuality: heicQuality + ) + } + #endif + + // MARK: - AttributedString Utilities + #if swift(>=5.10) + @available(iOS 18.0, macCatalyst 18.0, macOS 15.0, *) + /// Breaks an ``NSAttributedString`` that may contain adaptive-image glyphs into three parts. + /// + /// This is handy when you need to **serialise** rich text for network transport or persistent + /// storage, because `NSAdaptiveImageGlyph` itself is not `Codable`. + /// + /// ```swift + /// let (plain, ranges, blobs) = Customoji.decompose(attrString) + /// ``` + /// + /// - Returns: A tuple where: + /// - plain: UTF-16 plain text. + /// - ranges: An array mapping text ranges to glyph identifiers. + /// - blobs: A dictionary mapping identifier → raw HEIC data. + @inlinable + public static func decompose(_ attr: NSAttributedString) -> ( + plain: String, ranges: [(NSRange, String)], blobs: [String: Data] + ) { + var ranges = [(NSRange, String)]() + var blobs = [String: Data]() + + attr.enumerateAttribute( + .adaptiveImageGlyph, + in: NSRange(location: 0, length: attr.length) + ) { value, range, _ in + guard let g = value as? NSAdaptiveImageGlyph else { return } + let id = g.contentIdentifier + ranges.append((range, id)) + blobs[id] = blobs[id] ?? g.imageContent + } + + return (attr.string, ranges, blobs) + } + + @available(iOS 18.0, macCatalyst 18.0, macOS 15.0, *) + /// Reassembles an attributed string previously produced by ``decompose(_:)``. + /// + /// - Parameters: + /// - plain: The plain UTF-16 text. + /// - ranges: An array of `(NSRange, identifier)` pairs. + /// - blobs: A dictionary of identifier → HEIC data. *Must* contain every identifier referenced by `ranges`. + /// - Returns: A fully restored `NSAttributedString` with adaptive-image glyphs reinstated. + public static func recompose( + plain: String, + ranges: [(NSRange, String)], + blobs: [String: Data] + ) -> NSAttributedString { + let out = NSMutableAttributedString(string: plain) + var cache = [String: NSAdaptiveImageGlyph]() + + ranges.forEach { (range, id) in + if cache[id] == nil, let data = blobs[id] { + cache[id] = NSAdaptiveImageGlyph(imageContent: data) + } + if let glyph = cache[id] { + out.addAttribute( + .adaptiveImageGlyph, + value: glyph, + range: range + ) + } + } + return out + } + #endif + + // MARK: - Helper: Pixel-Side Validation + /// Ensures that the image’s **longer edge** does not exceed ``maxSide`` pixels, guarding against + /// excessive memory usage during HEIC encoding. + private static func validatePixelSide(of image: CMJImage) throws { + #if canImport(UIKit) + let scale = image.scale == 0 ? 1 : image.scale + let px = Int(max(image.size.width, image.size.height) * scale) + #elseif canImport(AppKit) + let px = Int( + max(image.size.width, image.size.height) + * CGFloat(NSScreen.main?.backingScaleFactor ?? 1) + ) + #endif + guard px <= maxSide else { throw Error.imageTooLarge } + } +} + +// ============================================================= +// Below this line lies the internal implementation. +// Public-facing symbols have already been documented above. +// ============================================================= + +// MARK: - Core Builder +@available(iOS 18.0, macCatalyst 18.0, macOS 15.0, *) +extension Customoji { + @Sendable fileprivate static func coreMakeGlyph( + from original: CGImage, + description: String, + identifier: String, + tileSizes: [Int], + cropToSquare: Bool, + heicQuality: CGFloat + ) throws -> NSAdaptiveImageGlyph { + let cg = try ensureSquare(original, cropIfNeeded: cropToSquare) + guard cg.width <= maxSide else { throw Error.imageTooLarge } + + let validSizes = try validatedTileSizes(tileSizes, max: cg.width) + let data = try heicData( + from: cg, + id: identifier, + description: description, + tileSizes: validSizes, + quality: heicQuality + ) + return NSAdaptiveImageGlyph(imageContent: data) + } +} + +// MARK: - HEIC Encoder +@available(iOS 18.0, macCatalyst 18.0, macOS 15.0, *) +extension Customoji { + fileprivate static func heicData( + from cg: CGImage, + id: String, + description: String, + tileSizes: [Int], + quality: CGFloat + ) throws -> Data { + guard (0...1).contains(quality) else { throw Error.invalidHeicQuality } + + let destData = NSMutableData() + guard + let dest = CGImageDestinationCreateWithData( + destData, + UTType.heic.identifier as CFString, + tileSizes.count, + nil + ) + else { + throw Error.heicDestinationCreationFailed + } + + // Attach Genmoji metadata + let meta = CGImageMetadataCreateMutable() + CGImageMetadataSetValueWithPath( + meta, + nil, + "tiff:\(kCGImagePropertyTIFFDocumentName)" as CFString, + id as CFString + ) + CGImageMetadataSetValueWithPath( + meta, + nil, + "dc:description" as CFString, + description as CFString + ) + + for (idx, side) in tileSizes.enumerated() { + if Task.isCancelled { throw CancellationError() } + guard let img = cg.scaled(to: side) else { + throw Error.imageScaleFailed + } + let opts = + [kCGImageDestinationLossyCompressionQuality: quality] + as CFDictionary + if idx == 0 { + CGImageDestinationAddImageAndMetadata(dest, img, meta, opts) + } else { + CGImageDestinationAddImage(dest, img, opts) + } + } + + guard CGImageDestinationFinalize(dest) else { + throw Error.heicFinalizeFailed + } + return destData as Data + } +} + +// MARK: - CGImage Helpers +extension CGImage { + /// Returns a copy whose longer edge equals `side` pixels. *Assumes the input is already square.* + fileprivate func scaled(to side: Int) -> CGImage? { + guard width != side else { return self } + guard let cs = CGColorSpace(name: CGColorSpace.sRGB) else { return nil } + + let hasAlpha: Bool = { + switch alphaInfo { + case .none, .noneSkipFirst, .noneSkipLast: return false + default: return true + } + }() + let bitmapInfo: UInt32 = + hasAlpha + ? CGImageAlphaInfo.premultipliedLast.rawValue + : CGImageAlphaInfo.noneSkipLast.rawValue + + guard + let ctx = CGContext( + data: nil, + width: side, + height: side, + bitsPerComponent: 8, + bytesPerRow: 0, + space: cs, + bitmapInfo: bitmapInfo + ) + else { return nil } + + ctx.interpolationQuality = .high + ctx.draw(self, in: CGRect(x: 0, y: 0, width: side, height: side)) + return ctx.makeImage() + } +} + +// MARK: - Image Extraction Helpers +extension Customoji { + fileprivate static func extractCGImage(from image: CMJImage) throws + -> CGImage + { + #if canImport(UIKit) + if let cg = (image as UIImage).cgImage { return cg } + + var rendered: CGImage? + let work = { rendered = renderCGImage(image as! UIImage) } + if Thread.isMainThread { + work() + } else { + DispatchQueue.main.sync(execute: work) + } + if let cg = rendered { return cg } + #elseif canImport(AppKit) + var rect = CGRect(origin: .zero, size: image.size) + if let cg = (image as NSImage).cgImage( + forProposedRect: &rect, + context: nil, + hints: nil + ) { + return cg + } + if let tiff = (image as NSImage).tiffRepresentation, + let rep = NSBitmapImageRep(data: tiff), let cg = rep.cgImage + { + return cg + } + #endif + throw Error.cgImageUnavailable + } + + #if canImport(UIKit) + private static func renderCGImage(_ image: UIImage) -> CGImage? { + precondition(Thread.isMainThread, "Must be on main thread") + let fmt = UIGraphicsImageRendererFormat() + fmt.scale = image.scale == 0 ? 1 : image.scale + fmt.opaque = false + return UIGraphicsImageRenderer(size: image.size, format: fmt).image + { _ in image.draw(at: .zero) }.cgImage + } + #endif +} + +// MARK: - Square Enforcement +extension Customoji { + fileprivate static func ensureSquare(_ cg: CGImage, cropIfNeeded: Bool) + throws -> CGImage + { + guard cg.width == cg.height else { + guard cropIfNeeded else { throw Error.nonSquare } + + let side = min(cg.width, cg.height) + let rect = CGRect( + x: (cg.width - side) / 2, + y: (cg.height - side) / 2, + width: side, + height: side + ) + + if let cropped = cg.cropping(to: rect) { return cropped } + if let scaled = cg.scaled(to: side) { return scaled } + throw Error.squareCropFailed + } + return cg + } +} + +// MARK: - Tile Size Validation +extension Customoji { + fileprivate static func validatedTileSizes(_ sizes: [Int], max: Int) throws + -> [Int] + { + guard !sizes.isEmpty else { throw Error.invalidTileSizes } + for (prev, curr) in zip(sizes, sizes.dropFirst()) where curr <= prev { + throw Error.invalidTileSizes + } + guard sizes.allSatisfy({ $0 > 0 && $0 <= max }) else { + throw Error.invalidTileSizes + } + return sizes + } +} + +extension NotificationContent { + var forceIsEmpty: Bool { + if self.sgStatus.status > 1 && !self.isEmpty { + if self.isPinned { + var desiredAction = PINNED_MESSAGE_ACTION + if let chatId = chatId, let exceptionAction = PINNED_MESSAGE_ACTION_EXCEPTIONS["\(chatId)"] { + desiredAction = exceptionAction + } + if desiredAction == "disabled" { + return true + } + } + if self.isMentionOrReply { + var desiredAction = MENTION_AND_REPLY_ACTION + if let chatId = chatId, let exceptionAction = MENTION_AND_REPLY_ACTION_EXCEPTIONS["\(chatId)"] { + desiredAction = exceptionAction + } + if desiredAction == "disabled" { + return true + } + } + } + return false + } + var forceIsSilent: Bool { + if self.sgStatus.status > 1 && !self.silent { + if self.isPinned { + var desiredAction = PINNED_MESSAGE_ACTION + if let chatId = chatId, let exceptionAction = PINNED_MESSAGE_ACTION_EXCEPTIONS["\(chatId)"] { + desiredAction = exceptionAction + } + if desiredAction == "silenced" { + return true + } + } + if self.isMentionOrReply { + var desiredAction = MENTION_AND_REPLY_ACTION + if let chatId = chatId, let exceptionAction = MENTION_AND_REPLY_ACTION_EXCEPTIONS["\(chatId)"] { + desiredAction = exceptionAction + } + if desiredAction == "silenced" { + return true + } + } + } + return false + } +} diff --git a/submodules/AccountContext/BUILD b/submodules/AccountContext/BUILD index acd19b9f..b984ce77 100644 --- a/submodules/AccountContext/BUILD +++ b/submodules/AccountContext/BUILD @@ -1,5 +1,11 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//Swiftgram/SGIAP:SGIAP", + "//Swiftgram/SGStatus:SGStatus", +] + swift_library( name = "AccountContext", module_name = "AccountContext", @@ -9,7 +15,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/TelegramAudio:TelegramAudio", "//submodules/AsyncDisplayKit:AsyncDisplayKit", "//submodules/TemporaryCachedPeerDataManager:TemporaryCachedPeerDataManager", diff --git a/submodules/AccountContext/Sources/AccountContext.swift b/submodules/AccountContext/Sources/AccountContext.swift index 608bd418..dc45caa0 100644 --- a/submodules/AccountContext/Sources/AccountContext.swift +++ b/submodules/AccountContext/Sources/AccountContext.swift @@ -1,3 +1,6 @@ +import SGSimpleSettings +import SGIAP +import SGStatus import Foundation import UIKit import AsyncDisplayKit @@ -185,16 +188,6 @@ public enum WallpaperUrlParameter { case gradient([UInt32], Int32?) } -public enum ResolvedUrlSettingsSection { - case theme - case devices - case autoremoveMessages - case twoStepAuth - case enableLog - case phonePrivacy - case loginEmail -} - public struct ResolvedBotChoosePeerTypes: OptionSet { public var rawValue: UInt32 @@ -315,19 +308,17 @@ public enum ResolvedUrl { case share(url: String?, text: String?, to: String?) case wallpaper(WallpaperUrlParameter) case theme(String) - case settings(ResolvedUrlSettingsSection) case joinVoiceChat(PeerId, String?) case importStickers case startAttach(peerId: PeerId, payload: String?, choose: ResolvedBotChoosePeerTypes?) case invoice(slug: String, invoice: TelegramMediaInvoice?) case premiumOffer(reference: String?) - case starsTopup(amount: Int64, purpose: String?) + case starsTopup(amount: Int64?, purpose: String?) case chatFolder(slug: String) case story(peerId: PeerId, id: Int32) case boost(peerId: PeerId?, status: ChannelBoostStatus?, myBoostStatus: MyBoostStatus?) case premiumGiftCode(slug: String) case premiumMultiGift(reference: String?) - case collectible(gift: StarGift.UniqueGift?) case auction(auction: GiftAuctionContext?) case messageLink(link: TelegramResolvedMessageLink?) case stars @@ -336,6 +327,60 @@ public enum ResolvedUrl { case storyFolder(peerId: PeerId, id: Int64) case giftCollection(peerId: PeerId, id: Int64) case sendGift(peerId: PeerId?) + case unknownDeepLink(path: String) + case oauth(url: String) + + public enum ResolvedCollectible { + case gift(StarGift.UniqueGift) + case invalidSlug + case alreadyBurned + } + case collectible(ResolvedCollectible) + + public enum ChatsSection { + case search + case edit + case emojiStatus + } + case chats(ChatsSection?) + + public enum ComposeSection { + case group + case channel + case contact + } + case compose(ComposeSection?) + + public enum PostStorySection { + case photo + case video + case live + } + case postStory(PostStorySection?) + + public enum ContactsSection { + case search + case sort + case new + case invite + case manage + } + case contacts(ContactsSection?) + + public enum SettingsSection { + public enum Legacy { + case theme + case devices + case autoremoveMessages + case enableLog + case phonePrivacy + case loginEmail + } + + case legacy(Legacy) + case path(String) + } + case settings(SettingsSection) } public enum ResolveUrlResult { @@ -696,6 +741,11 @@ public enum DeviceContactInfoSubject { } public enum PeerInfoControllerMode { + public enum PeerInfoMediaKind { + case photoVideo + case file + } + case generic case calls(messages: [Message]) case nearbyPeer(distance: Int32) @@ -711,6 +761,7 @@ public enum PeerInfoControllerMode { case monoforum(EnginePeer.Id) case storyAlbum(id: Int64) case giftCollection(id: Int64) + case media(kind: PeerInfoMediaKind, messageIndex: EngineMessage.Index) } public enum ContactListActionItemInlineIconPosition { @@ -972,18 +1023,32 @@ public protocol MediaEditorScreenResult { var target: Stories.PendingTarget { get } } +public enum StoryCameraMode { + case photo + case video + case live +} + public protocol TelegramRootControllerInterface: NavigationController { + var accountSettingsController: PeerInfoScreen? { get set } + @discardableResult - func openStoryCamera(customTarget: Stories.PendingTarget?, resumeLiveStream: Bool, transitionIn: StoryCameraTransitionIn?, transitionedIn: @escaping () -> Void, transitionOut: @escaping (Stories.PendingTarget?, Bool) -> StoryCameraTransitionOut?) -> StoryCameraTransitionInCoordinator? + func openStoryCamera(mode: StoryCameraMode, customTarget: Stories.PendingTarget?, resumeLiveStream: Bool, transitionIn: StoryCameraTransitionIn?, transitionedIn: @escaping () -> Void, transitionOut: @escaping (Stories.PendingTarget?, Bool) -> StoryCameraTransitionOut?) -> StoryCameraTransitionInCoordinator? func proceedWithStoryUpload(target: Stories.PendingTarget, results: [MediaEditorScreenResult], existingMedia: EngineMedia?, forwardInfo: Stories.PendingForwardInfo?, externalState: MediaEditorTransitionOutExternalState, commit: @escaping (@escaping () -> Void) -> Void) func getContactsController() -> ViewController? func getChatsController() -> ViewController? + func getSettingsController() -> ViewController? + func getPrivacySettings() -> Promise? - func openSettings() + func getTwoStepAuthData() -> Promise? + + func openContacts() + func openSettings(edit: Bool) func openBirthdaySetup() func openPhotoSetup(completedWithUploadingImage: @escaping (UIImage, Signal) -> UIView?) func openAvatars() + func startNewCall() } public protocol QuickReplySetupScreenInitialData: AnyObject { @@ -1185,6 +1250,7 @@ public enum ChannelMembersSearchControllerMode { case promote case ban case inviteToCall + case ownershipTransfer } public enum ChannelMembersSearchFilter { @@ -1241,10 +1307,18 @@ public protocol SharedAccountContext: AnyObject { var automaticMediaDownloadSettings: Signal { get } var currentAutodownloadSettings: Atomic { get } var immediateExperimentalUISettings: ExperimentalUISettings { get } + // MARK: Swiftgram + var immediateSGStatus: SGStatus { get } + var SGIAP: SGIAPManager? { get } + func makeSGProController(context: AccountContext) -> ViewController + func makeSGPayWallController(context: AccountContext) -> ViewController? + func makeSGUpdateIOSController() -> ViewController + var currentInAppNotificationSettings: Atomic { get } var currentMediaInputSettings: Atomic { get } var currentStickerSettings: Atomic { get } var currentMediaDisplaySettings: Atomic { get } + var currentChatSettings: Atomic { get } var energyUsageSettings: EnergyUsageSettings { get } @@ -1404,14 +1478,15 @@ public protocol SharedAccountContext: AnyObject { func makeGiftViewScreen(context: AccountContext, message: EngineMessage, shareStory: ((StarGift.UniqueGift) -> Void)?) -> ViewController func makeGiftViewScreen(context: AccountContext, gift: StarGift.UniqueGift, shareStory: ((StarGift.UniqueGift) -> Void)?, openChatTheme: (() -> Void)?, dismissed: (() -> Void)?) -> ViewController func makeGiftWearPreviewScreen(context: AccountContext, gift: StarGift, attributes: [StarGift.UniqueGift.Attribute]?) -> ViewController - func makeGiftUpgradePreviewScreen(context: AccountContext, attributes: [StarGift.UniqueGift.Attribute], peerName: String) -> ViewController + func makeGiftUpgradePreviewScreen(context: AccountContext, gift: StarGift.Gift, attributes: [StarGift.UniqueGift.Attribute], peerName: String) -> ViewController func makeGiftAuctionInfoScreen(context: AccountContext, auctionContext: GiftAuctionContext, completion: (() -> Void)?) -> ViewController func makeGiftAuctionBidScreen(context: AccountContext, toPeerId: EnginePeer.Id, text: String?, entities: [MessageTextEntity]?, hideName: Bool, auctionContext: GiftAuctionContext, acquiredGifts: Signal<[GiftAuctionAcquiredGift], NoError>?) -> ViewController func makeGiftAuctionViewScreen(context: AccountContext, auctionContext: GiftAuctionContext, peerId: EnginePeer.Id?, completion: @escaping (Signal<[GiftAuctionAcquiredGift], NoError>, [StarGift.UniqueGift.Attribute]?) -> Void) -> ViewController func makeGiftAuctionActiveBidsScreen(context: AccountContext) -> ViewController func makeGiftOfferScreen(context: AccountContext, updatedPresentationData: (initial: PresentationData, signal: Signal)?, gift: StarGift.UniqueGift, peer: EnginePeer, amount: CurrencyAmount, commit: @escaping () -> Void) -> ViewController - func makeGiftUpgradeVariantsScreen(context: AccountContext, gift: StarGift, attributes: [StarGift.UniqueGift.Attribute], selectedAttributes: [StarGift.UniqueGift.Attribute]?, focusedAttribute: StarGift.UniqueGift.Attribute?) -> ViewController + func makeGiftUpgradeVariantsScreen(context: AccountContext, gift: StarGift, crafted: Bool, attributes: [StarGift.UniqueGift.Attribute], selectedAttributes: [StarGift.UniqueGift.Attribute]?, focusedAttribute: StarGift.UniqueGift.Attribute?) -> ViewController func makeGiftAuctionWearPreviewScreen(context: AccountContext, auctionContext: GiftAuctionContext, acquiredGifts: Signal<[GiftAuctionAcquiredGift], NoError>?, attributes: [StarGift.UniqueGift.Attribute], completion: @escaping () -> Void) -> ViewController + func makeGiftCraftScreen(context: AccountContext, gift: StarGift.UniqueGift, profileGiftsContext: ProfileGiftsContext?) -> ViewController func makeGiftDemoScreen(context: AccountContext) -> ViewController func makeStorySharingScreen(context: AccountContext, subject: StorySharingSubject, parentController: ViewController) -> ViewController func makeContentReportScreen(context: AccountContext, subject: ReportContentSubject, forceDark: Bool, present: @escaping (ViewController) -> Void, completion: @escaping () -> Void, requestSelectMessages: ((String, Data, String?) -> Void)?) @@ -1526,6 +1601,7 @@ public protocol AccountContext: AnyObject { var downloadedMediaStoreManager: DownloadedMediaStoreManager { get } var peerChannelMemberCategoriesContextsManager: PeerChannelMemberCategoriesContextsManager { get } var wallpaperUploadManager: WallpaperUploadManager? { get } + var watchManager: WatchManager? { get } var inAppPurchaseManager: InAppPurchaseManager? { get } var starsContext: StarsContext? { get } var tonContext: StarsContext? { get } diff --git a/submodules/AccountContext/Sources/ChatController.swift b/submodules/AccountContext/Sources/ChatController.swift index e499fc07..a848d969 100644 --- a/submodules/AccountContext/Sources/ChatController.swift +++ b/submodules/AccountContext/Sources/ChatController.swift @@ -55,6 +55,7 @@ public final class ChatMessageItemAssociatedData: Equatable { public let accountPeer: EnginePeer? public let topicAuthorId: EnginePeer.Id? public let hasBots: Bool + public let translationSettings: TranslationSettings? public let translateToLanguage: String? public let maxReadStoryId: Int32? public let recommendedChannels: RecommendedChannels? @@ -91,6 +92,7 @@ public final class ChatMessageItemAssociatedData: Equatable { alwaysDisplayTranscribeButton: DisplayTranscribeButton = DisplayTranscribeButton(canBeDisplayed: false, displayForNotConsumed: false, providedByGroupBoost: false), topicAuthorId: EnginePeer.Id? = nil, hasBots: Bool = false, + translationSettings: TranslationSettings? = nil, translateToLanguage: String? = nil, maxReadStoryId: Int32? = nil, recommendedChannels: RecommendedChannels? = nil, @@ -126,6 +128,7 @@ public final class ChatMessageItemAssociatedData: Equatable { self.topicAuthorId = topicAuthorId self.alwaysDisplayTranscribeButton = alwaysDisplayTranscribeButton self.hasBots = hasBots + self.translationSettings = translationSettings self.translateToLanguage = translateToLanguage self.maxReadStoryId = maxReadStoryId self.recommendedChannels = recommendedChannels @@ -202,6 +205,9 @@ public final class ChatMessageItemAssociatedData: Equatable { if lhs.hasBots != rhs.hasBots { return false } + if lhs.translationSettings != rhs.translationSettings { + return false + } if lhs.translateToLanguage != rhs.translateToLanguage { return false } @@ -237,6 +243,10 @@ public final class ChatMessageItemAssociatedData: Equatable { } public extension ChatMessageItemAssociatedData { + var translateToLanguageSG: String? { + return self.translateToLanguage + } + var isInPinnedListMode: Bool { if case .pinnedMessages = self.subject { return true @@ -976,7 +986,9 @@ public enum PeerInfoAvatarUploadStatus { public protocol PeerInfoScreen: ViewController { var peerId: PeerId { get } var privacySettings: Promise { get } + var twoStepAuthData: Promise { get } + func activateEdit() func openBirthdaySetup() func toggleStorySelection(ids: [Int32], isSelected: Bool) func togglePaneIsReordering(isReordering: Bool) @@ -1093,6 +1105,12 @@ public protocol ChatController: ViewController { func restrictedSendingContentsText() -> String } +public extension ChatController { + var overlayTitle: String? { + return self.title + } +} + public protocol ChatMessagePreviewItemNode: AnyObject { var forwardInfoReferenceNode: ASDisplayNode? { get } } diff --git a/submodules/AccountContext/Sources/PeerNameColors.swift b/submodules/AccountContext/Sources/PeerNameColors.swift index 63c13124..497546e9 100644 --- a/submodules/AccountContext/Sources/PeerNameColors.swift +++ b/submodules/AccountContext/Sources/PeerNameColors.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import TelegramCore @@ -7,16 +8,16 @@ private extension PeerNameColors.Colors { if colors.colors.isEmpty { return nil } - self.main = UIColor(rgb: colors.colors[0]) + self._main = UIColor(rgb: colors.colors[0]) if colors.colors.count > 1 { - self.secondary = UIColor(rgb: colors.colors[1]) + self._secondary = UIColor(rgb: colors.colors[1]) } else { - self.secondary = nil + self._secondary = nil } if colors.colors.count > 2 { - self.tertiary = UIColor(rgb: colors.colors[2]) + self._tertiary = UIColor(rgb: colors.colors[2]) } else { - self.tertiary = nil + self._tertiary = nil } } } @@ -29,39 +30,67 @@ public class PeerNameColors: Equatable { } public struct Colors: Equatable { - public let main: UIColor - public let secondary: UIColor? - public let tertiary: UIColor? + private let _main: UIColor + private let _secondary: UIColor? + private let _tertiary: UIColor? + // MARK: Swiftgram + public var main: UIColor { + let currentSaturation = SGSimpleSettings.shared.accountColorsSaturation + if currentSaturation == 0 { + return _main + } else { + return _main.withReducedSaturation(CGFloat(currentSaturation) / 100.0) + } + } + + public var secondary: UIColor? { + let currentSaturation = SGSimpleSettings.shared.accountColorsSaturation + if currentSaturation == 0 { + return _secondary + } else { + return _secondary?.withReducedSaturation(CGFloat(currentSaturation) / 100.0) + } + } + + public var tertiary: UIColor? { + let currentSaturation = SGSimpleSettings.shared.accountColorsSaturation + if currentSaturation == 0 { + return _tertiary + } else { + return _tertiary?.withReducedSaturation(CGFloat(currentSaturation) / 100.0) + } + } public init(main: UIColor, secondary: UIColor?, tertiary: UIColor?) { - self.main = main - self.secondary = secondary - self.tertiary = tertiary + self._main = main + self._secondary = secondary + self._tertiary = tertiary } public init(main: UIColor) { - self.main = main - self.secondary = nil - self.tertiary = nil + self._main = main + self._secondary = nil + self._tertiary = nil } public init?(colors: [UIColor]) { guard let first = colors.first else { return nil } - self.main = first + self._main = first if colors.count == 3 { - self.secondary = colors[1] - self.tertiary = colors[2] + self._secondary = colors[1] + self._tertiary = colors[2] } else if colors.count == 2, let second = colors.last { - self.secondary = second - self.tertiary = nil + self._secondary = second + self._tertiary = nil } else { - self.secondary = nil - self.tertiary = nil + self._secondary = nil + self._tertiary = nil } } } + public static var defaultSingleColors: [Int32: Colors] { return [ @@ -361,3 +390,20 @@ public extension PeerCollectibleColor { } } } + +// MARK: Swiftgram +extension UIColor { + func withReducedSaturation(_ factor: CGFloat) -> UIColor { + var hue: CGFloat = 0 + var saturation: CGFloat = 0 + var brightness: CGFloat = 0 + var alpha: CGFloat = 0 + + if self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { + let newSaturation = max(0, min(1, saturation * factor)) + return UIColor(hue: hue, saturation: newSaturation, brightness: brightness, alpha: alpha) + } + + return self + } +} \ No newline at end of file diff --git a/submodules/AccountContext/Sources/PeerSelectionController.swift b/submodules/AccountContext/Sources/PeerSelectionController.swift index 9d2f520c..7085deed 100644 --- a/submodules/AccountContext/Sources/PeerSelectionController.swift +++ b/submodules/AccountContext/Sources/PeerSelectionController.swift @@ -62,6 +62,7 @@ public final class PeerSelectionControllerParams { public let multipleSelection: Bool public let multipleSelectionLimit: Int32? public let forwardedMessageIds: [EngineMessage.Id] + public let initialForwardOptionsState: ChatInterfaceForwardOptionsState? public let hasTypeHeaders: Bool public let selectForumThreads: Bool public let hasCreation: Bool @@ -84,6 +85,7 @@ public final class PeerSelectionControllerParams { multipleSelection: Bool = false, multipleSelectionLimit: Int32? = nil, forwardedMessageIds: [EngineMessage.Id] = [], + initialForwardOptionsState: ChatInterfaceForwardOptionsState? = nil, hasTypeHeaders: Bool = false, selectForumThreads: Bool = false, hasCreation: Bool = false, @@ -105,6 +107,7 @@ public final class PeerSelectionControllerParams { self.multipleSelection = multipleSelection self.multipleSelectionLimit = multipleSelectionLimit self.forwardedMessageIds = forwardedMessageIds + self.initialForwardOptionsState = initialForwardOptionsState self.hasTypeHeaders = hasTypeHeaders self.selectForumThreads = selectForumThreads self.hasCreation = hasCreation diff --git a/submodules/AccountContext/Sources/WatchManager.swift b/submodules/AccountContext/Sources/WatchManager.swift new file mode 100644 index 00000000..ce2e97c3 --- /dev/null +++ b/submodules/AccountContext/Sources/WatchManager.swift @@ -0,0 +1,23 @@ +import Foundation +import SwiftSignalKit +import TelegramCore + +public struct WatchRunningTasks: Equatable { + public let running: Bool + public let version: Int32 + + public init(running: Bool, version: Int32) { + self.running = running + self.version = version + } + + public static func ==(lhs: WatchRunningTasks, rhs: WatchRunningTasks) -> Bool { + return lhs.running == rhs.running && lhs.version == rhs.version + } +} + +public protocol WatchManager: AnyObject { + var watchAppInstalled: Signal { get } + var navigateToMessageRequested: Signal { get } + var runningTasks: Signal { get } +} diff --git a/submodules/AccountUtils/Sources/AccountUtils.swift b/submodules/AccountUtils/Sources/AccountUtils.swift index aa4f12eb..a12f1fad 100644 --- a/submodules/AccountUtils/Sources/AccountUtils.swift +++ b/submodules/AccountUtils/Sources/AccountUtils.swift @@ -4,9 +4,11 @@ import TelegramCore import TelegramUIPreferences import AccountContext -// GHOSTGRAM: Unlimited accounts bypass - always allow up to 10 accounts -public let maximumNumberOfAccounts = 10 -public let maximumPremiumNumberOfAccounts = 10 +// MARK: Swiftgram compatibility +public let maximumSwiftgramNumberOfAccounts = 500 +public let maximumSafeNumberOfAccounts = 6 +public let maximumNumberOfAccounts = maximumSwiftgramNumberOfAccounts +public let maximumPremiumNumberOfAccounts = maximumSwiftgramNumberOfAccounts public func activeAccountsAndPeers(context: AccountContext, includePrimary: Bool = false) -> Signal<((AccountContext, EnginePeer)?, [(AccountContext, EnginePeer, Int32)]), NoError> { let sharedContext = context.sharedContext diff --git a/submodules/AttachmentTextInputPanelNode/BUILD b/submodules/AttachmentTextInputPanelNode/BUILD index 25e0d545..179d1b32 100644 --- a/submodules/AttachmentTextInputPanelNode/BUILD +++ b/submodules/AttachmentTextInputPanelNode/BUILD @@ -1,5 +1,10 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgDeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//Swiftgram/SGInputToolbar:SGInputToolbar" +] + swift_library( name = "AttachmentTextInputPanelNode", module_name = "AttachmentTextInputPanelNode", @@ -9,7 +14,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgDeps + [ "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", "//submodules/AsyncDisplayKit:AsyncDisplayKit", "//submodules/Display:Display", diff --git a/submodules/AttachmentTextInputPanelNode/Sources/AttachmentTextInputPanelNode.swift b/submodules/AttachmentTextInputPanelNode/Sources/AttachmentTextInputPanelNode.swift index f74fde40..63bdce47 100644 --- a/submodules/AttachmentTextInputPanelNode/Sources/AttachmentTextInputPanelNode.swift +++ b/submodules/AttachmentTextInputPanelNode/Sources/AttachmentTextInputPanelNode.swift @@ -1,3 +1,8 @@ +// MARK: Swiftgram +import SGInputToolbar +import SwiftUI +import SGSimpleSettings + import Foundation import UIKit import Display @@ -301,6 +306,10 @@ public class AttachmentTextInputPanelNode: ASDisplayNode, TGCaptionPanelView, AS private let hapticFeedback = HapticFeedback() + // MARK: Swiftgram + // private var toolbarHostingController: UIViewController? //Any? // UIHostingController? + private var toolbarNode: ASDisplayNode? + public var inputTextState: ChatTextInputState { if let textInputNode = self.textInputNode { let selectionRange: Range = textInputNode.selectedRange.location ..< (textInputNode.selectedRange.location + textInputNode.selectedRange.length) @@ -520,6 +529,9 @@ public class AttachmentTextInputPanelNode: ASDisplayNode, TGCaptionPanelView, AS self?.maxCaptionLength = maxCaptionLength }) } + + // MARK: Swiftgram + self.initToolbarIfNeeded(context: context) } public var sendPressed: ((NSAttributedString?) -> Void)? @@ -646,6 +658,7 @@ public class AttachmentTextInputPanelNode: ASDisplayNode, TGCaptionPanelView, AS textInputNode.view.addGestureRecognizer(recognizer) textInputNode.textView.accessibilityHint = self.textPlaceholderNode.attributedText?.string + self.initToolbarIfNeeded(context: self.context) } private func textFieldMaxHeight(_ maxHeight: CGFloat, metrics: LayoutMetrics) -> CGFloat { @@ -966,7 +979,11 @@ public class AttachmentTextInputPanelNode: ASDisplayNode, TGCaptionPanelView, AS panelHeight += 11.0 } - return panelHeight + // MARK: Swiftgram + var toolbarOffset: CGFloat = 0.0 + toolbarOffset = layoutToolbar(transition: transition, panelHeight: panelHeight, width: width, leftInset: leftInset, rightInset: rightInset) + + return panelHeight + toolbarOffset } private func updateFieldAndButtonsLayout(inputHasText: Bool, panelHeight: CGFloat, transition: ContainedViewLayoutTransition) -> CGFloat { @@ -1490,6 +1507,10 @@ public class AttachmentTextInputPanelNode: ASDisplayNode, TGCaptionPanelView, AS } public func chatInputTextNodeShouldReturn() -> Bool { + return self.chatInputTextNodeShouldReturn(modifierFlags: []) + } + + public func chatInputTextNodeShouldReturn(modifierFlags: UIKeyModifierFlags) -> Bool { if self.actionButtons.sendButton.supernode != nil && !self.actionButtons.sendButton.isHidden && !self.actionButtons.sendButton.alpha.isZero { self.sendButtonPressed() } @@ -1497,7 +1518,7 @@ public class AttachmentTextInputPanelNode: ASDisplayNode, TGCaptionPanelView, AS } @objc public func editableTextNodeShouldReturn(_ editableTextNode: ASEditableTextNode) -> Bool { - return self.chatInputTextNodeShouldReturn() + return self.chatInputTextNodeShouldReturn(modifierFlags: []) } private func applyUpdateSendButtonIcon() { @@ -1965,3 +1986,99 @@ public class AttachmentTextInputPanelNode: ASDisplayNode, TGCaptionPanelView, AS return nil } } + +// MARK: Swiftgram +extension AttachmentTextInputPanelNode { + + func initToolbarIfNeeded(context: AccountContext) { + guard #available(iOS 13.0, *) else { return } + guard SGSimpleSettings.shared.inputToolbar else { return } + guard context.sharedContext.immediateSGStatus.status > 1 else { return } + guard self.toolbarNode == nil else { return } + let toolbarView = ChatToolbarView( + onQuote: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesQuote(strongSelf) + }, + onSpoiler: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesSpoiler(strongSelf) + }, + onBold: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesBold(strongSelf) + }, + onItalic: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesItalic(strongSelf) + }, + onMonospace: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesMonospace(strongSelf) + }, + onLink: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesLink(self!) + }, + onStrikethrough: { [weak self] + in guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesStrikethrough(strongSelf) + }, + onUnderline: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesUnderline(strongSelf) + }, + onCode: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesCodeBlock(strongSelf) + }, + onNewLine: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSetNewLine() + }, + // TODO(swiftgram): Binding + showNewLine: .constant(true), //.constant(self.sendWithReturnKey) + onClearFormatting: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.updateTextInputStateAndMode { current, inputMode in + return (chatTextInputClearFormattingAttributes(current), inputMode) + } + } + ) + let toolbarHostingController = UIHostingController(rootView: toolbarView) + toolbarHostingController.view.backgroundColor = UIColor.clear + let toolbarNode = ASDisplayNode { toolbarHostingController.view } + self.toolbarNode = toolbarNode + // assigning toolbarHostingController bugs responsivness and overrides layout + // self.toolbarHostingController = toolbarHostingController + + // Disable "Swipe to go back" gesture when touching scrollview + self.view.interactiveTransitionGestureRecognizerTest = { [weak self] point in + if let self, let _ = self.toolbarNode?.view.hitTest(point, with: nil) { + return false + } + return true + } + self.addSubnode(toolbarNode) + } + + func layoutToolbar(transition: ContainedViewLayoutTransition, panelHeight: CGFloat, width: CGFloat, leftInset: CGFloat, rightInset: CGFloat) -> CGFloat { + var toolbarHeight: CGFloat = 0.0 + var toolbarSpacing: CGFloat = 0.0 + if let toolbarNode = self.toolbarNode { + toolbarHeight = 44.0 + toolbarSpacing = 1.0 + transition.updateFrame(node: toolbarNode, frame: CGRect(origin: CGPoint(x: leftInset, y: panelHeight + toolbarSpacing), size: CGSize(width: width - rightInset - leftInset, height: toolbarHeight))) + } + return toolbarHeight + toolbarSpacing + } +} diff --git a/submodules/AttachmentUI/Sources/AttachmentPanel.swift b/submodules/AttachmentUI/Sources/AttachmentPanel.swift index d0f87723..dfe08c77 100644 --- a/submodules/AttachmentUI/Sources/AttachmentPanel.swift +++ b/submodules/AttachmentUI/Sources/AttachmentPanel.swift @@ -983,7 +983,7 @@ final class AttachmentPanel: ASDisplayNode, ASScrollViewDelegate, ASGestureRecog self.makeEntityInputView = makeEntityInputView - self.presentationInterfaceState = ChatPresentationInterfaceState(chatWallpaper: .builtin(WallpaperSettings()), theme: self.presentationData.theme, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, limitsConfiguration: self.context.currentLimitsConfiguration.with { $0 }, fontSize: self.presentationData.chatFontSize, bubbleCorners: self.presentationData.chatBubbleCorners, accountPeerId: self.context.account.peerId, mode: .standard(.default), chatLocation: chatLocation ?? .peer(id: context.account.peerId), subject: nil, peerNearbyData: nil, greetingData: nil, pendingUnpinnedAllMessages: false, activeGroupCallInfo: nil, hasActiveGroupCall: false, threadData: nil, isGeneralThreadClosed: nil, replyMessage: nil, accountPeerColor: nil, businessIntro: nil) + self.presentationInterfaceState = ChatPresentationInterfaceState(chatWallpaper: .builtin(WallpaperSettings()), theme: self.presentationData.theme, preferredGlassType: .default, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, limitsConfiguration: self.context.currentLimitsConfiguration.with { $0 }, fontSize: self.presentationData.chatFontSize, bubbleCorners: self.presentationData.chatBubbleCorners, accountPeerId: self.context.account.peerId, mode: .standard(.default), chatLocation: chatLocation ?? .peer(id: context.account.peerId), subject: nil, peerNearbyData: nil, greetingData: nil, pendingUnpinnedAllMessages: false, activeGroupCallInfo: nil, hasActiveGroupCall: false, threadData: nil, isGeneralThreadClosed: nil, replyMessage: nil, accountPeerColor: nil, businessIntro: nil) self.containerNode = ASDisplayNode() self.containerNode.clipsToBounds = false @@ -1029,9 +1029,9 @@ final class AttachmentPanel: ASDisplayNode, ASScrollViewDelegate, ASGestureRecog }, blockMessageAuthor: { _, _ in }, deleteMessages: { _, _, f in f(.default) - }, forwardSelectedMessages: { + }, forwardSelectedMessages: { _ in }, forwardCurrentForwardMessages: { - }, forwardMessages: { _ in + }, forwardMessages: { _, _ in }, updateForwardOptionsState: { [weak self] value in if let strongSelf = self { strongSelf.updateChatPresentationInterfaceState(animated: true, { $0.updatedInterfaceState({ $0.withUpdatedForwardOptionsState($0.forwardOptionsState) }) }) diff --git a/submodules/BuildConfig/PublicHeaders/BuildConfig/BuildConfig.h b/submodules/BuildConfig/PublicHeaders/BuildConfig/BuildConfig.h index 9ff7cf8e..1e098670 100644 --- a/submodules/BuildConfig/PublicHeaders/BuildConfig/BuildConfig.h +++ b/submodules/BuildConfig/PublicHeaders/BuildConfig/BuildConfig.h @@ -12,6 +12,7 @@ - (instancetype _Nonnull)initWithBaseAppBundleId:(NSString * _Nonnull)baseAppBundleId; @property (nonatomic, strong, readonly) NSString * _Nullable appCenterId; +@property (nonatomic, strong, readonly) NSString * _Nonnull sgConfig; @property (nonatomic, readonly) int32_t apiId; @property (nonatomic, strong, readonly) NSString * _Nonnull apiHash; @property (nonatomic, readonly) bool isInternalBuild; diff --git a/submodules/BuildConfig/Sources/BuildConfig.m b/submodules/BuildConfig/Sources/BuildConfig.m index a4f25b28..61d1ff15 100644 --- a/submodules/BuildConfig/Sources/BuildConfig.m +++ b/submodules/BuildConfig/Sources/BuildConfig.m @@ -1,5 +1,9 @@ #import +#ifndef APP_SG_CONFIG +#define APP_SG_CONFIG "" +#endif + static NSString *telegramApplicationSecretKey = @"telegramApplicationSecretKey_v3"; API_AVAILABLE(ios(10)) @interface LocalPrivateKey : NSObject { @@ -70,6 +74,7 @@ API_AVAILABLE(ios(10)) @interface BuildConfig () { NSData * _Nullable _bundleData; + NSString * _Nonnull _sgConfig; int32_t _apiId; NSString * _Nonnull _apiHash; NSString * _Nullable _appCenterId; @@ -127,6 +132,7 @@ API_AVAILABLE(ios(10)) - (instancetype _Nonnull)initWithBaseAppBundleId:(NSString * _Nonnull)baseAppBundleId { self = [super init]; if (self != nil) { + _sgConfig = @(APP_SG_CONFIG); _apiId = APP_CONFIG_API_ID; _apiHash = @(APP_CONFIG_API_HASH); _appCenterId = @(APP_CONFIG_APP_CENTER_ID); diff --git a/submodules/Camera/BUILD b/submodules/Camera/BUILD index cc549950..73567ab8 100644 --- a/submodules/Camera/BUILD +++ b/submodules/Camera/BUILD @@ -8,6 +8,10 @@ load("//build-system/bazel-utils:plist_fragment.bzl", "plist_fragment", ) +sgDeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + filegroup( name = "CameraMetalResources", srcs = glob([ @@ -52,7 +56,7 @@ swift_library( data = [ ":CameraBundle", ], - deps = [ + deps = sgDeps + [ "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", "//submodules/AsyncDisplayKit:AsyncDisplayKit", "//submodules/Display:Display", diff --git a/submodules/Camera/Sources/CameraOutput.swift b/submodules/Camera/Sources/CameraOutput.swift index a1f0a3fb..df5f4127 100644 --- a/submodules/Camera/Sources/CameraOutput.swift +++ b/submodules/Camera/Sources/CameraOutput.swift @@ -1,3 +1,5 @@ +import SGSimpleSettings + import Foundation import AVFoundation import UIKit @@ -367,6 +369,10 @@ final class CameraOutput: NSObject { AVVideoWidthKey: Int(dimensions.width), AVVideoHeightKey: Int(dimensions.height) ] + // MARK: Swiftgram + if SGSimpleSettings.shared.startTelescopeWithRearCam { + self.currentPosition = .back + } } else { let codecType: AVVideoCodecType = hasHEVCHardwareEncoder ? .hevc : .h264 if orientation == .landscapeLeft || orientation == .landscapeRight { diff --git a/submodules/ChatListUI/BUILD b/submodules/ChatListUI/BUILD index 2da4a2e0..c8c16471 100644 --- a/submodules/ChatListUI/BUILD +++ b/submodules/ChatListUI/BUILD @@ -1,20 +1,24 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//Swiftgram/SGAPIWebSettings:SGAPIWebSettings", + "//Swiftgram/SGAPIToken:SGAPIToken" +] +sgsrcs = [ + "//Swiftgram/SGChatListSimpleSettingsSignal:SGChatListSimpleSettingsSignal", +] + swift_library( name = "ChatListUI", module_name = "ChatListUI", - srcs = glob( - [ - "Sources/**/*.swift", - ], - exclude = [ - "Sources/ChatListFilterTabContainerNode.swift", - ], - ), + srcs = glob([ + "Sources/**/*.swift", + ]) + sgsrcs, copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", "//submodules/AsyncDisplayKit:AsyncDisplayKit", "//submodules/Display:Display", @@ -130,6 +134,10 @@ swift_library( "//submodules/TelegramUI/Components/LiveLocationHeaderPanelComponent", "//submodules/TelegramUI/Components/ChatList/ChatListSearchFiltersContainerNode", "//submodules/TelegramUI/Components/ChatList/ChatListHeaderNoticeComponent", + "//submodules/TelegramUI/Components/AlertComponent", + "//submodules/TelegramUI/Components/AlertComponent/AlertTransferHeaderComponent", + "//submodules/TelegramUI/Components/AvatarComponent", + "//submodules/TelegramUI/Components/PeerManagement/OwnershipTransferController", ], visibility = [ "//visibility:public", diff --git a/submodules/ChatListUI/Sources/ChatListCompatibility.swift b/submodules/ChatListUI/Sources/ChatListCompatibility.swift new file mode 100644 index 00000000..5eec844c --- /dev/null +++ b/submodules/ChatListUI/Sources/ChatListCompatibility.swift @@ -0,0 +1,63 @@ +import Foundation +import UIKit +import ObjectiveC.runtime +import Display +import ComponentFlow +import Postbox +import TelegramCore +import TelegramPresentationData +import AccountContext +import ContextUI +import ChatListHeaderComponent + +private var chatListNodePinnedHeaderDisplayFractionUpdatedKey: UInt8 = 0 +private var chatListNodePinnedScrollFractionKey: UInt8 = 0 + +extension ChatListNavigationBar.View { + func openEmojiStatusSetup() { + } + + func updateEdgeEffectForPinnedFraction(pinnedFraction: CGFloat, transition: ComponentTransition) { + } +} + +extension ChatListNode { + var pinnedHeaderDisplayFractionUpdated: ((ContainedViewLayoutTransition) -> Void)? { + get { + return objc_getAssociatedObject(self, &chatListNodePinnedHeaderDisplayFractionUpdatedKey) as? ((ContainedViewLayoutTransition) -> Void) + } + set { + objc_setAssociatedObject(self, &chatListNodePinnedHeaderDisplayFractionUpdatedKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) + } + } + + var pinnedScrollFraction: CGFloat { + get { + return CGFloat((objc_getAssociatedObject(self, &chatListNodePinnedScrollFractionKey) as? NSNumber)?.doubleValue ?? 0.0) + } + set { + objc_setAssociatedObject(self, &chatListNodePinnedScrollFractionKey, NSNumber(value: Double(newValue)), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } +} + +extension ChatListNodeInteraction { + func openSGAnnouncement(_ id: String, _ url: String, _ needAuth: Bool, _ permanent: Bool) { + self.openUrl(url) + } +} + +extension PeerInfoScreen { + public func tabBarItemContextActionRawUIView(sourceView: UIView, gesture: ContextGesture?) { + guard let sourceView = sourceView as? ContextExtractedContentContainingView, let gesture else { + return + } + self.tabBarItemContextAction(sourceView: sourceView, gesture: gesture) + } +} + +extension ChatListControllerImpl { + func presentLeaveChannelConfirmation(peer: EnginePeer, nextCreator: EnginePeer, completion: @escaping (Bool) -> Void) { + completion(true) + } +} diff --git a/submodules/ChatListUI/Sources/ChatListController.swift b/submodules/ChatListUI/Sources/ChatListController.swift index 6b6cf315..d888ec8d 100644 --- a/submodules/ChatListUI/Sources/ChatListController.swift +++ b/submodules/ChatListUI/Sources/ChatListController.swift @@ -1,3 +1,6 @@ +// MARK: Swiftgram +import SGSimpleSettings + import Foundation import UIKit import Postbox @@ -144,7 +147,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController private var didSuggestLoginEmailSetup = false private var didSuggestLoginPasskeySetup = false - private var presentationData: PresentationData + private(set) var presentationData: PresentationData private let presentationDataValue = Promise() private var presentationDataDisposable: Disposable? @@ -393,12 +396,23 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController strongSelf.chatListDisplayNode.willScrollToTop() strongSelf.chatListDisplayNode.effectiveContainerNode.currentItemNode.scrollToPosition(.top(adjustForTempInset: false)) case let .known(offset): - let isFirstFilter = strongSelf.chatListDisplayNode.effectiveContainerNode.currentItemNode.chatListFilter == strongSelf.chatListDisplayNode.mainContainerNode.availableFilters.first?.filter + // MARK: Swiftgram + let sgAllChatsHiddden = SGSimpleSettings.shared.allChatsHidden + var mainContainerNode_availableFilters = strongSelf.chatListDisplayNode.mainContainerNode.availableFilters + if sgAllChatsHiddden { + mainContainerNode_availableFilters.removeAll { $0 == .all } + } + let isFirstFilter = strongSelf.chatListDisplayNode.effectiveContainerNode.currentItemNode.chatListFilter == mainContainerNode_availableFilters.first?.filter if offset <= ChatListNavigationBar.searchScrollHeight + 1.0 && strongSelf.chatListDisplayNode.inlineStackContainerNode != nil { strongSelf.setInlineChatList(location: nil) } else if offset <= ChatListNavigationBar.searchScrollHeight + 1.0 && !isFirstFilter { - let firstFilter = strongSelf.chatListDisplayNode.effectiveContainerNode.availableFilters.first ?? .all + // MARK: Swiftgram + var effectiveContainerNode_availableFilters = strongSelf.chatListDisplayNode.mainContainerNode.availableFilters + if sgAllChatsHiddden { + effectiveContainerNode_availableFilters.removeAll { $0 == .all } + } + let firstFilter = effectiveContainerNode_availableFilters.first ?? .all let targetTab: ChatListFilterTabEntryId switch firstFilter { case .all: @@ -735,6 +749,22 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController if let navigationBarView = strongSelf.chatListDisplayNode.navigationBarView.view as? ChatListNavigationBar.View, let headerPanelsView = navigationBarView.headerPanels as? HeaderPanelContainerComponent.View, let tabsView = headerPanelsView.tabs as? HorizontalTabsComponent.View { tabsView.updateTabSwitchFraction(fraction: fraction, isDragging: strongSelf.chatListDisplayNode.mainContainerNode.isSwitchingCurrentItemFilterByDragging, transition: ComponentTransition(transition)) } + // MARK: Swiftgram + let switchingToFilterId: Int32 + switch (filter) { + case let .filter(filterId): + switchingToFilterId = filterId + default: + switchingToFilterId = -1 + } + + if fraction.isZero { + let accountId = "\(strongSelf.context.account.peerId.id._internalGetInt64Value())" + if SGSimpleSettings.shared.lastAccountFolders[accountId] != switchingToFilterId { + SGSimpleSettings.shared.lastAccountFolders[accountId] = switchingToFilterId + } + } + } self.reloadFilters() } @@ -1285,10 +1315,10 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController } if let sourceNode { - let controller = ContextController(presentationData: self.presentationData, source: .extracted(ChatListHeaderBarContextExtractedContentSource(controller: self, sourceNode: sourceNode, sourceView: sourceView, keepInPlace: keepInPlace)), items: .single(ContextController.Items(content: .list(items))), recognizer: nil, gesture: gesture) + let controller = makeContextController(presentationData: self.presentationData, source: .extracted(ChatListHeaderBarContextExtractedContentSource(controller: self, sourceNode: sourceNode, sourceView: sourceView, keepInPlace: keepInPlace)), items: .single(ContextController.Items(content: .list(items))), recognizer: nil, gesture: gesture) self.context.sharedContext.mainWindow?.presentInGlobalOverlay(controller) } else if let sourceView { - let controller = ContextController(presentationData: self.presentationData, source: .reference(ChatListHeaderBarContextReferenceContentSource(controller: self, sourceView: sourceView)), items: .single(ContextController.Items(content: .list(items))), recognizer: nil, gesture: gesture) + let controller = makeContextController(presentationData: self.presentationData, source: .reference(ChatListHeaderBarContextReferenceContentSource(controller: self, sourceView: sourceView)), items: .single(ContextController.Items(content: .list(items))), recognizer: nil, gesture: gesture) self.context.sharedContext.mainWindow?.presentInGlobalOverlay(controller) } }) @@ -1873,7 +1903,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController case let .groupReference(groupReference): let chatListController = ChatListControllerImpl(context: strongSelf.context, location: .chatList(groupId: groupReference.groupId), controlsHistoryPreload: false, hideNetworkActivityStatus: true, previewing: true, enableDebugActions: false) chatListController.navigationPresentation = .master - let contextController = ContextController(presentationData: strongSelf.presentationData, source: .controller(ContextControllerContentSourceImpl(controller: chatListController, sourceNode: node, navigationController: strongSelf.navigationController as? NavigationController)), items: archiveContextMenuItems(context: strongSelf.context, groupId: groupReference.groupId._asGroup(), chatListController: strongSelf) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) + let contextController = makeContextController(presentationData: strongSelf.presentationData, source: .controller(ContextControllerContentSourceImpl(controller: chatListController, sourceNode: node, navigationController: strongSelf.navigationController as? NavigationController)), items: archiveContextMenuItems(context: strongSelf.context, groupId: groupReference.groupId._asGroup(), chatListController: strongSelf) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) strongSelf.presentInGlobalOverlay(contextController) case let .peer(peerData): let peer = peerData.peer @@ -1891,12 +1921,12 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController chatController.canReadHistory.set(false) source = .controller(ContextControllerContentSourceImpl(controller: chatController, sourceNode: node, navigationController: strongSelf.navigationController as? NavigationController)) - let contextController = ContextController(presentationData: strongSelf.presentationData, source: source, items: chatForumTopicMenuItems(context: strongSelf.context, peerId: peer.peerId, threadId: threadId, isPinned: nil, isClosed: nil, chatListController: strongSelf, joined: joined, canSelect: false) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) + let contextController = makeContextController(presentationData: strongSelf.presentationData, source: source, items: chatForumTopicMenuItems(context: strongSelf.context, peerId: peer.peerId, threadId: threadId, isPinned: nil, isClosed: nil, chatListController: strongSelf, joined: joined, canSelect: false) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) strongSelf.presentInGlobalOverlay(contextController) } else { let chatListController = ChatListControllerImpl(context: strongSelf.context, location: .forum(peerId: channel.id), controlsHistoryPreload: false, hideNetworkActivityStatus: true, previewing: true, enableDebugActions: false) chatListController.navigationPresentation = .master - let contextController = ContextController(presentationData: strongSelf.presentationData, source: .controller(ContextControllerContentSourceImpl(controller: chatListController, sourceNode: node, navigationController: strongSelf.navigationController as? NavigationController)), items: chatContextMenuItems(context: strongSelf.context, peerId: peer.peerId, promoInfo: promoInfo, source: .chatList(filter: strongSelf.chatListDisplayNode.mainContainerNode.currentItemNode.chatListFilter), chatListController: strongSelf, joined: joined) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) + let contextController = makeContextController(presentationData: strongSelf.presentationData, source: .controller(ContextControllerContentSourceImpl(controller: chatListController, sourceNode: node, navigationController: strongSelf.navigationController as? NavigationController)), items: chatContextMenuItems(context: strongSelf.context, peerId: peer.peerId, promoInfo: promoInfo, source: .chatList(filter: strongSelf.chatListDisplayNode.mainContainerNode.currentItemNode.chatListFilter), chatListController: strongSelf, joined: joined) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) strongSelf.presentInGlobalOverlay(contextController) } } else if let peer = peer.peer, peer.id == strongSelf.context.account.peerId, peerData.displayAsTopicList { @@ -1908,7 +1938,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController source = .controller(ContextControllerContentSourceImpl(controller: peerInfoController, sourceNode: node, navigationController: strongSelf.navigationController as? NavigationController)) } - let contextController = ContextController(presentationData: strongSelf.presentationData, source: source, items: chatContextMenuItems(context: strongSelf.context, peerId: peer.id, promoInfo: promoInfo, source: .chatList(filter: strongSelf.chatListDisplayNode.mainContainerNode.currentItemNode.chatListFilter), chatListController: strongSelf, joined: joined) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) + let contextController = makeContextController(presentationData: strongSelf.presentationData, source: source, items: chatContextMenuItems(context: strongSelf.context, peerId: peer.id, promoInfo: promoInfo, source: .chatList(filter: strongSelf.chatListDisplayNode.mainContainerNode.currentItemNode.chatListFilter), chatListController: strongSelf, joined: joined) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) strongSelf.presentInGlobalOverlay(contextController) } } else { @@ -1926,7 +1956,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController source = .controller(ContextControllerContentSourceImpl(controller: chatController, sourceNode: node, navigationController: strongSelf.navigationController as? NavigationController)) } - let contextController = ContextController(context: strongSelf.context, presentationData: strongSelf.presentationData, source: source, items: chatContextMenuItems(context: strongSelf.context, peerId: peer.peerId, promoInfo: promoInfo, source: .chatList(filter: strongSelf.chatListDisplayNode.mainContainerNode.currentItemNode.chatListFilter), chatListController: strongSelf, joined: joined) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) + let contextController = makeContextController(context: strongSelf.context, presentationData: strongSelf.presentationData, source: source, items: chatContextMenuItems(context: strongSelf.context, peerId: peer.peerId, promoInfo: promoInfo, source: .chatList(filter: strongSelf.chatListDisplayNode.mainContainerNode.currentItemNode.chatListFilter), chatListController: strongSelf, joined: joined) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) strongSelf.presentInGlobalOverlay(contextController) dismissPreviewingImpl = { [weak self, weak contextController] animateIn in @@ -1960,7 +1990,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController chatController.canReadHistory.set(false) source = .controller(ContextControllerContentSourceImpl(controller: chatController, sourceNode: node, navigationController: strongSelf.navigationController as? NavigationController)) - let contextController = ContextController(presentationData: strongSelf.presentationData, source: source, items: chatForumTopicMenuItems(context: strongSelf.context, peerId: peer.peerId, threadId: threadId, isPinned: isPinned, isClosed: threadInfo?.isClosed, chatListController: strongSelf, joined: joined, canSelect: true) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) + let contextController = makeContextController(presentationData: strongSelf.presentationData, source: source, items: chatForumTopicMenuItems(context: strongSelf.context, peerId: peer.peerId, threadId: threadId, isPinned: isPinned, isClosed: threadInfo?.isClosed, chatListController: strongSelf, joined: joined, canSelect: true) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) strongSelf.presentInGlobalOverlay(contextController) } } @@ -1995,7 +2025,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController if case let .channel(channel) = peer, channel.isForumOrMonoForum { let chatListController = ChatListControllerImpl(context: strongSelf.context, location: .forum(peerId: channel.id), controlsHistoryPreload: false, hideNetworkActivityStatus: true, previewing: true, enableDebugActions: false) chatListController.navigationPresentation = .master - let contextController = ContextController(presentationData: strongSelf.presentationData, source: .controller(ContextControllerContentSourceImpl(controller: chatListController, sourceNode: node, navigationController: strongSelf.navigationController as? NavigationController)), items: chatContextMenuItems(context: strongSelf.context, peerId: peer.id, promoInfo: nil, source: .search(source), chatListController: strongSelf, joined: false) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) + let contextController = makeContextController(presentationData: strongSelf.presentationData, source: .controller(ContextControllerContentSourceImpl(controller: chatListController, sourceNode: node, navigationController: strongSelf.navigationController as? NavigationController)), items: chatContextMenuItems(context: strongSelf.context, peerId: peer.id, promoInfo: nil, source: .search(source), chatListController: strongSelf, joined: false) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) strongSelf.presentInGlobalOverlay(contextController) } else { let contextContentSource: ContextContentSource @@ -2011,7 +2041,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController contextContentSource = .controller(ContextControllerContentSourceImpl(controller: chatController, sourceNode: node, navigationController: strongSelf.navigationController as? NavigationController)) } - let contextController = ContextController(context: strongSelf.context, presentationData: strongSelf.presentationData, source: contextContentSource, items: chatContextMenuItems(context: strongSelf.context, peerId: peer.id, promoInfo: nil, source: .search(source), chatListController: strongSelf, joined: false) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) + let contextController = makeContextController(context: strongSelf.context, presentationData: strongSelf.presentationData, source: contextContentSource, items: chatContextMenuItems(context: strongSelf.context, peerId: peer.id, promoInfo: nil, source: .search(source), chatListController: strongSelf, joined: false) |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) strongSelf.presentInGlobalOverlay(contextController) } } @@ -2117,11 +2147,18 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController if self.previewing { self.storiesReady.set(.single(true)) } else { - self.storySubscriptionsDisposable = (self.context.engine.messages.storySubscriptions(isHidden: self.location == .chatList(groupId: .archive)) - |> deliverOnMainQueue).startStrict(next: { [weak self] rawStorySubscriptions in + // MARK: Swiftgram + let hideStoriesSignal = sgSimpleSettingsBoolSignal(.hideStories, defaultValue: false) + + self.storySubscriptionsDisposable = (combineLatest(self.context.engine.messages.storySubscriptions(isHidden: self.location == .chatList(groupId: .archive)), hideStoriesSignal) + |> deliverOnMainQueue).startStrict(next: { [weak self] rawStorySubscriptions, hideStories in guard let self else { return } + var rawStorySubscriptions = rawStorySubscriptions + if hideStories { + rawStorySubscriptions = EngineStorySubscriptions(accountItem: nil, items: [], hasMoreToken: nil) + } self.rawStorySubscriptions = rawStorySubscriptions var items: [EngineStorySubscriptions.Item] = [] @@ -3029,7 +3066,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController } if let rootController = self.context.sharedContext.mainWindow?.viewController as? TelegramRootControllerInterface { - let coordinator = rootController.openStoryCamera(customTarget: nil, resumeLiveStream: hasLiveStream, transitionIn: cameraTransitionIn, transitionedIn: {}, transitionOut: self.storyCameraTransitionOut()) + let coordinator = rootController.openStoryCamera(mode: .photo, customTarget: nil, resumeLiveStream: hasLiveStream, transitionIn: cameraTransitionIn, transitionedIn: {}, transitionOut: self.storyCameraTransitionOut()) coordinator?.animateIn() } } @@ -3425,7 +3462,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController }))) } - let controller = ContextController(presentationData: self.presentationData, source: .extracted(ChatListHeaderBarContextExtractedContentSource(controller: self, sourceNode: sourceNode, sourceView: nil, keepInPlace: false)), items: .single(ContextController.Items(content: .list(items))), recognizer: nil, gesture: gesture) + let controller = makeContextController(presentationData: self.presentationData, source: .extracted(ChatListHeaderBarContextExtractedContentSource(controller: self, sourceNode: sourceNode, sourceView: nil, keepInPlace: false)), items: .single(ContextController.Items(content: .list(items))), recognizer: nil, gesture: gesture) self.context.sharedContext.mainWindow?.presentInGlobalOverlay(controller) }) } @@ -3511,7 +3548,17 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController super.navigationStackConfigurationUpdated(next: next) } - @objc fileprivate func editPressed() { + public func activateEdit() { + self.editPressed() + } + + public func openEmojiStatusSetup() { + if let navigationBarView = self.chatListDisplayNode.navigationBarView.view as? ChatListNavigationBar.View { + navigationBarView.openEmojiStatusSetup() + } + } + + @objc func editPressed() { if self.secondaryContext == nil { if case .chatList(.root) = self.chatListDisplayNode.effectiveContainerNode.location { self.effectiveContext?.leftButton = AnyComponentWithIdentity(id: "done", component: AnyComponent(NavigationButtonComponent( @@ -3546,6 +3593,9 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController if let layout = self.validLayout { self.updateLayout(layout: layout, transition: .animated(duration: 0.2, curve: .easeInOut)) } + if SGSimpleSettings.shared.hideTabBar { + (self.parent as? TabBarController)?.updateIsTabBarHidden(false, transition: .animated(duration: 0.2, curve: .easeInOut)) + } } @objc fileprivate func donePressed() { @@ -3572,6 +3622,9 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController self.updateLayout(layout: layout, transition: .animated(duration: 0.2, curve: .easeInOut)) } } + if SGSimpleSettings.shared.hideTabBar { + (self.parent as? TabBarController)?.updateIsTabBarHidden(true, transition: .animated(duration: 0.2, curve: .easeInOut)) + } } private var skipTabContainerUpdate = false @@ -3878,7 +3931,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController } let presentationData = context.sharedContext.currentPresentationData.with { $0 } - let contextController = ContextController(presentationData: presentationData, source: .reference(HeaderContextReferenceContentSource(controller: sourceController, sourceView: sourceView)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) + let contextController = makeContextController(presentationData: presentationData, source: .reference(HeaderContextReferenceContentSource(controller: sourceController, sourceView: sourceView)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) sourceController.presentInGlobalOverlay(contextController) }) } @@ -3938,7 +3991,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController }))) } - let contextController = ContextController(presentationData: presentationData, source: .reference(HeaderContextReferenceContentSource(controller: self, sourceView: sourceView)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) + let contextController = makeContextController(presentationData: presentationData, source: .reference(HeaderContextReferenceContentSource(controller: self, sourceView: sourceView)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) self.presentInGlobalOverlay(contextController) }) } @@ -3947,12 +4000,23 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController private func reloadFilters(firstUpdate: (() -> Void)? = nil) { let filterItems = chatListFilterItems(context: self.context) var notifiedFirstUpdate = false + + // MARK: Swiftgram + let experimentalUISettingsKey: ValueBoxKey = ApplicationSpecificSharedDataKeys.experimentalUISettings + let displayTabsAtBottomSignal = self.context.sharedContext.accountManager.sharedData(keys: Set([experimentalUISettingsKey])) + |> map { sharedData -> Bool in + let settings: ExperimentalUISettings = sharedData.entries[experimentalUISettingsKey]?.get(ExperimentalUISettings.self) ?? ExperimentalUISettings.defaultSettings + return settings.foldersTabAtBottom + } + |> distinctUntilChanged + self.filterDisposable.set((combineLatest(queue: .mainQueue(), + displayTabsAtBottomSignal, filterItems, self.context.account.postbox.peerView(id: self.context.account.peerId), self.context.engine.data.get(TelegramEngine.EngineData.Item.Configuration.UserLimits(isPremium: false)) ) - |> deliverOnMainQueue).startStrict(next: { [weak self] countAndFilterItems, peerView, limits in + |> deliverOnMainQueue).startStrict(next: { [weak self] displayTabsAtBottom, countAndFilterItems, peerView, limits in guard let strongSelf = self else { return } @@ -3990,13 +4054,19 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController } let firstItem = countAndFilterItems.1.first?.0 ?? .allChats - let firstItemEntryId: ChatListFilterTabEntryId + var firstItemEntryId: ChatListFilterTabEntryId switch firstItem { case .allChats: firstItemEntryId = .all case let .filter(id, _, _, _): firstItemEntryId = .filter(id) } + // MARK: Swiftgram + if !strongSelf.initializedFilters && SGSimpleSettings.shared.rememberLastFolder { + if let lastFolder = SGSimpleSettings.shared.lastAccountFolders["\(strongSelf.context.account.peerId.id._internalGetInt64Value())"]{ + firstItemEntryId = lastFolder == -1 ? .all : .filter(lastFolder) + } + } var selectedEntryId = !strongSelf.initializedFilters ? firstItemEntryId : strongSelf.chatListDisplayNode.mainContainerNode.currentItemFilter var resetCurrentEntry = false @@ -4021,7 +4091,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController } } let filtersLimit = isPremium == false ? limits.maxFoldersCount : nil - strongSelf.tabContainerData = (resolvedItems, false, filtersLimit) + strongSelf.tabContainerData = (resolvedItems, displayTabsAtBottom, filtersLimit) var availableFilters: [ChatListContainerNodeFilter] = [] var hasAllChats = false for item in items { @@ -4754,7 +4824,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController completion?() self.updateTabBarSearchState(ViewController.TabBarSearchState(isActive: false), transition: transition) - (self.parent as? TabBarController)?.updateIsTabBarHidden(false, transition: transition) + (self.parent as? TabBarController)?.updateIsTabBarHidden(SGSimpleSettings.shared.hideTabBar ? true : false, transition: transition) self.isSearchActive = false if let navigationController = self.navigationController as? NavigationController { @@ -5421,10 +5491,33 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController if canRemoveGlobally && isGroupOrChannel { items.append(DeleteChatPeerActionSheetItem(context: strongSelf.context, peer: mainPeer, chatPeer: chatPeer, action: .deleteAndLeave, strings: strongSelf.presentationData.strings, nameDisplayOrder: strongSelf.presentationData.nameDisplayOrder)) - items.append(ActionSheetButtonItem(title: strongSelf.presentationData.strings.ChatList_DeleteForCurrentUser, color: .destructive, action: { [weak actionSheet] in + items.append(ActionSheetButtonItem(title: strongSelf.presentationData.strings.ChatList_DeleteForCurrentUser, color: .destructive, action: { [weak self, weak actionSheet] in actionSheet?.dismissAnimated() - self?.schedulePeerChatRemoval(peer: peer, type: .forLocalPeer, deleteGloballyIfPossible: false, completion: { - }) + + let proceed = { + self?.schedulePeerChatRemoval(peer: peer, type: .forLocalPeer, deleteGloballyIfPossible: false, completion: { + }) + } + + if let self, case let .channel(channel) = peer.peer, channel.flags.contains(.isCreator) { + let _ = (self.context.engine.peers.getFutureCreatorAfterLeave(peerId: channel.id) + |> deliverOnMainQueue).start(next: { [weak self] nextCreator in + guard let self else { + return + } + if let nextCreator, let peer = peer.peer { + self.presentLeaveChannelConfirmation(peer: peer, nextCreator: nextCreator, completion: { commit in + if commit { + proceed() + } + }) + } else { + proceed() + } + }) + } else { + proceed() + } })) let deleteForAllText: String @@ -5874,10 +5967,33 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController }) ], parseMarkdown: true), in: .window(.root)) } else { - completion(true) - self.schedulePeerChatRemoval(peer: peer, type: .forLocalPeer, deleteGloballyIfPossible: deleteGloballyIfPossible, completion: { - removed() - }) + let proceed = { + completion(true) + self.schedulePeerChatRemoval(peer: peer, type: .forLocalPeer, deleteGloballyIfPossible: deleteGloballyIfPossible, completion: { + removed() + }) + } + if case let .channel(channel) = peer.peer, channel.flags.contains(.isCreator) { + let _ = (self.context.engine.peers.getFutureCreatorAfterLeave(peerId: channel.id) + |> deliverOnMainQueue).start(next: { [weak self] nextCreator in + guard let self else { + return + } + if let nextCreator, let peer = peer.peer { + self.presentLeaveChannelConfirmation(peer: peer, nextCreator: nextCreator, completion: { commit in + if commit { + proceed() + } else { + completion(false) + } + }) + } else { + proceed() + } + }) + } else { + proceed() + } } } @@ -6206,7 +6322,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController } } - let controller = ContextController(context: strongSelf.context, presentationData: strongSelf.presentationData, source: .reference(ChatListTabBarContextReferenceContentSource(controller: strongSelf, sourceView: sourceView)), items: .single(ContextController.Items(content: .list(items))), recognizer: nil, gesture: gesture) + let controller = makeContextController(context: strongSelf.context, presentationData: strongSelf.presentationData, source: .reference(ChatListTabBarContextReferenceContentSource(controller: strongSelf, sourceView: sourceView)), items: .single(ContextController.Items(content: .list(items))), recognizer: nil, gesture: gesture) strongSelf.context.sharedContext.mainWindow?.presentInGlobalOverlay(controller) }) } @@ -6408,7 +6524,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController }) }))) - let contextController = ContextController(presentationData: presentationData, source: .reference(AdsInfoContextReferenceContentSource(controller: controller, sourceView: referenceView, insets: .zero, contentInsets: .zero)), items: .single(ContextController.Items(content: .list(actions))), gesture: nil) + let contextController = makeContextController(presentationData: presentationData, source: .reference(AdsInfoContextReferenceContentSource(controller: controller, sourceView: referenceView, insets: .zero, contentInsets: .zero)), items: .single(ContextController.Items(content: .list(actions))), gesture: nil) controller.presentInGlobalOverlay(contextController) } @@ -6425,7 +6541,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController if let current = self.storyCameraTransitionInCoordinator { coordinator = current } else { - coordinator = rootController.openStoryCamera(customTarget: nil, resumeLiveStream: false, transitionIn: nil, transitionedIn: {}, transitionOut: { [weak self] target, _ in + coordinator = rootController.openStoryCamera(mode: .photo, customTarget: nil, resumeLiveStream: false, transitionIn: nil, transitionedIn: {}, transitionOut: { [weak self] target, _ in guard let self, let target else { return nil } @@ -6591,18 +6707,18 @@ private final class ChatListLocationContext { private(set) var chatListTitle: NetworkStatusTitle? var leftButton: AnyComponentWithIdentity? + var defaultLeftButton: AnyComponentWithIdentity? var rightButton: AnyComponentWithIdentity? var proxyButton: AnyComponentWithIdentity? var storyButton: AnyComponentWithIdentity? - - // GHOSTGRAM: Account switcher — liquid glass avatar button for the next account var accountSwitcherButton: AnyComponentWithIdentity? + var tabBarMoreButton: AnyComponentWithIdentity? private var accountSwitcherDisposable: Disposable? private var accountSwitcherAvatarDisposable: Disposable? + private var accountSwitcherInfo: (primary: AccountRecordId?, accounts: [AccountWithInfo])? var rightButtons: [AnyComponentWithIdentity] { var result: [AnyComponentWithIdentity] = [] - // Account switcher is first — leftmost of the right-side buttons if let accountSwitcherButton = self.accountSwitcherButton { result.append(accountSwitcherButton) } @@ -6615,6 +6731,9 @@ private final class ChatListLocationContext { if let proxyButton = self.proxyButton { result.append(proxyButton) } + if let tabBarMoreButton = self.tabBarMoreButton { + result.append(tabBarMoreButton) + } return result } @@ -6640,91 +6759,15 @@ private final class ChatListLocationContext { self.location = location self.parentController = parentController - // GHOSTGRAM: Subscribe to account list and maintain the switcher button if case .chatList(.root) = location { self.accountSwitcherDisposable = (context.sharedContext.activeAccountsWithInfo - |> deliverOnMainQueue) - .start(next: { [weak self] (info: (primary: AccountRecordId?, accounts: [AccountWithInfo])) in - guard let self else { return } - - let primaryId = info.primary - let accounts = info.accounts - - // Only show when there is more than one account - guard accounts.count > 1, let primaryId = primaryId else { - if self.accountSwitcherButton != nil { - self.accountSwitcherButton = nil - let _ = self.parentController?.updateHeaderContent() - self.parentController?.requestLayout(transition: .immediate) - } - return - } - - // Find next account cyclically - let currentIndex = accounts.firstIndex(where: { $0.account.id == primaryId }) ?? 0 - let nextIndex = (currentIndex + 1) % accounts.count - let nextAccount = accounts[nextIndex] - let nextPeer = nextAccount.peer - let nextPeerId = "\(nextAccount.account.id)" - - // Build button placeholder immediately (image loads async) - let buildButton: (UIImage?) -> Void = { [weak self] image in - guard let self else { return } - guard case .chatList(.root) = self.location else { return } - - let sharedContext = self.context.sharedContext - let nextAccountId = nextAccount.account.id - - self.accountSwitcherButton = AnyComponentWithIdentity( - id: "accountSwitcher", - component: AnyComponent(NavigationButtonComponent( - content: .avatar(peerId: nextPeerId, avatarImage: image), - pressed: { [weak sharedContext] _ in - sharedContext?.switchToAccount(id: nextAccountId, fromSettingsController: nil, withChatListController: nil) - } - )) - ) - // Trigger header rebuild - let _ = self.parentController?.updateHeaderContent() - self.parentController?.requestLayout(transition: .immediate) - } - - // Attempt to load the peer's avatar from mediaBox - if let representation = nextPeer.smallProfileImage { - self.accountSwitcherAvatarDisposable?.dispose() - let resource = representation.resource - let account = nextAccount.account - - // GHOSTGRAM: Fetch first so the resource is populated by the time - // resourceData emits a complete result. The old order (subscribe→fetch) - // had a race where `completed` fired before data arrived, causing - // buildButton(nil) to be called and the avatar to never show. - if let peerReference = PeerReference(nextPeer) { - let _ = fetchedMediaResource( - mediaBox: account.postbox.mediaBox, - userLocation: .peer(nextPeer.id), - userContentType: .avatar, - reference: .avatar(peer: peerReference, resource: resource) - ).start() - } - - self.accountSwitcherAvatarDisposable = (account.postbox.mediaBox - .resourceData(resource) - |> filter { $0.complete } - |> take(1) - |> deliverOnMainQueue) - .start(next: { data in - if let uiImage = UIImage(contentsOfFile: data.path) { - buildButton(uiImage) - } else { - buildButton(nil) - } - }) - } else { - // No photo — show placeholder - buildButton(nil) - } - }) + |> deliverOnMainQueue).start(next: { [weak self] info in + guard let self else { + return + } + self.accountSwitcherInfo = info + self.updateAccountSwitcherButton(from: info) + }) } let hasProxy = context.sharedContext.accountManager.sharedData(keys: [SharedDataKeys.proxySettings]) @@ -6739,6 +6782,9 @@ private final class ChatListLocationContext { return lhs == rhs }) + // MARK: Swiftgram + let hideStoriesSignal = sgSimpleSettingsBoolSignal(.hideStories, defaultValue: false) + let passcode = context.sharedContext.accountManager.accessChallengeData() |> map { view -> (Bool, Bool) in let data = view.data @@ -6807,6 +6853,7 @@ private final class ChatListLocationContext { case .chatList: if !hideNetworkActivityStatus { self.titleDisposable = combineLatest(queue: .mainQueue(), + hideStoriesSignal, networkState, hasProxy, passcode, @@ -6815,12 +6862,13 @@ private final class ChatListLocationContext { peerStatus, parentController.updatedPresentationData.1, storyPostingAvailable - ).startStrict(next: { [weak self] networkState, proxy, passcode, stateAndFilterId, isReorderingTabs, peerStatus, presentationData, storyPostingAvailable in + ).startStrict(next: { [weak self] hideStories, networkState, proxy, passcode, stateAndFilterId, isReorderingTabs, peerStatus, presentationData, storyPostingAvailable in guard let self else { return } self.updateChatList( + hideStories: hideStories, networkState: networkState, proxy: proxy, passcode: passcode, @@ -7029,7 +7077,9 @@ private final class ChatListLocationContext { } var transition: ContainedViewLayoutTransition = .immediate let previousToolbar = previousToolbarValue.swap(toolbar) - if (previousToolbar == nil) != (toolbar == nil) { + if SGSimpleSettings.shared.hideTabBar { + transition = .animated(duration: 0.2, curve: .easeInOut) + } else if (previousToolbar == nil) != (toolbar == nil) { transition = .animated(duration: 0.4, curve: .spring) } if strongSelf.toolbar != toolbar { @@ -7049,7 +7099,87 @@ private final class ChatListLocationContext { self.accountSwitcherAvatarDisposable?.dispose() } + private func updateAccountSwitcherButton(from info: (primary: AccountRecordId?, accounts: [AccountWithInfo])) { + let primaryId = info.primary + let accounts = info.accounts + + guard accounts.count > 1, let primaryId else { + self.accountSwitcherAvatarDisposable?.dispose() + if self.accountSwitcherButton != nil { + self.accountSwitcherButton = nil + let _ = self.parentController?.updateHeaderContent() + self.parentController?.requestLayout(transition: .immediate) + } + return + } + + let currentIndex = accounts.firstIndex(where: { $0.account.id == primaryId }) ?? 0 + let targetIndex: Int + if currentIndex == 0 { + targetIndex = min(1, accounts.count - 1) + } else { + targetIndex = currentIndex - 1 + } + let targetAccount = accounts[targetIndex] + let targetPeer = targetAccount.peer + let targetPeerId = "\(targetAccount.account.id)" + + let buildButton: (UIImage?) -> Void = { [weak self] image in + guard let self else { + return + } + guard case .chatList(.root) = self.location else { + return + } + + let sharedContext = self.context.sharedContext + let targetAccountId = targetAccount.account.id + + self.accountSwitcherButton = AnyComponentWithIdentity( + id: "accountSwitcher", + component: AnyComponent(NavigationButtonComponent( + content: .avatar(peerId: targetPeerId, avatarImage: image), + pressed: { [weak sharedContext] _ in + sharedContext?.switchToAccount(id: targetAccountId, fromSettingsController: nil, withChatListController: nil) + } + )) + ) + let _ = self.parentController?.updateHeaderContent() + self.parentController?.requestLayout(transition: .immediate) + } + + if let representation = targetPeer.smallProfileImage { + self.accountSwitcherAvatarDisposable?.dispose() + let resource = representation.resource + let account = targetAccount.account + + if let peerReference = PeerReference(targetPeer) { + let _ = fetchedMediaResource( + mediaBox: account.postbox.mediaBox, + userLocation: .peer(targetPeer.id), + userContentType: .avatar, + reference: .avatar(peer: peerReference, resource: resource) + ).start() + } + + self.accountSwitcherAvatarDisposable = (account.postbox.mediaBox.resourceData(resource) + |> filter { $0.complete } + |> take(1) + |> deliverOnMainQueue).start(next: { data in + if let uiImage = UIImage(contentsOfFile: data.path) { + buildButton(uiImage) + } else { + buildButton(nil) + } + }) + } else { + self.accountSwitcherAvatarDisposable?.dispose() + buildButton(nil) + } + } + private func updateChatList( + hideStories: Bool, networkState: AccountNetworkState, proxy: (Bool, Bool), passcode: (Bool, Bool), @@ -7063,7 +7193,7 @@ private final class ChatListLocationContext { switch location { case let .chatList(groupId): if groupId == .root { - defaultTitle = presentationData.strings.DialogList_Title + defaultTitle = "" } else { defaultTitle = presentationData.strings.ChatList_ArchivedChatsTitle } @@ -7080,6 +7210,7 @@ private final class ChatListLocationContext { if case .chatList(.root) = self.location { self.rightButton = nil self.storyButton = nil + self.tabBarMoreButton = nil self.accountSwitcherButton = nil } let title = !stateAndFilterId.state.selectedPeerIds.isEmpty ? presentationData.strings.ChatList_SelectedChats(Int32(stateAndFilterId.state.selectedPeerIds.count)) : defaultTitle @@ -7096,6 +7227,7 @@ private final class ChatListLocationContext { if case .chatList(.root) = self.location { self.rightButton = nil self.storyButton = nil + self.tabBarMoreButton = nil self.accountSwitcherButton = nil } self.leftButton = AnyComponentWithIdentity(id: "done", component: AnyComponent(NavigationButtonComponent( @@ -7104,6 +7236,7 @@ private final class ChatListLocationContext { let _ = self?.parentController?.reorderingDonePressed() } ))) + self.defaultLeftButton = self.leftButton let (_, connectsViaProxy) = proxy @@ -7118,7 +7251,13 @@ private final class ChatListLocationContext { }*/ titleContent = NetworkStatusTitle(text: text, activity: true, hasProxy: false, connectsViaProxy: connectsViaProxy, isPasscodeSet: false, isManuallyLocked: false, peerStatus: peerStatus) case .updating: - titleContent = NetworkStatusTitle(text: presentationData.strings.State_Updating, activity: true, hasProxy: false, connectsViaProxy: connectsViaProxy, isPasscodeSet: false, isManuallyLocked: false, peerStatus: peerStatus) + let updatingText: String + if case .chatList(.root) = self.location { + updatingText = "" + } else { + updatingText = presentationData.strings.State_Updating + } + titleContent = NetworkStatusTitle(text: updatingText, activity: true, hasProxy: false, connectsViaProxy: connectsViaProxy, isPasscodeSet: false, isManuallyLocked: false, peerStatus: peerStatus) case .online: titleContent = NetworkStatusTitle(text: defaultTitle, activity: false, hasProxy: false, connectsViaProxy: connectsViaProxy, isPasscodeSet: false, isManuallyLocked: false, peerStatus: peerStatus) } @@ -7142,9 +7281,22 @@ private final class ChatListLocationContext { } ))) } + if SGSimpleSettings.shared.hideTabBar { + self.tabBarMoreButton = AnyComponentWithIdentity(id: "hiddenTabBarMore", component: AnyComponent(NavigationButtonComponent( + content: .more, + pressed: { [weak self] sourceView in + self?.performMoreAction(sourceView: sourceView) + }, + contextAction: { [weak self] sourceView, _ in + self?.performMoreAction(sourceView: sourceView) + } + ))) + } else { + self.tabBarMoreButton = nil + } if isReorderingTabs { - self.leftButton = AnyComponentWithIdentity(id: "done", component: AnyComponent(NavigationButtonComponent( + self.defaultLeftButton = AnyComponentWithIdentity(id: "done", component: AnyComponent(NavigationButtonComponent( content: .text(title: presentationData.strings.Common_Done, isBold: true), pressed: { [weak self] _ in let _ = self?.parentController?.reorderingDonePressed() @@ -7152,14 +7304,14 @@ private final class ChatListLocationContext { ))) } else { if stateAndFilterId.state.editing { - self.leftButton = AnyComponentWithIdentity(id: "done", component: AnyComponent(NavigationButtonComponent( + self.defaultLeftButton = AnyComponentWithIdentity(id: "done", component: AnyComponent(NavigationButtonComponent( content: .text(title: presentationData.strings.Common_Done, isBold: true), pressed: { [weak self] _ in self?.parentController?.donePressed() } ))) } else { - self.leftButton = AnyComponentWithIdentity(id: "edit", component: AnyComponent(NavigationButtonComponent( + self.defaultLeftButton = AnyComponentWithIdentity(id: "edit", component: AnyComponent(NavigationButtonComponent( content: .text(title: presentationData.strings.Common_Edit, isBold: false), pressed: { [weak self] _ in self?.parentController?.editPressed() @@ -7167,8 +7319,9 @@ private final class ChatListLocationContext { ))) } } + self.leftButton = self.defaultLeftButton - if storyPostingAvailable { + if storyPostingAvailable && !hideStories { self.storyButton = AnyComponentWithIdentity(id: "story", component: AnyComponent(NavigationButtonComponent( content: .icon(imageName: "Chat List/AddStoryIcon"), pressed: { [weak self] _ in @@ -7186,7 +7339,13 @@ private final class ChatListLocationContext { } else { self.storyButton = nil } + + if self.accountSwitcherButton == nil, let accountSwitcherInfo = self.accountSwitcherInfo { + self.updateAccountSwitcherButton(from: accountSwitcherInfo) + } + } else { + self.tabBarMoreButton = nil let parentController = self.parentController self.rightButton = AnyComponentWithIdentity(id: "more", component: AnyComponent(NavigationButtonComponent( content: .more, @@ -7202,6 +7361,7 @@ private final class ChatListLocationContext { parentController.openArchiveMoreMenu(sourceView: sourceView, gesture: gesture) } ))) + self.defaultLeftButton = self.leftButton } let (hasProxy, connectsViaProxy) = proxy @@ -7220,7 +7380,8 @@ private final class ChatListLocationContext { } titleContent = NetworkStatusTitle(text: text, activity: true, hasProxy: isRoot && hasProxy, connectsViaProxy: connectsViaProxy, isPasscodeSet: isRoot && isPasscodeSet, isManuallyLocked: isRoot && isManuallyLocked, peerStatus: peerStatus) case .updating: - titleContent = NetworkStatusTitle(text: presentationData.strings.State_Updating, activity: true, hasProxy: isRoot && hasProxy, connectsViaProxy: connectsViaProxy, isPasscodeSet: isRoot && isPasscodeSet, isManuallyLocked: isRoot && isManuallyLocked, peerStatus: peerStatus) + let updatingText: String = isRoot ? "" : presentationData.strings.State_Updating + titleContent = NetworkStatusTitle(text: updatingText, activity: true, hasProxy: isRoot && hasProxy, connectsViaProxy: connectsViaProxy, isPasscodeSet: isRoot && isPasscodeSet, isManuallyLocked: isRoot && isManuallyLocked, peerStatus: peerStatus) case .online: titleContent = NetworkStatusTitle(text: defaultTitle, activity: false, hasProxy: isRoot && hasProxy, connectsViaProxy: connectsViaProxy, isPasscodeSet: isRoot && isPasscodeSet, isManuallyLocked: isRoot && isManuallyLocked, peerStatus: peerStatus) } @@ -7397,8 +7558,13 @@ private final class ChatListLocationContext { } switch self.location { case let .chatList(mode): - if case .archive = mode { + switch mode { + case .archive: parentController.openArchiveMoreMenu(sourceView: sourceView, gesture: nil) + case .root: + if SGSimpleSettings.shared.hideTabBar { + parentController.settingsPressed() + } } case let .forum(peerId): ChatListControllerImpl.openMoreMenu(context: self.context, peerId: peerId, sourceController: parentController, isViewingAsTopics: true, sourceView: sourceView, gesture: nil) @@ -7425,3 +7591,15 @@ private final class AdsInfoContextReferenceContentSource: ContextReferenceConten return ContextControllerReferenceViewInfo(referenceView: self.sourceView, contentAreaInScreenSpace: UIScreen.main.bounds.inset(by: self.insets), insets: self.contentInsets) } } + +// MARK: Swiftgram +extension ChatListControllerImpl { + + @objc fileprivate func settingsPressed() { + if let rootController = self.context.sharedContext.mainWindow?.viewController as? TelegramRootControllerInterface { + if let accountSettingsController = rootController.accountSettingsController { + (self.navigationController as? NavigationController)?.pushViewController(accountSettingsController) + } + } + } +} diff --git a/submodules/ChatListUI/Sources/ChatListControllerNode.swift b/submodules/ChatListUI/Sources/ChatListControllerNode.swift index 9847039d..2f64f2f9 100644 --- a/submodules/ChatListUI/Sources/ChatListControllerNode.swift +++ b/submodules/ChatListUI/Sources/ChatListControllerNode.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import AsyncDisplayKit @@ -165,6 +166,7 @@ public final class ChatListContainerNode: ASDisplayNode, ASGestureRecognizerDele previousItemNode.listNode.updatePeerGrouping = nil previousItemNode.listNode.contentOffsetChanged = nil previousItemNode.listNode.contentScrollingEnded = nil + previousItemNode.listNode.pinnedHeaderDisplayFractionUpdated = nil previousItemNode.listNode.didBeginInteractiveDragging = nil previousItemNode.listNode.endedInteractiveDragging = { _ in } previousItemNode.listNode.shouldStopScrolling = nil @@ -327,11 +329,12 @@ public final class ChatListContainerNode: ASDisplayNode, ASGestureRecognizerDele } return self.contentScrollingEnded?(listView) ?? false - //DispatchQueue.main.async { [weak self] in - // let _ = self?.contentScrollingEnded?(listView) - //} - - //return false + } + itemNode.listNode.pinnedHeaderDisplayFractionUpdated = { [weak self] transition in + guard let self else { + return + } + self.pinnedHeaderDisplayFractionUpdated?(transition) } itemNode.listNode.activateChatPreview = { [weak self] item, threadId, sourceNode, gesture, location in self?.activateChatPreview?(item, threadId, sourceNode, gesture, location) @@ -427,6 +430,7 @@ public final class ChatListContainerNode: ASDisplayNode, ASGestureRecognizerDele var contentOffset: ListViewVisibleContentOffset? public var contentOffsetChanged: ((ListViewVisibleContentOffset, ListView) -> Void)? public var contentScrollingEnded: ((ListView) -> Bool)? + public var pinnedHeaderDisplayFractionUpdated: ((ContainedViewLayoutTransition) -> Void)? var didBeginInteractiveDragging: ((ListView) -> Void)? var endedInteractiveDragging: ((ListView) -> Void)? var shouldStopScrolling: ((ListView, CGFloat) -> Bool)? @@ -443,6 +447,34 @@ public final class ChatListContainerNode: ASDisplayNode, ASGestureRecognizerDele var canExpandHiddenItems: (() -> Bool)? public var displayFilterLimit: (() -> Void)? + public var pinnedHeaderDisplayFraction: CGFloat { + guard let currentItemNodeValue = self.currentItemNodeValue else { + return 0.0 + } + if self.transitionFraction != 0.0 { + var nextItemNode: ChatListContainerItemNode? + if let selectedIndex = self.availableFilters.firstIndex(where: { $0.id == self.selectedId }) { + if self.transitionFraction < 0.0 { + if selectedIndex + 1 < self.availableFilters.count { + nextItemNode = self.itemNodes[self.availableFilters[selectedIndex + 1].id] + } + } else { + if selectedIndex > 0 { + nextItemNode = self.itemNodes[self.availableFilters[selectedIndex - 1].id] + } + } + } + + if let nextItemNode { + let absTransitionFraction = abs(self.transitionFraction) + return (1.0 - absTransitionFraction) * currentItemNodeValue.listNode.pinnedScrollFraction + absTransitionFraction * nextItemNode.listNode.pinnedScrollFraction + } else { + return currentItemNodeValue.listNode.pinnedScrollFraction + } + } + return currentItemNodeValue.listNode.pinnedScrollFraction + } + public init( context: AccountContext, controller: ChatListControllerImpl?, @@ -501,8 +533,8 @@ public final class ChatListContainerNode: ASDisplayNode, ASGestureRecognizerDele self.applyItemNodeAsCurrent(id: .all, itemNode: itemNode) - let panRecognizer = InteractiveTransitionGestureRecognizer(target: self, action: #selector(self.panGesture(_:)), allowedDirections: { [weak self] _ in - guard let self, self.availableFilters.count > 1 || (self.controller?.isStoryPostingAvailable == true && !(self.context.sharedContext.callManager?.hasActiveCall ?? false)) else { + let panRecognizer = InteractiveTransitionGestureRecognizer(target: self, action: #selector(self.panGesture(_:)), allowedDirections: { [weak self] _ in // MARK: Swiftgram + guard let self, self.availableFilters.count > 1 || (self.controller?.isStoryPostingAvailable == true && !(self.context.sharedContext.callManager?.hasActiveCall ?? false) && !SGSimpleSettings.shared.disableSwipeToRecordStory) else { return [] } guard case .chatList(.root) = self.location else { @@ -524,7 +556,7 @@ public final class ChatListContainerNode: ASDisplayNode, ASGestureRecognizerDele } else { return [.rightEdge] } - }, edgeWidth: .widthMultiplier(factor: 1.0 / 6.0, min: 22.0, max: 80.0)) + }, edgeWidth: SGSimpleSettings.shared.disableChatSwipeOptions ? .widthMultiplier(factor: 1.0 / 6.0, min: 0.0, max: 0.0) : .widthMultiplier(factor: 1.0 / 6.0, min: 22.0, max: 80.0)) panRecognizer.delegate = self.wrappedGestureRecognizerDelegate panRecognizer.delaysTouchesBegan = false panRecognizer.cancelsTouchesInView = true @@ -553,8 +585,13 @@ public final class ChatListContainerNode: ASDisplayNode, ASGestureRecognizerDele } @objc private func panGesture(_ recognizer: UIPanGestureRecognizer) { - let filtersLimit = self.filtersLimit.flatMap({ $0 + 1 }) ?? Int32(self.availableFilters.count) - let maxFilterIndex = min(Int(filtersLimit), self.availableFilters.count) - 1 + // MARK: Swiftgram + var _availableFilters = self.availableFilters + if SGSimpleSettings.shared.allChatsHidden { + _availableFilters.removeAll { $0 == .all } + } + let filtersLimit = self.filtersLimit.flatMap({ $0 + 1 }) ?? Int32(_availableFilters.count) + let maxFilterIndex = min(Int(filtersLimit), _availableFilters.count) - 1 switch recognizer.state { case .began: @@ -584,11 +621,12 @@ public final class ChatListContainerNode: ASDisplayNode, ASGestureRecognizerDele self.update(layout: layout, navigationBarHeight: navigationBarHeight, visualNavigationHeight: visualNavigationHeight, originalNavigationHeight: originalNavigationHeight, cleanNavigationBarHeight: cleanNavigationBarHeight, insets: insets, isReorderingFilters: isReorderingFilters, isEditing: isEditing, inlineNavigationLocation: inlineNavigationLocation, inlineNavigationTransitionFraction: inlineNavigationTransitionFraction, storiesInset: storiesInset, transition: .immediate) self.isSwitchingCurrentItemFilterByDragging = true self.currentItemFilterUpdated?(self.currentItemFilter, self.transitionFraction, .immediate, true) + self.pinnedHeaderDisplayFractionUpdated?(.immediate) } } } case .changed: - if let (layout, navigationBarHeight, visualNavigationHeight, originalNavigationHeight: originalNavigationHeight, cleanNavigationBarHeight, insets, isReorderingFilters, isEditing, inlineNavigationLocation, inlineNavigationTransitionFraction, storiesInset) = self.validLayout, let selectedIndex = self.availableFilters.firstIndex(where: { $0.id == self.selectedId }) { + if let (layout, navigationBarHeight, visualNavigationHeight, originalNavigationHeight: originalNavigationHeight, cleanNavigationBarHeight, insets, isReorderingFilters, isEditing, inlineNavigationLocation, inlineNavigationTransitionFraction, storiesInset) = self.validLayout, let selectedIndex = _availableFilters.firstIndex(where: { $0.id == self.selectedId }) { let translation = recognizer.translation(in: self.view) var transitionFraction = translation.x / layout.size.width @@ -606,7 +644,7 @@ public final class ChatListContainerNode: ASDisplayNode, ASGestureRecognizerDele hasLiveStream = true } - if case .compact = layout.metrics.widthClass, self.controller?.isStoryPostingAvailable == true && !(self.context.sharedContext.callManager?.hasActiveCall ?? false) { + if case .compact = layout.metrics.widthClass, self.controller?.isStoryPostingAvailable == true && !(self.context.sharedContext.callManager?.hasActiveCall ?? false) && !SGSimpleSettings.shared.disableSwipeToRecordStory { if hasLiveStream { if translation.x >= 30.0 { self.panRecognizer?.cancel() @@ -661,9 +699,10 @@ public final class ChatListContainerNode: ASDisplayNode, ASGestureRecognizerDele self.update(layout: layout, navigationBarHeight: navigationBarHeight, visualNavigationHeight: visualNavigationHeight, originalNavigationHeight: originalNavigationHeight, cleanNavigationBarHeight: cleanNavigationBarHeight, insets: insets, isReorderingFilters: isReorderingFilters, isEditing: isEditing, inlineNavigationLocation: inlineNavigationLocation, inlineNavigationTransitionFraction: inlineNavigationTransitionFraction, storiesInset: storiesInset, transition: .immediate) self.isSwitchingCurrentItemFilterByDragging = true self.currentItemFilterUpdated?(self.currentItemFilter, self.transitionFraction, transition, false) + self.pinnedHeaderDisplayFractionUpdated?(transition) } case .cancelled, .ended: - if let (layout, navigationBarHeight, visualNavigationHeight, originalNavigationHeight: originalNavigationHeight, cleanNavigationBarHeight, insets, isReorderingFilters, isEditing, inlineNavigationLocation, inlineNavigationTransitionFraction, storiesInset) = self.validLayout, let selectedIndex = self.availableFilters.firstIndex(where: { $0.id == self.selectedId }) { + if let (layout, navigationBarHeight, visualNavigationHeight, originalNavigationHeight: originalNavigationHeight, cleanNavigationBarHeight, insets, isReorderingFilters, isEditing, inlineNavigationLocation, inlineNavigationTransitionFraction, storiesInset) = self.validLayout, let selectedIndex = _availableFilters.firstIndex(where: { $0.id == self.selectedId }) { let translation = recognizer.translation(in: self.view) let velocity = recognizer.velocity(in: self.view) var directionIsToRight: Bool? @@ -700,7 +739,7 @@ public final class ChatListContainerNode: ASDisplayNode, ASGestureRecognizerDele } else { updatedIndex = max(updatedIndex - 1, 0) } - let switchToId = self.availableFilters[updatedIndex].id + let switchToId = _availableFilters[updatedIndex].id if switchToId != self.selectedId, let itemNode = self.itemNodes[switchToId] { let _ = itemNode self.selectedId = switchToId @@ -723,6 +762,7 @@ public final class ChatListContainerNode: ASDisplayNode, ASGestureRecognizerDele } self.isSwitchingCurrentItemFilterByDragging = false self.currentItemFilterUpdated?(self.currentItemFilter, self.transitionFraction, transition, false) + self.pinnedHeaderDisplayFractionUpdated?(transition) } default: break @@ -843,6 +883,7 @@ public final class ChatListContainerNode: ASDisplayNode, ASGestureRecognizerDele let transition: ContainedViewLayoutTransition = .animated(duration: 0.35, curve: .spring) self.update(layout: layout, navigationBarHeight: navigationBarHeight, visualNavigationHeight: visualNavigationHeight, originalNavigationHeight: originalNavigationHeight, cleanNavigationBarHeight: cleanNavigationBarHeight, insets: insets, isReorderingFilters: isReorderingFilters, isEditing: isEditing, inlineNavigationLocation: inlineNavigationLocation, inlineNavigationTransitionFraction: inlineNavigationTransitionFraction, storiesInset: storiesInset, transition: transition) self.currentItemFilterUpdated?(self.currentItemFilter, self.transitionFraction, transition, false) + self.pinnedHeaderDisplayFractionUpdated?(transition) itemNode.emptyNode?.restartAnimation() completion?() } else if self.pendingItemNode == nil { @@ -889,6 +930,7 @@ public final class ChatListContainerNode: ASDisplayNode, ASGestureRecognizerDele strongSelf.selectedId = id strongSelf.applyItemNodeAsCurrent(id: id, itemNode: itemNode) strongSelf.currentItemFilterUpdated?(strongSelf.currentItemFilter, strongSelf.transitionFraction, .immediate, false) + strongSelf.pinnedHeaderDisplayFractionUpdated?(.immediate) completion?() return @@ -945,6 +987,7 @@ public final class ChatListContainerNode: ASDisplayNode, ASGestureRecognizerDele strongSelf.update(layout: layout, navigationBarHeight: navigationBarHeight, visualNavigationHeight: visualNavigationHeight, originalNavigationHeight: originalNavigationHeight, cleanNavigationBarHeight: cleanNavigationBarHeight, insets: insets, isReorderingFilters: isReorderingFilters, isEditing: isEditing, inlineNavigationLocation: inlineNavigationLocation, inlineNavigationTransitionFraction: inlineNavigationTransitionFraction, storiesInset: storiesInset, transition: .immediate) strongSelf.currentItemFilterUpdated?(strongSelf.currentItemFilter, strongSelf.transitionFraction, transition, false) + strongSelf.pinnedHeaderDisplayFractionUpdated?(transition) } completion?() @@ -1095,6 +1138,7 @@ final class ChatListControllerNode: ASDisplayNode, ASGestureRecognizerDelegate { private var tapRecognizer: UITapGestureRecognizer? var navigationBar: NavigationBar? let navigationBarView = ComponentView() + let sgFoldersView = ComponentView() weak var controller: ChatListControllerImpl? var toolbar: Toolbar? @@ -1171,12 +1215,16 @@ final class ChatListControllerNode: ASDisplayNode, ASGestureRecognizerDelegate { self.addSubnode(self.mainContainerNode) + self.mainContainerNode.contentOffsetChanged = { [weak self] offset, listView in self?.contentOffsetChanged(offset: offset, listView: listView, isPrimary: true) } self.mainContainerNode.contentScrollingEnded = { [weak self] listView in return self?.contentScrollingEnded(listView: listView, isPrimary: true) ?? false } + self.mainContainerNode.pinnedHeaderDisplayFractionUpdated = { [weak self] transition in + self?.pinnedHeaderDisplayFractionUpdated(transition: transition) + } self.mainContainerNode.didBeginInteractiveDragging = { [weak self] listView in self?.didBeginInteractiveDragging(listView: listView, isPrimary: true) } @@ -1361,7 +1409,7 @@ final class ChatListControllerNode: ASDisplayNode, ASGestureRecognizerDelegate { } } - private func updateNavigationBar(layout: ContainerViewLayout, deferScrollApplication: Bool, transition: ComponentTransition) -> (navigationHeight: CGFloat, storiesInset: CGFloat) { + private func updateNavigationBar(layout: ContainerViewLayout, deferScrollApplication: Bool, transition: ComponentTransition) -> (tabs: AnyComponent?, navigationHeight: CGFloat, storiesInset: CGFloat) { let headerContent = self.controller?.updateHeaderContent() var panels: [HeaderPanelContainerComponent.Panel] = [] @@ -1379,6 +1427,8 @@ final class ChatListControllerNode: ASDisplayNode, ASGestureRecognizerDelegate { return } switch notice { + case let .sgUrl(id, _, _, url, needAuth, permanent): + self.effectiveContainerNode.currentItemNode.interaction?.openSGAnnouncement(id, url, needAuth, permanent) case .clearStorage: self.effectiveContainerNode.currentItemNode.interaction?.openStorageManagement() case .setupPassword: @@ -1457,8 +1507,8 @@ final class ChatListControllerNode: ASDisplayNode, ASGestureRecognizerDelegate { } var navigationHeaderPanels: AnyComponent? + var tabs: AnyComponent? // MARK: Swiftgram if self.controller?.tabContainerData != nil || !panels.isEmpty { - var tabs: AnyComponent? if let tabContainerData = self.controller?.tabContainerData, tabContainerData.0.count > 1 { let selectedTab: HorizontalTabsComponent.Tab.Id switch self.effectiveContainerNode.currentItemFilter { @@ -1481,7 +1531,7 @@ final class ChatListControllerNode: ASDisplayNode, ASGestureRecognizerDelegate { switch entry { case .all: id = Int32.min - title = HorizontalTabsComponent.Tab.Title(text: self.presentationData.strings.ChatList_Tabs_All, entities: [], enableAnimations: false) + title = HorizontalTabsComponent.Tab.Title(text: sgUseShortAllChatsTitle(true) ? self.presentationData.strings.ChatList_Tabs_All : self.presentationData.strings.ChatList_Tabs_AllChats, entities: [], enableAnimations: false) isMainTab = true case let .filter(idValue, text, unread): id = AnyHashable(idValue) @@ -1581,7 +1631,7 @@ final class ChatListControllerNode: ASDisplayNode, ASGestureRecognizerDelegate { navigationHeaderPanels = AnyComponent(HeaderPanelContainerComponent( theme: self.presentationData.theme, - tabs: tabs, + tabs: (self.controller?.tabContainerData?.1 ?? false) ? nil : tabs, // MARK: Swiftgram panels: panels )) } @@ -1663,9 +1713,9 @@ final class ChatListControllerNode: ASDisplayNode, ASGestureRecognizerDelegate { } transition.setFrame(view: navigationBarComponentView, frame: CGRect(origin: CGPoint(), size: navigationBarSize)) - return (navigationBarSize.height, 0.0) + return (tabs, navigationBarSize.height, 0.0) } else { - return (0.0, 0.0) + return (tabs, 0.0, 0.0) } } @@ -1772,6 +1822,21 @@ final class ChatListControllerNode: ASDisplayNode, ASGestureRecognizerDelegate { storiesInset = navigationBarLayout.storiesInset self.containerLayout = (layout, navigationBarHeight, visualNavigationHeight, cleanNavigationBarHeight, storiesInset) + + // MARK: Swiftgram + let sgComponentTransition = ComponentTransition(transition) + let sgDisplayTabsAtBottom = self.controller?.tabContainerData?.1 ?? false + let sgShouldDisplayBottomFolders = sgDisplayTabsAtBottom && self.isSearchDisplayControllerActive == nil + let sgFoldersSize = self.sgFoldersView.update( + transition: sgComponentTransition, + component: AnyComponent(HeaderPanelContainerComponent( + theme: self.presentationData.theme, + tabs: navigationBarLayout.tabs, + panels: [] + )), + environment: {}, + containerSize: layout.size + ) var insets = layout.insets(options: [.input]) insets.top += navigationBarHeight @@ -1826,6 +1891,11 @@ final class ChatListControllerNode: ASDisplayNode, ASGestureRecognizerDelegate { toolbarNode?.removeFromSupernode() }) } + + // MARK: Swiftgram + if sgShouldDisplayBottomFolders && sgFoldersSize.height > 0.0 { + insets.bottom += sgFoldersSize.height + 16.0 + 8.0 + } var childrenLayout = layout childrenLayout.intrinsicInsets = UIEdgeInsets(top: visualNavigationHeight, left: childrenLayout.intrinsicInsets.left, bottom: childrenLayout.intrinsicInsets.bottom, right: childrenLayout.intrinsicInsets.right) @@ -1890,6 +1960,41 @@ final class ChatListControllerNode: ASDisplayNode, ASGestureRecognizerDelegate { navigationBarComponentView.deferScrollApplication = false navigationBarComponentView.applyCurrentScroll(transition: ComponentTransition(transition)) } + + // MARK: Swiftgram + if let sgFoldersView = self.sgFoldersView.view as? HeaderPanelContainerComponent.View { + if sgShouldDisplayBottomFolders && sgFoldersSize.height > 0.0 { + if sgFoldersView.superview == nil { + self.view.addSubview(sgFoldersView) + if transition.isAnimated { + sgFoldersView.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.23) + } else { + sgFoldersView.alpha = 1.0 + } + } + + // Magic +// var heightInset: CGFloat = 0.0 +// if case .forum = self.location { +// heightInset = 4.0 +// } +// var tabBarHeight: CGFloat + let bottomInset: CGFloat = layout.insets(options: []).bottom +// if !layout.safeInsets.left.isZero { +// tabBarHeight = 34.0 + bottomInset +// } else { +// tabBarHeight = 49.0 - heightInset + bottomInset +// } + // + // TODO(swiftgram): + sgComponentTransition.setFrame(view: sgFoldersView, frame: CGRect(origin: CGPoint(x: 0.0, y: layout.size.height - bottomInset - sgFoldersSize.height - 16.0), size: sgFoldersSize)) + } else { + sgFoldersView.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, removeOnCompletion: false, completion: { [weak sgFoldersView] _ in + sgFoldersView?.removeFromSuperview() + }) + } + } + // } @MainActor @@ -2172,6 +2277,19 @@ final class ChatListControllerNode: ASDisplayNode, ASGestureRecognizerDelegate { return false } + private func pinnedHeaderDisplayFractionUpdated(transition: ContainedViewLayoutTransition) { + var pinnedFraction: CGFloat = 0.0 + if let inlineStackContainerNode = self.inlineStackContainerNode, self.inlineStackContainerTransitionFraction != 0.0 { + pinnedFraction = (1.0 - self.inlineStackContainerTransitionFraction) * self.mainContainerNode.pinnedHeaderDisplayFraction + self.inlineStackContainerTransitionFraction * inlineStackContainerNode.pinnedHeaderDisplayFraction + } else { + pinnedFraction = self.mainContainerNode.pinnedHeaderDisplayFraction + } + + if let navigationBarComponentView = self.navigationBarView.view as? ChatListNavigationBar.View { + navigationBarComponentView.updateEdgeEffectForPinnedFraction(pinnedFraction: pinnedFraction, transition: ComponentTransition(transition)) + } + } + func makeInlineChatList(location: ChatListControllerLocation) -> ChatListContainerNode { var forumPeerId: EnginePeer.Id? if case let .forum(peerId) = location { @@ -2220,6 +2338,9 @@ final class ChatListControllerNode: ASDisplayNode, ASGestureRecognizerDelegate { inlineStackContainerNode.contentScrollingEnded = { [weak self] listView in return self?.contentScrollingEnded(listView: listView, isPrimary: false) ?? false } + inlineStackContainerNode.pinnedHeaderDisplayFractionUpdated = { [weak self] transition in + self?.pinnedHeaderDisplayFractionUpdated(transition: transition) + } inlineStackContainerNode.activateChatPreview = self.mainContainerNode.activateChatPreview inlineStackContainerNode.openStories = self.mainContainerNode.openStories diff --git a/submodules/ChatListUI/Sources/ChatListFilterPresetController.swift b/submodules/ChatListUI/Sources/ChatListFilterPresetController.swift index da255877..4a7b6938 100644 --- a/submodules/ChatListUI/Sources/ChatListFilterPresetController.swift +++ b/submodules/ChatListUI/Sources/ChatListFilterPresetController.swift @@ -1268,6 +1268,7 @@ private final class ChatListFilterPresetController: ItemListController { let presentationInterfaceState = ChatPresentationInterfaceState( chatWallpaper: .builtin(WallpaperSettings()), theme: presentationData.theme, + preferredGlassType: .default, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameDisplayOrder: presentationData.nameDisplayOrder, diff --git a/submodules/ChatListUI/Sources/ChatListSearchContainerNode.swift b/submodules/ChatListUI/Sources/ChatListSearchContainerNode.swift index 11af4ee9..98f1a6c5 100644 --- a/submodules/ChatListUI/Sources/ChatListSearchContainerNode.swift +++ b/submodules/ChatListUI/Sources/ChatListSearchContainerNode.swift @@ -1,4 +1,5 @@ import Foundation +import SGSimpleSettings import UIKit import AsyncDisplayKit import Display @@ -806,6 +807,9 @@ public final class ChatListSearchContainerNode: SearchDisplayControllerContentNo filtersInsets.bottom += 48.0 } + // TODO(swiftgram): too high if used from top bar + if !SGSimpleSettings.shared.showTabNames { filtersInsets.bottom += 16.0 } + transition.updateFrame(node: self.filterContainerNode, frame: CGRect(origin: CGPoint(x: layout.safeInsets.left + filtersInsets.left, y: layout.size.height - filtersInsets.bottom - 40.0), size: CGSize(width: layout.size.width - (layout.safeInsets.left + filtersInsets.left) * 2.0, height: 40.0))) self.updateFilterContainerNode(layout: layout, transition: transition) @@ -1174,7 +1178,7 @@ public final class ChatListSearchContainerNode: SearchDisplayControllerContentNo return items } - let controller = ContextController(presentationData: self.presentationData, source: .extracted(MessageContextExtractedContentSource(sourceNode: node, shouldBeDismissed: shouldBeDismissed)), items: items |> map { ContextController.Items(content: .list($0)) }, recognizer: nil, gesture: gesture) + let controller = makeContextController(presentationData: self.presentationData, source: .extracted(MessageContextExtractedContentSource(sourceNode: node, shouldBeDismissed: shouldBeDismissed)), items: items |> map { ContextController.Items(content: .list($0)) }, recognizer: nil, gesture: gesture) self.presentInGlobalOverlay?(controller, nil) return @@ -1248,7 +1252,7 @@ public final class ChatListSearchContainerNode: SearchDisplayControllerContentNo return items } - let controller = ContextController(presentationData: self.presentationData, source: .extracted(MessageContextExtractedContentSource(sourceNode: node)), items: items |> map { ContextController.Items(content: .list($0)) }, recognizer: nil, gesture: gesture) + let controller = makeContextController(presentationData: self.presentationData, source: .extracted(MessageContextExtractedContentSource(sourceNode: node)), items: items |> map { ContextController.Items(content: .list($0)) }, recognizer: nil, gesture: gesture) self.presentInGlobalOverlay?(controller, nil) } @@ -1312,7 +1316,7 @@ public final class ChatListSearchContainerNode: SearchDisplayControllerContentNo switch previewData { case let .gallery(gallery): gallery.setHintWillBePresentedInPreviewingContext(true) - let contextController = ContextController(presentationData: strongSelf.presentationData, source: .controller(ContextControllerContentSourceImpl(controller: gallery, sourceNode: node)), items: items |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) + let contextController = makeContextController(presentationData: strongSelf.presentationData, source: .controller(ContextControllerContentSourceImpl(controller: gallery, sourceNode: node)), items: items |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) strongSelf.presentInGlobalOverlay?(contextController, nil) case .instantPage: break diff --git a/submodules/ChatListUI/Sources/Node/ChatListItem.swift b/submodules/ChatListUI/Sources/Node/ChatListItem.swift index 35b8650c..c19553e4 100644 --- a/submodules/ChatListUI/Sources/Node/ChatListItem.swift +++ b/submodules/ChatListUI/Sources/Node/ChatListItem.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import AsyncDisplayKit @@ -704,7 +705,7 @@ private func revealOptions(strings: PresentationStrings, theme: PresentationThem } } } - if canDelete { + if canDelete && !SGSimpleSettings.shared.disableDeleteChatSwipeOption { options.append(ItemListRevealOption(key: RevealOptionKey.delete.rawValue, title: strings.Common_Delete, icon: deleteIcon, color: theme.list.itemDisclosureActions.destructive.fillColor, textColor: theme.list.itemDisclosureActions.destructive.foregroundColor)) } if case .savedMessagesChats = location { @@ -792,7 +793,7 @@ private func forumThreadRevealOptions(strings: PresentationStrings, theme: Prese } } } - if canDelete { + if canDelete && !SGSimpleSettings.shared.disableDeleteChatSwipeOption { options.append(ItemListRevealOption(key: RevealOptionKey.delete.rawValue, title: strings.Common_Delete, icon: deleteIcon, color: theme.list.itemDisclosureActions.destructive.fillColor, textColor: theme.list.itemDisclosureActions.destructive.foregroundColor)) } if canOpenClose { @@ -1756,7 +1757,10 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { } else if case let .groupReference(groupReference) = item.content { storyState = groupReference.storyState } - + // MARK: Swiftgram + let sgCompactChatList = SGSimpleSettings.shared.compactChatList + let sgCompactMessagePreview = SGCompactMessagePreviewLayout.isEnabled() + let sgAvatarScaleDivisor: CGFloat = SGCompactMessagePreviewLayout.avatarScaleDivisor(compactChatList: sgCompactChatList, compactMessagePreview: sgCompactMessagePreview) var peer: EnginePeer? var displayAsMessage = false var enablePreview = true @@ -1917,8 +1921,8 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { isForumAvatar = true } } - - var avatarDiameter = min(60.0, floor(item.presentationData.fontSize.baseDisplaySize * 60.0 / 17.0)) + // MARK: Swiftgram + var avatarDiameter = min(60.0, floor(item.presentationData.fontSize.baseDisplaySize * 60.0 / 17.0)) / sgAvatarScaleDivisor if case let .peer(peerData) = item.content, let customMessageListData = peerData.customMessageListData, customMessageListData.commandPrefix != nil { avatarDiameter = 40.0 @@ -2169,6 +2173,12 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { let currentChatListQuoteSearchResult = self.cachedChatListQuoteSearchResult let currentCustomTextEntities = self.cachedCustomTextEntities + + // MARK: Swiftgram + let sgCompactChatList = SGSimpleSettings.shared.compactChatList + let sgCompactMessagePreview = SGCompactMessagePreviewLayout.isEnabled() + let sgAvatarScaleDivisor: CGFloat = SGCompactMessagePreviewLayout.avatarScaleDivisor(compactChatList: sgCompactChatList, compactMessagePreview: sgCompactMessagePreview) + return { item, params, first, last, firstWithHeader, nextIsPinned in let titleFont = Font.medium(floor(item.presentationData.fontSize.itemListBaseFontSize * 16.0 / 17.0)) let textFont = Font.regular(floor(item.presentationData.fontSize.itemListBaseFontSize * 15.0 / 17.0)) @@ -2427,9 +2437,9 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { } let enableChatListPhotos = true - + // MARK: Swiftgram // if changed, adjust setupItem accordingly - var avatarDiameter = min(60.0, floor(item.presentationData.fontSize.baseDisplaySize * 60.0 / 17.0)) + var avatarDiameter = min(60.0, floor(item.presentationData.fontSize.baseDisplaySize * 60.0 / 17.0)) / sgAvatarScaleDivisor let avatarLeftInset: CGFloat if case let .peer(peerData) = item.content, let customMessageListData = peerData.customMessageListData, customMessageListData.commandPrefix != nil { @@ -2497,7 +2507,9 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { contentData = .group(peers: groupPeers) hideAuthor = true } - + // MARK: Swiftgram + let sgInlineAuthorPrefix = sgCompactMessagePreview && !hideAuthor + if sgCompactChatList || sgCompactMessagePreview { hideAuthor = true }; var attributedText: NSAttributedString var hasDraft = false @@ -2525,7 +2537,8 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { } } } - + // MARK: Swiftgram + if sgCompactChatList || sgInlineAuthorPrefix { useInlineAuthorPrefix = true }; if useInlineAuthorPrefix { if case let .user(author) = messages.last?.author { if author.id == item.context.account.peerId { @@ -3590,12 +3603,22 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { textMaxWidth -= 18.0 } - let (textLayout, textApply) = textLayout(TextNodeLayoutArguments(attributedString: textAttributedString, backgroundColor: nil, maximumNumberOfLines: (authorAttributedString == nil && itemTags.isEmpty && forumThread == nil && topForumTopicItems.isEmpty) ? 2 : 1, truncationType: .end, constrainedSize: CGSize(width: textMaxWidth, height: CGFloat.greatestFiniteMagnitude), alignment: .natural, cutout: textCutout, insets: UIEdgeInsets(top: 2.0, left: 1.0, bottom: 2.0, right: 1.0))) + // MARK: Swiftgram + let sgChatListMaxLines: Int + if sgCompactMessagePreview { + sgChatListMaxLines = 1 + } else { + sgChatListMaxLines = (authorAttributedString == nil && itemTags.isEmpty && forumThread == nil && topForumTopicItems.isEmpty && !sgCompactChatList) ? 2 : 1 + } + let (textLayout, textApply) = textLayout(TextNodeLayoutArguments(attributedString: textAttributedString, backgroundColor: nil, maximumNumberOfLines: sgChatListMaxLines, truncationType: .end, constrainedSize: CGSize(width: textMaxWidth, height: CGFloat.greatestFiniteMagnitude), alignment: .natural, cutout: textCutout, insets: UIEdgeInsets(top: 2.0, left: 1.0, bottom: 2.0, right: 1.0))) let maxTitleLines: Int switch item.index { case .forum: + // MARK: Swiftgram + if sgCompactChatList { maxTitleLines = 1 } else { maxTitleLines = 2 + } case .chatList: maxTitleLines = 1 } @@ -3722,6 +3745,8 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { peerRevealOptions = [ ItemListRevealOption(key: RevealOptionKey.hidePsa.rawValue, title: item.presentationData.strings.ChatList_HideAction, icon: deleteIcon, color: item.presentationData.theme.list.itemDisclosureActions.inactive.fillColor, textColor: item.presentationData.theme.list.itemDisclosureActions.neutral1.foregroundColor) ] + // MARK: Swiftgram + if SGSimpleSettings.shared.disableDeleteChatSwipeOption { peerRevealOptions.removeLast() } peerLeftRevealOptions = [] } else if case let .peer(peerData) = item.content, let customMessageListData = peerData.customMessageListData { peerLeftRevealOptions = [] @@ -3730,6 +3755,8 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { ItemListRevealOption(key: RevealOptionKey.edit.rawValue, title: item.presentationData.strings.ChatList_ItemMenuEdit, icon: .none, color: item.presentationData.theme.list.itemDisclosureActions.neutral2.fillColor, textColor: item.presentationData.theme.list.itemDisclosureActions.neutral2.foregroundColor), ItemListRevealOption(key: RevealOptionKey.delete.rawValue, title: item.presentationData.strings.ChatList_ItemMenuDelete, icon: .none, color: item.presentationData.theme.list.itemDisclosureActions.destructive.fillColor, textColor: item.presentationData.theme.list.itemDisclosureActions.destructive.foregroundColor) ] + // MARK: Swiftgram + if SGSimpleSettings.shared.disableDeleteChatSwipeOption { peerRevealOptions.removeLast() } } else { peerRevealOptions = [] } @@ -3772,6 +3799,16 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { peerRevealOptions = [] peerLeftRevealOptions = [] } + // MARK: Swiftgram + if sgCompactChatList { + peerRevealOptions = peerRevealOptions.map { option in + ItemListRevealOption(key: option.key, title: option.title, icon: .none, color: option.color, textColor: option.textColor) + } + peerLeftRevealOptions = peerLeftRevealOptions.map { option in + ItemListRevealOption(key: option.key, title: option.title, icon: .none, color: option.color, textColor: option.textColor) + } + } + // let (onlineLayout, onlineApply) = onlineLayout(online, onlineIsVoiceChat) var animateContent = false @@ -3794,7 +3831,8 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { itemHeight += titleSpacing itemHeight += authorSpacing } - + // MARK: Swiftgram + itemHeight = itemHeight / (sgCompactChatList ? 1.5 : 1.0) let rawContentRect = CGRect(origin: CGPoint(x: 2.0, y: layoutOffset + floor(item.presentationData.fontSize.itemListBaseFontSize * 8.0 / 17.0)), size: CGSize(width: rawContentWidth, height: itemHeight - 12.0 - 9.0)) let insets = ChatListItemNode.insets(first: first, last: last, firstWithHeader: firstWithHeader) @@ -3952,7 +3990,8 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { var avatarScaleOffset: CGFloat = 0.0 var avatarScale: CGFloat = 1.0 if let inlineNavigationLocation = item.interaction.inlineNavigationLocation { - let targetAvatarScale: CGFloat = floor(item.presentationData.fontSize.itemListBaseFontSize * 54.0 / 17.0) / avatarFrame.width + // MARK: Swiftgram + let targetAvatarScale: CGFloat = floor(item.presentationData.fontSize.itemListBaseFontSize * 54.0 / 17.0) / sgAvatarScaleDivisor / avatarFrame.width avatarScale = targetAvatarScale * inlineNavigationLocation.progress + 1.0 * (1.0 - inlineNavigationLocation.progress) let targetAvatarScaleOffset: CGFloat = -(avatarFrame.width - avatarFrame.width * avatarScale) * 0.5 @@ -4305,16 +4344,19 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { strongSelf.statusNode.fontSize = item.presentationData.fontSize.itemListBaseFontSize let _ = strongSelf.statusNode.transitionToState(statusState, animated: animateContent) + // MARK: Swiftgram + let sizeFactor = item.presentationData.fontSize.itemListBaseFontSize / 17.0 + let sgCompactMessagePreviewBadgeOffset = SGCompactMessagePreviewLayout.badgeOffset(sizeFactor: sizeFactor, compactMessagePreview: sgCompactMessagePreview, compactChatList: sgCompactChatList) + var nextBadgeX: CGFloat = contentRect.maxX if let _ = currentBadgeBackgroundImage { - let badgeFrame = CGRect(x: nextBadgeX - badgeLayout.width, y: contentRect.maxY - badgeLayout.height - 2.0, width: badgeLayout.width, height: badgeLayout.height) + let badgeFrame = CGRect(x: nextBadgeX - badgeLayout.width, y: contentRect.maxY - badgeLayout.height - 2.0 + (sgCompactChatList ? 13.0 / sizeFactor : 0.0) - sgCompactMessagePreviewBadgeOffset, width: badgeLayout.width, height: badgeLayout.height) transition.updateFrame(node: strongSelf.badgeNode, frame: badgeFrame) nextBadgeX -= badgeLayout.width + 6.0 } - if currentMentionBadgeImage != nil || currentBadgeBackgroundImage != nil { - let badgeFrame = CGRect(x: nextBadgeX - mentionBadgeLayout.width, y: contentRect.maxY - mentionBadgeLayout.height - 2.0, width: mentionBadgeLayout.width, height: mentionBadgeLayout.height) + let badgeFrame = CGRect(x: nextBadgeX - mentionBadgeLayout.width, y: contentRect.maxY - mentionBadgeLayout.height - 2.0 + (sgCompactChatList ? 13.0 / sizeFactor : 0.0) - sgCompactMessagePreviewBadgeOffset, width: mentionBadgeLayout.width, height: mentionBadgeLayout.height) transition.updateFrame(node: strongSelf.mentionBadgeNode, frame: badgeFrame) nextBadgeX -= mentionBadgeLayout.width + 6.0 @@ -4325,7 +4367,7 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { strongSelf.pinnedIconNode.isHidden = false let pinnedIconSize = currentPinnedIconImage.size - let pinnedIconFrame = CGRect(x: nextBadgeX - pinnedIconSize.width, y: contentRect.maxY - pinnedIconSize.height - 2.0, width: pinnedIconSize.width, height: pinnedIconSize.height) + let pinnedIconFrame = CGRect(x: nextBadgeX - pinnedIconSize.width, y: contentRect.maxY - pinnedIconSize.height - 2.0 + (sgCompactChatList ? 13.0 / sizeFactor : 0.0) - sgCompactMessagePreviewBadgeOffset, width: pinnedIconSize.width, height: pinnedIconSize.height) strongSelf.pinnedIconNode.frame = pinnedIconFrame nextBadgeX -= pinnedIconSize.width + 6.0 @@ -4339,7 +4381,17 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { let actionButtonTopInset = floor(item.presentationData.fontSize.itemListBaseFontSize * 5.0 / 17.0) let actionButtonBottomInset = floor(item.presentationData.fontSize.itemListBaseFontSize * 4.0 / 17.0) - let actionButtonSize = CGSize(width: actionButtonTitleNodeLayout.size.width + actionButtonSideInset * 2.0, height: actionButtonTitleNodeLayout.size.height + actionButtonTopInset + actionButtonBottomInset) + var actionButtonSize = CGSize(width: actionButtonTitleNodeLayout.size.width + actionButtonSideInset * 2.0, height: actionButtonTitleNodeLayout.size.height + actionButtonTopInset + actionButtonBottomInset) + // MARK: Swiftgram + let sgActionButtonScaleDivisor: CGFloat = sgCompactChatList ? 1.5 : 1.0 + if sgCompactChatList { + let sgCompactActionButtonSideInset = floor(item.presentationData.fontSize.itemListBaseFontSize * 3.0 / 17.0) + actionButtonSize.width = max(actionButtonSize.width / sgActionButtonScaleDivisor, actionButtonTitleNodeLayout.size.width + sgCompactActionButtonSideInset * 2.0) + } else { + actionButtonSize.width = actionButtonSize.width / sgActionButtonScaleDivisor + } + actionButtonSize.height = actionButtonSize.height / sgActionButtonScaleDivisor + // var actionButtonFrame = CGRect(x: nextBadgeX - actionButtonSize.width, y: contentRect.minY + floor((contentRect.height - actionButtonSize.height) * 0.5), width: actionButtonSize.width, height: actionButtonSize.height) actionButtonFrame.origin.y = max(actionButtonFrame.origin.y, dateFrame.maxY + floor(item.presentationData.fontSize.itemListBaseFontSize * 4.0 / 17.0)) @@ -4377,7 +4429,8 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { actionButtonNode.frame = actionButtonFrame actionButtonBackgroundView.frame = CGRect(origin: CGPoint(), size: actionButtonFrame.size) - actionButtonTitleNode.frame = CGRect(origin: CGPoint(x: floorToScreenPixels((actionButtonFrame.width - actionButtonTitleNodeLayout.size.width) * 0.5), y: actionButtonTopInset), size: actionButtonTitleNodeLayout.size) + let sgActionButtonTitleYOffset: CGFloat = sgCompactChatList ? floorToScreenPixels(1.0 * sizeFactor) : 0.0 + actionButtonTitleNode.frame = CGRect(origin: CGPoint(x: floorToScreenPixels(max(0.0, (actionButtonFrame.width - actionButtonTitleNodeLayout.size.width) * 0.5)), y: floorToScreenPixels((actionButtonFrame.height - actionButtonTitleNodeLayout.size.height) * 0.5 + sgActionButtonTitleYOffset)), size: actionButtonTitleNodeLayout.size) nextBadgeX -= actionButtonSize.width + 6.0 } else { @@ -4395,6 +4448,10 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { } } + // MARK: Swiftgram + let sgCompactMessagePreviewVerticalOffset: CGFloat = SGCompactMessagePreviewLayout.textVerticalOffset(sizeFactor: sizeFactor, compactMessagePreview: sgCompactMessagePreview, compactChatList: sgCompactChatList, hasAuthorLine: !authorLayout.height.isZero) + let sgCompactMessagePreviewTitleTextSpacing: CGFloat = SGCompactMessagePreviewLayout.titleTextSpacing(sizeFactor: sizeFactor, compactMessagePreview: sgCompactMessagePreview, compactChatList: sgCompactChatList, hasAuthorLine: !authorLayout.height.isZero) + // var titleOffset: CGFloat = titleLeftOffset if let currentSecretIconImage = currentSecretIconImage { let iconNode: ASImageNode @@ -4409,7 +4466,7 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { strongSelf.secretIconNode = iconNode } iconNode.image = currentSecretIconImage - transition.updateFrame(node: iconNode, frame: CGRect(origin: CGPoint(x: contentRect.origin.x + titleLeftOffset, y: contentRect.origin.y + floor((titleLayout.size.height - currentSecretIconImage.size.height) / 2.0)), size: currentSecretIconImage.size)) + transition.updateFrame(node: iconNode, frame: CGRect(origin: CGPoint(x: contentRect.origin.x + titleLeftOffset, y: contentRect.origin.y + floor((titleLayout.size.height - currentSecretIconImage.size.height) / 2.0) + sgCompactMessagePreviewVerticalOffset), size: currentSecretIconImage.size)) titleOffset += currentSecretIconImage.size.width + 3.0 } else if let secretIconNode = strongSelf.secretIconNode { strongSelf.secretIconNode = nil @@ -4417,12 +4474,12 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { } let contentDelta = CGPoint(x: contentRect.origin.x - (strongSelf.titleNode.frame.minX - titleOffset), y: contentRect.origin.y - (strongSelf.titleNode.frame.minY - UIScreenPixel)) - let titleFrame = CGRect(origin: CGPoint(x: contentRect.origin.x + titleOffset, y: contentRect.origin.y + UIScreenPixel), size: titleLayout.size) + let titleFrame = CGRect(origin: CGPoint(x: contentRect.origin.x + titleOffset, y: contentRect.origin.y + UIScreenPixel + sgCompactMessagePreviewVerticalOffset), size: titleLayout.size) strongSelf.titleNode.frame = titleFrame - let authorNodeFrame = CGRect(origin: CGPoint(x: contentRect.origin.x - 1.0, y: contentRect.minY + titleLayout.size.height), size: authorLayout) + let authorNodeFrame = CGRect(origin: CGPoint(x: contentRect.origin.x - 1.0, y: contentRect.minY + titleLayout.size.height + sgCompactMessagePreviewVerticalOffset), size: authorLayout) strongSelf.authorNode.frame = authorNodeFrame - let textNodeFrame = CGRect(origin: CGPoint(x: contentRect.origin.x - 1.0, y: contentRect.minY + titleLayout.size.height - 1.0 + UIScreenPixel + (authorLayout.height.isZero ? 0.0 : (authorLayout.height - 3.0))), size: textLayout.size) + let textNodeFrame = CGRect(origin: CGPoint(x: contentRect.origin.x - 1.0, y: contentRect.minY + titleLayout.size.height - 1.0 + UIScreenPixel + (authorLayout.height.isZero ? 0.0 : (authorLayout.height - 3.0)) + sgCompactMessagePreviewVerticalOffset + sgCompactMessagePreviewTitleTextSpacing), size: textLayout.size) if let topForumTopicRect, !isSearching { let compoundHighlightingNode: LinkHighlightingNode @@ -4604,8 +4661,11 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { if !itemTags.isEmpty { let sizeFactor = item.presentationData.fontSize.itemListBaseFontSize / 17.0 + // MARK: Swiftgram + let sgCompactMessagePreviewTagListOffset = max(0.0, SGCompactMessagePreviewLayout.textBlockOffset(sizeFactor: sizeFactor, compactMessagePreview: sgCompactMessagePreview, compactChatList: sgCompactChatList, hasAuthorLine: false) - floorToScreenPixels(4.0 * sizeFactor)) + // - let itemTagListFrame = CGRect(origin: CGPoint(x: contentRect.minX, y: contentRect.minY + measureLayout.size.height * 2.0 + floorToScreenPixels(2.0 * sizeFactor)), size: CGSize(width: contentRect.width, height: floorToScreenPixels(20.0 * sizeFactor))) + let itemTagListFrame = CGRect(origin: CGPoint(x: contentRect.minX, y: contentRect.minY + measureLayout.size.height * 2.0 + floorToScreenPixels(2.0 * sizeFactor) + sgCompactMessagePreviewTagListOffset), size: CGSize(width: contentRect.width, height: floorToScreenPixels(20.0 * sizeFactor))) var itemTagListTransition = transition let itemTagList: ComponentView @@ -5092,7 +5152,7 @@ public class ChatListItemNode: ItemListRevealOptionsItemNode { strongSelf.updateLayout(size: CGSize(width: layout.contentSize.width, height: itemHeight), leftInset: params.leftInset, rightInset: params.rightInset) - if item.editing { + if item.editing || SGSimpleSettings.shared.disableChatSwipeOptions { strongSelf.setRevealOptions((left: [], right: []), enableAnimations: item.context.sharedContext.energyUsageSettings.fullTranslucency) } else { strongSelf.setRevealOptions((left: peerLeftRevealOptions, right: peerRevealOptions), enableAnimations: item.context.sharedContext.energyUsageSettings.fullTranslucency) diff --git a/submodules/ChatListUI/Sources/Node/ChatListNoticeItem.swift b/submodules/ChatListUI/Sources/Node/ChatListNoticeItem.swift index 4833aefa..fcd04a51 100644 --- a/submodules/ChatListUI/Sources/Node/ChatListNoticeItem.swift +++ b/submodules/ChatListUI/Sources/Node/ChatListNoticeItem.swift @@ -190,6 +190,10 @@ final class ChatListNoticeItemNode: ItemListRevealOptionsItemNode { var alignment: NSTextAlignment = .left switch item.notice { + case let .sgUrl(_, title, text, _, _, _): + let titleStringValue = NSMutableAttributedString(attributedString: NSAttributedString(string: title, font: titleFont, textColor: item.theme.rootController.navigationBar.primaryTextColor)) + titleString = titleStringValue + textString = NSAttributedString(string: text ?? "", font: textFont, textColor: item.theme.rootController.navigationBar.secondaryTextColor) case let .clearStorage(sizeFraction): let sizeString = dataSizeString(Int64(sizeFraction), formatting: DataSizeStringFormatting(strings: item.strings, decimalSeparator: ".")) let rawTitleString = item.strings.ChatList_StorageHintTitle(sizeString) diff --git a/submodules/ChatPresentationInterfaceState/BUILD b/submodules/ChatPresentationInterfaceState/BUILD index 3ca6b4d9..7c97be95 100644 --- a/submodules/ChatPresentationInterfaceState/BUILD +++ b/submodules/ChatPresentationInterfaceState/BUILD @@ -1,5 +1,9 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + swift_library( name = "ChatPresentationInterfaceState", module_name = "ChatPresentationInterfaceState", @@ -9,7 +13,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", "//submodules/AsyncDisplayKit:AsyncDisplayKit", "//submodules/Display:Display", diff --git a/submodules/ChatPresentationInterfaceState/Sources/ChatPanelInterfaceInteraction.swift b/submodules/ChatPresentationInterfaceState/Sources/ChatPanelInterfaceInteraction.swift index 54e4686d..2a393a1d 100644 --- a/submodules/ChatPresentationInterfaceState/Sources/ChatPanelInterfaceInteraction.swift +++ b/submodules/ChatPresentationInterfaceState/Sources/ChatPanelInterfaceInteraction.swift @@ -72,6 +72,8 @@ public final class ChatPanelInterfaceInteraction { } public let setupReplyMessage: (MessageId?, Int32?, @escaping (ContainedViewLayoutTransition, @escaping () -> Void) -> Void) -> Void + public let sgSelectLastWordIfIdle: () -> Void + public let sgSetNewLine: () -> Void public let setupEditMessage: (MessageId?, @escaping (ContainedViewLayoutTransition) -> Void) -> Void public let beginMessageSelection: ([MessageId], @escaping (ContainedViewLayoutTransition) -> Void) -> Void public let cancelMessageSelection: (ContainedViewLayoutTransition) -> Void @@ -80,9 +82,9 @@ public final class ChatPanelInterfaceInteraction { public let reportMessages: ([Message], ContextControllerProtocol?) -> Void public let blockMessageAuthor: (Message, ContextControllerProtocol?) -> Void public let deleteMessages: ([Message], ContextControllerProtocol?, @escaping (ContextMenuActionResult) -> Void) -> Void - public let forwardSelectedMessages: () -> Void + public let forwardSelectedMessages: (String?) -> Void public let forwardCurrentForwardMessages: () -> Void - public let forwardMessages: ([Message]) -> Void + public let forwardMessages: ([Message], String?) -> Void public let updateForwardOptionsState: ((ChatInterfaceForwardOptionsState) -> ChatInterfaceForwardOptionsState) -> Void public let presentForwardOptions: (UIView) -> Void public let presentReplyOptions: (UIView) -> Void @@ -208,9 +210,9 @@ public final class ChatPanelInterfaceInteraction { reportMessages: @escaping ([Message], ContextControllerProtocol?) -> Void, blockMessageAuthor: @escaping (Message, ContextControllerProtocol?) -> Void, deleteMessages: @escaping ([Message], ContextControllerProtocol?, @escaping (ContextMenuActionResult) -> Void) -> Void, - forwardSelectedMessages: @escaping () -> Void, + forwardSelectedMessages: @escaping (String?) -> Void, forwardCurrentForwardMessages: @escaping () -> Void, - forwardMessages: @escaping ([Message]) -> Void, + forwardMessages: @escaping ([Message], String?) -> Void, updateForwardOptionsState: @escaping ((ChatInterfaceForwardOptionsState) -> ChatInterfaceForwardOptionsState) -> Void, presentForwardOptions: @escaping (UIView) -> Void, presentReplyOptions: @escaping (UIView) -> Void, @@ -453,6 +455,93 @@ public final class ChatPanelInterfaceInteraction { self.chatController = chatController self.statuses = statuses + + // MARK: Swiftgram + self.sgSelectLastWordIfIdle = { + updateTextInputStateAndMode { current, inputMode in + // No changes to current selection + if !current.selectionRange.isEmpty { + return (current, inputMode) + } + + let inputText = (current.inputText.mutableCopy() as? NSMutableAttributedString) ?? NSMutableAttributedString() + + // If text is empty or cursor is at the start, return current state + guard inputText.length > 0, current.selectionRange.lowerBound > 0 else { + return (current, inputMode) + } + + let plainText = inputText.string + let nsString = plainText as NSString + + // Create character set for word boundaries + let wordBoundaries = CharacterSet.whitespacesAndNewlines + + // Start from cursor position instead of end of text + var endIndex = current.selectionRange.lowerBound - 1 + + // Find last non-whitespace character before cursor + while endIndex >= 0 && + (nsString.substring(with: NSRange(location: endIndex, length: 1)) as NSString) + .rangeOfCharacter(from: wordBoundaries).location != NSNotFound { + endIndex -= 1 + } + + // If we only had whitespace before cursor, return current state + guard endIndex >= 0 else { + return (current, inputMode) + } + + // Find start of the current word by looking backwards for whitespace + var startIndex = endIndex + while startIndex > 0 { + let char = nsString.substring(with: NSRange(location: startIndex - 1, length: 1)) + if (char as NSString).rangeOfCharacter(from: wordBoundaries).location != NSNotFound { + break + } + startIndex -= 1 + } + + // Create range for the word at cursor + let wordLength = endIndex - startIndex + 1 + let wordRange = NSRange(location: startIndex, length: wordLength) + + // Create new selection range + let newSelectionRange = wordRange.location ..< (wordRange.location + wordLength) + + return (ChatTextInputState(inputText: inputText, selectionRange: newSelectionRange), inputMode) + } + } + self.sgSetNewLine = { + updateTextInputStateAndMode { current, inputMode in + let inputText = (current.inputText.mutableCopy() as? NSMutableAttributedString) ?? NSMutableAttributedString() + + // Check if there's selected text + let hasSelection = current.selectionRange.count > 0 + + if hasSelection { + // Move selected text to new line + let selectedText = inputText.attributedSubstring(from: NSRange(current.selectionRange)) + let newLineAttr = NSAttributedString(string: "\n") + + // Insert newline and selected text + inputText.replaceCharacters(in: NSRange(current.selectionRange), with: newLineAttr) + inputText.insert(selectedText, at: current.selectionRange.lowerBound + 1) + + // Update selection range to end of moved text + let newPosition = current.selectionRange.lowerBound + 1 + selectedText.length + return (ChatTextInputState(inputText: inputText, selectionRange: newPosition ..< newPosition), inputMode) + } else { + // Simple newline insertion at current position + let attributedString = NSAttributedString(string: "\n") + inputText.replaceCharacters(in: NSRange(current.selectionRange), with: attributedString) + + // Update cursor position + let newPosition = current.selectionRange.lowerBound + attributedString.length + return (ChatTextInputState(inputText: inputText, selectionRange: newPosition ..< newPosition), inputMode) + } + } + } } public convenience init( @@ -470,9 +559,9 @@ public final class ChatPanelInterfaceInteraction { }, blockMessageAuthor: { _, _ in }, deleteMessages: { _, _, f in f(.default) - }, forwardSelectedMessages: { + }, forwardSelectedMessages: { _ in }, forwardCurrentForwardMessages: { - }, forwardMessages: { _ in + }, forwardMessages: { _, _ in }, updateForwardOptionsState: { _ in }, presentForwardOptions: { _ in }, presentReplyOptions: { _ in diff --git a/submodules/ChatPresentationInterfaceState/Sources/ChatPresentationInterfaceState.swift b/submodules/ChatPresentationInterfaceState/Sources/ChatPresentationInterfaceState.swift index b6134692..81db881c 100644 --- a/submodules/ChatPresentationInterfaceState/Sources/ChatPresentationInterfaceState.swift +++ b/submodules/ChatPresentationInterfaceState/Sources/ChatPresentationInterfaceState.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import SwiftSignalKit @@ -468,6 +469,11 @@ public final class ChatPresentationInterfaceState: Equatable { } } + public enum GlassType { + case `default` + case clear + } + public let interfaceState: ChatInterfaceState public let chatLocation: ChatLocation public let renderedPeer: RenderedPeer? @@ -502,6 +508,7 @@ public final class ChatPresentationInterfaceState: Equatable { public let presentationReady: Bool public let chatWallpaper: TelegramWallpaper public let theme: PresentationTheme + public let preferredGlassType: GlassType public let strings: PresentationStrings public let dateTimeFormat: PresentationDateTimeFormat public let nameDisplayOrder: PresentationPersonNameOrder @@ -559,7 +566,7 @@ public final class ChatPresentationInterfaceState: Equatable { public let persistentData: PersistentPeerData public let removePaidMessageFeeData: RemovePaidMessageFeeData? - public init(chatWallpaper: TelegramWallpaper, theme: PresentationTheme, strings: PresentationStrings, dateTimeFormat: PresentationDateTimeFormat, nameDisplayOrder: PresentationPersonNameOrder, limitsConfiguration: LimitsConfiguration, fontSize: PresentationFontSize, bubbleCorners: PresentationChatBubbleCorners, accountPeerId: PeerId, mode: ChatControllerPresentationMode, chatLocation: ChatLocation, subject: ChatControllerSubject?, peerNearbyData: ChatPeerNearbyData?, greetingData: ChatGreetingData?, pendingUnpinnedAllMessages: Bool, activeGroupCallInfo: ChatActiveGroupCallInfo?, hasActiveGroupCall: Bool, threadData: ThreadData?, isGeneralThreadClosed: Bool?, replyMessage: Message?, accountPeerColor: AccountPeerColor?, businessIntro: TelegramBusinessIntro?) { + public init(chatWallpaper: TelegramWallpaper, theme: PresentationTheme, preferredGlassType: GlassType, strings: PresentationStrings, dateTimeFormat: PresentationDateTimeFormat, nameDisplayOrder: PresentationPersonNameOrder, limitsConfiguration: LimitsConfiguration, fontSize: PresentationFontSize, bubbleCorners: PresentationChatBubbleCorners, accountPeerId: PeerId, mode: ChatControllerPresentationMode, chatLocation: ChatLocation, subject: ChatControllerSubject?, peerNearbyData: ChatPeerNearbyData?, greetingData: ChatGreetingData?, pendingUnpinnedAllMessages: Bool, activeGroupCallInfo: ChatActiveGroupCallInfo?, hasActiveGroupCall: Bool, threadData: ThreadData?, isGeneralThreadClosed: Bool?, replyMessage: Message?, accountPeerColor: AccountPeerColor?, businessIntro: TelegramBusinessIntro?) { self.interfaceState = ChatInterfaceState() self.inputTextPanelState = ChatTextInputPanelState() self.editMessageState = nil @@ -594,6 +601,7 @@ public final class ChatPresentationInterfaceState: Equatable { self.chatWallpaper = chatWallpaper self.presentationReady = false self.theme = theme + self.preferredGlassType = preferredGlassType self.strings = strings self.dateTimeFormat = dateTimeFormat self.nameDisplayOrder = nameDisplayOrder @@ -654,7 +662,7 @@ public final class ChatPresentationInterfaceState: Equatable { self.removePaidMessageFeeData = nil } - public init(interfaceState: ChatInterfaceState, chatLocation: ChatLocation, renderedPeer: RenderedPeer?, isNotAccessible: Bool, explicitelyCanPinMessages: Bool, contactStatus: ChatContactStatus?, hasBots: Bool, isArchived: Bool, inputTextPanelState: ChatTextInputPanelState, editMessageState: ChatEditInterfaceMessageState?, inputQueryResults: [ChatPresentationInputQueryKind: ChatPresentationInputQueryResult], inputMode: ChatInputMode, titlePanelContexts: [ChatTitlePanelContext], keyboardButtonsMessage: Message?, pinnedMessageId: MessageId?, pinnedMessage: ChatPinnedMessage?, peerIsBlocked: Bool, peerIsMuted: Bool, peerDiscussionId: PeerId?, peerGeoLocation: PeerGeoLocation?, callsAvailable: Bool, callsPrivate: Bool, slowmodeState: ChatSlowmodeState?, chatHistoryState: ChatHistoryNodeHistoryState?, botStartPayload: String?, urlPreview: UrlPreview?, editingUrlPreview: UrlPreview?, search: ChatSearchData?, searchQuerySuggestionResult: ChatPresentationInputQueryResult?, historyFilter: HistoryFilter?, displayHistoryFilterAsList: Bool, presentationReady: Bool, chatWallpaper: TelegramWallpaper, theme: PresentationTheme, strings: PresentationStrings, dateTimeFormat: PresentationDateTimeFormat, nameDisplayOrder: PresentationPersonNameOrder, limitsConfiguration: LimitsConfiguration, fontSize: PresentationFontSize, bubbleCorners: PresentationChatBubbleCorners, accountPeerId: PeerId, mode: ChatControllerPresentationMode, hasScheduledMessages: Bool, autoremoveTimeout: Int32?, subject: ChatControllerSubject?, peerNearbyData: ChatPeerNearbyData?, greetingData: ChatGreetingData?, pendingUnpinnedAllMessages: Bool, activeGroupCallInfo: ChatActiveGroupCallInfo?, hasActiveGroupCall: Bool, reportReason: ReportReasonData?, showCommands: Bool, hasBotCommands: Bool, showSendAsPeers: Bool, sendAsPeers: [SendAsPeer]?, botMenuButton: BotMenuButton, showWebView: Bool, currentSendAsPeerId: PeerId?, copyProtectionEnabled: Bool, hasAtLeast3Messages: Bool, hasPlentyOfMessages: Bool, isPremium: Bool, premiumGiftOptions: [CachedPremiumGiftOption], suggestPremiumGift: Bool, forceInputCommandsHidden: Bool, voiceMessagesAvailable: Bool, customEmojiAvailable: Bool, threadData: ThreadData?, forumTopicData: ThreadData?, isGeneralThreadClosed: Bool?, translationState: ChatPresentationTranslationState?, replyMessage: Message?, accountPeerColor: AccountPeerColor?, savedMessagesTopicPeer: EnginePeer?, hasSearchTags: Bool, isPremiumRequiredForMessaging: Bool, sendPaidMessageStars: StarsAmount?, acknowledgedPaidMessage: Bool, hasSavedChats: Bool, appliedBoosts: Int32?, boostsToUnrestrict: Int32?, businessIntro: TelegramBusinessIntro?, hasBirthdayToday: Bool, adMessage: Message?, peerVerification: PeerVerification?, starGiftsAvailable: Bool, alwaysShowGiftButton: Bool, disallowedGifts: TelegramDisallowedGifts?, persistentData: PersistentPeerData, removePaidMessageFeeData: RemovePaidMessageFeeData?) { + public init(interfaceState: ChatInterfaceState, chatLocation: ChatLocation, renderedPeer: RenderedPeer?, isNotAccessible: Bool, explicitelyCanPinMessages: Bool, contactStatus: ChatContactStatus?, hasBots: Bool, isArchived: Bool, inputTextPanelState: ChatTextInputPanelState, editMessageState: ChatEditInterfaceMessageState?, inputQueryResults: [ChatPresentationInputQueryKind: ChatPresentationInputQueryResult], inputMode: ChatInputMode, titlePanelContexts: [ChatTitlePanelContext], keyboardButtonsMessage: Message?, pinnedMessageId: MessageId?, pinnedMessage: ChatPinnedMessage?, peerIsBlocked: Bool, peerIsMuted: Bool, peerDiscussionId: PeerId?, peerGeoLocation: PeerGeoLocation?, callsAvailable: Bool, callsPrivate: Bool, slowmodeState: ChatSlowmodeState?, chatHistoryState: ChatHistoryNodeHistoryState?, botStartPayload: String?, urlPreview: UrlPreview?, editingUrlPreview: UrlPreview?, search: ChatSearchData?, searchQuerySuggestionResult: ChatPresentationInputQueryResult?, historyFilter: HistoryFilter?, displayHistoryFilterAsList: Bool, presentationReady: Bool, chatWallpaper: TelegramWallpaper, theme: PresentationTheme, preferredGlassType: GlassType, strings: PresentationStrings, dateTimeFormat: PresentationDateTimeFormat, nameDisplayOrder: PresentationPersonNameOrder, limitsConfiguration: LimitsConfiguration, fontSize: PresentationFontSize, bubbleCorners: PresentationChatBubbleCorners, accountPeerId: PeerId, mode: ChatControllerPresentationMode, hasScheduledMessages: Bool, autoremoveTimeout: Int32?, subject: ChatControllerSubject?, peerNearbyData: ChatPeerNearbyData?, greetingData: ChatGreetingData?, pendingUnpinnedAllMessages: Bool, activeGroupCallInfo: ChatActiveGroupCallInfo?, hasActiveGroupCall: Bool, reportReason: ReportReasonData?, showCommands: Bool, hasBotCommands: Bool, showSendAsPeers: Bool, sendAsPeers: [SendAsPeer]?, botMenuButton: BotMenuButton, showWebView: Bool, currentSendAsPeerId: PeerId?, copyProtectionEnabled: Bool, hasAtLeast3Messages: Bool, hasPlentyOfMessages: Bool, isPremium: Bool, premiumGiftOptions: [CachedPremiumGiftOption], suggestPremiumGift: Bool, forceInputCommandsHidden: Bool, voiceMessagesAvailable: Bool, customEmojiAvailable: Bool, threadData: ThreadData?, forumTopicData: ThreadData?, isGeneralThreadClosed: Bool?, translationState: ChatPresentationTranslationState?, replyMessage: Message?, accountPeerColor: AccountPeerColor?, savedMessagesTopicPeer: EnginePeer?, hasSearchTags: Bool, isPremiumRequiredForMessaging: Bool, sendPaidMessageStars: StarsAmount?, acknowledgedPaidMessage: Bool, hasSavedChats: Bool, appliedBoosts: Int32?, boostsToUnrestrict: Int32?, businessIntro: TelegramBusinessIntro?, hasBirthdayToday: Bool, adMessage: Message?, peerVerification: PeerVerification?, starGiftsAvailable: Bool, alwaysShowGiftButton: Bool, disallowedGifts: TelegramDisallowedGifts?, persistentData: PersistentPeerData, removePaidMessageFeeData: RemovePaidMessageFeeData?) { self.interfaceState = interfaceState self.chatLocation = chatLocation self.renderedPeer = renderedPeer @@ -689,6 +697,7 @@ public final class ChatPresentationInterfaceState: Equatable { self.presentationReady = presentationReady self.chatWallpaper = chatWallpaper self.theme = theme + self.preferredGlassType = preferredGlassType self.strings = strings self.dateTimeFormat = dateTimeFormat self.nameDisplayOrder = nameDisplayOrder @@ -708,8 +717,13 @@ public final class ChatPresentationInterfaceState: Equatable { self.reportReason = reportReason self.showCommands = showCommands self.hasBotCommands = hasBotCommands + if SGSimpleSettings.shared.disableSendAsButton { + self.showSendAsPeers = false + self.sendAsPeers = nil + } else { self.showSendAsPeers = showSendAsPeers self.sendAsPeers = sendAsPeers + } self.botMenuButton = botMenuButton self.showWebView = showWebView self.currentSendAsPeerId = currentSendAsPeerId @@ -865,6 +879,9 @@ public final class ChatPresentationInterfaceState: Equatable { if lhs.theme !== rhs.theme { return false } + if lhs.preferredGlassType != rhs.preferredGlassType { + return false + } if lhs.strings !== rhs.strings { return false } @@ -1031,35 +1048,35 @@ public final class ChatPresentationInterfaceState: Equatable { } public func updatedInterfaceState(_ f: (ChatInterfaceState) -> ChatInterfaceState) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: f(self.interfaceState), chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: f(self.interfaceState), chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedChatLocation(_ chatLocation: ChatLocation) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedPeer(_ f: (RenderedPeer?) -> RenderedPeer?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: f(self.renderedPeer), isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: f(self.renderedPeer), isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedIsNotAccessible(_ isNotAccessible: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedExplicitelyCanPinMessages(_ explicitelyCanPinMessages: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedContactStatus(_ contactStatus: ChatContactStatus?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedHasBots(_ hasBots: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedIsArchived(_ isArchived: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedInputQueryResult(queryKind: ChatPresentationInputQueryKind, _ f: (ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult?) -> ChatPresentationInterfaceState { @@ -1076,307 +1093,311 @@ public final class ChatPresentationInterfaceState: Equatable { inputQueryResults.removeValue(forKey: queryKind) } - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedInputTextPanelState(_ f: (ChatTextInputPanelState) -> ChatTextInputPanelState) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: f(self.inputTextPanelState), editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: f(self.inputTextPanelState), editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedEditMessageState(_ editMessageState: ChatEditInterfaceMessageState?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedInputMode(_ f: (ChatInputMode) -> ChatInputMode) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: f(self.inputMode), titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: f(self.inputMode), titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedTitlePanelContext(_ f: ([ChatTitlePanelContext]) -> [ChatTitlePanelContext]) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: f(self.titlePanelContexts), keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: f(self.titlePanelContexts), keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedKeyboardButtonsMessage(_ message: Message?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: message, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: message, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedPinnedMessageId(_ pinnedMessageId: MessageId?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedPinnedMessage(_ pinnedMessage: ChatPinnedMessage?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedPeerIsBlocked(_ peerIsBlocked: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedPeerIsMuted(_ peerIsMuted: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedPeerDiscussionId(_ peerDiscussionId: PeerId?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedPeerGeoLocation(_ peerGeoLocation: PeerGeoLocation?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedCallsAvailable(_ callsAvailable: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedCallsPrivate(_ callsPrivate: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedSlowmodeState(_ slowmodeState: ChatSlowmodeState?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedBotStartPayload(_ botStartPayload: String?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedChatHistoryState(_ chatHistoryState: ChatHistoryNodeHistoryState?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedUrlPreview(_ urlPreview: UrlPreview?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedEditingUrlPreview(_ editingUrlPreview: UrlPreview?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedSearch(_ search: ChatSearchData?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedSearchQuerySuggestionResult(_ f: (ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: f(self.searchQuerySuggestionResult), historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: f(self.searchQuerySuggestionResult), historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedHistoryFilter(_ historyFilter: HistoryFilter?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedDisplayHistoryFilterAsList(_ displayHistoryFilterAsList: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedMode(_ mode: ChatControllerPresentationMode) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedPresentationReady(_ presentationReady: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedTheme(_ theme: PresentationTheme) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + } + + public func updatedPreferredGlassType(_ glassType: GlassType) -> ChatPresentationInterfaceState { + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: glassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedStrings(_ strings: PresentationStrings) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedDateTimeFormat(_ dateTimeFormat: PresentationDateTimeFormat) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedChatWallpaper(_ chatWallpaper: TelegramWallpaper) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedBubbleCorners(_ bubbleCorners: PresentationChatBubbleCorners) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedHasScheduledMessages(_ hasScheduledMessages: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedSubject(_ subject: ChatControllerSubject?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedAutoremoveTimeout(_ autoremoveTimeout: Int32?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedPendingUnpinnedAllMessages(_ pendingUnpinnedAllMessages: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedActiveGroupCallInfo(_ activeGroupCallInfo: ChatActiveGroupCallInfo?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedHasActiveGroupCall(_ hasActiveGroupCall: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedReportReason(_ reportReason: ReportReasonData?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedShowCommands(_ showCommands: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedHasBotCommands(_ hasBotCommands: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedShowSendAsPeers(_ showSendAsPeers: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedSendAsPeers(_ sendAsPeers: [SendAsPeer]?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedCurrentSendAsPeerId(_ currentSendAsPeerId: PeerId?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedBotMenuButton(_ botMenuButton: BotMenuButton) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedShowWebView(_ showWebView: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedCopyProtectionEnabled(_ copyProtectionEnabled: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedHasAtLeast3Messages(_ hasAtLeast3Messages: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedHasPlentyOfMessages(_ hasPlentyOfMessages: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedIsPremium(_ isPremium: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedPremiumGiftOptions(_ premiumGiftOptions: [CachedPremiumGiftOption]) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedSuggestPremiumGift(_ suggestPremiumGift: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedForceInputCommandsHidden(_ forceInputCommandsHidden: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedVoiceMessagesAvailable(_ voiceMessagesAvailable: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedCustomEmojiAvailable(_ customEmojiAvailable: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedThreadData(_ threadData: ThreadData?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedForumTopicData(_ forumTopicData: ThreadData?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedIsGeneralThreadClosed(_ isGeneralThreadClosed: Bool?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedTranslationState(_ translationState: ChatPresentationTranslationState?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedReplyMessage(_ replyMessage: Message?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedAccountPeerColor(_ accountPeerColor: AccountPeerColor?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedSavedMessagesTopicPeer(_ savedMessagesTopicPeer: EnginePeer?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedHasSearchTags(_ hasSearchTags: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedIsPremiumRequiredForMessaging(_ isPremiumRequiredForMessaging: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedSendPaidMessageStars(_ sendPaidMessageStars: StarsAmount?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedAcknowledgedPaidMessage(_ acknowledgedPaidMessage: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedHasSavedChats(_ hasSavedChats: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedAppliedBoosts(_ appliedBoosts: Int32?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedBoostsToUnrestrict(_ boostsToUnrestrict: Int32?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedBusinessIntro(_ businessIntro: TelegramBusinessIntro?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedHasBirthdayToday(_ hasBirthdayToday: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedAdMessage(_ adMessage: Message?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedPeerVerification(_ peerVerification: PeerVerification?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedStarGiftsAvailable(_ starGiftsAvailable: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedAlwaysShowGiftButton(_ alwaysShowGiftButton: Bool) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedDisallowedGifts(_ disallowedGifts: TelegramDisallowedGifts?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedPersistentData(_ persistentData: PersistentPeerData) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: persistentData, removePaidMessageFeeData: self.removePaidMessageFeeData) } public func updatedRemovePaidMessageFeeData(_ removePaidMessageFeeData: RemovePaidMessageFeeData?) -> ChatPresentationInterfaceState { - return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: removePaidMessageFeeData) + return ChatPresentationInterfaceState(interfaceState: self.interfaceState, chatLocation: self.chatLocation, renderedPeer: self.renderedPeer, isNotAccessible: self.isNotAccessible, explicitelyCanPinMessages: self.explicitelyCanPinMessages, contactStatus: self.contactStatus, hasBots: self.hasBots, isArchived: self.isArchived, inputTextPanelState: self.inputTextPanelState, editMessageState: self.editMessageState, inputQueryResults: self.inputQueryResults, inputMode: self.inputMode, titlePanelContexts: self.titlePanelContexts, keyboardButtonsMessage: self.keyboardButtonsMessage, pinnedMessageId: self.pinnedMessageId, pinnedMessage: self.pinnedMessage, peerIsBlocked: self.peerIsBlocked, peerIsMuted: self.peerIsMuted, peerDiscussionId: self.peerDiscussionId, peerGeoLocation: self.peerGeoLocation, callsAvailable: self.callsAvailable, callsPrivate: self.callsPrivate, slowmodeState: self.slowmodeState, chatHistoryState: self.chatHistoryState, botStartPayload: self.botStartPayload, urlPreview: self.urlPreview, editingUrlPreview: self.editingUrlPreview, search: self.search, searchQuerySuggestionResult: self.searchQuerySuggestionResult, historyFilter: self.historyFilter, displayHistoryFilterAsList: self.displayHistoryFilterAsList, presentationReady: self.presentationReady, chatWallpaper: self.chatWallpaper, theme: self.theme, preferredGlassType: self.preferredGlassType, strings: self.strings, dateTimeFormat: self.dateTimeFormat, nameDisplayOrder: self.nameDisplayOrder, limitsConfiguration: self.limitsConfiguration, fontSize: self.fontSize, bubbleCorners: self.bubbleCorners, accountPeerId: self.accountPeerId, mode: self.mode, hasScheduledMessages: self.hasScheduledMessages, autoremoveTimeout: self.autoremoveTimeout, subject: self.subject, peerNearbyData: self.peerNearbyData, greetingData: self.greetingData, pendingUnpinnedAllMessages: self.pendingUnpinnedAllMessages, activeGroupCallInfo: self.activeGroupCallInfo, hasActiveGroupCall: self.hasActiveGroupCall, reportReason: self.reportReason, showCommands: self.showCommands, hasBotCommands: self.hasBotCommands, showSendAsPeers: self.showSendAsPeers, sendAsPeers: self.sendAsPeers, botMenuButton: self.botMenuButton, showWebView: self.showWebView, currentSendAsPeerId: self.currentSendAsPeerId, copyProtectionEnabled: self.copyProtectionEnabled, hasAtLeast3Messages: self.hasAtLeast3Messages, hasPlentyOfMessages: self.hasPlentyOfMessages, isPremium: self.isPremium, premiumGiftOptions: self.premiumGiftOptions, suggestPremiumGift: self.suggestPremiumGift, forceInputCommandsHidden: self.forceInputCommandsHidden, voiceMessagesAvailable: self.voiceMessagesAvailable, customEmojiAvailable: self.customEmojiAvailable, threadData: self.threadData, forumTopicData: self.forumTopicData, isGeneralThreadClosed: self.isGeneralThreadClosed, translationState: self.translationState, replyMessage: self.replyMessage, accountPeerColor: self.accountPeerColor, savedMessagesTopicPeer: self.savedMessagesTopicPeer, hasSearchTags: self.hasSearchTags, isPremiumRequiredForMessaging: self.isPremiumRequiredForMessaging, sendPaidMessageStars: self.sendPaidMessageStars, acknowledgedPaidMessage: self.acknowledgedPaidMessage, hasSavedChats: self.hasSavedChats, appliedBoosts: self.appliedBoosts, boostsToUnrestrict: self.boostsToUnrestrict, businessIntro: self.businessIntro, hasBirthdayToday: self.hasBirthdayToday, adMessage: self.adMessage, peerVerification: self.peerVerification, starGiftsAvailable: self.starGiftsAvailable, alwaysShowGiftButton: self.alwaysShowGiftButton, disallowedGifts: self.disallowedGifts, persistentData: self.persistentData, removePaidMessageFeeData: removePaidMessageFeeData) } } diff --git a/submodules/ChatSendMessageActionUI/Sources/ChatSendMessageActionSheetController.swift b/submodules/ChatSendMessageActionUI/Sources/ChatSendMessageActionSheetController.swift index 30a4447d..8a0d2d29 100644 --- a/submodules/ChatSendMessageActionUI/Sources/ChatSendMessageActionSheetController.swift +++ b/submodules/ChatSendMessageActionUI/Sources/ChatSendMessageActionSheetController.swift @@ -72,6 +72,7 @@ public enum SendMessageActionSheetControllerParams { } public func makeChatSendMessageActionSheetController( + sgTranslationContext: (outgoingMessageTranslateToLang: String?, translate: (() -> Void)?, changeTranslationLanguage: (() -> ())?) = (outgoingMessageTranslateToLang: nil, translate: nil, changeTranslationLanguage: nil), initialData: ChatSendMessageContextScreen.InitialData, context: AccountContext, updatedPresentationData: (initial: PresentationData, signal: Signal)? = nil, @@ -93,6 +94,7 @@ public func makeChatSendMessageActionSheetController( isPremium: Bool = false ) -> ChatSendMessageActionSheetController { return ChatSendMessageContextScreen( + sgTranslationContext: sgTranslationContext, initialData: initialData, context: context, updatedPresentationData: updatedPresentationData, diff --git a/submodules/ChatSendMessageActionUI/Sources/ChatSendMessageContextScreen.swift b/submodules/ChatSendMessageActionUI/Sources/ChatSendMessageContextScreen.swift index 8d389567..88eaf974 100644 --- a/submodules/ChatSendMessageActionUI/Sources/ChatSendMessageContextScreen.swift +++ b/submodules/ChatSendMessageActionUI/Sources/ChatSendMessageContextScreen.swift @@ -53,6 +53,7 @@ public protocol ChatSendMessageContextScreenMediaPreview: AnyObject { final class ChatSendMessageContextScreenComponent: Component { typealias EnvironmentType = ViewControllerComponentContainer.Environment + let sgTranslationContext: (outgoingMessageTranslateToLang: String?, translate: (() -> Void)?, changeTranslationLanguage: (() -> ())?) let initialData: ChatSendMessageContextScreen.InitialData let context: AccountContext let updatedPresentationData: (initial: PresentationData, signal: Signal)? @@ -72,8 +73,9 @@ final class ChatSendMessageContextScreenComponent: Component { let reactionItems: [ReactionItem]? let availableMessageEffects: AvailableMessageEffects? let isPremium: Bool - + // MARK: Swiftgram init( + sgTranslationContext: (outgoingMessageTranslateToLang: String?, translate: (() -> Void)?, changeTranslationLanguage: (() -> ())?) = (outgoingMessageTranslateToLang: nil, translate: nil, changeTranslationLanguage: nil), initialData: ChatSendMessageContextScreen.InitialData, context: AccountContext, updatedPresentationData: (initial: PresentationData, signal: Signal)?, @@ -94,6 +96,7 @@ final class ChatSendMessageContextScreenComponent: Component { availableMessageEffects: AvailableMessageEffects?, isPremium: Bool ) { + self.sgTranslationContext = sgTranslationContext self.initialData = initialData self.context = context self.updatedPresentationData = updatedPresentationData @@ -642,6 +645,78 @@ final class ChatSendMessageContextScreenComponent: Component { ))) } + // MARK: Swiftgram + if !isSecret { + if let outgoingMessageTranslateToLang = component.sgTranslationContext.outgoingMessageTranslateToLang { + var languageCode = presentationData.strings.baseLanguageCode + let rawSuffix = "-raw" + if languageCode.hasSuffix(rawSuffix) { + languageCode = String(languageCode.dropLast(rawSuffix.count)) + } + + // Assuming, user want to send message in the same language the chat is + let toLang = outgoingMessageTranslateToLang + let key = "Translation.Language.\(toLang)" + let translateTitle: String + if let string = presentationData.strings.primaryComponent.dict[key] { + translateTitle = presentationData.strings.Conversation_Translation_TranslateTo(string).string + } else { + let languageLocale = Locale(identifier: languageCode) + let toLanguage = languageLocale.localizedString(forLanguageCode: toLang) ?? "" + translateTitle = presentationData.strings.Conversation_Translation_TranslateToOther(toLanguage).string + } + + items.append(.action(ContextMenuActionItem( + id: AnyHashable("sgTranslate"), + text: translateTitle, + icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Translate"), color: theme.contextMenu.primaryColor) + }, action: { [weak self] _, _ in + guard let self, let component = self.component else { + return + } + self.animateOutToEmpty = true + + component.sgTranslationContext.translate?() + self.environment?.controller()?.dismiss() + } + ))) + + items.append(.action(ContextMenuActionItem( + id: AnyHashable("sgChangeTranslateLang"), + text: presentationData.strings.Translate_ChangeLanguage, + icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Caption"), color: theme.contextMenu.primaryColor) + }, action: { [weak self] _, _ in + guard let self, let component = self.component else { + return + } + self.animateOutToEmpty = true + + self.environment?.controller()?.dismiss() + component.sgTranslationContext.changeTranslationLanguage?() + } + ))) + + } else { + items.append(.action(ContextMenuActionItem( + id: AnyHashable("sgChangeTranslateLang"), + text: presentationData.strings.Conversation_Translation_TranslateToOther("...").string, + icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Caption"), color: theme.contextMenu.primaryColor) + }, action: { [weak self] _, _ in + guard let self, let component = self.component else { + return + } + self.animateOutToEmpty = true + + self.environment?.controller()?.dismiss() + component.sgTranslationContext.changeTranslationLanguage?() + } + ))) + } + } + if case .separator = items.last { items.removeLast() } @@ -656,7 +731,7 @@ final class ChatSendMessageContextScreenComponent: Component { reactionItems: nil, previewReaction: nil, tip: nil, - tipSignal: .single(nil), + tipSignal: .single(nil as ContextController.Tip?), dismissed: nil ), animated: !transition.animation.isImmediate) } else { @@ -687,7 +762,7 @@ final class ChatSendMessageContextScreenComponent: Component { reactionItems: nil, previewReaction: nil, tip: nil, - tipSignal: .single(nil), + tipSignal: .single(nil as ContextController.Tip?), dismissed: nil ), currentScrollingState: nil, @@ -1425,6 +1500,7 @@ public class ChatSendMessageContextScreen: ViewControllerComponentContainer, Cha } public init( + sgTranslationContext: (outgoingMessageTranslateToLang: String?, translate: (() -> Void)?, changeTranslationLanguage: (() -> ())?) = (outgoingMessageTranslateToLang: nil, translate: nil, changeTranslationLanguage: nil), initialData: InitialData, context: AccountContext, updatedPresentationData: (initial: PresentationData, signal: Signal)?, @@ -1450,6 +1526,7 @@ public class ChatSendMessageContextScreen: ViewControllerComponentContainer, Cha super.init( context: context, component: ChatSendMessageContextScreenComponent( + sgTranslationContext: sgTranslationContext, initialData: initialData, context: context, updatedPresentationData: updatedPresentationData, diff --git a/submodules/Components/ResizableSheetComponent/BUILD b/submodules/Components/ResizableSheetComponent/BUILD new file mode 100644 index 00000000..cca9d7a5 --- /dev/null +++ b/submodules/Components/ResizableSheetComponent/BUILD @@ -0,0 +1,23 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "ResizableSheetComponent", + module_name = "ResizableSheetComponent", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/Display:Display", + "//submodules/ComponentFlow:ComponentFlow", + "//submodules/Components/ViewControllerComponent:ViewControllerComponent", + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + "//submodules/TelegramUI/Components/DynamicCornerRadiusView", + "//submodules/TelegramUI/Components/EdgeEffect", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/submodules/Components/ResizableSheetComponent/Sources/ResizableSheetComponent.swift b/submodules/Components/ResizableSheetComponent/Sources/ResizableSheetComponent.swift new file mode 100644 index 00000000..8ff5b544 --- /dev/null +++ b/submodules/Components/ResizableSheetComponent/Sources/ResizableSheetComponent.swift @@ -0,0 +1,828 @@ +import Foundation +import UIKit +import Display +import ComponentFlow +import ViewControllerComponent +import SwiftSignalKit +import DynamicCornerRadiusView +import TelegramPresentationData +import EdgeEffect + +public final class ResizableSheetComponentEnvironment: Equatable { + public struct BoundsUpdate { + public let bounds: CGRect + public let isInteractive: Bool + } + + public let theme: PresentationTheme + public let statusBarHeight: CGFloat + public let safeInsets: UIEdgeInsets + public let metrics: LayoutMetrics + public let deviceMetrics: DeviceMetrics + public let isDisplaying: Bool + public let isCentered: Bool + public let screenSize: CGSize + public let regularMetricsSize: CGSize? + public let dismiss: (Bool) -> Void + public let boundsUpdated: ActionSlot + + public init( + theme: PresentationTheme, + statusBarHeight: CGFloat, + safeInsets: UIEdgeInsets, + metrics: LayoutMetrics, + deviceMetrics: DeviceMetrics, + isDisplaying: Bool, + isCentered: Bool, + screenSize: CGSize, + regularMetricsSize: CGSize?, + dismiss: @escaping (Bool) -> Void, + boundsUpdated: ActionSlot = ActionSlot() + ) { + self.theme = theme + self.statusBarHeight = statusBarHeight + self.safeInsets = safeInsets + self.metrics = metrics + self.deviceMetrics = deviceMetrics + self.isDisplaying = isDisplaying + self.isCentered = isCentered + self.screenSize = screenSize + self.regularMetricsSize = regularMetricsSize + self.dismiss = dismiss + self.boundsUpdated = boundsUpdated + } + + public static func ==(lhs: ResizableSheetComponentEnvironment, rhs: ResizableSheetComponentEnvironment) -> Bool { + if lhs.theme != rhs.theme { + return false + } + if lhs.statusBarHeight != rhs.statusBarHeight { + return false + } + if lhs.safeInsets != rhs.safeInsets { + return false + } + if lhs.metrics != rhs.metrics { + return false + } + if lhs.deviceMetrics != rhs.deviceMetrics { + return false + } + if lhs.isDisplaying != rhs.isDisplaying { + return false + } + if lhs.isCentered != rhs.isCentered { + return false + } + if lhs.screenSize != rhs.screenSize { + return false + } + if lhs.regularMetricsSize != rhs.regularMetricsSize { + return false + } + return true + } +} + +public final class ResizableSheetComponent: Component { + public typealias EnvironmentType = (ChildEnvironmentType, ResizableSheetComponentEnvironment) + + public class ExternalState { + public fileprivate(set) var contentHeight: CGFloat + + public init() { + self.contentHeight = 0.0 + } + } + + public enum BackgroundColor: Equatable { + case color(UIColor) + } + + public let content: AnyComponent + public let titleItem: AnyComponent? + public let leftItem: AnyComponent? + public let rightItem: AnyComponent? + public let hasTopEdgeEffect: Bool + public let bottomItem: AnyComponent? + public let backgroundColor: BackgroundColor + public let isFullscreen: Bool + public let externalState: ExternalState? + public let animateOut: ActionSlot> + + public init( + content: AnyComponent, + titleItem: AnyComponent? = nil, + leftItem: AnyComponent? = nil, + rightItem: AnyComponent? = nil, + hasTopEdgeEffect: Bool = true, + bottomItem: AnyComponent? = nil, + backgroundColor: BackgroundColor, + isFullscreen: Bool = false, + externalState: ExternalState? = nil, + animateOut: ActionSlot>, + ) { + self.content = content + self.titleItem = titleItem + self.leftItem = leftItem + self.rightItem = rightItem + self.hasTopEdgeEffect = hasTopEdgeEffect + self.bottomItem = bottomItem + self.backgroundColor = backgroundColor + self.isFullscreen = isFullscreen + self.externalState = externalState + self.animateOut = animateOut + } + + public static func ==(lhs: ResizableSheetComponent, rhs: ResizableSheetComponent) -> Bool { + if lhs.content != rhs.content { + return false + } + if lhs.titleItem != rhs.titleItem { + return false + } + if lhs.leftItem != rhs.leftItem { + return false + } + if lhs.rightItem != rhs.rightItem { + return false + } + if lhs.hasTopEdgeEffect != rhs.hasTopEdgeEffect { + return false + } + if lhs.bottomItem != rhs.bottomItem { + return false + } + if lhs.backgroundColor != rhs.backgroundColor { + return false + } + if lhs.isFullscreen != rhs.isFullscreen { + return false + } + if lhs.animateOut != rhs.animateOut { + return false + } + return true + } + + private struct ItemLayout: Equatable { + var containerSize: CGSize + var containerInset: CGFloat + var containerCornerRadius: CGFloat + var bottomInset: CGFloat + var topInset: CGFloat + var fillingSize: CGFloat + let isTablet: Bool + + init(containerSize: CGSize, containerInset: CGFloat, containerCornerRadius: CGFloat, bottomInset: CGFloat, topInset: CGFloat, fillingSize: CGFloat, isTablet: Bool) { + self.containerSize = containerSize + self.containerInset = containerInset + self.containerCornerRadius = containerCornerRadius + self.bottomInset = bottomInset + self.topInset = topInset + self.fillingSize = fillingSize + self.isTablet = isTablet + } + } + + private final class ScrollView: UIScrollView { + override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + return super.hitTest(point, with: event) + } + } + + public final class View: UIView, UIScrollViewDelegate, ComponentTaggedView, UIGestureRecognizerDelegate { + public final class Tag { + public init() { + } + } + + public func matches(tag: Any) -> Bool { + if let _ = tag as? Tag { + return true + } + return false + } + + private let dimView: UIView + private let containerView: UIView + private let backgroundLayer: SimpleLayer + private let navigationBarContainer: SparseContainerView + private let bottomContainer: SparseContainerView + private let scrollView: ScrollView + private let scrollContentClippingView: SparseContainerView + private let scrollContentView: UIView + + private let topEdgeEffectView: EdgeEffectView + private let bottomEdgeEffectView: EdgeEffectView + private let contentView: ComponentView + + private var titleItemView: ComponentView? + private var leftItemView: ComponentView? + private var rightItemView: ComponentView? + private var bottomItemView: ComponentView? + + private let backgroundHandleView: UIImageView + + private var ignoreScrolling: Bool = false + private var isDismissingInteractively: Bool = false + private var dismissTranslation: CGFloat = 0.0 + private var dismissStartTranslation: CGFloat? + private var dismissPanGesture: UIPanGestureRecognizer? + + private var component: ResizableSheetComponent? + private weak var state: EmptyComponentState? + private var isUpdating: Bool = false + private var environment: ResizableSheetComponentEnvironment? + private var itemLayout: ItemLayout? + + override init(frame: CGRect) { + self.dimView = UIView() + self.containerView = UIView() + + self.containerView.clipsToBounds = true + self.containerView.layer.cornerRadius = 40.0 + self.containerView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner] + + self.backgroundLayer = SimpleLayer() + self.backgroundLayer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] + self.backgroundLayer.cornerRadius = 40.0 + + self.backgroundHandleView = UIImageView() + + self.navigationBarContainer = SparseContainerView() + self.bottomContainer = SparseContainerView() + + self.scrollView = ScrollView() + + self.scrollContentClippingView = SparseContainerView() + self.scrollContentClippingView.clipsToBounds = true + + self.scrollContentView = UIView() + + self.topEdgeEffectView = EdgeEffectView() + self.topEdgeEffectView.clipsToBounds = true + self.topEdgeEffectView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] + self.topEdgeEffectView.layer.cornerRadius = 40.0 + + self.bottomEdgeEffectView = EdgeEffectView() + self.bottomEdgeEffectView.clipsToBounds = true + self.bottomEdgeEffectView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner] + self.bottomEdgeEffectView.layer.cornerRadius = 40.0 + + self.contentView = ComponentView() + + super.init(frame: frame) + + self.addSubview(self.dimView) + self.addSubview(self.containerView) + self.containerView.layer.addSublayer(self.backgroundLayer) + + self.scrollView.delaysContentTouches = true + self.scrollView.canCancelContentTouches = true + self.scrollView.clipsToBounds = false + self.scrollView.contentInsetAdjustmentBehavior = .never + self.scrollView.automaticallyAdjustsScrollIndicatorInsets = false + self.scrollView.showsVerticalScrollIndicator = false + self.scrollView.showsHorizontalScrollIndicator = false + self.scrollView.alwaysBounceHorizontal = false + self.scrollView.alwaysBounceVertical = true + self.scrollView.scrollsToTop = false + self.scrollView.delegate = self + self.scrollView.clipsToBounds = true + + self.containerView.addSubview(self.scrollContentClippingView) + self.scrollContentClippingView.addSubview(self.scrollView) + + self.scrollView.addSubview(self.scrollContentView) + + self.containerView.addSubview(self.navigationBarContainer) + self.containerView.addSubview(self.bottomContainer) + + self.dimView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dimTapGesture(_:)))) + + let dismissPanGesture = UIPanGestureRecognizer(target: self, action: #selector(self.dismissPanGesture(_:))) + dismissPanGesture.maximumNumberOfTouches = 1 + dismissPanGesture.delegate = self + self.addGestureRecognizer(dismissPanGesture) + self.dismissPanGesture = dismissPanGesture + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + public func scrollViewDidScroll(_ scrollView: UIScrollView) { + if !self.ignoreScrolling { + self.updateScrolling(transition: .immediate) + } + } + + public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + if !self.bounds.contains(point) { + return nil + } + if !self.backgroundLayer.frame.contains(point) { + return self.dimView + } + + if let result = self.navigationBarContainer.hitTest(self.convert(point, to: self.navigationBarContainer), with: event) { + return result + } + if let result = self.bottomContainer.hitTest(self.convert(point, to: self.bottomContainer), with: event) { + return result + } + let result = super.hitTest(point, with: event) + return result + } + + override public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { + if gestureRecognizer === self.dismissPanGesture { + let pan = gestureRecognizer as! UIPanGestureRecognizer + let velocity = pan.velocity(in: self) + if abs(velocity.y) <= abs(velocity.x) { + return false + } + } + return true + } + + public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { + if gestureRecognizer === self.dismissPanGesture { + if otherGestureRecognizer === self.scrollView.panGestureRecognizer { + return true + } + } + return false + } + + @objc private func dimTapGesture(_ recognizer: UITapGestureRecognizer) { + if case .ended = recognizer.state { + self.dismissAnimated() + } + } + + public func dismissAnimated() { + guard let environment = self.environment else { + return + } + self.endEditing(true) + environment.dismiss(true) + } + + private func updateDismissTranslation(_ translation: CGFloat) { + self.dismissTranslation = translation + self.updateScrolling(transition: .immediate) + + let maxAlphaDistance = max(1.0, self.bounds.height * 0.9) + let alpha = 1.0 - min(1.0, translation / maxAlphaDistance) + self.dimView.alpha = alpha + } + + private func resetDismissTranslation(animated: Bool) { + self.dismissTranslation = 0.0 + if animated { + let transition: ComponentTransition = .easeInOut(duration: 0.2) + transition.setAlpha(view: self.dimView, alpha: 1.0) + self.updateScrolling(transition: transition) + } else { + self.dimView.alpha = 1.0 + self.updateScrolling(transition: .immediate) + } + } + + @objc private func dismissPanGesture(_ recognizer: UIPanGestureRecognizer) { + guard let component = self.component else { + return + } + + let translation = recognizer.translation(in: self) + switch recognizer.state { + case .began: + self.dismissStartTranslation = nil + case .changed: + let shouldStartDismiss = self.scrollView.contentOffset.y <= 0.0 && translation.y > 0.0 + if shouldStartDismiss { + if !self.isDismissingInteractively { + self.isDismissingInteractively = true + self.dismissStartTranslation = translation.y + self.scrollView.isScrollEnabled = false + } + + let start = self.dismissStartTranslation ?? translation.y + let dismissOffset = max(0.0, translation.y - start) + self.scrollView.contentOffset = .zero + self.updateDismissTranslation(dismissOffset) + } else if self.isDismissingInteractively { + let start = self.dismissStartTranslation ?? translation.y + let dismissOffset = max(0.0, translation.y - start) + self.updateDismissTranslation(dismissOffset) + } + case .ended, .cancelled: + if self.isDismissingInteractively { + let velocityY = recognizer.velocity(in: self).y + let currentOffset = self.dismissTranslation + let threshold = min(180.0, self.bounds.height * 0.25) + let shouldDismiss = currentOffset > threshold || velocityY > 1000.0 + + self.isDismissingInteractively = false + self.scrollView.isScrollEnabled = !component.isFullscreen + + if shouldDismiss { + let animateOffset = self.bounds.height - self.backgroundLayer.frame.minY + let initialVelocity = animateOffset > 0.0 ? max(0.0, velocityY) / animateOffset : 0.0 + self.animateOut(initialVelocity: initialVelocity, completion: { [weak self] in + self?.environment?.dismiss(false) + }) + } else { + self.resetDismissTranslation(animated: true) + } + } + default: + break + } + } + + private func updateScrolling(transition: ComponentTransition) { + guard let itemLayout = self.itemLayout, let component = self.component else { + return + } + var topOffset = -self.scrollView.bounds.minY + itemLayout.topInset + topOffset = max(0.0, topOffset) + transition.setTransform(layer: self.backgroundLayer, transform: CATransform3DMakeTranslation(0.0, topOffset + itemLayout.containerInset, 0.0)) + + transition.setPosition(view: self.navigationBarContainer, position: CGPoint(x: 0.0, y: topOffset + itemLayout.containerInset)) + + var topOffsetFraction = self.scrollView.bounds.minY / 100.0 + topOffsetFraction = max(0.0, min(1.0, topOffsetFraction)) + + if component.isFullscreen { + topOffsetFraction = 1.0 + } + + let minScale: CGFloat = itemLayout.isTablet ? 1.0 : (itemLayout.containerSize.width - 6.0 * 2.0) / itemLayout.containerSize.width + let minScaledTranslation: CGFloat = itemLayout.isTablet ? 0.0 : (itemLayout.containerSize.height - itemLayout.containerSize.height * minScale) * 0.5 - 6.0 + let minScaledCornerRadius: CGFloat = itemLayout.containerCornerRadius + + let scale = minScale * (1.0 - topOffsetFraction) + 1.0 * topOffsetFraction + let scaledTranslation = minScaledTranslation * (1.0 - topOffsetFraction) + let scaledCornerRadius = minScaledCornerRadius * (1.0 - topOffsetFraction) + itemLayout.containerCornerRadius * topOffsetFraction + + var containerTransform = CATransform3DIdentity + containerTransform = CATransform3DTranslate(containerTransform, 0.0, scaledTranslation, 0.0) + containerTransform = CATransform3DScale(containerTransform, scale, scale, scale) + containerTransform = CATransform3DTranslate(containerTransform, 0.0, self.dismissTranslation, 0.0) + transition.setTransform(view: self.containerView, transform: containerTransform) + transition.setCornerRadius(layer: self.containerView.layer, cornerRadius: scaledCornerRadius) + + if component.isFullscreen { + transition.setBounds(view: self.scrollView, bounds: CGRect(origin: .zero, size: self.scrollView.bounds.size)) + self.scrollView.isScrollEnabled = false + } else { + self.scrollView.isScrollEnabled = !self.isDismissingInteractively + } + + var bounds = self.scrollView.bounds + bounds.size.width = itemLayout.fillingSize + self.environment?.boundsUpdated.invoke(ResizableSheetComponentEnvironment.BoundsUpdate(bounds: bounds, isInteractive: self.scrollView.isTracking)) + } + + private var didPlayAppearanceAnimation = false + func animateIn() { + self.didPlayAppearanceAnimation = true + + self.dimView.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.3) + let animateOffset: CGFloat = self.bounds.height - self.backgroundLayer.frame.minY + self.scrollContentClippingView.layer.animatePosition(from: CGPoint(x: 0.0, y: animateOffset), to: CGPoint(), duration: 0.5, timingFunction: kCAMediaTimingFunctionSpring, additive: true) + self.backgroundLayer.animatePosition(from: CGPoint(x: 0.0, y: animateOffset), to: CGPoint(), duration: 0.5, timingFunction: kCAMediaTimingFunctionSpring, additive: true) + self.navigationBarContainer.layer.animatePosition(from: CGPoint(x: 0.0, y: animateOffset), to: CGPoint(), duration: 0.5, timingFunction: kCAMediaTimingFunctionSpring, additive: true) + self.bottomContainer.layer.animatePosition(from: CGPoint(x: 0.0, y: animateOffset), to: CGPoint(), duration: 0.5, timingFunction: kCAMediaTimingFunctionSpring, additive: true) + } + + func animateOut(initialVelocity: CGFloat? = nil, completion: @escaping () -> Void) { + let animateOffset: CGFloat = self.bounds.height - self.backgroundLayer.frame.minY + + self.dimView.layer.animateAlpha(from: self.dimView.alpha, to: 0.0, duration: 0.3, removeOnCompletion: false) + if let initialVelocity = initialVelocity { + let transition = ContainedViewLayoutTransition.animated(duration: 0.35, curve: .customSpring(damping: 124.0, initialVelocity: initialVelocity)) + + transition.updatePosition(layer: self.scrollContentClippingView.layer, position: CGPoint(x: self.scrollContentClippingView.layer.position.x, y: self.scrollContentClippingView.layer.position.y + animateOffset), completion: { _ in + completion() + }) + transition.updatePosition(layer: self.backgroundLayer, position: CGPoint(x: self.backgroundLayer.position.x, y: self.backgroundLayer.position.y + animateOffset)) + transition.updatePosition(layer: self.navigationBarContainer.layer, position: CGPoint(x: self.navigationBarContainer.layer.position.x, y: self.navigationBarContainer.layer.position.y + animateOffset)) + transition.updatePosition(layer: self.bottomContainer.layer, position: CGPoint(x: self.bottomContainer.layer.position.x, y: self.bottomContainer.layer.position.y + animateOffset)) + } else { + let duration: Double = 0.25 + self.scrollContentClippingView.layer.animatePosition(from: CGPoint(), to: CGPoint(x: 0.0, y: animateOffset), duration: duration, timingFunction: CAMediaTimingFunctionName.easeInEaseOut.rawValue, removeOnCompletion: false, additive: true, completion: { _ in + completion() + }) + self.backgroundLayer.animatePosition(from: CGPoint(), to: CGPoint(x: 0.0, y: animateOffset), duration: duration, timingFunction: CAMediaTimingFunctionName.easeInEaseOut.rawValue, removeOnCompletion: false, additive: true) + self.navigationBarContainer.layer.animatePosition(from: CGPoint(), to: CGPoint(x: 0.0, y: animateOffset), duration: duration, timingFunction: CAMediaTimingFunctionName.easeInEaseOut.rawValue, removeOnCompletion: false, additive: true) + self.bottomContainer.layer.animatePosition(from: CGPoint(), to: CGPoint(x: 0.0, y: animateOffset), duration: duration, timingFunction: CAMediaTimingFunctionName.easeInEaseOut.rawValue, removeOnCompletion: false, additive: true) + } + } + + func update(component: ResizableSheetComponent, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + self.isUpdating = true + defer { + self.isUpdating = false + } + + let sheetEnvironment = environment[ResizableSheetComponentEnvironment.self].value + component.animateOut.connect { [weak self] completion in + guard let self else { + return + } + self.animateOut { + completion(Void()) + } + } + + let resetScrolling = self.scrollView.bounds.width != availableSize.width + + let fillingSize: CGFloat + if case .regular = sheetEnvironment.metrics.widthClass { + fillingSize = min(availableSize.width, 414.0) - sheetEnvironment.safeInsets.left * 2.0 + } else { + fillingSize = min(availableSize.width, sheetEnvironment.deviceMetrics.screenSize.width) - sheetEnvironment.safeInsets.left * 2.0 + } + let rawSideInset: CGFloat = floor((availableSize.width - fillingSize) * 0.5) + + self.component = component + self.state = state + self.environment = sheetEnvironment + + self.dimView.backgroundColor = UIColor(white: 0.0, alpha: 0.5) + + let backgroundColor: UIColor + switch component.backgroundColor { + case let .color(color): + backgroundColor = color + self.backgroundLayer.backgroundColor = backgroundColor.cgColor + } + + transition.setFrame(view: self.dimView, frame: CGRect(origin: CGPoint(), size: availableSize)) + + var containerSize: CGSize + if !"".isEmpty, sheetEnvironment.isCentered { + let verticalInset: CGFloat = 44.0 + let maxSide = max(availableSize.width, availableSize.height) + let minSide = min(availableSize.width, availableSize.height) + containerSize = CGSize(width: min(availableSize.width - 20.0, floor(maxSide / 2.0)), height: min(availableSize.height, minSide) - verticalInset * 2.0) + if let regularMetricsSize = sheetEnvironment.regularMetricsSize { + containerSize = regularMetricsSize + } + } else { + containerSize = CGSize(width: fillingSize, height: .greatestFiniteMagnitude) + } + + var containerInset: CGFloat = sheetEnvironment.statusBarHeight + 10.0 + if component.isFullscreen { + containerInset = 0.0 + } + let clippingY: CGFloat + + self.contentView.parentState = state + let contentViewSize = self.contentView.update( + transition: transition, + component: component.content, + environment: { + environment[ChildEnvironmentType.self] + }, + containerSize: containerSize + ) + component.externalState?.contentHeight = contentViewSize.height + + if let contentView = self.contentView.view { + if contentView.superview == nil { + self.scrollContentView.addSubview(contentView) + } + transition.setFrame(view: contentView, frame: CGRect(origin: CGPoint(x: rawSideInset, y: 0.0), size: contentViewSize)) + } + + let contentHeight = contentViewSize.height + let initialContentHeight = contentHeight + + let edgeEffectHeight: CGFloat = 80.0 + let edgeEffectFrame = CGRect(origin: CGPoint(x: rawSideInset, y: 0.0), size: CGSize(width: fillingSize, height: edgeEffectHeight)) + transition.setFrame(view: self.topEdgeEffectView, frame: edgeEffectFrame) + self.topEdgeEffectView.update(content: backgroundColor, blur: true, alpha: 1.0, rect: edgeEffectFrame, edge: .top, edgeSize: edgeEffectFrame.height, transition: transition) + if self.topEdgeEffectView.superview == nil { + self.navigationBarContainer.insertSubview(self.topEdgeEffectView, at: 0) + } + self.topEdgeEffectView.isHidden = !component.hasTopEdgeEffect + + if let titleItem = component.titleItem { + let titleItemView: ComponentView + if let current = self.titleItemView { + titleItemView = current + } else { + titleItemView = ComponentView() + self.titleItemView = titleItemView + } + + let titleItemSize = titleItemView.update( + transition: transition, + component: titleItem, + environment: {}, + containerSize: CGSize(width: containerSize.width - 66.0 * 2.0, height: 66.0) + ) + let titleItemFrame = CGRect(origin: CGPoint(x: rawSideInset + floorToScreenPixels((containerSize.width - titleItemSize.width)) / 2.0, y: floorToScreenPixels(38.0 - titleItemSize.height * 0.5)), size: titleItemSize) + if let view = titleItemView.view { + if view.superview == nil { + self.navigationBarContainer.addSubview(view) + } + transition.setFrame(view: view, frame: titleItemFrame) + } + } else if let titleItemView = self.titleItemView { + self.titleItemView = nil + titleItemView.view?.removeFromSuperview() + } + + if let leftItem = component.leftItem { + var leftItemTransition = transition + let leftItemView: ComponentView + if let current = self.leftItemView { + leftItemView = current + } else { + leftItemTransition = .immediate + leftItemView = ComponentView() + self.leftItemView = leftItemView + } + + let leftItemSize = leftItemView.update( + transition: leftItemTransition, + component: leftItem, + environment: {}, + containerSize: CGSize(width: 66.0, height: 66.0) + ) + let leftItemFrame = CGRect(origin: CGPoint(x: rawSideInset + 16.0, y: 16.0), size: leftItemSize) + if let view = leftItemView.view { + if view.superview == nil { + self.navigationBarContainer.addSubview(view) + + if !transition.animation.isImmediate { + view.layer.animateScale(from: 0.01, to: 1.0, duration: 0.25) + view.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.25) + } + } + leftItemTransition.setFrame(view: view, frame: leftItemFrame) + } + } else if let leftItemView = self.leftItemView { + self.leftItemView = nil + if !transition.animation.isImmediate { + leftItemView.view?.layer.animateScale(from: 1.0, to: 0.01, duration: 0.25, removeOnCompletion: false) + leftItemView.view?.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.25, removeOnCompletion: false, completion: { _ in + leftItemView.view?.removeFromSuperview() + }) + } else { + leftItemView.view?.removeFromSuperview() + } + } + + if let rightItem = component.rightItem { + var rightItemTransition = transition + let rightItemView: ComponentView + if let current = self.rightItemView { + rightItemView = current + } else { + rightItemTransition = .immediate + rightItemView = ComponentView() + self.rightItemView = rightItemView + } + + let rightItemSize = rightItemView.update( + transition: rightItemTransition, + component: rightItem, + environment: {}, + containerSize: CGSize(width: 66.0, height: 66.0) + ) + let rightItemFrame = CGRect(origin: CGPoint(x: availableSize.width - rawSideInset - 16.0 - rightItemSize.width, y: 16.0), size: rightItemSize) + if let view = rightItemView.view { + if view.superview == nil { + self.navigationBarContainer.addSubview(view) + + if !transition.animation.isImmediate { + view.layer.animateScale(from: 0.01, to: 1.0, duration: 0.25) + view.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.25) + } + } + rightItemTransition.setFrame(view: view, frame: rightItemFrame) + } + } else if let rightItemView = self.rightItemView { + self.rightItemView = nil + if !transition.animation.isImmediate { + rightItemView.view?.layer.animateScale(from: 1.0, to: 0.01, duration: 0.25, removeOnCompletion: false) + rightItemView.view?.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.25, removeOnCompletion: false, completion: { _ in + rightItemView.view?.removeFromSuperview() + }) + } else { + rightItemView.view?.removeFromSuperview() + } + } + + if let bottomItem = component.bottomItem { + var bottomItemTransition = transition + let bottomItemView: ComponentView + if let current = self.bottomItemView { + bottomItemView = current + } else { + bottomItemTransition = .immediate + bottomItemView = ComponentView() + self.bottomItemView = bottomItemView + } + + let bottomInsets = ContainerViewLayout.concentricInsets(bottomInset: sheetEnvironment.safeInsets.bottom, innerDiameter: 52.0, sideInset: 30.0) + let bottomItemSize = bottomItemView.update( + transition: bottomItemTransition, + component: bottomItem, + environment: {}, + containerSize: CGSize(width: containerSize.width - bottomInsets.left - bottomInsets.right, height: 52.0) + ) + let bottomItemFrame = CGRect(origin: CGPoint(x: rawSideInset + floorToScreenPixels((containerSize.width - bottomItemSize.width)) / 2.0, y: availableSize.height - bottomItemSize.height - bottomInsets.bottom), size: bottomItemSize) + if let view = bottomItemView.view { + if view.superview == nil { + self.bottomContainer.addSubview(view) + + if !transition.animation.isImmediate { + view.layer.animateScale(from: 0.01, to: 1.0, duration: 0.25) + view.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.25) + } + } + bottomItemTransition.setFrame(view: view, frame: bottomItemFrame) + } + } else if let bottomItemView = self.bottomItemView { + self.bottomItemView = nil + if !transition.animation.isImmediate { + bottomItemView.view?.layer.animateScale(from: 1.0, to: 0.01, duration: 0.25, removeOnCompletion: false) + bottomItemView.view?.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.25, removeOnCompletion: false, completion: { _ in + bottomItemView.view?.removeFromSuperview() + }) + } else { + bottomItemView.view?.removeFromSuperview() + } + } + + let bottomEdgeEffectFrame = CGRect(origin: CGPoint(x: rawSideInset, y: availableSize.height - edgeEffectHeight), size: CGSize(width: fillingSize, height: edgeEffectHeight)) + transition.setFrame(view: self.bottomEdgeEffectView, frame: bottomEdgeEffectFrame) + self.bottomEdgeEffectView.update(content: .clear, blur: true, alpha: 1.0, rect: bottomEdgeEffectFrame, edge: .bottom, edgeSize: bottomEdgeEffectFrame.height, transition: transition) + if self.bottomEdgeEffectView.superview == nil { + self.bottomContainer.insertSubview(self.bottomEdgeEffectView, at: 0) + } + transition.setAlpha(view: self.bottomContainer, alpha: component.bottomItem != nil ? 1.0 : 0.0) + + + clippingY = availableSize.height + + var topInset: CGFloat = max(0.0, availableSize.height - containerInset - initialContentHeight) + if component.isFullscreen { + topInset = 0.0 + } + + let scrollContentHeight = max(topInset + contentHeight + containerInset, availableSize.height - containerInset) + + self.scrollContentClippingView.layer.cornerRadius = 38.0 + + self.itemLayout = ItemLayout(containerSize: availableSize, containerInset: containerInset, containerCornerRadius: sheetEnvironment.deviceMetrics.screenCornerRadius, bottomInset: sheetEnvironment.safeInsets.bottom, topInset: topInset, fillingSize: fillingSize, isTablet: sheetEnvironment.metrics.isTablet) + + transition.setFrame(view: self.scrollContentView, frame: CGRect(origin: CGPoint(x: 0.0, y: topInset + containerInset), size: CGSize(width: availableSize.width, height: contentHeight))) + + transition.setPosition(layer: self.backgroundLayer, position: CGPoint(x: availableSize.width / 2.0, y: availableSize.height / 2.0)) + transition.setBounds(layer: self.backgroundLayer, bounds: CGRect(origin: CGPoint(), size: CGSize(width: fillingSize, height: availableSize.height))) + + let scrollClippingFrame = CGRect(origin: CGPoint(x: 0.0, y: containerInset), size: CGSize(width: availableSize.width, height: clippingY - containerInset)) + transition.setPosition(view: self.scrollContentClippingView, position: scrollClippingFrame.center) + transition.setBounds(view: self.scrollContentClippingView, bounds: CGRect(origin: CGPoint(x: scrollClippingFrame.minX, y: scrollClippingFrame.minY), size: scrollClippingFrame.size)) + + self.ignoreScrolling = true + transition.setFrame(view: self.scrollView, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: availableSize.width, height: availableSize.height))) + let contentSize = CGSize(width: availableSize.width, height: scrollContentHeight) + if contentSize != self.scrollView.contentSize { + self.scrollView.contentSize = contentSize + } + if resetScrolling { + self.scrollView.bounds = CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: availableSize) + } + self.ignoreScrolling = false + self.updateScrolling(transition: transition) + + transition.setPosition(view: self.containerView, position: CGRect(origin: CGPoint(), size: availableSize).center) + transition.setBounds(view: self.containerView, bounds: CGRect(origin: CGPoint(), size: availableSize)) + + if sheetEnvironment.isDisplaying && !self.didPlayAppearanceAnimation { + self.animateIn() + } + + return availableSize + } + } + + public func makeView() -> View { + return View(frame: CGRect()) + } + + public func update(view: View, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + return view.update(component: self, availableSize: availableSize, state: state, environment: environment, transition: transition) + } +} diff --git a/submodules/ComposePollUI/Sources/ComposePollScreen.swift b/submodules/ComposePollUI/Sources/ComposePollScreen.swift index 32b9cdde..e6b35e38 100644 --- a/submodules/ComposePollUI/Sources/ComposePollScreen.swift +++ b/submodules/ComposePollUI/Sources/ComposePollScreen.swift @@ -532,6 +532,7 @@ final class ComposePollScreenComponent: Component { let presentationInterfaceState = ChatPresentationInterfaceState( chatWallpaper: .builtin(WallpaperSettings()), theme: presentationData.theme, + preferredGlassType: .default, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameDisplayOrder: presentationData.nameDisplayOrder, diff --git a/submodules/ContextUI/Sources/ContextControllerFactories.swift b/submodules/ContextUI/Sources/ContextControllerFactories.swift new file mode 100644 index 00000000..4c843ea1 --- /dev/null +++ b/submodules/ContextUI/Sources/ContextControllerFactories.swift @@ -0,0 +1,90 @@ +import Foundation +import UIKit +import Display +import SwiftSignalKit +import AccountContext +import TelegramPresentationData + +public func makeContextController( + context: AccountContext? = nil, + presentationData: PresentationData, + source: ContextContentSource, + items: Signal, + recognizer: TapLongTapOrDoubleTapGestureRecognizer? = nil, + gesture: ContextGesture? = nil, + workaroundUseLegacyImplementation: Bool = false, + disableScreenshots: Bool = false, + hideReactionPanelTail: Bool = false +) -> ContextController { + return ContextController( + context: context, + presentationData: presentationData, + source: source, + items: items, + recognizer: recognizer, + gesture: gesture, + workaroundUseLegacyImplementation: workaroundUseLegacyImplementation, + disableScreenshots: disableScreenshots, + hideReactionPanelTail: hideReactionPanelTail + ) +} + +public func makePeekController( + presentationData: PresentationData, + content: PeekControllerContent, + sourceView: @escaping () -> (UIView, CGRect)?, + activateImmediately: Bool = false +) -> PeekController { + return PeekController( + presentationData: presentationData, + content: content, + sourceView: sourceView, + activateImmediately: activateImmediately + ) +} + +public func makePinchController( + sourceNode: PinchSourceContainerNode, + disableScreenshots: Bool = false, + getContentAreaInScreenSpace: @escaping () -> CGRect +) -> PinchController { + return PinchController( + sourceNode: sourceNode, + disableScreenshots: disableScreenshots, + getContentAreaInScreenSpace: getContentAreaInScreenSpace + ) +} + +public func makeContextControllerActionsStackNode( + context: AccountContext?, + getController: @escaping () -> ContextControllerProtocol?, + requestDismiss: @escaping (ContextMenuActionResult) -> Void, + requestUpdate: @escaping (ContainedViewLayoutTransition) -> Void +) -> ContextControllerActionsStackNode { + return ContextControllerActionsStackNode( + context: context, + getController: getController, + requestDismiss: requestDismiss, + requestUpdate: requestUpdate + ) +} + +public func makeContextControllerActionsListStackItem( + id: AnyHashable?, + items: [ContextMenuItem], + reactionItems: ContextControllerReactionItems?, + previewReaction: ContextControllerPreviewReaction?, + tip: ContextController.Tip?, + tipSignal: Signal?, + dismissed: (() -> Void)? +) -> ContextControllerActionsListStackItem { + return ContextControllerActionsListStackItem( + id: id, + items: items, + reactionItems: reactionItems, + previewReaction: previewReaction, + tip: tip, + tipSignal: tipSignal, + dismissed: dismissed + ) +} diff --git a/submodules/CountrySelectionUI/Sources/AuthorizationSequenceCountrySelectionController.swift b/submodules/CountrySelectionUI/Sources/AuthorizationSequenceCountrySelectionController.swift index 3b3cdc1f..edf8c41e 100644 --- a/submodules/CountrySelectionUI/Sources/AuthorizationSequenceCountrySelectionController.swift +++ b/submodules/CountrySelectionUI/Sources/AuthorizationSequenceCountrySelectionController.swift @@ -76,6 +76,8 @@ private func loadCountryCodes() -> [Country] { private var countryCodes: [Country] = loadCountryCodes() private var countryCodesByPrefix: [String: (Country, Country.CountryCode)] = [:] +// MARK: Swiftgram +private var sgCountryCodesByPrefix: [String: (Country, Country.CountryCode)] = ["999": (Country(id: "XX", name: "Demo", localizedName: nil, countryCodes: [Country.CountryCode(code: "999", prefixes: [], patterns: ["XX X XXXX"])], hidden: false), Country.CountryCode(code: "999", prefixes: [], patterns: ["XX X XXXX"]))] public func loadServerCountryCodes(accountManager: AccountManager, engine: TelegramEngineUnauthorized, completion: @escaping () -> Void) { let _ = (engine.localization.getCountriesList(accountManager: accountManager, langCode: nil) @@ -235,7 +237,7 @@ public final class AuthorizationSequenceCountrySelectionController: ViewControll for i in 0.. country.1.code.count { break diff --git a/submodules/DebugSettingsUI/BUILD b/submodules/DebugSettingsUI/BUILD index 553c5023..970b8c18 100644 --- a/submodules/DebugSettingsUI/BUILD +++ b/submodules/DebugSettingsUI/BUILD @@ -1,5 +1,12 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGDebugUI:SGDebugUI", + "//Swiftgram/SGLogging:SGLogging", + "//Swiftgram/SGLoggingComposer:SGLoggingComposer", + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + swift_library( name = "DebugSettingsUI", module_name = "DebugSettingsUI", @@ -9,7 +16,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", "//submodules/Display:Display", "//submodules/Postbox:Postbox", diff --git a/submodules/DebugSettingsUI/Sources/DebugController.swift b/submodules/DebugSettingsUI/Sources/DebugController.swift index 27725379..2c26c578 100644 --- a/submodules/DebugSettingsUI/Sources/DebugController.swift +++ b/submodules/DebugSettingsUI/Sources/DebugController.swift @@ -1,3 +1,9 @@ +// MARK: Swiftgram +import SGLogging +import SGLoggingComposer +import SGSimpleSettings +import SGDebugUI + import Foundation import UIKit import Display @@ -45,6 +51,7 @@ private final class DebugControllerArguments { } private enum DebugControllerSection: Int32 { + case swiftgram case sticker case logs case logging @@ -57,6 +64,8 @@ private enum DebugControllerSection: Int32 { } private enum DebugControllerEntry: ItemListNodeEntry { + case SGDebug(PresentationTheme) + case sendSGLogs(PresentationTheme) case testStickerImport(PresentationTheme) case sendLogs(PresentationTheme) case sendOneLog(PresentationTheme) @@ -123,6 +132,8 @@ private enum DebugControllerEntry: ItemListNodeEntry { var section: ItemListSectionId { switch self { + case .sendSGLogs, .SGDebug: + return DebugControllerSection.swiftgram.rawValue case .testStickerImport: return DebugControllerSection.sticker.rawValue case .sendLogs, .sendOneLog, .sendShareLogs, .sendGroupCallLogs, .sendStorageStats, .sendNotificationLogs, .sendCriticalLogs, .sendAllLogs: @@ -150,6 +161,11 @@ private enum DebugControllerEntry: ItemListNodeEntry { var stableId: Int { switch self { + // MARK: Swiftgram + case .SGDebug: + return -110 + case .sendSGLogs: + return -100 case .testStickerImport: return 0 case .sendLogs: @@ -286,6 +302,13 @@ private enum DebugControllerEntry: ItemListNodeEntry { func item(presentationData: ItemListPresentationData, arguments: Any) -> ListViewItem { let arguments = arguments as! DebugControllerArguments switch self { + case .SGDebug: + return ItemListDisclosureItem(presentationData: presentationData, title: "Swiftgram Debug", label: "", sectionId: self.section, style: .blocks, action: { + guard let context = arguments.context else { + return + } + arguments.pushController(sgDebugController(context: context)) + }) case .testStickerImport: return ItemListActionItem(presentationData: presentationData, systemStyle: .glass, title: "Simulate Stickers Import", kind: .generic, alignment: .natural, sectionId: self.section, style: .blocks, action: { guard let context = arguments.context else { @@ -385,9 +408,20 @@ private enum DebugControllerEntry: ItemListNodeEntry { arguments.presentController(actionSheet, nil) }) }) - case .sendOneLog: - return ItemListDisclosureItem(presentationData: presentationData, systemStyle: .glass, title: "Send Latest Logs (Up to 4 MB)", label: "", sectionId: self.section, style: .blocks, action: { - let _ = (Logger.shared.collectLogs() + // MARK: Swiftgram + case .sendOneLog, .sendSGLogs: + var title = "Send Latest Logs (Up to 4 MB)" + var logCollectionSignal: Signal<[(String, String)], NoError> = Logger.shared.collectLogs() + var fileName = "Log-iOS-Short.txt" + var appName = "Telegram" + if case .sendSGLogs(_) = self { + title = "Send Swiftgram Logs" + logCollectionSignal = SGLogger.shared.collectLogs() + fileName = "Log-iOS-Swiftgram.txt" + appName = "Swiftgram" + } + return ItemListDisclosureItem(presentationData: presentationData, systemStyle: .glass, title: title, label: "", sectionId: self.section, style: .blocks, action: { + let _ = (logCollectionSignal |> deliverOnMainQueue).start(next: { logs in let presentationData = arguments.sharedContext.currentPresentationData.with { $0 } let actionSheet = ActionSheetController(presentationData: presentationData) @@ -434,7 +468,7 @@ private enum DebugControllerEntry: ItemListNodeEntry { let fileResource = LocalFileMediaResource(fileId: id, size: Int64(logData.count), isSecretRelated: false) context.account.postbox.mediaBox.storeResourceData(fileResource.id, data: logData) - let file = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: id), partialReference: nil, resource: fileResource, previewRepresentations: [], videoThumbnails: [], immediateThumbnailData: nil, mimeType: "application/text", size: Int64(logData.count), attributes: [.FileName(fileName: "Log-iOS-Short.txt")], alternativeRepresentations: []) + let file = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: id), partialReference: nil, resource: fileResource, previewRepresentations: [], videoThumbnails: [], immediateThumbnailData: nil, mimeType: "application/text", size: Int64(logData.count), attributes: [.FileName(fileName: fileName)], alternativeRepresentations: []) let message: EnqueueMessage = .message(text: "", attributes: [], inlineStickers: [:], mediaReference: .standalone(media: file), threadId: nil, replyToMessageId: nil, replyToStoryId: nil, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: []) let _ = enqueueMessages(account: context.account, peerId: peerId, messages: [message]).start() @@ -449,7 +483,7 @@ private enum DebugControllerEntry: ItemListNodeEntry { let composeController = MFMailComposeViewController() composeController.mailComposeDelegate = arguments.mailComposeDelegate - composeController.setSubject("Telegram Logs") + composeController.setSubject("\(appName) Logs") for (name, path) in logs { if let data = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) { composeController.addAttachmentData(data, mimeType: "application/text", fileName: name) @@ -1493,9 +1527,13 @@ private func debugControllerEntries(sharedContext: SharedAccountContext, present let isMainApp = sharedContext.applicationBindings.isMainApp + // MARK: Swiftgram + entries.append(.SGDebug(presentationData.theme)) + entries.append(.sendSGLogs(presentationData.theme)) + // entries.append(.testStickerImport(presentationData.theme)) entries.append(.sendLogs(presentationData.theme)) - //entries.append(.sendOneLog(presentationData.theme)) + entries.append(.sendOneLog(presentationData.theme)) entries.append(.sendShareLogs) entries.append(.sendGroupCallLogs) entries.append(.sendNotificationLogs(presentationData.theme)) @@ -1515,7 +1553,7 @@ private func debugControllerEntries(sharedContext: SharedAccountContext, present entries.append(.resetWebViewCache(presentationData.theme)) entries.append(.keepChatNavigationStack(presentationData.theme, experimentalSettings.keepChatNavigationStack)) - #if DEBUG + #if true entries.append(.skipReadHistory(presentationData.theme, experimentalSettings.skipReadHistory)) #endif entries.append(.alwaysDisplayTyping(experimentalSettings.alwaysDisplayTyping)) diff --git a/submodules/Display/BUILD b/submodules/Display/BUILD index 8e56c1d1..c700e245 100644 --- a/submodules/Display/BUILD +++ b/submodules/Display/BUILD @@ -1,15 +1,24 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgsrc = [ + "//Swiftgram/SGAppBadgeOffset:SGAppBadgeOffset" +] + +sgdeps = [ + "//submodules/Utils/DeviceModel", + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", +] + swift_library( name = "Display", module_name = "Display", - srcs = glob([ + srcs = sgsrc + glob([ "Source/**/*.swift", ]), copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/ObjCRuntimeUtils:ObjCRuntimeUtils", "//submodules/UIKitRuntimeUtils:UIKitRuntimeUtils", "//submodules/AppBundle:AppBundle", diff --git a/submodules/Display/Source/DeviceMetrics.swift b/submodules/Display/Source/DeviceMetrics.swift index c22f8975..c84c0f2a 100644 --- a/submodules/Display/Source/DeviceMetrics.swift +++ b/submodules/Display/Source/DeviceMetrics.swift @@ -410,9 +410,6 @@ public enum DeviceMetrics: CaseIterable, Equatable { } public var showAppBadge: Bool { - if case .iPhoneX = self { - return false - } - return self.hasTopNotch + return self.sgShowAppBadge } } diff --git a/submodules/Display/Source/WindowContent.swift b/submodules/Display/Source/WindowContent.swift index 9e22491a..0df87bf5 100644 --- a/submodules/Display/Source/WindowContent.swift +++ b/submodules/Display/Source/WindowContent.swift @@ -2,6 +2,7 @@ import Foundation import UIKit import AsyncDisplayKit import SwiftSignalKit +import SGSimpleSettings private struct WindowLayout: Equatable { let size: CGSize @@ -264,7 +265,7 @@ public class Window1 { public let hostView: WindowHostView public let badgeView: UIImageView - private var deviceMetrics: DeviceMetrics + private(set) var deviceMetrics: DeviceMetrics public let statusBarHost: StatusBarHost? private let keyboardManager: KeyboardManager? @@ -348,7 +349,11 @@ public class Window1 { public init(hostView: WindowHostView, statusBarHost: StatusBarHost?) { self.hostView = hostView self.badgeView = UIImageView() + if SGSimpleSettings.shared.status > 1, let image = UIImage(bundleImageName: SGSimpleSettings.shared.customAppBadge) { + self.badgeView.image = image + } else { self.badgeView.image = UIImage(bundleImageName: "Components/AppBadge") + } self.badgeView.isHidden = true self.systemUserInterfaceStyle = hostView.systemUserInterfaceStyle @@ -1253,7 +1258,7 @@ public class Window1 { if let image = self.badgeView.image { self.updateBadgeVisibility() - self.badgeView.frame = CGRect(origin: CGPoint(x: floorToScreenPixels((self.windowLayout.size.width - image.size.width) / 2.0), y: 5.0), size: image.size) + self.badgeView.frame = CGRect(origin: CGPoint(x: floorToScreenPixels((self.windowLayout.size.width - image.size.width) / 2.0), y: self.deviceMetrics.sgAppBadgeOffset()), size: image.size) } } } diff --git a/submodules/DrawingUI/Sources/DrawingStickerEntityView.swift b/submodules/DrawingUI/Sources/DrawingStickerEntityView.swift index 3565513a..1d25d800 100644 --- a/submodules/DrawingUI/Sources/DrawingStickerEntityView.swift +++ b/submodules/DrawingUI/Sources/DrawingStickerEntityView.swift @@ -305,7 +305,7 @@ public class DrawingStickerEntityView: DrawingEntityView { var file: TelegramMediaFile? for attribute in gift.attributes { - if case let .model(_, fileValue, _) = attribute { + if case let StarGift.UniqueGift.Attribute.model(_, fileValue, _, _) = attribute { file = fileValue break } @@ -466,7 +466,7 @@ public class DrawingStickerEntityView: DrawingEntityView { file = fileValue } else if case let .gift(gift, _) = self.stickerEntity.content { for attribute in gift.attributes { - if case let .model(_, fileValue, _) = attribute { + if case let StarGift.UniqueGift.Attribute.model(_, fileValue, _, _) = attribute { file = fileValue break } @@ -887,7 +887,7 @@ public class DrawingStickerEntityView: DrawingEntityView { } else if case let .gift(gift, _) = self.stickerEntity.content { var file: TelegramMediaFile? for attribute in gift.attributes { - if case let .model(_, fileValue, _) = attribute { + if case let StarGift.UniqueGift.Attribute.model(_, fileValue, _, _) = attribute { file = fileValue break } diff --git a/submodules/GalleryUI/BUILD b/submodules/GalleryUI/BUILD index 9e84ea0a..79051c01 100644 --- a/submodules/GalleryUI/BUILD +++ b/submodules/GalleryUI/BUILD @@ -1,5 +1,9 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + swift_library( name = "GalleryUI", module_name = "GalleryUI", @@ -9,7 +13,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", "//submodules/AsyncDisplayKit:AsyncDisplayKit", "//submodules/Display:Display", @@ -70,6 +74,10 @@ swift_library( "//submodules/TelegramUI/Components/PlainButtonComponent", "//submodules/AvatarNode", "//submodules/PhotoResources", + "//submodules/TelegramUI/Components/EdgeEffect", + "//submodules/TelegramUI/Components/GlassBackgroundComponent", + "//submodules/TelegramUI/Components/GlassControls", + "//submodules/TelegramUI/Components/VideoPlaybackControlsComponent", ], visibility = [ "//visibility:public", diff --git a/submodules/GalleryUI/Sources/ChatItemGalleryFooterContentNode.swift b/submodules/GalleryUI/Sources/ChatItemGalleryFooterContentNode.swift index 97112822..cea0deb9 100644 --- a/submodules/GalleryUI/Sources/ChatItemGalleryFooterContentNode.swift +++ b/submodules/GalleryUI/Sources/ChatItemGalleryFooterContentNode.swift @@ -124,6 +124,11 @@ class CaptionScrollWrapperNode: ASDisplayNode { } final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode, ASScrollViewDelegate { + struct SettingsButtonState: Equatable { + let speed: String? + let quality: String? + } + private let context: AccountContext private var presentationData: PresentationData private var theme: PresentationTheme @@ -1147,6 +1152,14 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode, ASScroll } } + func setMessage(_ message: Message, displayInfo: Bool, translateToLanguage: String? = nil, peerIsCopyProtected: Bool, displayPictureInPictureButton: Bool, settingsButtonState: SettingsButtonState?, displayStickersButton: Bool) { + self.setMessage(message, displayInfo: displayInfo, translateToLanguage: translateToLanguage, peerIsCopyProtected: peerIsCopyProtected) + } + + func setMessage(_ message: Message, displayInfo: Bool, translateToLanguage: String? = nil, peerIsCopyProtected: Bool, displayPictureInPictureButton: Bool, settingsButtonState: SettingsButtonState?, displayStickersButton: Bool, animated: Bool) { + self.setMessage(message, displayInfo: displayInfo, translateToLanguage: translateToLanguage, peerIsCopyProtected: peerIsCopyProtected, displayPictureInPictureButton: displayPictureInPictureButton, settingsButtonState: settingsButtonState, displayStickersButton: displayStickersButton) + } + func setWebPage(_ webPage: TelegramMediaWebpage, media: Media) { self.currentWebPageAndMedia = (webPage, media) } diff --git a/submodules/GalleryUI/Sources/GalleryController.swift b/submodules/GalleryUI/Sources/GalleryController.swift index e36181f6..efda7851 100644 --- a/submodules/GalleryUI/Sources/GalleryController.swift +++ b/submodules/GalleryUI/Sources/GalleryController.swift @@ -140,11 +140,11 @@ public func internalDocumentItemSupportsMimeType(_ type: String, fileName: Strin return false } -private let textFont = Font.regular(16.0) -private let boldFont = Font.bold(16.0) -private let italicFont = Font.italic(16.0) -private let boldItalicFont = Font.semiboldItalic(16.0) -private let fixedFont = UIFont(name: "Menlo-Regular", size: 15.0) ?? textFont +private let textFont = Font.regular(17.0) +private let boldFont = Font.bold(17.0) +private let italicFont = Font.italic(17.0) +private let boldItalicFont = Font.semiboldItalic(17.0) +private let fixedFont = UIFont(name: "Menlo-Regular", size: 17.0) ?? textFont public func galleryCaptionStringWithAppliedEntities(context: AccountContext, text: String, entities: [MessageTextEntity], message: Message?, cachedMessageSyntaxHighlight: CachedMessageSyntaxHighlight? = nil) -> NSAttributedString { var baseQuoteSecondaryTintColor: UIColor? @@ -535,6 +535,10 @@ public struct GalleryConfiguration { } static func with(appConfiguration: AppConfiguration) -> GalleryConfiguration { + // MARK: Swiftgram + if appConfiguration.sgWebSettings.global.ytPip { + return GalleryConfiguration(youtubePictureInPictureEnabled: true) + } if let data = appConfiguration.data, let value = data["youtube_pip"] as? String { return GalleryConfiguration(youtubePictureInPictureEnabled: value != "disabled") } else { @@ -576,8 +580,7 @@ private func galleryEntriesForMessageHistoryEntries(_ entries: [MessageHistoryEn } public class GalleryController: ViewController, StandalonePresentableController, KeyShortcutResponder, GalleryControllerProtocol { - public static let darkNavigationTheme = NavigationBarTheme(overallDarkAppearance: true, buttonColor: .white, disabledButtonColor: UIColor(rgb: 0x525252), primaryTextColor: .white, backgroundColor: UIColor(white: 0.0, alpha: 0.6), enableBackgroundBlur: false, separatorColor: UIColor(white: 0.0, alpha: 0.8), badgeBackgroundColor: .clear, badgeStrokeColor: .clear, badgeTextColor: .clear) - public static let lightNavigationTheme = NavigationBarTheme(overallDarkAppearance: false, buttonColor: UIColor(rgb: 0x0088ff), disabledButtonColor: UIColor(rgb: 0xd0d0d0), primaryTextColor: .black, backgroundColor: UIColor(red: 0.968626451, green: 0.968626451, blue: 0.968626451, alpha: 1.0), enableBackgroundBlur: false, separatorColor: UIColor(red: 0.6953125, green: 0.6953125, blue: 0.6953125, alpha: 1.0), badgeBackgroundColor: .clear, badgeStrokeColor: .clear, badgeTextColor: .clear) + public static let darkNavigationTheme = NavigationBarTheme(overallDarkAppearance: true, buttonColor: .white, disabledButtonColor: UIColor(rgb: 0x525252), primaryTextColor: .white, backgroundColor: UIColor(white: 0.0, alpha: 0.6), enableBackgroundBlur: false, separatorColor: UIColor(white: 0.0, alpha: 0.8), badgeBackgroundColor: .clear, badgeStrokeColor: .clear, badgeTextColor: .clear, edgeEffectColor: .clear, style: .glass) private var galleryNode: GalleryControllerNode { return self.displayNode as! GalleryControllerNode @@ -588,6 +591,8 @@ public class GalleryController: ViewController, StandalonePresentableController, private let source: GalleryControllerItemSource private let invertItemOrder: Bool + private let titleView: GalleryTitleView + private let streamVideos: Bool private let _ready = Promise() @@ -618,7 +623,7 @@ public class GalleryController: ViewController, StandalonePresentableController, private var configuration: GalleryConfiguration? private let centralItemTitle = Promise() - private let centralItemTitleView = Promise() + private let centralItemTitleContent = Promise() private let centralItemRightBarButtonItem = Promise() private let centralItemRightBarButtonItems = Promise<[UIBarButtonItem]?>(nil) private let centralItemNavigationStyle = Promise() @@ -646,6 +651,8 @@ public class GalleryController: ViewController, StandalonePresentableController, public var onDidAppear: (() -> Void)? public var useSimpleAnimation: Bool = false + public var navigateToMessageContext: ((EngineMessage) -> Void)? + private var initialOrientation: UIInterfaceOrientation? public init(context: AccountContext, source: GalleryControllerItemSource, invertItemOrder: Bool = false, streamSingleVideo: Bool = false, fromPlayingVideo: Bool = false, landscape: Bool = false, timecode: Double? = nil, playbackRate: Double? = nil, synchronousLoad: Bool = false, replaceRootController: @escaping (ViewController, Promise?) -> Void, baseNavigationController: NavigationController?, actionInteraction: GalleryControllerActionInteraction? = nil, generateStoreAfterDownload: ((Message, TelegramMediaFile) -> (() -> Void)?)? = nil) { @@ -681,6 +688,8 @@ public class GalleryController: ViewController, StandalonePresentableController, openActionOptionsImpl?(action, message) } + self.titleView = GalleryTitleView(context: context, presentationData: self.presentationData) + super.init(navigationBarPresentationData: NavigationBarPresentationData(theme: GalleryController.darkNavigationTheme, strings: NavigationBarStrings(presentationStrings: self.presentationData.strings))) let backItem = UIBarButtonItem(backButtonAppearanceWithTitle: self.presentationData.strings.Common_Back, target: self, action: #selector(self.donePressed)) @@ -916,8 +925,8 @@ public class GalleryController: ViewController, StandalonePresentableController, self?.navigationItem.title = title })) - self.centralItemAttributesDisposable.add(self.centralItemTitleView.get().start(next: { [weak self] titleView in - self?.navigationItem.titleView = titleView + self.centralItemAttributesDisposable.add(self.centralItemTitleContent.get().start(next: { [weak self] titleContent in + self?.titleView.setContent(content: titleContent) })) self.centralItemAttributesDisposable.add(combineLatest(self.centralItemRightBarButtonItem.get(), self.centralItemRightBarButtonItems.get()).start(next: { [weak self] rightBarButtonItem, rightBarButtonItems in @@ -934,7 +943,7 @@ public class GalleryController: ViewController, StandalonePresentableController, self.centralItemAttributesDisposable.add(self.centralItemFooterContentNode.get().start(next: { [weak self] footerContentNode, overlayContentNode in self?.galleryNode.updatePresentationState({ $0.withUpdatedFooterContentNode(footerContentNode).withUpdatedOverlayContentNode(overlayContentNode) - }, transition: .immediate) + }, transition: .animated(duration: 0.4, curve: .spring)) })) self.centralItemAttributesDisposable.add(self.centralItemNavigationStyle.get().start(next: { [weak self] style in @@ -1298,6 +1307,10 @@ public class GalleryController: ViewController, StandalonePresentableController, var animatedOutNode = true var animatedOutInterface = false + if forceAway { + self._hiddenMedia.set(.single(nil)) + } + let completion = { [weak self] in if animatedOutNode && animatedOutInterface { self?.actionInteraction?.updateCanReadHistory(true) @@ -1371,10 +1384,12 @@ public class GalleryController: ViewController, StandalonePresentableController, } }, controller: { [weak self] in return self + }, currentItemNode: { [weak self] in + return self?.galleryNode.pager.centralItemNode() }) let disableTapNavigation = !(self.context.sharedContext.currentMediaDisplaySettings.with { $0 }.showNextMediaOnTap) - self.displayNode = GalleryControllerNode(context: self.context, controllerInteraction: controllerInteraction, disableTapNavigation: disableTapNavigation) + self.displayNode = GalleryControllerNode(context: self.context, controllerInteraction: controllerInteraction, titleView: titleView, disableTapNavigation: disableTapNavigation) self.displayNodeDidLoad() self.galleryNode.statusBar = self.statusBar @@ -1528,7 +1543,7 @@ public class GalleryController: ViewController, StandalonePresentableController, if let node = strongSelf.galleryNode.pager.centralItemNode() { strongSelf.centralItemTitle.set(node.title()) - strongSelf.centralItemTitleView.set(node.titleView()) + strongSelf.centralItemTitleContent.set(node.titleContent()) strongSelf.centralItemRightBarButtonItem.set(node.rightBarButtonItem()) strongSelf.centralItemRightBarButtonItems.set(node.rightBarButtonItems()) strongSelf.centralItemNavigationStyle.set(node.navigationStyle()) @@ -1714,7 +1729,7 @@ public class GalleryController: ViewController, StandalonePresentableController, let entry = self.entries[centralItemNode.index] self.centralItemTitle.set(centralItemNode.title()) - self.centralItemTitleView.set(centralItemNode.titleView()) + self.centralItemTitleContent.set(centralItemNode.titleContent()) self.centralItemRightBarButtonItem.set(centralItemNode.rightBarButtonItem()) self.centralItemRightBarButtonItems.set(centralItemNode.rightBarButtonItems()) self.centralItemNavigationStyle.set(centralItemNode.navigationStyle()) @@ -1767,7 +1782,7 @@ public class GalleryController: ViewController, StandalonePresentableController, if let centralItemNode = self.galleryNode.pager.centralItemNode() { let message = self.entries[centralItemNode.index].entry.message self.centralItemTitle.set(centralItemNode.title()) - self.centralItemTitleView.set(centralItemNode.titleView()) + self.centralItemTitleContent.set(centralItemNode.titleContent()) self.centralItemRightBarButtonItem.set(centralItemNode.rightBarButtonItem()) self.centralItemRightBarButtonItems.set(centralItemNode.rightBarButtonItems()) self.centralItemNavigationStyle.set(centralItemNode.navigationStyle()) @@ -1912,4 +1927,11 @@ public class GalleryController: ViewController, StandalonePresentableController, return true } + + func dismissAndNavigateToMessageContext(message: Message) { + if let navigateToMessageContext = self.navigateToMessageContext { + navigateToMessageContext(EngineMessage(message)) + } + self.dismiss(forceAway: true) + } } diff --git a/submodules/GalleryUI/Sources/GalleryControllerNode.swift b/submodules/GalleryUI/Sources/GalleryControllerNode.swift index 1c8cf7ec..2c4a9620 100644 --- a/submodules/GalleryUI/Sources/GalleryControllerNode.swift +++ b/submodules/GalleryUI/Sources/GalleryControllerNode.swift @@ -57,7 +57,7 @@ open class GalleryControllerNode: ASDisplayNode, ASScrollViewDelegate, ASGesture } } - public init(context: AccountContext, controllerInteraction: GalleryControllerInteraction, pageGap: CGFloat = 20.0, disableTapNavigation: Bool = false) { + public init(context: AccountContext, controllerInteraction: GalleryControllerInteraction, titleView: UIView? = nil, pageGap: CGFloat = 20.0, disableTapNavigation: Bool = false) { self.context = context self.backgroundNode = ASDisplayNode() self.backgroundNode.backgroundColor = UIColor.black diff --git a/submodules/GalleryUI/Sources/GalleryFooterContentNode.swift b/submodules/GalleryUI/Sources/GalleryFooterContentNode.swift index e4d02722..d3fb0f2d 100644 --- a/submodules/GalleryUI/Sources/GalleryFooterContentNode.swift +++ b/submodules/GalleryUI/Sources/GalleryFooterContentNode.swift @@ -12,14 +12,16 @@ public final class GalleryControllerInteraction { public let replaceRootController: (ViewController, Promise?) -> Void public let editMedia: (MessageId) -> Void public let controller: () -> ViewController? + public let currentItemNode: (() -> GalleryItemNode?)? - public init(presentController: @escaping (ViewController, ViewControllerPresentationArguments?) -> Void, pushController: @escaping (ViewController) -> Void, dismissController: @escaping () -> Void, replaceRootController: @escaping (ViewController, Promise?) -> Void, editMedia: @escaping (MessageId) -> Void, controller: @escaping () -> ViewController?) { + public init(presentController: @escaping (ViewController, ViewControllerPresentationArguments?) -> Void, pushController: @escaping (ViewController) -> Void, dismissController: @escaping () -> Void, replaceRootController: @escaping (ViewController, Promise?) -> Void, editMedia: @escaping (MessageId) -> Void, controller: @escaping () -> ViewController?, currentItemNode: (() -> GalleryItemNode?)? = nil) { self.presentController = presentController self.pushController = pushController self.dismissController = dismissController self.replaceRootController = replaceRootController self.editMedia = editMedia self.controller = controller + self.currentItemNode = currentItemNode } } diff --git a/submodules/GalleryUI/Sources/GalleryItemNode.swift b/submodules/GalleryUI/Sources/GalleryItemNode.swift index 58d07b84..35bd5fa8 100644 --- a/submodules/GalleryUI/Sources/GalleryItemNode.swift +++ b/submodules/GalleryUI/Sources/GalleryItemNode.swift @@ -56,6 +56,10 @@ open class GalleryItemNode: ASDisplayNode { return .single(nil) } + open func titleContent() -> Signal { + return .single(nil) + } + open func rightBarButtonItem() -> Signal { return .single(nil) } diff --git a/submodules/GalleryUI/Sources/GalleryTitleView.swift b/submodules/GalleryUI/Sources/GalleryTitleView.swift index bfae2810..91a37d5f 100644 --- a/submodules/GalleryUI/Sources/GalleryTitleView.swift +++ b/submodules/GalleryUI/Sources/GalleryTitleView.swift @@ -6,15 +6,32 @@ import Postbox import TelegramCore import TelegramPresentationData import TelegramStringFormatting +import AccountContext private let titleFont = Font.medium(15.0) private let dateFont = Font.regular(14.0) -final class GalleryTitleView: UIView, NavigationBarTitleView { +public final class GalleryTitleView: UIView, NavigationBarTitleView { + public struct Content { + let message: EngineMessage? + let title: String? + let action: (() -> Void)? + + init(message: EngineMessage, title: String?, action: (() -> Void)?) { + self.message = message + self.title = title + self.action = action + } + } + private let authorNameNode: ASTextNode private let dateNode: ASTextNode + private var context: AccountContext? + private var presentationDataValue: PresentationData? + private var contentAction: (() -> Void)? + private var tapRecognizer: UITapGestureRecognizer? - var requestUpdate: ((ContainedViewLayoutTransition) -> Void)? + public var requestUpdate: ((ContainedViewLayoutTransition) -> Void)? override init(frame: CGRect) { self.authorNameNode = ASTextNode() @@ -31,6 +48,12 @@ final class GalleryTitleView: UIView, NavigationBarTitleView { self.addSubnode(self.dateNode) } + convenience init(context: AccountContext, presentationData: PresentationData) { + self.init(frame: CGRect()) + self.context = context + self.presentationDataValue = presentationData + } + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @@ -43,7 +66,37 @@ final class GalleryTitleView: UIView, NavigationBarTitleView { self.dateNode.attributedText = NSAttributedString(string: dateText, font: dateFont, textColor: .white) } - func updateLayout(availableSize: CGSize, transition: ContainedViewLayoutTransition) -> CGSize { + func setContent(content: Content?) { + self.contentAction = content?.action + + if self.tapRecognizer == nil { + let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.contentTapped)) + self.addGestureRecognizer(tapRecognizer) + self.tapRecognizer = tapRecognizer + } + self.tapRecognizer?.isEnabled = content?.action != nil + + if let content, let message = content.message, let context = self.context, let presentationData = self.presentationDataValue { + self.setMessage(message._asMessage(), presentationData: presentationData, accountPeerId: context.account.peerId) + if let title = content.title { + self.authorNameNode.attributedText = NSAttributedString(string: title, font: titleFont, textColor: .white) + } + } else if let title = content?.title { + self.authorNameNode.attributedText = NSAttributedString(string: title, font: titleFont, textColor: .white) + self.dateNode.attributedText = nil + } else { + self.authorNameNode.attributedText = nil + self.dateNode.attributedText = nil + } + + self.requestUpdate?(.immediate) + } + + @objc private func contentTapped() { + self.contentAction?() + } + + public func updateLayout(availableSize: CGSize, transition: ContainedViewLayoutTransition) -> CGSize { let size = availableSize let leftInset: CGFloat = 0.0 @@ -63,7 +116,7 @@ final class GalleryTitleView: UIView, NavigationBarTitleView { return availableSize } - func animateLayoutTransition() { + public func animateLayoutTransition() { } } diff --git a/submodules/GalleryUI/Sources/Items/ChatImageGalleryItem.swift b/submodules/GalleryUI/Sources/Items/ChatImageGalleryItem.swift index 48fea8c8..9ae7add1 100644 --- a/submodules/GalleryUI/Sources/Items/ChatImageGalleryItem.swift +++ b/submodules/GalleryUI/Sources/Items/ChatImageGalleryItem.swift @@ -756,7 +756,7 @@ final class ChatImageGalleryItemNode: ZoomableContentGalleryItemNode { guard let controller = self.baseNavigationController()?.topViewController as? ViewController else { return } - let contextController = ContextController(presentationData: self.presentationData.withUpdated(theme: defaultDarkColorPresentationTheme), source: .reference(HeaderContextReferenceContentSource(controller: controller, sourceNode: self.moreBarButton.referenceNode, actionsOnTop: false)), items: items |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) + let contextController = ContextController(presentationData: self.presentationData.withUpdated(theme: defaultDarkColorPresentationTheme), source: .reference(HeaderContextReferenceContentSource(controller: controller, sourceView: sourceNode.view, actionsOnTop: false)), items: items |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) controller.presentInGlobalOverlay(contextController) } diff --git a/submodules/GalleryUI/Sources/Items/UniversalVideoGalleryItem.swift b/submodules/GalleryUI/Sources/Items/UniversalVideoGalleryItem.swift index 216ad401..9359d626 100644 --- a/submodules/GalleryUI/Sources/Items/UniversalVideoGalleryItem.swift +++ b/submodules/GalleryUI/Sources/Items/UniversalVideoGalleryItem.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import AsyncDisplayKit @@ -36,6 +37,7 @@ import ComponentDisplayAdapters import ToastComponent import MultilineTextComponent import BundleIconComponent +import VideoPlaybackControlsComponent public enum UniversalVideoGalleryItemContentInfo { case message(Message, Int?) @@ -100,32 +102,14 @@ public class UniversalVideoGalleryItem: GalleryItem { public func node(synchronous: Bool) -> GalleryItemNode { let node = UniversalVideoGalleryItemNode(context: self.context, presentationData: self.presentationData, performAction: self.performAction, openActionOptions: self.openActionOptions, present: self.present) - if let indexData = self.indexData { - node._title.set(.single(self.presentationData.strings.Items_NOfM("\(indexData.position + 1)", "\(indexData.totalCount)").string)) - } else if case let .message(message, _) = self.contentInfo, let _ = message.adAttribute { - node._title.set(.single(self.presentationData.strings.Gallery_Ad)) - } - node.setupItem(self) - if self.displayInfoOnTop, case let .message(message, _) = self.contentInfo { - node.titleContentView?.setMessage(message, presentationData: self.presentationData, accountPeerId: self.context.account.peerId) - } - return node } public func updateNode(node: GalleryItemNode, synchronous: Bool) { if let node = node as? UniversalVideoGalleryItemNode { - if let indexData = self.indexData { - node._title.set(.single(self.presentationData.strings.Items_NOfM("\(indexData.position + 1)", "\(indexData.totalCount)").string)) - } - node.setupItem(self) - - if self.displayInfoOnTop, case let .message(message, _) = self.contentInfo { - node.titleContentView?.setMessage(message, presentationData: self.presentationData, accountPeerId: self.context.account.peerId) - } } } @@ -237,7 +221,7 @@ private final class UniversalVideoGalleryItemOverlayNode: GalleryOverlayContentN var performAction: ((GalleryControllerInteractionTapAction) -> Void)? var presentPremiumDemo: (() -> Void)? - var openMoreMenu: ((ContextReferenceContentNode, Message) -> Void)? + var openMoreMenu: ((UIView, Message) -> Void)? private var validLayout: (size: CGSize, metrics: LayoutMetrics, insets: UIEdgeInsets)? @@ -373,7 +357,7 @@ private final class UniversalVideoGalleryItemOverlayNode: GalleryOverlayContentN }, moreAction: { [weak self] sourceNode in if let self { - self.openMoreMenu?(sourceNode, adMessage) + self.openMoreMenu?(sourceNode.view, adMessage) } } ) @@ -434,14 +418,18 @@ func optionsBackgroundImage(dark: Bool) -> UIImage? { } func optionsCircleImage(dark: Bool) -> UIImage? { - return generateImage(CGSize(width: 22.0, height: 22.0), contextGenerator: { size, context in + return generateImage(CGSize(width: 44.0, height: 44.0), contextGenerator: { size, context in context.clear(CGRect(origin: CGPoint(), size: size)) - context.setStrokeColor(UIColor.white.cgColor) - let lineWidth: CGFloat = 1.3 - context.setLineWidth(lineWidth) - - context.strokeEllipse(in: CGRect(origin: CGPoint(), size: size).insetBy(dx: lineWidth, dy: lineWidth)) + context.setFillColor(UIColor.white.cgColor) + + let spacing: CGFloat = 3.66 + let width: CGFloat = 4.33 + for i in 0 ..< 3 { + let x: CGFloat = floorToScreenPixels((size.width - width * 3.0 - spacing * 2.0) * 0.5) + CGFloat(i) * (width + spacing) + let y: CGFloat = floorToScreenPixels((size.height - width) * 0.5) + context.fillEllipse(in: CGRect(origin: CGPoint(x: x, y: y), size: CGSize(width: width, height: width))) + } }) } @@ -491,7 +479,6 @@ final class MoreHeaderButton: HighlightableButtonNode { let referenceNode: ContextReferenceContentNode let containerNode: ContextControllerSourceNode private let iconNode: ASImageNode - private var animationNode: AnimationNode? var contextAction: ((ASDisplayNode, ContextGesture?) -> Void)? @@ -527,29 +514,17 @@ final class MoreHeaderButton: HighlightableButtonNode { strongSelf.contextAction?(strongSelf.containerNode, gesture) } - self.containerNode.frame = CGRect(origin: CGPoint(), size: CGSize(width: 26.0, height: 44.0)) + self.containerNode.frame = CGRect(origin: CGPoint(), size: CGSize(width: 44.0, height: 44.0)) self.referenceNode.frame = self.containerNode.bounds self.iconNode.image = optionsCircleImage(dark: false) if let image = self.iconNode.image { self.iconNode.frame = CGRect(origin: CGPoint(x: floor((self.containerNode.bounds.width - image.size.width) / 2.0), y: floor((self.containerNode.bounds.height - image.size.height) / 2.0)), size: image.size) } - - self.hitTestSlop = UIEdgeInsets(top: 0.0, left: -4.0, bottom: 0.0, right: -4.0) } private var content: Content? func setContent(_ content: Content, animated: Bool = false) { - if case .more = content, self.animationNode == nil { - let iconColor = UIColor(rgb: 0xffffff) - let animationNode = AnimationNode(animation: "anim_profilemore", colors: ["Point 2.Group 1.Fill 1": iconColor, - "Point 3.Group 1.Fill 1": iconColor, - "Point 1.Group 1.Fill 1": iconColor], scale: 1.0) - let animationSize = CGSize(width: 22.0, height: 22.0) - animationNode.frame = CGRect(origin: CGPoint(x: floor((self.containerNode.bounds.width - animationSize.width) / 2.0), y: floor((self.containerNode.bounds.height - animationSize.height) / 2.0)), size: animationSize) - self.addSubnode(animationNode) - self.animationNode = animationNode - } if animated { if let snapshotView = self.referenceNode.view.snapshotContentTree() { snapshotView.frame = self.referenceNode.frame @@ -562,9 +537,6 @@ final class MoreHeaderButton: HighlightableButtonNode { self.iconNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.3) self.iconNode.layer.animateScale(from: 0.1, to: 1.0, duration: 0.3) - - self.animationNode?.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.3) - self.animationNode?.layer.animateScale(from: 0.1, to: 1.0, duration: 0.3) } switch content { @@ -575,7 +547,6 @@ final class MoreHeaderButton: HighlightableButtonNode { self.iconNode.image = image self.iconNode.isHidden = false - self.animationNode?.isHidden = true case let .more(image): if let image = image { self.iconNode.frame = CGRect(origin: CGPoint(x: floor((self.containerNode.bounds.width - image.size.width) / 2.0), y: floor((self.containerNode.bounds.height - image.size.height) / 2.0)), size: image.size) @@ -583,7 +554,6 @@ final class MoreHeaderButton: HighlightableButtonNode { self.iconNode.image = image self.iconNode.isHidden = false - self.animationNode?.isHidden = false } } else { self.content = content @@ -595,7 +565,6 @@ final class MoreHeaderButton: HighlightableButtonNode { self.iconNode.image = image self.iconNode.isHidden = false - self.animationNode?.isHidden = true case let .more(image): if let image = image { self.iconNode.frame = CGRect(origin: CGPoint(x: floor((self.containerNode.bounds.width - image.size.width) / 2.0), y: floor((self.containerNode.bounds.height - image.size.height) / 2.0)), size: image.size) @@ -603,7 +572,6 @@ final class MoreHeaderButton: HighlightableButtonNode { self.iconNode.image = image self.iconNode.isHidden = false - self.animationNode?.isHidden = false } } } @@ -614,236 +582,13 @@ final class MoreHeaderButton: HighlightableButtonNode { } override func calculateSizeThatFits(_ constrainedSize: CGSize) -> CGSize { - return CGSize(width: wide ? 32.0 : 22.0, height: 44.0) + return CGSize(width: 44.0, height: 44.0) } func onLayout() { } func play() { - self.animationNode?.playOnce() - } -} - -final class SettingsHeaderButton: HighlightableButtonNode { - let referenceNode: ContextReferenceContentNode - let containerNode: ContextControllerSourceNode - - private let iconLayer: RasterizedCompositionMonochromeLayer - - private let gearsLayer: RasterizedCompositionImageLayer - private let dotLayer: RasterizedCompositionImageLayer - - private var speedBadge: ComponentView? - private var qualityBadge: ComponentView? - - private var speedBadgeText: String? - private var qualityBadgeText: String? - - private let badgeFont: UIFont - - private var isMenuOpen: Bool = false - - var contextAction: ((ASDisplayNode, ContextGesture?) -> Void)? - - private let wide: Bool - - init(wide: Bool = false) { - self.wide = wide - - self.referenceNode = ContextReferenceContentNode() - self.containerNode = ContextControllerSourceNode() - self.containerNode.animateScale = false - - self.iconLayer = RasterizedCompositionMonochromeLayer() - //self.iconLayer.backgroundColor = UIColor.green.cgColor - - self.gearsLayer = RasterizedCompositionImageLayer() - self.gearsLayer.image = generateTintedImage(image: UIImage(bundleImageName: "Media Gallery/NavigationSettingsNoDot"), color: .white) - - self.dotLayer = RasterizedCompositionImageLayer() - self.dotLayer.image = generateFilledCircleImage(diameter: 4.0, color: .white) - - self.iconLayer.contentsLayer.addSublayer(self.gearsLayer) - self.iconLayer.contentsLayer.addSublayer(self.dotLayer) - - self.badgeFont = Font.with(size: 8.0, design: .round, weight: .bold) - - super.init() - - self.containerNode.addSubnode(self.referenceNode) - self.referenceNode.layer.addSublayer(self.iconLayer) - self.addSubnode(self.containerNode) - - self.containerNode.shouldBegin = { [weak self] location in - guard let strongSelf = self, let _ = strongSelf.contextAction else { - return false - } - return true - } - self.containerNode.activated = { [weak self] gesture, _ in - guard let strongSelf = self else { - return - } - strongSelf.contextAction?(strongSelf.containerNode, gesture) - } - - self.containerNode.frame = CGRect(origin: CGPoint(), size: CGSize(width: 26.0, height: 44.0)) - self.referenceNode.frame = self.containerNode.bounds - - self.hitTestSlop = UIEdgeInsets(top: 0.0, left: -4.0, bottom: 0.0, right: -4.0) - - if let image = self.gearsLayer.image { - let iconInnerInsets = UIEdgeInsets(top: 4.0, left: 8.0, bottom: 4.0, right: 6.0) - let iconSize = CGSize(width: image.size.width + iconInnerInsets.left + iconInnerInsets.right, height: image.size.height + iconInnerInsets.top + iconInnerInsets.bottom) - let iconFrame = CGRect(origin: CGPoint(x: floor((self.containerNode.bounds.width - iconSize.width) / 2.0), y: floor((self.containerNode.bounds.height - iconSize.height) / 2.0)), size: iconSize) - self.iconLayer.position = iconFrame.center - self.iconLayer.bounds = CGRect(origin: CGPoint(), size: iconFrame.size) - - self.iconLayer.contentsLayer.position = CGRect(origin: CGPoint(), size: iconFrame.size).center - self.iconLayer.contentsLayer.bounds = CGRect(origin: CGPoint(), size: iconFrame.size) - - self.iconLayer.maskedLayer.position = CGRect(origin: CGPoint(), size: iconFrame.size).center - self.iconLayer.maskedLayer.bounds = CGRect(origin: CGPoint(), size: iconFrame.size) - self.iconLayer.maskedLayer.backgroundColor = UIColor.white.cgColor - - let gearsFrame = CGRect(origin: CGPoint(x: floor((iconSize.width - image.size.width) * 0.5), y: floor((iconSize.height - image.size.height) * 0.5)), size: image.size) - self.gearsLayer.position = gearsFrame.center - self.gearsLayer.bounds = CGRect(origin: CGPoint(), size: gearsFrame.size) - - if let dotImage = self.dotLayer.image { - let dotFrame = CGRect(origin: CGPoint(x: gearsFrame.minX + floorToScreenPixels((gearsFrame.width - dotImage.size.width) * 0.5), y: gearsFrame.minY + floorToScreenPixels((gearsFrame.height - dotImage.size.height) * 0.5)), size: dotImage.size) - self.dotLayer.position = dotFrame.center - self.dotLayer.bounds = CGRect(origin: CGPoint(), size: dotFrame.size) - } - } - } - - override func didLoad() { - super.didLoad() - self.view.isOpaque = false - } - - override func calculateSizeThatFits(_ constrainedSize: CGSize) -> CGSize { - return CGSize(width: wide ? 32.0 : 22.0, height: 44.0) - } - - func onLayout() { - } - - func setIsMenuOpen(isMenuOpen: Bool) { - if self.isMenuOpen == isMenuOpen { - return - } - self.isMenuOpen = isMenuOpen - - let rotationTransition: ContainedViewLayoutTransition = .animated(duration: 0.35, curve: .spring) - rotationTransition.updateTransform(layer: self.gearsLayer, transform: CGAffineTransformMakeRotation(isMenuOpen ? (CGFloat.pi * 2.0 / 6.0) : 0.0)) - self.gearsLayer.animateScale(from: 1.0, to: 1.07, duration: 0.1, removeOnCompletion: false, completion: { [weak self] finished in - guard let self, finished else { - return - } - self.gearsLayer.animateScale(from: 1.07, to: 1.0, duration: 0.1, removeOnCompletion: true) - }) - - self.dotLayer.animateScale(from: 1.0, to: 0.8, duration: 0.1, removeOnCompletion: false, completion: { [weak self] finished in - guard let self, finished else { - return - } - self.dotLayer.animateScale(from: 0.8, to: 1.0, duration: 0.1, removeOnCompletion: true) - }) - } - - func setBadges(speed: String?, quality: String?, transition: ComponentTransition) { - if self.speedBadgeText == speed && self.qualityBadgeText == quality { - return - } - self.speedBadgeText = speed - self.qualityBadgeText = quality - - if let badgeText = speed { - var badgeTransition = transition - let speedBadge: ComponentView - if let current = self.speedBadge { - speedBadge = current - } else { - speedBadge = ComponentView() - self.speedBadge = speedBadge - badgeTransition = badgeTransition.withAnimation(.none) - } - let badgeSize = speedBadge.update( - transition: badgeTransition, - component: AnyComponent(BadgeComponent( - text: badgeText, - font: self.badgeFont, - cornerRadius: .custom(3.0), - insets: UIEdgeInsets(top: 1.33, left: 1.66, bottom: 1.33, right: 1.66), - outerInsets: UIEdgeInsets(top: 1.0, left: 1.0, bottom: 1.0, right: 1.0) - )), - environment: {}, - containerSize: CGSize(width: 100.0, height: 100.0) - ) - if let speedBadgeView = speedBadge.view { - if speedBadgeView.layer.superlayer == nil { - self.iconLayer.contentsLayer.addSublayer(speedBadgeView.layer) - - transition.animateAlpha(layer: speedBadgeView.layer, from: 0.0, to: 1.0) - transition.animateScale(layer: speedBadgeView.layer, from: 0.001, to: 1.0) - } - badgeTransition.setFrame(layer: speedBadgeView.layer, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: badgeSize)) - } - } else if let speedBadge = self.speedBadge { - self.speedBadge = nil - if let speedBadgeView = speedBadge.view { - let speedBadgeLayer = speedBadgeView.layer - transition.setAlpha(layer: speedBadgeLayer, alpha: 0.0, completion: { [weak speedBadgeLayer] _ in - speedBadgeLayer?.removeFromSuperlayer() - }) - transition.setScale(layer: speedBadgeLayer, scale: 0.001) - } - } - - if let badgeText = quality { - var badgeTransition = transition - let qualityBadge: ComponentView - if let current = self.qualityBadge { - qualityBadge = current - } else { - qualityBadge = ComponentView() - self.qualityBadge = qualityBadge - badgeTransition = badgeTransition.withAnimation(.none) - } - let badgeSize = qualityBadge.update( - transition: badgeTransition, - component: AnyComponent(BadgeComponent( - text: badgeText, - font: self.badgeFont, - cornerRadius: .custom(3.0), - insets: UIEdgeInsets(top: 1.33, left: 1.66, bottom: 1.33, right: 1.66), - outerInsets: UIEdgeInsets(top: 1.0, left: 1.0, bottom: 1.0, right: 1.0) - )), - environment: {}, - containerSize: CGSize(width: 100.0, height: 100.0) - ) - if let qualityBadgeView = qualityBadge.view { - if qualityBadgeView.layer.superlayer == nil { - self.iconLayer.contentsLayer.addSublayer(qualityBadgeView.layer) - - transition.animateAlpha(layer: qualityBadgeView.layer, from: 0.0, to: 1.0) - transition.animateScale(layer: qualityBadgeView.layer, from: 0.001, to: 1.0) - } - badgeTransition.setFrame(layer: qualityBadgeView.layer, frame: CGRect(origin: CGPoint(x: self.iconLayer.bounds.width - badgeSize.width, y: self.iconLayer.bounds.height - badgeSize.height), size: badgeSize)) - } - } else if let qualityBadge = self.qualityBadge { - self.qualityBadge = nil - if let qualityBadgeView = qualityBadge.view { - let qualityBadgeLayer = qualityBadgeView.layer - transition.setAlpha(layer: qualityBadgeLayer, alpha: 0.0, completion: { [weak qualityBadgeLayer] _ in - qualityBadgeLayer?.removeFromSuperlayer() - }) - transition.setScale(layer: qualityBadgeLayer, scale: 0.001) - } - } } } @@ -1117,7 +862,7 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { fileprivate let _ready = Promise() fileprivate let _title = Promise() - fileprivate let _titleView = Promise() + fileprivate let _titleContent = Promise(nil) fileprivate let _rightBarButtonItems = Promise<[UIBarButtonItem]?>() fileprivate var titleContentView: GalleryTitleView? @@ -1129,8 +874,6 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { private var moreBarButtonRate: Double = 1.0 private var moreBarButtonRateTimestamp: Double? - private let settingsBarButton: SettingsHeaderButton - private var videoNode: UniversalVideoNode? private var videoNodeUserInteractionEnabled: Bool = false private var videoFramePreview: FramePreview? @@ -1140,6 +883,8 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { private let statusNode: RadialStatusNode private var statusNodeShouldBeHidden = true + private let playbackControls = ComponentView() + private var isCentral: Bool? private var _isVisible: Bool? private var initiallyActivated = false @@ -1153,6 +898,8 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { private var dismissOnOrientationChange = false private var keepSoundOnDismiss = false private var hasPictureInPicture = false + private var displayStickersButton: Bool = false + private var settingsButtonState: ChatItemGalleryFooterContentNode.SettingsButtonState? private var pictureInPictureButton: UIBarButtonItem? @@ -1168,7 +915,6 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { private let statusDisposable = MetaDisposable() private let moreButtonStateDisposable = MetaDisposable() - private let settingsButtonStateDisposable = MetaDisposable() private let mediaPlaybackStateDisposable = MetaDisposable() private let fetchDisposable = MetaDisposable() @@ -1182,6 +928,7 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { private var isPlaying = false private let isPlayingPromise = ValuePromise(false, ignoreRepeated: true) private let isInteractingPromise = ValuePromise(false, ignoreRepeated: true) + private var areControlsVisible: Bool = true private let controlsVisiblePromise = ValuePromise(true, ignoreRepeated: true) private let isShowingContextMenuPromise = ValuePromise(false, ignoreRepeated: true) private let isShowingSettingsMenuPromise = ValuePromise(false, ignoreRepeated: true) @@ -1227,9 +974,6 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { self.moreBarButton.isUserInteractionEnabled = true self.moreBarButton.setContent(.more(optionsCircleImage(dark: false))) - self.settingsBarButton = SettingsHeaderButton() - self.settingsBarButton.isUserInteractionEnabled = true - super.init() self.clipsToBounds = true @@ -1259,7 +1003,6 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { } self.moreBarButton.addTarget(self, action: #selector(self.moreButtonPressed), forControlEvents: .touchUpInside) - self.settingsBarButton.addTarget(self, action: #selector(self.settingsButtonPressed), forControlEvents: .touchUpInside) self.footerContentNode.interacting = { [weak self] value in self?.isInteractingPromise.set(value) @@ -1268,8 +1011,6 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { self.statusButtonNode.addSubnode(self.statusNode) self.statusButtonNode.addTarget(self, action: #selector(self.statusButtonPressed), forControlEvents: .touchUpInside) - self.addSubnode(self.statusButtonNode) - self.footerContentNode.playbackControl = { [weak self] in if let strongSelf = self { if !strongSelf.isPaused { @@ -1373,12 +1114,9 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { if case let .message(message, _) = self.item?.contentInfo, let _ = message.adAttribute { adMessage = message } - self.openMoreMenu(sourceNode: self.moreBarButton.referenceNode, gesture: gesture, adMessage: adMessage, isSettings: false) + self.openMoreMenu(sourceView: self.moreBarButton.referenceNode.view, gesture: gesture, adMessage: adMessage, isSettings: false) } - self.titleContentView = GalleryTitleView(frame: CGRect()) - self._titleView.set(.single(self.titleContentView)) - let shouldHideControlsSignal: Signal = combineLatest(self.isPlayingPromise.get(), self.isInteractingPromise.get(), self.controlsVisiblePromise.get(), self.isShowingContextMenuPromise.get(), self.isShowingSettingsMenuPromise.get(), self.isShowingAdMenuPromise.get(), self.hasExpandedCaptionPromise.get()) |> mapToSignal { isPlaying, isInteracting, controlsVisible, isShowingContextMenu, isShowingSettingsMenu, isShowingAdMenu, hasExpandedCaptionPromise -> Signal in if isShowingContextMenu || isShowingSettingsMenu || isShowingAdMenu || hasExpandedCaptionPromise { @@ -1403,7 +1141,6 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { deinit { self.statusDisposable.dispose() self.moreButtonStateDisposable.dispose() - self.settingsButtonStateDisposable.dispose() self.mediaPlaybackStateDisposable.dispose() self.scrubbingFrameDisposable?.dispose() self.hideControlsDisposable?.dispose() @@ -1451,6 +1188,60 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { transition.updateFrame(node: self.statusButtonNode, frame: statusFrame) transition.updateFrame(node: self.statusNode, frame: CGRect(origin: CGPoint(), size: statusFrame.size)) + let hideControls = self.item?.hideControls ?? true + + var playbackControlsIsPlaying: Bool = false + var playbackControlsIsSeekable: Bool = false + var playbackControlsIsVisible: Bool = false + if case let .playback(paused, seekable) = self.footerContentNode.content { + playbackControlsIsVisible = true + playbackControlsIsSeekable = seekable + playbackControlsIsPlaying = !paused + } + if !self.areControlsVisible || hideControls { + playbackControlsIsVisible = false + } + + let playbackControlsSize = self.playbackControls.update( + transition: ComponentTransition(transition), + component: AnyComponent(VideoPlaybackControlsComponent( + layoutParams: VideoPlaybackControlsComponent.LayoutParams( + sideButtonSize: 64.0, + centerButtonSize: 92.0, + spacing: 30.0 + ), + isVisible: playbackControlsIsVisible, + isPlaying: playbackControlsIsPlaying, + displaySeekControls: playbackControlsIsSeekable, + togglePlayback: { [weak self] in + guard let self else { + return + } + self.footerContentNode.playbackControlPressed() + }, + seek: { [weak self] isForward in + guard let self else { + return + } + if isForward { + self.footerContentNode.seekForward?(15.0) + } else { + self.footerContentNode.seekBackward?(15.0) + } + } + )), + environment: {}, + containerSize: CGSize(width: 1000.0, height: 1000.0) + ) + let playbackControlsFrame = CGRect(origin: CGPoint(x: floor((layout.size.width - playbackControlsSize.width) / 2.0), y: floor((layout.size.height - playbackControlsSize.height) / 2.0)), size: playbackControlsSize) + if let playbackControlsView = self.playbackControls.view { + if playbackControlsView.superview == nil { + self.view.addSubview(playbackControlsView) + } + let transition = ComponentTransition(transition) + transition.setFrame(view: playbackControlsView, frame: playbackControlsFrame) + } + if let pictureInPictureNode = self.pictureInPictureNode { if let item = self.item { var placeholderSize = item.content.dimensions.fitted(layout.size) @@ -1822,15 +1613,27 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { } } - self.settingsBarButton.setBadges(speed: rateString, quality: qualityString, transition: .spring(duration: 0.35)) - })) - - self.settingsButtonStateDisposable.set((self.isShowingSettingsMenuPromise.get() - |> deliverOnMainQueue).start(next: { [weak self] isShowingSettingsMenu in - guard let self else { - return + if self.settingsButtonState != nil { + let settingsButtonState = ChatItemGalleryFooterContentNode.SettingsButtonState( + speed: rateString, + quality: qualityString + ) + if self.settingsButtonState != settingsButtonState { + self.settingsButtonState = settingsButtonState + if let validLayout = self.validLayout { + if let contentInfo = item.contentInfo { + switch contentInfo { + case let .message(message, _): + self.footerContentNode.setMessage(message, displayInfo: !item.displayInfoOnTop, peerIsCopyProtected: item.peerIsCopyProtected, displayPictureInPictureButton: self.hasPictureInPicture, settingsButtonState: self.settingsButtonState, displayStickersButton: self.displayStickersButton, animated: true) + case let .webPage(webPage, media, _): + self.footerContentNode.setWebPage(webPage, media: media) + } + } + + self.containerLayoutUpdated(validLayout.layout, navigationBarHeight: validLayout.navigationBarHeight, transition: .animated(duration: 0.4, curve: .spring)) + } + } } - self.settingsBarButton.setIsMenuOpen(isMenuOpen: isShowingSettingsMenu) })) self.statusDisposable.set((combineLatest(queue: .mainQueue(), videoNode.status, mediaFileStatus) @@ -1894,11 +1697,13 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { isPaused = false } } else if strongSelf.actionAtEnd == .stop { - strongSelf.isPlayingPromise.set(false) - strongSelf.isPlaying = false - if strongSelf.isCentral == true { - if !item.isSecret && !strongSelf.playOnDismiss { - strongSelf.updateControlsVisibility(true) + if strongSelf.isPlaying { + strongSelf.isPlayingPromise.set(false) + strongSelf.isPlaying = false + if strongSelf.isCentral == true { + if !item.isSecret && !strongSelf.playOnDismiss { + strongSelf.updateControlsVisibility(true) + } } } } @@ -1953,44 +1758,56 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { strongSelf.statusButtonNode.isHidden = strongSelf.hideStatusNodeUntilCentrality || strongSelf.statusNodeShouldBeHidden } + let footerContent: ChatItemGalleryFooterContent if isAnimated || disablePlayerControls { - strongSelf.footerContentNode.content = .info + footerContent = .info } else if isPaused && !strongSelf.ignorePauseStatus && strongSelf.isCentral == true { if hasStarted || strongSelf.didPause { - strongSelf.footerContentNode.content = .playback(paused: true, seekable: seekable) + footerContent = .playback(paused: true, seekable: seekable) } else if let fetchStatus = fetchStatus, !strongSelf.requiresDownload { if item.content is HLSVideoContent { - strongSelf.footerContentNode.content = .playback(paused: true, seekable: seekable) + footerContent = .playback(paused: true, seekable: seekable) } else { - strongSelf.footerContentNode.content = .fetch(status: fetchStatus, seekable: seekable) + footerContent = .fetch(status: fetchStatus, seekable: seekable) } + } else { + footerContent = .info } } else { - strongSelf.footerContentNode.content = .playback(paused: false, seekable: seekable) + footerContent = .playback(paused: false, seekable: seekable) + } + + if strongSelf.footerContentNode.content != footerContent { + strongSelf.footerContentNode.content = footerContent + + if let validLayout = strongSelf.validLayout { + strongSelf.containerLayoutUpdated(validLayout.layout, navigationBarHeight: validLayout.navigationBarHeight, transition: .animated(duration: 0.2, curve: .easeInOut)) + } } } })) self.zoomableContent = (videoSize, videoNode) + + var hasSettingsButton = false var barButtonItems: [UIBarButtonItem] = [] if hasLinkedStickers { - let rightBarButtonItem = UIBarButtonItem(image: generateTintedImage(image: UIImage(bundleImageName: "Media Gallery/Stickers"), color: .white), style: .plain, target: self, action: #selector(self.openStickersButtonPressed)) - rightBarButtonItem.accessibilityLabel = self.presentationData.strings.Gallery_VoiceOver_Stickers - barButtonItems.append(rightBarButtonItem) + self.displayStickersButton = true } if forceEnablePiP || (!isAnimated && !disablePlayerControls && !disablePictureInPicture) { - let rightBarButtonItem = UIBarButtonItem(image: pictureInPictureButtonImage, style: .plain, target: self, action: #selector(self.pictureInPictureButtonPressed)) + /*let rightBarButtonItem = UIBarButtonItem(image: pictureInPictureButtonImage, style: .plain, target: self, action: #selector(self.pictureInPictureButtonPressed)) rightBarButtonItem.accessibilityLabel = self.presentationData.strings.Gallery_VoiceOver_PictureInPicture self.pictureInPictureButton = rightBarButtonItem - barButtonItems.append(rightBarButtonItem) + barButtonItems.append(rightBarButtonItem)*/ self.hasPictureInPicture = true } else { self.hasPictureInPicture = false } - + if let contentInfo = item.contentInfo, case let .message(message, mediaIndex) = contentInfo { + var hasMoreButton = false var file: TelegramMediaFile? for m in message.media { if let m = m as? TelegramMediaFile, m.isVideo { @@ -2009,7 +1826,6 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { } } - var hasMoreButton = false if isEnhancedWebPlayer { hasMoreButton = true } else if let file = file, !file.isAnimated { @@ -2025,9 +1841,7 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { } if !isAnimated && !disablePlayerControls { - let settingsMenuItem = UIBarButtonItem(customDisplayNode: self.settingsBarButton)! - settingsMenuItem.accessibilityLabel = self.presentationData.strings.Settings_Title - barButtonItems.append(settingsMenuItem) + hasSettingsButton = true } if hasMoreButton { @@ -2037,6 +1851,12 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { } } + if hasSettingsButton { + self.settingsButtonState = ChatItemGalleryFooterContentNode.SettingsButtonState( + speed: nil, + quality: nil + ) + } self._rightBarButtonItems.set(.single(barButtonItems)) videoNode.playbackCompleted = { [weak self, weak videoNode] in @@ -2091,7 +1911,7 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { switch contentInfo { case let .message(message, _): isAd = message.adAttribute != nil - self.footerContentNode.setMessage(message, displayInfo: !item.displayInfoOnTop, peerIsCopyProtected: item.peerIsCopyProtected) + self.footerContentNode.setMessage(message, displayInfo: !item.displayInfoOnTop, peerIsCopyProtected: item.peerIsCopyProtected, displayPictureInPictureButton: self.hasPictureInPicture, settingsButtonState: self.settingsButtonState, displayStickersButton: self.displayStickersButton) case let .webPage(webPage, media, _): self.footerContentNode.setWebPage(webPage, media: media) } @@ -2115,18 +1935,42 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { self.overlayContentNode.presentPremiumDemo = { [weak self] in self?.presentPremiumDemo() } - self.overlayContentNode.openMoreMenu = { [weak self] sourceNode, adMessage in - self?.openMoreMenu(sourceNode: sourceNode, gesture: nil, adMessage: adMessage, isSettings: false, actionsOnTop: true) + self.overlayContentNode.openMoreMenu = { [weak self] sourceView, adMessage in + self?.openMoreMenu(sourceView: sourceView, gesture: nil, adMessage: adMessage, isSettings: false, actionsOnTop: true) } self.overlayContentNode.setMessage(context: item.context, message: message) } + + var title: String? + if let indexData = item.indexData { + title = self.presentationData.strings.Items_NOfM("\(indexData.position + 1)", "\(indexData.totalCount)").string + } else if case let .message(message, _) = item.contentInfo, let _ = message.adAttribute { + title = self.presentationData.strings.Gallery_Ad + } + + if case let .message(message, _) = item.contentInfo { + self._titleContent.set(.single(GalleryTitleView.Content(message: EngineMessage(message), title: title, action: message.adAttribute == nil ? { [weak self] in + guard let self else { + return + } + guard let controller = self.galleryController() as? GalleryController else { + return + } + controller.dismissAndNavigateToMessageContext(message: message) + } : nil))) + } } override func controlsVisibilityUpdated(isVisible: Bool) { + self.areControlsVisible = isVisible self.controlsVisiblePromise.set(isVisible) self.videoNode?.isUserInteractionEnabled = isVisible ? self.videoNodeUserInteractionEnabled : false self.videoNode?.notifyPlaybackControlsHidden(!isVisible) + + if let validLayout = self.validLayout { + self.containerLayoutUpdated(validLayout.layout, navigationBarHeight: validLayout.navigationBarHeight, transition: .animated(duration: 0.2, curve: .easeInOut)) + } } private func updateDisplayPlaceholder() { @@ -2546,6 +2390,12 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { self.statusButtonNode.layer.animatePosition(from: CGPoint(x: transformedSuperFrame.midX, y: transformedSuperFrame.midY), to: self.statusButtonNode.position, duration: 0.25, timingFunction: kCAMediaTimingFunctionSpring) self.statusButtonNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.25, timingFunction: kCAMediaTimingFunctionSpring) self.statusButtonNode.layer.animateScale(from: 0.5, to: 1.0, duration: 0.25, timingFunction: kCAMediaTimingFunctionSpring) + + if let playbackControlsView = self.playbackControls.view { + playbackControlsView.layer.animatePosition(from: CGPoint(x: transformedSuperFrame.midX, y: transformedSuperFrame.midY), to: playbackControlsView.layer.position, duration: 0.25, timingFunction: kCAMediaTimingFunctionSpring) + playbackControlsView.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2, timingFunction: kCAMediaTimingFunctionSpring) + playbackControlsView.layer.animateScale(from: 0.2, to: 1.0, duration: 0.25, timingFunction: kCAMediaTimingFunctionSpring) + } } } @@ -2637,6 +2487,13 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { self.statusButtonNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.25, removeOnCompletion: false) self.statusButtonNode.layer.animateScale(from: 1.0, to: 0.2, duration: 0.25, removeOnCompletion: false) + if let playbackControlsView = self.playbackControls.view { + playbackControlsView.layer.animatePosition(from: playbackControlsView.layer.position, to: CGPoint(x: transformedSelfFrame.midX, y: transformedSelfFrame.midY), duration: 0.25, timingFunction: kCAMediaTimingFunctionSpring, removeOnCompletion: false, completion: { _ in + }) + playbackControlsView.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.25, removeOnCompletion: false) + playbackControlsView.layer.animateScale(from: 1.0, to: 0.2, duration: 0.25, removeOnCompletion: false) + } + let fromTransform: CATransform3D let toTransform: CATransform3D @@ -2862,6 +2719,12 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { } override func maybePerformActionForSwipeDismiss() -> Bool { + if #available(iOS 15.0, *) { + if SGSimpleSettings.shared.videoPIPSwipeDirection != SGSimpleSettings.VideoPIPSwipeDirection.up.rawValue { + return false + } + } + if let data = self.context.currentAppConfiguration.with({ $0 }).data { if let _ = data["ios_killswitch_disable_swipe_pip"] { return false @@ -2899,8 +2762,8 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { return self._title.get() } - override func titleView() -> Signal { - return self._titleView.get() + override func titleContent() -> Signal { + return self._titleContent.get() } override func rightBarButtonItems() -> Signal<[UIBarButtonItem]?, NoError> { @@ -3036,7 +2899,7 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { switch contentInfo { case let .message(message, _): isAd = message.adAttribute != nil - self.footerContentNode.setMessage(message, displayInfo: !item.displayInfoOnTop, peerIsCopyProtected: item.peerIsCopyProtected) + self.footerContentNode.setMessage(message, displayInfo: !item.displayInfoOnTop, peerIsCopyProtected: item.peerIsCopyProtected, displayPictureInPictureButton: self.hasPictureInPicture, settingsButtonState: self.settingsButtonState, displayStickersButton: self.displayStickersButton) case let .webPage(webPage, media, _): self.footerContentNode.setWebPage(webPage, media: media) } @@ -3237,7 +3100,7 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { } private var playOnDismiss = false - private func openMoreMenu(sourceNode: ContextReferenceContentNode, gesture: ContextGesture?, adMessage: Message?, isSettings: Bool, actionsOnTop: Bool = false) { + private func openMoreMenu(sourceView: UIView, gesture: ContextGesture?, adMessage: Message?, isSettings: Bool, actionsOnTop: Bool = false) { guard let controller = self.baseNavigationController()?.topViewController as? ViewController else { return } @@ -3254,7 +3117,10 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { }) } - let contextController = ContextController(presentationData: self.presentationData.withUpdated(theme: defaultDarkColorPresentationTheme), source: .reference(HeaderContextReferenceContentSource(controller: controller, sourceNode: sourceNode, actionsOnTop: actionsOnTop)), items: items |> map { items in + let sourceView = sourceView + _ = isSettings + + let contextController = makeContextController(presentationData: self.presentationData.withUpdated(theme: defaultDarkColorPresentationTheme), source: .reference(HeaderContextReferenceContentSource(controller: controller, sourceView: sourceView, actionsOnTop: actionsOnTop)), items: items |> map { items in if !items.topItems.isEmpty { return ContextController.Items(id: AnyHashable(0), content: .twoLists(items.items, items.topItems)) } else { @@ -3761,16 +3627,16 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { f(.default) }))) } - - // if #available(iOS 11.0, *) { - // items.append(.action(ContextMenuActionItem(text: "AirPlay", textColor: .primary, icon: { theme in generateTintedImage(image: UIImage(bundleImageName: "Media Gallery/AirPlay"), color: theme.contextMenu.primaryColor) }, action: { [weak self] _, f in - // f(.default) - // guard let strongSelf = self else { - // return - // } - // strongSelf.beginAirPlaySetup() - // }))) - // } + // MARK: Swiftgram + if #available(iOS 11.0, *) { + items.append(.action(ContextMenuActionItem(text: "AirPlay", textColor: .primary, icon: { theme in generateTintedImage(image: UIImage(bundleImageName: "Media Gallery/AirPlay"), color: theme.contextMenu.primaryColor) }, action: { [weak self] _, f in + f(.default) + guard let strongSelf = self else { + return + } + strongSelf.beginAirPlaySetup() + }))) + } if let (message, _, _) = strongSelf.contentInfo() { for media in message.media { @@ -3912,8 +3778,8 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { }) } - @objc private func settingsButtonPressed() { - self.openMoreMenu(sourceNode: self.settingsBarButton.referenceNode, gesture: nil, adMessage: nil, isSettings: true) + func settingsButtonPressed(sourceView: UIView) { + self.openMoreMenu(sourceView: sourceView, gesture: nil, adMessage: nil, isSettings: true, actionsOnTop: true) } override func adjustForPreviewing() { @@ -4087,17 +3953,17 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { final class HeaderContextReferenceContentSource: ContextReferenceContentSource { private let controller: ViewController - private let sourceNode: ContextReferenceContentNode + private let sourceView: UIView private let actionsOnTop: Bool - init(controller: ViewController, sourceNode: ContextReferenceContentNode, actionsOnTop: Bool) { + init(controller: ViewController, sourceView: UIView, actionsOnTop: Bool) { self.controller = controller - self.sourceNode = sourceNode + self.sourceView = sourceView self.actionsOnTop = actionsOnTop } func transitionInfo() -> ContextControllerReferenceViewInfo? { - return ContextControllerReferenceViewInfo(referenceView: self.sourceNode.view, contentAreaInScreenSpace: UIScreen.main.bounds, actionsPosition: self.actionsOnTop ? .top : .bottom) + return ContextControllerReferenceViewInfo(referenceView: self.sourceView, contentAreaInScreenSpace: UIScreen.main.bounds, actionsPosition: self.actionsOnTop ? .top : .bottom) } } diff --git a/submodules/ItemListPeerActionItem/Sources/ItemListPeerActionItem.swift b/submodules/ItemListPeerActionItem/Sources/ItemListPeerActionItem.swift index 3f877671..830ce2dd 100644 --- a/submodules/ItemListPeerActionItem/Sources/ItemListPeerActionItem.swift +++ b/submodules/ItemListPeerActionItem/Sources/ItemListPeerActionItem.swift @@ -34,9 +34,10 @@ public class ItemListPeerActionItem: ListViewItem, ItemListItem { let color: ItemListPeerActionItemColor let noInsets: Bool public let sectionId: ItemListSectionId + public let tag: ItemListItemTag? public let action: (() -> Void)? - public init(presentationData: ItemListPresentationData, style: ItemListStyle = .blocks, systemStyle: ItemListSystemStyle = .legacy, icon: UIImage?, iconSignal: Signal? = nil, title: String, additionalBadgeIcon: UIImage? = nil, alwaysPlain: Bool = false, hasSeparator: Bool = true, sectionId: ItemListSectionId, height: ItemListPeerActionItemHeight = .peerList, color: ItemListPeerActionItemColor = .accent, noInsets: Bool = false, editing: Bool = false, action: (() -> Void)?) { + public init(presentationData: ItemListPresentationData, style: ItemListStyle = .blocks, systemStyle: ItemListSystemStyle = .legacy, icon: UIImage?, iconSignal: Signal? = nil, title: String, additionalBadgeIcon: UIImage? = nil, alwaysPlain: Bool = false, hasSeparator: Bool = true, sectionId: ItemListSectionId, height: ItemListPeerActionItemHeight = .peerList, color: ItemListPeerActionItemColor = .accent, noInsets: Bool = false, editing: Bool = false, tag: ItemListItemTag? = nil, action: (() -> Void)?) { self.presentationData = presentationData self.style = style self.systemStyle = systemStyle @@ -51,6 +52,7 @@ public class ItemListPeerActionItem: ListViewItem, ItemListItem { self.noInsets = noInsets self.color = color self.sectionId = sectionId + self.tag = tag self.action = action } @@ -116,7 +118,7 @@ public class ItemListPeerActionItem: ListViewItem, ItemListItem { } } -public final class ItemListPeerActionItemNode: ListViewItemNode { +public final class ItemListPeerActionItemNode: ListViewItemNode, ItemListItemNode { private let backgroundNode: ASDisplayNode private let topStripeNode: ASDisplayNode private let bottomStripeNode: ASDisplayNode @@ -131,6 +133,10 @@ public final class ItemListPeerActionItemNode: ListViewItemNode { private var item: ItemListPeerActionItem? + public var tag: ItemListItemTag? { + return self.item?.tag + } + private let iconDisposable = MetaDisposable() public init() { diff --git a/submodules/ItemListUI/Sources/ItemListItem.swift b/submodules/ItemListUI/Sources/ItemListItem.swift index 44d4897e..a662f9e2 100644 --- a/submodules/ItemListUI/Sources/ItemListItem.swift +++ b/submodules/ItemListUI/Sources/ItemListItem.swift @@ -33,6 +33,12 @@ public extension ItemListItem { public protocol ItemListItemNode { var tag: ItemListItemTag? { get } + func displayHighlight() +} + +public extension ItemListItemNode { + func displayHighlight() { + } } public protocol ItemListItemFocusableNode { diff --git a/submodules/ItemListUI/Sources/Items/ItemListDisclosureItem.swift b/submodules/ItemListUI/Sources/Items/ItemListDisclosureItem.swift index 5d518b5f..2753f364 100644 --- a/submodules/ItemListUI/Sources/Items/ItemListDisclosureItem.swift +++ b/submodules/ItemListUI/Sources/Items/ItemListDisclosureItem.swift @@ -63,6 +63,8 @@ public class ItemListDisclosureItem: ListViewItem, ItemListItem, ListItemCompone let label: String let attributedLabel: NSAttributedString? let labelStyle: ItemListDisclosureLabelStyle + let sgLabelMaximumNumberOfLines: Int + let centerLabelAlignment: Bool let additionalDetailLabel: String? let additionalDetailLabelColor: ItemListDisclosureItemDetailLabelColor public let sectionId: ItemListSectionId @@ -74,7 +76,7 @@ public class ItemListDisclosureItem: ListViewItem, ItemListItem, ListItemCompone public let tag: ItemListItemTag? public let shimmeringIndex: Int? - public init(presentationData: ItemListPresentationData, systemStyle: ItemListSystemStyle = .legacy, icon: UIImage? = nil, context: AccountContext? = nil, iconPeer: EnginePeer? = nil, title: String, attributedTitle: NSAttributedString? = nil, enabled: Bool = true, titleColor: ItemListDisclosureItemTitleColor = .primary, titleFont: ItemListDisclosureItemTitleFont = .regular, titleIcon: UIImage? = nil, titleBadge: String? = nil, label: String, attributedLabel: NSAttributedString? = nil, labelStyle: ItemListDisclosureLabelStyle = .text, additionalDetailLabel: String? = nil, additionalDetailLabelColor: ItemListDisclosureItemDetailLabelColor = .generic, sectionId: ItemListSectionId, style: ItemListStyle, disclosureStyle: ItemListDisclosureStyle = .arrow, noInsets: Bool = false, action: (() -> Void)?, clearHighlightAutomatically: Bool = true, tag: ItemListItemTag? = nil, shimmeringIndex: Int? = nil) { + public init(presentationData: ItemListPresentationData, systemStyle: ItemListSystemStyle = .legacy, icon: UIImage? = nil, context: AccountContext? = nil, iconPeer: EnginePeer? = nil, title: String, attributedTitle: NSAttributedString? = nil, enabled: Bool = true, titleColor: ItemListDisclosureItemTitleColor = .primary, titleFont: ItemListDisclosureItemTitleFont = .regular, titleIcon: UIImage? = nil, titleBadge: String? = nil, label: String, attributedLabel: NSAttributedString? = nil, labelStyle: ItemListDisclosureLabelStyle = .text, sgLabelMaximumNumberOfLines: Int = 1, centerLabelAlignment: Bool = false, additionalDetailLabel: String? = nil, additionalDetailLabelColor: ItemListDisclosureItemDetailLabelColor = .generic, sectionId: ItemListSectionId, style: ItemListStyle, disclosureStyle: ItemListDisclosureStyle = .arrow, noInsets: Bool = false, action: (() -> Void)?, clearHighlightAutomatically: Bool = true, tag: ItemListItemTag? = nil, shimmeringIndex: Int? = nil) { self.presentationData = presentationData self.systemStyle = systemStyle self.icon = icon @@ -88,8 +90,10 @@ public class ItemListDisclosureItem: ListViewItem, ItemListItem, ListItemCompone self.titleBadge = titleBadge self.enabled = enabled self.labelStyle = labelStyle + self.sgLabelMaximumNumberOfLines = sgLabelMaximumNumberOfLines self.label = label self.attributedLabel = attributedLabel + self.centerLabelAlignment = centerLabelAlignment self.additionalDetailLabel = additionalDetailLabel self.additionalDetailLabelColor = additionalDetailLabelColor self.sectionId = sectionId @@ -173,6 +177,7 @@ private let boldBadgeFont = Font.semibold(14.0) public class ItemListDisclosureItemNode: ListViewItemNode, ItemListItemNode { private let backgroundNode: ASDisplayNode + private let highlightNode: ASDisplayNode private let topStripeNode: ASDisplayNode private let bottomStripeNode: ASDisplayNode private let highlightedBackgroundNode: ASDisplayNode @@ -215,6 +220,9 @@ public class ItemListDisclosureItemNode: ListViewItemNode, ItemListItemNode { self.backgroundNode.isLayerBacked = true self.backgroundNode.backgroundColor = .white + self.highlightNode = ASDisplayNode() + self.highlightNode.isLayerBacked = true + self.maskNode = ASImageNode() self.maskNode.isUserInteractionEnabled = false @@ -283,6 +291,20 @@ public class ItemListDisclosureItemNode: ListViewItemNode, ItemListItemNode { transition.updateAlpha(node: self.arrowNode, alpha: hasContextMenu ? 0.5 : 1.0) } + public func displayHighlight() { + if self.backgroundNode.supernode != nil { + self.insertSubnode(self.highlightNode, aboveSubnode: self.backgroundNode) + } else { + self.insertSubnode(self.highlightNode, at: 0) + } + + Queue.mainQueue().after(1.2, { + self.highlightNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.3, removeOnCompletion: false, completion: { _ in + self.highlightNode.removeFromSupernode() + }) + }) + } + public func asyncLayout() -> (_ item: ItemListDisclosureItem, _ params: ListViewItemLayoutParams, _ insets: ItemListNeighbors) -> (ListViewItemNodeLayout, () -> Void) { let makeTitleLayout = TextNode.asyncLayout(self.titleNode.textNode) let makeTitleWithEntitiesLayout = TextNodeWithEntities.asyncLayout(self.titleNode) @@ -447,12 +469,15 @@ public class ItemListDisclosureItemNode: ListViewItemNode, ItemListItemNode { labelBadgeColor = item.presentationData.theme.list.itemSecondaryTextColor labelFont = defaultLabelFont } - var multilineLabel = false + // MARK: Swiftgram + let labelMaximumNumberOfLines: Int if case .multilineDetailText = item.labelStyle { - multilineLabel = true + labelMaximumNumberOfLines = 0 + } else { + labelMaximumNumberOfLines = max(1, item.sgLabelMaximumNumberOfLines) } - - let (labelLayout, labelApply) = makeLabelLayout(TextNodeLayoutArguments(attributedString: item.attributedLabel ?? NSAttributedString(string: item.label, font: labelFont, textColor: labelBadgeColor), backgroundColor: nil, maximumNumberOfLines: multilineLabel ? 0 : 1, truncationType: .end, constrainedSize: CGSize(width: labelConstrain, height: CGFloat.greatestFiniteMagnitude), alignment: .natural, cutout: nil, insets: UIEdgeInsets())) + // + let (labelLayout, labelApply) = makeLabelLayout(TextNodeLayoutArguments(attributedString: item.attributedLabel ?? NSAttributedString(string: item.label, font: labelFont, textColor: labelBadgeColor), backgroundColor: nil, maximumNumberOfLines: labelMaximumNumberOfLines, truncationType: .end, constrainedSize: CGSize(width: labelConstrain, height: CGFloat.greatestFiniteMagnitude), alignment: .natural, cutout: nil, insets: UIEdgeInsets())) var additionalDetailLabelInfo: (TextNodeLayout, () -> TextNode)? if let additionalDetailLabel = item.additionalDetailLabel { @@ -506,7 +531,9 @@ public class ItemListDisclosureItemNode: ListViewItemNode, ItemListItemNode { case .detailText, .multilineDetailText: height = verticalInset * 2.0 + titleLayout.size.height + titleSpacing + labelLayout.size.height default: - height = verticalInset * 2.0 + titleLayout.size.height + // MARK: Swiftgram + height = verticalInset * 2.0 + max(titleLayout.size.height, labelLayout.size.height) + // } if let additionalDetailLabelInfo = additionalDetailLabelInfo { height += titleSpacing + additionalDetailLabelInfo.0.size.height @@ -600,6 +627,7 @@ public class ItemListDisclosureItemNode: ListViewItemNode, ItemListItemNode { strongSelf.bottomStripeNode.backgroundColor = itemSeparatorColor strongSelf.backgroundNode.backgroundColor = itemBackgroundColor strongSelf.highlightedBackgroundNode.backgroundColor = item.presentationData.theme.list.itemHighlightedBackgroundColor + strongSelf.highlightNode.backgroundColor = item.presentationData.theme.list.itemHighlightedBackgroundColor } if let titleWithEntitiesApply = titleWithEntitiesLayoutAndApply?.1, let context = item.context { @@ -671,6 +699,7 @@ public class ItemListDisclosureItemNode: ListViewItemNode, ItemListItemNode { strongSelf.maskNode.image = hasCorners ? PresentationResourcesItemList.cornersImage(item.presentationData.theme, top: hasTopCorners, bottom: hasBottomCorners, glass: item.systemStyle == .glass) : nil strongSelf.backgroundNode.frame = CGRect(origin: CGPoint(x: 0.0, y: -min(insets.top, separatorHeight)), size: CGSize(width: params.width, height: contentSize.height + min(insets.top, separatorHeight) + min(insets.bottom, separatorHeight))) + strongSelf.highlightNode.frame = CGRect(origin: CGPoint(x: 0.0, y: -min(insets.top, separatorHeight)), size: CGSize(width: params.width, height: contentSize.height + min(insets.top, separatorHeight) + min(insets.bottom, separatorHeight))) strongSelf.maskNode.frame = strongSelf.backgroundNode.frame.insetBy(dx: params.leftInset, dy: 0.0) strongSelf.topStripeNode.frame = CGRect(origin: CGPoint(x: 0.0, y: -min(insets.top, separatorHeight)), size: CGSize(width: params.width, height: separatorHeight)) strongSelf.bottomStripeNode.frame = CGRect(origin: CGPoint(x: bottomStripeInset, y: contentSize.height - separatorHeight), size: CGSize(width: params.width - params.rightInset - bottomStripeInset - separatorRightInset, height: separatorHeight)) @@ -707,7 +736,7 @@ public class ItemListDisclosureItemNode: ListViewItemNode, ItemListItemNode { if case .semitransparentBadge = item.labelStyle { badgeWidth += 2.0 } - let badgeFrame = CGRect(origin: CGPoint(x: params.width - rightInset - badgeWidth, y: floor((contentSize.height - badgeDiameter) / 2.0)), size: CGSize(width: badgeWidth, height: badgeDiameter)) + let badgeFrame = CGRect(origin: CGPoint(x: item.centerLabelAlignment ? floor((params.width - badgeWidth) / 2.0) : params.width - rightInset - badgeWidth, y: floor((contentSize.height - badgeDiameter) / 2.0)), size: CGSize(width: badgeWidth, height: badgeDiameter)) strongSelf.labelBadgeNode.frame = badgeFrame let labelFrame: CGRect @@ -715,7 +744,7 @@ public class ItemListDisclosureItemNode: ListViewItemNode, ItemListItemNode { case .badge: labelFrame = CGRect(origin: CGPoint(x: params.width - rightInset - badgeWidth + (badgeWidth - labelLayout.size.width) / 2.0, y: badgeFrame.minY + 1.0), size: labelLayout.size) case .semitransparentBadge: - labelFrame = CGRect(origin: CGPoint(x: params.width - rightInset - badgeWidth + (badgeWidth - labelLayout.size.width) / 2.0, y: badgeFrame.minY + 1.0 - UIScreenPixel + floorToScreenPixels((badgeDiameter - labelLayout.size.height) / 2.0)), size: labelLayout.size) + labelFrame = CGRect(origin: CGPoint(x: item.centerLabelAlignment ? floor((params.width - badgeWidth + (badgeWidth - labelLayout.size.width)) / 2.0) : params.width - rightInset - badgeWidth + (badgeWidth - labelLayout.size.width) / 2.0, y: badgeFrame.minY + 1.0 - UIScreenPixel + floorToScreenPixels((badgeDiameter - labelLayout.size.height) / 2.0)), size: labelLayout.size) case .detailText, .multilineDetailText: labelFrame = CGRect(origin: CGPoint(x: leftInset, y: titleFrame.maxY + titleSpacing), size: labelLayout.size) default: diff --git a/submodules/LegacyMediaPickerUI/BUILD b/submodules/LegacyMediaPickerUI/BUILD index 7cdc9988..b435ef50 100644 --- a/submodules/LegacyMediaPickerUI/BUILD +++ b/submodules/LegacyMediaPickerUI/BUILD @@ -1,5 +1,9 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + swift_library( name = "LegacyMediaPickerUI", module_name = "LegacyMediaPickerUI", diff --git a/submodules/LegacyMediaPickerUI/Sources/LegacyMediaPickers.swift b/submodules/LegacyMediaPickerUI/Sources/LegacyMediaPickers.swift index 65dcb75c..6550b5a9 100644 --- a/submodules/LegacyMediaPickerUI/Sources/LegacyMediaPickers.swift +++ b/submodules/LegacyMediaPickerUI/Sources/LegacyMediaPickers.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import LegacyComponents @@ -410,7 +411,8 @@ public func legacyAssetPickerEnqueueMessages(context: AccountContext, account: A defer { TempBox.shared.dispose(tempFile) } - if let scaledImageData = compressImageToJPEG(scaledImage, quality: 0.6, tempFilePath: tempFile.path) { + // MARK: Swiftgram + if let scaledImageData = compressImageToJPEG(scaledImage, quality: Float(SGSimpleSettings.shared.outgoingPhotoQuality) / 100.0, tempFilePath: tempFile.path) { let _ = try? scaledImageData.write(to: URL(fileURLWithPath: tempFilePath)) let resource = LocalFileReferenceMediaResource(localFilePath: tempFilePath, randomId: randomId) @@ -771,6 +773,7 @@ public func legacyAssetPickerEnqueueMessages(context: AccountContext, account: A break } case let .video(data, thumbnail, cover, adjustments, caption, asFile, asAnimation, stickers): + var adjustments = adjustments var finalDimensions: CGSize var finalDuration: Double switch data { @@ -845,9 +848,80 @@ public func legacyAssetPickerEnqueueMessages(context: AccountContext, account: A preset = TGMediaVideoConversionPresetAnimation } - if !asAnimation { - finalDimensions = TGMediaVideoConverter.dimensions(for: finalDimensions, adjustments: adjustments, preset: TGMediaVideoConversionPresetCompressedMedium) + // MARK: Swiftgram + // TODO(swiftgram): Nice thumbnail + var asTelescope = false +#if false + if let strongAdjustments = adjustments, strongAdjustments.sendAsTelescope { + asTelescope = true + // Final size + let size = CGSize(width: finalDimensions.width, height: finalDimensions.height) + + // Respecting user's crop + var cropRect = strongAdjustments.cropRect + + let originalSize: CGSize + if strongAdjustments.cropApplied(forAvatar: false) { + originalSize = strongAdjustments.originalSize + } else { + // It's a hack, video is resized according to the quality preset + // To prevent this resize we must set original size the same as the after-resized video + originalSize = size + } + + // Already square + if abs(finalDimensions.width - finalDimensions.height) < CGFloat.ulpOfOne { + cropRect = cropRect.insetBy(dx: 13.0, dy: 13.0) + cropRect = cropRect.offsetBy(dx: 2.0, dy: 3.0) + } else { + // Need to make a square + let shortestSide = min(size.width, size.height) + let newX = cropRect.origin.x + (size.width - shortestSide) / 2.0 + let newY = cropRect.origin.y + (size.height - shortestSide) / 2.0 + cropRect = CGRect(x: newX, y: newY, width: shortestSide, height: shortestSide) + print("size.width \(size.width)") + print("size.height \(size.height)") + print("shortestSide \(shortestSide)") + print("cropRect.origin.x \(cropRect.origin.x)") + print("cropRect.origin.y \(cropRect.origin.y)") + print("newX \(newX)") + print("newY \(newY)") + } + + let maxDuration: Double = 60.0 + let trimmedDuration: TimeInterval + if strongAdjustments.trimApplied() { + trimmedDuration = strongAdjustments.trimEndValue - strongAdjustments.trimStartValue + } else { + trimmedDuration = finalDuration + } + + let trimEndValueLimited: TimeInterval + if trimmedDuration > maxDuration { + trimEndValueLimited = strongAdjustments.trimEndValue - (trimmedDuration - maxDuration) + } else { + trimEndValueLimited = strongAdjustments.trimEndValue + } + + print("Preset TGMediaVideoConversionPresetVideoMessageHD \(TGMediaVideoConversionPresetVideoMessageHD)") + print("Preset TGMediaVideoConversionPresetVideoMessage \(TGMediaVideoConversionPresetVideoMessage)") + print("Preset TGMediaVideoConversionPresetCompressedLow \(TGMediaVideoConversionPresetCompressedLow)") + + // Dynamically calculate size with different presets and use the best one + for presetTest in [TGMediaVideoConversionPresetVideoMessageHD, TGMediaVideoConversionPresetVideoMessage, TGMediaVideoConversionPresetCompressedLow] { + adjustments = TGVideoEditAdjustments(originalSize: originalSize, cropRect: cropRect, cropOrientation: strongAdjustments.cropOrientation, cropRotation: strongAdjustments.cropRotation, cropLockedAspectRatio: 1.0, cropMirrored: strongAdjustments.cropMirrored, trimStartValue: strongAdjustments.trimStartValue, trimEndValue: trimEndValueLimited, toolValues: strongAdjustments.toolValues, paintingData: strongAdjustments.paintingData, sendAsGif: false, sendAsTelescope: strongAdjustments.sendAsTelescope, preset: presetTest) + + finalDimensions = TGMediaVideoConverter.dimensions(for: finalDimensions, adjustments: adjustments, preset: presetTest) + + let estimatedVideoMessageSize = TGMediaVideoConverter.estimatedSize(for: presetTest, duration: finalDuration, hasAudio: true) + if estimatedVideoMessageSize < 8 * 1024 * 1024 { + print("Using preset \(presetTest)") + preset = presetTest + break + } + } } +#endif var resourceAdjustments: VideoMediaResourceAdjustments? if let adjustments = adjustments { @@ -924,7 +998,10 @@ public func legacyAssetPickerEnqueueMessages(context: AccountContext, account: A attributes.append(EmbeddedMediaStickersMessageAttribute(files: stickerFiles)) fileAttributes.append(.HasLinkedStickers) } - + // MARK: Swiftgram + if asTelescope { + fileAttributes = [.FileName(fileName: "video.mp4"), .Video(duration: finalDuration, size: PixelDimensions(finalDimensions), flags: [.instantRoundVideo], preloadSize: nil, coverTime: nil, videoCodec: nil)] + } let media = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: Int64.random(in: Int64.min ... Int64.max)), partialReference: nil, resource: resource, previewRepresentations: previewRepresentations, videoThumbnails: [], videoCover: videoCover, immediateThumbnailData: nil, mimeType: "video/mp4", size: nil, attributes: fileAttributes, alternativeRepresentations: []) if let timer = item.timer, timer > 0 && (timer <= 60 || timer == viewOnceTimeout) { diff --git a/submodules/LocalMediaResources/BUILD b/submodules/LocalMediaResources/BUILD index b0f3f832..636f28df 100644 --- a/submodules/LocalMediaResources/BUILD +++ b/submodules/LocalMediaResources/BUILD @@ -1,5 +1,9 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + swift_library( name = "LocalMediaResources", module_name = "LocalMediaResources", @@ -9,7 +13,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", "//submodules/Postbox:Postbox", "//submodules/TelegramCore:TelegramCore", diff --git a/submodules/LocalMediaResources/Sources/FetchPhotoLibraryImageResource.swift b/submodules/LocalMediaResources/Sources/FetchPhotoLibraryImageResource.swift index f19199c1..5ec4a255 100644 --- a/submodules/LocalMediaResources/Sources/FetchPhotoLibraryImageResource.swift +++ b/submodules/LocalMediaResources/Sources/FetchPhotoLibraryImageResource.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import Photos @@ -182,7 +183,7 @@ public func fetchPhotoLibraryResource(localIdentifier: String, width: Int32?, he defer { TempBox.shared.dispose(tempFile) } - if let scaledImage = scaledImage, let data = compressImageToJPEG(scaledImage, quality: 0.6, tempFilePath: tempFile.path) { + if let scaledImage = scaledImage, let data = compressImageToJPEG(scaledImage, quality: Float(SGSimpleSettings.shared.outgoingPhotoQuality) / 100.0, tempFilePath: tempFile.path) { #if DEBUG print("compression completion \((CACurrentMediaTime() - startTime) * 1000.0) ms") #endif @@ -192,7 +193,7 @@ public func fetchPhotoLibraryResource(localIdentifier: String, width: Int32?, he subscriber.putCompletion() } case .jxl: - if let scaledImage = scaledImage, let data = compressImageToJPEGXL(scaledImage, quality: Int(quality ?? 75)) { + if let scaledImage = scaledImage, let data = compressImageToJPEGXL(scaledImage, quality: Int(SGSimpleSettings.shared.outgoingPhotoQuality)) { #if DEBUG print("jpegxl compression completion \((CACurrentMediaTime() - startTime) * 1000.0) ms") #endif diff --git a/submodules/MediaPickerUI/Sources/LegacyMediaPickerGallery.swift b/submodules/MediaPickerUI/Sources/LegacyMediaPickerGallery.swift index 507e1d78..6fe474af 100644 --- a/submodules/MediaPickerUI/Sources/LegacyMediaPickerGallery.swift +++ b/submodules/MediaPickerUI/Sources/LegacyMediaPickerGallery.swift @@ -144,12 +144,14 @@ func presentLegacyMediaPickerGallery(context: AccountContext, peer: EnginePeer?, recipientName = peer?.displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder) } } - let model = TGMediaPickerGalleryModel(context: legacyController.context, items: items, focus: focusItem, selectionContext: selectionContext, editingContext: editingContext, hasCaptions: true, allowCaptionEntities: true, hasTimer: hasTimer, onlyCrop: false, inhibitDocumentCaptions: false, hasSelectionPanel: true, hasCamera: false, recipientName: recipientName, isScheduledMessages: isScheduledMessages, hasCoverButton: hasCoverButton)! model.stickersContext = paintStickersContext controller.model = model model.controller = controller - model.willFinishEditingItem = { item, adjustments, representation, hasChanges in + model.willFinishEditingItem = { (item: TGMediaEditableItem?, adjustments: TGMediaEditAdjustments?, representation: Any?, hasChanges: Bool) in + guard let item else { + return + } if hasChanges { editingContext.setAdjustments(adjustments, for: item) editingContext.setTemporaryRep(representation, for: item) @@ -159,10 +161,16 @@ func presentLegacyMediaPickerGallery(context: AccountContext, peer: EnginePeer?, selectionContext.setItem(item, selected: true) } } - model.didFinishEditingItem = { item, adjustments, result, thumbnail in + model.didFinishEditingItem = { (item: TGMediaEditableItem?, adjustments: TGMediaEditAdjustments?, result: UIImage?, thumbnail: UIImage?) in + guard let item, let result, let thumbnail else { + return + } editingContext.setImage(result, thumbnailImage: thumbnail, for: item, synchronous: false) } - model.saveItemCaption = { item, caption in + model.saveItemCaption = { (item: TGMediaEditableItem?, caption: NSAttributedString?) in + guard let item else { + return + } editingContext.setCaption(caption, for: item) if let selectionContext = selectionContext, let caption = caption, caption.length > 0, let item = item as? TGMediaSelectableItem { selectionContext.setItem(item, selected: true) @@ -226,7 +234,7 @@ func presentLegacyMediaPickerGallery(context: AccountContext, peer: EnginePeer?, legacyController?.dismiss() } - model.interfaceView.donePressed = { [weak controller] item in + model.interfaceView.donePressed = { [weak controller] (item: TGModernGalleryItem?) in if let item = item as? TGMediaPickerGalleryItem { completed(item.asset, false, nil, { controller?.dismissWhenReady(animated: true) @@ -235,7 +243,7 @@ func presentLegacyMediaPickerGallery(context: AccountContext, peer: EnginePeer?, } } if !isScheduledMessages && peer != nil { - model.interfaceView.doneLongPressed = { [weak selectionContext, weak editingContext, weak legacyController, weak model] item in + model.interfaceView.doneLongPressed = { [weak selectionContext, weak editingContext, weak legacyController, weak model] (item: TGModernGalleryItem?) in if let legacyController = legacyController, let item = item as? TGMediaPickerGalleryItem, let model = model, let selectionContext = selectionContext { var effectiveHasSchedule = hasSchedule diff --git a/submodules/MediaPickerUI/Sources/MediaPickerScreen.swift b/submodules/MediaPickerUI/Sources/MediaPickerScreen.swift index a561b2df..b01c9907 100644 --- a/submodules/MediaPickerUI/Sources/MediaPickerScreen.swift +++ b/submodules/MediaPickerUI/Sources/MediaPickerScreen.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import Display @@ -291,7 +292,7 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att fileprivate var avatarEditorPreviewView: AvatarEditorPreviewView? private var cameraActivateAreaNode: AccessibilityAreaNode - private var placeholderNode: MediaPickerPlaceholderNode? + fileprivate var placeholderNode: MediaPickerPlaceholderNode? private var manageNode: MediaPickerManageNode? private var scrollingArea: SparseItemGridScrollingArea private var isFastScrolling = false @@ -317,6 +318,7 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att private var fastScrollContentOffset = ValuePromise(ignoreRepeated: true) private var fastScrollDisposable: Disposable? + fileprivate var currentContentOffset: GridNodeVisibleContentOffset? fileprivate var scrolledToTop = true fileprivate var scrolledExactlyToTop = true fileprivate var isSwitchingAssetGroup = false @@ -453,33 +455,9 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att guard let self else { return } + self.currentContentOffset = offset self.updateNavigation(transition: .immediate) - - var scrolledToTop = false - var scrolledExactlyToTop = false - if case let .known(contentOffset) = offset { - if contentOffset < 30.0 { - scrolledToTop = true - } - if contentOffset < 5.0 { - scrolledExactlyToTop = true - } - } - - var updated = false - var transition: ContainedViewLayoutTransition = .animated(duration: 0.5, curve: .easeInOut) - if self.scrolledToTop != scrolledToTop { - self.scrolledToTop = scrolledToTop - updated = true - } - if self.scrolledExactlyToTop != scrolledExactlyToTop { - self.scrolledExactlyToTop = scrolledExactlyToTop - updated = true - transition = .animated(duration: 0.25, curve: .easeInOut) - } - if updated { - self.controller?.updateNavigationButtons(transition: transition) - } + self.updateTopEdgeEffect() } self.hiddenMediaDisposable = (self.hiddenMediaId.get() @@ -687,8 +665,8 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att useModernCamera = true } - if useLegacyCamera { - let enableAnimations = self.controller?.context.sharedContext.energyUsageSettings.fullTranslucency ?? true + if useLegacyCamera && !SGSimpleSettings.shared.disableGalleryCamera { + let enableAnimations = self.controller?.context.sharedContext.energyUsageSettings.fullTranslucency ?? true && !SGSimpleSettings.shared.disableGalleryCameraPreview let cameraView = TGAttachmentCameraView(forSelfPortrait: false, videoModeByDefault: controller.bannedSendPhotos != nil && controller.bannedSendVideos == nil)! cameraView.clipsToBounds = true @@ -711,7 +689,7 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att self.gridNode.scrollView.addSubview(cameraView) self.gridNode.addSubnode(self.cameraActivateAreaNode) - } else if useModernCamera, !Camera.isIpad { + } else if useModernCamera, !Camera.isIpad, !SGSimpleSettings.shared.disableGalleryCamera { #if !targetEnvironment(simulator) var cameraPosition: Camera.Position = .back if case .assets(nil, .createAvatar) = controller.subject { @@ -771,6 +749,41 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att } } + func updateTopEdgeEffect() { + guard let offset = self.currentContentOffset else { + return + } + var scrolledToTop = false + var scrolledExactlyToTop = false + if case let .known(contentOffset) = offset { + if contentOffset < 30.0 { + scrolledToTop = true + } + if contentOffset < 5.0 { + scrolledExactlyToTop = true + } + } + if self.placeholderNode != nil { + scrolledToTop = true + scrolledExactlyToTop = true + } + + var updated = false + var transition: ContainedViewLayoutTransition = .animated(duration: 0.5, curve: .easeInOut) + if self.scrolledToTop != scrolledToTop { + self.scrolledToTop = scrolledToTop + updated = true + } + if self.scrolledExactlyToTop != scrolledExactlyToTop { + self.scrolledExactlyToTop = scrolledExactlyToTop + updated = true + transition = .animated(duration: 0.25, curve: .easeInOut) + } + if updated { + self.controller?.updateNavigationButtons(transition: transition) + } + } + func setupSelectionGesture() { guard self.selectionGesture == nil else { return @@ -831,14 +844,18 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att let isCameraActive = !self.isSuspended && !self.hasGallery && self.isCameraPreviewVisible if let cameraView = self.cameraView { if isCameraActive { - cameraView.resumePreview() + if !SGSimpleSettings.shared.disableGalleryCameraPreview { + cameraView.resumePreview() + } } else { cameraView.pausePreview() } } else if let camera = self.modernCamera, let cameraView = self.modernCameraView { if isCameraActive { - cameraView.isEnabled = true - camera.startCapture() + if !SGSimpleSettings.shared.disableGalleryCameraPreview { + cameraView.isEnabled = true + camera.startCapture() + } } else { cameraView.isEnabled = false camera.stopCapture() @@ -1685,6 +1702,8 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att self.placeholderNode = placeholderNode placeholderTransition = .immediate + + self.updateTopEdgeEffect() } placeholderNode.update(layout: layout, theme: self.presentationData.theme, strings: self.presentationData.strings, hasCamera: false, transition: placeholderTransition) placeholderTransition.updateFrame(node: placeholderNode, frame: innerBounds) @@ -1849,6 +1868,8 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att } if case let .noAccess(cameraAccess) = self.state { + self.controller?.titleView.isEnabled = false + var hasCamera = cameraAccess == .authorized var story = false if let subject = self.controller?.subject { @@ -1885,6 +1906,8 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att placeholderTransition = .immediate self.updateNavigation(transition: .immediate) + + self.updateTopEdgeEffect() } placeholderNode.update(layout: layout, theme: self.presentationData.theme, strings: self.presentationData.strings, hasCamera: hasCamera, transition: placeholderTransition) placeholderTransition.updateFrame(node: placeholderNode, frame: innerBounds) @@ -2388,7 +2411,7 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att ) self.titleView.isHighlighted = true - let contextController = ContextController( + let contextController = makeContextController( presentationData: self.presentationData, source: .reference(MediaPickerContextReferenceContentSource(controller: self, sourceView: self.titleView)), items: .single(ContextController.Items(content: .custom(content))), @@ -2514,7 +2537,7 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att moreIsVisible = true } else { let title: String - let isEnabled: Bool + var isEnabled: Bool if self.controllerNode.currentDisplayMode == .selected { title = "" // self.presentationData.strings.Attachment_SelectedMedia(count) isEnabled = false @@ -2522,7 +2545,12 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att title = self.selectedCollectionValue?.localizedTitle ?? self.presentationData.strings.MediaPicker_Recents isEnabled = true } - self.titleView.updateTitle(title: title, isEnabled: isEnabled, animated: true) + var titleIsEnabled = isEnabled + if self.controllerNode.placeholderNode != nil { + titleIsEnabled = false + } + + self.titleView.updateTitle(title: title, isEnabled: titleIsEnabled, animated: true) self.cancelButtonNode.setState(isEnabled ? .cancel : .back, animated: true) isBack = !isEnabled @@ -2609,7 +2637,14 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att } } - if let moreButton = self.rightButton { + if moreIsVisible, case .glass = self.style { + let moreButton: ComponentView + if let current = self.rightButton { + moreButton = current + } else { + moreButton = ComponentView() + self.rightButton = moreButton + } let moreButtonSize = moreButton.update( transition: buttonTransition, component: AnyComponent(GlassBarButtonComponent( @@ -2638,18 +2673,28 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att if let view = moreButton.view { if view.superview == nil { self.view.addSubview(view) + if transition.isAnimated { + let transition = ComponentTransition(transition) + transition.animateAlpha(view: view, from: 0.0, to: 1.0) + transition.animateScale(view: view, from: 0.1, to: 1.0) + } } view.bounds = CGRect(origin: .zero, size: moreButtonFrame.size) view.center = moreButtonFrame.center } - } - - if let moreButtonView = self.rightButton?.view { - transition.updateAlpha(layer: moreButtonView.layer, alpha: moreIsVisible ? 1.0 : 0.0) - transition.updateTransformScale(layer: moreButtonView.layer, scale: moreIsVisible ? 1.0 : 0.1) - } else { - transition.updateAlpha(node: self.moreButtonNode.iconNode, alpha: moreIsVisible ? 1.0 : 0.0) - transition.updateTransformScale(node: self.moreButtonNode.iconNode, scale: moreIsVisible ? 1.0 : 0.1) + } else if let moreButton = self.rightButton { + self.rightButton = nil + if let view = moreButton.view { + if transition.isAnimated { + let transition = ComponentTransition(transition) + view.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.25, removeOnCompletion: false, completion: { _ in + view.removeFromSuperview() + }) + transition.animateScale(view: view, from: 1.0, to: 0.1) + } else { + view.removeFromSuperview() + } + } } if case .assets(_, .story) = self.subject { @@ -2923,7 +2968,7 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att self?.presentFilePicker() }))) - let contextController = ContextController(presentationData: self.presentationData, source: .reference(MediaPickerContextReferenceContentSource(controller: self, sourceView: view)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) + let contextController = makeContextController(presentationData: self.presentationData, source: .reference(MediaPickerContextReferenceContentSource(controller: self, sourceView: view)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) self.presentInGlobalOverlay(contextController) return @@ -3084,7 +3129,7 @@ public final class MediaPickerScreenImpl: ViewController, MediaPickerScreen, Att return ContextController.Items(content: .list(items)) } - let contextController = ContextController(presentationData: self.presentationData, source: .reference(MediaPickerContextReferenceContentSource(controller: self, sourceView: view)), items: items, gesture: gesture) + let contextController = makeContextController(presentationData: self.presentationData, source: .reference(MediaPickerContextReferenceContentSource(controller: self, sourceView: view)), items: items, gesture: gesture) self.presentInGlobalOverlay(contextController) } } diff --git a/submodules/MediaPlayer/BUILD b/submodules/MediaPlayer/BUILD index af588856..a2597a22 100644 --- a/submodules/MediaPlayer/BUILD +++ b/submodules/MediaPlayer/BUILD @@ -1,5 +1,9 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + swift_library( name = "UniversalMediaPlayer", module_name = "UniversalMediaPlayer", @@ -9,7 +13,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/TelegramCore:TelegramCore", "//submodules/Postbox:Postbox", "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", diff --git a/submodules/MtProtoKit/Sources/MTApiEnvironment.m b/submodules/MtProtoKit/Sources/MTApiEnvironment.m index 14197ec5..c6718541 100644 --- a/submodules/MtProtoKit/Sources/MTApiEnvironment.m +++ b/submodules/MtProtoKit/Sources/MTApiEnvironment.m @@ -74,6 +74,113 @@ static NSData *base64_decode(NSString *str) { } } +static NSDictionary *> * +MTDeviceSpoofProfiles(void) { + static NSDictionary *> + *profiles; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + profiles = @{ + @1 : @{ + @"deviceModel" : @"iPhone 14 Pro", + @"systemVersion" : @"iOS 17.2" + }, + @2 : @{ + @"deviceModel" : @"iPhone 15 Pro Max", + @"systemVersion" : @"iOS 17.4" + }, + @3 : @{ + @"deviceModel" : @"Samsung SM-S918B", + @"systemVersion" : @"Android 14" + }, + @4 : @{ + @"deviceModel" : @"Google Pixel 8 Pro", + @"systemVersion" : @"Android 14" + }, + @5 : @{ + @"deviceModel" : @"PC 64bit", + @"systemVersion" : @"Windows 11" + }, + @6 : @{ + @"deviceModel" : @"MacBook Pro", + @"systemVersion" : @"macOS 14.3" + }, + @7 : @{ + @"deviceModel" : @"Web", + @"systemVersion" : @"Chrome 121" + }, + @8 : @{ + @"deviceModel" : @"HUAWEI MNA-LX9", + @"systemVersion" : @"HarmonyOS 4.0" + }, + @9 : @{ + @"deviceModel" : @"Xiaomi 2311DRK48G", + @"systemVersion" : @"Android 14" + } + }; + }); + return profiles; +} + +static NSString *MTDeviceSpoofTrimmedString(NSString *value) { + if (value == nil) { + return @""; + } + return + [value stringByTrimmingCharactersInSet: + [NSCharacterSet whitespaceAndNewlineCharacterSet]]; +} + +static NSInteger MTDeviceSpoofSanitizedProfileId(NSUserDefaults *defaults) { + NSInteger profileId = + [defaults integerForKey:@"DeviceSpoof.selectedProfileId"]; + if (profileId == 0 || profileId == 100 || + MTDeviceSpoofProfiles()[@(profileId)] != nil) { + return profileId; + } + [defaults setInteger:0 forKey:@"DeviceSpoof.selectedProfileId"]; + return 0; +} + +static BOOL MTDeviceSpoofIsEnabled(NSUserDefaults *defaults) { + return [defaults boolForKey:@"DeviceSpoof.hasExplicitConfiguration"] && + [defaults boolForKey:@"DeviceSpoof.isEnabled"]; +} + +static void MTDeviceSpoofResolveValues(NSUserDefaults *defaults, + NSString *__autoreleasing *deviceModel, + NSString *__autoreleasing *systemVersion) { + *deviceModel = nil; + *systemVersion = nil; + + if (!MTDeviceSpoofIsEnabled(defaults)) { + return; + } + + NSInteger profileId = MTDeviceSpoofSanitizedProfileId(defaults); + if (profileId == 0) { + return; + } + + if (profileId == 100) { + NSString *customDeviceModel = + MTDeviceSpoofTrimmedString([defaults stringForKey:@"DeviceSpoof.customDeviceModel"]); + NSString *customSystemVersion = + MTDeviceSpoofTrimmedString([defaults stringForKey:@"DeviceSpoof.customSystemVersion"]); + if (customDeviceModel.length == 0 || customSystemVersion.length == 0) { + return; + } + *deviceModel = customDeviceModel; + *systemVersion = customSystemVersion; + return; + } + + NSDictionary *profile = + MTDeviceSpoofProfiles()[@(profileId)]; + *deviceModel = profile[@"deviceModel"]; + *systemVersion = profile[@"systemVersion"]; +} + @implementation MTProxySecret - (instancetype _Nullable)initWithSecret:(NSData *_Nonnull)secret { @@ -409,49 +516,10 @@ static NSData *base64_decode(NSString *str) { - (id _Nonnull)initWithDeviceModelName:(NSString *_Nullable)deviceModelName { self = [super init]; if (self != nil) { - // GHOSTGRAM: Check for device spoofing from UserDefaults NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - BOOL spoofEnabled = [defaults boolForKey:@"DeviceSpoof.isEnabled"]; - NSInteger profileId = - [defaults integerForKey:@"DeviceSpoof.selectedProfileId"]; - NSString *spoofedModel = nil; NSString *spoofedVersion = nil; - - if (spoofEnabled && profileId != 0) { - if (profileId == 100) { - // Custom profile - spoofedModel = [defaults stringForKey:@"DeviceSpoof.customDeviceModel"]; - spoofedVersion = - [defaults stringForKey:@"DeviceSpoof.customSystemVersion"]; - } else { - // Preset profiles - NSDictionary *models = @{ - @1 : @"iPhone 14 Pro", - @2 : @"iPhone 15 Pro Max", - @3 : @"Samsung SM-S918B", - @4 : @"Google Pixel 8 Pro", - @5 : @"PC 64bit", - @6 : @"MacBook Pro", - @7 : @"Web", - @8 : @"HUAWEI MNA-LX9", - @9 : @"Xiaomi 2311DRK48G" - }; - NSDictionary *versions = @{ - @1 : @"iOS 17.2", - @2 : @"iOS 17.4", - @3 : @"Android 14", - @4 : @"Android 14", - @5 : @"Windows 11", - @6 : @"macOS 14.3", - @7 : @"Chrome 121", - @8 : @"HarmonyOS 4.0", - @9 : @"Android 14" - }; - spoofedModel = models[@(profileId)]; - spoofedVersion = versions[@(profileId)]; - } - } + MTDeviceSpoofResolveValues(defaults, &spoofedModel, &spoofedVersion); if (spoofedModel.length > 0) { _deviceModel = spoofedModel; diff --git a/submodules/ObjCRuntimeUtils/Source/ObjCRuntimeUtils/RuntimeUtils.h b/submodules/ObjCRuntimeUtils/Source/ObjCRuntimeUtils/RuntimeUtils.h index a1911221..1635c7b5 100644 --- a/submodules/ObjCRuntimeUtils/Source/ObjCRuntimeUtils/RuntimeUtils.h +++ b/submodules/ObjCRuntimeUtils/Source/ObjCRuntimeUtils/RuntimeUtils.h @@ -1,5 +1,8 @@ #import +#import +#if __has_include() #import +#endif typedef enum { NSObjectAssociationPolicyRetain = 0, @@ -32,4 +35,3 @@ typedef enum { @end SEL _Nonnull makeSelectorFromString(NSString * _Nonnull string); - diff --git a/submodules/PeerInfoUI/Sources/ChannelMembersSearchControllerNode.swift b/submodules/PeerInfoUI/Sources/ChannelMembersSearchControllerNode.swift index af8f4190..72c6e3eb 100644 --- a/submodules/PeerInfoUI/Sources/ChannelMembersSearchControllerNode.swift +++ b/submodules/PeerInfoUI/Sources/ChannelMembersSearchControllerNode.swift @@ -339,7 +339,7 @@ class ChannelMembersSearchControllerNode: ASDisplayNode { } } } - case .promote: + case .promote, .ownershipTransfer: if peer.id == context.account.peerId { continue } @@ -531,7 +531,7 @@ class ChannelMembersSearchControllerNode: ASDisplayNode { var label: String? var enabled = true switch mode { - case .ban, .promote: + case .ban, .promote, .ownershipTransfer: if participant.peer.id == context.account.peerId { continue participantsLoop } diff --git a/submodules/PlatformRestrictionMatching/Sources/PlatformRestrictionMatching.swift b/submodules/PlatformRestrictionMatching/Sources/PlatformRestrictionMatching.swift index cdafe9a3..38d40950 100644 --- a/submodules/PlatformRestrictionMatching/Sources/PlatformRestrictionMatching.swift +++ b/submodules/PlatformRestrictionMatching/Sources/PlatformRestrictionMatching.swift @@ -8,6 +8,15 @@ public extension Message { } func restrictionReason(platform: String, contentSettings: ContentSettings) -> String? { + // MARK: Swiftgram + if let author = self.author { + let chatId = author.id.id._internalGetInt64Value() + if contentSettings.appConfiguration.sgWebSettings.global.forceReasons.contains(chatId) { + return "Unavailable in Swiftgram due to App Store Guidelines" + } else if contentSettings.appConfiguration.sgWebSettings.global.unforceReasons.contains(chatId) { + return nil + } + } if let attribute = self.restrictedContentAttribute { if let value = attribute.platformText(platform: platform, contentSettings: contentSettings) { return value @@ -18,17 +27,40 @@ public extension Message { } public extension RestrictedContentMessageAttribute { - func platformText(platform: String, contentSettings: ContentSettings) -> String? { + func platformText(platform: String, contentSettings: ContentSettings, chatId: Int64? = nil) -> String? { + // MARK: Swiftgram + if let chatId = chatId { + if contentSettings.appConfiguration.sgWebSettings.global.forceReasons.contains(chatId) { + return "Unavailable in Swiftgram due to App Store Guidelines" + } else if contentSettings.appConfiguration.sgWebSettings.global.unforceReasons.contains(chatId) { + return nil + } + } for rule in self.rules { if rule.reason == "sensitive" { continue } if rule.platform == "all" || rule.platform == "ios" || contentSettings.addContentRestrictionReasons.contains(rule.platform) { if !contentSettings.ignoreContentRestrictionReasons.contains(rule.reason) { - return rule.text + return rule.text + "\n" + "\(rule.reason)-\(rule.platform)" } } } return nil } } + +// MARK: Swiftgram +public extension Message { + func canRevealContent(contentSettings: ContentSettings) -> Bool { + if contentSettings.appConfiguration.sgWebSettings.global.canViewMessages && self.flags.contains(.CopyProtected) { + let messageContentWasUnblocked = self.restrictedContentAttribute != nil && self.isRestricted(platform: "ios", contentSettings: ContentSettings.default) && !self.isRestricted(platform: "ios", contentSettings: contentSettings) + var authorWasUnblocked: Bool = false + if let author = self.author { + authorWasUnblocked = author.restrictionText(platform: "ios", contentSettings: ContentSettings.default) != nil && author.restrictionText(platform: "ios", contentSettings: contentSettings) == nil + } + return messageContentWasUnblocked || authorWasUnblocked + } + return false + } +} diff --git a/submodules/SettingsUI/BUILD b/submodules/SettingsUI/BUILD index 06cc3d6d..2613733b 100644 --- a/submodules/SettingsUI/BUILD +++ b/submodules/SettingsUI/BUILD @@ -1,15 +1,25 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//submodules/BuildConfig:BuildConfig", + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//Swiftgram/SGStrings:SGStrings" +] + +sgsrc = [ + "//Swiftgram/SGRecentSessionApiId:SGRecentSessionApiId", +] + swift_library( name = "SettingsUI", module_name = "SettingsUI", - srcs = glob([ + srcs = sgsrc + glob([ "Sources/**/*.swift", ]), copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", "//submodules/AsyncDisplayKit:AsyncDisplayKit", "//submodules/Display:Display", @@ -135,6 +145,11 @@ swift_library( "//submodules/TelegramUI/Components/AlertComponent", "//submodules/TelegramUI/Components/AlertComponent/AlertInputFieldComponent", "//submodules/TelegramUI/Components/EdgeEffect", + "//submodules/TelegramUI/Components/AvatarEditorScreen", + "//submodules/TelegramUI/Components/Settings/PeerSelectionScreen", + "//submodules/TelegramUI/Components/ListSectionComponent", + "//submodules/TelegramUI/Components/ListActionItemComponent", + "//submodules/Utils/DeviceModel", ], visibility = [ "//visibility:public", diff --git a/submodules/SettingsUI/Sources/Data and Storage/ProxyListSettingsController.swift b/submodules/SettingsUI/Sources/Data and Storage/ProxyListSettingsController.swift index 1ecf2768..22fd73ca 100644 --- a/submodules/SettingsUI/Sources/Data and Storage/ProxyListSettingsController.swift +++ b/submodules/SettingsUI/Sources/Data and Storage/ProxyListSettingsController.swift @@ -1,3 +1,7 @@ +// MARK: Swiftgram +import SGSimpleSettings +import SGStrings + import Foundation import UIKit import Display @@ -13,6 +17,7 @@ import UrlEscaping import ShareController private final class ProxySettingsControllerArguments { + let toggleLocalDNS: (Bool) -> Void let toggleEnabled: (Bool) -> Void let addNewServer: () -> Void let activateServer: (ProxyServerSettings) -> Void @@ -22,7 +27,8 @@ private final class ProxySettingsControllerArguments { let toggleUseForCalls: (Bool) -> Void let shareProxyList: () -> Void - init(toggleEnabled: @escaping (Bool) -> Void, addNewServer: @escaping () -> Void, activateServer: @escaping (ProxyServerSettings) -> Void, editServer: @escaping (ProxyServerSettings) -> Void, removeServer: @escaping (ProxyServerSettings) -> Void, setServerWithRevealedOptions: @escaping (ProxyServerSettings?, ProxyServerSettings?) -> Void, toggleUseForCalls: @escaping (Bool) -> Void, shareProxyList: @escaping () -> Void) { + init(toggleLocalDNS: @escaping (Bool) -> Void, toggleEnabled: @escaping (Bool) -> Void, addNewServer: @escaping () -> Void, activateServer: @escaping (ProxyServerSettings) -> Void, editServer: @escaping (ProxyServerSettings) -> Void, removeServer: @escaping (ProxyServerSettings) -> Void, setServerWithRevealedOptions: @escaping (ProxyServerSettings?, ProxyServerSettings?) -> Void, toggleUseForCalls: @escaping (Bool) -> Void, shareProxyList: @escaping () -> Void) { + self.toggleLocalDNS = toggleLocalDNS self.toggleEnabled = toggleEnabled self.addNewServer = addNewServer self.activateServer = activateServer @@ -58,8 +64,25 @@ private enum ProxySettingsControllerEntryId: Equatable, Hashable { case server(String, Int32, ProxyServerConnection) } +public enum ProxySettingsEntryTag: ItemListItemTag, Equatable { + case edit + case useProxy + case shareList + case useForCalls + + public func isEqual(to other: ItemListItemTag) -> Bool { + if let other = other as? ProxySettingsEntryTag, self == other { + return true + } else { + return false + } + } +} + private enum ProxySettingsControllerEntry: ItemListNodeEntry { case enabled(PresentationTheme, String, Bool, Bool) + case localDNSToggle(PresentationTheme, String, Bool) + case localDNSNotice(PresentationTheme, String) case serversHeader(PresentationTheme, String) case addServer(PresentationTheme, String, Bool) case server(Int, PresentationTheme, PresentationStrings, ProxyServerSettings, Bool, DisplayProxyServerStatus, ProxySettingsServerItemEditing, Bool) @@ -69,6 +92,8 @@ private enum ProxySettingsControllerEntry: ItemListNodeEntry { var section: ItemListSectionId { switch self { + case .localDNSToggle, .localDNSNotice: + return ProxySettingsControllerSection.enabled.rawValue case .enabled: return ProxySettingsControllerSection.enabled.rawValue case .serversHeader, .addServer, .server: @@ -83,6 +108,10 @@ private enum ProxySettingsControllerEntry: ItemListNodeEntry { var stableId: ProxySettingsControllerEntryId { switch self { case .enabled: + return .index(-2) + case .localDNSToggle: + return .index(-1) + case .localDNSNotice: return .index(0) case .serversHeader: return .index(1) @@ -107,6 +136,18 @@ private enum ProxySettingsControllerEntry: ItemListNodeEntry { } else { return false } + case let .localDNSToggle(lhsTheme, lhsText, lhsValue): + if case let .localDNSToggle(rhsTheme, rhsText, rhsValue) = rhs, lhsTheme === rhsTheme, lhsText == rhsText, lhsValue == rhsValue { + return true + } else { + return false + } + case let .localDNSNotice(lhsTheme, lhsText): + if case let .localDNSNotice(rhsTheme, rhsText) = rhs, lhsTheme === rhsTheme, lhsText == rhsText { + return true + } else { + return false + } case let .serversHeader(lhsTheme, lhsText): if case let .serversHeader(rhsTheme, rhsText) = rhs, lhsTheme === rhsTheme, lhsText == rhsText { return true @@ -155,23 +196,37 @@ private enum ProxySettingsControllerEntry: ItemListNodeEntry { default: return true } + case .localDNSToggle: + switch rhs { + case .enabled, .localDNSToggle: + return false + default: + return true + } + case .localDNSNotice: + switch rhs { + case .enabled, .localDNSToggle, .localDNSNotice: + return false + default: + return true + } case .serversHeader: switch rhs { - case .enabled, .serversHeader: + case .enabled, .localDNSToggle, .localDNSNotice, .serversHeader: return false default: return true } case .addServer: switch rhs { - case .enabled, .serversHeader, .addServer: + case .enabled, .localDNSToggle, .localDNSNotice, .serversHeader, .addServer: return false default: return true } case let .server(lhsIndex, _, _, _, _, _, _, _): switch rhs { - case .enabled, .serversHeader, .addServer: + case .enabled, .localDNSToggle, .localDNSNotice, .serversHeader, .addServer: return false case let .server(rhsIndex, _, _, _, _, _, _, _): return lhsIndex < rhsIndex @@ -180,14 +235,14 @@ private enum ProxySettingsControllerEntry: ItemListNodeEntry { } case .shareProxyList: switch rhs { - case .enabled, .serversHeader, .addServer, .server, .shareProxyList: + case .enabled, .localDNSToggle, .localDNSNotice, .serversHeader, .addServer, .server, .shareProxyList: return false default: return true } case .useForCalls: switch rhs { - case .enabled, .serversHeader, .addServer, .server, .shareProxyList, .useForCalls: + case .enabled, .localDNSToggle, .localDNSNotice, .serversHeader, .addServer, .server, .shareProxyList, .useForCalls: return false default: return true @@ -207,7 +262,13 @@ private enum ProxySettingsControllerEntry: ItemListNodeEntry { } else { arguments.toggleEnabled(value) } + }, tag: ProxySettingsEntryTag.useProxy) + case let .localDNSToggle(_, text, value): + return ItemListSwitchItem(presentationData: presentationData, title: text, value: value, enabled: true, sectionId: self.section, style: .blocks, updated: { value in + arguments.toggleLocalDNS(value) }) + case let .localDNSNotice(_, text): + return ItemListTextItem(presentationData: presentationData, text: .markdown(text), sectionId: self.section) case let .serversHeader(_, text): return ItemListSectionHeaderItem(presentationData: presentationData, text: text, sectionId: self.section) case let .addServer(_, text, _): @@ -225,13 +286,13 @@ private enum ProxySettingsControllerEntry: ItemListNodeEntry { arguments.removeServer(settings) }) case let .shareProxyList(_, text): - return ProxySettingsActionItem(presentationData: presentationData, systemStyle: .glass, title: text, sectionId: self.section, editing: false, action: { + return ProxySettingsActionItem(presentationData: presentationData, systemStyle: .glass, title: text, sectionId: self.section, editing: false, tag: ProxySettingsEntryTag.shareList, action: { arguments.shareProxyList() }) case let .useForCalls(_, text, value): return ItemListSwitchItem(presentationData: presentationData, systemStyle: .glass, title: text, value: value, enableInteractiveChanges: true, enabled: true, sectionId: self.section, style: .blocks, updated: { value in arguments.toggleUseForCalls(value) - }) + }, tag: ProxySettingsEntryTag.useForCalls) case let .useForCallsInfo(_, text): return ItemListTextItem(presentationData: presentationData, text: .plain(text), sectionId: self.section) } @@ -242,6 +303,9 @@ private func proxySettingsControllerEntries(theme: PresentationTheme, strings: P var entries: [ProxySettingsControllerEntry] = [] entries.append(.enabled(theme, strings.ChatSettings_ConnectionType_UseProxy, proxySettings.enabled, proxySettings.servers.isEmpty)) + // MARK: Swiftgram + entries.append(.localDNSToggle(theme, i18n("ProxySettings.UseSystemDNS", strings.baseLanguageCode), SGSimpleSettings.shared.localDNSForProxyHost)) + entries.append(.localDNSNotice(theme, i18n("ProxySettings.UseSystemDNS.Notice", strings.baseLanguageCode))) entries.append(.serversHeader(theme, strings.SocksProxySetup_SavedProxies)) entries.append(.addServer(theme, strings.SocksProxySetup_AddProxy, state.editing)) var index = 0 @@ -308,13 +372,14 @@ public enum ProxySettingsControllerMode { case modal } -public func proxySettingsController(context: AccountContext, mode: ProxySettingsControllerMode = .default) -> ViewController { +public func proxySettingsController(context: AccountContext, mode: ProxySettingsControllerMode = .default, focusOnItemTag: ProxySettingsEntryTag? = nil) -> ViewController { let presentationData = context.sharedContext.currentPresentationData.with { $0 } - return proxySettingsController(accountManager: context.sharedContext.accountManager, sharedContext: context.sharedContext, context: context, postbox: context.account.postbox, network: context.account.network, mode: mode, presentationData: presentationData, updatedPresentationData: context.sharedContext.presentationData) + return proxySettingsController(accountManager: context.sharedContext.accountManager, sharedContext: context.sharedContext, context: context, postbox: context.account.postbox, network: context.account.network, mode: mode, presentationData: presentationData, updatedPresentationData: context.sharedContext.presentationData, focusOnItemTag: focusOnItemTag) } -public func proxySettingsController(accountManager: AccountManager, sharedContext: SharedAccountContext, context: AccountContext? = nil, postbox: Postbox, network: Network, mode: ProxySettingsControllerMode, presentationData: PresentationData, updatedPresentationData: Signal) -> ViewController { +public func proxySettingsController(accountManager: AccountManager, sharedContext: SharedAccountContext, context: AccountContext? = nil, postbox: Postbox, network: Network, mode: ProxySettingsControllerMode, presentationData: PresentationData, updatedPresentationData: Signal, focusOnItemTag: ProxySettingsEntryTag? = nil) -> ViewController { var pushControllerImpl: ((ViewController) -> Void)? + var presentControllerImpl: ((ViewController, ViewControllerPresentationArguments?) -> Void)? var dismissImpl: (() -> Void)? let stateValue = Atomic(value: ProxySettingsControllerState()) let statePromise = ValuePromise(stateValue.with { $0 }) @@ -332,9 +397,35 @@ public func proxySettingsController(accountManager: AccountManager Void)? - let arguments = ProxySettingsControllerArguments(toggleEnabled: { value in + let arguments = ProxySettingsControllerArguments(toggleLocalDNS: { value in + SGSimpleSettings.shared.localDNSForProxyHost = value + guard let context = context else { + return + } + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + let actionSheet = ActionSheetController(presentationData: presentationData) + actionSheet.setItemGroups([ActionSheetItemGroup(items: [ + ActionSheetTextItem(title: i18n("Common.RestartRequired", presentationData.strings.baseLanguageCode)), + ActionSheetButtonItem(title: i18n("Common.RestartNow", presentationData.strings.baseLanguageCode), color: .destructive, font: .default, action: { + exit(0) + }) + ]), ActionSheetItemGroup(items: [ + ActionSheetButtonItem(title: presentationData.strings.Common_Cancel, color: .accent, font: .bold, action: { [weak actionSheet] in + actionSheet?.dismissAnimated() + }) + ])]) + presentControllerImpl?(actionSheet, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + }, toggleEnabled: { value in let _ = updateProxySettingsInteractively(accountManager: accountManager, { current in var current = current current.enabled = value @@ -431,7 +522,7 @@ public func proxySettingsController(accountManager: AccountManager Void - init(presentationData: ItemListPresentationData, systemStyle: ItemListSystemStyle = .legacy, title: String, icon: ProxySettingsActionIcon = .none, sectionId: ItemListSectionId, editing: Bool, action: @escaping () -> Void) { + init(presentationData: ItemListPresentationData, systemStyle: ItemListSystemStyle = .legacy, title: String, icon: ProxySettingsActionIcon = .none, sectionId: ItemListSectionId, editing: Bool, tag: ItemListItemTag? = nil, action: @escaping () -> Void) { self.presentationData = presentationData self.systemStyle = systemStyle self.title = title self.icon = icon self.editing = editing self.sectionId = sectionId + self.tag = tag self.action = action } @@ -77,7 +79,7 @@ final class ProxySettingsActionItem: ListViewItem, ItemListItem { } } -private final class ProxySettingsActionItemNode: ListViewItemNode { +private final class ProxySettingsActionItemNode: ListViewItemNode, ItemListItemNode { private let backgroundNode: ASDisplayNode private let topStripeNode: ASDisplayNode private let bottomStripeNode: ASDisplayNode @@ -89,6 +91,10 @@ private final class ProxySettingsActionItemNode: ListViewItemNode { private var item: ProxySettingsActionItem? + var tag: ItemListItemTag? { + return self.item?.tag + } + init() { self.backgroundNode = ASDisplayNode() self.backgroundNode.isLayerBacked = true diff --git a/submodules/SettingsUI/Sources/DeletedMessagesController.swift b/submodules/SettingsUI/Sources/DeletedMessagesController.swift index 20fc8e6a..fbb7f9fb 100644 --- a/submodules/SettingsUI/Sources/DeletedMessagesController.swift +++ b/submodules/SettingsUI/Sources/DeletedMessagesController.swift @@ -8,8 +8,10 @@ import Postbox import TelegramPresentationData import ItemListUI import AccountContext +import PresentationDataUtils import ComponentFlow import SliderComponent +import AlertUI private let minDeletedMessageTransparencyPercent: Int32 = Int32(AntiDeleteManager.minDeletedMessageTransparency * 100.0) private let maxDeletedMessageTransparencyPercent: Int32 = Int32(AntiDeleteManager.maxDeletedMessageTransparency * 100.0) @@ -27,6 +29,7 @@ private enum DeletedMessagesSection: Int32 { private enum DeletedMessagesEntry: ItemListNodeEntry { case enableToggle(PresentationTheme, String, Bool) case archiveMediaToggle(PresentationTheme, String, Bool) + case history(PresentationTheme, String, String) case transparencySlider(PresentationTheme, Int32, Bool) case settingsInfo(PresentationTheme, String) @@ -40,10 +43,12 @@ private enum DeletedMessagesEntry: ItemListNodeEntry { return 0 case .archiveMediaToggle: return 1 - case .transparencySlider: + case .history: return 2 - case .settingsInfo: + case .transparencySlider: return 3 + case .settingsInfo: + return 4 } } @@ -61,6 +66,12 @@ private enum DeletedMessagesEntry: ItemListNodeEntry { return true } return false + case let .history(lhsTheme, lhsText, lhsValue): + if case let .history(rhsTheme, rhsText, rhsValue) = rhs, + lhsTheme === rhsTheme, lhsText == rhsText, lhsValue == rhsValue { + return true + } + return false case let .transparencySlider(lhsTheme, lhsValue, lhsIsEnabled): if case let .transparencySlider(rhsTheme, rhsValue, rhsIsEnabled) = rhs, lhsTheme === rhsTheme, lhsValue == rhsValue, lhsIsEnabled == rhsIsEnabled { @@ -104,6 +115,17 @@ private enum DeletedMessagesEntry: ItemListNodeEntry { arguments.toggleArchiveMedia(value) } ) + case let .history(_, text, value): + return ItemListDisclosureItem( + presentationData: presentationData, + title: text, + label: value, + sectionId: self.section, + style: .blocks, + action: { + arguments.openHistory() + } + ) case let .transparencySlider(theme, value, isEnabled): return DeletedMessagesTransparencySliderItem( theme: theme, @@ -125,15 +147,18 @@ private enum DeletedMessagesEntry: ItemListNodeEntry { private final class DeletedMessagesControllerArguments { let toggleEnabled: (Bool) -> Void let toggleArchiveMedia: (Bool) -> Void + let openHistory: () -> Void let updateTransparency: (Int32) -> Void init( toggleEnabled: @escaping (Bool) -> Void, toggleArchiveMedia: @escaping (Bool) -> Void, + openHistory: @escaping () -> Void, updateTransparency: @escaping (Int32) -> Void ) { self.toggleEnabled = toggleEnabled self.toggleArchiveMedia = toggleArchiveMedia + self.openHistory = openHistory self.updateTransparency = updateTransparency } } @@ -143,11 +168,13 @@ private final class DeletedMessagesControllerArguments { private struct DeletedMessagesControllerState: Equatable { var isEnabled: Bool var archiveMedia: Bool + var archivedCount: Int var transparencyPercent: Int32 static func ==(lhs: DeletedMessagesControllerState, rhs: DeletedMessagesControllerState) -> Bool { return lhs.isEnabled == rhs.isEnabled && lhs.archiveMedia == rhs.archiveMedia && + lhs.archivedCount == rhs.archivedCount && lhs.transparencyPercent == rhs.transparencyPercent } } @@ -162,6 +189,7 @@ private func deletedMessagesControllerEntries( entries.append(.enableToggle(presentationData.theme, "Сохранять удалённые сообщения", state.isEnabled)) entries.append(.archiveMediaToggle(presentationData.theme, "Архивировать медиа", state.archiveMedia)) + entries.append(.history(presentationData.theme, "История удалений", state.archivedCount == 0 ? "Пусто" : "\(state.archivedCount)")) entries.append(.transparencySlider(presentationData.theme, state.transparencyPercent, state.isEnabled)) entries.append(.settingsInfo(presentationData.theme, "Когда включено, сообщения, удалённые другими пользователями, будут сохраняться локально. Прозрачность влияет только на сообщения, которые уже помечены как удалённые.")) @@ -171,9 +199,12 @@ private func deletedMessagesControllerEntries( // MARK: - Controller public func deletedMessagesController(context: AccountContext) -> ViewController { + var pushControllerImpl: ((ViewController, Bool) -> Void)? + let initialState = DeletedMessagesControllerState( isEnabled: AntiDeleteManager.shared.isEnabled, archiveMedia: AntiDeleteManager.shared.archiveMedia, + archivedCount: AntiDeleteManager.shared.archivedCount, transparencyPercent: clampDeletedMessageTransparencyPercent(Int32(round(AntiDeleteManager.shared.deletedMessageTransparency * 100.0))) ) @@ -200,6 +231,9 @@ public func deletedMessagesController(context: AccountContext) -> ViewController return state } }, + openHistory: { + pushControllerImpl?(deletedMessagesHistoryController(context: context), true) + }, updateTransparency: { value in let clampedValue = clampDeletedMessageTransparencyPercent(value) AntiDeleteManager.shared.deletedMessageTransparency = Double(clampedValue) / 100.0 @@ -238,6 +272,257 @@ public func deletedMessagesController(context: AccountContext) -> ViewController } let controller = ItemListController(context: context, state: signal) + controller.didAppear = { _ in + updateState { state in + var state = state + state.isEnabled = AntiDeleteManager.shared.isEnabled + state.archiveMedia = AntiDeleteManager.shared.archiveMedia + state.archivedCount = AntiDeleteManager.shared.archivedCount + state.transparencyPercent = clampDeletedMessageTransparencyPercent(Int32(round(AntiDeleteManager.shared.deletedMessageTransparency * 100.0))) + return state + } + } + pushControllerImpl = { [weak controller] c, _ in + controller?.push(c) + } + return controller +} + +// MARK: - Deleted History + +private enum DeletedMessagesHistorySection: Int32 { + case actions + case messages +} + +private enum DeletedMessagesHistoryEntry: ItemListNodeEntry { + case clear(PresentationTheme, Bool) + case message(PresentationTheme, Int32, String, String) + case empty(PresentationTheme, String) + + var section: ItemListSectionId { + switch self { + case .clear: + return DeletedMessagesHistorySection.actions.rawValue + case .message, .empty: + return DeletedMessagesHistorySection.messages.rawValue + } + } + + var stableId: Int32 { + switch self { + case .clear: + return 0 + case let .message(_, index, _, _): + return 1000 + index + case .empty: + return 1 + } + } + + static func ==(lhs: DeletedMessagesHistoryEntry, rhs: DeletedMessagesHistoryEntry) -> Bool { + switch lhs { + case let .clear(lhsTheme, lhsEnabled): + if case let .clear(rhsTheme, rhsEnabled) = rhs, lhsTheme === rhsTheme, lhsEnabled == rhsEnabled { + return true + } + return false + case let .message(lhsTheme, lhsIndex, lhsTitle, lhsLabel): + if case let .message(rhsTheme, rhsIndex, rhsTitle, rhsLabel) = rhs, lhsTheme === rhsTheme, lhsIndex == rhsIndex, lhsTitle == rhsTitle, lhsLabel == rhsLabel { + return true + } + return false + case let .empty(lhsTheme, lhsText): + if case let .empty(rhsTheme, rhsText) = rhs, lhsTheme === rhsTheme, lhsText == rhsText { + return true + } + return false + } + } + + static func <(lhs: DeletedMessagesHistoryEntry, rhs: DeletedMessagesHistoryEntry) -> Bool { + return lhs.stableId < rhs.stableId + } + + func item(presentationData: ItemListPresentationData, arguments: Any) -> ListViewItem { + let arguments = arguments as! DeletedMessagesHistoryControllerArguments + + switch self { + case let .clear(_, enabled): + return ItemListActionItem( + presentationData: presentationData, + systemStyle: .glass, + title: "Очистить историю", + kind: enabled ? .destructive : .disabled, + alignment: .natural, + sectionId: self.section, + style: .blocks, + action: { + if enabled { + arguments.clearHistory() + } + } + ) + case let .message(_, _, title, label): + return ItemListTextItem( + presentationData: presentationData, + text: .plain("\(label)\n\(title)"), + sectionId: self.section + ) + case let .empty(_, text): + return ItemListTextItem( + presentationData: presentationData, + text: .plain(text), + sectionId: self.section + ) + } + } +} + +private final class DeletedMessagesHistoryControllerArguments { + let clearHistory: () -> Void + + init(clearHistory: @escaping () -> Void) { + self.clearHistory = clearHistory + } +} + +private struct DeletedMessagesHistoryControllerState: Equatable { + var messages: [AntiDeleteManager.ArchivedMessage] + + static func ==(lhs: DeletedMessagesHistoryControllerState, rhs: DeletedMessagesHistoryControllerState) -> Bool { + if lhs.messages.count != rhs.messages.count { + return false + } + for (lhsMessage, rhsMessage) in zip(lhs.messages, rhs.messages) { + if lhsMessage.globalId != rhsMessage.globalId || + lhsMessage.peerId != rhsMessage.peerId || + lhsMessage.messageId != rhsMessage.messageId || + lhsMessage.timestamp != rhsMessage.timestamp || + lhsMessage.deletedAt != rhsMessage.deletedAt || + lhsMessage.authorId != rhsMessage.authorId || + lhsMessage.text != rhsMessage.text || + lhsMessage.forwardAuthorId != rhsMessage.forwardAuthorId || + lhsMessage.mediaDescription != rhsMessage.mediaDescription { + return false + } + } + return true + } +} + +private func deletedMessagesHistoryDateString(timestamp: Int32) -> String { + let formatter = DateFormatter() + formatter.locale = Locale.current + formatter.dateStyle = .short + formatter.timeStyle = .medium + return formatter.string(from: Date(timeIntervalSince1970: TimeInterval(timestamp))) +} + +private func deletedMessagesHistoryEntries( + presentationData: PresentationData, + state: DeletedMessagesHistoryControllerState +) -> [DeletedMessagesHistoryEntry] { + var entries: [DeletedMessagesHistoryEntry] = [] + entries.append(.clear(presentationData.theme, !state.messages.isEmpty)) + + if state.messages.isEmpty { + entries.append(.empty(presentationData.theme, "История удалений пуста.")) + return entries + } + + for (index, message) in state.messages.enumerated() { + var preview = message.text.trimmingCharacters(in: .whitespacesAndNewlines) + if preview.isEmpty { + preview = message.mediaDescription ?? "Сообщение без текста" + } + preview = preview.replacingOccurrences(of: "\n", with: " ") + if preview.count > 80 { + preview = String(preview.prefix(80)) + "..." + } + + let title = "Чат \(message.peerId): \(preview)" + let label = deletedMessagesHistoryDateString(timestamp: message.deletedAt) + + entries.append(.message(presentationData.theme, Int32(index), title, label)) + } + + return entries +} + +private func deletedMessagesHistoryController(context: AccountContext) -> ViewController { + var presentControllerImpl: ((ViewController, ViewControllerPresentationArguments?) -> Void)? + + let initialState = DeletedMessagesHistoryControllerState( + messages: AntiDeleteManager.shared.getAllArchivedMessages() + ) + + let statePromise = ValuePromise(initialState, ignoreRepeated: true) + let stateValue = Atomic(value: initialState) + let updateState: ((DeletedMessagesHistoryControllerState) -> DeletedMessagesHistoryControllerState) -> Void = { f in + statePromise.set(stateValue.modify { f($0) }) + } + + let arguments = DeletedMessagesHistoryControllerArguments( + clearHistory: { + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + let alert = textAlertController( + context: context, + title: "Очистить историю?", + text: "Это удалит локально сохранённые удалённые сообщения.", + actions: [ + TextAlertAction(type: .genericAction, title: presentationData.strings.Common_Cancel, action: {}), + TextAlertAction(type: .destructiveAction, title: "Очистить", action: { + AntiDeleteManager.shared.clearArchive() + updateState { state in + var state = state + state.messages = AntiDeleteManager.shared.getAllArchivedMessages() + return state + } + }) + ] + ) + presentControllerImpl?(alert, nil) + } + ) + + let signal: Signal<(ItemListControllerState, (ItemListNodeState, DeletedMessagesHistoryControllerArguments)), NoError> = combineLatest( + context.sharedContext.presentationData, + statePromise.get() + ) + |> map { presentationData, state -> (ItemListControllerState, (ItemListNodeState, DeletedMessagesHistoryControllerArguments)) in + let entries = deletedMessagesHistoryEntries(presentationData: presentationData, state: state) + + let controllerState = ItemListControllerState( + presentationData: ItemListPresentationData(presentationData), + title: .text("История удалений"), + leftNavigationButton: nil, + rightNavigationButton: nil, + backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back), + animateChanges: false + ) + + let listState = ItemListNodeState( + presentationData: ItemListPresentationData(presentationData), + entries: entries, + style: .blocks, + animateChanges: false + ) + + return (controllerState, (listState, arguments)) + } + + let controller = ItemListController(context: context, state: signal) + controller.didAppear = { _ in + updateState { state in + var state = state + state.messages = AntiDeleteManager.shared.getAllArchivedMessages() + return state + } + } + presentControllerImpl = { [weak controller] c, a in + controller?.present(c, in: .window(.root), with: a) + } return controller } diff --git a/submodules/SettingsUI/Sources/DeviceSpoofController.swift b/submodules/SettingsUI/Sources/DeviceSpoofController.swift index a6b7f454..9cc7cbaf 100644 --- a/submodules/SettingsUI/Sources/DeviceSpoofController.swift +++ b/submodules/SettingsUI/Sources/DeviceSpoofController.swift @@ -236,24 +236,28 @@ public func deviceSpoofController(context: AccountContext) -> ViewController { let arguments = DeviceSpoofControllerArguments( toggleEnabled: { value in + DeviceSpoofManager.shared.hasExplicitConfiguration = true DeviceSpoofManager.shared.isEnabled = value updateState { state in state.isEnabled = value } }, selectProfile: { id in + DeviceSpoofManager.shared.hasExplicitConfiguration = true DeviceSpoofManager.shared.selectedProfileId = id updateState { state in state.selectedProfileId = id } }, updateCustomDeviceModel: { text in + DeviceSpoofManager.shared.hasExplicitConfiguration = true DeviceSpoofManager.shared.customDeviceModel = text updateState { state in state.customDeviceModel = text } }, updateCustomSystemVersion: { text in + DeviceSpoofManager.shared.hasExplicitConfiguration = true DeviceSpoofManager.shared.customSystemVersion = text updateState { state in state.customSystemVersion = text diff --git a/submodules/SettingsUI/Sources/Privacy and Security/Recent Sessions/RecentSessionsController.swift b/submodules/SettingsUI/Sources/Privacy and Security/Recent Sessions/RecentSessionsController.swift index 7ff33d6e..4610747e 100644 --- a/submodules/SettingsUI/Sources/Privacy and Security/Recent Sessions/RecentSessionsController.swift +++ b/submodules/SettingsUI/Sources/Privacy and Security/Recent Sessions/RecentSessionsController.swift @@ -89,6 +89,20 @@ private struct SortIndex: Comparable { } } +public enum RecentSessionsEntryTag: ItemListItemTag, Equatable { + case edit + case terminateOtherSessions + case autoTerminate + + public func isEqual(to other: ItemListItemTag) -> Bool { + if let other = other as? RecentSessionsEntryTag, self == other { + return true + } else { + return false + } + } +} + private enum RecentSessionsEntry: ItemListNodeEntry { case header(SortIndex, String) case currentSessionHeader(SortIndex, String) @@ -339,7 +353,7 @@ private enum RecentSessionsEntry: ItemListNodeEntry { arguments.openSession(session) }) case let .terminateOtherSessions(_, text): - return ItemListPeerActionItem(presentationData: presentationData, systemStyle: .glass, icon: PresentationResourcesItemList.blockDestructiveIcon(presentationData.theme), title: text, sectionId: self.section, height: .generic, color: .destructive, editing: false, action: { + return ItemListPeerActionItem(presentationData: presentationData, systemStyle: .glass, icon: PresentationResourcesItemList.blockDestructiveIcon(presentationData.theme), title: text, sectionId: self.section, height: .generic, color: .destructive, editing: false, tag: RecentSessionsEntryTag.terminateOtherSessions, action: { arguments.terminateOtherSessions() }) case let .terminateAllWebSessions(_, text): @@ -403,7 +417,7 @@ private enum RecentSessionsEntry: ItemListNodeEntry { case let .ttlTimeout(_, text, value): return ItemListDisclosureItem(presentationData: presentationData, systemStyle: .glass, title: text, label: value, sectionId: self.section, style: .blocks, action: { arguments.setupAuthorizationTTL() - }, tag: PrivacyAndSecurityEntryTag.accountTimeout) + }, tag: RecentSessionsEntryTag.autoTerminate) } } } @@ -560,13 +574,19 @@ private func recentSessionsControllerEntries(presentationData: PresentationData, private final class RecentSessionsControllerImpl: ItemListController, RecentSessionsController { } -public func recentSessionsController(context: AccountContext, activeSessionsContext: ActiveSessionsContext, webSessionsContext: WebSessionsContext, websitesOnly: Bool) -> ViewController & RecentSessionsController { +public func recentSessionsController(context: AccountContext, activeSessionsContext: ActiveSessionsContext, webSessionsContext: WebSessionsContext, websitesOnly: Bool, focusOnItemTag: RecentSessionsEntryTag? = nil) -> ViewController & RecentSessionsController { let statePromise = ValuePromise(RecentSessionsControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: RecentSessionsControllerState()) let updateState: ((RecentSessionsControllerState) -> RecentSessionsControllerState) -> Void = { f in statePromise.set(stateValue.modify { f($0) }) } + if focusOnItemTag == .edit { + updateState { + $0.withUpdatedEditing(true) + } + } + activeSessionsContext.loadMore() webSessionsContext.loadMore() @@ -603,15 +623,12 @@ public func recentSessionsController(context: AccountContext, activeSessionsCont let removeSessionImpl: (Int64, @escaping () -> Void) -> Void = { sessionId, completion in let presentationData = context.sharedContext.currentPresentationData.with { $0 } - let controller = ActionSheetController(presentationData: presentationData) - let dismissAction: () -> Void = { [weak controller] in - controller?.dismissAnimated() - } - controller.setItemGroups([ - ActionSheetItemGroup(items: [ - ActionSheetTextItem(title: presentationData.strings.AuthSessions_TerminateSessionText), - ActionSheetButtonItem(title: presentationData.strings.AuthSessions_TerminateSession, color: .destructive, action: { - dismissAction() + let controller = textAlertController( + context: context, + title: nil, + text: presentationData.strings.AuthSessions_TerminateSessionText, + actions: [ + TextAlertAction(type: .defaultDestructiveAction, title: presentationData.strings.AuthSessions_TerminateSession, action: { completion() updateState { @@ -629,11 +646,12 @@ public func recentSessionsController(context: AccountContext, activeSessionsCont } context.sharedContext.updateNotificationTokensRegistration() })) - }) - ]), - ActionSheetItemGroup(items: [ActionSheetButtonItem(title: presentationData.strings.Common_Cancel, action: { dismissAction() })]) - ]) - presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + }), + TextAlertAction(type: .genericAction, title: presentationData.strings.Common_Cancel, action: {}) + ], + actionLayout: .vertical + ) + presentControllerImpl?(controller, nil) } let removeWebSessionImpl: (Int64) -> Void = { sessionId in @@ -670,16 +688,12 @@ public func recentSessionsController(context: AccountContext, activeSessionsCont removeSessionImpl(sessionId, {}) }, terminateOtherSessions: { let presentationData = context.sharedContext.currentPresentationData.with { $0 } - let controller = ActionSheetController(presentationData: presentationData) - let dismissAction: () -> Void = { [weak controller] in - controller?.dismissAnimated() - } - controller.setItemGroups([ - ActionSheetItemGroup(items: [ - ActionSheetTextItem(title: presentationData.strings.AuthSessions_TerminateOtherSessionsText), - ActionSheetButtonItem(title: presentationData.strings.AuthSessions_TerminateOtherSessions, color: .destructive, action: { - dismissAction() - + let controller = textAlertController( + context: context, + title: nil, + text: presentationData.strings.AuthSessions_TerminateOtherSessionsText, + actions: [ + TextAlertAction(type: .defaultDestructiveAction, title: presentationData.strings.AuthSessions_TerminateOtherSessions, action: { updateState { return $0.withUpdatedTerminatingOtherSessions(true) } @@ -695,11 +709,12 @@ public func recentSessionsController(context: AccountContext, activeSessionsCont } context.sharedContext.updateNotificationTokensRegistration() })) - }) - ]), - ActionSheetItemGroup(items: [ActionSheetButtonItem(title: presentationData.strings.Common_Cancel, action: { dismissAction() })]) - ]) - presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + }), + TextAlertAction(type: .genericAction, title: presentationData.strings.Common_Cancel, action: {}) + ], + actionLayout: .vertical + ) + presentControllerImpl?(controller, nil) }, openSession: { session in let controller = RecentSessionScreen(context: context, subject: .session(session), updateAcceptSecretChats: { value in updateSessionDisposable.set(activeSessionsContext.updateSessionAcceptsSecretChats(session, accepts: value).start()) @@ -801,6 +816,10 @@ public func recentSessionsController(context: AccountContext, activeSessionsCont guard let appConfiguration = view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) else { return false } + // MARK: Swiftgram + if appConfiguration.sgWebSettings.global.qrLogin { + return true + } guard let data = appConfiguration.data, let enableQR = data["qr_login_camera"] as? Bool, enableQR else { return false } @@ -865,7 +884,7 @@ public func recentSessionsController(context: AccountContext, activeSessionsCont } let controllerState = ItemListControllerState(presentationData: ItemListPresentationData(presentationData), title: title, leftNavigationButton: nil, rightNavigationButton: rightNavigationButton, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back), animateChanges: true) - let listState = ItemListNodeState(presentationData: ItemListPresentationData(presentationData), entries: entries, style: .blocks, emptyStateItem: emptyStateItem, crossfadeState: crossfadeState, animateChanges: animateChanges, scrollEnabled: emptyStateItem == nil) + let listState = ItemListNodeState(presentationData: ItemListPresentationData(presentationData), entries: entries, style: .blocks, ensureVisibleItemTag: focusOnItemTag, emptyStateItem: emptyStateItem, crossfadeState: crossfadeState, animateChanges: animateChanges, scrollEnabled: emptyStateItem == nil) return (controllerState, (listState, arguments)) } |> afterDisposed { @@ -891,5 +910,19 @@ public func recentSessionsController(context: AccountContext, activeSessionsCont controller?.dismiss() } + if let focusOnItemTag { + var didFocusOnItem = false + controller.afterTransactionCompleted = { [weak controller] in + if !didFocusOnItem, let controller { + controller.forEachItemNode { itemNode in + if let itemNode = itemNode as? ItemListItemNode, let tag = itemNode.tag, tag.isEqual(to: focusOnItemTag) { + didFocusOnItem = true + itemNode.displayHighlight() + } + } + } + } + } + return controller } diff --git a/submodules/SettingsUI/Sources/Privacy and Security/RecentSessionScreen.swift b/submodules/SettingsUI/Sources/Privacy and Security/RecentSessionScreen.swift index ef326ba1..73f57ea8 100644 --- a/submodules/SettingsUI/Sources/Privacy and Security/RecentSessionScreen.swift +++ b/submodules/SettingsUI/Sources/Privacy and Security/RecentSessionScreen.swift @@ -5,359 +5,271 @@ import AsyncDisplayKit import TelegramCore import SwiftSignalKit import AccountContext -import SolidRoundedButtonNode import TelegramPresentationData -import TelegramUIPreferences -import TelegramStringFormatting +import ComponentFlow +import ViewControllerComponent +import SheetComponent +import MultilineTextComponent +import BalancedTextComponent +import GlassBarButtonComponent +import ButtonComponent +import TableComponent import PresentationDataUtils -import AnimationUI -import MergeLists -import MediaResources -import StickerResources -import AnimatedStickerNode -import TelegramAnimatedStickerNode -import AvatarNode -import UndoUI +import BundleIconComponent +import LottieAnimationComponent +import ListSectionComponent +import ListActionItemComponent +import AvatarComponent +import TelegramStringFormatting +import Markdown -private func closeButtonImage(theme: PresentationTheme) -> UIImage? { - return generateImage(CGSize(width: 30.0, height: 30.0), contextGenerator: { size, context in - context.clear(CGRect(origin: CGPoint(), size: size)) - - context.setFillColor(UIColor(rgb: 0x808084, alpha: 0.1).cgColor) - context.fillEllipse(in: CGRect(origin: CGPoint(), size: size)) - - context.setLineWidth(2.0) - context.setLineCap(.round) - context.setStrokeColor(theme.actionSheet.inputClearButtonColor.cgColor) - - context.move(to: CGPoint(x: 10.0, y: 10.0)) - context.addLine(to: CGPoint(x: 20.0, y: 20.0)) - context.strokePath() - - context.move(to: CGPoint(x: 20.0, y: 10.0)) - context.addLine(to: CGPoint(x: 10.0, y: 20.0)) - context.strokePath() - }) -} - -final class RecentSessionScreen: ViewController { - enum Subject { - case session(RecentAccountSession) - case website(WebAuthorization, EnginePeer?) - } - private var controllerNode: RecentSessionScreenNode { - return self.displayNode as! RecentSessionScreenNode - } +private final class RecentSessionSheetContent: CombinedComponent { + typealias EnvironmentType = ViewControllerComponentContainer.Environment - private var animatedIn = false + let context: AccountContext + let subject: RecentSessionScreen.Subject + let cancel: (Bool) -> Void - private let context: AccountContext - private let subject: RecentSessionScreen.Subject - private let remove: (@escaping () -> Void) -> Void - private let updateAcceptSecretChats: (Bool) -> Void - private let updateAcceptIncomingCalls: (Bool) -> Void - - private var presentationData: PresentationData - private var presentationDataDisposable: Disposable? - - var dismissed: (() -> Void)? - - var passthroughHitTestImpl: ((CGPoint) -> UIView?)? { - didSet { - if self.isNodeLoaded { - self.controllerNode.passthroughHitTestImpl = self.passthroughHitTestImpl - } - } - } - - init(context: AccountContext, subject: RecentSessionScreen.Subject, updateAcceptSecretChats: @escaping (Bool) -> Void, updateAcceptIncomingCalls: @escaping (Bool) -> Void, remove: @escaping (@escaping () -> Void) -> Void) { + init( + context: AccountContext, + subject: RecentSessionScreen.Subject, + cancel: @escaping (Bool) -> Void + ) { self.context = context - self.presentationData = context.sharedContext.currentPresentationData.with { $0 } self.subject = subject - self.remove = remove - self.updateAcceptSecretChats = updateAcceptSecretChats - self.updateAcceptIncomingCalls = updateAcceptIncomingCalls + self.cancel = cancel + } + + static func ==(lhs: RecentSessionSheetContent, rhs: RecentSessionSheetContent) -> Bool { + if lhs.context !== rhs.context { + return false + } + return true + } + + final class State: ComponentState { + var allowSecretChats: Bool? + var allowIncomingCalls: Bool? - super.init(navigationBarPresentationData: nil) + weak var controller: RecentSessionScreen? - self.statusBar.statusBarStyle = .Ignore - - self.blocksBackgroundWhenInOverlay = true - - self.presentationDataDisposable = (context.sharedContext.presentationData - |> deliverOnMainQueue).start(next: { [weak self] presentationData in - if let strongSelf = self { - strongSelf.presentationData = presentationData - strongSelf.controllerNode.updatePresentationData(presentationData) + init(subject: RecentSessionScreen.Subject) { + super.init() + + switch subject { + case let .session(session): + if !session.flags.contains(.passwordPending) && session.apiId != 22 { + self.allowIncomingCalls = session.flags.contains(.acceptsIncomingCalls) + + if ![2040, 2496].contains(session.apiId) { + self.allowSecretChats = session.flags.contains(.acceptsSecretChats) + } + } + case .website: + break } - }) + } - self.statusBar.statusBarStyle = .Ignore - } - - required init(coder aDecoder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - deinit { - self.presentationDataDisposable?.dispose() - } - - override public func loadDisplayNode() { - self.displayNode = RecentSessionScreenNode(context: self.context, presentationData: self.presentationData, controller: self, subject: self.subject) - self.controllerNode.passthroughHitTestImpl = self.passthroughHitTestImpl - self.controllerNode.present = { [weak self] c in - self?.present(c, in: .current) + func toggleAllowSecretChats() { + guard let controller = self.controller else { + return + } + + if let allowSecretChats = self.allowSecretChats { + let newValue = !allowSecretChats + self.allowSecretChats = newValue + controller.updateAcceptSecretChats(newValue) + } + + self.updated() } - self.controllerNode.dismiss = { [weak self] in - self?.presentingViewController?.dismiss(animated: false, completion: nil) + + func toggleAllowIncomingCalls() { + guard let controller = self.controller else { + return + } + + if let allowIncomingCalls = self.allowIncomingCalls { + let newValue = !allowIncomingCalls + self.allowIncomingCalls = newValue + controller.updateAcceptIncomingCalls(newValue) + } + + self.updated() } - self.controllerNode.remove = { [weak self] in - self?.remove({ - self?.controllerNode.animateOut() + + func terminate() { + guard let controller = self.controller else { + return + } + self.updated() + + controller.remove({ [weak controller] in + controller?.dismissAnimated() }) } - self.controllerNode.updateAcceptSecretChats = { [weak self] value in - self?.updateAcceptSecretChats(value) - } - self.controllerNode.updateAcceptIncomingCalls = { [weak self] value in - self?.updateAcceptIncomingCalls(value) - } } - override public func loadView() { - super.loadView() - - self.view.disablesInteractiveTransitionGestureRecognizer = true + func makeState() -> State { + return State(subject: self.subject) } - override public func viewDidAppear(_ animated: Bool) { - super.viewDidAppear(animated) + static var body: Body { + let closeButton = Child(GlassBarButtonComponent.self) + let icon = Child(ZStack.self) + let avatar = Child(AvatarComponent.self) + let title = Child(BalancedTextComponent.self) + let description = Child(MultilineTextComponent.self) + let clientSection = Child(ListSectionComponent.self) + let optionsSection = Child(ListSectionComponent.self) + let button = Child(ButtonComponent.self) - if !self.animatedIn { - self.animatedIn = true - self.controllerNode.animateIn() - } - } - - override public func dismiss(completion: (() -> Void)? = nil) { - self.controllerNode.animateOut(completion: completion) - - self.dismissed?() - } - - override public func containerLayoutUpdated(_ layout: ContainerViewLayout, transition: ContainedViewLayoutTransition) { - super.containerLayoutUpdated(layout, transition: transition) - - self.controllerNode.containerLayoutUpdated(layout, navigationBarHeight: self.navigationLayout(layout: layout).navigationFrame.maxY, transition: transition) - } -} - -private class RecentSessionScreenNode: ViewControllerTracingNode, ASScrollViewDelegate { - private let context: AccountContext - private var presentationData: PresentationData - private weak var controller: RecentSessionScreen? - private let subject: RecentSessionScreen.Subject - - private let dimNode: ASDisplayNode - private let wrappingScrollNode: ASScrollNode - private let contentContainerNode: ASDisplayNode - private let topContentContainerNode: SparseNode - private let backgroundNode: ASDisplayNode - private let contentBackgroundNode: ASDisplayNode - private var iconNode: ASImageNode? - private var animationBackgroundNode: ASDisplayNode? - private var animationNode: AnimationNode? - private var avatarNode: AvatarNode? - private let titleNode: ImmediateTextNode - private let textNode: ImmediateTextNode - private let fieldBackgroundNode: ASDisplayNode - private let deviceTitleNode: ImmediateTextNode - private let deviceValueNode: ImmediateTextNode - private let firstSeparatorNode: ASDisplayNode - private let ipTitleNode: ImmediateTextNode - private let ipValueNode: ImmediateTextNode - private let secondSeparatorNode: ASDisplayNode - private let locationTitleNode: ImmediateTextNode - private let locationValueNode: ImmediateTextNode - private let locationInfoNode: ImmediateTextNode - - private let acceptBackgroundNode: ASDisplayNode - private let acceptHeaderNode: ImmediateTextNode - private let secretChatsTitleNode: ImmediateTextNode - private let secretChatsSwitchNode: SwitchNode - private let secretChatsActivateAreaNode: AccessibilityAreaNode - private let incomingCallsTitleNode: ImmediateTextNode - private let incomingCallsSwitchNode: SwitchNode - private let incomingCallsActivateAreaNode: AccessibilityAreaNode - private let acceptSeparatorNode: ASDisplayNode - - private let cancelButton: HighlightableButtonNode - private let terminateButton: SolidRoundedButtonNode - - private var containerLayout: (ContainerViewLayout, CGFloat)? - - var present: ((ViewController) -> Void)? - var remove: (() -> Void)? - var dismiss: (() -> Void)? - var updateAcceptSecretChats: ((Bool) -> Void)? - var updateAcceptIncomingCalls: ((Bool) -> Void)? - - init(context: AccountContext, presentationData: PresentationData, controller: RecentSessionScreen, subject: RecentSessionScreen.Subject) { - self.context = context - self.controller = controller - self.presentationData = presentationData - self.subject = subject - - self.wrappingScrollNode = ASScrollNode() - self.wrappingScrollNode.view.alwaysBounceVertical = true - self.wrappingScrollNode.view.delaysContentTouches = false - self.wrappingScrollNode.view.showsVerticalScrollIndicator = false - self.wrappingScrollNode.view.canCancelContentTouches = true - - self.dimNode = ASDisplayNode() - self.dimNode.backgroundColor = UIColor(white: 0.0, alpha: 0.5) - - self.contentContainerNode = ASDisplayNode() - self.contentContainerNode.isOpaque = false - - self.topContentContainerNode = SparseNode() - self.topContentContainerNode.isOpaque = false - - self.backgroundNode = ASDisplayNode() - self.backgroundNode.clipsToBounds = true - self.backgroundNode.cornerRadius = 16.0 - - let backgroundColor = self.presentationData.theme.list.blocksBackgroundColor - let textColor = self.presentationData.theme.list.itemPrimaryTextColor - let accentColor = self.presentationData.theme.list.itemAccentColor - let secondaryTextColor = self.presentationData.theme.list.itemSecondaryTextColor - - self.contentBackgroundNode = ASDisplayNode() - self.contentBackgroundNode.backgroundColor = backgroundColor - - self.titleNode = ImmediateTextNode() - self.titleNode.maximumNumberOfLines = 2 - self.titleNode.textAlignment = .center - - self.textNode = ImmediateTextNode() - self.textNode.maximumNumberOfLines = 1 - self.textNode.textAlignment = .center - - self.fieldBackgroundNode = ASDisplayNode() - self.fieldBackgroundNode.clipsToBounds = true - self.fieldBackgroundNode.cornerRadius = 11 - self.fieldBackgroundNode.backgroundColor = self.presentationData.theme.list.itemBlocksBackgroundColor - - self.deviceTitleNode = ImmediateTextNode() - self.deviceValueNode = ImmediateTextNode() - - self.ipTitleNode = ImmediateTextNode() - self.ipValueNode = ImmediateTextNode() - - self.locationTitleNode = ImmediateTextNode() - self.locationValueNode = ImmediateTextNode() - self.locationInfoNode = ImmediateTextNode() - - self.acceptHeaderNode = ImmediateTextNode() - self.secretChatsTitleNode = ImmediateTextNode() - self.secretChatsSwitchNode = SwitchNode() - self.incomingCallsTitleNode = ImmediateTextNode() - self.incomingCallsSwitchNode = SwitchNode() - - self.secretChatsActivateAreaNode = AccessibilityAreaNode() - self.incomingCallsActivateAreaNode = AccessibilityAreaNode() - - self.cancelButton = HighlightableButtonNode() - self.cancelButton.setImage(closeButtonImage(theme: self.presentationData.theme), for: .normal) - self.cancelButton.accessibilityLabel = presentationData.strings.Common_Close - self.cancelButton.accessibilityTraits = [.button] - - self.terminateButton = SolidRoundedButtonNode(theme: SolidRoundedButtonTheme(backgroundColor: self.presentationData.theme.list.itemBlocksBackgroundColor, foregroundColor: self.presentationData.theme.list.itemDestructiveColor), font: .regular, height: 44.0, cornerRadius: 11.0) - - var hasSecretChats = false - var hasIncomingCalls = false - - let timestamp = Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970) - let title: String - let subtitle: String - let subtitleActive: Bool - let device: String - let deviceTitle: String - let location: String - let ip: String - switch subject { + return { context in + let environment = context.environment[ViewControllerComponentContainer.Environment.self].value + let component = context.component + let theme = environment.theme + let strings = environment.strings + let presentationData = component.context.sharedContext.currentPresentationData.with { $0 } + let state = context.state + if state.controller == nil { + state.controller = environment.controller() as? RecentSessionScreen + } + + let sideInset: CGFloat = 16.0 + environment.safeInsets.left + + let closeButton = closeButton.update( + component: GlassBarButtonComponent( + size: CGSize(width: 44.0, height: 44.0), + backgroundColor: nil, + isDark: theme.overallDarkAppearance, + state: .glass, + component: AnyComponentWithIdentity(id: "close", component: AnyComponent( + BundleIconComponent( + name: "Navigation/Close", + tintColor: theme.chat.inputPanel.panelControlColor + ) + )), + action: { _ in + component.cancel(true) + } + ), + availableSize: CGSize(width: 44.0, height: 44.0), + transition: .immediate + ) + context.add(closeButton + .position(CGPoint(x: 16.0 + closeButton.size.width / 2.0, y: 16.0 + closeButton.size.height / 2.0)) + ) + + var contentHeight: CGFloat = 32.0 + switch component.subject { case let .session(session): - self.terminateButton.title = self.presentationData.strings.AuthSessions_View_TerminateSession - var appVersion = session.appVersion - appVersion = appVersion.replacingOccurrences(of: "APPSTORE", with: "").replacingOccurrences(of: "BETA", with: "Beta").trimmingTrailingSpaces() + let (image, backgroundColor, animationName, colorsArray) = iconForSession(session) - if session.isCurrent { - subtitle = presentationData.strings.Presence_online - subtitleActive = true - } else { - subtitle = stringForRelativeActivityTimestamp(strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, relativeTimestamp: session.activityDate, relativeTo: timestamp) - subtitleActive = false - } - deviceTitle = presentationData.strings.AuthSessions_View_Application - - var deviceString = "" - if !session.deviceModel.isEmpty { - deviceString = session.deviceModel - } - title = deviceString - device = "\(session.appName) \(appVersion)" - location = session.country - ip = session.ip - - let (icon, backgroundColor, animationName, colorsArray) = iconForSession(session) - if let animationName = animationName { + var items: [AnyComponentWithIdentity] = [] + items.append( + AnyComponentWithIdentity( + id: "background", + component: AnyComponent( + FilledRoundedRectangleComponent( + color: backgroundColor ?? .clear, + cornerRadius: .value(20.0), + smoothCorners: true + ) + ) + ) + ) + if let animationName { var colors: [String: UIColor] = [:] - if let colorsArray = colorsArray { + if let colorsArray { for color in colorsArray { colors[color] = backgroundColor } } - let animationNode = AnimationNode(animation: animationName, colors: colors, scale: 1.0) - self.animationNode = animationNode - - let animationBackgroundNode = ASDisplayNode() - animationBackgroundNode.cornerRadius = 20.0 - animationBackgroundNode.backgroundColor = backgroundColor - self.animationBackgroundNode = animationBackgroundNode - } else if let icon = icon { - let iconNode = ASImageNode() - iconNode.displaysAsynchronously = false - iconNode.image = icon - self.iconNode = iconNode + items.append( + AnyComponentWithIdentity( + id: "animation", + component: AnyComponent( + LottieAnimationComponent( + animation: .init(name: animationName, mode: .animating(loop: false)), + colors: colors, + size: CGSize(width: 92.0, height: 92.0) + ) + ) + ) + ) + } else if let image { + items.append( + AnyComponentWithIdentity( + id: "icon", + component: AnyComponent( + Image(image: image) + ) + ) + ) } - - self.secretChatsSwitchNode.isOn = session.flags.contains(.acceptsSecretChats) - self.incomingCallsSwitchNode.isOn = session.flags.contains(.acceptsIncomingCalls) - - self.secretChatsActivateAreaNode.accessibilityValue = self.secretChatsSwitchNode.isOn ? presentationData.strings.VoiceOver_Common_On : presentationData.strings.VoiceOver_Common_Off - self.incomingCallsActivateAreaNode.accessibilityValue = self.incomingCallsSwitchNode.isOn ? presentationData.strings.VoiceOver_Common_On : presentationData.strings.VoiceOver_Common_Off - - if !session.flags.contains(.passwordPending) && session.apiId != 22 { - hasIncomingCalls = true - if ![2040, 2496].contains(session.apiId) { - hasSecretChats = true - } + + let icon = icon.update( + component: ZStack(items), + availableSize: CGSize(width: 92.0, height: 92.0), + transition: .immediate + ) + context.add(icon + .position(CGPoint(x: context.availableSize.width / 2.0, y: contentHeight + icon.size.height / 2.0)) + ) + contentHeight += icon.size.height + contentHeight += 18.0 + case let .website(_, peer): + if let peer { + let avatar = avatar.update( + component: AvatarComponent( + context: component.context, + theme: environment.theme, + peer: peer + ), + availableSize: CGSize(width: 92.0, height: 92.0), + transition: .immediate + ) + context.add(avatar + .position(CGPoint(x: context.availableSize.width / 2.0, y: contentHeight + avatar.size.height / 2.0)) + ) + contentHeight += avatar.size.height + contentHeight += 18.0 } - case let .website(website, peer): - self.terminateButton.title = self.presentationData.strings.AuthSessions_View_Logout + } - if let peer = peer { - title = peer.displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder) + let titleString: String + let subtitleString: String + let subtitleActive: Bool + let applicationTitle: String + let applicationString: String + let ipString: String? + let locationString: String + let buttonString: String? + + switch component.subject { + case let .session(session): + titleString = session.deviceModel + if session.isCurrent { + subtitleString = strings.Presence_online + subtitleActive = true } else { - title = "" + let timestamp = Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970) + subtitleString = stringForRelativeActivityTimestamp(strings: strings, dateTimeFormat: presentationData.dateTimeFormat, relativeTimestamp: session.activityDate, relativeTo: timestamp) + subtitleActive = false } - - subtitle = website.domain + var appVersion = session.appVersion + appVersion = appVersion.replacingOccurrences(of: "APPSTORE", with: "").replacingOccurrences(of: "BETA", with: "Beta").trimmingTrailingSpaces() + applicationTitle = strings.AuthSessions_View_Application + applicationString = "\(session.appName) \(appVersion)" + ipString = session.ip // MARK: Swiftgram + locationString = session.country + + buttonString = !session.isCurrent ? strings.AuthSessions_View_TerminateSession : nil + case let .website(website, peer): + titleString = peer?.compactDisplayTitle ?? "" + subtitleString = website.domain subtitleActive = false - - deviceTitle = presentationData.strings.AuthSessions_View_Browser - + var deviceString = "" if !website.browser.isEmpty { deviceString += website.browser @@ -368,558 +280,433 @@ private class RecentSessionScreenNode: ViewControllerTracingNode, ASScrollViewDe } deviceString += website.platform } - device = deviceString - location = website.region - ip = website.ip - - let avatarNode = AvatarNode(font: avatarPlaceholderFont(size: 12.0)) - avatarNode.clipsToBounds = true - avatarNode.cornerRadius = 17.0 - if let peer { - avatarNode.setPeer(context: context, theme: presentationData.theme, peer: peer, authorOfMessage: nil, overrideImage: nil, emptyColor: nil, clipStyle: .none, synchronousLoad: false, displayDimensions: CGSize(width: 72.0, height: 72.0), storeUnrounded: false) - } - self.avatarNode = avatarNode - } - - self.titleNode.attributedText = NSAttributedString(string: title, font: Font.regular(30.0), textColor: textColor) - self.titleNode.accessibilityLabel = title - self.titleNode.isAccessibilityElement = true - - self.textNode.attributedText = NSAttributedString(string: subtitle, font: Font.regular(17.0), textColor: subtitleActive ? accentColor : secondaryTextColor) - self.textNode.accessibilityLabel = subtitle - self.textNode.isAccessibilityElement = true - - self.deviceTitleNode.attributedText = NSAttributedString(string: deviceTitle, font: Font.regular(17.0), textColor: textColor) - self.deviceValueNode.attributedText = NSAttributedString(string: device, font: Font.regular(17.0), textColor: secondaryTextColor) - self.deviceValueNode.accessibilityLabel = deviceTitle - self.deviceValueNode.accessibilityValue = device - self.deviceValueNode.isAccessibilityElement = true - - self.firstSeparatorNode = ASDisplayNode() - self.firstSeparatorNode.backgroundColor = self.presentationData.theme.list.itemBlocksSeparatorColor - - self.ipTitleNode.attributedText = NSAttributedString(string: self.presentationData.strings.AuthSessions_View_IP, font: Font.regular(17.0), textColor: textColor) - self.ipValueNode.attributedText = NSAttributedString(string: ip, font: Font.regular(17.0), textColor: secondaryTextColor) - self.ipValueNode.accessibilityLabel = self.presentationData.strings.AuthSessions_View_IP - self.ipValueNode.accessibilityValue = ip - self.ipValueNode.isAccessibilityElement = true - - self.secondSeparatorNode = ASDisplayNode() - self.secondSeparatorNode.backgroundColor = self.presentationData.theme.list.itemBlocksSeparatorColor - - self.locationTitleNode.attributedText = NSAttributedString(string: self.presentationData.strings.AuthSessions_View_Location, font: Font.regular(17.0), textColor: textColor) - - self.locationValueNode.attributedText = NSAttributedString(string: location, font: Font.regular(17.0), textColor: secondaryTextColor) - self.locationValueNode.accessibilityLabel = self.presentationData.strings.AuthSessions_View_Location - self.locationValueNode.accessibilityValue = location - self.locationValueNode.isAccessibilityElement = true + applicationTitle = strings.AuthSessions_View_Browser + applicationString = deviceString + ipString = website.ip + locationString = website.region + + buttonString = strings.AuthSessions_View_Logout + } - self.locationInfoNode.attributedText = NSAttributedString(string: self.presentationData.strings.AuthSessions_View_LocationInfo, font: Font.regular(13.0), textColor: secondaryTextColor) - self.locationInfoNode.maximumNumberOfLines = 4 - self.locationInfoNode.accessibilityLabel = self.presentationData.strings.AuthSessions_View_LocationInfo - self.locationInfoNode.isAccessibilityElement = true - - self.acceptBackgroundNode = ASDisplayNode() - self.acceptBackgroundNode.clipsToBounds = true - self.acceptBackgroundNode.cornerRadius = 11 - self.acceptBackgroundNode.backgroundColor = self.presentationData.theme.list.itemBlocksBackgroundColor - - self.acceptHeaderNode.attributedText = NSAttributedString(string: self.presentationData.strings.AuthSessions_View_AcceptTitle.uppercased(), font: Font.regular(17.0), textColor: textColor) - self.acceptHeaderNode.accessibilityLabel = self.presentationData.strings.AuthSessions_View_AcceptTitle - self.acceptHeaderNode.isAccessibilityElement = true - - self.secretChatsTitleNode.attributedText = NSAttributedString(string: self.presentationData.strings.AuthSessions_View_AcceptSecretChats, font: Font.regular(17.0), textColor: textColor) - self.incomingCallsTitleNode.attributedText = NSAttributedString(string: self.presentationData.strings.AuthSessions_View_AcceptIncomingCalls, font: Font.regular(17.0), textColor: textColor) - - self.secretChatsActivateAreaNode.accessibilityLabel = self.presentationData.strings.AuthSessions_View_AcceptSecretChats - self.secretChatsActivateAreaNode.accessibilityHint = self.presentationData.strings.VoiceOver_Common_SwitchHint - - self.incomingCallsActivateAreaNode.accessibilityLabel = self.presentationData.strings.AuthSessions_View_AcceptIncomingCalls - self.incomingCallsActivateAreaNode.accessibilityHint = self.presentationData.strings.VoiceOver_Common_SwitchHint - - self.acceptSeparatorNode = ASDisplayNode() - self.acceptSeparatorNode.backgroundColor = self.presentationData.theme.list.itemBlocksSeparatorColor - - super.init() - - self.backgroundColor = nil - self.isOpaque = false - - self.addSubnode(self.dimNode) - - self.wrappingScrollNode.view.delegate = self.wrappedScrollViewDelegate - self.addSubnode(self.wrappingScrollNode) - - self.wrappingScrollNode.addSubnode(self.backgroundNode) - self.wrappingScrollNode.addSubnode(self.contentContainerNode) - self.wrappingScrollNode.addSubnode(self.topContentContainerNode) - - self.backgroundNode.addSubnode(self.contentBackgroundNode) - self.contentContainerNode.addSubnode(self.titleNode) - self.contentContainerNode.addSubnode(self.textNode) - - self.contentContainerNode.addSubnode(self.fieldBackgroundNode) - - self.contentContainerNode.addSubnode(self.deviceTitleNode) - self.contentContainerNode.addSubnode(self.deviceValueNode) - - self.contentContainerNode.addSubnode(self.ipTitleNode) - self.contentContainerNode.addSubnode(self.ipValueNode) - - self.contentContainerNode.addSubnode(self.locationTitleNode) - self.contentContainerNode.addSubnode(self.locationValueNode) - self.contentContainerNode.addSubnode(self.locationInfoNode) - - self.contentContainerNode.addSubnode(self.firstSeparatorNode) - self.contentContainerNode.addSubnode(self.secondSeparatorNode) - - self.contentContainerNode.addSubnode(self.terminateButton) - self.topContentContainerNode.addSubnode(self.cancelButton) - - self.iconNode.flatMap { self.contentContainerNode.addSubnode($0) } - self.animationBackgroundNode.flatMap { self.contentContainerNode.addSubnode($0) } - self.animationNode.flatMap { self.contentContainerNode.addSubnode($0) } - self.avatarNode.flatMap { self.contentContainerNode.addSubnode($0) } - - if hasIncomingCalls { - self.contentContainerNode.addSubnode(self.acceptBackgroundNode) - self.contentContainerNode.addSubnode(self.acceptHeaderNode) - if hasSecretChats { - self.contentContainerNode.addSubnode(self.secretChatsTitleNode) - self.contentContainerNode.addSubnode(self.secretChatsSwitchNode) - self.contentContainerNode.addSubnode(self.secretChatsActivateAreaNode) - - self.secretChatsSwitchNode.valueUpdated = { [weak self] value in - if let strongSelf = self { - strongSelf.updateAcceptSecretChats?(value) - - strongSelf.secretChatsActivateAreaNode.accessibilityValue = value ? presentationData.strings.VoiceOver_Common_On : presentationData.strings.VoiceOver_Common_Off - } - } - - self.secretChatsActivateAreaNode.activate = { [weak self] in - guard let strongSelf = self else { - return false - } - let value = !strongSelf.secretChatsSwitchNode.isOn - strongSelf.updateAcceptSecretChats?(value) - strongSelf.secretChatsActivateAreaNode.accessibilityValue = value ? presentationData.strings.VoiceOver_Common_On : presentationData.strings.VoiceOver_Common_Off - return true - } - - self.contentContainerNode.addSubnode(self.acceptSeparatorNode) + // MARK: Swiftgram + let sgApiIdString: String? + if case let .session(session) = component.subject { + sgApiIdString = SGRecentSessionApiId.string(for: session) + } else { + sgApiIdString = nil } - self.contentContainerNode.addSubnode(self.incomingCallsTitleNode) - self.contentContainerNode.addSubnode(self.incomingCallsSwitchNode) - self.contentContainerNode.addSubnode(self.incomingCallsActivateAreaNode) + // - self.incomingCallsSwitchNode.valueUpdated = { [weak self] value in - if let strongSelf = self { - strongSelf.updateAcceptIncomingCalls?(value) - - strongSelf.incomingCallsActivateAreaNode.accessibilityValue = value ? presentationData.strings.VoiceOver_Common_On : presentationData.strings.VoiceOver_Common_Off - } - } + let titleFont = Font.bold(24.0) + let title = title.update( + component: BalancedTextComponent( + text: .markdown(text: titleString, attributes: MarkdownAttributes(body: MarkdownAttributeSet(font: titleFont, textColor: theme.actionSheet.primaryTextColor), bold: MarkdownAttributeSet(font: titleFont, textColor: theme.actionSheet.controlAccentColor), link: MarkdownAttributeSet(font: titleFont, textColor: theme.actionSheet.primaryTextColor), linkAttribute: { _ in return nil })), + horizontalAlignment: .center, + maximumNumberOfLines: 2 + ), + availableSize: CGSize(width: context.availableSize.width - sideInset * 2.0 - 60.0, height: CGFloat.greatestFiniteMagnitude), + transition: .immediate + ) + context.add(title + .position(CGPoint(x: context.availableSize.width / 2.0, y: contentHeight + title.size.height / 2.0)) + ) + contentHeight += title.size.height + contentHeight += 2.0 - self.incomingCallsActivateAreaNode.activate = { [weak self] in - guard let strongSelf = self else { - return false - } - let value = !strongSelf.incomingCallsSwitchNode.isOn - strongSelf.updateAcceptIncomingCalls?(value) - strongSelf.incomingCallsActivateAreaNode.accessibilityValue = value ? presentationData.strings.VoiceOver_Common_On : presentationData.strings.VoiceOver_Common_Off - return true - } - } - - self.cancelButton.addTarget(self, action: #selector(self.cancelButtonPressed), forControlEvents: .touchUpInside) - self.terminateButton.pressed = { [weak self] in - if let strongSelf = self { - strongSelf.remove?() - } - } - } - - override func didLoad() { - super.didLoad() - - if #available(iOSApplicationExtension 11.0, iOS 11.0, *) { - self.wrappingScrollNode.view.contentInsetAdjustmentBehavior = .never - } - - self.dimNode.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dimTapGesture))) - - let titleGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.handleTitleLongPress(_:))) - self.titleNode.view.addGestureRecognizer(titleGestureRecognizer) - - let deviceGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.handleDeviceLongPress(_:))) - self.deviceValueNode.view.addGestureRecognizer(deviceGestureRecognizer) - - let locationGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLocationLongPress(_:))) - self.locationValueNode.view.addGestureRecognizer(locationGestureRecognizer) - - let ipGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.handleIpLongPress(_:))) - self.ipValueNode.view.addGestureRecognizer(ipGestureRecognizer) - - if let animationNode = self.animationNode { - animationNode.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.animationPressed))) - } - } - - @objc private func handleTitleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) { - if gestureRecognizer.state == .began { - self.displayCopyContextMenu(self.titleNode, self.titleNode.attributedText?.string ?? "") - } - } - - @objc private func handleDeviceLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) { - if gestureRecognizer.state == .began { - self.displayCopyContextMenu(self.deviceValueNode, self.deviceValueNode.attributedText?.string ?? "") - } - } - - @objc private func handleLocationLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) { - if gestureRecognizer.state == .began { - self.displayCopyContextMenu(self.locationValueNode, self.locationValueNode.attributedText?.string ?? "") - } - } - - @objc private func handleIpLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) { - if gestureRecognizer.state == .began { - self.displayCopyContextMenu(self.ipValueNode, self.ipValueNode.attributedText?.string ?? "") - } - } - - private func displayCopyContextMenu(_ node: ASDisplayNode, _ string: String) { - if !string.isEmpty { - var actions: [ContextMenuAction] = [] - actions.append(ContextMenuAction(content: .text(title: self.presentationData.strings.Conversation_ContextMenuCopy, accessibilityLabel: self.presentationData.strings.Conversation_ContextMenuCopy), action: { [weak self] in - UIPasteboard.general.string = string - - if let strongSelf = self { - let presentationData = strongSelf.context.sharedContext.currentPresentationData.with { $0 } - strongSelf.controller?.present(UndoOverlayController(presentationData: presentationData, content: .copy(text: presentationData.strings.Conversation_TextCopied), elevatedLayout: false, animateInAsReplacement: false, action: { _ in return false }), in: .window(.root)) - } - })) - let contextMenuController = makeContextMenuController(actions: actions) - self.controller?.present(contextMenuController, in: .window(.root), with: ContextMenuControllerPresentationArguments(sourceNodeAndRect: { [weak self] in - if let strongSelf = self { - return (node, node.bounds.insetBy(dx: 0.0, dy: -2.0), strongSelf, strongSelf.view.bounds) - } else { - return nil - } - })) - } - } - - func updatePresentationData(_ presentationData: PresentationData) { - guard !self.animatedOut else { - return - } - let previousTheme = self.presentationData.theme - self.presentationData = presentationData - - self.contentBackgroundNode.backgroundColor = self.presentationData.theme.list.blocksBackgroundColor - - self.titleNode.attributedText = NSAttributedString(string: self.titleNode.attributedText?.string ?? "", font: Font.regular(30.0), textColor: self.presentationData.theme.list.itemPrimaryTextColor) - - let subtitleColor: UIColor - if case let .session(session) = self.subject, session.isCurrent { - subtitleColor = self.presentationData.theme.list.itemAccentColor - } else { - subtitleColor = self.presentationData.theme.list.itemSecondaryTextColor - } - self.textNode.attributedText = NSAttributedString(string: self.textNode.attributedText?.string ?? "", font: Font.regular(17.0), textColor: subtitleColor) - - self.fieldBackgroundNode.backgroundColor = self.presentationData.theme.list.itemBlocksBackgroundColor - self.firstSeparatorNode.backgroundColor = self.presentationData.theme.list.itemBlocksSeparatorColor - self.secondSeparatorNode.backgroundColor = self.presentationData.theme.list.itemBlocksSeparatorColor - self.acceptSeparatorNode.backgroundColor = self.presentationData.theme.list.itemBlocksSeparatorColor - - self.deviceTitleNode.attributedText = NSAttributedString(string: self.deviceTitleNode.attributedText?.string ?? "", font: Font.regular(17.0), textColor: self.presentationData.theme.list.itemPrimaryTextColor) - self.locationTitleNode.attributedText = NSAttributedString(string: self.locationTitleNode.attributedText?.string ?? "", font: Font.regular(17.0), textColor: self.presentationData.theme.list.itemPrimaryTextColor) - self.ipTitleNode.attributedText = NSAttributedString(string: self.ipTitleNode.attributedText?.string ?? "", font: Font.regular(17.0), textColor: self.presentationData.theme.list.itemPrimaryTextColor) - - self.deviceValueNode.attributedText = NSAttributedString(string: self.deviceValueNode.attributedText?.string ?? "", font: Font.regular(17.0), textColor: self.presentationData.theme.list.itemSecondaryTextColor) - self.locationValueNode.attributedText = NSAttributedString(string: self.locationValueNode.attributedText?.string ?? "", font: Font.regular(17.0), textColor: self.presentationData.theme.list.itemSecondaryTextColor) - self.ipValueNode.attributedText = NSAttributedString(string: self.ipValueNode.attributedText?.string ?? "", font: Font.regular(17.0), textColor: self.presentationData.theme.list.itemSecondaryTextColor) - self.locationInfoNode.attributedText = NSAttributedString(string: self.locationInfoNode.attributedText?.string ?? "", font: Font.regular(13.0), textColor: self.presentationData.theme.list.itemSecondaryTextColor) - - self.acceptHeaderNode.attributedText = NSAttributedString(string: self.acceptHeaderNode.attributedText?.string ?? "", font: Font.regular(13.0), textColor: self.presentationData.theme.list.itemSecondaryTextColor) - self.secretChatsTitleNode.attributedText = NSAttributedString(string: self.secretChatsTitleNode.attributedText?.string ?? "", font: Font.regular(17.0), textColor: self.presentationData.theme.list.itemPrimaryTextColor) - self.incomingCallsTitleNode.attributedText = NSAttributedString(string: self.incomingCallsTitleNode.attributedText?.string ?? "", font: Font.regular(17.0), textColor: self.presentationData.theme.list.itemPrimaryTextColor) - self.acceptBackgroundNode.backgroundColor = self.presentationData.theme.list.itemBlocksBackgroundColor - - if previousTheme !== presentationData.theme, let (layout, navigationBarHeight) = self.containerLayout { - self.containerLayoutUpdated(layout, navigationBarHeight: navigationBarHeight, transition: .immediate) - } - - self.cancelButton.setImage(closeButtonImage(theme: self.presentationData.theme), for: .normal) - self.terminateButton.updateTheme(SolidRoundedButtonTheme(backgroundColor: self.presentationData.theme.list.itemBlocksBackgroundColor, foregroundColor: self.presentationData.theme.list.itemDestructiveColor)) - } - - @objc func animationPressed() { - if let animationNode = self.animationNode, !animationNode.isPlaying { - animationNode.playOnce() - } - } - - @objc func cancelButtonPressed() { - self.animateOut() - } - - @objc func dimTapGesture() { - self.cancelButtonPressed() - } - - private var animatedOut = false - func animateIn() { - self.dimNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.4) - - let offset = self.bounds.size.height - self.contentBackgroundNode.frame.minY - let dimPosition = self.dimNode.layer.position - - let transition = ContainedViewLayoutTransition.animated(duration: 0.4, curve: .spring) - let targetBounds = self.bounds - self.bounds = self.bounds.offsetBy(dx: 0.0, dy: -offset) - self.dimNode.position = CGPoint(x: dimPosition.x, y: dimPosition.y - offset) - transition.animateView({ - self.bounds = targetBounds - self.dimNode.position = dimPosition - }) - } - - func animateOut(completion: (() -> Void)? = nil) { - self.animatedOut = true - - var dimCompleted = false - var offsetCompleted = false - - let internalCompletion: () -> Void = { [weak self] in - if let strongSelf = self, dimCompleted && offsetCompleted { - strongSelf.dismiss?() - } - completion?() - } - - self.dimNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.3, removeOnCompletion: false, completion: { _ in - dimCompleted = true - internalCompletion() - }) - - let offset = self.bounds.size.height - self.contentBackgroundNode.frame.minY - self.wrappingScrollNode.layer.animateBoundsOriginYAdditive(from: 0.0, to: -offset, duration: 0.3, timingFunction: CAMediaTimingFunctionName.easeInEaseOut.rawValue, removeOnCompletion: false, completion: { _ in - offsetCompleted = true - internalCompletion() - }) - - - self.controller?.window?.forEachController { c in - if let c = c as? UndoOverlayController { - c.dismiss() - } - } - } - - var passthroughHitTestImpl: ((CGPoint) -> UIView?)? - override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { - if self.bounds.contains(point) { - if !self.contentBackgroundNode.bounds.contains(self.convert(point, to: self.contentBackgroundNode)) { - return self.dimNode.view - } - } - return super.hitTest(point, with: event) - } - - func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { - let contentOffset = scrollView.contentOffset - let additionalTopHeight = max(0.0, -contentOffset.y) - - if additionalTopHeight >= 30.0 { - self.cancelButtonPressed() - } - } - - func containerLayoutUpdated(_ layout: ContainerViewLayout, navigationBarHeight: CGFloat, transition: ContainedViewLayoutTransition) { - let isFirstTime = self.containerLayout == nil - self.containerLayout = (layout, navigationBarHeight) - - var insets = layout.insets(options: [.statusBar, .input]) - let cleanInsets = layout.insets(options: [.statusBar]) - insets.top = max(10.0, insets.top) - - let bottomInset: CGFloat = 10.0 + cleanInsets.bottom - - let width = horizontalContainerFillingSizeForLayout(layout: layout, sideInset: 0.0) - - transition.updateFrame(node: self.wrappingScrollNode, frame: CGRect(origin: CGPoint(), size: layout.size)) - transition.updateFrame(node: self.dimNode, frame: CGRect(origin: CGPoint(), size: layout.size)) - - let iconSize = CGSize(width: 72.0, height: 72.0) - let iconFrame = CGRect(origin: CGPoint(x: floorToScreenPixels((width - iconSize.width) / 2.0), y: 36.0), size: iconSize) - - if let iconNode = self.iconNode { - transition.updateFrame(node: iconNode, frame: iconFrame) - } else if let animationNode = self.animationNode, let animationBackgroundNode = self.animationBackgroundNode { - transition.updateFrame(node: animationNode, frame: iconFrame) - transition.updateFrame(node: animationBackgroundNode, frame: iconFrame) - if #available(iOS 13.0, *) { - animationBackgroundNode.layer.cornerCurve = .continuous - } - if isFirstTime { - Queue.mainQueue().after(0.5) { - animationNode.playOnce() - } - } - } else if let avatarNode = self.avatarNode { - transition.updateFrame(node: avatarNode, frame: iconFrame) - } - - let inset: CGFloat = 16.0 - let titleSize = self.titleNode.updateLayout(CGSize(width: width - inset * 2.0, height: 100.0)) - let titleFrame = CGRect(origin: CGPoint(x: floorToScreenPixels((width - titleSize.width) / 2.0), y: 120.0), size: titleSize) - transition.updateFrame(node: self.titleNode, frame: titleFrame) - - let textSize = self.textNode.updateLayout(CGSize(width: width - inset * 2.0, height: 60.0)) - let textFrame = CGRect(origin: CGPoint(x: floorToScreenPixels((width - textSize.width) / 2.0), y: titleFrame.maxY), size: textSize) - transition.updateFrame(node: self.textNode, frame: textFrame) - - let cancelSize = CGSize(width: 44.0, height: 44.0) - let cancelFrame = CGRect(origin: CGPoint(x: width - cancelSize.width - 3.0, y: 6.0), size: cancelSize) - transition.updateFrame(node: self.cancelButton, frame: cancelFrame) - - let fieldItemHeight: CGFloat = 44.0 - var fieldFrame = CGRect(x: inset, y: textFrame.maxY + 24.0, width: width - inset * 2.0, height: fieldItemHeight * 2.0) - if !(self.ipValueNode.attributedText?.string ?? "").isEmpty { - fieldFrame.size.height += fieldItemHeight + let textFont = Font.regular(15.0) + let description = description.update( + component: MultilineTextComponent( + text: .plain(NSAttributedString(string: subtitleString, font: textFont, textColor: subtitleActive ? theme.actionSheet.controlAccentColor : theme.actionSheet.secondaryTextColor)), + horizontalAlignment: .center, + maximumNumberOfLines: 3, + lineSpacing: 0.2 + ), + availableSize: CGSize(width: context.availableSize.width - sideInset * 2.0 - 60.0, height: CGFloat.greatestFiniteMagnitude), + transition: .immediate + ) + context.add(description + .position(CGPoint(x: context.availableSize.width / 2.0, y: contentHeight + description.size.height / 2.0)) + ) + contentHeight += description.size.height + contentHeight += 22.0 - self.ipTitleNode.isHidden = false - self.ipValueNode.isHidden = false - self.secondSeparatorNode.isHidden = false - } else { - self.ipTitleNode.isHidden = true - self.ipValueNode.isHidden = true - self.secondSeparatorNode.isHidden = true - } - transition.updateFrame(node: self.fieldBackgroundNode, frame: fieldFrame) - - let maxFieldTitleWidth = (width - inset * 4.0) * 0.4 - - let deviceTitleTextSize = self.deviceTitleNode.updateLayout(CGSize(width: maxFieldTitleWidth, height: fieldItemHeight)) - let deviceTitleTextFrame = CGRect(origin: CGPoint(x: fieldFrame.minX + inset, y: fieldFrame.minY + floorToScreenPixels((fieldItemHeight - deviceTitleTextSize.height) / 2.0)), size: deviceTitleTextSize) - transition.updateFrame(node: self.deviceTitleNode, frame: deviceTitleTextFrame) - - let deviceValueTextSize = self.deviceValueNode.updateLayout(CGSize(width: fieldFrame.width - inset * 2.0 - deviceTitleTextSize.width - 10.0, height: fieldItemHeight)) - let deviceValueTextFrame = CGRect(origin: CGPoint(x: fieldFrame.maxX - deviceValueTextSize.width - inset, y: fieldFrame.minY + floorToScreenPixels((fieldItemHeight - deviceValueTextSize.height) / 2.0)), size: deviceValueTextSize) - transition.updateFrame(node: self.deviceValueNode, frame: deviceValueTextFrame) - - transition.updateFrame(node: self.firstSeparatorNode, frame: CGRect(x: fieldFrame.minX + inset, y: fieldFrame.minY + fieldItemHeight, width: fieldFrame.width - inset, height: UIScreenPixel)) - - let ipTitleTextSize = self.ipTitleNode.updateLayout(CGSize(width: maxFieldTitleWidth, height: fieldItemHeight)) - let ipTitleTextFrame = CGRect(origin: CGPoint(x: fieldFrame.minX + inset, y: fieldFrame.minY + fieldItemHeight + floorToScreenPixels((fieldItemHeight - ipTitleTextSize.height) / 2.0)), size: ipTitleTextSize) - transition.updateFrame(node: self.ipTitleNode, frame: ipTitleTextFrame) - - let ipValueTextSize = self.ipValueNode.updateLayout(CGSize(width: fieldFrame.width - inset * 2.0 - ipTitleTextSize.width - 10.0, height: fieldItemHeight)) - let ipValueTextFrame = CGRect(origin: CGPoint(x: fieldFrame.maxX - ipValueTextSize.width - inset, y: fieldFrame.minY + fieldItemHeight + floorToScreenPixels((fieldItemHeight - ipValueTextSize.height) / 2.0)), size: ipValueTextSize) - transition.updateFrame(node: self.ipValueNode, frame: ipValueTextFrame) - - transition.updateFrame(node: self.secondSeparatorNode, frame: CGRect(x: fieldFrame.minX + inset, y: fieldFrame.minY + fieldItemHeight + fieldItemHeight, width: fieldFrame.width - inset, height: UIScreenPixel)) - - let locationTitleTextSize = self.locationTitleNode.updateLayout(CGSize(width: maxFieldTitleWidth, height: fieldItemHeight)) - let locationTitleTextFrame = CGRect(origin: CGPoint(x: fieldFrame.minX + inset, y: fieldFrame.maxY - fieldItemHeight + floorToScreenPixels((fieldItemHeight - locationTitleTextSize.height) / 2.0)), size: locationTitleTextSize) - transition.updateFrame(node: self.locationTitleNode, frame: locationTitleTextFrame) - - let locationValueTextSize = self.locationValueNode.updateLayout(CGSize(width: fieldFrame.width - inset * 2.0 - locationTitleTextSize.width - 10.0, height: fieldItemHeight)) - let locationValueTextFrame = CGRect(origin: CGPoint(x: fieldFrame.maxX - locationValueTextSize.width - inset, y: fieldFrame.maxY - fieldItemHeight + floorToScreenPixels((fieldItemHeight - locationValueTextSize.height) / 2.0)), size: locationValueTextSize) - transition.updateFrame(node: self.locationValueNode, frame: locationValueTextFrame) - - let locationInfoTextSize = self.locationInfoNode.updateLayout(CGSize(width: fieldFrame.width - inset * 2.0, height: fieldItemHeight * 2.0)) - let locationInfoTextFrame = CGRect(origin: CGPoint(x: fieldFrame.minX + inset, y: fieldFrame.maxY + 6.0), size: locationInfoTextSize) - transition.updateFrame(node: self.locationInfoNode, frame: locationInfoTextFrame) - - var contentHeight = locationInfoTextFrame.maxY + bottomInset + 64.0 - - var secretFrame = CGRect(x: inset, y: locationInfoTextFrame.maxY + 59.0, width: width - inset * 2.0, height: fieldItemHeight) - if let _ = self.secretChatsTitleNode.supernode { - secretFrame.size.height += fieldItemHeight - } - transition.updateFrame(node: self.acceptBackgroundNode, frame: secretFrame) - - let secretChatsHeaderTextSize = self.acceptHeaderNode.updateLayout(CGSize(width: secretFrame.width - inset * 2.0, height: fieldItemHeight)) - let secretChatsHeaderTextFrame = CGRect(origin: CGPoint(x: secretFrame.minX + inset, y: secretFrame.minY - secretChatsHeaderTextSize.height - 6.0), size: secretChatsHeaderTextSize) - transition.updateFrame(node: self.acceptHeaderNode, frame: secretChatsHeaderTextFrame) - - if let _ = self.secretChatsTitleNode.supernode { - let secretChatsTitleTextSize = self.secretChatsTitleNode.updateLayout(CGSize(width: width - inset * 4.0 - 80.0, height: fieldItemHeight)) - let secretChatsTitleTextFrame = CGRect(origin: CGPoint(x: secretFrame.minX + inset, y: secretFrame.minY + floorToScreenPixels((fieldItemHeight - secretChatsTitleTextSize.height) / 2.0)), size: secretChatsTitleTextSize) - transition.updateFrame(node: self.secretChatsTitleNode, frame: secretChatsTitleTextFrame) + var clientSectionItems: [AnyComponentWithIdentity] = [] + clientSectionItems.append( + AnyComponentWithIdentity(id: "application", component: AnyComponent( + ListActionItemComponent( + theme: theme, + style: .glass, + title: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: applicationTitle, + font: Font.regular(17.0), + textColor: theme.list.itemPrimaryTextColor + )), + maximumNumberOfLines: 1 + )), + accessory: .custom(ListActionItemComponent.CustomAccessory( + component: AnyComponentWithIdentity( + id: "info", + component: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: applicationString, + font: Font.regular(presentationData.listsFontSize.itemListBaseFontSize), + textColor: theme.list.itemSecondaryTextColor + )), + maximumNumberOfLines: 1 + )) + ), + insets: UIEdgeInsets(top: 0.0, left: 8.0, bottom: 0.0, right: 14.0), + isInteractive: true + )), + action: nil + ) + )) + ) - if let switchView = self.secretChatsSwitchNode.view as? UISwitch { - if self.secretChatsSwitchNode.bounds.size.width.isZero { - switchView.sizeToFit() - } - let switchSize = switchView.bounds.size - - self.secretChatsSwitchNode.frame = CGRect(origin: CGPoint(x: fieldFrame.maxX - switchSize.width - inset, y: secretFrame.minY + floorToScreenPixels((fieldItemHeight - switchSize.height) / 2.0)), size: switchSize) - self.secretChatsActivateAreaNode.frame = CGRect(origin: CGPoint(x: secretFrame.minX, y: secretFrame.minY), size: CGSize(width: fieldFrame.width, height: fieldItemHeight)) + // MARK: Swiftgram + if let sgApiIdString { + clientSectionItems.append(sgRecentSessionApiIdItem(apiIdString: sgApiIdString, theme: theme, presentationData: presentationData, strings: strings, controller: state.controller)) } - } - - let incomingCallsTitleTextSize = self.incomingCallsTitleNode.updateLayout(CGSize(width: width - inset * 4.0 - 80.0, height: fieldItemHeight)) - let incomingCallsTitleTextFrame = CGRect(origin: CGPoint(x: secretFrame.minX + inset, y: secretFrame.maxY - fieldItemHeight + floorToScreenPixels((fieldItemHeight - incomingCallsTitleTextSize.height) / 2.0)), size: incomingCallsTitleTextSize) - transition.updateFrame(node: self.incomingCallsTitleNode, frame: incomingCallsTitleTextFrame) - - transition.updateFrame(node: self.acceptSeparatorNode, frame: CGRect(x: secretFrame.minX + inset, y: secretFrame.minY + fieldItemHeight, width: fieldFrame.width - inset, height: UIScreenPixel)) - - if let switchView = self.incomingCallsSwitchNode.view as? UISwitch { - if self.incomingCallsSwitchNode.bounds.size.width.isZero { - switchView.sizeToFit() - } - let switchSize = switchView.bounds.size + // - self.incomingCallsSwitchNode.frame = CGRect(origin: CGPoint(x: fieldFrame.maxX - switchSize.width - inset, y: secretFrame.maxY - fieldItemHeight + floorToScreenPixels((fieldItemHeight - switchSize.height) / 2.0)), size: switchSize) - self.incomingCallsActivateAreaNode.frame = CGRect(origin: CGPoint(x: secretFrame.minX, y: secretFrame.maxY - fieldItemHeight), size: CGSize(width: fieldFrame.width, height: fieldItemHeight)) + if let ipString { + clientSectionItems.append( + AnyComponentWithIdentity(id: "ip", component: AnyComponent( + ListActionItemComponent( + theme: theme, + style: .glass, + title: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: strings.AuthSessions_View_IP, + font: Font.regular(17.0), + textColor: theme.list.itemPrimaryTextColor + )), + maximumNumberOfLines: 1 + )), + accessory: .custom(ListActionItemComponent.CustomAccessory( + component: AnyComponentWithIdentity( + id: "info", + component: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: ipString, + font: Font.regular(presentationData.listsFontSize.itemListBaseFontSize), + textColor: theme.list.itemSecondaryTextColor + )), + maximumNumberOfLines: 1 + )) + ), + insets: UIEdgeInsets(top: 0.0, left: 8.0, bottom: 0.0, right: 14.0), + isInteractive: true + )), + action: nil + ) + )) + ) + } + + clientSectionItems.append( + AnyComponentWithIdentity(id: "region", component: AnyComponent( + ListActionItemComponent( + theme: theme, + style: .glass, + title: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: strings.AuthSessions_View_Location, + font: Font.regular(17.0), + textColor: theme.list.itemPrimaryTextColor + )), + maximumNumberOfLines: 1 + )), + accessory: .custom(ListActionItemComponent.CustomAccessory( + component: AnyComponentWithIdentity( + id: "info", + component: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: locationString, + font: Font.regular(presentationData.listsFontSize.itemListBaseFontSize), + textColor: theme.list.itemSecondaryTextColor + )), + maximumNumberOfLines: 1 + )) + ), + insets: UIEdgeInsets(top: 0.0, left: 8.0, bottom: 0.0, right: 14.0), + isInteractive: true + )), + action: nil + ) + )) + ) + + let clientSection = clientSection.update( + component: ListSectionComponent( + theme: theme, + style: .glass, + header: nil, + footer: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: strings.AuthSessions_View_LocationInfo, + font: Font.regular(presentationData.listsFontSize.itemListBaseHeaderFontSize), + textColor: environment.theme.list.freeTextColor + )), + maximumNumberOfLines: 0 + )), + items: clientSectionItems + ), + availableSize: CGSize(width: context.availableSize.width - sideInset * 2.0, height: context.availableSize.height), + transition: context.transition + ) + context.add(clientSection + .position(CGPoint(x: context.availableSize.width / 2.0, y: contentHeight + clientSection.size.height / 2.0)) + ) + contentHeight += clientSection.size.height + + if state.allowSecretChats != nil || state.allowIncomingCalls != nil { + contentHeight += 38.0 + + var optionsSectionItems: [AnyComponentWithIdentity] = [] + + if let allowSecretChats = state.allowSecretChats { + optionsSectionItems.append(AnyComponentWithIdentity(id: "allowSecretChats", component: AnyComponent(ListActionItemComponent( + theme: theme, + style: .glass, + title: AnyComponent(VStack([ + AnyComponentWithIdentity(id: AnyHashable(0), component: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: strings.AuthSessions_View_AcceptSecretChats, + font: Font.regular(presentationData.listsFontSize.itemListBaseFontSize), + textColor: theme.list.itemPrimaryTextColor + )), + maximumNumberOfLines: 1 + ))), + ], alignment: .left, spacing: 2.0)), + accessory: .toggle(ListActionItemComponent.Toggle(style: .regular, isOn: allowSecretChats, action: { [weak state] _ in + guard let state else { + return + } + state.toggleAllowSecretChats() + })), + action: nil + )))) + } + if let allowIncomingCalls = state.allowIncomingCalls { + optionsSectionItems.append(AnyComponentWithIdentity(id: "allowIncomingCalls", component: AnyComponent(ListActionItemComponent( + theme: theme, + style: .glass, + title: AnyComponent(VStack([ + AnyComponentWithIdentity(id: AnyHashable(0), component: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: strings.AuthSessions_View_AcceptIncomingCalls, + font: Font.regular(presentationData.listsFontSize.itemListBaseFontSize), + textColor: theme.list.itemPrimaryTextColor + )), + maximumNumberOfLines: 1 + ))), + ], alignment: .left, spacing: 2.0)), + accessory: .toggle(ListActionItemComponent.Toggle(style: .regular, isOn: allowIncomingCalls, action: { [weak state] _ in + guard let state else { + return + } + state.toggleAllowIncomingCalls() + })), + action: nil + )))) + } + let optionsSection = optionsSection.update( + component: ListSectionComponent( + theme: theme, + style: .glass, + header: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: environment.strings.AuthSessions_View_AcceptTitle.uppercased(), + font: Font.regular(presentationData.listsFontSize.itemListBaseHeaderFontSize), + textColor: theme.list.freeTextColor + )), + maximumNumberOfLines: 0 + )), + footer: nil, + items: optionsSectionItems + ), + availableSize: CGSize(width: context.availableSize.width - sideInset * 2.0, height: context.availableSize.height), + transition: context.transition + ) + context.add(optionsSection + .position(CGPoint(x: context.availableSize.width / 2.0, y: contentHeight + optionsSection.size.height / 2.0)) + ) + contentHeight += optionsSection.size.height + } + contentHeight += 32.0 + + if let buttonString { + let buttonInsets = ContainerViewLayout.concentricInsets(bottomInset: environment.safeInsets.bottom, innerDiameter: 52.0, sideInset: 30.0) + let button = button.update( + component: ButtonComponent( + background: ButtonComponent.Background( + style: .glass, + color: theme.list.itemDestructiveColor, + foreground: .white, + pressedColor: theme.list.itemCheckColors.fillColor.withMultipliedAlpha(0.9) + ), + content: AnyComponentWithIdentity( + id: AnyHashable(0), + component: AnyComponent(MultilineTextComponent(text: .plain(NSMutableAttributedString(string: buttonString, font: Font.semibold(17.0), textColor: theme.list.itemCheckColors.foregroundColor, paragraphAlignment: .center)))) + ), + action: { [weak state] in + state?.terminate() + } + ), + availableSize: CGSize(width: context.availableSize.width - buttonInsets.left - buttonInsets.right, height: 52.0), + transition: .immediate + ) + context.add(button + .position(CGPoint(x: context.availableSize.width / 2.0 , y: contentHeight + button.size.height / 2.0)) + ) + contentHeight += button.size.height + contentHeight += buttonInsets.bottom + } + + return CGSize(width: context.availableSize.width, height: contentHeight) + } + } +} + +private final class RecentSessionSheetComponent: CombinedComponent { + typealias EnvironmentType = ViewControllerComponentContainer.Environment + + let context: AccountContext + let subject: RecentSessionScreen.Subject + + init( + context: AccountContext, + subject: RecentSessionScreen.Subject + ) { + self.context = context + self.subject = subject + } + + static func ==(lhs: RecentSessionSheetComponent, rhs: RecentSessionSheetComponent) -> Bool { + if lhs.context !== rhs.context { + return false + } + return true + } + + static var body: Body { + let sheet = Child(SheetComponent.self) + let animateOut = StoredActionSlot(Action.self) + + return { context in + let environment = context.environment[EnvironmentType.self] + let controller = environment.controller + + let sheet = sheet.update( + component: SheetComponent( + content: AnyComponent(RecentSessionSheetContent( + context: context.component.context, + subject: context.component.subject, + cancel: { animate in + if animate { + animateOut.invoke(Action { _ in + if let controller = controller() { + controller.dismiss(completion: nil) + } + }) + } else if let controller = controller() { + controller.dismiss(animated: false, completion: nil) + } + } + )), + style: .glass, + backgroundColor: .color(environment.theme.list.modalBlocksBackgroundColor), + followContentSizeChanges: true, + clipsContent: true, + animateOut: animateOut + ), + environment: { + environment + SheetComponentEnvironment( + isDisplaying: environment.value.isVisible, + isCentered: environment.metrics.widthClass == .regular, + hasInputHeight: !environment.inputHeight.isZero, + regularMetricsSize: CGSize(width: 430.0, height: 900.0), + dismiss: { animated in + if animated { + animateOut.invoke(Action { _ in + if let controller = controller() { + controller.dismiss(completion: nil) + } + }) + } else { + if let controller = controller() { + controller.dismiss(completion: nil) + } + } + } + ) + }, + availableSize: context.availableSize, + transition: context.transition + ) + + context.add(sheet + .position(CGPoint(x: context.availableSize.width / 2.0, y: context.availableSize.height / 2.0)) + ) + + return context.availableSize + } + } +} + +public class RecentSessionScreen: ViewControllerComponentContainer { + public enum Subject { + case session(RecentAccountSession) + case website(WebAuthorization, EnginePeer?) + } + + private let context: AccountContext + fileprivate let updateAcceptSecretChats: (Bool) -> Void + fileprivate let updateAcceptIncomingCalls: (Bool) -> Void + fileprivate let remove: (@escaping () -> Void) -> Void + + public init( + context: AccountContext, + subject: RecentSessionScreen.Subject, + updateAcceptSecretChats: @escaping (Bool) -> Void, + updateAcceptIncomingCalls: @escaping (Bool) -> Void, + remove: @escaping (@escaping () -> Void) -> Void + ) { + self.context = context + self.updateAcceptSecretChats = updateAcceptSecretChats + self.updateAcceptIncomingCalls = updateAcceptIncomingCalls + self.remove = remove + + super.init( + context: context, + component: RecentSessionSheetComponent( + context: context, + subject: subject + ), + navigationBarAppearance: .none, + statusBarStyle: .ignore, + theme: .default + ) + + self.navigationPresentation = .flatModal + } + + required public init(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + public override func viewDidLoad() { + super.viewDidLoad() + + self.view.disablesInteractiveModalDismiss = true + } + + public func dismissAnimated() { + if let view = self.node.hostView.findTaggedView(tag: SheetComponent.View.Tag()) as? SheetComponent.View { + view.dismissAnimated() } - - if let _ = self.acceptBackgroundNode.supernode { - contentHeight += secretFrame.maxY - locationInfoTextFrame.maxY - } - contentHeight += 40.0 - - let isCurrent: Bool - if case let .session(session) = self.subject, session.isCurrent { - isCurrent = true - } else { - isCurrent = false - } - - if isCurrent { - contentHeight -= 68.0 - self.terminateButton.isHidden = true - self.terminateButton.isAccessibilityElement = false - } else { - self.terminateButton.isHidden = false - self.terminateButton.isAccessibilityElement = true - } - - let sideInset = floor((layout.size.width - width) / 2.0) - let scrollContentHeight = max(layout.size.height, contentHeight) - let contentContainerFrame = CGRect(origin: CGPoint(x: sideInset, y: max(layout.statusBarHeight ?? 20.0, layout.size.height - contentHeight)), size: CGSize(width: width, height: contentHeight)) - let contentFrame = contentContainerFrame - - self.wrappingScrollNode.view.contentSize = CGSize(width: layout.size.width, height: scrollContentHeight) - - var backgroundFrame = CGRect(origin: CGPoint(x: contentFrame.minX, y: contentFrame.minY), size: CGSize(width: width, height: contentFrame.height + 2000.0)) - if backgroundFrame.minY < contentFrame.minY { - backgroundFrame.origin.y = contentFrame.minY - } - transition.updateFrame(node: self.backgroundNode, frame: backgroundFrame) - transition.updateFrame(node: self.contentBackgroundNode, frame: CGRect(origin: CGPoint(), size: backgroundFrame.size)) - - let doneButtonHeight = self.terminateButton.updateLayout(width: width - inset * 2.0, transition: transition) - transition.updateFrame(node: self.terminateButton, frame: CGRect(x: inset, y: contentHeight - doneButtonHeight - 40.0 - insets.bottom - 6.0, width: width, height: doneButtonHeight)) - - transition.updateFrame(node: self.contentContainerNode, frame: contentContainerFrame) - transition.updateFrame(node: self.topContentContainerNode, frame: contentContainerFrame) } } diff --git a/submodules/SettingsUI/Sources/Themes/ThemeSettingsController.swift b/submodules/SettingsUI/Sources/Themes/ThemeSettingsController.swift index 4aa227f8..b7649cb1 100644 --- a/submodules/SettingsUI/Sources/Themes/ThemeSettingsController.swift +++ b/submodules/SettingsUI/Sources/Themes/ThemeSettingsController.swift @@ -23,6 +23,7 @@ import ThemeCarouselItem import ThemeAccentColorScreen import WallpaperGridScreen import PeerNameColorItem +import DeviceModel private final class ThemeSettingsControllerArguments { let context: AccountContext @@ -38,13 +39,34 @@ private final class ThemeSettingsControllerArguments { let openBubbleSettings: () -> Void let openPowerSavingSettings: () -> Void let openStickersAndEmoji: () -> Void + let toggleSendWithCmdEnter: (Bool) -> Void let toggleShowNextMediaOnTap: (Bool) -> Void let selectAppIcon: (PresentationAppIcon) -> Void let editTheme: (PresentationCloudTheme) -> Void let themeContextAction: (Bool, PresentationThemeReference, ASDisplayNode, ContextGesture?) -> Void let colorContextAction: (Bool, PresentationThemeReference, ThemeSettingsColorOption?, ASDisplayNode, ContextGesture?) -> Void - init(context: AccountContext, selectTheme: @escaping (PresentationThemeReference) -> Void, openThemeSettings: @escaping () -> Void, openWallpaperSettings: @escaping () -> Void, openNameColorSettings: @escaping () -> Void, selectAccentColor: @escaping (PresentationThemeAccentColor?) -> Void, openAccentColorPicker: @escaping (PresentationThemeReference, Bool) -> Void, toggleNightTheme: @escaping (Bool) -> Void, openAutoNightTheme: @escaping () -> Void, openTextSize: @escaping () -> Void, openBubbleSettings: @escaping () -> Void, openPowerSavingSettings: @escaping () -> Void, openStickersAndEmoji: @escaping () -> Void, toggleShowNextMediaOnTap: @escaping (Bool) -> Void, selectAppIcon: @escaping (PresentationAppIcon) -> Void, editTheme: @escaping (PresentationCloudTheme) -> Void, themeContextAction: @escaping (Bool, PresentationThemeReference, ASDisplayNode, ContextGesture?) -> Void, colorContextAction: @escaping (Bool, PresentationThemeReference, ThemeSettingsColorOption?, ASDisplayNode, ContextGesture?) -> Void) { + init( + context: AccountContext, + selectTheme: @escaping (PresentationThemeReference) -> Void, + openThemeSettings: @escaping () -> Void, + openWallpaperSettings: @escaping () -> Void, + openNameColorSettings: @escaping () -> Void, + selectAccentColor: @escaping (PresentationThemeAccentColor?) -> Void, + openAccentColorPicker: @escaping (PresentationThemeReference, Bool) -> Void, + toggleNightTheme: @escaping (Bool) -> Void, + openAutoNightTheme: @escaping () -> Void, + openTextSize: @escaping () -> Void, + openBubbleSettings: @escaping () -> Void, + openPowerSavingSettings: @escaping () -> Void, + openStickersAndEmoji: @escaping () -> Void, + toggleSendWithCmdEnter: @escaping (Bool) -> Void, + toggleShowNextMediaOnTap: @escaping (Bool) -> Void, + selectAppIcon: @escaping (PresentationAppIcon) -> Void, + editTheme: @escaping (PresentationCloudTheme) -> Void, + themeContextAction: @escaping (Bool, PresentationThemeReference, ASDisplayNode, ContextGesture?) -> Void, + colorContextAction: @escaping (Bool, PresentationThemeReference, ThemeSettingsColorOption?, ASDisplayNode, ContextGesture?) -> Void + ) { self.context = context self.selectTheme = selectTheme self.openThemeSettings = openThemeSettings @@ -58,6 +80,7 @@ private final class ThemeSettingsControllerArguments { self.openBubbleSettings = openBubbleSettings self.openPowerSavingSettings = openPowerSavingSettings self.openStickersAndEmoji = openStickersAndEmoji + self.toggleSendWithCmdEnter = toggleSendWithCmdEnter self.toggleShowNextMediaOnTap = toggleShowNextMediaOnTap self.selectAppIcon = selectAppIcon self.editTheme = editTheme @@ -84,6 +107,9 @@ public enum ThemeSettingsEntryTag: ItemListItemTag { case powerSaving case stickersAndEmoji case animations + case sendWithCmdEnter + case tapForNextMedia + case nightMode public func isEqual(to other: ItemListItemTag) -> Bool { if let other = other as? ThemeSettingsEntryTag, self == other { @@ -110,6 +136,7 @@ private enum ThemeSettingsControllerEntry: ItemListNodeEntry { case powerSaving case stickersAndEmoji case otherHeader(PresentationTheme, String) + case sendWithCmdEnter(PresentationTheme, String, Bool) case showNextMediaOnTap(PresentationTheme, String, Bool) case showNextMediaOnTapInfo(PresentationTheme, String) @@ -125,7 +152,7 @@ private enum ThemeSettingsControllerEntry: ItemListNodeEntry { return ThemeSettingsControllerSection.icon.rawValue case .powerSaving, .stickersAndEmoji: return ThemeSettingsControllerSection.message.rawValue - case .otherHeader, .showNextMediaOnTap, .showNextMediaOnTapInfo: + case .otherHeader, .sendWithCmdEnter, .showNextMediaOnTap, .showNextMediaOnTapInfo: return ThemeSettingsControllerSection.other.rawValue } } @@ -162,10 +189,12 @@ private enum ThemeSettingsControllerEntry: ItemListNodeEntry { return 13 case .otherHeader: return 14 - case .showNextMediaOnTap: + case .sendWithCmdEnter: return 15 - case .showNextMediaOnTapInfo: + case .showNextMediaOnTap: return 16 + case .showNextMediaOnTapInfo: + return 17 } } @@ -261,6 +290,12 @@ private enum ThemeSettingsControllerEntry: ItemListNodeEntry { } else { return false } + case let .sendWithCmdEnter(lhsTheme, lhsTitle, lhsValue): + if case let .sendWithCmdEnter(rhsTheme, rhsTitle, rhsValue) = rhs, lhsTheme === rhsTheme, lhsTitle == rhsTitle, lhsValue == rhsValue { + return true + } else { + return false + } case let .showNextMediaOnTap(lhsTheme, lhsTitle, lhsValue): if case let .showNextMediaOnTap(rhsTheme, rhsTitle, rhsValue) = rhs, lhsTheme === rhsTheme, lhsTitle == rhsTitle, lhsValue == rhsValue { return true @@ -318,7 +353,7 @@ private enum ThemeSettingsControllerEntry: ItemListNodeEntry { case let .autoNight(_, title, value, enabled): return ItemListSwitchItem(presentationData: presentationData, systemStyle: .glass, title: title, value: value, enabled: enabled, sectionId: self.section, style: .blocks, updated: { value in arguments.toggleNightTheme(value) - }, tag: nil) + }, tag: ThemeSettingsEntryTag.nightMode) case let .autoNightTheme(_, text, value): return ItemListDisclosureItem(presentationData: presentationData, systemStyle: .glass, icon: nil, title: text, label: value, labelStyle: .text, sectionId: self.section, style: .blocks, disclosureStyle: .arrow, action: { arguments.openAutoNightTheme() @@ -349,17 +384,35 @@ private enum ThemeSettingsControllerEntry: ItemListNodeEntry { }) case let .otherHeader(_, text): return ItemListSectionHeaderItem(presentationData: presentationData, text: text, sectionId: self.section) + case let .sendWithCmdEnter(_, title, value): + return ItemListSwitchItem(presentationData: presentationData, systemStyle: .glass, title: title, value: value, sectionId: self.section, style: .blocks, updated: { value in + arguments.toggleSendWithCmdEnter(value) + }, tag: ThemeSettingsEntryTag.sendWithCmdEnter) case let .showNextMediaOnTap(_, title, value): return ItemListSwitchItem(presentationData: presentationData, systemStyle: .glass, title: title, value: value, sectionId: self.section, style: .blocks, updated: { value in arguments.toggleShowNextMediaOnTap(value) - }, tag: ThemeSettingsEntryTag.animations) + }, tag: ThemeSettingsEntryTag.tapForNextMedia) case let .showNextMediaOnTapInfo(_, text): return ItemListTextItem(presentationData: presentationData, text: .plain(text), sectionId: self.section) } } } -private func themeSettingsControllerEntries(presentationData: PresentationData, presentationThemeSettings: PresentationThemeSettings, mediaSettings: MediaDisplaySettings, themeReference: PresentationThemeReference, availableThemes: [PresentationThemeReference], availableAppIcons: [PresentationAppIcon], currentAppIconName: String?, isPremium: Bool, chatThemes: [PresentationThemeReference], animatedEmojiStickers: [String: [StickerPackItem]], accountPeer: EnginePeer?, nameColors: PeerNameColors) -> [ThemeSettingsControllerEntry] { +private func themeSettingsControllerEntries( + presentationData: PresentationData, + presentationThemeSettings: PresentationThemeSettings, + chatSettings: ChatSettings, + mediaSettings: MediaDisplaySettings, + themeReference: PresentationThemeReference, + availableThemes: [PresentationThemeReference], + availableAppIcons: [PresentationAppIcon], + currentAppIconName: String?, + isPremium: Bool, + chatThemes: [PresentationThemeReference], + animatedEmojiStickers: [String: [StickerPackItem]], + accountPeer: EnginePeer?, + nameColors: PeerNameColors +) -> [ThemeSettingsControllerEntry] { var entries: [ThemeSettingsControllerEntry] = [] let strings = presentationData.strings @@ -435,6 +488,9 @@ private func themeSettingsControllerEntries(presentationData: PresentationData, } entries.append(.otherHeader(presentationData.theme, strings.Appearance_Other.uppercased())) + if DeviceModel.current.isIpad { + entries.append(.sendWithCmdEnter(presentationData.theme, "Send with Cmd+Enter", chatSettings.sendWithCmdEnter)) + } entries.append(.showNextMediaOnTap(presentationData.theme, strings.Appearance_ShowNextMediaOnTap, mediaSettings.showNextMediaOnTap)) entries.append(.showNextMediaOnTapInfo(presentationData.theme, strings.Appearance_ShowNextMediaOnTapInfo)) @@ -513,73 +569,96 @@ public func themeSettingsController(context: AccountContext, focusOnItemTag: The return animatedEmojiStickers } - let arguments = ThemeSettingsControllerArguments(context: context, selectTheme: { theme in + let selectThemeArgument: (PresentationThemeReference) -> Void = { theme in selectThemeImpl?(theme) - }, openThemeSettings: { + } + let openThemeSettingsArgument: () -> Void = { pushControllerImpl?(themePickerController(context: context)) - }, openWallpaperSettings: { + } + let openWallpaperSettingsArgument: () -> Void = { pushControllerImpl?(ThemeGridController(context: context)) - }, openNameColorSettings: { + } + let openNameColorSettingsArgument: () -> Void = { pushControllerImpl?(UserAppearanceScreen(context: context)) - }, selectAccentColor: { accentColor in + } + let selectAccentColorArgument: (PresentationThemeAccentColor?) -> Void = { accentColor in selectAccentColorImpl?(accentColor) - }, openAccentColorPicker: { themeReference, create in + } + let openAccentColorPickerArgument: (PresentationThemeReference, Bool) -> Void = { themeReference, create in openAccentColorPickerImpl?(themeReference, create) - }, toggleNightTheme: { value in + } + let toggleNightThemeArgument: (Bool) -> Void = { value in let _ = updatePresentationThemeSettingsInteractively(accountManager: context.sharedContext.accountManager, { current in var current = current current.automaticThemeSwitchSetting.force = value return current }).start() presentCrossfadeControllerImpl?(true) - }, openAutoNightTheme: { + } + let openAutoNightThemeArgument: () -> Void = { pushControllerImpl?(themeAutoNightSettingsController(context: context)) - }, openTextSize: { + } + let openTextSizeArgument: () -> Void = { let _ = (context.sharedContext.accountManager.sharedData(keys: Set([ApplicationSpecificSharedDataKeys.presentationThemeSettings])) |> take(1) |> deliverOnMainQueue).start(next: { view in let settings = view.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings]?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings pushControllerImpl?(TextSizeSelectionController(context: context, presentationThemeSettings: settings)) }) - }, openBubbleSettings: { + } + let openBubbleSettingsArgument: () -> Void = { let _ = (context.sharedContext.accountManager.sharedData(keys: Set([ApplicationSpecificSharedDataKeys.presentationThemeSettings])) |> take(1) |> deliverOnMainQueue).start(next: { view in let settings = view.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings]?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings pushControllerImpl?(BubbleSettingsController(context: context, presentationThemeSettings: settings)) }) - }, openPowerSavingSettings: { + } + let openPowerSavingSettingsArgument: () -> Void = { pushControllerImpl?(energySavingSettingsScreen(context: context)) - }, openStickersAndEmoji: { + } + let openStickersAndEmojiArgument: () -> Void = { let _ = (archivedPacks.get() |> take(1) |> deliverOnMainQueue).start(next: { archivedStickerPacks in pushControllerImpl?(installedStickerPacksController(context: context, mode: .general, archivedPacks: archivedStickerPacks, updatedPacks: { _ in })) }) - }, toggleShowNextMediaOnTap: { value in + } + let toggleSendWithCmdEnterArgument: (Bool) -> Void = { value in + let _ = updateChatSettingsInteractively(accountManager: context.sharedContext.accountManager, { current in + return current.withUpdatedSendWithCmdEnter(value) + }).start() + } + let toggleShowNextMediaOnTapArgument: (Bool) -> Void = { value in let _ = updateMediaDisplaySettingsInteractively(accountManager: context.sharedContext.accountManager, { current in return current.withUpdatedShowNextMediaOnTap(value) }).start() - }, selectAppIcon: { icon in - let _ = (context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: context.account.peerId)) - |> deliverOnMainQueue).start(next: { peer in - let isPremium = peer?.isPremium ?? false - if icon.isPremium && !isPremium { - var replaceImpl: ((ViewController) -> Void)? - let controller = PremiumDemoScreen(context: context, subject: .appIcons, source: .other, action: { - let controller = PremiumIntroScreen(context: context, source: .appIcons) - replaceImpl?(controller) - }) - replaceImpl = { [weak controller] c in - controller?.replace(with: c) - } - pushControllerImpl?(controller) - } else { - currentAppIconName.set(icon.name) - context.sharedContext.applicationBindings.requestSetAlternateIconName(icon.isDefault ? nil : icon.name, { _ in - }) + } + + func selectAppIconArgument(_ icon: PresentationAppIcon) { + let isPremium = context.isPremium + if icon.isPremium && !isPremium { + var replaceImpl: ((ViewController) -> Void)? + let controller = PremiumDemoScreen(context: context, subject: .appIcons, source: .other, action: { + let controller = PremiumIntroScreen(context: context, source: .appIcons) + replaceImpl?(controller) + }) + replaceImpl = { [weak controller] c in + controller?.replace(with: c) } - }) - }, editTheme: { theme in + pushControllerImpl?(controller) + } else if icon.isSGPro && context.sharedContext.immediateSGStatus.status < 2 { + if let payWallController = context.sharedContext.makeSGPayWallController(context: context) { + presentControllerImpl?(payWallController, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + } else { + presentControllerImpl?(context.sharedContext.makeSGUpdateIOSController(), nil) + } + } else { + currentAppIconName.set(icon.name) + context.sharedContext.applicationBindings.requestSetAlternateIconName(icon.isDefault ? nil : icon.name, { _ in + }) + } + } + let editThemeArgument: (PresentationCloudTheme) -> Void = { theme in let controller = editThemeController(context: context, mode: .edit(theme), navigateToChat: { peerId in let _ = (context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: peerId)) |> deliverOnMainQueue).start(next: { peer in @@ -592,7 +671,8 @@ public func themeSettingsController(context: AccountContext, focusOnItemTag: The }) }) pushControllerImpl?(controller) - }, themeContextAction: { isCurrent, reference, node, gesture in + } + let themeContextActionArgument: (Bool, PresentationThemeReference, ASDisplayNode, ContextGesture?) -> Void = { isCurrent, reference, node, gesture in let _ = (context.sharedContext.accountManager.transaction { transaction -> (PresentationThemeAccentColor?, TelegramWallpaper?) in let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings)?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings let accentColor = settings.themeSpecificAccentColors[reference.index] @@ -779,10 +859,11 @@ public func themeSettingsController(context: AccountContext, focusOnItemTag: The }))) } - let contextController = ContextController(presentationData: presentationData, source: .controller(ContextControllerContentSourceImpl(controller: themeController, sourceNode: node)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) + let contextController = makeContextController(presentationData: presentationData, source: .controller(ContextControllerContentSourceImpl(controller: themeController, sourceNode: node)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) presentInGlobalOverlayImpl?(contextController, nil) }) - }, colorContextAction: { isCurrent, reference, accentColor, node, gesture in + } + let colorContextActionArgument: (Bool, PresentationThemeReference, ThemeSettingsColorOption?, ASDisplayNode, ContextGesture?) -> Void = { isCurrent, reference, accentColor, node, gesture in let _ = (context.sharedContext.accountManager.transaction { transaction -> (ThemeSettingsColorOption?, TelegramWallpaper?) in let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings)?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings var wallpaper: TelegramWallpaper? @@ -1028,17 +1109,56 @@ public func themeSettingsController(context: AccountContext, focusOnItemTag: The } } } - let contextController = ContextController(presentationData: presentationData, source: .controller(ContextControllerContentSourceImpl(controller: themeController, sourceNode: node)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) + let contextController = makeContextController(presentationData: presentationData, source: .controller(ContextControllerContentSourceImpl(controller: themeController, sourceNode: node)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) presentInGlobalOverlayImpl?(contextController, nil) }) - }) + } - let signal = combineLatest(queue: .mainQueue(), context.sharedContext.presentationData, context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.presentationThemeSettings, SharedDataKeys.chatThemes, ApplicationSpecificSharedDataKeys.mediaDisplaySettings]), cloudThemes.get(), availableAppIcons, currentAppIconName.get(), removedThemeIndexesPromise.get(), animatedEmojiStickers, context.account.postbox.peerView(id: context.account.peerId), context.engine.data.subscribe(TelegramEngine.EngineData.Item.Peer.Peer(id: context.account.peerId))) - |> map { presentationData, sharedData, cloudThemes, availableAppIcons, currentAppIconName, removedThemeIndexes, animatedEmojiStickers, peerView, accountPeer -> (ItemListControllerState, (ItemListNodeState, Any)) in + let arguments: ThemeSettingsControllerArguments = ThemeSettingsControllerArguments( + context: context, + selectTheme: selectThemeArgument, + openThemeSettings: openThemeSettingsArgument, + openWallpaperSettings: openWallpaperSettingsArgument, + openNameColorSettings: openNameColorSettingsArgument, + selectAccentColor: selectAccentColorArgument, + openAccentColorPicker: openAccentColorPickerArgument, + toggleNightTheme: toggleNightThemeArgument, + openAutoNightTheme: openAutoNightThemeArgument, + openTextSize: openTextSizeArgument, + openBubbleSettings: openBubbleSettingsArgument, + openPowerSavingSettings: openPowerSavingSettingsArgument, + openStickersAndEmoji: openStickersAndEmojiArgument, + toggleSendWithCmdEnter: toggleSendWithCmdEnterArgument, + toggleShowNextMediaOnTap: toggleShowNextMediaOnTapArgument, + selectAppIcon: selectAppIconArgument, + editTheme: editThemeArgument, + themeContextAction: themeContextActionArgument, + colorContextAction: colorContextActionArgument + ) + + let signal: Signal<(ItemListControllerState, (ItemListNodeState, ThemeSettingsControllerArguments)), NoError> = combineLatest( + queue: .mainQueue(), + context.sharedContext.presentationData, + context.sharedContext.accountManager.sharedData(keys: [ + ApplicationSpecificSharedDataKeys.presentationThemeSettings, + ApplicationSpecificSharedDataKeys.chatSettings, + ApplicationSpecificSharedDataKeys.mediaDisplaySettings, + SharedDataKeys.chatThemes + ]), + cloudThemes.get(), + availableAppIcons, + currentAppIconName.get(), + removedThemeIndexesPromise.get(), + animatedEmojiStickers, + context.account.postbox.peerView(id: context.account.peerId), + context.engine.data.subscribe(TelegramEngine.EngineData.Item.Peer.Peer(id: context.account.peerId)) + ) + |> map { presentationData, sharedData, cloudThemes, availableAppIcons, currentAppIconName, removedThemeIndexes, animatedEmojiStickers, peerView, accountPeer -> (ItemListControllerState, (ItemListNodeState, ThemeSettingsControllerArguments)) in let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings]?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings + let chatSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.chatSettings]?.get(ChatSettings.self) ?? ChatSettings.defaultSettings let mediaSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.mediaDisplaySettings]?.get(MediaDisplaySettings.self) ?? MediaDisplaySettings.defaultSettings - let isPremium = peerView.peers[peerView.peerId]?.isPremium ?? false + let isPremium = context.sharedContext.immediateSGStatus.status > 1 let themeReference: PresentationThemeReference if presentationData.autoNightModeTriggered { @@ -1075,7 +1195,7 @@ public func themeSettingsController(context: AccountContext, focusOnItemTag: The chatThemes.insert(.builtin(.dayClassic), at: 0) let controllerState = ItemListControllerState(presentationData: ItemListPresentationData(presentationData), title: .text(presentationData.strings.Appearance_Title), leftNavigationButton: nil, rightNavigationButton: nil, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back)) - let listState = ItemListNodeState(presentationData: ItemListPresentationData(presentationData), entries: themeSettingsControllerEntries(presentationData: presentationData, presentationThemeSettings: settings, mediaSettings: mediaSettings, themeReference: themeReference, availableThemes: availableThemes, availableAppIcons: availableAppIcons, currentAppIconName: currentAppIconName, isPremium: isPremium, chatThemes: chatThemes, animatedEmojiStickers: animatedEmojiStickers, accountPeer: accountPeer, nameColors: context.peerNameColors), style: .blocks, ensureVisibleItemTag: focusOnItemTag, animateChanges: false) + let listState = ItemListNodeState(presentationData: ItemListPresentationData(presentationData), entries: themeSettingsControllerEntries(presentationData: presentationData, presentationThemeSettings: settings, chatSettings: chatSettings, mediaSettings: mediaSettings, themeReference: themeReference, availableThemes: availableThemes, availableAppIcons: availableAppIcons, currentAppIconName: currentAppIconName, isPremium: isPremium, chatThemes: chatThemes, animatedEmojiStickers: animatedEmojiStickers, accountPeer: accountPeer, nameColors: context.peerNameColors), style: .blocks, ensureVisibleItemTag: focusOnItemTag, animateChanges: false) return (controllerState, (listState, arguments)) } @@ -1309,6 +1429,21 @@ public func themeSettingsController(context: AccountContext, focusOnItemTag: The presentCrossfadeControllerImpl?(true) }) } + + if let focusOnItemTag { + var didFocusOnItem = false + controller.afterTransactionCompleted = { [weak controller] in + if !didFocusOnItem, let controller { + controller.forEachItemNode { itemNode in + if let itemNode = itemNode as? ItemListItemNode, let tag = itemNode.tag, tag.isEqual(to: focusOnItemTag) { + didFocusOnItem = true + itemNode.displayHighlight() + } + } + } + } + } + return controller } diff --git a/submodules/ShareController/BUILD b/submodules/ShareController/BUILD index e5104519..ec5db66c 100644 --- a/submodules/ShareController/BUILD +++ b/submodules/ShareController/BUILD @@ -1,5 +1,9 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + swift_library( name = "ShareController", module_name = "ShareController", @@ -9,7 +13,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", "//submodules/AsyncDisplayKit:AsyncDisplayKit", "//submodules/Postbox:Postbox", diff --git a/submodules/ShareController/Sources/ShareController.swift b/submodules/ShareController/Sources/ShareController.swift index c5622bec..dbf00232 100644 --- a/submodules/ShareController/Sources/ShareController.swift +++ b/submodules/ShareController/Sources/ShareController.swift @@ -1,4 +1,5 @@ import Foundation +import SGSimpleSettings import UIKit import Display import AsyncDisplayKit @@ -453,7 +454,14 @@ public final class ShareController: ViewController { public var parentNavigationController: NavigationController? - public convenience init(context: AccountContext, subject: ShareControllerSubject, presetText: String? = nil, preferredAction: ShareControllerPreferredAction = .default, showInChat: ((Message) -> Void)? = nil, fromForeignApp: Bool = false, segmentedValues: [ShareControllerSegmentedValue]? = nil, externalShare: Bool = true, immediateExternalShare: Bool = false, switchableAccounts: [AccountWithInfo] = [], immediatePeerId: PeerId? = nil, updatedPresentationData: (initial: PresentationData, signal: Signal)? = nil, forceTheme: PresentationTheme? = nil, forcedActionTitle: String? = nil, shareAsLink: Bool = false, collectibleItemInfo: TelegramCollectibleItemInfo? = nil) { + public convenience init(context: AccountContext, subject: ShareControllerSubject, presetText: String? = nil, preferredAction: ShareControllerPreferredAction = .default, showInChat: ((Message) -> Void)? = nil, fromForeignApp: Bool = false, segmentedValues: [ShareControllerSegmentedValue]? = nil, externalShare: Bool = true, immediateExternalShare: Bool = false, immediateExternalShareOverridingSGBehaviour: Bool? = nil, switchableAccounts: [AccountWithInfo] = [], immediatePeerId: PeerId? = nil, updatedPresentationData: (initial: PresentationData, signal: Signal)? = nil, forceTheme: PresentationTheme? = nil, forcedActionTitle: String? = nil, shareAsLink: Bool = false, collectibleItemInfo: TelegramCollectibleItemInfo? = nil) { + var immediateExternalShare = immediateExternalShare + if SGSimpleSettings.shared.forceSystemSharing { + immediateExternalShare = true + } + if let immediateExternalShareOverridingSGBehaviour = immediateExternalShareOverridingSGBehaviour { + immediateExternalShare = immediateExternalShareOverridingSGBehaviour + } self.init( environment: ShareControllerAppEnvironment(sharedContext: context.sharedContext), currentContext: ShareControllerAppAccountContext(context: context), @@ -1092,7 +1100,7 @@ public final class ShareController: ViewController { var restrictedText: String? for attribute in message.attributes { if let attribute = attribute as? RestrictedContentMessageAttribute { - restrictedText = attribute.platformText(platform: "ios", contentSettings: strongSelf.currentContext.contentSettings) ?? "" + restrictedText = attribute.platformText(platform: "ios", contentSettings: strongSelf.currentContext.contentSettings, chatId: message.author?.id.id._internalGetInt64Value()) ?? "" } } diff --git a/submodules/ShareController/Sources/SharePeersContainerNode.swift b/submodules/ShareController/Sources/SharePeersContainerNode.swift index 63caa245..33f95893 100644 --- a/submodules/ShareController/Sources/SharePeersContainerNode.swift +++ b/submodules/ShareController/Sources/SharePeersContainerNode.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import AsyncDisplayKit @@ -163,7 +164,7 @@ final class SharePeersContainerNode: ASDisplayNode, ShareContentContainerNode { self.peersValue.set(.single(peers)) - let canShareStory = controllerInteraction.shareStory != nil + let canShareStory = controllerInteraction.shareStory != nil && SGSimpleSettings.shared.showRepostToStoryV2 let items: Signal<[SharePeerEntry], NoError> = combineLatest(self.peersValue.get(), self.foundPeers.get(), self.tick.get(), self.themePromise.get()) |> map { [weak controllerInteraction] initialPeers, foundPeers, _, theme -> [SharePeerEntry] in @@ -326,6 +327,30 @@ final class SharePeersContainerNode: ASDisplayNode, ShareContentContainerNode { } self.contentTitleNode.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.debugTapGesture(_:)))) + + // MARK: Swiftgram + self.isAccessibilityElement = false + + self.contentTitleNode.isAccessibilityElement = true + self.contentTitleNode.accessibilityLabel = strings.ShareMenu_ShareTo + self.contentTitleNode.accessibilityTraits = .header + + self.contentSubtitleNode.isAccessibilityElement = true + self.contentSubtitleNode.accessibilityLabel = strings.ShareMenu_SelectChats + + self.searchButtonNode.isAccessibilityElement = true + self.searchButtonNode.accessibilityLabel = strings.Common_Search + self.searchButtonNode.accessibilityTraits = .button + + self.shareButtonNode.isAccessibilityElement = true + self.shareButtonNode.accessibilityLabel = "System Share Menu" + self.shareButtonNode.accessibilityTraits = .button + + self.contentTitleAccountNode.isAccessibilityElement = true + self.contentTitleAccountNode.accessibilityLabel = strings.Shortcut_SwitchAccount + self.contentTitleAccountNode.accessibilityTraits = .button + // + } deinit { @@ -701,6 +726,7 @@ final class SharePeersContainerNode: ASDisplayNode, ShareContentContainerNode { }) } self.contentSubtitleNode.attributedText = NSAttributedString(string: subtitleText, font: subtitleFont, textColor: self.theme.actionSheet.secondaryTextColor) + self.contentSubtitleNode.accessibilityLabel = subtitleText } self.contentGridNode.forEachItemNode { itemNode in if let itemNode = itemNode as? ShareControllerPeerGridItemNode { diff --git a/submodules/TabBarUI/BUILD b/submodules/TabBarUI/BUILD index 2a3e1999..eddc3019 100644 --- a/submodules/TabBarUI/BUILD +++ b/submodules/TabBarUI/BUILD @@ -1,15 +1,23 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", +] + +sgsrc = [ + "//Swiftgram/SGTabBarHeightModifier:SGTabBarHeightModifier" +] + swift_library( name = "TabBarUI", module_name = "TabBarUI", - srcs = glob([ + srcs = sgsrc + glob([ "Sources/**/*.swift", ]), copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/AsyncDisplayKit", "//submodules/Display", "//submodules/SSignalKit/SwiftSignalKit", diff --git a/submodules/TabBarUI/Sources/TabBarContollerNode.swift b/submodules/TabBarUI/Sources/TabBarContollerNode.swift index c4de51c3..539a92f0 100644 --- a/submodules/TabBarUI/Sources/TabBarContollerNode.swift +++ b/submodules/TabBarUI/Sources/TabBarContollerNode.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import AsyncDisplayKit @@ -164,7 +165,7 @@ final class TabBarControllerNode: ASDisplayNode { transition.updateAlpha(node: self.disabledOverlayNode, alpha: value ? 0.0 : 1.0) } - var tabBarHidden = false { + var tabBarHidden = SGSimpleSettings.shared.hideTabBar { didSet { if self.tabBarHidden != oldValue { self.requestUpdate() @@ -250,7 +251,7 @@ final class TabBarControllerNode: ASDisplayNode { } ) }, - search: self.currentController?.tabBarSearchState.flatMap { tabBarSearchState in + search: (!SGSimpleSettings.shared.tabBarSearchEnabled) ? nil : self.currentController?.tabBarSearchState.flatMap { tabBarSearchState in return TabBarComponent.Search( isActive: tabBarSearchState.isActive, activate: { [weak self] in diff --git a/submodules/TabBarUI/Sources/TabBarNode.swift b/submodules/TabBarUI/Sources/TabBarNode.swift index 5b08f3eb..fb5c3a15 100644 --- a/submodules/TabBarUI/Sources/TabBarNode.swift +++ b/submodules/TabBarUI/Sources/TabBarNode.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import AsyncDisplayKit @@ -720,6 +721,11 @@ class TabBarNode: ASDisplayNode, ASGestureRecognizerDelegate { node.contextImageNode.frame = CGRect(origin: CGPoint(), size: nodeFrame.size) node.contextTextImageNode.frame = CGRect(origin: CGPoint(), size: nodeFrame.size) + + node.imageNode.frame = CGRect(origin: CGPoint(x: 0.0, y: 6.0), size: nodeFrame.size) + node.textImageNode.frame = CGRect(origin: CGPoint(), size: CGSize()) + + let scaleFactor: CGFloat = horizontal ? 0.8 : 1.0 node.animationContainerNode.subnodeTransform = CATransform3DMakeScale(scaleFactor, scaleFactor, 1.0) let animationOffset: CGPoint = self.tabBarItems[i].item.animationOffset diff --git a/submodules/TelegramApi/Sources/Api0.swift b/submodules/TelegramApi/Sources/Api0.swift index 455ff48a..c9da0e78 100644 --- a/submodules/TelegramApi/Sources/Api0.swift +++ b/submodules/TelegramApi/Sources/Api0.swift @@ -538,25 +538,26 @@ fileprivate let parsers: [Int32 : (BufferReader) -> Any?] = { dict[736157604] = { return Api.JSONValue.parse_jsonNumber($0) } dict[-1715350371] = { return Api.JSONValue.parse_jsonObject($0) } dict[-1222740358] = { return Api.JSONValue.parse_jsonString($0) } - dict[-916050683] = { return Api.KeyboardButton.parse_inputKeyboardButtonRequestPeer($0) } - dict[-802258988] = { return Api.KeyboardButton.parse_inputKeyboardButtonUrlAuth($0) } - dict[-376962181] = { return Api.KeyboardButton.parse_inputKeyboardButtonUserProfile($0) } - dict[-1560655744] = { return Api.KeyboardButton.parse_keyboardButton($0) } - dict[-1344716869] = { return Api.KeyboardButton.parse_keyboardButtonBuy($0) } - dict[901503851] = { return Api.KeyboardButton.parse_keyboardButtonCallback($0) } - dict[1976723854] = { return Api.KeyboardButton.parse_keyboardButtonCopy($0) } - dict[1358175439] = { return Api.KeyboardButton.parse_keyboardButtonGame($0) } - dict[-59151553] = { return Api.KeyboardButton.parse_keyboardButtonRequestGeoLocation($0) } - dict[1406648280] = { return Api.KeyboardButton.parse_keyboardButtonRequestPeer($0) } - dict[-1318425559] = { return Api.KeyboardButton.parse_keyboardButtonRequestPhone($0) } - dict[-1144565411] = { return Api.KeyboardButton.parse_keyboardButtonRequestPoll($0) } - dict[-1598009252] = { return Api.KeyboardButton.parse_keyboardButtonSimpleWebView($0) } - dict[-1816527947] = { return Api.KeyboardButton.parse_keyboardButtonSwitchInline($0) } - dict[629866245] = { return Api.KeyboardButton.parse_keyboardButtonUrl($0) } - dict[280464681] = { return Api.KeyboardButton.parse_keyboardButtonUrlAuth($0) } - dict[814112961] = { return Api.KeyboardButton.parse_keyboardButtonUserProfile($0) } - dict[326529584] = { return Api.KeyboardButton.parse_keyboardButtonWebView($0) } + dict[45580630] = { return Api.KeyboardButton.parse_inputKeyboardButtonRequestPeer($0) } + dict[1744911986] = { return Api.KeyboardButton.parse_inputKeyboardButtonUrlAuth($0) } + dict[2103314375] = { return Api.KeyboardButton.parse_inputKeyboardButtonUserProfile($0) } + dict[2098662655] = { return Api.KeyboardButton.parse_keyboardButton($0) } + dict[1067792645] = { return Api.KeyboardButton.parse_keyboardButtonBuy($0) } + dict[-433338016] = { return Api.KeyboardButton.parse_keyboardButtonCallback($0) } + dict[-1127960816] = { return Api.KeyboardButton.parse_keyboardButtonCopy($0) } + dict[-1983540999] = { return Api.KeyboardButton.parse_keyboardButtonGame($0) } + dict[-1438582451] = { return Api.KeyboardButton.parse_keyboardButtonRequestGeoLocation($0) } + dict[1527715317] = { return Api.KeyboardButton.parse_keyboardButtonRequestPeer($0) } + dict[1098841487] = { return Api.KeyboardButton.parse_keyboardButtonRequestPhone($0) } + dict[2047989634] = { return Api.KeyboardButton.parse_keyboardButtonRequestPoll($0) } + dict[-514047120] = { return Api.KeyboardButton.parse_keyboardButtonSimpleWebView($0) } + dict[-1726768644] = { return Api.KeyboardButton.parse_keyboardButtonSwitchInline($0) } + dict[-670292500] = { return Api.KeyboardButton.parse_keyboardButtonUrl($0) } + dict[-183499015] = { return Api.KeyboardButton.parse_keyboardButtonUrlAuth($0) } + dict[-1057137399] = { return Api.KeyboardButton.parse_keyboardButtonUserProfile($0) } + dict[-398020192] = { return Api.KeyboardButton.parse_keyboardButtonWebView($0) } dict[2002815875] = { return Api.KeyboardButtonRow.parse_keyboardButtonRow($0) } + dict[1339896880] = { return Api.KeyboardButtonStyle.parse_keyboardButtonStyle($0) } dict[-886477832] = { return Api.LabeledPrice.parse_labeledPrice($0) } dict[-209337866] = { return Api.LangPackDifference.parse_langPackDifference($0) } dict[-288727837] = { return Api.LangPackLanguage.parse_langPackLanguage($0) } @@ -579,6 +580,7 @@ fileprivate let parsers: [Int32 : (BufferReader) -> Any?] = { dict[2055212554] = { return Api.Message.parse_messageService($0) } dict[-872240531] = { return Api.MessageAction.parse_messageActionBoostApply($0) } dict[-988359047] = { return Api.MessageAction.parse_messageActionBotAllowed($0) } + dict[-511160261] = { return Api.MessageAction.parse_messageActionChangeCreator($0) } dict[-1781355374] = { return Api.MessageAction.parse_messageActionChannelCreate($0) } dict[-365344535] = { return Api.MessageAction.parse_messageActionChannelMigrateFrom($0) } dict[365886720] = { return Api.MessageAction.parse_messageActionChatAddUser($0) } @@ -606,6 +608,7 @@ fileprivate let parsers: [Int32 : (BufferReader) -> Any?] = { dict[-1281329567] = { return Api.MessageAction.parse_messageActionGroupCallScheduled($0) } dict[-1615153660] = { return Api.MessageAction.parse_messageActionHistoryClear($0) } dict[1345295095] = { return Api.MessageAction.parse_messageActionInviteToGroupCall($0) } + dict[-1333866363] = { return Api.MessageAction.parse_messageActionNewCreatorPending($0) } dict[-2068281992] = { return Api.MessageAction.parse_messageActionPaidMessagesPrice($0) } dict[-1407246387] = { return Api.MessageAction.parse_messageActionPaidMessagesRefunded($0) } dict[1102307842] = { return Api.MessageAction.parse_messageActionPaymentRefunded($0) } @@ -625,7 +628,7 @@ fileprivate let parsers: [Int32 : (BufferReader) -> Any?] = { dict[-366202413] = { return Api.MessageAction.parse_messageActionStarGift($0) } dict[2000845012] = { return Api.MessageAction.parse_messageActionStarGiftPurchaseOffer($0) } dict[1940760427] = { return Api.MessageAction.parse_messageActionStarGiftPurchaseOfferDeclined($0) } - dict[-1787656893] = { return Api.MessageAction.parse_messageActionStarGiftUnique($0) } + dict[-423422686] = { return Api.MessageAction.parse_messageActionStarGiftUnique($0) } dict[747579941] = { return Api.MessageAction.parse_messageActionSuggestBirthday($0) } dict[1474192222] = { return Api.MessageAction.parse_messageActionSuggestProfilePhoto($0) } dict[-293988970] = { return Api.MessageAction.parse_messageActionSuggestedPostApproval($0) } @@ -917,7 +920,7 @@ fileprivate let parsers: [Int32 : (BufferReader) -> Any?] = { dict[1681948327] = { return Api.SavedDialog.parse_monoForumDialog($0) } dict[-1115174036] = { return Api.SavedDialog.parse_savedDialog($0) } dict[-881854424] = { return Api.SavedReactionTag.parse_savedReactionTag($0) } - dict[-355041186] = { return Api.SavedStarGift.parse_savedStarGift($0) } + dict[1105150972] = { return Api.SavedStarGift.parse_savedStarGift($0) } dict[1040931690] = { return Api.SearchPostsFlood.parse_searchPostsFlood($0) } dict[-911191137] = { return Api.SearchResultsCalendarPeriod.parse_searchResultsCalendarPeriod($0) } dict[2137295719] = { return Api.SearchResultsPosition.parse_searchResultPosition($0) } @@ -983,16 +986,21 @@ fileprivate let parsers: [Int32 : (BufferReader) -> Any?] = { dict[1124938064] = { return Api.SponsoredMessageReportOption.parse_sponsoredMessageReportOption($0) } dict[-963180333] = { return Api.SponsoredPeer.parse_sponsoredPeer($0) } dict[825922887] = { return Api.StarGift.parse_starGift($0) } - dict[1453155529] = { return Api.StarGift.parse_starGiftUnique($0) } + dict[-2047825459] = { return Api.StarGift.parse_starGiftUnique($0) } dict[-753154979] = { return Api.StarGiftActiveAuctionState.parse_starGiftActiveAuctionState($0) } - dict[-650279524] = { return Api.StarGiftAttribute.parse_starGiftAttributeBackdrop($0) } - dict[970559507] = { return Api.StarGiftAttribute.parse_starGiftAttributeModel($0) } + dict[-1624963868] = { return Api.StarGiftAttribute.parse_starGiftAttributeBackdrop($0) } + dict[1448235490] = { return Api.StarGiftAttribute.parse_starGiftAttributeModel($0) } dict[-524291476] = { return Api.StarGiftAttribute.parse_starGiftAttributeOriginalDetails($0) } - dict[330104601] = { return Api.StarGiftAttribute.parse_starGiftAttributePattern($0) } + dict[1315997162] = { return Api.StarGiftAttribute.parse_starGiftAttributePattern($0) } dict[783398488] = { return Api.StarGiftAttributeCounter.parse_starGiftAttributeCounter($0) } dict[520210263] = { return Api.StarGiftAttributeId.parse_starGiftAttributeIdBackdrop($0) } dict[1219145276] = { return Api.StarGiftAttributeId.parse_starGiftAttributeIdModel($0) } dict[1242965043] = { return Api.StarGiftAttributeId.parse_starGiftAttributeIdPattern($0) } + dict[910391095] = { return Api.StarGiftAttributeRarity.parse_starGiftAttributeRarity($0) } + dict[2029777832] = { return Api.StarGiftAttributeRarity.parse_starGiftAttributeRarityEpic($0) } + dict[-822614104] = { return Api.StarGiftAttributeRarity.parse_starGiftAttributeRarityLegendary($0) } + dict[-259174037] = { return Api.StarGiftAttributeRarity.parse_starGiftAttributeRarityRare($0) } + dict[-607231095] = { return Api.StarGiftAttributeRarity.parse_starGiftAttributeRarityUncommon($0) } dict[1118831432] = { return Api.StarGiftAuctionAcquiredGift.parse_starGiftAuctionAcquiredGift($0) } dict[984483112] = { return Api.StarGiftAuctionRound.parse_starGiftAuctionRound($0) } dict[178266597] = { return Api.StarGiftAuctionRound.parse_starGiftAuctionRoundExtendable($0) } @@ -1206,6 +1214,7 @@ fileprivate let parsers: [Int32 : (BufferReader) -> Any?] = { dict[-245208620] = { return Api.Update.parse_updateSmsJob($0) } dict[1222788802] = { return Api.Update.parse_updateStarGiftAuctionState($0) } dict[-598150370] = { return Api.Update.parse_updateStarGiftAuctionUserState($0) } + dict[-1408818108] = { return Api.Update.parse_updateStarGiftCraftFail($0) } dict[1317053305] = { return Api.Update.parse_updateStarsBalance($0) } dict[-1518030823] = { return Api.Update.parse_updateStarsRevenueStatus($0) } dict[834816008] = { return Api.Update.parse_updateStickerSets($0) } @@ -1230,9 +1239,9 @@ fileprivate let parsers: [Int32 : (BufferReader) -> Any?] = { dict[1957577280] = { return Api.Updates.parse_updates($0) } dict[1918567619] = { return Api.Updates.parse_updatesCombined($0) } dict[-484987010] = { return Api.Updates.parse_updatesTooLong($0) } - dict[-1886646706] = { return Api.UrlAuthResult.parse_urlAuthResultAccepted($0) } + dict[1648005024] = { return Api.UrlAuthResult.parse_urlAuthResultAccepted($0) } dict[-1445536993] = { return Api.UrlAuthResult.parse_urlAuthResultDefault($0) } - dict[-1831650802] = { return Api.UrlAuthResult.parse_urlAuthResultRequest($0) } + dict[855293722] = { return Api.UrlAuthResult.parse_urlAuthResultRequest($0) } dict[829899656] = { return Api.User.parse_user($0) } dict[-742634630] = { return Api.User.parse_userEmpty($0) } dict[-1607745218] = { return Api.UserFull.parse_userFull($0) } @@ -1593,18 +1602,17 @@ public extension Api { } return nil } - - static func parse(_ reader: BufferReader, signature: Int32) -> Any? { - if let parser = parsers[signature] { - return parser(reader) - } - else { - telegramApiLog("Type constructor \(String(UInt32(bitPattern: signature), radix: 16, uppercase: false)) not found") - return nil - } + + static func parse(_ reader: BufferReader, signature: Int32) -> Any? { + if let parser = parsers[signature] { + return parser(reader) + } else { + telegramApiLog("Type constructor \(String(UInt32(bitPattern: signature), radix: 16, uppercase: false)) not found") + return nil } - - static func parseVector(_ reader: BufferReader, elementSignature: Int32, elementType: T.Type) -> [T]? { + } + + static func parseVector(_ reader: BufferReader, elementSignature: Int32, elementType: T.Type) -> [T]? { if let count = reader.readInt32() { var array = [T]() var i: Int32 = 0 @@ -1613,8 +1621,7 @@ public extension Api { if elementSignature == 0 { if let unboxedSignature = reader.readInt32() { signature = unboxedSignature - } - else { + } else { return nil } } @@ -1625,12 +1632,11 @@ public extension Api { return nil } } else { - if let item = Api.parse(reader, signature: signature) as? T { - array.append(item) - } - else { - return nil - } + if let item = Api.parse(reader, signature: signature) as? T { + array.append(item) + } else { + return nil + } } i += 1 } @@ -1638,1170 +1644,1173 @@ public extension Api { } return nil } - + static func serializeObject(_ object: Any, buffer: Buffer, boxed: Swift.Bool) { switch object { - case let _1 as Api.AccountDaysTTL: - _1.serialize(buffer, boxed) - case let _1 as Api.AttachMenuBot: - _1.serialize(buffer, boxed) - case let _1 as Api.AttachMenuBotIcon: - _1.serialize(buffer, boxed) - case let _1 as Api.AttachMenuBotIconColor: - _1.serialize(buffer, boxed) - case let _1 as Api.AttachMenuBots: - _1.serialize(buffer, boxed) - case let _1 as Api.AttachMenuBotsBot: - _1.serialize(buffer, boxed) - case let _1 as Api.AttachMenuPeerType: - _1.serialize(buffer, boxed) - case let _1 as Api.AuctionBidLevel: - _1.serialize(buffer, boxed) - case let _1 as Api.Authorization: - _1.serialize(buffer, boxed) - case let _1 as Api.AutoDownloadSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.AutoSaveException: - _1.serialize(buffer, boxed) - case let _1 as Api.AutoSaveSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.AvailableEffect: - _1.serialize(buffer, boxed) - case let _1 as Api.AvailableReaction: - _1.serialize(buffer, boxed) - case let _1 as Api.BankCardOpenUrl: - _1.serialize(buffer, boxed) - case let _1 as Api.BaseTheme: - _1.serialize(buffer, boxed) - case let _1 as Api.Birthday: - _1.serialize(buffer, boxed) - case let _1 as Api.Bool: - _1.serialize(buffer, boxed) - case let _1 as Api.Boost: - _1.serialize(buffer, boxed) - case let _1 as Api.BotApp: - _1.serialize(buffer, boxed) - case let _1 as Api.BotAppSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.BotBusinessConnection: - _1.serialize(buffer, boxed) - case let _1 as Api.BotCommand: - _1.serialize(buffer, boxed) - case let _1 as Api.BotCommandScope: - _1.serialize(buffer, boxed) - case let _1 as Api.BotInfo: - _1.serialize(buffer, boxed) - case let _1 as Api.BotInlineMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.BotInlineResult: - _1.serialize(buffer, boxed) - case let _1 as Api.BotMenuButton: - _1.serialize(buffer, boxed) - case let _1 as Api.BotPreviewMedia: - _1.serialize(buffer, boxed) - case let _1 as Api.BotVerification: - _1.serialize(buffer, boxed) - case let _1 as Api.BotVerifierSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.BusinessAwayMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.BusinessAwayMessageSchedule: - _1.serialize(buffer, boxed) - case let _1 as Api.BusinessBotRecipients: - _1.serialize(buffer, boxed) - case let _1 as Api.BusinessBotRights: - _1.serialize(buffer, boxed) - case let _1 as Api.BusinessChatLink: - _1.serialize(buffer, boxed) - case let _1 as Api.BusinessGreetingMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.BusinessIntro: - _1.serialize(buffer, boxed) - case let _1 as Api.BusinessLocation: - _1.serialize(buffer, boxed) - case let _1 as Api.BusinessRecipients: - _1.serialize(buffer, boxed) - case let _1 as Api.BusinessWeeklyOpen: - _1.serialize(buffer, boxed) - case let _1 as Api.BusinessWorkHours: - _1.serialize(buffer, boxed) - case let _1 as Api.CdnConfig: - _1.serialize(buffer, boxed) - case let _1 as Api.CdnPublicKey: - _1.serialize(buffer, boxed) - case let _1 as Api.ChannelAdminLogEvent: - _1.serialize(buffer, boxed) - case let _1 as Api.ChannelAdminLogEventAction: - _1.serialize(buffer, boxed) - case let _1 as Api.ChannelAdminLogEventsFilter: - _1.serialize(buffer, boxed) - case let _1 as Api.ChannelLocation: - _1.serialize(buffer, boxed) - case let _1 as Api.ChannelMessagesFilter: - _1.serialize(buffer, boxed) - case let _1 as Api.ChannelParticipant: - _1.serialize(buffer, boxed) - case let _1 as Api.ChannelParticipantsFilter: - _1.serialize(buffer, boxed) - case let _1 as Api.Chat: - _1.serialize(buffer, boxed) - case let _1 as Api.ChatAdminRights: - _1.serialize(buffer, boxed) - case let _1 as Api.ChatAdminWithInvites: - _1.serialize(buffer, boxed) - case let _1 as Api.ChatBannedRights: - _1.serialize(buffer, boxed) - case let _1 as Api.ChatFull: - _1.serialize(buffer, boxed) - case let _1 as Api.ChatInvite: - _1.serialize(buffer, boxed) - case let _1 as Api.ChatInviteImporter: - _1.serialize(buffer, boxed) - case let _1 as Api.ChatOnlines: - _1.serialize(buffer, boxed) - case let _1 as Api.ChatParticipant: - _1.serialize(buffer, boxed) - case let _1 as Api.ChatParticipants: - _1.serialize(buffer, boxed) - case let _1 as Api.ChatPhoto: - _1.serialize(buffer, boxed) - case let _1 as Api.ChatReactions: - _1.serialize(buffer, boxed) - case let _1 as Api.ChatTheme: - _1.serialize(buffer, boxed) - case let _1 as Api.CodeSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.Config: - _1.serialize(buffer, boxed) - case let _1 as Api.ConnectedBot: - _1.serialize(buffer, boxed) - case let _1 as Api.ConnectedBotStarRef: - _1.serialize(buffer, boxed) - case let _1 as Api.Contact: - _1.serialize(buffer, boxed) - case let _1 as Api.ContactBirthday: - _1.serialize(buffer, boxed) - case let _1 as Api.ContactStatus: - _1.serialize(buffer, boxed) - case let _1 as Api.DataJSON: - _1.serialize(buffer, boxed) - case let _1 as Api.DcOption: - _1.serialize(buffer, boxed) - case let _1 as Api.DefaultHistoryTTL: - _1.serialize(buffer, boxed) - case let _1 as Api.Dialog: - _1.serialize(buffer, boxed) - case let _1 as Api.DialogFilter: - _1.serialize(buffer, boxed) - case let _1 as Api.DialogFilterSuggested: - _1.serialize(buffer, boxed) - case let _1 as Api.DialogPeer: - _1.serialize(buffer, boxed) - case let _1 as Api.DisallowedGiftsSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.Document: - _1.serialize(buffer, boxed) - case let _1 as Api.DocumentAttribute: - _1.serialize(buffer, boxed) - case let _1 as Api.DraftMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.EmailVerification: - _1.serialize(buffer, boxed) - case let _1 as Api.EmailVerifyPurpose: - _1.serialize(buffer, boxed) - case let _1 as Api.EmojiGroup: - _1.serialize(buffer, boxed) - case let _1 as Api.EmojiKeyword: - _1.serialize(buffer, boxed) - case let _1 as Api.EmojiKeywordsDifference: - _1.serialize(buffer, boxed) - case let _1 as Api.EmojiLanguage: - _1.serialize(buffer, boxed) - case let _1 as Api.EmojiList: - _1.serialize(buffer, boxed) - case let _1 as Api.EmojiStatus: - _1.serialize(buffer, boxed) - case let _1 as Api.EmojiURL: - _1.serialize(buffer, boxed) - case let _1 as Api.EncryptedChat: - _1.serialize(buffer, boxed) - case let _1 as Api.EncryptedFile: - _1.serialize(buffer, boxed) - case let _1 as Api.EncryptedMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.ExportedChatInvite: - _1.serialize(buffer, boxed) - case let _1 as Api.ExportedChatlistInvite: - _1.serialize(buffer, boxed) - case let _1 as Api.ExportedContactToken: - _1.serialize(buffer, boxed) - case let _1 as Api.ExportedMessageLink: - _1.serialize(buffer, boxed) - case let _1 as Api.ExportedStoryLink: - _1.serialize(buffer, boxed) - case let _1 as Api.FactCheck: - _1.serialize(buffer, boxed) - case let _1 as Api.FileHash: - _1.serialize(buffer, boxed) - case let _1 as Api.Folder: - _1.serialize(buffer, boxed) - case let _1 as Api.FolderPeer: - _1.serialize(buffer, boxed) - case let _1 as Api.ForumTopic: - _1.serialize(buffer, boxed) - case let _1 as Api.FoundStory: - _1.serialize(buffer, boxed) - case let _1 as Api.Game: - _1.serialize(buffer, boxed) - case let _1 as Api.GeoPoint: - _1.serialize(buffer, boxed) - case let _1 as Api.GeoPointAddress: - _1.serialize(buffer, boxed) - case let _1 as Api.GlobalPrivacySettings: - _1.serialize(buffer, boxed) - case let _1 as Api.GroupCall: - _1.serialize(buffer, boxed) - case let _1 as Api.GroupCallDonor: - _1.serialize(buffer, boxed) - case let _1 as Api.GroupCallMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.GroupCallParticipant: - _1.serialize(buffer, boxed) - case let _1 as Api.GroupCallParticipantVideo: - _1.serialize(buffer, boxed) - case let _1 as Api.GroupCallParticipantVideoSourceGroup: - _1.serialize(buffer, boxed) - case let _1 as Api.GroupCallStreamChannel: - _1.serialize(buffer, boxed) - case let _1 as Api.HighScore: - _1.serialize(buffer, boxed) - case let _1 as Api.ImportedContact: - _1.serialize(buffer, boxed) - case let _1 as Api.InlineBotSwitchPM: - _1.serialize(buffer, boxed) - case let _1 as Api.InlineBotWebView: - _1.serialize(buffer, boxed) - case let _1 as Api.InlineQueryPeerType: - _1.serialize(buffer, boxed) - case let _1 as Api.InputAppEvent: - _1.serialize(buffer, boxed) - case let _1 as Api.InputBotApp: - _1.serialize(buffer, boxed) - case let _1 as Api.InputBotInlineMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.InputBotInlineMessageID: - _1.serialize(buffer, boxed) - case let _1 as Api.InputBotInlineResult: - _1.serialize(buffer, boxed) - case let _1 as Api.InputBusinessAwayMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.InputBusinessBotRecipients: - _1.serialize(buffer, boxed) - case let _1 as Api.InputBusinessChatLink: - _1.serialize(buffer, boxed) - case let _1 as Api.InputBusinessGreetingMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.InputBusinessIntro: - _1.serialize(buffer, boxed) - case let _1 as Api.InputBusinessRecipients: - _1.serialize(buffer, boxed) - case let _1 as Api.InputChannel: - _1.serialize(buffer, boxed) - case let _1 as Api.InputChatPhoto: - _1.serialize(buffer, boxed) - case let _1 as Api.InputChatTheme: - _1.serialize(buffer, boxed) - case let _1 as Api.InputChatlist: - _1.serialize(buffer, boxed) - case let _1 as Api.InputCheckPasswordSRP: - _1.serialize(buffer, boxed) - case let _1 as Api.InputClientProxy: - _1.serialize(buffer, boxed) - case let _1 as Api.InputCollectible: - _1.serialize(buffer, boxed) - case let _1 as Api.InputContact: - _1.serialize(buffer, boxed) - case let _1 as Api.InputDialogPeer: - _1.serialize(buffer, boxed) - case let _1 as Api.InputDocument: - _1.serialize(buffer, boxed) - case let _1 as Api.InputEncryptedChat: - _1.serialize(buffer, boxed) - case let _1 as Api.InputEncryptedFile: - _1.serialize(buffer, boxed) - case let _1 as Api.InputFile: - _1.serialize(buffer, boxed) - case let _1 as Api.InputFileLocation: - _1.serialize(buffer, boxed) - case let _1 as Api.InputFolderPeer: - _1.serialize(buffer, boxed) - case let _1 as Api.InputGame: - _1.serialize(buffer, boxed) - case let _1 as Api.InputGeoPoint: - _1.serialize(buffer, boxed) - case let _1 as Api.InputGroupCall: - _1.serialize(buffer, boxed) - case let _1 as Api.InputInvoice: - _1.serialize(buffer, boxed) - case let _1 as Api.InputMedia: - _1.serialize(buffer, boxed) - case let _1 as Api.InputMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.InputNotifyPeer: - _1.serialize(buffer, boxed) - case let _1 as Api.InputPasskeyCredential: - _1.serialize(buffer, boxed) - case let _1 as Api.InputPasskeyResponse: - _1.serialize(buffer, boxed) - case let _1 as Api.InputPaymentCredentials: - _1.serialize(buffer, boxed) - case let _1 as Api.InputPeer: - _1.serialize(buffer, boxed) - case let _1 as Api.InputPeerNotifySettings: - _1.serialize(buffer, boxed) - case let _1 as Api.InputPhoneCall: - _1.serialize(buffer, boxed) - case let _1 as Api.InputPhoto: - _1.serialize(buffer, boxed) - case let _1 as Api.InputPrivacyKey: - _1.serialize(buffer, boxed) - case let _1 as Api.InputPrivacyRule: - _1.serialize(buffer, boxed) - case let _1 as Api.InputQuickReplyShortcut: - _1.serialize(buffer, boxed) - case let _1 as Api.InputReplyTo: - _1.serialize(buffer, boxed) - case let _1 as Api.InputSavedStarGift: - _1.serialize(buffer, boxed) - case let _1 as Api.InputSecureFile: - _1.serialize(buffer, boxed) - case let _1 as Api.InputSecureValue: - _1.serialize(buffer, boxed) - case let _1 as Api.InputSingleMedia: - _1.serialize(buffer, boxed) - case let _1 as Api.InputStarGiftAuction: - _1.serialize(buffer, boxed) - case let _1 as Api.InputStarsTransaction: - _1.serialize(buffer, boxed) - case let _1 as Api.InputStickerSet: - _1.serialize(buffer, boxed) - case let _1 as Api.InputStickerSetItem: - _1.serialize(buffer, boxed) - case let _1 as Api.InputStickeredMedia: - _1.serialize(buffer, boxed) - case let _1 as Api.InputStorePaymentPurpose: - _1.serialize(buffer, boxed) - case let _1 as Api.InputTheme: - _1.serialize(buffer, boxed) - case let _1 as Api.InputThemeSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.InputUser: - _1.serialize(buffer, boxed) - case let _1 as Api.InputWallPaper: - _1.serialize(buffer, boxed) - case let _1 as Api.InputWebDocument: - _1.serialize(buffer, boxed) - case let _1 as Api.InputWebFileLocation: - _1.serialize(buffer, boxed) - case let _1 as Api.Invoice: - _1.serialize(buffer, boxed) - case let _1 as Api.JSONObjectValue: - _1.serialize(buffer, boxed) - case let _1 as Api.JSONValue: - _1.serialize(buffer, boxed) - case let _1 as Api.KeyboardButton: - _1.serialize(buffer, boxed) - case let _1 as Api.KeyboardButtonRow: - _1.serialize(buffer, boxed) - case let _1 as Api.LabeledPrice: - _1.serialize(buffer, boxed) - case let _1 as Api.LangPackDifference: - _1.serialize(buffer, boxed) - case let _1 as Api.LangPackLanguage: - _1.serialize(buffer, boxed) - case let _1 as Api.LangPackString: - _1.serialize(buffer, boxed) - case let _1 as Api.MaskCoords: - _1.serialize(buffer, boxed) - case let _1 as Api.MediaArea: - _1.serialize(buffer, boxed) - case let _1 as Api.MediaAreaCoordinates: - _1.serialize(buffer, boxed) - case let _1 as Api.Message: - _1.serialize(buffer, boxed) - case let _1 as Api.MessageAction: - _1.serialize(buffer, boxed) - case let _1 as Api.MessageEntity: - _1.serialize(buffer, boxed) - case let _1 as Api.MessageExtendedMedia: - _1.serialize(buffer, boxed) - case let _1 as Api.MessageFwdHeader: - _1.serialize(buffer, boxed) - case let _1 as Api.MessageMedia: - _1.serialize(buffer, boxed) - case let _1 as Api.MessagePeerReaction: - _1.serialize(buffer, boxed) - case let _1 as Api.MessagePeerVote: - _1.serialize(buffer, boxed) - case let _1 as Api.MessageRange: - _1.serialize(buffer, boxed) - case let _1 as Api.MessageReactions: - _1.serialize(buffer, boxed) - case let _1 as Api.MessageReactor: - _1.serialize(buffer, boxed) - case let _1 as Api.MessageReplies: - _1.serialize(buffer, boxed) - case let _1 as Api.MessageReplyHeader: - _1.serialize(buffer, boxed) - case let _1 as Api.MessageReportOption: - _1.serialize(buffer, boxed) - case let _1 as Api.MessageViews: - _1.serialize(buffer, boxed) - case let _1 as Api.MessagesFilter: - _1.serialize(buffer, boxed) - case let _1 as Api.MissingInvitee: - _1.serialize(buffer, boxed) - case let _1 as Api.MyBoost: - _1.serialize(buffer, boxed) - case let _1 as Api.NearestDc: - _1.serialize(buffer, boxed) - case let _1 as Api.NotificationSound: - _1.serialize(buffer, boxed) - case let _1 as Api.NotifyPeer: - _1.serialize(buffer, boxed) - case let _1 as Api.OutboxReadDate: - _1.serialize(buffer, boxed) - case let _1 as Api.Page: - _1.serialize(buffer, boxed) - case let _1 as Api.PageBlock: - _1.serialize(buffer, boxed) - case let _1 as Api.PageCaption: - _1.serialize(buffer, boxed) - case let _1 as Api.PageListItem: - _1.serialize(buffer, boxed) - case let _1 as Api.PageListOrderedItem: - _1.serialize(buffer, boxed) - case let _1 as Api.PageRelatedArticle: - _1.serialize(buffer, boxed) - case let _1 as Api.PageTableCell: - _1.serialize(buffer, boxed) - case let _1 as Api.PageTableRow: - _1.serialize(buffer, boxed) - case let _1 as Api.PaidReactionPrivacy: - _1.serialize(buffer, boxed) - case let _1 as Api.Passkey: - _1.serialize(buffer, boxed) - case let _1 as Api.PasswordKdfAlgo: - _1.serialize(buffer, boxed) - case let _1 as Api.PaymentCharge: - _1.serialize(buffer, boxed) - case let _1 as Api.PaymentFormMethod: - _1.serialize(buffer, boxed) - case let _1 as Api.PaymentRequestedInfo: - _1.serialize(buffer, boxed) - case let _1 as Api.PaymentSavedCredentials: - _1.serialize(buffer, boxed) - case let _1 as Api.Peer: - _1.serialize(buffer, boxed) - case let _1 as Api.PeerBlocked: - _1.serialize(buffer, boxed) - case let _1 as Api.PeerColor: - _1.serialize(buffer, boxed) - case let _1 as Api.PeerLocated: - _1.serialize(buffer, boxed) - case let _1 as Api.PeerNotifySettings: - _1.serialize(buffer, boxed) - case let _1 as Api.PeerSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.PeerStories: - _1.serialize(buffer, boxed) - case let _1 as Api.PendingSuggestion: - _1.serialize(buffer, boxed) - case let _1 as Api.PhoneCall: - _1.serialize(buffer, boxed) - case let _1 as Api.PhoneCallDiscardReason: - _1.serialize(buffer, boxed) - case let _1 as Api.PhoneCallProtocol: - _1.serialize(buffer, boxed) - case let _1 as Api.PhoneConnection: - _1.serialize(buffer, boxed) - case let _1 as Api.Photo: - _1.serialize(buffer, boxed) - case let _1 as Api.PhotoSize: - _1.serialize(buffer, boxed) - case let _1 as Api.Poll: - _1.serialize(buffer, boxed) - case let _1 as Api.PollAnswer: - _1.serialize(buffer, boxed) - case let _1 as Api.PollAnswerVoters: - _1.serialize(buffer, boxed) - case let _1 as Api.PollResults: - _1.serialize(buffer, boxed) - case let _1 as Api.PopularContact: - _1.serialize(buffer, boxed) - case let _1 as Api.PostAddress: - _1.serialize(buffer, boxed) - case let _1 as Api.PostInteractionCounters: - _1.serialize(buffer, boxed) - case let _1 as Api.PremiumGiftCodeOption: - _1.serialize(buffer, boxed) - case let _1 as Api.PremiumSubscriptionOption: - _1.serialize(buffer, boxed) - case let _1 as Api.PrepaidGiveaway: - _1.serialize(buffer, boxed) - case let _1 as Api.PrivacyKey: - _1.serialize(buffer, boxed) - case let _1 as Api.PrivacyRule: - _1.serialize(buffer, boxed) - case let _1 as Api.ProfileTab: - _1.serialize(buffer, boxed) - case let _1 as Api.PublicForward: - _1.serialize(buffer, boxed) - case let _1 as Api.QuickReply: - _1.serialize(buffer, boxed) - case let _1 as Api.Reaction: - _1.serialize(buffer, boxed) - case let _1 as Api.ReactionCount: - _1.serialize(buffer, boxed) - case let _1 as Api.ReactionNotificationsFrom: - _1.serialize(buffer, boxed) - case let _1 as Api.ReactionsNotifySettings: - _1.serialize(buffer, boxed) - case let _1 as Api.ReadParticipantDate: - _1.serialize(buffer, boxed) - case let _1 as Api.ReceivedNotifyMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.RecentMeUrl: - _1.serialize(buffer, boxed) - case let _1 as Api.RecentStory: - _1.serialize(buffer, boxed) - case let _1 as Api.ReplyMarkup: - _1.serialize(buffer, boxed) - case let _1 as Api.ReportReason: - _1.serialize(buffer, boxed) - case let _1 as Api.ReportResult: - _1.serialize(buffer, boxed) - case let _1 as Api.RequestPeerType: - _1.serialize(buffer, boxed) - case let _1 as Api.RequestedPeer: - _1.serialize(buffer, boxed) - case let _1 as Api.RequirementToContact: - _1.serialize(buffer, boxed) - case let _1 as Api.RestrictionReason: - _1.serialize(buffer, boxed) - case let _1 as Api.RichText: - _1.serialize(buffer, boxed) - case let _1 as Api.SavedContact: - _1.serialize(buffer, boxed) - case let _1 as Api.SavedDialog: - _1.serialize(buffer, boxed) - case let _1 as Api.SavedReactionTag: - _1.serialize(buffer, boxed) - case let _1 as Api.SavedStarGift: - _1.serialize(buffer, boxed) - case let _1 as Api.SearchPostsFlood: - _1.serialize(buffer, boxed) - case let _1 as Api.SearchResultsCalendarPeriod: - _1.serialize(buffer, boxed) - case let _1 as Api.SearchResultsPosition: - _1.serialize(buffer, boxed) - case let _1 as Api.SecureCredentialsEncrypted: - _1.serialize(buffer, boxed) - case let _1 as Api.SecureData: - _1.serialize(buffer, boxed) - case let _1 as Api.SecureFile: - _1.serialize(buffer, boxed) - case let _1 as Api.SecurePasswordKdfAlgo: - _1.serialize(buffer, boxed) - case let _1 as Api.SecurePlainData: - _1.serialize(buffer, boxed) - case let _1 as Api.SecureRequiredType: - _1.serialize(buffer, boxed) - case let _1 as Api.SecureSecretSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.SecureValue: - _1.serialize(buffer, boxed) - case let _1 as Api.SecureValueError: - _1.serialize(buffer, boxed) - case let _1 as Api.SecureValueHash: - _1.serialize(buffer, boxed) - case let _1 as Api.SecureValueType: - _1.serialize(buffer, boxed) - case let _1 as Api.SendAsPeer: - _1.serialize(buffer, boxed) - case let _1 as Api.SendMessageAction: - _1.serialize(buffer, boxed) - case let _1 as Api.ShippingOption: - _1.serialize(buffer, boxed) - case let _1 as Api.SmsJob: - _1.serialize(buffer, boxed) - case let _1 as Api.SponsoredMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.SponsoredMessageReportOption: - _1.serialize(buffer, boxed) - case let _1 as Api.SponsoredPeer: - _1.serialize(buffer, boxed) - case let _1 as Api.StarGift: - _1.serialize(buffer, boxed) - case let _1 as Api.StarGiftActiveAuctionState: - _1.serialize(buffer, boxed) - case let _1 as Api.StarGiftAttribute: - _1.serialize(buffer, boxed) - case let _1 as Api.StarGiftAttributeCounter: - _1.serialize(buffer, boxed) - case let _1 as Api.StarGiftAttributeId: - _1.serialize(buffer, boxed) - case let _1 as Api.StarGiftAuctionAcquiredGift: - _1.serialize(buffer, boxed) - case let _1 as Api.StarGiftAuctionRound: - _1.serialize(buffer, boxed) - case let _1 as Api.StarGiftAuctionState: - _1.serialize(buffer, boxed) - case let _1 as Api.StarGiftAuctionUserState: - _1.serialize(buffer, boxed) - case let _1 as Api.StarGiftBackground: - _1.serialize(buffer, boxed) - case let _1 as Api.StarGiftCollection: - _1.serialize(buffer, boxed) - case let _1 as Api.StarGiftUpgradePrice: - _1.serialize(buffer, boxed) - case let _1 as Api.StarRefProgram: - _1.serialize(buffer, boxed) - case let _1 as Api.StarsAmount: - _1.serialize(buffer, boxed) - case let _1 as Api.StarsGiftOption: - _1.serialize(buffer, boxed) - case let _1 as Api.StarsGiveawayOption: - _1.serialize(buffer, boxed) - case let _1 as Api.StarsGiveawayWinnersOption: - _1.serialize(buffer, boxed) - case let _1 as Api.StarsRating: - _1.serialize(buffer, boxed) - case let _1 as Api.StarsRevenueStatus: - _1.serialize(buffer, boxed) - case let _1 as Api.StarsSubscription: - _1.serialize(buffer, boxed) - case let _1 as Api.StarsSubscriptionPricing: - _1.serialize(buffer, boxed) - case let _1 as Api.StarsTopupOption: - _1.serialize(buffer, boxed) - case let _1 as Api.StarsTransaction: - _1.serialize(buffer, boxed) - case let _1 as Api.StarsTransactionPeer: - _1.serialize(buffer, boxed) - case let _1 as Api.StatsAbsValueAndPrev: - _1.serialize(buffer, boxed) - case let _1 as Api.StatsDateRangeDays: - _1.serialize(buffer, boxed) - case let _1 as Api.StatsGraph: - _1.serialize(buffer, boxed) - case let _1 as Api.StatsGroupTopAdmin: - _1.serialize(buffer, boxed) - case let _1 as Api.StatsGroupTopInviter: - _1.serialize(buffer, boxed) - case let _1 as Api.StatsGroupTopPoster: - _1.serialize(buffer, boxed) - case let _1 as Api.StatsPercentValue: - _1.serialize(buffer, boxed) - case let _1 as Api.StatsURL: - _1.serialize(buffer, boxed) - case let _1 as Api.StickerKeyword: - _1.serialize(buffer, boxed) - case let _1 as Api.StickerPack: - _1.serialize(buffer, boxed) - case let _1 as Api.StickerSet: - _1.serialize(buffer, boxed) - case let _1 as Api.StickerSetCovered: - _1.serialize(buffer, boxed) - case let _1 as Api.StoriesStealthMode: - _1.serialize(buffer, boxed) - case let _1 as Api.StoryAlbum: - _1.serialize(buffer, boxed) - case let _1 as Api.StoryFwdHeader: - _1.serialize(buffer, boxed) - case let _1 as Api.StoryItem: - _1.serialize(buffer, boxed) - case let _1 as Api.StoryReaction: - _1.serialize(buffer, boxed) - case let _1 as Api.StoryView: - _1.serialize(buffer, boxed) - case let _1 as Api.StoryViews: - _1.serialize(buffer, boxed) - case let _1 as Api.SuggestedPost: - _1.serialize(buffer, boxed) - case let _1 as Api.TextWithEntities: - _1.serialize(buffer, boxed) - case let _1 as Api.Theme: - _1.serialize(buffer, boxed) - case let _1 as Api.ThemeSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.Timezone: - _1.serialize(buffer, boxed) - case let _1 as Api.TodoCompletion: - _1.serialize(buffer, boxed) - case let _1 as Api.TodoItem: - _1.serialize(buffer, boxed) - case let _1 as Api.TodoList: - _1.serialize(buffer, boxed) - case let _1 as Api.TopPeer: - _1.serialize(buffer, boxed) - case let _1 as Api.TopPeerCategory: - _1.serialize(buffer, boxed) - case let _1 as Api.TopPeerCategoryPeers: - _1.serialize(buffer, boxed) - case let _1 as Api.Update: - _1.serialize(buffer, boxed) - case let _1 as Api.Updates: - _1.serialize(buffer, boxed) - case let _1 as Api.UrlAuthResult: - _1.serialize(buffer, boxed) - case let _1 as Api.User: - _1.serialize(buffer, boxed) - case let _1 as Api.UserFull: - _1.serialize(buffer, boxed) - case let _1 as Api.UserProfilePhoto: - _1.serialize(buffer, boxed) - case let _1 as Api.UserStatus: - _1.serialize(buffer, boxed) - case let _1 as Api.Username: - _1.serialize(buffer, boxed) - case let _1 as Api.VideoSize: - _1.serialize(buffer, boxed) - case let _1 as Api.WallPaper: - _1.serialize(buffer, boxed) - case let _1 as Api.WallPaperSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.WebAuthorization: - _1.serialize(buffer, boxed) - case let _1 as Api.WebDocument: - _1.serialize(buffer, boxed) - case let _1 as Api.WebPage: - _1.serialize(buffer, boxed) - case let _1 as Api.WebPageAttribute: - _1.serialize(buffer, boxed) - case let _1 as Api.WebViewMessageSent: - _1.serialize(buffer, boxed) - case let _1 as Api.WebViewResult: - _1.serialize(buffer, boxed) - case let _1 as Api.account.AuthorizationForm: - _1.serialize(buffer, boxed) - case let _1 as Api.account.Authorizations: - _1.serialize(buffer, boxed) - case let _1 as Api.account.AutoDownloadSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.account.AutoSaveSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.account.BusinessChatLinks: - _1.serialize(buffer, boxed) - case let _1 as Api.account.ChatThemes: - _1.serialize(buffer, boxed) - case let _1 as Api.account.ConnectedBots: - _1.serialize(buffer, boxed) - case let _1 as Api.account.ContentSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.account.EmailVerified: - _1.serialize(buffer, boxed) - case let _1 as Api.account.EmojiStatuses: - _1.serialize(buffer, boxed) - case let _1 as Api.account.PaidMessagesRevenue: - _1.serialize(buffer, boxed) - case let _1 as Api.account.PasskeyRegistrationOptions: - _1.serialize(buffer, boxed) - case let _1 as Api.account.Passkeys: - _1.serialize(buffer, boxed) - case let _1 as Api.account.Password: - _1.serialize(buffer, boxed) - case let _1 as Api.account.PasswordInputSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.account.PasswordSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.account.PrivacyRules: - _1.serialize(buffer, boxed) - case let _1 as Api.account.ResetPasswordResult: - _1.serialize(buffer, boxed) - case let _1 as Api.account.ResolvedBusinessChatLinks: - _1.serialize(buffer, boxed) - case let _1 as Api.account.SavedMusicIds: - _1.serialize(buffer, boxed) - case let _1 as Api.account.SavedRingtone: - _1.serialize(buffer, boxed) - case let _1 as Api.account.SavedRingtones: - _1.serialize(buffer, boxed) - case let _1 as Api.account.SentEmailCode: - _1.serialize(buffer, boxed) - case let _1 as Api.account.Takeout: - _1.serialize(buffer, boxed) - case let _1 as Api.account.Themes: - _1.serialize(buffer, boxed) - case let _1 as Api.account.TmpPassword: - _1.serialize(buffer, boxed) - case let _1 as Api.account.WallPapers: - _1.serialize(buffer, boxed) - case let _1 as Api.account.WebAuthorizations: - _1.serialize(buffer, boxed) - case let _1 as Api.auth.Authorization: - _1.serialize(buffer, boxed) - case let _1 as Api.auth.CodeType: - _1.serialize(buffer, boxed) - case let _1 as Api.auth.ExportedAuthorization: - _1.serialize(buffer, boxed) - case let _1 as Api.auth.LoggedOut: - _1.serialize(buffer, boxed) - case let _1 as Api.auth.LoginToken: - _1.serialize(buffer, boxed) - case let _1 as Api.auth.PasskeyLoginOptions: - _1.serialize(buffer, boxed) - case let _1 as Api.auth.PasswordRecovery: - _1.serialize(buffer, boxed) - case let _1 as Api.auth.SentCode: - _1.serialize(buffer, boxed) - case let _1 as Api.auth.SentCodeType: - _1.serialize(buffer, boxed) - case let _1 as Api.bots.BotInfo: - _1.serialize(buffer, boxed) - case let _1 as Api.bots.PopularAppBots: - _1.serialize(buffer, boxed) - case let _1 as Api.bots.PreviewInfo: - _1.serialize(buffer, boxed) - case let _1 as Api.channels.AdminLogResults: - _1.serialize(buffer, boxed) - case let _1 as Api.channels.ChannelParticipant: - _1.serialize(buffer, boxed) - case let _1 as Api.channels.ChannelParticipants: - _1.serialize(buffer, boxed) - case let _1 as Api.channels.SendAsPeers: - _1.serialize(buffer, boxed) - case let _1 as Api.channels.SponsoredMessageReportResult: - _1.serialize(buffer, boxed) - case let _1 as Api.chatlists.ChatlistInvite: - _1.serialize(buffer, boxed) - case let _1 as Api.chatlists.ChatlistUpdates: - _1.serialize(buffer, boxed) - case let _1 as Api.chatlists.ExportedChatlistInvite: - _1.serialize(buffer, boxed) - case let _1 as Api.chatlists.ExportedInvites: - _1.serialize(buffer, boxed) - case let _1 as Api.contacts.Blocked: - _1.serialize(buffer, boxed) - case let _1 as Api.contacts.ContactBirthdays: - _1.serialize(buffer, boxed) - case let _1 as Api.contacts.Contacts: - _1.serialize(buffer, boxed) - case let _1 as Api.contacts.Found: - _1.serialize(buffer, boxed) - case let _1 as Api.contacts.ImportedContacts: - _1.serialize(buffer, boxed) - case let _1 as Api.contacts.ResolvedPeer: - _1.serialize(buffer, boxed) - case let _1 as Api.contacts.SponsoredPeers: - _1.serialize(buffer, boxed) - case let _1 as Api.contacts.TopPeers: - _1.serialize(buffer, boxed) - case let _1 as Api.fragment.CollectibleInfo: - _1.serialize(buffer, boxed) - case let _1 as Api.help.AppConfig: - _1.serialize(buffer, boxed) - case let _1 as Api.help.AppUpdate: - _1.serialize(buffer, boxed) - case let _1 as Api.help.CountriesList: - _1.serialize(buffer, boxed) - case let _1 as Api.help.Country: - _1.serialize(buffer, boxed) - case let _1 as Api.help.CountryCode: - _1.serialize(buffer, boxed) - case let _1 as Api.help.DeepLinkInfo: - _1.serialize(buffer, boxed) - case let _1 as Api.help.InviteText: - _1.serialize(buffer, boxed) - case let _1 as Api.help.PassportConfig: - _1.serialize(buffer, boxed) - case let _1 as Api.help.PeerColorOption: - _1.serialize(buffer, boxed) - case let _1 as Api.help.PeerColorSet: - _1.serialize(buffer, boxed) - case let _1 as Api.help.PeerColors: - _1.serialize(buffer, boxed) - case let _1 as Api.help.PremiumPromo: - _1.serialize(buffer, boxed) - case let _1 as Api.help.PromoData: - _1.serialize(buffer, boxed) - case let _1 as Api.help.RecentMeUrls: - _1.serialize(buffer, boxed) - case let _1 as Api.help.Support: - _1.serialize(buffer, boxed) - case let _1 as Api.help.SupportName: - _1.serialize(buffer, boxed) - case let _1 as Api.help.TermsOfService: - _1.serialize(buffer, boxed) - case let _1 as Api.help.TermsOfServiceUpdate: - _1.serialize(buffer, boxed) - case let _1 as Api.help.TimezonesList: - _1.serialize(buffer, boxed) - case let _1 as Api.help.UserInfo: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.AffectedFoundMessages: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.AffectedHistory: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.AffectedMessages: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.AllStickers: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.ArchivedStickers: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.AvailableEffects: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.AvailableReactions: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.BotApp: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.BotCallbackAnswer: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.BotPreparedInlineMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.BotResults: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.ChatAdminsWithInvites: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.ChatFull: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.ChatInviteImporters: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.Chats: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.CheckedHistoryImportPeer: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.DhConfig: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.DialogFilters: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.Dialogs: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.DiscussionMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.EmojiGameInfo: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.EmojiGameOutcome: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.EmojiGroups: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.ExportedChatInvite: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.ExportedChatInvites: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.FavedStickers: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.FeaturedStickers: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.ForumTopics: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.FoundStickerSets: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.FoundStickers: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.HighScores: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.HistoryImport: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.HistoryImportParsed: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.InactiveChats: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.InvitedUsers: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.MessageEditData: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.MessageReactionsList: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.MessageViews: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.Messages: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.MyStickers: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.PeerDialogs: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.PeerSettings: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.PreparedInlineMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.QuickReplies: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.Reactions: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.RecentStickers: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.SavedDialogs: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.SavedGifs: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.SavedReactionTags: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.SearchCounter: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.SearchResultsCalendar: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.SearchResultsPositions: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.SentEncryptedMessage: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.SponsoredMessages: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.StickerSet: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.StickerSetInstallResult: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.Stickers: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.TranscribedAudio: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.TranslatedText: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.VotesList: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.WebPage: - _1.serialize(buffer, boxed) - case let _1 as Api.messages.WebPagePreview: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.BankCardData: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.CheckCanSendGiftResult: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.CheckedGiftCode: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.ConnectedStarRefBots: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.ExportedInvoice: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.GiveawayInfo: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.PaymentForm: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.PaymentReceipt: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.PaymentResult: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.ResaleStarGifts: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.SavedInfo: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.SavedStarGifts: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.StarGiftActiveAuctions: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.StarGiftAuctionAcquiredGifts: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.StarGiftAuctionState: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.StarGiftCollections: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.StarGiftUpgradeAttributes: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.StarGiftUpgradePreview: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.StarGiftWithdrawalUrl: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.StarGifts: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.StarsRevenueAdsAccountUrl: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.StarsRevenueStats: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.StarsRevenueWithdrawalUrl: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.StarsStatus: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.SuggestedStarRefBots: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.UniqueStarGift: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.UniqueStarGiftValueInfo: - _1.serialize(buffer, boxed) - case let _1 as Api.payments.ValidatedRequestedInfo: - _1.serialize(buffer, boxed) - case let _1 as Api.phone.ExportedGroupCallInvite: - _1.serialize(buffer, boxed) - case let _1 as Api.phone.GroupCall: - _1.serialize(buffer, boxed) - case let _1 as Api.phone.GroupCallStars: - _1.serialize(buffer, boxed) - case let _1 as Api.phone.GroupCallStreamChannels: - _1.serialize(buffer, boxed) - case let _1 as Api.phone.GroupCallStreamRtmpUrl: - _1.serialize(buffer, boxed) - case let _1 as Api.phone.GroupParticipants: - _1.serialize(buffer, boxed) - case let _1 as Api.phone.JoinAsPeers: - _1.serialize(buffer, boxed) - case let _1 as Api.phone.PhoneCall: - _1.serialize(buffer, boxed) - case let _1 as Api.photos.Photo: - _1.serialize(buffer, boxed) - case let _1 as Api.photos.Photos: - _1.serialize(buffer, boxed) - case let _1 as Api.premium.BoostsList: - _1.serialize(buffer, boxed) - case let _1 as Api.premium.BoostsStatus: - _1.serialize(buffer, boxed) - case let _1 as Api.premium.MyBoosts: - _1.serialize(buffer, boxed) - case let _1 as Api.smsjobs.EligibilityToJoin: - _1.serialize(buffer, boxed) - case let _1 as Api.smsjobs.Status: - _1.serialize(buffer, boxed) - case let _1 as Api.stats.BroadcastStats: - _1.serialize(buffer, boxed) - case let _1 as Api.stats.MegagroupStats: - _1.serialize(buffer, boxed) - case let _1 as Api.stats.MessageStats: - _1.serialize(buffer, boxed) - case let _1 as Api.stats.PublicForwards: - _1.serialize(buffer, boxed) - case let _1 as Api.stats.StoryStats: - _1.serialize(buffer, boxed) - case let _1 as Api.stickers.SuggestedShortName: - _1.serialize(buffer, boxed) - case let _1 as Api.storage.FileType: - _1.serialize(buffer, boxed) - case let _1 as Api.stories.Albums: - _1.serialize(buffer, boxed) - case let _1 as Api.stories.AllStories: - _1.serialize(buffer, boxed) - case let _1 as Api.stories.CanSendStoryCount: - _1.serialize(buffer, boxed) - case let _1 as Api.stories.FoundStories: - _1.serialize(buffer, boxed) - case let _1 as Api.stories.PeerStories: - _1.serialize(buffer, boxed) - case let _1 as Api.stories.Stories: - _1.serialize(buffer, boxed) - case let _1 as Api.stories.StoryReactionsList: - _1.serialize(buffer, boxed) - case let _1 as Api.stories.StoryViews: - _1.serialize(buffer, boxed) - case let _1 as Api.stories.StoryViewsList: - _1.serialize(buffer, boxed) - case let _1 as Api.updates.ChannelDifference: - _1.serialize(buffer, boxed) - case let _1 as Api.updates.Difference: - _1.serialize(buffer, boxed) - case let _1 as Api.updates.State: - _1.serialize(buffer, boxed) - case let _1 as Api.upload.CdnFile: - _1.serialize(buffer, boxed) - case let _1 as Api.upload.File: - _1.serialize(buffer, boxed) - case let _1 as Api.upload.WebFile: - _1.serialize(buffer, boxed) - case let _1 as Api.users.SavedMusic: - _1.serialize(buffer, boxed) - case let _1 as Api.users.UserFull: - _1.serialize(buffer, boxed) - case let _1 as Api.users.Users: - _1.serialize(buffer, boxed) - default: - break + case let _1 as Api.AccountDaysTTL: + _1.serialize(buffer, boxed) + case let _1 as Api.AttachMenuBot: + _1.serialize(buffer, boxed) + case let _1 as Api.AttachMenuBotIcon: + _1.serialize(buffer, boxed) + case let _1 as Api.AttachMenuBotIconColor: + _1.serialize(buffer, boxed) + case let _1 as Api.AttachMenuBots: + _1.serialize(buffer, boxed) + case let _1 as Api.AttachMenuBotsBot: + _1.serialize(buffer, boxed) + case let _1 as Api.AttachMenuPeerType: + _1.serialize(buffer, boxed) + case let _1 as Api.AuctionBidLevel: + _1.serialize(buffer, boxed) + case let _1 as Api.Authorization: + _1.serialize(buffer, boxed) + case let _1 as Api.AutoDownloadSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.AutoSaveException: + _1.serialize(buffer, boxed) + case let _1 as Api.AutoSaveSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.AvailableEffect: + _1.serialize(buffer, boxed) + case let _1 as Api.AvailableReaction: + _1.serialize(buffer, boxed) + case let _1 as Api.BankCardOpenUrl: + _1.serialize(buffer, boxed) + case let _1 as Api.BaseTheme: + _1.serialize(buffer, boxed) + case let _1 as Api.Birthday: + _1.serialize(buffer, boxed) + case let _1 as Api.Bool: + _1.serialize(buffer, boxed) + case let _1 as Api.Boost: + _1.serialize(buffer, boxed) + case let _1 as Api.BotApp: + _1.serialize(buffer, boxed) + case let _1 as Api.BotAppSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.BotBusinessConnection: + _1.serialize(buffer, boxed) + case let _1 as Api.BotCommand: + _1.serialize(buffer, boxed) + case let _1 as Api.BotCommandScope: + _1.serialize(buffer, boxed) + case let _1 as Api.BotInfo: + _1.serialize(buffer, boxed) + case let _1 as Api.BotInlineMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.BotInlineResult: + _1.serialize(buffer, boxed) + case let _1 as Api.BotMenuButton: + _1.serialize(buffer, boxed) + case let _1 as Api.BotPreviewMedia: + _1.serialize(buffer, boxed) + case let _1 as Api.BotVerification: + _1.serialize(buffer, boxed) + case let _1 as Api.BotVerifierSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.BusinessAwayMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.BusinessAwayMessageSchedule: + _1.serialize(buffer, boxed) + case let _1 as Api.BusinessBotRecipients: + _1.serialize(buffer, boxed) + case let _1 as Api.BusinessBotRights: + _1.serialize(buffer, boxed) + case let _1 as Api.BusinessChatLink: + _1.serialize(buffer, boxed) + case let _1 as Api.BusinessGreetingMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.BusinessIntro: + _1.serialize(buffer, boxed) + case let _1 as Api.BusinessLocation: + _1.serialize(buffer, boxed) + case let _1 as Api.BusinessRecipients: + _1.serialize(buffer, boxed) + case let _1 as Api.BusinessWeeklyOpen: + _1.serialize(buffer, boxed) + case let _1 as Api.BusinessWorkHours: + _1.serialize(buffer, boxed) + case let _1 as Api.CdnConfig: + _1.serialize(buffer, boxed) + case let _1 as Api.CdnPublicKey: + _1.serialize(buffer, boxed) + case let _1 as Api.ChannelAdminLogEvent: + _1.serialize(buffer, boxed) + case let _1 as Api.ChannelAdminLogEventAction: + _1.serialize(buffer, boxed) + case let _1 as Api.ChannelAdminLogEventsFilter: + _1.serialize(buffer, boxed) + case let _1 as Api.ChannelLocation: + _1.serialize(buffer, boxed) + case let _1 as Api.ChannelMessagesFilter: + _1.serialize(buffer, boxed) + case let _1 as Api.ChannelParticipant: + _1.serialize(buffer, boxed) + case let _1 as Api.ChannelParticipantsFilter: + _1.serialize(buffer, boxed) + case let _1 as Api.Chat: + _1.serialize(buffer, boxed) + case let _1 as Api.ChatAdminRights: + _1.serialize(buffer, boxed) + case let _1 as Api.ChatAdminWithInvites: + _1.serialize(buffer, boxed) + case let _1 as Api.ChatBannedRights: + _1.serialize(buffer, boxed) + case let _1 as Api.ChatFull: + _1.serialize(buffer, boxed) + case let _1 as Api.ChatInvite: + _1.serialize(buffer, boxed) + case let _1 as Api.ChatInviteImporter: + _1.serialize(buffer, boxed) + case let _1 as Api.ChatOnlines: + _1.serialize(buffer, boxed) + case let _1 as Api.ChatParticipant: + _1.serialize(buffer, boxed) + case let _1 as Api.ChatParticipants: + _1.serialize(buffer, boxed) + case let _1 as Api.ChatPhoto: + _1.serialize(buffer, boxed) + case let _1 as Api.ChatReactions: + _1.serialize(buffer, boxed) + case let _1 as Api.ChatTheme: + _1.serialize(buffer, boxed) + case let _1 as Api.CodeSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.Config: + _1.serialize(buffer, boxed) + case let _1 as Api.ConnectedBot: + _1.serialize(buffer, boxed) + case let _1 as Api.ConnectedBotStarRef: + _1.serialize(buffer, boxed) + case let _1 as Api.Contact: + _1.serialize(buffer, boxed) + case let _1 as Api.ContactBirthday: + _1.serialize(buffer, boxed) + case let _1 as Api.ContactStatus: + _1.serialize(buffer, boxed) + case let _1 as Api.DataJSON: + _1.serialize(buffer, boxed) + case let _1 as Api.DcOption: + _1.serialize(buffer, boxed) + case let _1 as Api.DefaultHistoryTTL: + _1.serialize(buffer, boxed) + case let _1 as Api.Dialog: + _1.serialize(buffer, boxed) + case let _1 as Api.DialogFilter: + _1.serialize(buffer, boxed) + case let _1 as Api.DialogFilterSuggested: + _1.serialize(buffer, boxed) + case let _1 as Api.DialogPeer: + _1.serialize(buffer, boxed) + case let _1 as Api.DisallowedGiftsSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.Document: + _1.serialize(buffer, boxed) + case let _1 as Api.DocumentAttribute: + _1.serialize(buffer, boxed) + case let _1 as Api.DraftMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.EmailVerification: + _1.serialize(buffer, boxed) + case let _1 as Api.EmailVerifyPurpose: + _1.serialize(buffer, boxed) + case let _1 as Api.EmojiGroup: + _1.serialize(buffer, boxed) + case let _1 as Api.EmojiKeyword: + _1.serialize(buffer, boxed) + case let _1 as Api.EmojiKeywordsDifference: + _1.serialize(buffer, boxed) + case let _1 as Api.EmojiLanguage: + _1.serialize(buffer, boxed) + case let _1 as Api.EmojiList: + _1.serialize(buffer, boxed) + case let _1 as Api.EmojiStatus: + _1.serialize(buffer, boxed) + case let _1 as Api.EmojiURL: + _1.serialize(buffer, boxed) + case let _1 as Api.EncryptedChat: + _1.serialize(buffer, boxed) + case let _1 as Api.EncryptedFile: + _1.serialize(buffer, boxed) + case let _1 as Api.EncryptedMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.ExportedChatInvite: + _1.serialize(buffer, boxed) + case let _1 as Api.ExportedChatlistInvite: + _1.serialize(buffer, boxed) + case let _1 as Api.ExportedContactToken: + _1.serialize(buffer, boxed) + case let _1 as Api.ExportedMessageLink: + _1.serialize(buffer, boxed) + case let _1 as Api.ExportedStoryLink: + _1.serialize(buffer, boxed) + case let _1 as Api.FactCheck: + _1.serialize(buffer, boxed) + case let _1 as Api.FileHash: + _1.serialize(buffer, boxed) + case let _1 as Api.Folder: + _1.serialize(buffer, boxed) + case let _1 as Api.FolderPeer: + _1.serialize(buffer, boxed) + case let _1 as Api.ForumTopic: + _1.serialize(buffer, boxed) + case let _1 as Api.FoundStory: + _1.serialize(buffer, boxed) + case let _1 as Api.Game: + _1.serialize(buffer, boxed) + case let _1 as Api.GeoPoint: + _1.serialize(buffer, boxed) + case let _1 as Api.GeoPointAddress: + _1.serialize(buffer, boxed) + case let _1 as Api.GlobalPrivacySettings: + _1.serialize(buffer, boxed) + case let _1 as Api.GroupCall: + _1.serialize(buffer, boxed) + case let _1 as Api.GroupCallDonor: + _1.serialize(buffer, boxed) + case let _1 as Api.GroupCallMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.GroupCallParticipant: + _1.serialize(buffer, boxed) + case let _1 as Api.GroupCallParticipantVideo: + _1.serialize(buffer, boxed) + case let _1 as Api.GroupCallParticipantVideoSourceGroup: + _1.serialize(buffer, boxed) + case let _1 as Api.GroupCallStreamChannel: + _1.serialize(buffer, boxed) + case let _1 as Api.HighScore: + _1.serialize(buffer, boxed) + case let _1 as Api.ImportedContact: + _1.serialize(buffer, boxed) + case let _1 as Api.InlineBotSwitchPM: + _1.serialize(buffer, boxed) + case let _1 as Api.InlineBotWebView: + _1.serialize(buffer, boxed) + case let _1 as Api.InlineQueryPeerType: + _1.serialize(buffer, boxed) + case let _1 as Api.InputAppEvent: + _1.serialize(buffer, boxed) + case let _1 as Api.InputBotApp: + _1.serialize(buffer, boxed) + case let _1 as Api.InputBotInlineMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.InputBotInlineMessageID: + _1.serialize(buffer, boxed) + case let _1 as Api.InputBotInlineResult: + _1.serialize(buffer, boxed) + case let _1 as Api.InputBusinessAwayMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.InputBusinessBotRecipients: + _1.serialize(buffer, boxed) + case let _1 as Api.InputBusinessChatLink: + _1.serialize(buffer, boxed) + case let _1 as Api.InputBusinessGreetingMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.InputBusinessIntro: + _1.serialize(buffer, boxed) + case let _1 as Api.InputBusinessRecipients: + _1.serialize(buffer, boxed) + case let _1 as Api.InputChannel: + _1.serialize(buffer, boxed) + case let _1 as Api.InputChatPhoto: + _1.serialize(buffer, boxed) + case let _1 as Api.InputChatTheme: + _1.serialize(buffer, boxed) + case let _1 as Api.InputChatlist: + _1.serialize(buffer, boxed) + case let _1 as Api.InputCheckPasswordSRP: + _1.serialize(buffer, boxed) + case let _1 as Api.InputClientProxy: + _1.serialize(buffer, boxed) + case let _1 as Api.InputCollectible: + _1.serialize(buffer, boxed) + case let _1 as Api.InputContact: + _1.serialize(buffer, boxed) + case let _1 as Api.InputDialogPeer: + _1.serialize(buffer, boxed) + case let _1 as Api.InputDocument: + _1.serialize(buffer, boxed) + case let _1 as Api.InputEncryptedChat: + _1.serialize(buffer, boxed) + case let _1 as Api.InputEncryptedFile: + _1.serialize(buffer, boxed) + case let _1 as Api.InputFile: + _1.serialize(buffer, boxed) + case let _1 as Api.InputFileLocation: + _1.serialize(buffer, boxed) + case let _1 as Api.InputFolderPeer: + _1.serialize(buffer, boxed) + case let _1 as Api.InputGame: + _1.serialize(buffer, boxed) + case let _1 as Api.InputGeoPoint: + _1.serialize(buffer, boxed) + case let _1 as Api.InputGroupCall: + _1.serialize(buffer, boxed) + case let _1 as Api.InputInvoice: + _1.serialize(buffer, boxed) + case let _1 as Api.InputMedia: + _1.serialize(buffer, boxed) + case let _1 as Api.InputMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.InputNotifyPeer: + _1.serialize(buffer, boxed) + case let _1 as Api.InputPasskeyCredential: + _1.serialize(buffer, boxed) + case let _1 as Api.InputPasskeyResponse: + _1.serialize(buffer, boxed) + case let _1 as Api.InputPaymentCredentials: + _1.serialize(buffer, boxed) + case let _1 as Api.InputPeer: + _1.serialize(buffer, boxed) + case let _1 as Api.InputPeerNotifySettings: + _1.serialize(buffer, boxed) + case let _1 as Api.InputPhoneCall: + _1.serialize(buffer, boxed) + case let _1 as Api.InputPhoto: + _1.serialize(buffer, boxed) + case let _1 as Api.InputPrivacyKey: + _1.serialize(buffer, boxed) + case let _1 as Api.InputPrivacyRule: + _1.serialize(buffer, boxed) + case let _1 as Api.InputQuickReplyShortcut: + _1.serialize(buffer, boxed) + case let _1 as Api.InputReplyTo: + _1.serialize(buffer, boxed) + case let _1 as Api.InputSavedStarGift: + _1.serialize(buffer, boxed) + case let _1 as Api.InputSecureFile: + _1.serialize(buffer, boxed) + case let _1 as Api.InputSecureValue: + _1.serialize(buffer, boxed) + case let _1 as Api.InputSingleMedia: + _1.serialize(buffer, boxed) + case let _1 as Api.InputStarGiftAuction: + _1.serialize(buffer, boxed) + case let _1 as Api.InputStarsTransaction: + _1.serialize(buffer, boxed) + case let _1 as Api.InputStickerSet: + _1.serialize(buffer, boxed) + case let _1 as Api.InputStickerSetItem: + _1.serialize(buffer, boxed) + case let _1 as Api.InputStickeredMedia: + _1.serialize(buffer, boxed) + case let _1 as Api.InputStorePaymentPurpose: + _1.serialize(buffer, boxed) + case let _1 as Api.InputTheme: + _1.serialize(buffer, boxed) + case let _1 as Api.InputThemeSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.InputUser: + _1.serialize(buffer, boxed) + case let _1 as Api.InputWallPaper: + _1.serialize(buffer, boxed) + case let _1 as Api.InputWebDocument: + _1.serialize(buffer, boxed) + case let _1 as Api.InputWebFileLocation: + _1.serialize(buffer, boxed) + case let _1 as Api.Invoice: + _1.serialize(buffer, boxed) + case let _1 as Api.JSONObjectValue: + _1.serialize(buffer, boxed) + case let _1 as Api.JSONValue: + _1.serialize(buffer, boxed) + case let _1 as Api.KeyboardButton: + _1.serialize(buffer, boxed) + case let _1 as Api.KeyboardButtonRow: + _1.serialize(buffer, boxed) + case let _1 as Api.KeyboardButtonStyle: + _1.serialize(buffer, boxed) + case let _1 as Api.LabeledPrice: + _1.serialize(buffer, boxed) + case let _1 as Api.LangPackDifference: + _1.serialize(buffer, boxed) + case let _1 as Api.LangPackLanguage: + _1.serialize(buffer, boxed) + case let _1 as Api.LangPackString: + _1.serialize(buffer, boxed) + case let _1 as Api.MaskCoords: + _1.serialize(buffer, boxed) + case let _1 as Api.MediaArea: + _1.serialize(buffer, boxed) + case let _1 as Api.MediaAreaCoordinates: + _1.serialize(buffer, boxed) + case let _1 as Api.Message: + _1.serialize(buffer, boxed) + case let _1 as Api.MessageAction: + _1.serialize(buffer, boxed) + case let _1 as Api.MessageEntity: + _1.serialize(buffer, boxed) + case let _1 as Api.MessageExtendedMedia: + _1.serialize(buffer, boxed) + case let _1 as Api.MessageFwdHeader: + _1.serialize(buffer, boxed) + case let _1 as Api.MessageMedia: + _1.serialize(buffer, boxed) + case let _1 as Api.MessagePeerReaction: + _1.serialize(buffer, boxed) + case let _1 as Api.MessagePeerVote: + _1.serialize(buffer, boxed) + case let _1 as Api.MessageRange: + _1.serialize(buffer, boxed) + case let _1 as Api.MessageReactions: + _1.serialize(buffer, boxed) + case let _1 as Api.MessageReactor: + _1.serialize(buffer, boxed) + case let _1 as Api.MessageReplies: + _1.serialize(buffer, boxed) + case let _1 as Api.MessageReplyHeader: + _1.serialize(buffer, boxed) + case let _1 as Api.MessageReportOption: + _1.serialize(buffer, boxed) + case let _1 as Api.MessageViews: + _1.serialize(buffer, boxed) + case let _1 as Api.MessagesFilter: + _1.serialize(buffer, boxed) + case let _1 as Api.MissingInvitee: + _1.serialize(buffer, boxed) + case let _1 as Api.MyBoost: + _1.serialize(buffer, boxed) + case let _1 as Api.NearestDc: + _1.serialize(buffer, boxed) + case let _1 as Api.NotificationSound: + _1.serialize(buffer, boxed) + case let _1 as Api.NotifyPeer: + _1.serialize(buffer, boxed) + case let _1 as Api.OutboxReadDate: + _1.serialize(buffer, boxed) + case let _1 as Api.Page: + _1.serialize(buffer, boxed) + case let _1 as Api.PageBlock: + _1.serialize(buffer, boxed) + case let _1 as Api.PageCaption: + _1.serialize(buffer, boxed) + case let _1 as Api.PageListItem: + _1.serialize(buffer, boxed) + case let _1 as Api.PageListOrderedItem: + _1.serialize(buffer, boxed) + case let _1 as Api.PageRelatedArticle: + _1.serialize(buffer, boxed) + case let _1 as Api.PageTableCell: + _1.serialize(buffer, boxed) + case let _1 as Api.PageTableRow: + _1.serialize(buffer, boxed) + case let _1 as Api.PaidReactionPrivacy: + _1.serialize(buffer, boxed) + case let _1 as Api.Passkey: + _1.serialize(buffer, boxed) + case let _1 as Api.PasswordKdfAlgo: + _1.serialize(buffer, boxed) + case let _1 as Api.PaymentCharge: + _1.serialize(buffer, boxed) + case let _1 as Api.PaymentFormMethod: + _1.serialize(buffer, boxed) + case let _1 as Api.PaymentRequestedInfo: + _1.serialize(buffer, boxed) + case let _1 as Api.PaymentSavedCredentials: + _1.serialize(buffer, boxed) + case let _1 as Api.Peer: + _1.serialize(buffer, boxed) + case let _1 as Api.PeerBlocked: + _1.serialize(buffer, boxed) + case let _1 as Api.PeerColor: + _1.serialize(buffer, boxed) + case let _1 as Api.PeerLocated: + _1.serialize(buffer, boxed) + case let _1 as Api.PeerNotifySettings: + _1.serialize(buffer, boxed) + case let _1 as Api.PeerSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.PeerStories: + _1.serialize(buffer, boxed) + case let _1 as Api.PendingSuggestion: + _1.serialize(buffer, boxed) + case let _1 as Api.PhoneCall: + _1.serialize(buffer, boxed) + case let _1 as Api.PhoneCallDiscardReason: + _1.serialize(buffer, boxed) + case let _1 as Api.PhoneCallProtocol: + _1.serialize(buffer, boxed) + case let _1 as Api.PhoneConnection: + _1.serialize(buffer, boxed) + case let _1 as Api.Photo: + _1.serialize(buffer, boxed) + case let _1 as Api.PhotoSize: + _1.serialize(buffer, boxed) + case let _1 as Api.Poll: + _1.serialize(buffer, boxed) + case let _1 as Api.PollAnswer: + _1.serialize(buffer, boxed) + case let _1 as Api.PollAnswerVoters: + _1.serialize(buffer, boxed) + case let _1 as Api.PollResults: + _1.serialize(buffer, boxed) + case let _1 as Api.PopularContact: + _1.serialize(buffer, boxed) + case let _1 as Api.PostAddress: + _1.serialize(buffer, boxed) + case let _1 as Api.PostInteractionCounters: + _1.serialize(buffer, boxed) + case let _1 as Api.PremiumGiftCodeOption: + _1.serialize(buffer, boxed) + case let _1 as Api.PremiumSubscriptionOption: + _1.serialize(buffer, boxed) + case let _1 as Api.PrepaidGiveaway: + _1.serialize(buffer, boxed) + case let _1 as Api.PrivacyKey: + _1.serialize(buffer, boxed) + case let _1 as Api.PrivacyRule: + _1.serialize(buffer, boxed) + case let _1 as Api.ProfileTab: + _1.serialize(buffer, boxed) + case let _1 as Api.PublicForward: + _1.serialize(buffer, boxed) + case let _1 as Api.QuickReply: + _1.serialize(buffer, boxed) + case let _1 as Api.Reaction: + _1.serialize(buffer, boxed) + case let _1 as Api.ReactionCount: + _1.serialize(buffer, boxed) + case let _1 as Api.ReactionNotificationsFrom: + _1.serialize(buffer, boxed) + case let _1 as Api.ReactionsNotifySettings: + _1.serialize(buffer, boxed) + case let _1 as Api.ReadParticipantDate: + _1.serialize(buffer, boxed) + case let _1 as Api.ReceivedNotifyMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.RecentMeUrl: + _1.serialize(buffer, boxed) + case let _1 as Api.RecentStory: + _1.serialize(buffer, boxed) + case let _1 as Api.ReplyMarkup: + _1.serialize(buffer, boxed) + case let _1 as Api.ReportReason: + _1.serialize(buffer, boxed) + case let _1 as Api.ReportResult: + _1.serialize(buffer, boxed) + case let _1 as Api.RequestPeerType: + _1.serialize(buffer, boxed) + case let _1 as Api.RequestedPeer: + _1.serialize(buffer, boxed) + case let _1 as Api.RequirementToContact: + _1.serialize(buffer, boxed) + case let _1 as Api.RestrictionReason: + _1.serialize(buffer, boxed) + case let _1 as Api.RichText: + _1.serialize(buffer, boxed) + case let _1 as Api.SavedContact: + _1.serialize(buffer, boxed) + case let _1 as Api.SavedDialog: + _1.serialize(buffer, boxed) + case let _1 as Api.SavedReactionTag: + _1.serialize(buffer, boxed) + case let _1 as Api.SavedStarGift: + _1.serialize(buffer, boxed) + case let _1 as Api.SearchPostsFlood: + _1.serialize(buffer, boxed) + case let _1 as Api.SearchResultsCalendarPeriod: + _1.serialize(buffer, boxed) + case let _1 as Api.SearchResultsPosition: + _1.serialize(buffer, boxed) + case let _1 as Api.SecureCredentialsEncrypted: + _1.serialize(buffer, boxed) + case let _1 as Api.SecureData: + _1.serialize(buffer, boxed) + case let _1 as Api.SecureFile: + _1.serialize(buffer, boxed) + case let _1 as Api.SecurePasswordKdfAlgo: + _1.serialize(buffer, boxed) + case let _1 as Api.SecurePlainData: + _1.serialize(buffer, boxed) + case let _1 as Api.SecureRequiredType: + _1.serialize(buffer, boxed) + case let _1 as Api.SecureSecretSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.SecureValue: + _1.serialize(buffer, boxed) + case let _1 as Api.SecureValueError: + _1.serialize(buffer, boxed) + case let _1 as Api.SecureValueHash: + _1.serialize(buffer, boxed) + case let _1 as Api.SecureValueType: + _1.serialize(buffer, boxed) + case let _1 as Api.SendAsPeer: + _1.serialize(buffer, boxed) + case let _1 as Api.SendMessageAction: + _1.serialize(buffer, boxed) + case let _1 as Api.ShippingOption: + _1.serialize(buffer, boxed) + case let _1 as Api.SmsJob: + _1.serialize(buffer, boxed) + case let _1 as Api.SponsoredMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.SponsoredMessageReportOption: + _1.serialize(buffer, boxed) + case let _1 as Api.SponsoredPeer: + _1.serialize(buffer, boxed) + case let _1 as Api.StarGift: + _1.serialize(buffer, boxed) + case let _1 as Api.StarGiftActiveAuctionState: + _1.serialize(buffer, boxed) + case let _1 as Api.StarGiftAttribute: + _1.serialize(buffer, boxed) + case let _1 as Api.StarGiftAttributeCounter: + _1.serialize(buffer, boxed) + case let _1 as Api.StarGiftAttributeId: + _1.serialize(buffer, boxed) + case let _1 as Api.StarGiftAttributeRarity: + _1.serialize(buffer, boxed) + case let _1 as Api.StarGiftAuctionAcquiredGift: + _1.serialize(buffer, boxed) + case let _1 as Api.StarGiftAuctionRound: + _1.serialize(buffer, boxed) + case let _1 as Api.StarGiftAuctionState: + _1.serialize(buffer, boxed) + case let _1 as Api.StarGiftAuctionUserState: + _1.serialize(buffer, boxed) + case let _1 as Api.StarGiftBackground: + _1.serialize(buffer, boxed) + case let _1 as Api.StarGiftCollection: + _1.serialize(buffer, boxed) + case let _1 as Api.StarGiftUpgradePrice: + _1.serialize(buffer, boxed) + case let _1 as Api.StarRefProgram: + _1.serialize(buffer, boxed) + case let _1 as Api.StarsAmount: + _1.serialize(buffer, boxed) + case let _1 as Api.StarsGiftOption: + _1.serialize(buffer, boxed) + case let _1 as Api.StarsGiveawayOption: + _1.serialize(buffer, boxed) + case let _1 as Api.StarsGiveawayWinnersOption: + _1.serialize(buffer, boxed) + case let _1 as Api.StarsRating: + _1.serialize(buffer, boxed) + case let _1 as Api.StarsRevenueStatus: + _1.serialize(buffer, boxed) + case let _1 as Api.StarsSubscription: + _1.serialize(buffer, boxed) + case let _1 as Api.StarsSubscriptionPricing: + _1.serialize(buffer, boxed) + case let _1 as Api.StarsTopupOption: + _1.serialize(buffer, boxed) + case let _1 as Api.StarsTransaction: + _1.serialize(buffer, boxed) + case let _1 as Api.StarsTransactionPeer: + _1.serialize(buffer, boxed) + case let _1 as Api.StatsAbsValueAndPrev: + _1.serialize(buffer, boxed) + case let _1 as Api.StatsDateRangeDays: + _1.serialize(buffer, boxed) + case let _1 as Api.StatsGraph: + _1.serialize(buffer, boxed) + case let _1 as Api.StatsGroupTopAdmin: + _1.serialize(buffer, boxed) + case let _1 as Api.StatsGroupTopInviter: + _1.serialize(buffer, boxed) + case let _1 as Api.StatsGroupTopPoster: + _1.serialize(buffer, boxed) + case let _1 as Api.StatsPercentValue: + _1.serialize(buffer, boxed) + case let _1 as Api.StatsURL: + _1.serialize(buffer, boxed) + case let _1 as Api.StickerKeyword: + _1.serialize(buffer, boxed) + case let _1 as Api.StickerPack: + _1.serialize(buffer, boxed) + case let _1 as Api.StickerSet: + _1.serialize(buffer, boxed) + case let _1 as Api.StickerSetCovered: + _1.serialize(buffer, boxed) + case let _1 as Api.StoriesStealthMode: + _1.serialize(buffer, boxed) + case let _1 as Api.StoryAlbum: + _1.serialize(buffer, boxed) + case let _1 as Api.StoryFwdHeader: + _1.serialize(buffer, boxed) + case let _1 as Api.StoryItem: + _1.serialize(buffer, boxed) + case let _1 as Api.StoryReaction: + _1.serialize(buffer, boxed) + case let _1 as Api.StoryView: + _1.serialize(buffer, boxed) + case let _1 as Api.StoryViews: + _1.serialize(buffer, boxed) + case let _1 as Api.SuggestedPost: + _1.serialize(buffer, boxed) + case let _1 as Api.TextWithEntities: + _1.serialize(buffer, boxed) + case let _1 as Api.Theme: + _1.serialize(buffer, boxed) + case let _1 as Api.ThemeSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.Timezone: + _1.serialize(buffer, boxed) + case let _1 as Api.TodoCompletion: + _1.serialize(buffer, boxed) + case let _1 as Api.TodoItem: + _1.serialize(buffer, boxed) + case let _1 as Api.TodoList: + _1.serialize(buffer, boxed) + case let _1 as Api.TopPeer: + _1.serialize(buffer, boxed) + case let _1 as Api.TopPeerCategory: + _1.serialize(buffer, boxed) + case let _1 as Api.TopPeerCategoryPeers: + _1.serialize(buffer, boxed) + case let _1 as Api.Update: + _1.serialize(buffer, boxed) + case let _1 as Api.Updates: + _1.serialize(buffer, boxed) + case let _1 as Api.UrlAuthResult: + _1.serialize(buffer, boxed) + case let _1 as Api.User: + _1.serialize(buffer, boxed) + case let _1 as Api.UserFull: + _1.serialize(buffer, boxed) + case let _1 as Api.UserProfilePhoto: + _1.serialize(buffer, boxed) + case let _1 as Api.UserStatus: + _1.serialize(buffer, boxed) + case let _1 as Api.Username: + _1.serialize(buffer, boxed) + case let _1 as Api.VideoSize: + _1.serialize(buffer, boxed) + case let _1 as Api.WallPaper: + _1.serialize(buffer, boxed) + case let _1 as Api.WallPaperSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.WebAuthorization: + _1.serialize(buffer, boxed) + case let _1 as Api.WebDocument: + _1.serialize(buffer, boxed) + case let _1 as Api.WebPage: + _1.serialize(buffer, boxed) + case let _1 as Api.WebPageAttribute: + _1.serialize(buffer, boxed) + case let _1 as Api.WebViewMessageSent: + _1.serialize(buffer, boxed) + case let _1 as Api.WebViewResult: + _1.serialize(buffer, boxed) + case let _1 as Api.account.AuthorizationForm: + _1.serialize(buffer, boxed) + case let _1 as Api.account.Authorizations: + _1.serialize(buffer, boxed) + case let _1 as Api.account.AutoDownloadSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.account.AutoSaveSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.account.BusinessChatLinks: + _1.serialize(buffer, boxed) + case let _1 as Api.account.ChatThemes: + _1.serialize(buffer, boxed) + case let _1 as Api.account.ConnectedBots: + _1.serialize(buffer, boxed) + case let _1 as Api.account.ContentSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.account.EmailVerified: + _1.serialize(buffer, boxed) + case let _1 as Api.account.EmojiStatuses: + _1.serialize(buffer, boxed) + case let _1 as Api.account.PaidMessagesRevenue: + _1.serialize(buffer, boxed) + case let _1 as Api.account.PasskeyRegistrationOptions: + _1.serialize(buffer, boxed) + case let _1 as Api.account.Passkeys: + _1.serialize(buffer, boxed) + case let _1 as Api.account.Password: + _1.serialize(buffer, boxed) + case let _1 as Api.account.PasswordInputSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.account.PasswordSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.account.PrivacyRules: + _1.serialize(buffer, boxed) + case let _1 as Api.account.ResetPasswordResult: + _1.serialize(buffer, boxed) + case let _1 as Api.account.ResolvedBusinessChatLinks: + _1.serialize(buffer, boxed) + case let _1 as Api.account.SavedMusicIds: + _1.serialize(buffer, boxed) + case let _1 as Api.account.SavedRingtone: + _1.serialize(buffer, boxed) + case let _1 as Api.account.SavedRingtones: + _1.serialize(buffer, boxed) + case let _1 as Api.account.SentEmailCode: + _1.serialize(buffer, boxed) + case let _1 as Api.account.Takeout: + _1.serialize(buffer, boxed) + case let _1 as Api.account.Themes: + _1.serialize(buffer, boxed) + case let _1 as Api.account.TmpPassword: + _1.serialize(buffer, boxed) + case let _1 as Api.account.WallPapers: + _1.serialize(buffer, boxed) + case let _1 as Api.account.WebAuthorizations: + _1.serialize(buffer, boxed) + case let _1 as Api.auth.Authorization: + _1.serialize(buffer, boxed) + case let _1 as Api.auth.CodeType: + _1.serialize(buffer, boxed) + case let _1 as Api.auth.ExportedAuthorization: + _1.serialize(buffer, boxed) + case let _1 as Api.auth.LoggedOut: + _1.serialize(buffer, boxed) + case let _1 as Api.auth.LoginToken: + _1.serialize(buffer, boxed) + case let _1 as Api.auth.PasskeyLoginOptions: + _1.serialize(buffer, boxed) + case let _1 as Api.auth.PasswordRecovery: + _1.serialize(buffer, boxed) + case let _1 as Api.auth.SentCode: + _1.serialize(buffer, boxed) + case let _1 as Api.auth.SentCodeType: + _1.serialize(buffer, boxed) + case let _1 as Api.bots.BotInfo: + _1.serialize(buffer, boxed) + case let _1 as Api.bots.PopularAppBots: + _1.serialize(buffer, boxed) + case let _1 as Api.bots.PreviewInfo: + _1.serialize(buffer, boxed) + case let _1 as Api.channels.AdminLogResults: + _1.serialize(buffer, boxed) + case let _1 as Api.channels.ChannelParticipant: + _1.serialize(buffer, boxed) + case let _1 as Api.channels.ChannelParticipants: + _1.serialize(buffer, boxed) + case let _1 as Api.channels.SendAsPeers: + _1.serialize(buffer, boxed) + case let _1 as Api.channels.SponsoredMessageReportResult: + _1.serialize(buffer, boxed) + case let _1 as Api.chatlists.ChatlistInvite: + _1.serialize(buffer, boxed) + case let _1 as Api.chatlists.ChatlistUpdates: + _1.serialize(buffer, boxed) + case let _1 as Api.chatlists.ExportedChatlistInvite: + _1.serialize(buffer, boxed) + case let _1 as Api.chatlists.ExportedInvites: + _1.serialize(buffer, boxed) + case let _1 as Api.contacts.Blocked: + _1.serialize(buffer, boxed) + case let _1 as Api.contacts.ContactBirthdays: + _1.serialize(buffer, boxed) + case let _1 as Api.contacts.Contacts: + _1.serialize(buffer, boxed) + case let _1 as Api.contacts.Found: + _1.serialize(buffer, boxed) + case let _1 as Api.contacts.ImportedContacts: + _1.serialize(buffer, boxed) + case let _1 as Api.contacts.ResolvedPeer: + _1.serialize(buffer, boxed) + case let _1 as Api.contacts.SponsoredPeers: + _1.serialize(buffer, boxed) + case let _1 as Api.contacts.TopPeers: + _1.serialize(buffer, boxed) + case let _1 as Api.fragment.CollectibleInfo: + _1.serialize(buffer, boxed) + case let _1 as Api.help.AppConfig: + _1.serialize(buffer, boxed) + case let _1 as Api.help.AppUpdate: + _1.serialize(buffer, boxed) + case let _1 as Api.help.CountriesList: + _1.serialize(buffer, boxed) + case let _1 as Api.help.Country: + _1.serialize(buffer, boxed) + case let _1 as Api.help.CountryCode: + _1.serialize(buffer, boxed) + case let _1 as Api.help.DeepLinkInfo: + _1.serialize(buffer, boxed) + case let _1 as Api.help.InviteText: + _1.serialize(buffer, boxed) + case let _1 as Api.help.PassportConfig: + _1.serialize(buffer, boxed) + case let _1 as Api.help.PeerColorOption: + _1.serialize(buffer, boxed) + case let _1 as Api.help.PeerColorSet: + _1.serialize(buffer, boxed) + case let _1 as Api.help.PeerColors: + _1.serialize(buffer, boxed) + case let _1 as Api.help.PremiumPromo: + _1.serialize(buffer, boxed) + case let _1 as Api.help.PromoData: + _1.serialize(buffer, boxed) + case let _1 as Api.help.RecentMeUrls: + _1.serialize(buffer, boxed) + case let _1 as Api.help.Support: + _1.serialize(buffer, boxed) + case let _1 as Api.help.SupportName: + _1.serialize(buffer, boxed) + case let _1 as Api.help.TermsOfService: + _1.serialize(buffer, boxed) + case let _1 as Api.help.TermsOfServiceUpdate: + _1.serialize(buffer, boxed) + case let _1 as Api.help.TimezonesList: + _1.serialize(buffer, boxed) + case let _1 as Api.help.UserInfo: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.AffectedFoundMessages: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.AffectedHistory: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.AffectedMessages: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.AllStickers: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.ArchivedStickers: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.AvailableEffects: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.AvailableReactions: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.BotApp: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.BotCallbackAnswer: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.BotPreparedInlineMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.BotResults: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.ChatAdminsWithInvites: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.ChatFull: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.ChatInviteImporters: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.Chats: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.CheckedHistoryImportPeer: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.DhConfig: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.DialogFilters: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.Dialogs: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.DiscussionMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.EmojiGameInfo: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.EmojiGameOutcome: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.EmojiGroups: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.ExportedChatInvite: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.ExportedChatInvites: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.FavedStickers: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.FeaturedStickers: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.ForumTopics: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.FoundStickerSets: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.FoundStickers: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.HighScores: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.HistoryImport: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.HistoryImportParsed: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.InactiveChats: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.InvitedUsers: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.MessageEditData: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.MessageReactionsList: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.MessageViews: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.Messages: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.MyStickers: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.PeerDialogs: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.PeerSettings: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.PreparedInlineMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.QuickReplies: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.Reactions: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.RecentStickers: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.SavedDialogs: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.SavedGifs: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.SavedReactionTags: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.SearchCounter: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.SearchResultsCalendar: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.SearchResultsPositions: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.SentEncryptedMessage: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.SponsoredMessages: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.StickerSet: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.StickerSetInstallResult: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.Stickers: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.TranscribedAudio: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.TranslatedText: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.VotesList: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.WebPage: + _1.serialize(buffer, boxed) + case let _1 as Api.messages.WebPagePreview: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.BankCardData: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.CheckCanSendGiftResult: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.CheckedGiftCode: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.ConnectedStarRefBots: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.ExportedInvoice: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.GiveawayInfo: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.PaymentForm: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.PaymentReceipt: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.PaymentResult: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.ResaleStarGifts: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.SavedInfo: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.SavedStarGifts: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.StarGiftActiveAuctions: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.StarGiftAuctionAcquiredGifts: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.StarGiftAuctionState: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.StarGiftCollections: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.StarGiftUpgradeAttributes: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.StarGiftUpgradePreview: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.StarGiftWithdrawalUrl: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.StarGifts: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.StarsRevenueAdsAccountUrl: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.StarsRevenueStats: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.StarsRevenueWithdrawalUrl: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.StarsStatus: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.SuggestedStarRefBots: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.UniqueStarGift: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.UniqueStarGiftValueInfo: + _1.serialize(buffer, boxed) + case let _1 as Api.payments.ValidatedRequestedInfo: + _1.serialize(buffer, boxed) + case let _1 as Api.phone.ExportedGroupCallInvite: + _1.serialize(buffer, boxed) + case let _1 as Api.phone.GroupCall: + _1.serialize(buffer, boxed) + case let _1 as Api.phone.GroupCallStars: + _1.serialize(buffer, boxed) + case let _1 as Api.phone.GroupCallStreamChannels: + _1.serialize(buffer, boxed) + case let _1 as Api.phone.GroupCallStreamRtmpUrl: + _1.serialize(buffer, boxed) + case let _1 as Api.phone.GroupParticipants: + _1.serialize(buffer, boxed) + case let _1 as Api.phone.JoinAsPeers: + _1.serialize(buffer, boxed) + case let _1 as Api.phone.PhoneCall: + _1.serialize(buffer, boxed) + case let _1 as Api.photos.Photo: + _1.serialize(buffer, boxed) + case let _1 as Api.photos.Photos: + _1.serialize(buffer, boxed) + case let _1 as Api.premium.BoostsList: + _1.serialize(buffer, boxed) + case let _1 as Api.premium.BoostsStatus: + _1.serialize(buffer, boxed) + case let _1 as Api.premium.MyBoosts: + _1.serialize(buffer, boxed) + case let _1 as Api.smsjobs.EligibilityToJoin: + _1.serialize(buffer, boxed) + case let _1 as Api.smsjobs.Status: + _1.serialize(buffer, boxed) + case let _1 as Api.stats.BroadcastStats: + _1.serialize(buffer, boxed) + case let _1 as Api.stats.MegagroupStats: + _1.serialize(buffer, boxed) + case let _1 as Api.stats.MessageStats: + _1.serialize(buffer, boxed) + case let _1 as Api.stats.PublicForwards: + _1.serialize(buffer, boxed) + case let _1 as Api.stats.StoryStats: + _1.serialize(buffer, boxed) + case let _1 as Api.stickers.SuggestedShortName: + _1.serialize(buffer, boxed) + case let _1 as Api.storage.FileType: + _1.serialize(buffer, boxed) + case let _1 as Api.stories.Albums: + _1.serialize(buffer, boxed) + case let _1 as Api.stories.AllStories: + _1.serialize(buffer, boxed) + case let _1 as Api.stories.CanSendStoryCount: + _1.serialize(buffer, boxed) + case let _1 as Api.stories.FoundStories: + _1.serialize(buffer, boxed) + case let _1 as Api.stories.PeerStories: + _1.serialize(buffer, boxed) + case let _1 as Api.stories.Stories: + _1.serialize(buffer, boxed) + case let _1 as Api.stories.StoryReactionsList: + _1.serialize(buffer, boxed) + case let _1 as Api.stories.StoryViews: + _1.serialize(buffer, boxed) + case let _1 as Api.stories.StoryViewsList: + _1.serialize(buffer, boxed) + case let _1 as Api.updates.ChannelDifference: + _1.serialize(buffer, boxed) + case let _1 as Api.updates.Difference: + _1.serialize(buffer, boxed) + case let _1 as Api.updates.State: + _1.serialize(buffer, boxed) + case let _1 as Api.upload.CdnFile: + _1.serialize(buffer, boxed) + case let _1 as Api.upload.File: + _1.serialize(buffer, boxed) + case let _1 as Api.upload.WebFile: + _1.serialize(buffer, boxed) + case let _1 as Api.users.SavedMusic: + _1.serialize(buffer, boxed) + case let _1 as Api.users.UserFull: + _1.serialize(buffer, boxed) + case let _1 as Api.users.Users: + _1.serialize(buffer, boxed) + default: + break } } - } diff --git a/submodules/TelegramApi/Sources/Api1.swift b/submodules/TelegramApi/Sources/Api1.swift index 1056c070..1926282c 100644 --- a/submodules/TelegramApi/Sources/Api1.swift +++ b/submodules/TelegramApi/Sources/Api1.swift @@ -1,69 +1,94 @@ public extension Api { enum AccountDaysTTL: TypeConstructorDescription { - case accountDaysTTL(days: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .accountDaysTTL(let days): - if boxed { - buffer.appendInt32(-1194283041) - } - serializeInt32(days, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .accountDaysTTL(let days): - return ("accountDaysTTL", [("days", days as Any)]) - } - } - + public class Cons_accountDaysTTL { + public var days: Int32 + public init(days: Int32) { + self.days = days + } + } + case accountDaysTTL(Cons_accountDaysTTL) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .accountDaysTTL(let _data): + if boxed { + buffer.appendInt32(-1194283041) + } + serializeInt32(_data.days, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .accountDaysTTL(let _data): + return ("accountDaysTTL", [("days", _data.days as Any)]) + } + } + public static func parse_accountDaysTTL(_ reader: BufferReader) -> AccountDaysTTL? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.AccountDaysTTL.accountDaysTTL(days: _1!) + if _c1 { + return Api.AccountDaysTTL.accountDaysTTL(Cons_accountDaysTTL(days: _1!)) + } + else { + return nil + } } - } } public extension Api { enum AttachMenuBot: TypeConstructorDescription { - case attachMenuBot(flags: Int32, botId: Int64, shortName: String, peerTypes: [Api.AttachMenuPeerType]?, icons: [Api.AttachMenuBotIcon]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .attachMenuBot(let flags, let botId, let shortName, let peerTypes, let icons): - if boxed { - buffer.appendInt32(-653423106) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(botId, buffer: buffer, boxed: false) - serializeString(shortName, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peerTypes!.count)) - for item in peerTypes! { - item.serialize(buffer, true) - }} + public class Cons_attachMenuBot { + public var flags: Int32 + public var botId: Int64 + public var shortName: String + public var peerTypes: [Api.AttachMenuPeerType]? + public var icons: [Api.AttachMenuBotIcon] + public init(flags: Int32, botId: Int64, shortName: String, peerTypes: [Api.AttachMenuPeerType]?, icons: [Api.AttachMenuBotIcon]) { + self.flags = flags + self.botId = botId + self.shortName = shortName + self.peerTypes = peerTypes + self.icons = icons + } + } + case attachMenuBot(Cons_attachMenuBot) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .attachMenuBot(let _data): + if boxed { + buffer.appendInt32(-653423106) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.botId, buffer: buffer, boxed: false) + serializeString(_data.shortName, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(icons.count)) - for item in icons { + buffer.appendInt32(Int32(_data.peerTypes!.count)) + for item in _data.peerTypes! { item.serialize(buffer, true) } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .attachMenuBot(let flags, let botId, let shortName, let peerTypes, let icons): - return ("attachMenuBot", [("flags", flags as Any), ("botId", botId as Any), ("shortName", shortName as Any), ("peerTypes", peerTypes as Any), ("icons", icons as Any)]) - } - } - + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.icons.count)) + for item in _data.icons { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .attachMenuBot(let _data): + return ("attachMenuBot", [("flags", _data.flags as Any), ("botId", _data.botId as Any), ("shortName", _data.shortName as Any), ("peerTypes", _data.peerTypes as Any), ("icons", _data.icons as Any)]) + } + } + public static func parse_attachMenuBot(_ reader: BufferReader) -> AttachMenuBot? { var _1: Int32? _1 = reader.readInt32() @@ -72,9 +97,11 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: [Api.AttachMenuPeerType]? - if Int(_1!) & Int(1 << 3) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.AttachMenuPeerType.self) - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.AttachMenuPeerType.self) + } + } var _5: [Api.AttachMenuBotIcon]? if let _ = reader.readInt32() { _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.AttachMenuBotIcon.self) @@ -84,45 +111,58 @@ public extension Api { let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 3) == 0) || _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.AttachMenuBot.attachMenuBot(flags: _1!, botId: _2!, shortName: _3!, peerTypes: _4, icons: _5!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.AttachMenuBot.attachMenuBot(Cons_attachMenuBot(flags: _1!, botId: _2!, shortName: _3!, peerTypes: _4, icons: _5!)) + } + else { + return nil + } } - } } public extension Api { enum AttachMenuBotIcon: TypeConstructorDescription { - case attachMenuBotIcon(flags: Int32, name: String, icon: Api.Document, colors: [Api.AttachMenuBotIconColor]?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .attachMenuBotIcon(let flags, let name, let icon, let colors): - if boxed { - buffer.appendInt32(-1297663893) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(name, buffer: buffer, boxed: false) - icon.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(colors!.count)) - for item in colors! { + public class Cons_attachMenuBotIcon { + public var flags: Int32 + public var name: String + public var icon: Api.Document + public var colors: [Api.AttachMenuBotIconColor]? + public init(flags: Int32, name: String, icon: Api.Document, colors: [Api.AttachMenuBotIconColor]?) { + self.flags = flags + self.name = name + self.icon = icon + self.colors = colors + } + } + case attachMenuBotIcon(Cons_attachMenuBotIcon) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .attachMenuBotIcon(let _data): + if boxed { + buffer.appendInt32(-1297663893) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.name, buffer: buffer, boxed: false) + _data.icon.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.colors!.count)) + for item in _data.colors! { item.serialize(buffer, true) - }} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .attachMenuBotIcon(let flags, let name, let icon, let colors): - return ("attachMenuBotIcon", [("flags", flags as Any), ("name", name as Any), ("icon", icon as Any), ("colors", colors as Any)]) - } - } - + } + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .attachMenuBotIcon(let _data): + return ("attachMenuBotIcon", [("flags", _data.flags as Any), ("name", _data.name as Any), ("icon", _data.icon as Any), ("colors", _data.colors as Any)]) + } + } + public static func parse_attachMenuBotIcon(_ reader: BufferReader) -> AttachMenuBotIcon? { var _1: Int32? _1 = reader.readInt32() @@ -133,45 +173,55 @@ public extension Api { _3 = Api.parse(reader, signature: signature) as? Api.Document } var _4: [Api.AttachMenuBotIconColor]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.AttachMenuBotIconColor.self) - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.AttachMenuBotIconColor.self) + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.AttachMenuBotIcon.attachMenuBotIcon(flags: _1!, name: _2!, icon: _3!, colors: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.AttachMenuBotIcon.attachMenuBotIcon(Cons_attachMenuBotIcon(flags: _1!, name: _2!, icon: _3!, colors: _4)) + } + else { + return nil + } } - } } public extension Api { enum AttachMenuBotIconColor: TypeConstructorDescription { - case attachMenuBotIconColor(name: String, color: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .attachMenuBotIconColor(let name, let color): - if boxed { - buffer.appendInt32(1165423600) - } - serializeString(name, buffer: buffer, boxed: false) - serializeInt32(color, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .attachMenuBotIconColor(let name, let color): - return ("attachMenuBotIconColor", [("name", name as Any), ("color", color as Any)]) - } - } - + public class Cons_attachMenuBotIconColor { + public var name: String + public var color: Int32 + public init(name: String, color: Int32) { + self.name = name + self.color = color + } + } + case attachMenuBotIconColor(Cons_attachMenuBotIconColor) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .attachMenuBotIconColor(let _data): + if boxed { + buffer.appendInt32(1165423600) + } + serializeString(_data.name, buffer: buffer, boxed: false) + serializeInt32(_data.color, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .attachMenuBotIconColor(let _data): + return ("attachMenuBotIconColor", [("name", _data.name as Any), ("color", _data.color as Any)]) + } + } + public static func parse_attachMenuBotIconColor(_ reader: BufferReader) -> AttachMenuBotIconColor? { var _1: String? _1 = parseString(reader) @@ -179,54 +229,65 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.AttachMenuBotIconColor.attachMenuBotIconColor(name: _1!, color: _2!) + if _c1 && _c2 { + return Api.AttachMenuBotIconColor.attachMenuBotIconColor(Cons_attachMenuBotIconColor(name: _1!, color: _2!)) + } + else { + return nil + } } - } } public extension Api { enum AttachMenuBots: TypeConstructorDescription { - case attachMenuBots(hash: Int64, bots: [Api.AttachMenuBot], users: [Api.User]) + public class Cons_attachMenuBots { + public var hash: Int64 + public var bots: [Api.AttachMenuBot] + public var users: [Api.User] + public init(hash: Int64, bots: [Api.AttachMenuBot], users: [Api.User]) { + self.hash = hash + self.bots = bots + self.users = users + } + } + case attachMenuBots(Cons_attachMenuBots) case attachMenuBotsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .attachMenuBots(let hash, let bots, let users): - if boxed { - buffer.appendInt32(1011024320) - } - serializeInt64(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(bots.count)) - for item in bots { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .attachMenuBotsNotModified: - if boxed { - buffer.appendInt32(-237467044) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .attachMenuBots(let hash, let bots, let users): - return ("attachMenuBots", [("hash", hash as Any), ("bots", bots as Any), ("users", users as Any)]) - case .attachMenuBotsNotModified: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .attachMenuBots(let _data): + if boxed { + buffer.appendInt32(1011024320) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.bots.count)) + for item in _data.bots { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .attachMenuBotsNotModified: + if boxed { + buffer.appendInt32(-237467044) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .attachMenuBots(let _data): + return ("attachMenuBots", [("hash", _data.hash as Any), ("bots", _data.bots as Any), ("users", _data.users as Any)]) + case .attachMenuBotsNotModified: return ("attachMenuBotsNotModified", []) - } - } - + } + } + public static func parse_attachMenuBots(_ reader: BufferReader) -> AttachMenuBots? { var _1: Int64? _1 = reader.readInt64() @@ -241,44 +302,53 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.AttachMenuBots.attachMenuBots(hash: _1!, bots: _2!, users: _3!) + if _c1 && _c2 && _c3 { + return Api.AttachMenuBots.attachMenuBots(Cons_attachMenuBots(hash: _1!, bots: _2!, users: _3!)) + } + else { + return nil + } } public static func parse_attachMenuBotsNotModified(_ reader: BufferReader) -> AttachMenuBots? { return Api.AttachMenuBots.attachMenuBotsNotModified } - } } public extension Api { enum AttachMenuBotsBot: TypeConstructorDescription { - case attachMenuBotsBot(bot: Api.AttachMenuBot, users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .attachMenuBotsBot(let bot, let users): - if boxed { - buffer.appendInt32(-1816172929) - } - bot.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .attachMenuBotsBot(let bot, let users): - return ("attachMenuBotsBot", [("bot", bot as Any), ("users", users as Any)]) - } - } - + public class Cons_attachMenuBotsBot { + public var bot: Api.AttachMenuBot + public var users: [Api.User] + public init(bot: Api.AttachMenuBot, users: [Api.User]) { + self.bot = bot + self.users = users + } + } + case attachMenuBotsBot(Cons_attachMenuBotsBot) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .attachMenuBotsBot(let _data): + if boxed { + buffer.appendInt32(-1816172929) + } + _data.bot.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .attachMenuBotsBot(let _data): + return ("attachMenuBotsBot", [("bot", _data.bot as Any), ("users", _data.users as Any)]) + } + } + public static func parse_attachMenuBotsBot(_ reader: BufferReader) -> AttachMenuBotsBot? { var _1: Api.AttachMenuBot? if let signature = reader.readInt32() { @@ -290,11 +360,13 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.AttachMenuBotsBot.attachMenuBotsBot(bot: _1!, users: _2!) + if _c1 && _c2 { + return Api.AttachMenuBotsBot.attachMenuBotsBot(Cons_attachMenuBotsBot(bot: _1!, users: _2!)) + } + else { + return nil + } } - } } public extension Api { @@ -304,57 +376,52 @@ public extension Api { case attachMenuPeerTypeChat case attachMenuPeerTypePM case attachMenuPeerTypeSameBotPM - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .attachMenuPeerTypeBotPM: - if boxed { - buffer.appendInt32(-1020528102) - } - - break - case .attachMenuPeerTypeBroadcast: - if boxed { - buffer.appendInt32(2080104188) - } - - break - case .attachMenuPeerTypeChat: - if boxed { - buffer.appendInt32(84480319) - } - - break - case .attachMenuPeerTypePM: - if boxed { - buffer.appendInt32(-247016673) - } - - break - case .attachMenuPeerTypeSameBotPM: - if boxed { - buffer.appendInt32(2104224014) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .attachMenuPeerTypeBotPM: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .attachMenuPeerTypeBotPM: + if boxed { + buffer.appendInt32(-1020528102) + } + break + case .attachMenuPeerTypeBroadcast: + if boxed { + buffer.appendInt32(2080104188) + } + break + case .attachMenuPeerTypeChat: + if boxed { + buffer.appendInt32(84480319) + } + break + case .attachMenuPeerTypePM: + if boxed { + buffer.appendInt32(-247016673) + } + break + case .attachMenuPeerTypeSameBotPM: + if boxed { + buffer.appendInt32(2104224014) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .attachMenuPeerTypeBotPM: return ("attachMenuPeerTypeBotPM", []) - case .attachMenuPeerTypeBroadcast: + case .attachMenuPeerTypeBroadcast: return ("attachMenuPeerTypeBroadcast", []) - case .attachMenuPeerTypeChat: + case .attachMenuPeerTypeChat: return ("attachMenuPeerTypeChat", []) - case .attachMenuPeerTypePM: + case .attachMenuPeerTypePM: return ("attachMenuPeerTypePM", []) - case .attachMenuPeerTypeSameBotPM: + case .attachMenuPeerTypeSameBotPM: return ("attachMenuPeerTypeSameBotPM", []) - } - } - + } + } + public static func parse_attachMenuPeerTypeBotPM(_ reader: BufferReader) -> AttachMenuPeerType? { return Api.AttachMenuPeerType.attachMenuPeerTypeBotPM } @@ -370,33 +437,42 @@ public extension Api { public static func parse_attachMenuPeerTypeSameBotPM(_ reader: BufferReader) -> AttachMenuPeerType? { return Api.AttachMenuPeerType.attachMenuPeerTypeSameBotPM } - } } public extension Api { enum AuctionBidLevel: TypeConstructorDescription { - case auctionBidLevel(pos: Int32, amount: Int64, date: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .auctionBidLevel(let pos, let amount, let date): - if boxed { - buffer.appendInt32(822231244) - } - serializeInt32(pos, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .auctionBidLevel(let pos, let amount, let date): - return ("auctionBidLevel", [("pos", pos as Any), ("amount", amount as Any), ("date", date as Any)]) - } - } - + public class Cons_auctionBidLevel { + public var pos: Int32 + public var amount: Int64 + public var date: Int32 + public init(pos: Int32, amount: Int64, date: Int32) { + self.pos = pos + self.amount = amount + self.date = date + } + } + case auctionBidLevel(Cons_auctionBidLevel) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .auctionBidLevel(let _data): + if boxed { + buffer.appendInt32(822231244) + } + serializeInt32(_data.pos, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .auctionBidLevel(let _data): + return ("auctionBidLevel", [("pos", _data.pos as Any), ("amount", _data.amount as Any), ("date", _data.date as Any)]) + } + } + public static func parse_auctionBidLevel(_ reader: BufferReader) -> AuctionBidLevel? { var _1: Int32? _1 = reader.readInt32() @@ -407,48 +483,79 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.AuctionBidLevel.auctionBidLevel(pos: _1!, amount: _2!, date: _3!) + if _c1 && _c2 && _c3 { + return Api.AuctionBidLevel.auctionBidLevel(Cons_auctionBidLevel(pos: _1!, amount: _2!, date: _3!)) + } + else { + return nil + } } - } } public extension Api { enum Authorization: TypeConstructorDescription { - case authorization(flags: Int32, hash: Int64, deviceModel: String, platform: String, systemVersion: String, apiId: Int32, appName: String, appVersion: String, dateCreated: Int32, dateActive: Int32, ip: String, country: String, region: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .authorization(let flags, let hash, let deviceModel, let platform, let systemVersion, let apiId, let appName, let appVersion, let dateCreated, let dateActive, let ip, let country, let region): - if boxed { - buffer.appendInt32(-1392388579) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - serializeString(deviceModel, buffer: buffer, boxed: false) - serializeString(platform, buffer: buffer, boxed: false) - serializeString(systemVersion, buffer: buffer, boxed: false) - serializeInt32(apiId, buffer: buffer, boxed: false) - serializeString(appName, buffer: buffer, boxed: false) - serializeString(appVersion, buffer: buffer, boxed: false) - serializeInt32(dateCreated, buffer: buffer, boxed: false) - serializeInt32(dateActive, buffer: buffer, boxed: false) - serializeString(ip, buffer: buffer, boxed: false) - serializeString(country, buffer: buffer, boxed: false) - serializeString(region, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .authorization(let flags, let hash, let deviceModel, let platform, let systemVersion, let apiId, let appName, let appVersion, let dateCreated, let dateActive, let ip, let country, let region): - return ("authorization", [("flags", flags as Any), ("hash", hash as Any), ("deviceModel", deviceModel as Any), ("platform", platform as Any), ("systemVersion", systemVersion as Any), ("apiId", apiId as Any), ("appName", appName as Any), ("appVersion", appVersion as Any), ("dateCreated", dateCreated as Any), ("dateActive", dateActive as Any), ("ip", ip as Any), ("country", country as Any), ("region", region as Any)]) - } - } - + public class Cons_authorization { + public var flags: Int32 + public var hash: Int64 + public var deviceModel: String + public var platform: String + public var systemVersion: String + public var apiId: Int32 + public var appName: String + public var appVersion: String + public var dateCreated: Int32 + public var dateActive: Int32 + public var ip: String + public var country: String + public var region: String + public init(flags: Int32, hash: Int64, deviceModel: String, platform: String, systemVersion: String, apiId: Int32, appName: String, appVersion: String, dateCreated: Int32, dateActive: Int32, ip: String, country: String, region: String) { + self.flags = flags + self.hash = hash + self.deviceModel = deviceModel + self.platform = platform + self.systemVersion = systemVersion + self.apiId = apiId + self.appName = appName + self.appVersion = appVersion + self.dateCreated = dateCreated + self.dateActive = dateActive + self.ip = ip + self.country = country + self.region = region + } + } + case authorization(Cons_authorization) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .authorization(let _data): + if boxed { + buffer.appendInt32(-1392388579) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.hash, buffer: buffer, boxed: false) + serializeString(_data.deviceModel, buffer: buffer, boxed: false) + serializeString(_data.platform, buffer: buffer, boxed: false) + serializeString(_data.systemVersion, buffer: buffer, boxed: false) + serializeInt32(_data.apiId, buffer: buffer, boxed: false) + serializeString(_data.appName, buffer: buffer, boxed: false) + serializeString(_data.appVersion, buffer: buffer, boxed: false) + serializeInt32(_data.dateCreated, buffer: buffer, boxed: false) + serializeInt32(_data.dateActive, buffer: buffer, boxed: false) + serializeString(_data.ip, buffer: buffer, boxed: false) + serializeString(_data.country, buffer: buffer, boxed: false) + serializeString(_data.region, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .authorization(let _data): + return ("authorization", [("flags", _data.flags as Any), ("hash", _data.hash as Any), ("deviceModel", _data.deviceModel as Any), ("platform", _data.platform as Any), ("systemVersion", _data.systemVersion as Any), ("apiId", _data.apiId as Any), ("appName", _data.appName as Any), ("appVersion", _data.appVersion as Any), ("dateCreated", _data.dateCreated as Any), ("dateActive", _data.dateActive as Any), ("ip", _data.ip as Any), ("country", _data.country as Any), ("region", _data.region as Any)]) + } + } + public static func parse_authorization(_ reader: BufferReader) -> Authorization? { var _1: Int32? _1 = reader.readInt32() @@ -489,52 +596,61 @@ public extension Api { let _c11 = _11 != nil let _c12 = _12 != nil let _c13 = _13 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - return Api.Authorization.authorization(flags: _1!, hash: _2!, deviceModel: _3!, platform: _4!, systemVersion: _5!, apiId: _6!, appName: _7!, appVersion: _8!, dateCreated: _9!, dateActive: _10!, ip: _11!, country: _12!, region: _13!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 { + return Api.Authorization.authorization(Cons_authorization(flags: _1!, hash: _2!, deviceModel: _3!, platform: _4!, systemVersion: _5!, apiId: _6!, appName: _7!, appVersion: _8!, dateCreated: _9!, dateActive: _10!, ip: _11!, country: _12!, region: _13!)) + } + else { + return nil + } } - } } public extension Api { enum AutoDownloadSettings: TypeConstructorDescription { - case autoDownloadSettings(flags: Int32, photoSizeMax: Int32, videoSizeMax: Int64, fileSizeMax: Int64, videoUploadMaxbitrate: Int32, smallQueueActiveOperationsMax: Int32, largeQueueActiveOperationsMax: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .autoDownloadSettings(let flags, let photoSizeMax, let videoSizeMax, let fileSizeMax, let videoUploadMaxbitrate, let smallQueueActiveOperationsMax, let largeQueueActiveOperationsMax): - if boxed { - buffer.appendInt32(-1163561432) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(photoSizeMax, buffer: buffer, boxed: false) - serializeInt64(videoSizeMax, buffer: buffer, boxed: false) - serializeInt64(fileSizeMax, buffer: buffer, boxed: false) - serializeInt32(videoUploadMaxbitrate, buffer: buffer, boxed: false) - serializeInt32(smallQueueActiveOperationsMax, buffer: buffer, boxed: false) - serializeInt32(largeQueueActiveOperationsMax, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .autoDownloadSettings(let flags, let photoSizeMax, let videoSizeMax, let fileSizeMax, let videoUploadMaxbitrate, let smallQueueActiveOperationsMax, let largeQueueActiveOperationsMax): - return ("autoDownloadSettings", [("flags", flags as Any), ("photoSizeMax", photoSizeMax as Any), ("videoSizeMax", videoSizeMax as Any), ("fileSizeMax", fileSizeMax as Any), ("videoUploadMaxbitrate", videoUploadMaxbitrate as Any), ("smallQueueActiveOperationsMax", smallQueueActiveOperationsMax as Any), ("largeQueueActiveOperationsMax", largeQueueActiveOperationsMax as Any)]) - } - } - + public class Cons_autoDownloadSettings { + public var flags: Int32 + public var photoSizeMax: Int32 + public var videoSizeMax: Int64 + public var fileSizeMax: Int64 + public var videoUploadMaxbitrate: Int32 + public var smallQueueActiveOperationsMax: Int32 + public var largeQueueActiveOperationsMax: Int32 + public init(flags: Int32, photoSizeMax: Int32, videoSizeMax: Int64, fileSizeMax: Int64, videoUploadMaxbitrate: Int32, smallQueueActiveOperationsMax: Int32, largeQueueActiveOperationsMax: Int32) { + self.flags = flags + self.photoSizeMax = photoSizeMax + self.videoSizeMax = videoSizeMax + self.fileSizeMax = fileSizeMax + self.videoUploadMaxbitrate = videoUploadMaxbitrate + self.smallQueueActiveOperationsMax = smallQueueActiveOperationsMax + self.largeQueueActiveOperationsMax = largeQueueActiveOperationsMax + } + } + case autoDownloadSettings(Cons_autoDownloadSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .autoDownloadSettings(let _data): + if boxed { + buffer.appendInt32(-1163561432) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.photoSizeMax, buffer: buffer, boxed: false) + serializeInt64(_data.videoSizeMax, buffer: buffer, boxed: false) + serializeInt64(_data.fileSizeMax, buffer: buffer, boxed: false) + serializeInt32(_data.videoUploadMaxbitrate, buffer: buffer, boxed: false) + serializeInt32(_data.smallQueueActiveOperationsMax, buffer: buffer, boxed: false) + serializeInt32(_data.largeQueueActiveOperationsMax, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .autoDownloadSettings(let _data): + return ("autoDownloadSettings", [("flags", _data.flags as Any), ("photoSizeMax", _data.photoSizeMax as Any), ("videoSizeMax", _data.videoSizeMax as Any), ("fileSizeMax", _data.fileSizeMax as Any), ("videoUploadMaxbitrate", _data.videoUploadMaxbitrate as Any), ("smallQueueActiveOperationsMax", _data.smallQueueActiveOperationsMax as Any), ("largeQueueActiveOperationsMax", _data.largeQueueActiveOperationsMax as Any)]) + } + } + public static func parse_autoDownloadSettings(_ reader: BufferReader) -> AutoDownloadSettings? { var _1: Int32? _1 = reader.readInt32() @@ -557,41 +673,46 @@ public extension Api { let _c5 = _5 != nil let _c6 = _6 != nil let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.AutoDownloadSettings.autoDownloadSettings(flags: _1!, photoSizeMax: _2!, videoSizeMax: _3!, fileSizeMax: _4!, videoUploadMaxbitrate: _5!, smallQueueActiveOperationsMax: _6!, largeQueueActiveOperationsMax: _7!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.AutoDownloadSettings.autoDownloadSettings(Cons_autoDownloadSettings(flags: _1!, photoSizeMax: _2!, videoSizeMax: _3!, fileSizeMax: _4!, videoUploadMaxbitrate: _5!, smallQueueActiveOperationsMax: _6!, largeQueueActiveOperationsMax: _7!)) + } + else { + return nil + } } - } } public extension Api { enum AutoSaveException: TypeConstructorDescription { - case autoSaveException(peer: Api.Peer, settings: Api.AutoSaveSettings) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .autoSaveException(let peer, let settings): - if boxed { - buffer.appendInt32(-2124403385) - } - peer.serialize(buffer, true) - settings.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .autoSaveException(let peer, let settings): - return ("autoSaveException", [("peer", peer as Any), ("settings", settings as Any)]) - } - } - + public class Cons_autoSaveException { + public var peer: Api.Peer + public var settings: Api.AutoSaveSettings + public init(peer: Api.Peer, settings: Api.AutoSaveSettings) { + self.peer = peer + self.settings = settings + } + } + case autoSaveException(Cons_autoSaveException) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .autoSaveException(let _data): + if boxed { + buffer.appendInt32(-2124403385) + } + _data.peer.serialize(buffer, true) + _data.settings.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .autoSaveException(let _data): + return ("autoSaveException", [("peer", _data.peer as Any), ("settings", _data.settings as Any)]) + } + } + public static func parse_autoSaveException(_ reader: BufferReader) -> AutoSaveException? { var _1: Api.Peer? if let signature = reader.readInt32() { @@ -603,77 +724,113 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.AutoSaveException.autoSaveException(peer: _1!, settings: _2!) + if _c1 && _c2 { + return Api.AutoSaveException.autoSaveException(Cons_autoSaveException(peer: _1!, settings: _2!)) + } + else { + return nil + } } - } } public extension Api { enum AutoSaveSettings: TypeConstructorDescription { - case autoSaveSettings(flags: Int32, videoMaxSize: Int64?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .autoSaveSettings(let flags, let videoMaxSize): - if boxed { - buffer.appendInt32(-934791986) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeInt64(videoMaxSize!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .autoSaveSettings(let flags, let videoMaxSize): - return ("autoSaveSettings", [("flags", flags as Any), ("videoMaxSize", videoMaxSize as Any)]) - } - } - + public class Cons_autoSaveSettings { + public var flags: Int32 + public var videoMaxSize: Int64? + public init(flags: Int32, videoMaxSize: Int64?) { + self.flags = flags + self.videoMaxSize = videoMaxSize + } + } + case autoSaveSettings(Cons_autoSaveSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .autoSaveSettings(let _data): + if boxed { + buffer.appendInt32(-934791986) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt64(_data.videoMaxSize!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .autoSaveSettings(let _data): + return ("autoSaveSettings", [("flags", _data.flags as Any), ("videoMaxSize", _data.videoMaxSize as Any)]) + } + } + public static func parse_autoSaveSettings(_ reader: BufferReader) -> AutoSaveSettings? { var _1: Int32? _1 = reader.readInt32() var _2: Int64? - if Int(_1!) & Int(1 << 2) != 0 {_2 = reader.readInt64() } + if Int(_1!) & Int(1 << 2) != 0 { + _2 = reader.readInt64() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 2) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.AutoSaveSettings.autoSaveSettings(flags: _1!, videoMaxSize: _2) + if _c1 && _c2 { + return Api.AutoSaveSettings.autoSaveSettings(Cons_autoSaveSettings(flags: _1!, videoMaxSize: _2)) + } + else { + return nil + } } - } } public extension Api { enum AvailableEffect: TypeConstructorDescription { - case availableEffect(flags: Int32, id: Int64, emoticon: String, staticIconId: Int64?, effectStickerId: Int64, effectAnimationId: Int64?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .availableEffect(let flags, let id, let emoticon, let staticIconId, let effectStickerId, let effectAnimationId): - if boxed { - buffer.appendInt32(-1815879042) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeString(emoticon, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(staticIconId!, buffer: buffer, boxed: false)} - serializeInt64(effectStickerId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt64(effectAnimationId!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .availableEffect(let flags, let id, let emoticon, let staticIconId, let effectStickerId, let effectAnimationId): - return ("availableEffect", [("flags", flags as Any), ("id", id as Any), ("emoticon", emoticon as Any), ("staticIconId", staticIconId as Any), ("effectStickerId", effectStickerId as Any), ("effectAnimationId", effectAnimationId as Any)]) - } - } - + public class Cons_availableEffect { + public var flags: Int32 + public var id: Int64 + public var emoticon: String + public var staticIconId: Int64? + public var effectStickerId: Int64 + public var effectAnimationId: Int64? + public init(flags: Int32, id: Int64, emoticon: String, staticIconId: Int64?, effectStickerId: Int64, effectAnimationId: Int64?) { + self.flags = flags + self.id = id + self.emoticon = emoticon + self.staticIconId = staticIconId + self.effectStickerId = effectStickerId + self.effectAnimationId = effectAnimationId + } + } + case availableEffect(Cons_availableEffect) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .availableEffect(let _data): + if boxed { + buffer.appendInt32(-1815879042) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeString(_data.emoticon, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.staticIconId!, buffer: buffer, boxed: false) + } + serializeInt64(_data.effectStickerId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt64(_data.effectAnimationId!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .availableEffect(let _data): + return ("availableEffect", [("flags", _data.flags as Any), ("id", _data.id as Any), ("emoticon", _data.emoticon as Any), ("staticIconId", _data.staticIconId as Any), ("effectStickerId", _data.effectStickerId as Any), ("effectAnimationId", _data.effectAnimationId as Any)]) + } + } + public static func parse_availableEffect(_ reader: BufferReader) -> AvailableEffect? { var _1: Int32? _1 = reader.readInt32() @@ -682,59 +839,89 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_4 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = reader.readInt64() + } var _5: Int64? _5 = reader.readInt64() var _6: Int64? - if Int(_1!) & Int(1 << 1) != 0 {_6 = reader.readInt64() } + if Int(_1!) & Int(1 << 1) != 0 { + _6 = reader.readInt64() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil let _c5 = _5 != nil let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.AvailableEffect.availableEffect(flags: _1!, id: _2!, emoticon: _3!, staticIconId: _4, effectStickerId: _5!, effectAnimationId: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.AvailableEffect.availableEffect(Cons_availableEffect(flags: _1!, id: _2!, emoticon: _3!, staticIconId: _4, effectStickerId: _5!, effectAnimationId: _6)) + } + else { + return nil + } } - } } public extension Api { enum AvailableReaction: TypeConstructorDescription { - case availableReaction(flags: Int32, reaction: String, title: String, staticIcon: Api.Document, appearAnimation: Api.Document, selectAnimation: Api.Document, activateAnimation: Api.Document, effectAnimation: Api.Document, aroundAnimation: Api.Document?, centerIcon: Api.Document?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .availableReaction(let flags, let reaction, let title, let staticIcon, let appearAnimation, let selectAnimation, let activateAnimation, let effectAnimation, let aroundAnimation, let centerIcon): - if boxed { - buffer.appendInt32(-1065882623) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(reaction, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - staticIcon.serialize(buffer, true) - appearAnimation.serialize(buffer, true) - selectAnimation.serialize(buffer, true) - activateAnimation.serialize(buffer, true) - effectAnimation.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {aroundAnimation!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {centerIcon!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .availableReaction(let flags, let reaction, let title, let staticIcon, let appearAnimation, let selectAnimation, let activateAnimation, let effectAnimation, let aroundAnimation, let centerIcon): - return ("availableReaction", [("flags", flags as Any), ("reaction", reaction as Any), ("title", title as Any), ("staticIcon", staticIcon as Any), ("appearAnimation", appearAnimation as Any), ("selectAnimation", selectAnimation as Any), ("activateAnimation", activateAnimation as Any), ("effectAnimation", effectAnimation as Any), ("aroundAnimation", aroundAnimation as Any), ("centerIcon", centerIcon as Any)]) - } - } - + public class Cons_availableReaction { + public var flags: Int32 + public var reaction: String + public var title: String + public var staticIcon: Api.Document + public var appearAnimation: Api.Document + public var selectAnimation: Api.Document + public var activateAnimation: Api.Document + public var effectAnimation: Api.Document + public var aroundAnimation: Api.Document? + public var centerIcon: Api.Document? + public init(flags: Int32, reaction: String, title: String, staticIcon: Api.Document, appearAnimation: Api.Document, selectAnimation: Api.Document, activateAnimation: Api.Document, effectAnimation: Api.Document, aroundAnimation: Api.Document?, centerIcon: Api.Document?) { + self.flags = flags + self.reaction = reaction + self.title = title + self.staticIcon = staticIcon + self.appearAnimation = appearAnimation + self.selectAnimation = selectAnimation + self.activateAnimation = activateAnimation + self.effectAnimation = effectAnimation + self.aroundAnimation = aroundAnimation + self.centerIcon = centerIcon + } + } + case availableReaction(Cons_availableReaction) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .availableReaction(let _data): + if boxed { + buffer.appendInt32(-1065882623) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.reaction, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + _data.staticIcon.serialize(buffer, true) + _data.appearAnimation.serialize(buffer, true) + _data.selectAnimation.serialize(buffer, true) + _data.activateAnimation.serialize(buffer, true) + _data.effectAnimation.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.aroundAnimation!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.centerIcon!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .availableReaction(let _data): + return ("availableReaction", [("flags", _data.flags as Any), ("reaction", _data.reaction as Any), ("title", _data.title as Any), ("staticIcon", _data.staticIcon as Any), ("appearAnimation", _data.appearAnimation as Any), ("selectAnimation", _data.selectAnimation as Any), ("activateAnimation", _data.activateAnimation as Any), ("effectAnimation", _data.effectAnimation as Any), ("aroundAnimation", _data.aroundAnimation as Any), ("centerIcon", _data.centerIcon as Any)]) + } + } + public static func parse_availableReaction(_ reader: BufferReader) -> AvailableReaction? { var _1: Int32? _1 = reader.readInt32() @@ -763,13 +950,17 @@ public extension Api { _8 = Api.parse(reader, signature: signature) as? Api.Document } var _9: Api.Document? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.Document - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.Document + } + } var _10: Api.Document? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _10 = Api.parse(reader, signature: signature) as? Api.Document - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _10 = Api.parse(reader, signature: signature) as? Api.Document + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -780,44 +971,46 @@ public extension Api { let _c8 = _8 != nil let _c9 = (Int(_1!) & Int(1 << 1) == 0) || _9 != nil let _c10 = (Int(_1!) & Int(1 << 1) == 0) || _10 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - return Api.AvailableReaction.availableReaction(flags: _1!, reaction: _2!, title: _3!, staticIcon: _4!, appearAnimation: _5!, selectAnimation: _6!, activateAnimation: _7!, effectAnimation: _8!, aroundAnimation: _9, centerIcon: _10) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 { + return Api.AvailableReaction.availableReaction(Cons_availableReaction(flags: _1!, reaction: _2!, title: _3!, staticIcon: _4!, appearAnimation: _5!, selectAnimation: _6!, activateAnimation: _7!, effectAnimation: _8!, aroundAnimation: _9, centerIcon: _10)) + } + else { + return nil + } } - } } public extension Api { enum BankCardOpenUrl: TypeConstructorDescription { - case bankCardOpenUrl(url: String, name: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .bankCardOpenUrl(let url, let name): - if boxed { - buffer.appendInt32(-177732982) - } - serializeString(url, buffer: buffer, boxed: false) - serializeString(name, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .bankCardOpenUrl(let url, let name): - return ("bankCardOpenUrl", [("url", url as Any), ("name", name as Any)]) - } - } - + public class Cons_bankCardOpenUrl { + public var url: String + public var name: String + public init(url: String, name: String) { + self.url = url + self.name = name + } + } + case bankCardOpenUrl(Cons_bankCardOpenUrl) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .bankCardOpenUrl(let _data): + if boxed { + buffer.appendInt32(-177732982) + } + serializeString(_data.url, buffer: buffer, boxed: false) + serializeString(_data.name, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .bankCardOpenUrl(let _data): + return ("bankCardOpenUrl", [("url", _data.url as Any), ("name", _data.name as Any)]) + } + } + public static func parse_bankCardOpenUrl(_ reader: BufferReader) -> BankCardOpenUrl? { var _1: String? _1 = parseString(reader) @@ -825,11 +1018,13 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.BankCardOpenUrl.bankCardOpenUrl(url: _1!, name: _2!) + if _c1 && _c2 { + return Api.BankCardOpenUrl.bankCardOpenUrl(Cons_bankCardOpenUrl(url: _1!, name: _2!)) + } + else { + return nil + } } - } } public extension Api { @@ -839,57 +1034,52 @@ public extension Api { case baseThemeDay case baseThemeNight case baseThemeTinted - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .baseThemeArctic: - if boxed { - buffer.appendInt32(1527845466) - } - - break - case .baseThemeClassic: - if boxed { - buffer.appendInt32(-1012849566) - } - - break - case .baseThemeDay: - if boxed { - buffer.appendInt32(-69724536) - } - - break - case .baseThemeNight: - if boxed { - buffer.appendInt32(-1212997976) - } - - break - case .baseThemeTinted: - if boxed { - buffer.appendInt32(1834973166) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .baseThemeArctic: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .baseThemeArctic: + if boxed { + buffer.appendInt32(1527845466) + } + break + case .baseThemeClassic: + if boxed { + buffer.appendInt32(-1012849566) + } + break + case .baseThemeDay: + if boxed { + buffer.appendInt32(-69724536) + } + break + case .baseThemeNight: + if boxed { + buffer.appendInt32(-1212997976) + } + break + case .baseThemeTinted: + if boxed { + buffer.appendInt32(1834973166) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .baseThemeArctic: return ("baseThemeArctic", []) - case .baseThemeClassic: + case .baseThemeClassic: return ("baseThemeClassic", []) - case .baseThemeDay: + case .baseThemeDay: return ("baseThemeDay", []) - case .baseThemeNight: + case .baseThemeNight: return ("baseThemeNight", []) - case .baseThemeTinted: + case .baseThemeTinted: return ("baseThemeTinted", []) - } - } - + } + } + public static func parse_baseThemeArctic(_ reader: BufferReader) -> BaseTheme? { return Api.BaseTheme.baseThemeArctic } @@ -905,34 +1095,47 @@ public extension Api { public static func parse_baseThemeTinted(_ reader: BufferReader) -> BaseTheme? { return Api.BaseTheme.baseThemeTinted } - } } public extension Api { enum Birthday: TypeConstructorDescription { - case birthday(flags: Int32, day: Int32, month: Int32, year: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .birthday(let flags, let day, let month, let year): - if boxed { - buffer.appendInt32(1821253126) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(day, buffer: buffer, boxed: false) - serializeInt32(month, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(year!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .birthday(let flags, let day, let month, let year): - return ("birthday", [("flags", flags as Any), ("day", day as Any), ("month", month as Any), ("year", year as Any)]) - } - } - + public class Cons_birthday { + public var flags: Int32 + public var day: Int32 + public var month: Int32 + public var year: Int32? + public init(flags: Int32, day: Int32, month: Int32, year: Int32?) { + self.flags = flags + self.day = day + self.month = month + self.year = year + } + } + case birthday(Cons_birthday) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .birthday(let _data): + if boxed { + buffer.appendInt32(1821253126) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.day, buffer: buffer, boxed: false) + serializeInt32(_data.month, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.year!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .birthday(let _data): + return ("birthday", [("flags", _data.flags as Any), ("day", _data.day as Any), ("month", _data.month as Any), ("year", _data.year as Any)]) + } + } + public static func parse_birthday(_ reader: BufferReader) -> Birthday? { var _1: Int32? _1 = reader.readInt32() @@ -941,109 +1144,150 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.Birthday.birthday(flags: _1!, day: _2!, month: _3!, year: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.Birthday.birthday(Cons_birthday(flags: _1!, day: _2!, month: _3!, year: _4)) + } + else { + return nil + } } - } } public extension Api { enum Bool: TypeConstructorDescription { case boolFalse case boolTrue - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .boolFalse: - if boxed { - buffer.appendInt32(-1132882121) - } - - break - case .boolTrue: - if boxed { - buffer.appendInt32(-1720552011) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .boolFalse: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .boolFalse: + if boxed { + buffer.appendInt32(-1132882121) + } + break + case .boolTrue: + if boxed { + buffer.appendInt32(-1720552011) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .boolFalse: return ("boolFalse", []) - case .boolTrue: + case .boolTrue: return ("boolTrue", []) - } - } - + } + } + public static func parse_boolFalse(_ reader: BufferReader) -> Bool? { return Api.Bool.boolFalse } public static func parse_boolTrue(_ reader: BufferReader) -> Bool? { return Api.Bool.boolTrue } - } } public extension Api { enum Boost: TypeConstructorDescription { - case boost(flags: Int32, id: String, userId: Int64?, giveawayMsgId: Int32?, date: Int32, expires: Int32, usedGiftSlug: String?, multiplier: Int32?, stars: Int64?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .boost(let flags, let id, let userId, let giveawayMsgId, let date, let expires, let usedGiftSlug, let multiplier, let stars): - if boxed { - buffer.appendInt32(1262359766) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(userId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(giveawayMsgId!, buffer: buffer, boxed: false)} - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt32(expires, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {serializeString(usedGiftSlug!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeInt32(multiplier!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 6) != 0 {serializeInt64(stars!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .boost(let flags, let id, let userId, let giveawayMsgId, let date, let expires, let usedGiftSlug, let multiplier, let stars): - return ("boost", [("flags", flags as Any), ("id", id as Any), ("userId", userId as Any), ("giveawayMsgId", giveawayMsgId as Any), ("date", date as Any), ("expires", expires as Any), ("usedGiftSlug", usedGiftSlug as Any), ("multiplier", multiplier as Any), ("stars", stars as Any)]) - } - } - + public class Cons_boost { + public var flags: Int32 + public var id: String + public var userId: Int64? + public var giveawayMsgId: Int32? + public var date: Int32 + public var expires: Int32 + public var usedGiftSlug: String? + public var multiplier: Int32? + public var stars: Int64? + public init(flags: Int32, id: String, userId: Int64?, giveawayMsgId: Int32?, date: Int32, expires: Int32, usedGiftSlug: String?, multiplier: Int32?, stars: Int64?) { + self.flags = flags + self.id = id + self.userId = userId + self.giveawayMsgId = giveawayMsgId + self.date = date + self.expires = expires + self.usedGiftSlug = usedGiftSlug + self.multiplier = multiplier + self.stars = stars + } + } + case boost(Cons_boost) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .boost(let _data): + if boxed { + buffer.appendInt32(1262359766) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.id, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.userId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.giveawayMsgId!, buffer: buffer, boxed: false) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt32(_data.expires, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeString(_data.usedGiftSlug!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeInt32(_data.multiplier!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + serializeInt64(_data.stars!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .boost(let _data): + return ("boost", [("flags", _data.flags as Any), ("id", _data.id as Any), ("userId", _data.userId as Any), ("giveawayMsgId", _data.giveawayMsgId as Any), ("date", _data.date as Any), ("expires", _data.expires as Any), ("usedGiftSlug", _data.usedGiftSlug as Any), ("multiplier", _data.multiplier as Any), ("stars", _data.stars as Any)]) + } + } + public static func parse_boost(_ reader: BufferReader) -> Boost? { var _1: Int32? _1 = reader.readInt32() var _2: String? _2 = parseString(reader) var _3: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt64() + } var _4: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _4 = reader.readInt32() + } var _5: Int32? _5 = reader.readInt32() var _6: Int32? _6 = reader.readInt32() var _7: String? - if Int(_1!) & Int(1 << 4) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 4) != 0 { + _7 = parseString(reader) + } var _8: Int32? - if Int(_1!) & Int(1 << 5) != 0 {_8 = reader.readInt32() } + if Int(_1!) & Int(1 << 5) != 0 { + _8 = reader.readInt32() + } var _9: Int64? - if Int(_1!) & Int(1 << 6) != 0 {_9 = reader.readInt64() } + if Int(_1!) & Int(1 << 6) != 0 { + _9 = reader.readInt64() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil @@ -1053,59 +1297,77 @@ public extension Api { let _c7 = (Int(_1!) & Int(1 << 4) == 0) || _7 != nil let _c8 = (Int(_1!) & Int(1 << 5) == 0) || _8 != nil let _c9 = (Int(_1!) & Int(1 << 6) == 0) || _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.Boost.boost(flags: _1!, id: _2!, userId: _3, giveawayMsgId: _4, date: _5!, expires: _6!, usedGiftSlug: _7, multiplier: _8, stars: _9) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.Boost.boost(Cons_boost(flags: _1!, id: _2!, userId: _3, giveawayMsgId: _4, date: _5!, expires: _6!, usedGiftSlug: _7, multiplier: _8, stars: _9)) + } + else { + return nil + } } - } } public extension Api { enum BotApp: TypeConstructorDescription { - case botApp(flags: Int32, id: Int64, accessHash: Int64, shortName: String, title: String, description: String, photo: Api.Photo, document: Api.Document?, hash: Int64) + public class Cons_botApp { + public var flags: Int32 + public var id: Int64 + public var accessHash: Int64 + public var shortName: String + public var title: String + public var description: String + public var photo: Api.Photo + public var document: Api.Document? + public var hash: Int64 + public init(flags: Int32, id: Int64, accessHash: Int64, shortName: String, title: String, description: String, photo: Api.Photo, document: Api.Document?, hash: Int64) { + self.flags = flags + self.id = id + self.accessHash = accessHash + self.shortName = shortName + self.title = title + self.description = description + self.photo = photo + self.document = document + self.hash = hash + } + } + case botApp(Cons_botApp) case botAppNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botApp(let flags, let id, let accessHash, let shortName, let title, let description, let photo, let document, let hash): - if boxed { - buffer.appendInt32(-1778593322) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeString(shortName, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(description, buffer: buffer, boxed: false) - photo.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {document!.serialize(buffer, true)} - serializeInt64(hash, buffer: buffer, boxed: false) - break - case .botAppNotModified: - if boxed { - buffer.appendInt32(1571189943) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botApp(let flags, let id, let accessHash, let shortName, let title, let description, let photo, let document, let hash): - return ("botApp", [("flags", flags as Any), ("id", id as Any), ("accessHash", accessHash as Any), ("shortName", shortName as Any), ("title", title as Any), ("description", description as Any), ("photo", photo as Any), ("document", document as Any), ("hash", hash as Any)]) - case .botAppNotModified: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botApp(let _data): + if boxed { + buffer.appendInt32(-1778593322) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeString(_data.shortName, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.description, buffer: buffer, boxed: false) + _data.photo.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.document!.serialize(buffer, true) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + break + case .botAppNotModified: + if boxed { + buffer.appendInt32(1571189943) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botApp(let _data): + return ("botApp", [("flags", _data.flags as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("shortName", _data.shortName as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("photo", _data.photo as Any), ("document", _data.document as Any), ("hash", _data.hash as Any)]) + case .botAppNotModified: return ("botAppNotModified", []) - } - } - + } + } + public static func parse_botApp(_ reader: BufferReader) -> BotApp? { var _1: Int32? _1 = reader.readInt32() @@ -1124,9 +1386,11 @@ public extension Api { _7 = Api.parse(reader, signature: signature) as? Api.Photo } var _8: Api.Document? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.Document - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.Document + } + } var _9: Int64? _9 = reader.readInt64() let _c1 = _1 != nil @@ -1138,77 +1402,106 @@ public extension Api { let _c7 = _7 != nil let _c8 = (Int(_1!) & Int(1 << 0) == 0) || _8 != nil let _c9 = _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.BotApp.botApp(flags: _1!, id: _2!, accessHash: _3!, shortName: _4!, title: _5!, description: _6!, photo: _7!, document: _8, hash: _9!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.BotApp.botApp(Cons_botApp(flags: _1!, id: _2!, accessHash: _3!, shortName: _4!, title: _5!, description: _6!, photo: _7!, document: _8, hash: _9!)) + } + else { + return nil + } } public static func parse_botAppNotModified(_ reader: BufferReader) -> BotApp? { return Api.BotApp.botAppNotModified } - } } public extension Api { enum BotAppSettings: TypeConstructorDescription { - case botAppSettings(flags: Int32, placeholderPath: Buffer?, backgroundColor: Int32?, backgroundDarkColor: Int32?, headerColor: Int32?, headerDarkColor: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botAppSettings(let flags, let placeholderPath, let backgroundColor, let backgroundDarkColor, let headerColor, let headerDarkColor): - if boxed { - buffer.appendInt32(-912582320) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeBytes(placeholderPath!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(backgroundColor!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(backgroundDarkColor!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(headerColor!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(headerDarkColor!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botAppSettings(let flags, let placeholderPath, let backgroundColor, let backgroundDarkColor, let headerColor, let headerDarkColor): - return ("botAppSettings", [("flags", flags as Any), ("placeholderPath", placeholderPath as Any), ("backgroundColor", backgroundColor as Any), ("backgroundDarkColor", backgroundDarkColor as Any), ("headerColor", headerColor as Any), ("headerDarkColor", headerDarkColor as Any)]) - } - } - + public class Cons_botAppSettings { + public var flags: Int32 + public var placeholderPath: Buffer? + public var backgroundColor: Int32? + public var backgroundDarkColor: Int32? + public var headerColor: Int32? + public var headerDarkColor: Int32? + public init(flags: Int32, placeholderPath: Buffer?, backgroundColor: Int32?, backgroundDarkColor: Int32?, headerColor: Int32?, headerDarkColor: Int32?) { + self.flags = flags + self.placeholderPath = placeholderPath + self.backgroundColor = backgroundColor + self.backgroundDarkColor = backgroundDarkColor + self.headerColor = headerColor + self.headerDarkColor = headerDarkColor + } + } + case botAppSettings(Cons_botAppSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botAppSettings(let _data): + if boxed { + buffer.appendInt32(-912582320) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeBytes(_data.placeholderPath!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.backgroundColor!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.backgroundDarkColor!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.headerColor!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.headerDarkColor!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botAppSettings(let _data): + return ("botAppSettings", [("flags", _data.flags as Any), ("placeholderPath", _data.placeholderPath as Any), ("backgroundColor", _data.backgroundColor as Any), ("backgroundDarkColor", _data.backgroundDarkColor as Any), ("headerColor", _data.headerColor as Any), ("headerDarkColor", _data.headerDarkColor as Any)]) + } + } + public static func parse_botAppSettings(_ reader: BufferReader) -> BotAppSettings? { var _1: Int32? _1 = reader.readInt32() var _2: Buffer? - if Int(_1!) & Int(1 << 0) != 0 {_2 = parseBytes(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = parseBytes(reader) + } var _3: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _3 = reader.readInt32() + } var _4: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _4 = reader.readInt32() + } var _5: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 3) != 0 { + _5 = reader.readInt32() + } var _6: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _6 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 3) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 4) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.BotAppSettings.botAppSettings(flags: _1!, placeholderPath: _2, backgroundColor: _3, backgroundDarkColor: _4, headerColor: _5, headerDarkColor: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.BotAppSettings.botAppSettings(Cons_botAppSettings(flags: _1!, placeholderPath: _2, backgroundColor: _3, backgroundDarkColor: _4, headerColor: _5, headerDarkColor: _6)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api10.swift b/submodules/TelegramApi/Sources/Api10.swift index 08d007a9..cd73820e 100644 --- a/submodules/TelegramApi/Sources/Api10.swift +++ b/submodules/TelegramApi/Sources/Api10.swift @@ -1,130 +1,235 @@ public extension Api { indirect enum InputFileLocation: TypeConstructorDescription { - case inputDocumentFileLocation(id: Int64, accessHash: Int64, fileReference: Buffer, thumbSize: String) - case inputEncryptedFileLocation(id: Int64, accessHash: Int64) - case inputFileLocation(volumeId: Int64, localId: Int32, secret: Int64, fileReference: Buffer) - case inputGroupCallStream(flags: Int32, call: Api.InputGroupCall, timeMs: Int64, scale: Int32, videoChannel: Int32?, videoQuality: Int32?) - case inputPeerPhotoFileLocation(flags: Int32, peer: Api.InputPeer, photoId: Int64) - case inputPhotoFileLocation(id: Int64, accessHash: Int64, fileReference: Buffer, thumbSize: String) - case inputPhotoLegacyFileLocation(id: Int64, accessHash: Int64, fileReference: Buffer, volumeId: Int64, localId: Int32, secret: Int64) - case inputSecureFileLocation(id: Int64, accessHash: Int64) - case inputStickerSetThumb(stickerset: Api.InputStickerSet, thumbVersion: Int32) + public class Cons_inputDocumentFileLocation { + public var id: Int64 + public var accessHash: Int64 + public var fileReference: Buffer + public var thumbSize: String + public init(id: Int64, accessHash: Int64, fileReference: Buffer, thumbSize: String) { + self.id = id + self.accessHash = accessHash + self.fileReference = fileReference + self.thumbSize = thumbSize + } + } + public class Cons_inputEncryptedFileLocation { + public var id: Int64 + public var accessHash: Int64 + public init(id: Int64, accessHash: Int64) { + self.id = id + self.accessHash = accessHash + } + } + public class Cons_inputFileLocation { + public var volumeId: Int64 + public var localId: Int32 + public var secret: Int64 + public var fileReference: Buffer + public init(volumeId: Int64, localId: Int32, secret: Int64, fileReference: Buffer) { + self.volumeId = volumeId + self.localId = localId + self.secret = secret + self.fileReference = fileReference + } + } + public class Cons_inputGroupCallStream { + public var flags: Int32 + public var call: Api.InputGroupCall + public var timeMs: Int64 + public var scale: Int32 + public var videoChannel: Int32? + public var videoQuality: Int32? + public init(flags: Int32, call: Api.InputGroupCall, timeMs: Int64, scale: Int32, videoChannel: Int32?, videoQuality: Int32?) { + self.flags = flags + self.call = call + self.timeMs = timeMs + self.scale = scale + self.videoChannel = videoChannel + self.videoQuality = videoQuality + } + } + public class Cons_inputPeerPhotoFileLocation { + public var flags: Int32 + public var peer: Api.InputPeer + public var photoId: Int64 + public init(flags: Int32, peer: Api.InputPeer, photoId: Int64) { + self.flags = flags + self.peer = peer + self.photoId = photoId + } + } + public class Cons_inputPhotoFileLocation { + public var id: Int64 + public var accessHash: Int64 + public var fileReference: Buffer + public var thumbSize: String + public init(id: Int64, accessHash: Int64, fileReference: Buffer, thumbSize: String) { + self.id = id + self.accessHash = accessHash + self.fileReference = fileReference + self.thumbSize = thumbSize + } + } + public class Cons_inputPhotoLegacyFileLocation { + public var id: Int64 + public var accessHash: Int64 + public var fileReference: Buffer + public var volumeId: Int64 + public var localId: Int32 + public var secret: Int64 + public init(id: Int64, accessHash: Int64, fileReference: Buffer, volumeId: Int64, localId: Int32, secret: Int64) { + self.id = id + self.accessHash = accessHash + self.fileReference = fileReference + self.volumeId = volumeId + self.localId = localId + self.secret = secret + } + } + public class Cons_inputSecureFileLocation { + public var id: Int64 + public var accessHash: Int64 + public init(id: Int64, accessHash: Int64) { + self.id = id + self.accessHash = accessHash + } + } + public class Cons_inputStickerSetThumb { + public var stickerset: Api.InputStickerSet + public var thumbVersion: Int32 + public init(stickerset: Api.InputStickerSet, thumbVersion: Int32) { + self.stickerset = stickerset + self.thumbVersion = thumbVersion + } + } + case inputDocumentFileLocation(Cons_inputDocumentFileLocation) + case inputEncryptedFileLocation(Cons_inputEncryptedFileLocation) + case inputFileLocation(Cons_inputFileLocation) + case inputGroupCallStream(Cons_inputGroupCallStream) + case inputPeerPhotoFileLocation(Cons_inputPeerPhotoFileLocation) + case inputPhotoFileLocation(Cons_inputPhotoFileLocation) + case inputPhotoLegacyFileLocation(Cons_inputPhotoLegacyFileLocation) + case inputSecureFileLocation(Cons_inputSecureFileLocation) + case inputStickerSetThumb(Cons_inputStickerSetThumb) case inputTakeoutFileLocation - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputDocumentFileLocation(let id, let accessHash, let fileReference, let thumbSize): - if boxed { - buffer.appendInt32(-1160743548) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeBytes(fileReference, buffer: buffer, boxed: false) - serializeString(thumbSize, buffer: buffer, boxed: false) - break - case .inputEncryptedFileLocation(let id, let accessHash): - if boxed { - buffer.appendInt32(-182231723) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - case .inputFileLocation(let volumeId, let localId, let secret, let fileReference): - if boxed { - buffer.appendInt32(-539317279) - } - serializeInt64(volumeId, buffer: buffer, boxed: false) - serializeInt32(localId, buffer: buffer, boxed: false) - serializeInt64(secret, buffer: buffer, boxed: false) - serializeBytes(fileReference, buffer: buffer, boxed: false) - break - case .inputGroupCallStream(let flags, let call, let timeMs, let scale, let videoChannel, let videoQuality): - if boxed { - buffer.appendInt32(93890858) - } - serializeInt32(flags, buffer: buffer, boxed: false) - call.serialize(buffer, true) - serializeInt64(timeMs, buffer: buffer, boxed: false) - serializeInt32(scale, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(videoChannel!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(videoQuality!, buffer: buffer, boxed: false)} - break - case .inputPeerPhotoFileLocation(let flags, let peer, let photoId): - if boxed { - buffer.appendInt32(925204121) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt64(photoId, buffer: buffer, boxed: false) - break - case .inputPhotoFileLocation(let id, let accessHash, let fileReference, let thumbSize): - if boxed { - buffer.appendInt32(1075322878) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeBytes(fileReference, buffer: buffer, boxed: false) - serializeString(thumbSize, buffer: buffer, boxed: false) - break - case .inputPhotoLegacyFileLocation(let id, let accessHash, let fileReference, let volumeId, let localId, let secret): - if boxed { - buffer.appendInt32(-667654413) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeBytes(fileReference, buffer: buffer, boxed: false) - serializeInt64(volumeId, buffer: buffer, boxed: false) - serializeInt32(localId, buffer: buffer, boxed: false) - serializeInt64(secret, buffer: buffer, boxed: false) - break - case .inputSecureFileLocation(let id, let accessHash): - if boxed { - buffer.appendInt32(-876089816) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - case .inputStickerSetThumb(let stickerset, let thumbVersion): - if boxed { - buffer.appendInt32(-1652231205) - } - stickerset.serialize(buffer, true) - serializeInt32(thumbVersion, buffer: buffer, boxed: false) - break - case .inputTakeoutFileLocation: - if boxed { - buffer.appendInt32(700340377) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputDocumentFileLocation(let id, let accessHash, let fileReference, let thumbSize): - return ("inputDocumentFileLocation", [("id", id as Any), ("accessHash", accessHash as Any), ("fileReference", fileReference as Any), ("thumbSize", thumbSize as Any)]) - case .inputEncryptedFileLocation(let id, let accessHash): - return ("inputEncryptedFileLocation", [("id", id as Any), ("accessHash", accessHash as Any)]) - case .inputFileLocation(let volumeId, let localId, let secret, let fileReference): - return ("inputFileLocation", [("volumeId", volumeId as Any), ("localId", localId as Any), ("secret", secret as Any), ("fileReference", fileReference as Any)]) - case .inputGroupCallStream(let flags, let call, let timeMs, let scale, let videoChannel, let videoQuality): - return ("inputGroupCallStream", [("flags", flags as Any), ("call", call as Any), ("timeMs", timeMs as Any), ("scale", scale as Any), ("videoChannel", videoChannel as Any), ("videoQuality", videoQuality as Any)]) - case .inputPeerPhotoFileLocation(let flags, let peer, let photoId): - return ("inputPeerPhotoFileLocation", [("flags", flags as Any), ("peer", peer as Any), ("photoId", photoId as Any)]) - case .inputPhotoFileLocation(let id, let accessHash, let fileReference, let thumbSize): - return ("inputPhotoFileLocation", [("id", id as Any), ("accessHash", accessHash as Any), ("fileReference", fileReference as Any), ("thumbSize", thumbSize as Any)]) - case .inputPhotoLegacyFileLocation(let id, let accessHash, let fileReference, let volumeId, let localId, let secret): - return ("inputPhotoLegacyFileLocation", [("id", id as Any), ("accessHash", accessHash as Any), ("fileReference", fileReference as Any), ("volumeId", volumeId as Any), ("localId", localId as Any), ("secret", secret as Any)]) - case .inputSecureFileLocation(let id, let accessHash): - return ("inputSecureFileLocation", [("id", id as Any), ("accessHash", accessHash as Any)]) - case .inputStickerSetThumb(let stickerset, let thumbVersion): - return ("inputStickerSetThumb", [("stickerset", stickerset as Any), ("thumbVersion", thumbVersion as Any)]) - case .inputTakeoutFileLocation: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputDocumentFileLocation(let _data): + if boxed { + buffer.appendInt32(-1160743548) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeBytes(_data.fileReference, buffer: buffer, boxed: false) + serializeString(_data.thumbSize, buffer: buffer, boxed: false) + break + case .inputEncryptedFileLocation(let _data): + if boxed { + buffer.appendInt32(-182231723) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + case .inputFileLocation(let _data): + if boxed { + buffer.appendInt32(-539317279) + } + serializeInt64(_data.volumeId, buffer: buffer, boxed: false) + serializeInt32(_data.localId, buffer: buffer, boxed: false) + serializeInt64(_data.secret, buffer: buffer, boxed: false) + serializeBytes(_data.fileReference, buffer: buffer, boxed: false) + break + case .inputGroupCallStream(let _data): + if boxed { + buffer.appendInt32(93890858) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.call.serialize(buffer, true) + serializeInt64(_data.timeMs, buffer: buffer, boxed: false) + serializeInt32(_data.scale, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.videoChannel!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.videoQuality!, buffer: buffer, boxed: false) + } + break + case .inputPeerPhotoFileLocation(let _data): + if boxed { + buffer.appendInt32(925204121) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeInt64(_data.photoId, buffer: buffer, boxed: false) + break + case .inputPhotoFileLocation(let _data): + if boxed { + buffer.appendInt32(1075322878) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeBytes(_data.fileReference, buffer: buffer, boxed: false) + serializeString(_data.thumbSize, buffer: buffer, boxed: false) + break + case .inputPhotoLegacyFileLocation(let _data): + if boxed { + buffer.appendInt32(-667654413) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeBytes(_data.fileReference, buffer: buffer, boxed: false) + serializeInt64(_data.volumeId, buffer: buffer, boxed: false) + serializeInt32(_data.localId, buffer: buffer, boxed: false) + serializeInt64(_data.secret, buffer: buffer, boxed: false) + break + case .inputSecureFileLocation(let _data): + if boxed { + buffer.appendInt32(-876089816) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + case .inputStickerSetThumb(let _data): + if boxed { + buffer.appendInt32(-1652231205) + } + _data.stickerset.serialize(buffer, true) + serializeInt32(_data.thumbVersion, buffer: buffer, boxed: false) + break + case .inputTakeoutFileLocation: + if boxed { + buffer.appendInt32(700340377) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputDocumentFileLocation(let _data): + return ("inputDocumentFileLocation", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("fileReference", _data.fileReference as Any), ("thumbSize", _data.thumbSize as Any)]) + case .inputEncryptedFileLocation(let _data): + return ("inputEncryptedFileLocation", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any)]) + case .inputFileLocation(let _data): + return ("inputFileLocation", [("volumeId", _data.volumeId as Any), ("localId", _data.localId as Any), ("secret", _data.secret as Any), ("fileReference", _data.fileReference as Any)]) + case .inputGroupCallStream(let _data): + return ("inputGroupCallStream", [("flags", _data.flags as Any), ("call", _data.call as Any), ("timeMs", _data.timeMs as Any), ("scale", _data.scale as Any), ("videoChannel", _data.videoChannel as Any), ("videoQuality", _data.videoQuality as Any)]) + case .inputPeerPhotoFileLocation(let _data): + return ("inputPeerPhotoFileLocation", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("photoId", _data.photoId as Any)]) + case .inputPhotoFileLocation(let _data): + return ("inputPhotoFileLocation", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("fileReference", _data.fileReference as Any), ("thumbSize", _data.thumbSize as Any)]) + case .inputPhotoLegacyFileLocation(let _data): + return ("inputPhotoLegacyFileLocation", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("fileReference", _data.fileReference as Any), ("volumeId", _data.volumeId as Any), ("localId", _data.localId as Any), ("secret", _data.secret as Any)]) + case .inputSecureFileLocation(let _data): + return ("inputSecureFileLocation", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any)]) + case .inputStickerSetThumb(let _data): + return ("inputStickerSetThumb", [("stickerset", _data.stickerset as Any), ("thumbVersion", _data.thumbVersion as Any)]) + case .inputTakeoutFileLocation: return ("inputTakeoutFileLocation", []) - } - } - + } + } + public static func parse_inputDocumentFileLocation(_ reader: BufferReader) -> InputFileLocation? { var _1: Int64? _1 = reader.readInt64() @@ -138,11 +243,12 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputFileLocation.inputDocumentFileLocation(id: _1!, accessHash: _2!, fileReference: _3!, thumbSize: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputFileLocation.inputDocumentFileLocation(Cons_inputDocumentFileLocation(id: _1!, accessHash: _2!, fileReference: _3!, thumbSize: _4!)) + } + else { + return nil + } } public static func parse_inputEncryptedFileLocation(_ reader: BufferReader) -> InputFileLocation? { var _1: Int64? @@ -151,9 +257,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputFileLocation.inputEncryptedFileLocation(id: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputFileLocation.inputEncryptedFileLocation(Cons_inputEncryptedFileLocation(id: _1!, accessHash: _2!)) + } + else { + return nil + } } public static func parse_inputFileLocation(_ reader: BufferReader) -> InputFileLocation? { var _1: Int64? @@ -168,11 +277,12 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputFileLocation.inputFileLocation(volumeId: _1!, localId: _2!, secret: _3!, fileReference: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputFileLocation.inputFileLocation(Cons_inputFileLocation(volumeId: _1!, localId: _2!, secret: _3!, fileReference: _4!)) + } + else { + return nil + } } public static func parse_inputGroupCallStream(_ reader: BufferReader) -> InputFileLocation? { var _1: Int32? @@ -186,22 +296,25 @@ public extension Api { var _4: Int32? _4 = reader.readInt32() var _5: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _5 = reader.readInt32() + } var _6: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _6 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.InputFileLocation.inputGroupCallStream(flags: _1!, call: _2!, timeMs: _3!, scale: _4!, videoChannel: _5, videoQuality: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.InputFileLocation.inputGroupCallStream(Cons_inputGroupCallStream(flags: _1!, call: _2!, timeMs: _3!, scale: _4!, videoChannel: _5, videoQuality: _6)) + } + else { + return nil + } } public static func parse_inputPeerPhotoFileLocation(_ reader: BufferReader) -> InputFileLocation? { var _1: Int32? @@ -215,10 +328,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputFileLocation.inputPeerPhotoFileLocation(flags: _1!, peer: _2!, photoId: _3!) + if _c1 && _c2 && _c3 { + return Api.InputFileLocation.inputPeerPhotoFileLocation(Cons_inputPeerPhotoFileLocation(flags: _1!, peer: _2!, photoId: _3!)) + } + else { + return nil + } } public static func parse_inputPhotoFileLocation(_ reader: BufferReader) -> InputFileLocation? { var _1: Int64? @@ -233,11 +348,12 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputFileLocation.inputPhotoFileLocation(id: _1!, accessHash: _2!, fileReference: _3!, thumbSize: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputFileLocation.inputPhotoFileLocation(Cons_inputPhotoFileLocation(id: _1!, accessHash: _2!, fileReference: _3!, thumbSize: _4!)) + } + else { + return nil + } } public static func parse_inputPhotoLegacyFileLocation(_ reader: BufferReader) -> InputFileLocation? { var _1: Int64? @@ -258,13 +374,12 @@ public extension Api { let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.InputFileLocation.inputPhotoLegacyFileLocation(id: _1!, accessHash: _2!, fileReference: _3!, volumeId: _4!, localId: _5!, secret: _6!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.InputFileLocation.inputPhotoLegacyFileLocation(Cons_inputPhotoLegacyFileLocation(id: _1!, accessHash: _2!, fileReference: _3!, volumeId: _4!, localId: _5!, secret: _6!)) + } + else { + return nil + } } public static func parse_inputSecureFileLocation(_ reader: BufferReader) -> InputFileLocation? { var _1: Int64? @@ -273,9 +388,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputFileLocation.inputSecureFileLocation(id: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputFileLocation.inputSecureFileLocation(Cons_inputSecureFileLocation(id: _1!, accessHash: _2!)) + } + else { + return nil + } } public static func parse_inputStickerSetThumb(_ reader: BufferReader) -> InputFileLocation? { var _1: Api.InputStickerSet? @@ -286,39 +404,49 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputFileLocation.inputStickerSetThumb(stickerset: _1!, thumbVersion: _2!) + if _c1 && _c2 { + return Api.InputFileLocation.inputStickerSetThumb(Cons_inputStickerSetThumb(stickerset: _1!, thumbVersion: _2!)) + } + else { + return nil + } } public static func parse_inputTakeoutFileLocation(_ reader: BufferReader) -> InputFileLocation? { return Api.InputFileLocation.inputTakeoutFileLocation } - } } public extension Api { indirect enum InputFolderPeer: TypeConstructorDescription { - case inputFolderPeer(peer: Api.InputPeer, folderId: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputFolderPeer(let peer, let folderId): - if boxed { - buffer.appendInt32(-70073706) - } - peer.serialize(buffer, true) - serializeInt32(folderId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputFolderPeer(let peer, let folderId): - return ("inputFolderPeer", [("peer", peer as Any), ("folderId", folderId as Any)]) - } - } - + public class Cons_inputFolderPeer { + public var peer: Api.InputPeer + public var folderId: Int32 + public init(peer: Api.InputPeer, folderId: Int32) { + self.peer = peer + self.folderId = folderId + } + } + case inputFolderPeer(Cons_inputFolderPeer) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputFolderPeer(let _data): + if boxed { + buffer.appendInt32(-70073706) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.folderId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputFolderPeer(let _data): + return ("inputFolderPeer", [("peer", _data.peer as Any), ("folderId", _data.folderId as Any)]) + } + } + public static func parse_inputFolderPeer(_ reader: BufferReader) -> InputFolderPeer? { var _1: Api.InputPeer? if let signature = reader.readInt32() { @@ -328,46 +456,64 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputFolderPeer.inputFolderPeer(peer: _1!, folderId: _2!) + if _c1 && _c2 { + return Api.InputFolderPeer.inputFolderPeer(Cons_inputFolderPeer(peer: _1!, folderId: _2!)) + } + else { + return nil + } } - } } public extension Api { indirect enum InputGame: TypeConstructorDescription { - case inputGameID(id: Int64, accessHash: Int64) - case inputGameShortName(botId: Api.InputUser, shortName: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputGameID(let id, let accessHash): - if boxed { - buffer.appendInt32(53231223) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - case .inputGameShortName(let botId, let shortName): - if boxed { - buffer.appendInt32(-1020139510) - } - botId.serialize(buffer, true) - serializeString(shortName, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputGameID(let id, let accessHash): - return ("inputGameID", [("id", id as Any), ("accessHash", accessHash as Any)]) - case .inputGameShortName(let botId, let shortName): - return ("inputGameShortName", [("botId", botId as Any), ("shortName", shortName as Any)]) - } - } - + public class Cons_inputGameID { + public var id: Int64 + public var accessHash: Int64 + public init(id: Int64, accessHash: Int64) { + self.id = id + self.accessHash = accessHash + } + } + public class Cons_inputGameShortName { + public var botId: Api.InputUser + public var shortName: String + public init(botId: Api.InputUser, shortName: String) { + self.botId = botId + self.shortName = shortName + } + } + case inputGameID(Cons_inputGameID) + case inputGameShortName(Cons_inputGameShortName) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputGameID(let _data): + if boxed { + buffer.appendInt32(53231223) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + case .inputGameShortName(let _data): + if boxed { + buffer.appendInt32(-1020139510) + } + _data.botId.serialize(buffer, true) + serializeString(_data.shortName, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputGameID(let _data): + return ("inputGameID", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any)]) + case .inputGameShortName(let _data): + return ("inputGameShortName", [("botId", _data.botId as Any), ("shortName", _data.shortName as Any)]) + } + } + public static func parse_inputGameID(_ reader: BufferReader) -> InputGame? { var _1: Int64? _1 = reader.readInt64() @@ -375,9 +521,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputGame.inputGameID(id: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputGame.inputGameID(Cons_inputGameID(id: _1!, accessHash: _2!)) + } + else { + return nil + } } public static func parse_inputGameShortName(_ reader: BufferReader) -> InputGame? { var _1: Api.InputUser? @@ -388,47 +537,62 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputGame.inputGameShortName(botId: _1!, shortName: _2!) + if _c1 && _c2 { + return Api.InputGame.inputGameShortName(Cons_inputGameShortName(botId: _1!, shortName: _2!)) + } + else { + return nil + } } - } } public extension Api { enum InputGeoPoint: TypeConstructorDescription { - case inputGeoPoint(flags: Int32, lat: Double, long: Double, accuracyRadius: Int32?) + public class Cons_inputGeoPoint { + public var flags: Int32 + public var lat: Double + public var long: Double + public var accuracyRadius: Int32? + public init(flags: Int32, lat: Double, long: Double, accuracyRadius: Int32?) { + self.flags = flags + self.lat = lat + self.long = long + self.accuracyRadius = accuracyRadius + } + } + case inputGeoPoint(Cons_inputGeoPoint) case inputGeoPointEmpty - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputGeoPoint(let flags, let lat, let long, let accuracyRadius): - if boxed { - buffer.appendInt32(1210199983) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeDouble(lat, buffer: buffer, boxed: false) - serializeDouble(long, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(accuracyRadius!, buffer: buffer, boxed: false)} - break - case .inputGeoPointEmpty: - if boxed { - buffer.appendInt32(-457104426) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputGeoPoint(let flags, let lat, let long, let accuracyRadius): - return ("inputGeoPoint", [("flags", flags as Any), ("lat", lat as Any), ("long", long as Any), ("accuracyRadius", accuracyRadius as Any)]) - case .inputGeoPointEmpty: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputGeoPoint(let _data): + if boxed { + buffer.appendInt32(1210199983) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeDouble(_data.lat, buffer: buffer, boxed: false) + serializeDouble(_data.long, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.accuracyRadius!, buffer: buffer, boxed: false) + } + break + case .inputGeoPointEmpty: + if boxed { + buffer.appendInt32(-457104426) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputGeoPoint(let _data): + return ("inputGeoPoint", [("flags", _data.flags as Any), ("lat", _data.lat as Any), ("long", _data.long as Any), ("accuracyRadius", _data.accuracyRadius as Any)]) + case .inputGeoPointEmpty: return ("inputGeoPointEmpty", []) - } - } - + } + } + public static func parse_inputGeoPoint(_ reader: BufferReader) -> InputGeoPoint? { var _1: Int32? _1 = reader.readInt32() @@ -437,64 +601,86 @@ public extension Api { var _3: Double? _3 = reader.readDouble() var _4: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputGeoPoint.inputGeoPoint(flags: _1!, lat: _2!, long: _3!, accuracyRadius: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputGeoPoint.inputGeoPoint(Cons_inputGeoPoint(flags: _1!, lat: _2!, long: _3!, accuracyRadius: _4)) + } + else { + return nil + } } public static func parse_inputGeoPointEmpty(_ reader: BufferReader) -> InputGeoPoint? { return Api.InputGeoPoint.inputGeoPointEmpty } - } } public extension Api { enum InputGroupCall: TypeConstructorDescription { - case inputGroupCall(id: Int64, accessHash: Int64) - case inputGroupCallInviteMessage(msgId: Int32) - case inputGroupCallSlug(slug: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputGroupCall(let id, let accessHash): - if boxed { - buffer.appendInt32(-659913713) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - case .inputGroupCallInviteMessage(let msgId): - if boxed { - buffer.appendInt32(-1945083841) - } - serializeInt32(msgId, buffer: buffer, boxed: false) - break - case .inputGroupCallSlug(let slug): - if boxed { - buffer.appendInt32(-33127873) - } - serializeString(slug, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputGroupCall(let id, let accessHash): - return ("inputGroupCall", [("id", id as Any), ("accessHash", accessHash as Any)]) - case .inputGroupCallInviteMessage(let msgId): - return ("inputGroupCallInviteMessage", [("msgId", msgId as Any)]) - case .inputGroupCallSlug(let slug): - return ("inputGroupCallSlug", [("slug", slug as Any)]) - } - } - + public class Cons_inputGroupCall { + public var id: Int64 + public var accessHash: Int64 + public init(id: Int64, accessHash: Int64) { + self.id = id + self.accessHash = accessHash + } + } + public class Cons_inputGroupCallInviteMessage { + public var msgId: Int32 + public init(msgId: Int32) { + self.msgId = msgId + } + } + public class Cons_inputGroupCallSlug { + public var slug: String + public init(slug: String) { + self.slug = slug + } + } + case inputGroupCall(Cons_inputGroupCall) + case inputGroupCallInviteMessage(Cons_inputGroupCallInviteMessage) + case inputGroupCallSlug(Cons_inputGroupCallSlug) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputGroupCall(let _data): + if boxed { + buffer.appendInt32(-659913713) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + case .inputGroupCallInviteMessage(let _data): + if boxed { + buffer.appendInt32(-1945083841) + } + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + break + case .inputGroupCallSlug(let _data): + if boxed { + buffer.appendInt32(-33127873) + } + serializeString(_data.slug, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputGroupCall(let _data): + return ("inputGroupCall", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any)]) + case .inputGroupCallInviteMessage(let _data): + return ("inputGroupCallInviteMessage", [("msgId", _data.msgId as Any)]) + case .inputGroupCallSlug(let _data): + return ("inputGroupCallSlug", [("slug", _data.slug as Any)]) + } + } + public static func parse_inputGroupCall(_ reader: BufferReader) -> InputGroupCall? { var _1: Int64? _1 = reader.readInt64() @@ -502,193 +688,337 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputGroupCall.inputGroupCall(id: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputGroupCall.inputGroupCall(Cons_inputGroupCall(id: _1!, accessHash: _2!)) + } + else { + return nil + } } public static func parse_inputGroupCallInviteMessage(_ reader: BufferReader) -> InputGroupCall? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputGroupCall.inputGroupCallInviteMessage(msgId: _1!) + if _c1 { + return Api.InputGroupCall.inputGroupCallInviteMessage(Cons_inputGroupCallInviteMessage(msgId: _1!)) + } + else { + return nil + } } public static func parse_inputGroupCallSlug(_ reader: BufferReader) -> InputGroupCall? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputGroupCall.inputGroupCallSlug(slug: _1!) + if _c1 { + return Api.InputGroupCall.inputGroupCallSlug(Cons_inputGroupCallSlug(slug: _1!)) + } + else { + return nil + } } - } } public extension Api { indirect enum InputInvoice: TypeConstructorDescription { - case inputInvoiceBusinessBotTransferStars(bot: Api.InputUser, stars: Int64) - case inputInvoiceChatInviteSubscription(hash: String) - case inputInvoiceMessage(peer: Api.InputPeer, msgId: Int32) - case inputInvoicePremiumAuthCode(purpose: Api.InputStorePaymentPurpose) - case inputInvoicePremiumGiftCode(purpose: Api.InputStorePaymentPurpose, option: Api.PremiumGiftCodeOption) - case inputInvoicePremiumGiftStars(flags: Int32, userId: Api.InputUser, months: Int32, message: Api.TextWithEntities?) - case inputInvoiceSlug(slug: String) - case inputInvoiceStarGift(flags: Int32, peer: Api.InputPeer, giftId: Int64, message: Api.TextWithEntities?) - case inputInvoiceStarGiftAuctionBid(flags: Int32, peer: Api.InputPeer?, giftId: Int64, bidAmount: Int64, message: Api.TextWithEntities?) - case inputInvoiceStarGiftDropOriginalDetails(stargift: Api.InputSavedStarGift) - case inputInvoiceStarGiftPrepaidUpgrade(peer: Api.InputPeer, hash: String) - case inputInvoiceStarGiftResale(flags: Int32, slug: String, toId: Api.InputPeer) - case inputInvoiceStarGiftTransfer(stargift: Api.InputSavedStarGift, toId: Api.InputPeer) - case inputInvoiceStarGiftUpgrade(flags: Int32, stargift: Api.InputSavedStarGift) - case inputInvoiceStars(purpose: Api.InputStorePaymentPurpose) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputInvoiceBusinessBotTransferStars(let bot, let stars): - if boxed { - buffer.appendInt32(-191267262) - } - bot.serialize(buffer, true) - serializeInt64(stars, buffer: buffer, boxed: false) - break - case .inputInvoiceChatInviteSubscription(let hash): - if boxed { - buffer.appendInt32(887591921) - } - serializeString(hash, buffer: buffer, boxed: false) - break - case .inputInvoiceMessage(let peer, let msgId): - if boxed { - buffer.appendInt32(-977967015) - } - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - break - case .inputInvoicePremiumAuthCode(let purpose): - if boxed { - buffer.appendInt32(1048049172) - } - purpose.serialize(buffer, true) - break - case .inputInvoicePremiumGiftCode(let purpose, let option): - if boxed { - buffer.appendInt32(-1734841331) - } - purpose.serialize(buffer, true) - option.serialize(buffer, true) - break - case .inputInvoicePremiumGiftStars(let flags, let userId, let months, let message): - if boxed { - buffer.appendInt32(-625298705) - } - serializeInt32(flags, buffer: buffer, boxed: false) - userId.serialize(buffer, true) - serializeInt32(months, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {message!.serialize(buffer, true)} - break - case .inputInvoiceSlug(let slug): - if boxed { - buffer.appendInt32(-1020867857) - } - serializeString(slug, buffer: buffer, boxed: false) - break - case .inputInvoiceStarGift(let flags, let peer, let giftId, let message): - if boxed { - buffer.appendInt32(-396206446) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt64(giftId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {message!.serialize(buffer, true)} - break - case .inputInvoiceStarGiftAuctionBid(let flags, let peer, let giftId, let bidAmount, let message): - if boxed { - buffer.appendInt32(516618768) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {peer!.serialize(buffer, true)} - serializeInt64(giftId, buffer: buffer, boxed: false) - serializeInt64(bidAmount, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {message!.serialize(buffer, true)} - break - case .inputInvoiceStarGiftDropOriginalDetails(let stargift): - if boxed { - buffer.appendInt32(153344209) - } - stargift.serialize(buffer, true) - break - case .inputInvoiceStarGiftPrepaidUpgrade(let peer, let hash): - if boxed { - buffer.appendInt32(-1710536520) - } - peer.serialize(buffer, true) - serializeString(hash, buffer: buffer, boxed: false) - break - case .inputInvoiceStarGiftResale(let flags, let slug, let toId): - if boxed { - buffer.appendInt32(-1012968668) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(slug, buffer: buffer, boxed: false) - toId.serialize(buffer, true) - break - case .inputInvoiceStarGiftTransfer(let stargift, let toId): - if boxed { - buffer.appendInt32(1247763417) - } - stargift.serialize(buffer, true) - toId.serialize(buffer, true) - break - case .inputInvoiceStarGiftUpgrade(let flags, let stargift): - if boxed { - buffer.appendInt32(1300335965) - } - serializeInt32(flags, buffer: buffer, boxed: false) - stargift.serialize(buffer, true) - break - case .inputInvoiceStars(let purpose): - if boxed { - buffer.appendInt32(1710230755) - } - purpose.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputInvoiceBusinessBotTransferStars(let bot, let stars): - return ("inputInvoiceBusinessBotTransferStars", [("bot", bot as Any), ("stars", stars as Any)]) - case .inputInvoiceChatInviteSubscription(let hash): - return ("inputInvoiceChatInviteSubscription", [("hash", hash as Any)]) - case .inputInvoiceMessage(let peer, let msgId): - return ("inputInvoiceMessage", [("peer", peer as Any), ("msgId", msgId as Any)]) - case .inputInvoicePremiumAuthCode(let purpose): - return ("inputInvoicePremiumAuthCode", [("purpose", purpose as Any)]) - case .inputInvoicePremiumGiftCode(let purpose, let option): - return ("inputInvoicePremiumGiftCode", [("purpose", purpose as Any), ("option", option as Any)]) - case .inputInvoicePremiumGiftStars(let flags, let userId, let months, let message): - return ("inputInvoicePremiumGiftStars", [("flags", flags as Any), ("userId", userId as Any), ("months", months as Any), ("message", message as Any)]) - case .inputInvoiceSlug(let slug): - return ("inputInvoiceSlug", [("slug", slug as Any)]) - case .inputInvoiceStarGift(let flags, let peer, let giftId, let message): - return ("inputInvoiceStarGift", [("flags", flags as Any), ("peer", peer as Any), ("giftId", giftId as Any), ("message", message as Any)]) - case .inputInvoiceStarGiftAuctionBid(let flags, let peer, let giftId, let bidAmount, let message): - return ("inputInvoiceStarGiftAuctionBid", [("flags", flags as Any), ("peer", peer as Any), ("giftId", giftId as Any), ("bidAmount", bidAmount as Any), ("message", message as Any)]) - case .inputInvoiceStarGiftDropOriginalDetails(let stargift): - return ("inputInvoiceStarGiftDropOriginalDetails", [("stargift", stargift as Any)]) - case .inputInvoiceStarGiftPrepaidUpgrade(let peer, let hash): - return ("inputInvoiceStarGiftPrepaidUpgrade", [("peer", peer as Any), ("hash", hash as Any)]) - case .inputInvoiceStarGiftResale(let flags, let slug, let toId): - return ("inputInvoiceStarGiftResale", [("flags", flags as Any), ("slug", slug as Any), ("toId", toId as Any)]) - case .inputInvoiceStarGiftTransfer(let stargift, let toId): - return ("inputInvoiceStarGiftTransfer", [("stargift", stargift as Any), ("toId", toId as Any)]) - case .inputInvoiceStarGiftUpgrade(let flags, let stargift): - return ("inputInvoiceStarGiftUpgrade", [("flags", flags as Any), ("stargift", stargift as Any)]) - case .inputInvoiceStars(let purpose): - return ("inputInvoiceStars", [("purpose", purpose as Any)]) - } - } - + public class Cons_inputInvoiceBusinessBotTransferStars { + public var bot: Api.InputUser + public var stars: Int64 + public init(bot: Api.InputUser, stars: Int64) { + self.bot = bot + self.stars = stars + } + } + public class Cons_inputInvoiceChatInviteSubscription { + public var hash: String + public init(hash: String) { + self.hash = hash + } + } + public class Cons_inputInvoiceMessage { + public var peer: Api.InputPeer + public var msgId: Int32 + public init(peer: Api.InputPeer, msgId: Int32) { + self.peer = peer + self.msgId = msgId + } + } + public class Cons_inputInvoicePremiumAuthCode { + public var purpose: Api.InputStorePaymentPurpose + public init(purpose: Api.InputStorePaymentPurpose) { + self.purpose = purpose + } + } + public class Cons_inputInvoicePremiumGiftCode { + public var purpose: Api.InputStorePaymentPurpose + public var option: Api.PremiumGiftCodeOption + public init(purpose: Api.InputStorePaymentPurpose, option: Api.PremiumGiftCodeOption) { + self.purpose = purpose + self.option = option + } + } + public class Cons_inputInvoicePremiumGiftStars { + public var flags: Int32 + public var userId: Api.InputUser + public var months: Int32 + public var message: Api.TextWithEntities? + public init(flags: Int32, userId: Api.InputUser, months: Int32, message: Api.TextWithEntities?) { + self.flags = flags + self.userId = userId + self.months = months + self.message = message + } + } + public class Cons_inputInvoiceSlug { + public var slug: String + public init(slug: String) { + self.slug = slug + } + } + public class Cons_inputInvoiceStarGift { + public var flags: Int32 + public var peer: Api.InputPeer + public var giftId: Int64 + public var message: Api.TextWithEntities? + public init(flags: Int32, peer: Api.InputPeer, giftId: Int64, message: Api.TextWithEntities?) { + self.flags = flags + self.peer = peer + self.giftId = giftId + self.message = message + } + } + public class Cons_inputInvoiceStarGiftAuctionBid { + public var flags: Int32 + public var peer: Api.InputPeer? + public var giftId: Int64 + public var bidAmount: Int64 + public var message: Api.TextWithEntities? + public init(flags: Int32, peer: Api.InputPeer?, giftId: Int64, bidAmount: Int64, message: Api.TextWithEntities?) { + self.flags = flags + self.peer = peer + self.giftId = giftId + self.bidAmount = bidAmount + self.message = message + } + } + public class Cons_inputInvoiceStarGiftDropOriginalDetails { + public var stargift: Api.InputSavedStarGift + public init(stargift: Api.InputSavedStarGift) { + self.stargift = stargift + } + } + public class Cons_inputInvoiceStarGiftPrepaidUpgrade { + public var peer: Api.InputPeer + public var hash: String + public init(peer: Api.InputPeer, hash: String) { + self.peer = peer + self.hash = hash + } + } + public class Cons_inputInvoiceStarGiftResale { + public var flags: Int32 + public var slug: String + public var toId: Api.InputPeer + public init(flags: Int32, slug: String, toId: Api.InputPeer) { + self.flags = flags + self.slug = slug + self.toId = toId + } + } + public class Cons_inputInvoiceStarGiftTransfer { + public var stargift: Api.InputSavedStarGift + public var toId: Api.InputPeer + public init(stargift: Api.InputSavedStarGift, toId: Api.InputPeer) { + self.stargift = stargift + self.toId = toId + } + } + public class Cons_inputInvoiceStarGiftUpgrade { + public var flags: Int32 + public var stargift: Api.InputSavedStarGift + public init(flags: Int32, stargift: Api.InputSavedStarGift) { + self.flags = flags + self.stargift = stargift + } + } + public class Cons_inputInvoiceStars { + public var purpose: Api.InputStorePaymentPurpose + public init(purpose: Api.InputStorePaymentPurpose) { + self.purpose = purpose + } + } + case inputInvoiceBusinessBotTransferStars(Cons_inputInvoiceBusinessBotTransferStars) + case inputInvoiceChatInviteSubscription(Cons_inputInvoiceChatInviteSubscription) + case inputInvoiceMessage(Cons_inputInvoiceMessage) + case inputInvoicePremiumAuthCode(Cons_inputInvoicePremiumAuthCode) + case inputInvoicePremiumGiftCode(Cons_inputInvoicePremiumGiftCode) + case inputInvoicePremiumGiftStars(Cons_inputInvoicePremiumGiftStars) + case inputInvoiceSlug(Cons_inputInvoiceSlug) + case inputInvoiceStarGift(Cons_inputInvoiceStarGift) + case inputInvoiceStarGiftAuctionBid(Cons_inputInvoiceStarGiftAuctionBid) + case inputInvoiceStarGiftDropOriginalDetails(Cons_inputInvoiceStarGiftDropOriginalDetails) + case inputInvoiceStarGiftPrepaidUpgrade(Cons_inputInvoiceStarGiftPrepaidUpgrade) + case inputInvoiceStarGiftResale(Cons_inputInvoiceStarGiftResale) + case inputInvoiceStarGiftTransfer(Cons_inputInvoiceStarGiftTransfer) + case inputInvoiceStarGiftUpgrade(Cons_inputInvoiceStarGiftUpgrade) + case inputInvoiceStars(Cons_inputInvoiceStars) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputInvoiceBusinessBotTransferStars(let _data): + if boxed { + buffer.appendInt32(-191267262) + } + _data.bot.serialize(buffer, true) + serializeInt64(_data.stars, buffer: buffer, boxed: false) + break + case .inputInvoiceChatInviteSubscription(let _data): + if boxed { + buffer.appendInt32(887591921) + } + serializeString(_data.hash, buffer: buffer, boxed: false) + break + case .inputInvoiceMessage(let _data): + if boxed { + buffer.appendInt32(-977967015) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + break + case .inputInvoicePremiumAuthCode(let _data): + if boxed { + buffer.appendInt32(1048049172) + } + _data.purpose.serialize(buffer, true) + break + case .inputInvoicePremiumGiftCode(let _data): + if boxed { + buffer.appendInt32(-1734841331) + } + _data.purpose.serialize(buffer, true) + _data.option.serialize(buffer, true) + break + case .inputInvoicePremiumGiftStars(let _data): + if boxed { + buffer.appendInt32(-625298705) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.userId.serialize(buffer, true) + serializeInt32(_data.months, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.message!.serialize(buffer, true) + } + break + case .inputInvoiceSlug(let _data): + if boxed { + buffer.appendInt32(-1020867857) + } + serializeString(_data.slug, buffer: buffer, boxed: false) + break + case .inputInvoiceStarGift(let _data): + if boxed { + buffer.appendInt32(-396206446) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeInt64(_data.giftId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.message!.serialize(buffer, true) + } + break + case .inputInvoiceStarGiftAuctionBid(let _data): + if boxed { + buffer.appendInt32(516618768) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.peer!.serialize(buffer, true) + } + serializeInt64(_data.giftId, buffer: buffer, boxed: false) + serializeInt64(_data.bidAmount, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.message!.serialize(buffer, true) + } + break + case .inputInvoiceStarGiftDropOriginalDetails(let _data): + if boxed { + buffer.appendInt32(153344209) + } + _data.stargift.serialize(buffer, true) + break + case .inputInvoiceStarGiftPrepaidUpgrade(let _data): + if boxed { + buffer.appendInt32(-1710536520) + } + _data.peer.serialize(buffer, true) + serializeString(_data.hash, buffer: buffer, boxed: false) + break + case .inputInvoiceStarGiftResale(let _data): + if boxed { + buffer.appendInt32(-1012968668) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.slug, buffer: buffer, boxed: false) + _data.toId.serialize(buffer, true) + break + case .inputInvoiceStarGiftTransfer(let _data): + if boxed { + buffer.appendInt32(1247763417) + } + _data.stargift.serialize(buffer, true) + _data.toId.serialize(buffer, true) + break + case .inputInvoiceStarGiftUpgrade(let _data): + if boxed { + buffer.appendInt32(1300335965) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.stargift.serialize(buffer, true) + break + case .inputInvoiceStars(let _data): + if boxed { + buffer.appendInt32(1710230755) + } + _data.purpose.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputInvoiceBusinessBotTransferStars(let _data): + return ("inputInvoiceBusinessBotTransferStars", [("bot", _data.bot as Any), ("stars", _data.stars as Any)]) + case .inputInvoiceChatInviteSubscription(let _data): + return ("inputInvoiceChatInviteSubscription", [("hash", _data.hash as Any)]) + case .inputInvoiceMessage(let _data): + return ("inputInvoiceMessage", [("peer", _data.peer as Any), ("msgId", _data.msgId as Any)]) + case .inputInvoicePremiumAuthCode(let _data): + return ("inputInvoicePremiumAuthCode", [("purpose", _data.purpose as Any)]) + case .inputInvoicePremiumGiftCode(let _data): + return ("inputInvoicePremiumGiftCode", [("purpose", _data.purpose as Any), ("option", _data.option as Any)]) + case .inputInvoicePremiumGiftStars(let _data): + return ("inputInvoicePremiumGiftStars", [("flags", _data.flags as Any), ("userId", _data.userId as Any), ("months", _data.months as Any), ("message", _data.message as Any)]) + case .inputInvoiceSlug(let _data): + return ("inputInvoiceSlug", [("slug", _data.slug as Any)]) + case .inputInvoiceStarGift(let _data): + return ("inputInvoiceStarGift", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("giftId", _data.giftId as Any), ("message", _data.message as Any)]) + case .inputInvoiceStarGiftAuctionBid(let _data): + return ("inputInvoiceStarGiftAuctionBid", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("giftId", _data.giftId as Any), ("bidAmount", _data.bidAmount as Any), ("message", _data.message as Any)]) + case .inputInvoiceStarGiftDropOriginalDetails(let _data): + return ("inputInvoiceStarGiftDropOriginalDetails", [("stargift", _data.stargift as Any)]) + case .inputInvoiceStarGiftPrepaidUpgrade(let _data): + return ("inputInvoiceStarGiftPrepaidUpgrade", [("peer", _data.peer as Any), ("hash", _data.hash as Any)]) + case .inputInvoiceStarGiftResale(let _data): + return ("inputInvoiceStarGiftResale", [("flags", _data.flags as Any), ("slug", _data.slug as Any), ("toId", _data.toId as Any)]) + case .inputInvoiceStarGiftTransfer(let _data): + return ("inputInvoiceStarGiftTransfer", [("stargift", _data.stargift as Any), ("toId", _data.toId as Any)]) + case .inputInvoiceStarGiftUpgrade(let _data): + return ("inputInvoiceStarGiftUpgrade", [("flags", _data.flags as Any), ("stargift", _data.stargift as Any)]) + case .inputInvoiceStars(let _data): + return ("inputInvoiceStars", [("purpose", _data.purpose as Any)]) + } + } + public static func parse_inputInvoiceBusinessBotTransferStars(_ reader: BufferReader) -> InputInvoice? { var _1: Api.InputUser? if let signature = reader.readInt32() { @@ -698,16 +1028,23 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputInvoice.inputInvoiceBusinessBotTransferStars(bot: _1!, stars: _2!) + if _c1 && _c2 { + return Api.InputInvoice.inputInvoiceBusinessBotTransferStars(Cons_inputInvoiceBusinessBotTransferStars(bot: _1!, stars: _2!)) + } + else { + return nil + } } public static func parse_inputInvoiceChatInviteSubscription(_ reader: BufferReader) -> InputInvoice? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputInvoice.inputInvoiceChatInviteSubscription(hash: _1!) + if _c1 { + return Api.InputInvoice.inputInvoiceChatInviteSubscription(Cons_inputInvoiceChatInviteSubscription(hash: _1!)) + } + else { + return nil + } } public static func parse_inputInvoiceMessage(_ reader: BufferReader) -> InputInvoice? { var _1: Api.InputPeer? @@ -718,9 +1055,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputInvoice.inputInvoiceMessage(peer: _1!, msgId: _2!) + if _c1 && _c2 { + return Api.InputInvoice.inputInvoiceMessage(Cons_inputInvoiceMessage(peer: _1!, msgId: _2!)) + } + else { + return nil + } } public static func parse_inputInvoicePremiumAuthCode(_ reader: BufferReader) -> InputInvoice? { var _1: Api.InputStorePaymentPurpose? @@ -728,8 +1068,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.InputStorePaymentPurpose } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputInvoice.inputInvoicePremiumAuthCode(purpose: _1!) + if _c1 { + return Api.InputInvoice.inputInvoicePremiumAuthCode(Cons_inputInvoicePremiumAuthCode(purpose: _1!)) + } + else { + return nil + } } public static func parse_inputInvoicePremiumGiftCode(_ reader: BufferReader) -> InputInvoice? { var _1: Api.InputStorePaymentPurpose? @@ -742,9 +1086,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputInvoice.inputInvoicePremiumGiftCode(purpose: _1!, option: _2!) + if _c1 && _c2 { + return Api.InputInvoice.inputInvoicePremiumGiftCode(Cons_inputInvoicePremiumGiftCode(purpose: _1!, option: _2!)) + } + else { + return nil + } } public static func parse_inputInvoicePremiumGiftStars(_ reader: BufferReader) -> InputInvoice? { var _1: Int32? @@ -756,25 +1103,32 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: Api.TextWithEntities? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.TextWithEntities - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.TextWithEntities + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputInvoice.inputInvoicePremiumGiftStars(flags: _1!, userId: _2!, months: _3!, message: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputInvoice.inputInvoicePremiumGiftStars(Cons_inputInvoicePremiumGiftStars(flags: _1!, userId: _2!, months: _3!, message: _4)) + } + else { + return nil + } } public static func parse_inputInvoiceSlug(_ reader: BufferReader) -> InputInvoice? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputInvoice.inputInvoiceSlug(slug: _1!) + if _c1 { + return Api.InputInvoice.inputInvoiceSlug(Cons_inputInvoiceSlug(slug: _1!)) + } + else { + return nil + } } public static func parse_inputInvoiceStarGift(_ reader: BufferReader) -> InputInvoice? { var _1: Int32? @@ -786,45 +1140,52 @@ public extension Api { var _3: Int64? _3 = reader.readInt64() var _4: Api.TextWithEntities? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.TextWithEntities - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.TextWithEntities + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputInvoice.inputInvoiceStarGift(flags: _1!, peer: _2!, giftId: _3!, message: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputInvoice.inputInvoiceStarGift(Cons_inputInvoiceStarGift(flags: _1!, peer: _2!, giftId: _3!, message: _4)) + } + else { + return nil + } } public static func parse_inputInvoiceStarGiftAuctionBid(_ reader: BufferReader) -> InputInvoice? { var _1: Int32? _1 = reader.readInt32() var _2: Api.InputPeer? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.InputPeer - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.InputPeer + } + } var _3: Int64? _3 = reader.readInt64() var _4: Int64? _4 = reader.readInt64() var _5: Api.TextWithEntities? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.TextWithEntities - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.TextWithEntities + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 3) == 0) || _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.InputInvoice.inputInvoiceStarGiftAuctionBid(flags: _1!, peer: _2, giftId: _3!, bidAmount: _4!, message: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.InputInvoice.inputInvoiceStarGiftAuctionBid(Cons_inputInvoiceStarGiftAuctionBid(flags: _1!, peer: _2, giftId: _3!, bidAmount: _4!, message: _5)) + } + else { + return nil + } } public static func parse_inputInvoiceStarGiftDropOriginalDetails(_ reader: BufferReader) -> InputInvoice? { var _1: Api.InputSavedStarGift? @@ -832,8 +1193,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.InputSavedStarGift } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputInvoice.inputInvoiceStarGiftDropOriginalDetails(stargift: _1!) + if _c1 { + return Api.InputInvoice.inputInvoiceStarGiftDropOriginalDetails(Cons_inputInvoiceStarGiftDropOriginalDetails(stargift: _1!)) + } + else { + return nil + } } public static func parse_inputInvoiceStarGiftPrepaidUpgrade(_ reader: BufferReader) -> InputInvoice? { var _1: Api.InputPeer? @@ -844,9 +1209,12 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputInvoice.inputInvoiceStarGiftPrepaidUpgrade(peer: _1!, hash: _2!) + if _c1 && _c2 { + return Api.InputInvoice.inputInvoiceStarGiftPrepaidUpgrade(Cons_inputInvoiceStarGiftPrepaidUpgrade(peer: _1!, hash: _2!)) + } + else { + return nil + } } public static func parse_inputInvoiceStarGiftResale(_ reader: BufferReader) -> InputInvoice? { var _1: Int32? @@ -860,10 +1228,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputInvoice.inputInvoiceStarGiftResale(flags: _1!, slug: _2!, toId: _3!) + if _c1 && _c2 && _c3 { + return Api.InputInvoice.inputInvoiceStarGiftResale(Cons_inputInvoiceStarGiftResale(flags: _1!, slug: _2!, toId: _3!)) + } + else { + return nil + } } public static func parse_inputInvoiceStarGiftTransfer(_ reader: BufferReader) -> InputInvoice? { var _1: Api.InputSavedStarGift? @@ -876,9 +1246,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputInvoice.inputInvoiceStarGiftTransfer(stargift: _1!, toId: _2!) + if _c1 && _c2 { + return Api.InputInvoice.inputInvoiceStarGiftTransfer(Cons_inputInvoiceStarGiftTransfer(stargift: _1!, toId: _2!)) + } + else { + return nil + } } public static func parse_inputInvoiceStarGiftUpgrade(_ reader: BufferReader) -> InputInvoice? { var _1: Int32? @@ -889,9 +1262,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputInvoice.inputInvoiceStarGiftUpgrade(flags: _1!, stargift: _2!) + if _c1 && _c2 { + return Api.InputInvoice.inputInvoiceStarGiftUpgrade(Cons_inputInvoiceStarGiftUpgrade(flags: _1!, stargift: _2!)) + } + else { + return nil + } } public static func parse_inputInvoiceStars(_ reader: BufferReader) -> InputInvoice? { var _1: Api.InputStorePaymentPurpose? @@ -899,9 +1275,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.InputStorePaymentPurpose } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputInvoice.inputInvoiceStars(purpose: _1!) + if _c1 { + return Api.InputInvoice.inputInvoiceStars(Cons_inputInvoiceStars(purpose: _1!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api11.swift b/submodules/TelegramApi/Sources/Api11.swift index f44bd4e7..a1ff5f52 100644 --- a/submodules/TelegramApi/Sources/Api11.swift +++ b/submodules/TelegramApi/Sources/Api11.swift @@ -1,276 +1,555 @@ public extension Api { indirect enum InputMedia: TypeConstructorDescription { - case inputMediaContact(phoneNumber: String, firstName: String, lastName: String, vcard: String) - case inputMediaDice(emoticon: String) - case inputMediaDocument(flags: Int32, id: Api.InputDocument, videoCover: Api.InputPhoto?, videoTimestamp: Int32?, ttlSeconds: Int32?, query: String?) - case inputMediaDocumentExternal(flags: Int32, url: String, ttlSeconds: Int32?, videoCover: Api.InputPhoto?, videoTimestamp: Int32?) + public class Cons_inputMediaContact { + public var phoneNumber: String + public var firstName: String + public var lastName: String + public var vcard: String + public init(phoneNumber: String, firstName: String, lastName: String, vcard: String) { + self.phoneNumber = phoneNumber + self.firstName = firstName + self.lastName = lastName + self.vcard = vcard + } + } + public class Cons_inputMediaDice { + public var emoticon: String + public init(emoticon: String) { + self.emoticon = emoticon + } + } + public class Cons_inputMediaDocument { + public var flags: Int32 + public var id: Api.InputDocument + public var videoCover: Api.InputPhoto? + public var videoTimestamp: Int32? + public var ttlSeconds: Int32? + public var query: String? + public init(flags: Int32, id: Api.InputDocument, videoCover: Api.InputPhoto?, videoTimestamp: Int32?, ttlSeconds: Int32?, query: String?) { + self.flags = flags + self.id = id + self.videoCover = videoCover + self.videoTimestamp = videoTimestamp + self.ttlSeconds = ttlSeconds + self.query = query + } + } + public class Cons_inputMediaDocumentExternal { + public var flags: Int32 + public var url: String + public var ttlSeconds: Int32? + public var videoCover: Api.InputPhoto? + public var videoTimestamp: Int32? + public init(flags: Int32, url: String, ttlSeconds: Int32?, videoCover: Api.InputPhoto?, videoTimestamp: Int32?) { + self.flags = flags + self.url = url + self.ttlSeconds = ttlSeconds + self.videoCover = videoCover + self.videoTimestamp = videoTimestamp + } + } + public class Cons_inputMediaGame { + public var id: Api.InputGame + public init(id: Api.InputGame) { + self.id = id + } + } + public class Cons_inputMediaGeoLive { + public var flags: Int32 + public var geoPoint: Api.InputGeoPoint + public var heading: Int32? + public var period: Int32? + public var proximityNotificationRadius: Int32? + public init(flags: Int32, geoPoint: Api.InputGeoPoint, heading: Int32?, period: Int32?, proximityNotificationRadius: Int32?) { + self.flags = flags + self.geoPoint = geoPoint + self.heading = heading + self.period = period + self.proximityNotificationRadius = proximityNotificationRadius + } + } + public class Cons_inputMediaGeoPoint { + public var geoPoint: Api.InputGeoPoint + public init(geoPoint: Api.InputGeoPoint) { + self.geoPoint = geoPoint + } + } + public class Cons_inputMediaInvoice { + public var flags: Int32 + public var title: String + public var description: String + public var photo: Api.InputWebDocument? + public var invoice: Api.Invoice + public var payload: Buffer + public var provider: String? + public var providerData: Api.DataJSON + public var startParam: String? + public var extendedMedia: Api.InputMedia? + public init(flags: Int32, title: String, description: String, photo: Api.InputWebDocument?, invoice: Api.Invoice, payload: Buffer, provider: String?, providerData: Api.DataJSON, startParam: String?, extendedMedia: Api.InputMedia?) { + self.flags = flags + self.title = title + self.description = description + self.photo = photo + self.invoice = invoice + self.payload = payload + self.provider = provider + self.providerData = providerData + self.startParam = startParam + self.extendedMedia = extendedMedia + } + } + public class Cons_inputMediaPaidMedia { + public var flags: Int32 + public var starsAmount: Int64 + public var extendedMedia: [Api.InputMedia] + public var payload: String? + public init(flags: Int32, starsAmount: Int64, extendedMedia: [Api.InputMedia], payload: String?) { + self.flags = flags + self.starsAmount = starsAmount + self.extendedMedia = extendedMedia + self.payload = payload + } + } + public class Cons_inputMediaPhoto { + public var flags: Int32 + public var id: Api.InputPhoto + public var ttlSeconds: Int32? + public init(flags: Int32, id: Api.InputPhoto, ttlSeconds: Int32?) { + self.flags = flags + self.id = id + self.ttlSeconds = ttlSeconds + } + } + public class Cons_inputMediaPhotoExternal { + public var flags: Int32 + public var url: String + public var ttlSeconds: Int32? + public init(flags: Int32, url: String, ttlSeconds: Int32?) { + self.flags = flags + self.url = url + self.ttlSeconds = ttlSeconds + } + } + public class Cons_inputMediaPoll { + public var flags: Int32 + public var poll: Api.Poll + public var correctAnswers: [Buffer]? + public var solution: String? + public var solutionEntities: [Api.MessageEntity]? + public init(flags: Int32, poll: Api.Poll, correctAnswers: [Buffer]?, solution: String?, solutionEntities: [Api.MessageEntity]?) { + self.flags = flags + self.poll = poll + self.correctAnswers = correctAnswers + self.solution = solution + self.solutionEntities = solutionEntities + } + } + public class Cons_inputMediaStakeDice { + public var gameHash: String + public var tonAmount: Int64 + public var clientSeed: Buffer + public init(gameHash: String, tonAmount: Int64, clientSeed: Buffer) { + self.gameHash = gameHash + self.tonAmount = tonAmount + self.clientSeed = clientSeed + } + } + public class Cons_inputMediaStory { + public var peer: Api.InputPeer + public var id: Int32 + public init(peer: Api.InputPeer, id: Int32) { + self.peer = peer + self.id = id + } + } + public class Cons_inputMediaTodo { + public var todo: Api.TodoList + public init(todo: Api.TodoList) { + self.todo = todo + } + } + public class Cons_inputMediaUploadedDocument { + public var flags: Int32 + public var file: Api.InputFile + public var thumb: Api.InputFile? + public var mimeType: String + public var attributes: [Api.DocumentAttribute] + public var stickers: [Api.InputDocument]? + public var videoCover: Api.InputPhoto? + public var videoTimestamp: Int32? + public var ttlSeconds: Int32? + public init(flags: Int32, file: Api.InputFile, thumb: Api.InputFile?, mimeType: String, attributes: [Api.DocumentAttribute], stickers: [Api.InputDocument]?, videoCover: Api.InputPhoto?, videoTimestamp: Int32?, ttlSeconds: Int32?) { + self.flags = flags + self.file = file + self.thumb = thumb + self.mimeType = mimeType + self.attributes = attributes + self.stickers = stickers + self.videoCover = videoCover + self.videoTimestamp = videoTimestamp + self.ttlSeconds = ttlSeconds + } + } + public class Cons_inputMediaUploadedPhoto { + public var flags: Int32 + public var file: Api.InputFile + public var stickers: [Api.InputDocument]? + public var ttlSeconds: Int32? + public init(flags: Int32, file: Api.InputFile, stickers: [Api.InputDocument]?, ttlSeconds: Int32?) { + self.flags = flags + self.file = file + self.stickers = stickers + self.ttlSeconds = ttlSeconds + } + } + public class Cons_inputMediaVenue { + public var geoPoint: Api.InputGeoPoint + public var title: String + public var address: String + public var provider: String + public var venueId: String + public var venueType: String + public init(geoPoint: Api.InputGeoPoint, title: String, address: String, provider: String, venueId: String, venueType: String) { + self.geoPoint = geoPoint + self.title = title + self.address = address + self.provider = provider + self.venueId = venueId + self.venueType = venueType + } + } + public class Cons_inputMediaWebPage { + public var flags: Int32 + public var url: String + public init(flags: Int32, url: String) { + self.flags = flags + self.url = url + } + } + case inputMediaContact(Cons_inputMediaContact) + case inputMediaDice(Cons_inputMediaDice) + case inputMediaDocument(Cons_inputMediaDocument) + case inputMediaDocumentExternal(Cons_inputMediaDocumentExternal) case inputMediaEmpty - case inputMediaGame(id: Api.InputGame) - case inputMediaGeoLive(flags: Int32, geoPoint: Api.InputGeoPoint, heading: Int32?, period: Int32?, proximityNotificationRadius: Int32?) - case inputMediaGeoPoint(geoPoint: Api.InputGeoPoint) - case inputMediaInvoice(flags: Int32, title: String, description: String, photo: Api.InputWebDocument?, invoice: Api.Invoice, payload: Buffer, provider: String?, providerData: Api.DataJSON, startParam: String?, extendedMedia: Api.InputMedia?) - case inputMediaPaidMedia(flags: Int32, starsAmount: Int64, extendedMedia: [Api.InputMedia], payload: String?) - case inputMediaPhoto(flags: Int32, id: Api.InputPhoto, ttlSeconds: Int32?) - case inputMediaPhotoExternal(flags: Int32, url: String, ttlSeconds: Int32?) - case inputMediaPoll(flags: Int32, poll: Api.Poll, correctAnswers: [Buffer]?, solution: String?, solutionEntities: [Api.MessageEntity]?) - case inputMediaStakeDice(gameHash: String, tonAmount: Int64, clientSeed: Buffer) - case inputMediaStory(peer: Api.InputPeer, id: Int32) - case inputMediaTodo(todo: Api.TodoList) - case inputMediaUploadedDocument(flags: Int32, file: Api.InputFile, thumb: Api.InputFile?, mimeType: String, attributes: [Api.DocumentAttribute], stickers: [Api.InputDocument]?, videoCover: Api.InputPhoto?, videoTimestamp: Int32?, ttlSeconds: Int32?) - case inputMediaUploadedPhoto(flags: Int32, file: Api.InputFile, stickers: [Api.InputDocument]?, ttlSeconds: Int32?) - case inputMediaVenue(geoPoint: Api.InputGeoPoint, title: String, address: String, provider: String, venueId: String, venueType: String) - case inputMediaWebPage(flags: Int32, url: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputMediaContact(let phoneNumber, let firstName, let lastName, let vcard): - if boxed { - buffer.appendInt32(-122978821) - } - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(firstName, buffer: buffer, boxed: false) - serializeString(lastName, buffer: buffer, boxed: false) - serializeString(vcard, buffer: buffer, boxed: false) - break - case .inputMediaDice(let emoticon): - if boxed { - buffer.appendInt32(-428884101) - } - serializeString(emoticon, buffer: buffer, boxed: false) - break - case .inputMediaDocument(let flags, let id, let videoCover, let videoTimestamp, let ttlSeconds, let query): - if boxed { - buffer.appendInt32(-1468646731) - } - serializeInt32(flags, buffer: buffer, boxed: false) - id.serialize(buffer, true) - if Int(flags) & Int(1 << 3) != 0 {videoCover!.serialize(buffer, true)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(videoTimestamp!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(ttlSeconds!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(query!, buffer: buffer, boxed: false)} - break - case .inputMediaDocumentExternal(let flags, let url, let ttlSeconds, let videoCover, let videoTimestamp): - if boxed { - buffer.appendInt32(2006319353) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(ttlSeconds!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {videoCover!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(videoTimestamp!, buffer: buffer, boxed: false)} - break - case .inputMediaEmpty: - if boxed { - buffer.appendInt32(-1771768449) - } - - break - case .inputMediaGame(let id): - if boxed { - buffer.appendInt32(-750828557) - } - id.serialize(buffer, true) - break - case .inputMediaGeoLive(let flags, let geoPoint, let heading, let period, let proximityNotificationRadius): - if boxed { - buffer.appendInt32(-1759532989) - } - serializeInt32(flags, buffer: buffer, boxed: false) - geoPoint.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(heading!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(period!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(proximityNotificationRadius!, buffer: buffer, boxed: false)} - break - case .inputMediaGeoPoint(let geoPoint): - if boxed { - buffer.appendInt32(-104578748) - } - geoPoint.serialize(buffer, true) - break - case .inputMediaInvoice(let flags, let title, let description, let photo, let invoice, let payload, let provider, let providerData, let startParam, let extendedMedia): - if boxed { - buffer.appendInt32(1080028941) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(description, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {photo!.serialize(buffer, true)} - invoice.serialize(buffer, true) - serializeBytes(payload, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {serializeString(provider!, buffer: buffer, boxed: false)} - providerData.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {serializeString(startParam!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {extendedMedia!.serialize(buffer, true)} - break - case .inputMediaPaidMedia(let flags, let starsAmount, let extendedMedia, let payload): - if boxed { - buffer.appendInt32(-1005571194) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(starsAmount, buffer: buffer, boxed: false) + case inputMediaGame(Cons_inputMediaGame) + case inputMediaGeoLive(Cons_inputMediaGeoLive) + case inputMediaGeoPoint(Cons_inputMediaGeoPoint) + case inputMediaInvoice(Cons_inputMediaInvoice) + case inputMediaPaidMedia(Cons_inputMediaPaidMedia) + case inputMediaPhoto(Cons_inputMediaPhoto) + case inputMediaPhotoExternal(Cons_inputMediaPhotoExternal) + case inputMediaPoll(Cons_inputMediaPoll) + case inputMediaStakeDice(Cons_inputMediaStakeDice) + case inputMediaStory(Cons_inputMediaStory) + case inputMediaTodo(Cons_inputMediaTodo) + case inputMediaUploadedDocument(Cons_inputMediaUploadedDocument) + case inputMediaUploadedPhoto(Cons_inputMediaUploadedPhoto) + case inputMediaVenue(Cons_inputMediaVenue) + case inputMediaWebPage(Cons_inputMediaWebPage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputMediaContact(let _data): + if boxed { + buffer.appendInt32(-122978821) + } + serializeString(_data.phoneNumber, buffer: buffer, boxed: false) + serializeString(_data.firstName, buffer: buffer, boxed: false) + serializeString(_data.lastName, buffer: buffer, boxed: false) + serializeString(_data.vcard, buffer: buffer, boxed: false) + break + case .inputMediaDice(let _data): + if boxed { + buffer.appendInt32(-428884101) + } + serializeString(_data.emoticon, buffer: buffer, boxed: false) + break + case .inputMediaDocument(let _data): + if boxed { + buffer.appendInt32(-1468646731) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.id.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.videoCover!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.videoTimestamp!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.ttlSeconds!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.query!, buffer: buffer, boxed: false) + } + break + case .inputMediaDocumentExternal(let _data): + if boxed { + buffer.appendInt32(2006319353) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.ttlSeconds!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.videoCover!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.videoTimestamp!, buffer: buffer, boxed: false) + } + break + case .inputMediaEmpty: + if boxed { + buffer.appendInt32(-1771768449) + } + break + case .inputMediaGame(let _data): + if boxed { + buffer.appendInt32(-750828557) + } + _data.id.serialize(buffer, true) + break + case .inputMediaGeoLive(let _data): + if boxed { + buffer.appendInt32(-1759532989) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.geoPoint.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.heading!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.period!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.proximityNotificationRadius!, buffer: buffer, boxed: false) + } + break + case .inputMediaGeoPoint(let _data): + if boxed { + buffer.appendInt32(-104578748) + } + _data.geoPoint.serialize(buffer, true) + break + case .inputMediaInvoice(let _data): + if boxed { + buffer.appendInt32(1080028941) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.description, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.photo!.serialize(buffer, true) + } + _data.invoice.serialize(buffer, true) + serializeBytes(_data.payload, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.provider!, buffer: buffer, boxed: false) + } + _data.providerData.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.startParam!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.extendedMedia!.serialize(buffer, true) + } + break + case .inputMediaPaidMedia(let _data): + if boxed { + buffer.appendInt32(-1005571194) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.starsAmount, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.extendedMedia.count)) + for item in _data.extendedMedia { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.payload!, buffer: buffer, boxed: false) + } + break + case .inputMediaPhoto(let _data): + if boxed { + buffer.appendInt32(-1279654347) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.id.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.ttlSeconds!, buffer: buffer, boxed: false) + } + break + case .inputMediaPhotoExternal(let _data): + if boxed { + buffer.appendInt32(-440664550) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.ttlSeconds!, buffer: buffer, boxed: false) + } + break + case .inputMediaPoll(let _data): + if boxed { + buffer.appendInt32(261416433) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.poll.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(extendedMedia.count)) - for item in extendedMedia { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 0) != 0 {serializeString(payload!, buffer: buffer, boxed: false)} - break - case .inputMediaPhoto(let flags, let id, let ttlSeconds): - if boxed { - buffer.appendInt32(-1279654347) - } - serializeInt32(flags, buffer: buffer, boxed: false) - id.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(ttlSeconds!, buffer: buffer, boxed: false)} - break - case .inputMediaPhotoExternal(let flags, let url, let ttlSeconds): - if boxed { - buffer.appendInt32(-440664550) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(ttlSeconds!, buffer: buffer, boxed: false)} - break - case .inputMediaPoll(let flags, let poll, let correctAnswers, let solution, let solutionEntities): - if boxed { - buffer.appendInt32(261416433) - } - serializeInt32(flags, buffer: buffer, boxed: false) - poll.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(correctAnswers!.count)) - for item in correctAnswers! { + buffer.appendInt32(Int32(_data.correctAnswers!.count)) + for item in _data.correctAnswers! { serializeBytes(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 1) != 0 {serializeString(solution!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(solutionEntities!.count)) - for item in solutionEntities! { - item.serialize(buffer, true) - }} - break - case .inputMediaStakeDice(let gameHash, let tonAmount, let clientSeed): - if boxed { - buffer.appendInt32(-207018934) } - serializeString(gameHash, buffer: buffer, boxed: false) - serializeInt64(tonAmount, buffer: buffer, boxed: false) - serializeBytes(clientSeed, buffer: buffer, boxed: false) - break - case .inputMediaStory(let peer, let id): - if boxed { - buffer.appendInt32(-1979852936) - } - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - break - case .inputMediaTodo(let todo): - if boxed { - buffer.appendInt32(-1614454818) - } - todo.serialize(buffer, true) - break - case .inputMediaUploadedDocument(let flags, let file, let thumb, let mimeType, let attributes, let stickers, let videoCover, let videoTimestamp, let ttlSeconds): - if boxed { - buffer.appendInt32(58495792) - } - serializeInt32(flags, buffer: buffer, boxed: false) - file.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {thumb!.serialize(buffer, true)} - serializeString(mimeType, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.solution!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(attributes.count)) - for item in attributes { + buffer.appendInt32(Int32(_data.solutionEntities!.count)) + for item in _data.solutionEntities! { item.serialize(buffer, true) } - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stickers!.count)) - for item in stickers! { + } + break + case .inputMediaStakeDice(let _data): + if boxed { + buffer.appendInt32(-207018934) + } + serializeString(_data.gameHash, buffer: buffer, boxed: false) + serializeInt64(_data.tonAmount, buffer: buffer, boxed: false) + serializeBytes(_data.clientSeed, buffer: buffer, boxed: false) + break + case .inputMediaStory(let _data): + if boxed { + buffer.appendInt32(-1979852936) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.id, buffer: buffer, boxed: false) + break + case .inputMediaTodo(let _data): + if boxed { + buffer.appendInt32(-1614454818) + } + _data.todo.serialize(buffer, true) + break + case .inputMediaUploadedDocument(let _data): + if boxed { + buffer.appendInt32(58495792) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.file.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.thumb!.serialize(buffer, true) + } + serializeString(_data.mimeType, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.attributes.count)) + for item in _data.attributes { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.stickers!.count)) + for item in _data.stickers! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 6) != 0 {videoCover!.serialize(buffer, true)} - if Int(flags) & Int(1 << 7) != 0 {serializeInt32(videoTimestamp!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(ttlSeconds!, buffer: buffer, boxed: false)} - break - case .inputMediaUploadedPhoto(let flags, let file, let stickers, let ttlSeconds): - if boxed { - buffer.appendInt32(505969924) } - serializeInt32(flags, buffer: buffer, boxed: false) - file.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stickers!.count)) - for item in stickers! { + } + if Int(_data.flags) & Int(1 << 6) != 0 { + _data.videoCover!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 7) != 0 { + serializeInt32(_data.videoTimestamp!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.ttlSeconds!, buffer: buffer, boxed: false) + } + break + case .inputMediaUploadedPhoto(let _data): + if boxed { + buffer.appendInt32(505969924) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.file.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.stickers!.count)) + for item in _data.stickers! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(ttlSeconds!, buffer: buffer, boxed: false)} - break - case .inputMediaVenue(let geoPoint, let title, let address, let provider, let venueId, let venueType): - if boxed { - buffer.appendInt32(-1052959727) } - geoPoint.serialize(buffer, true) - serializeString(title, buffer: buffer, boxed: false) - serializeString(address, buffer: buffer, boxed: false) - serializeString(provider, buffer: buffer, boxed: false) - serializeString(venueId, buffer: buffer, boxed: false) - serializeString(venueType, buffer: buffer, boxed: false) - break - case .inputMediaWebPage(let flags, let url): - if boxed { - buffer.appendInt32(-1038383031) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputMediaContact(let phoneNumber, let firstName, let lastName, let vcard): - return ("inputMediaContact", [("phoneNumber", phoneNumber as Any), ("firstName", firstName as Any), ("lastName", lastName as Any), ("vcard", vcard as Any)]) - case .inputMediaDice(let emoticon): - return ("inputMediaDice", [("emoticon", emoticon as Any)]) - case .inputMediaDocument(let flags, let id, let videoCover, let videoTimestamp, let ttlSeconds, let query): - return ("inputMediaDocument", [("flags", flags as Any), ("id", id as Any), ("videoCover", videoCover as Any), ("videoTimestamp", videoTimestamp as Any), ("ttlSeconds", ttlSeconds as Any), ("query", query as Any)]) - case .inputMediaDocumentExternal(let flags, let url, let ttlSeconds, let videoCover, let videoTimestamp): - return ("inputMediaDocumentExternal", [("flags", flags as Any), ("url", url as Any), ("ttlSeconds", ttlSeconds as Any), ("videoCover", videoCover as Any), ("videoTimestamp", videoTimestamp as Any)]) - case .inputMediaEmpty: + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.ttlSeconds!, buffer: buffer, boxed: false) + } + break + case .inputMediaVenue(let _data): + if boxed { + buffer.appendInt32(-1052959727) + } + _data.geoPoint.serialize(buffer, true) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.address, buffer: buffer, boxed: false) + serializeString(_data.provider, buffer: buffer, boxed: false) + serializeString(_data.venueId, buffer: buffer, boxed: false) + serializeString(_data.venueType, buffer: buffer, boxed: false) + break + case .inputMediaWebPage(let _data): + if boxed { + buffer.appendInt32(-1038383031) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputMediaContact(let _data): + return ("inputMediaContact", [("phoneNumber", _data.phoneNumber as Any), ("firstName", _data.firstName as Any), ("lastName", _data.lastName as Any), ("vcard", _data.vcard as Any)]) + case .inputMediaDice(let _data): + return ("inputMediaDice", [("emoticon", _data.emoticon as Any)]) + case .inputMediaDocument(let _data): + return ("inputMediaDocument", [("flags", _data.flags as Any), ("id", _data.id as Any), ("videoCover", _data.videoCover as Any), ("videoTimestamp", _data.videoTimestamp as Any), ("ttlSeconds", _data.ttlSeconds as Any), ("query", _data.query as Any)]) + case .inputMediaDocumentExternal(let _data): + return ("inputMediaDocumentExternal", [("flags", _data.flags as Any), ("url", _data.url as Any), ("ttlSeconds", _data.ttlSeconds as Any), ("videoCover", _data.videoCover as Any), ("videoTimestamp", _data.videoTimestamp as Any)]) + case .inputMediaEmpty: return ("inputMediaEmpty", []) - case .inputMediaGame(let id): - return ("inputMediaGame", [("id", id as Any)]) - case .inputMediaGeoLive(let flags, let geoPoint, let heading, let period, let proximityNotificationRadius): - return ("inputMediaGeoLive", [("flags", flags as Any), ("geoPoint", geoPoint as Any), ("heading", heading as Any), ("period", period as Any), ("proximityNotificationRadius", proximityNotificationRadius as Any)]) - case .inputMediaGeoPoint(let geoPoint): - return ("inputMediaGeoPoint", [("geoPoint", geoPoint as Any)]) - case .inputMediaInvoice(let flags, let title, let description, let photo, let invoice, let payload, let provider, let providerData, let startParam, let extendedMedia): - return ("inputMediaInvoice", [("flags", flags as Any), ("title", title as Any), ("description", description as Any), ("photo", photo as Any), ("invoice", invoice as Any), ("payload", payload as Any), ("provider", provider as Any), ("providerData", providerData as Any), ("startParam", startParam as Any), ("extendedMedia", extendedMedia as Any)]) - case .inputMediaPaidMedia(let flags, let starsAmount, let extendedMedia, let payload): - return ("inputMediaPaidMedia", [("flags", flags as Any), ("starsAmount", starsAmount as Any), ("extendedMedia", extendedMedia as Any), ("payload", payload as Any)]) - case .inputMediaPhoto(let flags, let id, let ttlSeconds): - return ("inputMediaPhoto", [("flags", flags as Any), ("id", id as Any), ("ttlSeconds", ttlSeconds as Any)]) - case .inputMediaPhotoExternal(let flags, let url, let ttlSeconds): - return ("inputMediaPhotoExternal", [("flags", flags as Any), ("url", url as Any), ("ttlSeconds", ttlSeconds as Any)]) - case .inputMediaPoll(let flags, let poll, let correctAnswers, let solution, let solutionEntities): - return ("inputMediaPoll", [("flags", flags as Any), ("poll", poll as Any), ("correctAnswers", correctAnswers as Any), ("solution", solution as Any), ("solutionEntities", solutionEntities as Any)]) - case .inputMediaStakeDice(let gameHash, let tonAmount, let clientSeed): - return ("inputMediaStakeDice", [("gameHash", gameHash as Any), ("tonAmount", tonAmount as Any), ("clientSeed", clientSeed as Any)]) - case .inputMediaStory(let peer, let id): - return ("inputMediaStory", [("peer", peer as Any), ("id", id as Any)]) - case .inputMediaTodo(let todo): - return ("inputMediaTodo", [("todo", todo as Any)]) - case .inputMediaUploadedDocument(let flags, let file, let thumb, let mimeType, let attributes, let stickers, let videoCover, let videoTimestamp, let ttlSeconds): - return ("inputMediaUploadedDocument", [("flags", flags as Any), ("file", file as Any), ("thumb", thumb as Any), ("mimeType", mimeType as Any), ("attributes", attributes as Any), ("stickers", stickers as Any), ("videoCover", videoCover as Any), ("videoTimestamp", videoTimestamp as Any), ("ttlSeconds", ttlSeconds as Any)]) - case .inputMediaUploadedPhoto(let flags, let file, let stickers, let ttlSeconds): - return ("inputMediaUploadedPhoto", [("flags", flags as Any), ("file", file as Any), ("stickers", stickers as Any), ("ttlSeconds", ttlSeconds as Any)]) - case .inputMediaVenue(let geoPoint, let title, let address, let provider, let venueId, let venueType): - return ("inputMediaVenue", [("geoPoint", geoPoint as Any), ("title", title as Any), ("address", address as Any), ("provider", provider as Any), ("venueId", venueId as Any), ("venueType", venueType as Any)]) - case .inputMediaWebPage(let flags, let url): - return ("inputMediaWebPage", [("flags", flags as Any), ("url", url as Any)]) - } - } - + case .inputMediaGame(let _data): + return ("inputMediaGame", [("id", _data.id as Any)]) + case .inputMediaGeoLive(let _data): + return ("inputMediaGeoLive", [("flags", _data.flags as Any), ("geoPoint", _data.geoPoint as Any), ("heading", _data.heading as Any), ("period", _data.period as Any), ("proximityNotificationRadius", _data.proximityNotificationRadius as Any)]) + case .inputMediaGeoPoint(let _data): + return ("inputMediaGeoPoint", [("geoPoint", _data.geoPoint as Any)]) + case .inputMediaInvoice(let _data): + return ("inputMediaInvoice", [("flags", _data.flags as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("photo", _data.photo as Any), ("invoice", _data.invoice as Any), ("payload", _data.payload as Any), ("provider", _data.provider as Any), ("providerData", _data.providerData as Any), ("startParam", _data.startParam as Any), ("extendedMedia", _data.extendedMedia as Any)]) + case .inputMediaPaidMedia(let _data): + return ("inputMediaPaidMedia", [("flags", _data.flags as Any), ("starsAmount", _data.starsAmount as Any), ("extendedMedia", _data.extendedMedia as Any), ("payload", _data.payload as Any)]) + case .inputMediaPhoto(let _data): + return ("inputMediaPhoto", [("flags", _data.flags as Any), ("id", _data.id as Any), ("ttlSeconds", _data.ttlSeconds as Any)]) + case .inputMediaPhotoExternal(let _data): + return ("inputMediaPhotoExternal", [("flags", _data.flags as Any), ("url", _data.url as Any), ("ttlSeconds", _data.ttlSeconds as Any)]) + case .inputMediaPoll(let _data): + return ("inputMediaPoll", [("flags", _data.flags as Any), ("poll", _data.poll as Any), ("correctAnswers", _data.correctAnswers as Any), ("solution", _data.solution as Any), ("solutionEntities", _data.solutionEntities as Any)]) + case .inputMediaStakeDice(let _data): + return ("inputMediaStakeDice", [("gameHash", _data.gameHash as Any), ("tonAmount", _data.tonAmount as Any), ("clientSeed", _data.clientSeed as Any)]) + case .inputMediaStory(let _data): + return ("inputMediaStory", [("peer", _data.peer as Any), ("id", _data.id as Any)]) + case .inputMediaTodo(let _data): + return ("inputMediaTodo", [("todo", _data.todo as Any)]) + case .inputMediaUploadedDocument(let _data): + return ("inputMediaUploadedDocument", [("flags", _data.flags as Any), ("file", _data.file as Any), ("thumb", _data.thumb as Any), ("mimeType", _data.mimeType as Any), ("attributes", _data.attributes as Any), ("stickers", _data.stickers as Any), ("videoCover", _data.videoCover as Any), ("videoTimestamp", _data.videoTimestamp as Any), ("ttlSeconds", _data.ttlSeconds as Any)]) + case .inputMediaUploadedPhoto(let _data): + return ("inputMediaUploadedPhoto", [("flags", _data.flags as Any), ("file", _data.file as Any), ("stickers", _data.stickers as Any), ("ttlSeconds", _data.ttlSeconds as Any)]) + case .inputMediaVenue(let _data): + return ("inputMediaVenue", [("geoPoint", _data.geoPoint as Any), ("title", _data.title as Any), ("address", _data.address as Any), ("provider", _data.provider as Any), ("venueId", _data.venueId as Any), ("venueType", _data.venueType as Any)]) + case .inputMediaWebPage(let _data): + return ("inputMediaWebPage", [("flags", _data.flags as Any), ("url", _data.url as Any)]) + } + } + public static func parse_inputMediaContact(_ reader: BufferReader) -> InputMedia? { var _1: String? _1 = parseString(reader) @@ -284,18 +563,23 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputMedia.inputMediaContact(phoneNumber: _1!, firstName: _2!, lastName: _3!, vcard: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputMedia.inputMediaContact(Cons_inputMediaContact(phoneNumber: _1!, firstName: _2!, lastName: _3!, vcard: _4!)) + } + else { + return nil + } } public static func parse_inputMediaDice(_ reader: BufferReader) -> InputMedia? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputMedia.inputMediaDice(emoticon: _1!) + if _c1 { + return Api.InputMedia.inputMediaDice(Cons_inputMediaDice(emoticon: _1!)) + } + else { + return nil + } } public static func parse_inputMediaDocument(_ reader: BufferReader) -> InputMedia? { var _1: Int32? @@ -305,28 +589,35 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.InputDocument } var _3: Api.InputPhoto? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.InputPhoto - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.InputPhoto + } + } var _4: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _4 = reader.readInt32() + } var _5: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _5 = reader.readInt32() + } var _6: String? - if Int(_1!) & Int(1 << 1) != 0 {_6 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _6 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 3) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 4) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.InputMedia.inputMediaDocument(flags: _1!, id: _2!, videoCover: _3, videoTimestamp: _4, ttlSeconds: _5, query: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.InputMedia.inputMediaDocument(Cons_inputMediaDocument(flags: _1!, id: _2!, videoCover: _3, videoTimestamp: _4, ttlSeconds: _5, query: _6)) + } + else { + return nil + } } public static func parse_inputMediaDocumentExternal(_ reader: BufferReader) -> InputMedia? { var _1: Int32? @@ -334,24 +625,30 @@ public extension Api { var _2: String? _2 = parseString(reader) var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } var _4: Api.InputPhoto? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.InputPhoto - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.InputPhoto + } + } var _5: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 3) != 0 { + _5 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 3) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.InputMedia.inputMediaDocumentExternal(flags: _1!, url: _2!, ttlSeconds: _3, videoCover: _4, videoTimestamp: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.InputMedia.inputMediaDocumentExternal(Cons_inputMediaDocumentExternal(flags: _1!, url: _2!, ttlSeconds: _3, videoCover: _4, videoTimestamp: _5)) + } + else { + return nil + } } public static func parse_inputMediaEmpty(_ reader: BufferReader) -> InputMedia? { return Api.InputMedia.inputMediaEmpty @@ -362,8 +659,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.InputGame } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputMedia.inputMediaGame(id: _1!) + if _c1 { + return Api.InputMedia.inputMediaGame(Cons_inputMediaGame(id: _1!)) + } + else { + return nil + } } public static func parse_inputMediaGeoLive(_ reader: BufferReader) -> InputMedia? { var _1: Int32? @@ -373,22 +674,28 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.InputGeoPoint } var _3: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _3 = reader.readInt32() + } var _4: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = reader.readInt32() + } var _5: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 3) != 0 { + _5 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 2) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 3) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.InputMedia.inputMediaGeoLive(flags: _1!, geoPoint: _2!, heading: _3, period: _4, proximityNotificationRadius: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.InputMedia.inputMediaGeoLive(Cons_inputMediaGeoLive(flags: _1!, geoPoint: _2!, heading: _3, period: _4, proximityNotificationRadius: _5)) + } + else { + return nil + } } public static func parse_inputMediaGeoPoint(_ reader: BufferReader) -> InputMedia? { var _1: Api.InputGeoPoint? @@ -396,8 +703,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.InputGeoPoint } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputMedia.inputMediaGeoPoint(geoPoint: _1!) + if _c1 { + return Api.InputMedia.inputMediaGeoPoint(Cons_inputMediaGeoPoint(geoPoint: _1!)) + } + else { + return nil + } } public static func parse_inputMediaInvoice(_ reader: BufferReader) -> InputMedia? { var _1: Int32? @@ -407,9 +718,11 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: Api.InputWebDocument? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.InputWebDocument - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.InputWebDocument + } + } var _5: Api.Invoice? if let signature = reader.readInt32() { _5 = Api.parse(reader, signature: signature) as? Api.Invoice @@ -417,17 +730,23 @@ public extension Api { var _6: Buffer? _6 = parseBytes(reader) var _7: String? - if Int(_1!) & Int(1 << 3) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 3) != 0 { + _7 = parseString(reader) + } var _8: Api.DataJSON? if let signature = reader.readInt32() { _8 = Api.parse(reader, signature: signature) as? Api.DataJSON } var _9: String? - if Int(_1!) & Int(1 << 1) != 0 {_9 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _9 = parseString(reader) + } var _10: Api.InputMedia? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _10 = Api.parse(reader, signature: signature) as? Api.InputMedia - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _10 = Api.parse(reader, signature: signature) as? Api.InputMedia + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -438,17 +757,12 @@ public extension Api { let _c8 = _8 != nil let _c9 = (Int(_1!) & Int(1 << 1) == 0) || _9 != nil let _c10 = (Int(_1!) & Int(1 << 2) == 0) || _10 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - return Api.InputMedia.inputMediaInvoice(flags: _1!, title: _2!, description: _3!, photo: _4, invoice: _5!, payload: _6!, provider: _7, providerData: _8!, startParam: _9, extendedMedia: _10) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 { + return Api.InputMedia.inputMediaInvoice(Cons_inputMediaInvoice(flags: _1!, title: _2!, description: _3!, photo: _4, invoice: _5!, payload: _6!, provider: _7, providerData: _8!, startParam: _9, extendedMedia: _10)) + } + else { + return nil + } } public static func parse_inputMediaPaidMedia(_ reader: BufferReader) -> InputMedia? { var _1: Int32? @@ -460,16 +774,19 @@ public extension Api { _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputMedia.self) } var _4: String? - if Int(_1!) & Int(1 << 0) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputMedia.inputMediaPaidMedia(flags: _1!, starsAmount: _2!, extendedMedia: _3!, payload: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputMedia.inputMediaPaidMedia(Cons_inputMediaPaidMedia(flags: _1!, starsAmount: _2!, extendedMedia: _3!, payload: _4)) + } + else { + return nil + } } public static func parse_inputMediaPhoto(_ reader: BufferReader) -> InputMedia? { var _1: Int32? @@ -479,14 +796,18 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.InputPhoto } var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputMedia.inputMediaPhoto(flags: _1!, id: _2!, ttlSeconds: _3) + if _c1 && _c2 && _c3 { + return Api.InputMedia.inputMediaPhoto(Cons_inputMediaPhoto(flags: _1!, id: _2!, ttlSeconds: _3)) + } + else { + return nil + } } public static func parse_inputMediaPhotoExternal(_ reader: BufferReader) -> InputMedia? { var _1: Int32? @@ -494,14 +815,18 @@ public extension Api { var _2: String? _2 = parseString(reader) var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputMedia.inputMediaPhotoExternal(flags: _1!, url: _2!, ttlSeconds: _3) + if _c1 && _c2 && _c3 { + return Api.InputMedia.inputMediaPhotoExternal(Cons_inputMediaPhotoExternal(flags: _1!, url: _2!, ttlSeconds: _3)) + } + else { + return nil + } } public static func parse_inputMediaPoll(_ reader: BufferReader) -> InputMedia? { var _1: Int32? @@ -511,26 +836,32 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.Poll } var _3: [Buffer]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: -1255641564, elementType: Buffer.self) - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: -1255641564, elementType: Buffer.self) + } + } var _4: String? - if Int(_1!) & Int(1 << 1) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = parseString(reader) + } var _5: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.InputMedia.inputMediaPoll(flags: _1!, poll: _2!, correctAnswers: _3, solution: _4, solutionEntities: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.InputMedia.inputMediaPoll(Cons_inputMediaPoll(flags: _1!, poll: _2!, correctAnswers: _3, solution: _4, solutionEntities: _5)) + } + else { + return nil + } } public static func parse_inputMediaStakeDice(_ reader: BufferReader) -> InputMedia? { var _1: String? @@ -542,10 +873,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputMedia.inputMediaStakeDice(gameHash: _1!, tonAmount: _2!, clientSeed: _3!) + if _c1 && _c2 && _c3 { + return Api.InputMedia.inputMediaStakeDice(Cons_inputMediaStakeDice(gameHash: _1!, tonAmount: _2!, clientSeed: _3!)) + } + else { + return nil + } } public static func parse_inputMediaStory(_ reader: BufferReader) -> InputMedia? { var _1: Api.InputPeer? @@ -556,9 +889,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputMedia.inputMediaStory(peer: _1!, id: _2!) + if _c1 && _c2 { + return Api.InputMedia.inputMediaStory(Cons_inputMediaStory(peer: _1!, id: _2!)) + } + else { + return nil + } } public static func parse_inputMediaTodo(_ reader: BufferReader) -> InputMedia? { var _1: Api.TodoList? @@ -566,8 +902,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.TodoList } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputMedia.inputMediaTodo(todo: _1!) + if _c1 { + return Api.InputMedia.inputMediaTodo(Cons_inputMediaTodo(todo: _1!)) + } + else { + return nil + } } public static func parse_inputMediaUploadedDocument(_ reader: BufferReader) -> InputMedia? { var _1: Int32? @@ -577,9 +917,11 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.InputFile } var _3: Api.InputFile? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.InputFile - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.InputFile + } + } var _4: String? _4 = parseString(reader) var _5: [Api.DocumentAttribute]? @@ -587,17 +929,25 @@ public extension Api { _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.DocumentAttribute.self) } var _6: [Api.InputDocument]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputDocument.self) - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputDocument.self) + } + } var _7: Api.InputPhoto? - if Int(_1!) & Int(1 << 6) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.InputPhoto - } } + if Int(_1!) & Int(1 << 6) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.InputPhoto + } + } var _8: Int32? - if Int(_1!) & Int(1 << 7) != 0 {_8 = reader.readInt32() } + if Int(_1!) & Int(1 << 7) != 0 { + _8 = reader.readInt32() + } var _9: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_9 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _9 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 2) == 0) || _3 != nil @@ -607,16 +957,12 @@ public extension Api { let _c7 = (Int(_1!) & Int(1 << 6) == 0) || _7 != nil let _c8 = (Int(_1!) & Int(1 << 7) == 0) || _8 != nil let _c9 = (Int(_1!) & Int(1 << 1) == 0) || _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.InputMedia.inputMediaUploadedDocument(flags: _1!, file: _2!, thumb: _3, mimeType: _4!, attributes: _5!, stickers: _6, videoCover: _7, videoTimestamp: _8, ttlSeconds: _9) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.InputMedia.inputMediaUploadedDocument(Cons_inputMediaUploadedDocument(flags: _1!, file: _2!, thumb: _3, mimeType: _4!, attributes: _5!, stickers: _6, videoCover: _7, videoTimestamp: _8, ttlSeconds: _9)) + } + else { + return nil + } } public static func parse_inputMediaUploadedPhoto(_ reader: BufferReader) -> InputMedia? { var _1: Int32? @@ -626,20 +972,25 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.InputFile } var _3: [Api.InputDocument]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputDocument.self) - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputDocument.self) + } + } var _4: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputMedia.inputMediaUploadedPhoto(flags: _1!, file: _2!, stickers: _3, ttlSeconds: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputMedia.inputMediaUploadedPhoto(Cons_inputMediaUploadedPhoto(flags: _1!, file: _2!, stickers: _3, ttlSeconds: _4)) + } + else { + return nil + } } public static func parse_inputMediaVenue(_ reader: BufferReader) -> InputMedia? { var _1: Api.InputGeoPoint? @@ -662,13 +1013,12 @@ public extension Api { let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.InputMedia.inputMediaVenue(geoPoint: _1!, title: _2!, address: _3!, provider: _4!, venueId: _5!, venueType: _6!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.InputMedia.inputMediaVenue(Cons_inputMediaVenue(geoPoint: _1!, title: _2!, address: _3!, provider: _4!, venueId: _5!, venueType: _6!)) + } + else { + return nil + } } public static func parse_inputMediaWebPage(_ reader: BufferReader) -> InputMedia? { var _1: Int32? @@ -677,63 +1027,84 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputMedia.inputMediaWebPage(flags: _1!, url: _2!) + if _c1 && _c2 { + return Api.InputMedia.inputMediaWebPage(Cons_inputMediaWebPage(flags: _1!, url: _2!)) + } + else { + return nil + } } - } } public extension Api { enum InputMessage: TypeConstructorDescription { - case inputMessageCallbackQuery(id: Int32, queryId: Int64) - case inputMessageID(id: Int32) + public class Cons_inputMessageCallbackQuery { + public var id: Int32 + public var queryId: Int64 + public init(id: Int32, queryId: Int64) { + self.id = id + self.queryId = queryId + } + } + public class Cons_inputMessageID { + public var id: Int32 + public init(id: Int32) { + self.id = id + } + } + public class Cons_inputMessageReplyTo { + public var id: Int32 + public init(id: Int32) { + self.id = id + } + } + case inputMessageCallbackQuery(Cons_inputMessageCallbackQuery) + case inputMessageID(Cons_inputMessageID) case inputMessagePinned - case inputMessageReplyTo(id: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputMessageCallbackQuery(let id, let queryId): - if boxed { - buffer.appendInt32(-1392895362) - } - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt64(queryId, buffer: buffer, boxed: false) - break - case .inputMessageID(let id): - if boxed { - buffer.appendInt32(-1502174430) - } - serializeInt32(id, buffer: buffer, boxed: false) - break - case .inputMessagePinned: - if boxed { - buffer.appendInt32(-2037963464) - } - - break - case .inputMessageReplyTo(let id): - if boxed { - buffer.appendInt32(-1160215659) - } - serializeInt32(id, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputMessageCallbackQuery(let id, let queryId): - return ("inputMessageCallbackQuery", [("id", id as Any), ("queryId", queryId as Any)]) - case .inputMessageID(let id): - return ("inputMessageID", [("id", id as Any)]) - case .inputMessagePinned: + case inputMessageReplyTo(Cons_inputMessageReplyTo) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputMessageCallbackQuery(let _data): + if boxed { + buffer.appendInt32(-1392895362) + } + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.queryId, buffer: buffer, boxed: false) + break + case .inputMessageID(let _data): + if boxed { + buffer.appendInt32(-1502174430) + } + serializeInt32(_data.id, buffer: buffer, boxed: false) + break + case .inputMessagePinned: + if boxed { + buffer.appendInt32(-2037963464) + } + break + case .inputMessageReplyTo(let _data): + if boxed { + buffer.appendInt32(-1160215659) + } + serializeInt32(_data.id, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputMessageCallbackQuery(let _data): + return ("inputMessageCallbackQuery", [("id", _data.id as Any), ("queryId", _data.queryId as Any)]) + case .inputMessageID(let _data): + return ("inputMessageID", [("id", _data.id as Any)]) + case .inputMessagePinned: return ("inputMessagePinned", []) - case .inputMessageReplyTo(let id): - return ("inputMessageReplyTo", [("id", id as Any)]) - } - } - + case .inputMessageReplyTo(let _data): + return ("inputMessageReplyTo", [("id", _data.id as Any)]) + } + } + public static func parse_inputMessageCallbackQuery(_ reader: BufferReader) -> InputMessage? { var _1: Int32? _1 = reader.readInt32() @@ -741,16 +1112,23 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputMessage.inputMessageCallbackQuery(id: _1!, queryId: _2!) + if _c1 && _c2 { + return Api.InputMessage.inputMessageCallbackQuery(Cons_inputMessageCallbackQuery(id: _1!, queryId: _2!)) + } + else { + return nil + } } public static func parse_inputMessageID(_ reader: BufferReader) -> InputMessage? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputMessage.inputMessageID(id: _1!) + if _c1 { + return Api.InputMessage.inputMessageID(Cons_inputMessageID(id: _1!)) + } + else { + return nil + } } public static func parse_inputMessagePinned(_ reader: BufferReader) -> InputMessage? { return Api.InputMessage.inputMessagePinned @@ -759,71 +1137,85 @@ public extension Api { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputMessage.inputMessageReplyTo(id: _1!) + if _c1 { + return Api.InputMessage.inputMessageReplyTo(Cons_inputMessageReplyTo(id: _1!)) + } + else { + return nil + } } - } } public extension Api { indirect enum InputNotifyPeer: TypeConstructorDescription { + public class Cons_inputNotifyForumTopic { + public var peer: Api.InputPeer + public var topMsgId: Int32 + public init(peer: Api.InputPeer, topMsgId: Int32) { + self.peer = peer + self.topMsgId = topMsgId + } + } + public class Cons_inputNotifyPeer { + public var peer: Api.InputPeer + public init(peer: Api.InputPeer) { + self.peer = peer + } + } case inputNotifyBroadcasts case inputNotifyChats - case inputNotifyForumTopic(peer: Api.InputPeer, topMsgId: Int32) - case inputNotifyPeer(peer: Api.InputPeer) + case inputNotifyForumTopic(Cons_inputNotifyForumTopic) + case inputNotifyPeer(Cons_inputNotifyPeer) case inputNotifyUsers - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputNotifyBroadcasts: - if boxed { - buffer.appendInt32(-1311015810) - } - - break - case .inputNotifyChats: - if boxed { - buffer.appendInt32(1251338318) - } - - break - case .inputNotifyForumTopic(let peer, let topMsgId): - if boxed { - buffer.appendInt32(1548122514) - } - peer.serialize(buffer, true) - serializeInt32(topMsgId, buffer: buffer, boxed: false) - break - case .inputNotifyPeer(let peer): - if boxed { - buffer.appendInt32(-1195615476) - } - peer.serialize(buffer, true) - break - case .inputNotifyUsers: - if boxed { - buffer.appendInt32(423314455) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputNotifyBroadcasts: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputNotifyBroadcasts: + if boxed { + buffer.appendInt32(-1311015810) + } + break + case .inputNotifyChats: + if boxed { + buffer.appendInt32(1251338318) + } + break + case .inputNotifyForumTopic(let _data): + if boxed { + buffer.appendInt32(1548122514) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.topMsgId, buffer: buffer, boxed: false) + break + case .inputNotifyPeer(let _data): + if boxed { + buffer.appendInt32(-1195615476) + } + _data.peer.serialize(buffer, true) + break + case .inputNotifyUsers: + if boxed { + buffer.appendInt32(423314455) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputNotifyBroadcasts: return ("inputNotifyBroadcasts", []) - case .inputNotifyChats: + case .inputNotifyChats: return ("inputNotifyChats", []) - case .inputNotifyForumTopic(let peer, let topMsgId): - return ("inputNotifyForumTopic", [("peer", peer as Any), ("topMsgId", topMsgId as Any)]) - case .inputNotifyPeer(let peer): - return ("inputNotifyPeer", [("peer", peer as Any)]) - case .inputNotifyUsers: + case .inputNotifyForumTopic(let _data): + return ("inputNotifyForumTopic", [("peer", _data.peer as Any), ("topMsgId", _data.topMsgId as Any)]) + case .inputNotifyPeer(let _data): + return ("inputNotifyPeer", [("peer", _data.peer as Any)]) + case .inputNotifyUsers: return ("inputNotifyUsers", []) - } - } - + } + } + public static func parse_inputNotifyBroadcasts(_ reader: BufferReader) -> InputNotifyPeer? { return Api.InputNotifyPeer.inputNotifyBroadcasts } @@ -839,9 +1231,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputNotifyPeer.inputNotifyForumTopic(peer: _1!, topMsgId: _2!) + if _c1 && _c2 { + return Api.InputNotifyPeer.inputNotifyForumTopic(Cons_inputNotifyForumTopic(peer: _1!, topMsgId: _2!)) + } + else { + return nil + } } public static func parse_inputNotifyPeer(_ reader: BufferReader) -> InputNotifyPeer? { var _1: Api.InputPeer? @@ -849,54 +1244,77 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.InputPeer } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputNotifyPeer.inputNotifyPeer(peer: _1!) + if _c1 { + return Api.InputNotifyPeer.inputNotifyPeer(Cons_inputNotifyPeer(peer: _1!)) + } + else { + return nil + } } public static func parse_inputNotifyUsers(_ reader: BufferReader) -> InputNotifyPeer? { return Api.InputNotifyPeer.inputNotifyUsers } - } } public extension Api { enum InputPasskeyCredential: TypeConstructorDescription { - case inputPasskeyCredentialFirebasePNV(pnvToken: String) - case inputPasskeyCredentialPublicKey(id: String, rawId: String, response: Api.InputPasskeyResponse) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputPasskeyCredentialFirebasePNV(let pnvToken): - if boxed { - buffer.appendInt32(1528613672) - } - serializeString(pnvToken, buffer: buffer, boxed: false) - break - case .inputPasskeyCredentialPublicKey(let id, let rawId, let response): - if boxed { - buffer.appendInt32(1009235855) - } - serializeString(id, buffer: buffer, boxed: false) - serializeString(rawId, buffer: buffer, boxed: false) - response.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputPasskeyCredentialFirebasePNV(let pnvToken): - return ("inputPasskeyCredentialFirebasePNV", [("pnvToken", pnvToken as Any)]) - case .inputPasskeyCredentialPublicKey(let id, let rawId, let response): - return ("inputPasskeyCredentialPublicKey", [("id", id as Any), ("rawId", rawId as Any), ("response", response as Any)]) - } - } - + public class Cons_inputPasskeyCredentialFirebasePNV { + public var pnvToken: String + public init(pnvToken: String) { + self.pnvToken = pnvToken + } + } + public class Cons_inputPasskeyCredentialPublicKey { + public var id: String + public var rawId: String + public var response: Api.InputPasskeyResponse + public init(id: String, rawId: String, response: Api.InputPasskeyResponse) { + self.id = id + self.rawId = rawId + self.response = response + } + } + case inputPasskeyCredentialFirebasePNV(Cons_inputPasskeyCredentialFirebasePNV) + case inputPasskeyCredentialPublicKey(Cons_inputPasskeyCredentialPublicKey) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputPasskeyCredentialFirebasePNV(let _data): + if boxed { + buffer.appendInt32(1528613672) + } + serializeString(_data.pnvToken, buffer: buffer, boxed: false) + break + case .inputPasskeyCredentialPublicKey(let _data): + if boxed { + buffer.appendInt32(1009235855) + } + serializeString(_data.id, buffer: buffer, boxed: false) + serializeString(_data.rawId, buffer: buffer, boxed: false) + _data.response.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputPasskeyCredentialFirebasePNV(let _data): + return ("inputPasskeyCredentialFirebasePNV", [("pnvToken", _data.pnvToken as Any)]) + case .inputPasskeyCredentialPublicKey(let _data): + return ("inputPasskeyCredentialPublicKey", [("id", _data.id as Any), ("rawId", _data.rawId as Any), ("response", _data.response as Any)]) + } + } + public static func parse_inputPasskeyCredentialFirebasePNV(_ reader: BufferReader) -> InputPasskeyCredential? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputPasskeyCredential.inputPasskeyCredentialFirebasePNV(pnvToken: _1!) + if _c1 { + return Api.InputPasskeyCredential.inputPasskeyCredentialFirebasePNV(Cons_inputPasskeyCredentialFirebasePNV(pnvToken: _1!)) + } + else { + return nil + } } public static func parse_inputPasskeyCredentialPublicKey(_ reader: BufferReader) -> InputPasskeyCredential? { var _1: String? @@ -910,49 +1328,70 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputPasskeyCredential.inputPasskeyCredentialPublicKey(id: _1!, rawId: _2!, response: _3!) + if _c1 && _c2 && _c3 { + return Api.InputPasskeyCredential.inputPasskeyCredentialPublicKey(Cons_inputPasskeyCredentialPublicKey(id: _1!, rawId: _2!, response: _3!)) + } + else { + return nil + } } - } } public extension Api { enum InputPasskeyResponse: TypeConstructorDescription { - case inputPasskeyResponseLogin(clientData: Api.DataJSON, authenticatorData: Buffer, signature: Buffer, userHandle: String) - case inputPasskeyResponseRegister(clientData: Api.DataJSON, attestationData: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputPasskeyResponseLogin(let clientData, let authenticatorData, let signature, let userHandle): - if boxed { - buffer.appendInt32(-1021329078) - } - clientData.serialize(buffer, true) - serializeBytes(authenticatorData, buffer: buffer, boxed: false) - serializeBytes(signature, buffer: buffer, boxed: false) - serializeString(userHandle, buffer: buffer, boxed: false) - break - case .inputPasskeyResponseRegister(let clientData, let attestationData): - if boxed { - buffer.appendInt32(1046713180) - } - clientData.serialize(buffer, true) - serializeBytes(attestationData, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputPasskeyResponseLogin(let clientData, let authenticatorData, let signature, let userHandle): - return ("inputPasskeyResponseLogin", [("clientData", clientData as Any), ("authenticatorData", authenticatorData as Any), ("signature", signature as Any), ("userHandle", userHandle as Any)]) - case .inputPasskeyResponseRegister(let clientData, let attestationData): - return ("inputPasskeyResponseRegister", [("clientData", clientData as Any), ("attestationData", attestationData as Any)]) - } - } - + public class Cons_inputPasskeyResponseLogin { + public var clientData: Api.DataJSON + public var authenticatorData: Buffer + public var signature: Buffer + public var userHandle: String + public init(clientData: Api.DataJSON, authenticatorData: Buffer, signature: Buffer, userHandle: String) { + self.clientData = clientData + self.authenticatorData = authenticatorData + self.signature = signature + self.userHandle = userHandle + } + } + public class Cons_inputPasskeyResponseRegister { + public var clientData: Api.DataJSON + public var attestationData: Buffer + public init(clientData: Api.DataJSON, attestationData: Buffer) { + self.clientData = clientData + self.attestationData = attestationData + } + } + case inputPasskeyResponseLogin(Cons_inputPasskeyResponseLogin) + case inputPasskeyResponseRegister(Cons_inputPasskeyResponseRegister) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputPasskeyResponseLogin(let _data): + if boxed { + buffer.appendInt32(-1021329078) + } + _data.clientData.serialize(buffer, true) + serializeBytes(_data.authenticatorData, buffer: buffer, boxed: false) + serializeBytes(_data.signature, buffer: buffer, boxed: false) + serializeString(_data.userHandle, buffer: buffer, boxed: false) + break + case .inputPasskeyResponseRegister(let _data): + if boxed { + buffer.appendInt32(1046713180) + } + _data.clientData.serialize(buffer, true) + serializeBytes(_data.attestationData, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputPasskeyResponseLogin(let _data): + return ("inputPasskeyResponseLogin", [("clientData", _data.clientData as Any), ("authenticatorData", _data.authenticatorData as Any), ("signature", _data.signature as Any), ("userHandle", _data.userHandle as Any)]) + case .inputPasskeyResponseRegister(let _data): + return ("inputPasskeyResponseRegister", [("clientData", _data.clientData as Any), ("attestationData", _data.attestationData as Any)]) + } + } + public static func parse_inputPasskeyResponseLogin(_ reader: BufferReader) -> InputPasskeyResponse? { var _1: Api.DataJSON? if let signature = reader.readInt32() { @@ -968,11 +1407,12 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputPasskeyResponse.inputPasskeyResponseLogin(clientData: _1!, authenticatorData: _2!, signature: _3!, userHandle: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputPasskeyResponse.inputPasskeyResponseLogin(Cons_inputPasskeyResponseLogin(clientData: _1!, authenticatorData: _2!, signature: _3!, userHandle: _4!)) + } + else { + return nil + } } public static func parse_inputPasskeyResponseRegister(_ reader: BufferReader) -> InputPasskeyResponse? { var _1: Api.DataJSON? @@ -983,10 +1423,12 @@ public extension Api { _2 = parseBytes(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputPasskeyResponse.inputPasskeyResponseRegister(clientData: _1!, attestationData: _2!) + if _c1 && _c2 { + return Api.InputPasskeyResponse.inputPasskeyResponseRegister(Cons_inputPasskeyResponseRegister(clientData: _1!, attestationData: _2!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api12.swift b/submodules/TelegramApi/Sources/Api12.swift index 42fc616a..fcccdfe5 100644 --- a/submodules/TelegramApi/Sources/Api12.swift +++ b/submodules/TelegramApi/Sources/Api12.swift @@ -1,54 +1,82 @@ public extension Api { enum InputPaymentCredentials: TypeConstructorDescription { - case inputPaymentCredentials(flags: Int32, data: Api.DataJSON) - case inputPaymentCredentialsApplePay(paymentData: Api.DataJSON) - case inputPaymentCredentialsGooglePay(paymentToken: Api.DataJSON) - case inputPaymentCredentialsSaved(id: String, tmpPassword: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputPaymentCredentials(let flags, let data): - if boxed { - buffer.appendInt32(873977640) - } - serializeInt32(flags, buffer: buffer, boxed: false) - data.serialize(buffer, true) - break - case .inputPaymentCredentialsApplePay(let paymentData): - if boxed { - buffer.appendInt32(178373535) - } - paymentData.serialize(buffer, true) - break - case .inputPaymentCredentialsGooglePay(let paymentToken): - if boxed { - buffer.appendInt32(-1966921727) - } - paymentToken.serialize(buffer, true) - break - case .inputPaymentCredentialsSaved(let id, let tmpPassword): - if boxed { - buffer.appendInt32(-1056001329) - } - serializeString(id, buffer: buffer, boxed: false) - serializeBytes(tmpPassword, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputPaymentCredentials(let flags, let data): - return ("inputPaymentCredentials", [("flags", flags as Any), ("data", data as Any)]) - case .inputPaymentCredentialsApplePay(let paymentData): - return ("inputPaymentCredentialsApplePay", [("paymentData", paymentData as Any)]) - case .inputPaymentCredentialsGooglePay(let paymentToken): - return ("inputPaymentCredentialsGooglePay", [("paymentToken", paymentToken as Any)]) - case .inputPaymentCredentialsSaved(let id, let tmpPassword): - return ("inputPaymentCredentialsSaved", [("id", id as Any), ("tmpPassword", tmpPassword as Any)]) - } - } - + public class Cons_inputPaymentCredentials { + public var flags: Int32 + public var data: Api.DataJSON + public init(flags: Int32, data: Api.DataJSON) { + self.flags = flags + self.data = data + } + } + public class Cons_inputPaymentCredentialsApplePay { + public var paymentData: Api.DataJSON + public init(paymentData: Api.DataJSON) { + self.paymentData = paymentData + } + } + public class Cons_inputPaymentCredentialsGooglePay { + public var paymentToken: Api.DataJSON + public init(paymentToken: Api.DataJSON) { + self.paymentToken = paymentToken + } + } + public class Cons_inputPaymentCredentialsSaved { + public var id: String + public var tmpPassword: Buffer + public init(id: String, tmpPassword: Buffer) { + self.id = id + self.tmpPassword = tmpPassword + } + } + case inputPaymentCredentials(Cons_inputPaymentCredentials) + case inputPaymentCredentialsApplePay(Cons_inputPaymentCredentialsApplePay) + case inputPaymentCredentialsGooglePay(Cons_inputPaymentCredentialsGooglePay) + case inputPaymentCredentialsSaved(Cons_inputPaymentCredentialsSaved) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputPaymentCredentials(let _data): + if boxed { + buffer.appendInt32(873977640) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.data.serialize(buffer, true) + break + case .inputPaymentCredentialsApplePay(let _data): + if boxed { + buffer.appendInt32(178373535) + } + _data.paymentData.serialize(buffer, true) + break + case .inputPaymentCredentialsGooglePay(let _data): + if boxed { + buffer.appendInt32(-1966921727) + } + _data.paymentToken.serialize(buffer, true) + break + case .inputPaymentCredentialsSaved(let _data): + if boxed { + buffer.appendInt32(-1056001329) + } + serializeString(_data.id, buffer: buffer, boxed: false) + serializeBytes(_data.tmpPassword, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputPaymentCredentials(let _data): + return ("inputPaymentCredentials", [("flags", _data.flags as Any), ("data", _data.data as Any)]) + case .inputPaymentCredentialsApplePay(let _data): + return ("inputPaymentCredentialsApplePay", [("paymentData", _data.paymentData as Any)]) + case .inputPaymentCredentialsGooglePay(let _data): + return ("inputPaymentCredentialsGooglePay", [("paymentToken", _data.paymentToken as Any)]) + case .inputPaymentCredentialsSaved(let _data): + return ("inputPaymentCredentialsSaved", [("id", _data.id as Any), ("tmpPassword", _data.tmpPassword as Any)]) + } + } + public static func parse_inputPaymentCredentials(_ reader: BufferReader) -> InputPaymentCredentials? { var _1: Int32? _1 = reader.readInt32() @@ -58,9 +86,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputPaymentCredentials.inputPaymentCredentials(flags: _1!, data: _2!) + if _c1 && _c2 { + return Api.InputPaymentCredentials.inputPaymentCredentials(Cons_inputPaymentCredentials(flags: _1!, data: _2!)) + } + else { + return nil + } } public static func parse_inputPaymentCredentialsApplePay(_ reader: BufferReader) -> InputPaymentCredentials? { var _1: Api.DataJSON? @@ -68,8 +99,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.DataJSON } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputPaymentCredentials.inputPaymentCredentialsApplePay(paymentData: _1!) + if _c1 { + return Api.InputPaymentCredentials.inputPaymentCredentialsApplePay(Cons_inputPaymentCredentialsApplePay(paymentData: _1!)) + } + else { + return nil + } } public static func parse_inputPaymentCredentialsGooglePay(_ reader: BufferReader) -> InputPaymentCredentials? { var _1: Api.DataJSON? @@ -77,8 +112,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.DataJSON } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputPaymentCredentials.inputPaymentCredentialsGooglePay(paymentToken: _1!) + if _c1 { + return Api.InputPaymentCredentials.inputPaymentCredentialsGooglePay(Cons_inputPaymentCredentialsGooglePay(paymentToken: _1!)) + } + else { + return nil + } } public static func parse_inputPaymentCredentialsSaved(_ reader: BufferReader) -> InputPaymentCredentials? { var _1: String? @@ -87,95 +126,137 @@ public extension Api { _2 = parseBytes(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputPaymentCredentials.inputPaymentCredentialsSaved(id: _1!, tmpPassword: _2!) + if _c1 && _c2 { + return Api.InputPaymentCredentials.inputPaymentCredentialsSaved(Cons_inputPaymentCredentialsSaved(id: _1!, tmpPassword: _2!)) + } + else { + return nil + } } - } } public extension Api { indirect enum InputPeer: TypeConstructorDescription { - case inputPeerChannel(channelId: Int64, accessHash: Int64) - case inputPeerChannelFromMessage(peer: Api.InputPeer, msgId: Int32, channelId: Int64) - case inputPeerChat(chatId: Int64) + public class Cons_inputPeerChannel { + public var channelId: Int64 + public var accessHash: Int64 + public init(channelId: Int64, accessHash: Int64) { + self.channelId = channelId + self.accessHash = accessHash + } + } + public class Cons_inputPeerChannelFromMessage { + public var peer: Api.InputPeer + public var msgId: Int32 + public var channelId: Int64 + public init(peer: Api.InputPeer, msgId: Int32, channelId: Int64) { + self.peer = peer + self.msgId = msgId + self.channelId = channelId + } + } + public class Cons_inputPeerChat { + public var chatId: Int64 + public init(chatId: Int64) { + self.chatId = chatId + } + } + public class Cons_inputPeerUser { + public var userId: Int64 + public var accessHash: Int64 + public init(userId: Int64, accessHash: Int64) { + self.userId = userId + self.accessHash = accessHash + } + } + public class Cons_inputPeerUserFromMessage { + public var peer: Api.InputPeer + public var msgId: Int32 + public var userId: Int64 + public init(peer: Api.InputPeer, msgId: Int32, userId: Int64) { + self.peer = peer + self.msgId = msgId + self.userId = userId + } + } + case inputPeerChannel(Cons_inputPeerChannel) + case inputPeerChannelFromMessage(Cons_inputPeerChannelFromMessage) + case inputPeerChat(Cons_inputPeerChat) case inputPeerEmpty case inputPeerSelf - case inputPeerUser(userId: Int64, accessHash: Int64) - case inputPeerUserFromMessage(peer: Api.InputPeer, msgId: Int32, userId: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputPeerChannel(let channelId, let accessHash): - if boxed { - buffer.appendInt32(666680316) - } - serializeInt64(channelId, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - case .inputPeerChannelFromMessage(let peer, let msgId, let channelId): - if boxed { - buffer.appendInt32(-1121318848) - } - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeInt64(channelId, buffer: buffer, boxed: false) - break - case .inputPeerChat(let chatId): - if boxed { - buffer.appendInt32(900291769) - } - serializeInt64(chatId, buffer: buffer, boxed: false) - break - case .inputPeerEmpty: - if boxed { - buffer.appendInt32(2134579434) - } - - break - case .inputPeerSelf: - if boxed { - buffer.appendInt32(2107670217) - } - - break - case .inputPeerUser(let userId, let accessHash): - if boxed { - buffer.appendInt32(-571955892) - } - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - case .inputPeerUserFromMessage(let peer, let msgId, let userId): - if boxed { - buffer.appendInt32(-1468331492) - } - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputPeerChannel(let channelId, let accessHash): - return ("inputPeerChannel", [("channelId", channelId as Any), ("accessHash", accessHash as Any)]) - case .inputPeerChannelFromMessage(let peer, let msgId, let channelId): - return ("inputPeerChannelFromMessage", [("peer", peer as Any), ("msgId", msgId as Any), ("channelId", channelId as Any)]) - case .inputPeerChat(let chatId): - return ("inputPeerChat", [("chatId", chatId as Any)]) - case .inputPeerEmpty: + case inputPeerUser(Cons_inputPeerUser) + case inputPeerUserFromMessage(Cons_inputPeerUserFromMessage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputPeerChannel(let _data): + if boxed { + buffer.appendInt32(666680316) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + case .inputPeerChannelFromMessage(let _data): + if boxed { + buffer.appendInt32(-1121318848) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + break + case .inputPeerChat(let _data): + if boxed { + buffer.appendInt32(900291769) + } + serializeInt64(_data.chatId, buffer: buffer, boxed: false) + break + case .inputPeerEmpty: + if boxed { + buffer.appendInt32(2134579434) + } + break + case .inputPeerSelf: + if boxed { + buffer.appendInt32(2107670217) + } + break + case .inputPeerUser(let _data): + if boxed { + buffer.appendInt32(-571955892) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + case .inputPeerUserFromMessage(let _data): + if boxed { + buffer.appendInt32(-1468331492) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputPeerChannel(let _data): + return ("inputPeerChannel", [("channelId", _data.channelId as Any), ("accessHash", _data.accessHash as Any)]) + case .inputPeerChannelFromMessage(let _data): + return ("inputPeerChannelFromMessage", [("peer", _data.peer as Any), ("msgId", _data.msgId as Any), ("channelId", _data.channelId as Any)]) + case .inputPeerChat(let _data): + return ("inputPeerChat", [("chatId", _data.chatId as Any)]) + case .inputPeerEmpty: return ("inputPeerEmpty", []) - case .inputPeerSelf: + case .inputPeerSelf: return ("inputPeerSelf", []) - case .inputPeerUser(let userId, let accessHash): - return ("inputPeerUser", [("userId", userId as Any), ("accessHash", accessHash as Any)]) - case .inputPeerUserFromMessage(let peer, let msgId, let userId): - return ("inputPeerUserFromMessage", [("peer", peer as Any), ("msgId", msgId as Any), ("userId", userId as Any)]) - } - } - + case .inputPeerUser(let _data): + return ("inputPeerUser", [("userId", _data.userId as Any), ("accessHash", _data.accessHash as Any)]) + case .inputPeerUserFromMessage(let _data): + return ("inputPeerUserFromMessage", [("peer", _data.peer as Any), ("msgId", _data.msgId as Any), ("userId", _data.userId as Any)]) + } + } + public static func parse_inputPeerChannel(_ reader: BufferReader) -> InputPeer? { var _1: Int64? _1 = reader.readInt64() @@ -183,9 +264,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputPeer.inputPeerChannel(channelId: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputPeer.inputPeerChannel(Cons_inputPeerChannel(channelId: _1!, accessHash: _2!)) + } + else { + return nil + } } public static func parse_inputPeerChannelFromMessage(_ reader: BufferReader) -> InputPeer? { var _1: Api.InputPeer? @@ -199,17 +283,23 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputPeer.inputPeerChannelFromMessage(peer: _1!, msgId: _2!, channelId: _3!) + if _c1 && _c2 && _c3 { + return Api.InputPeer.inputPeerChannelFromMessage(Cons_inputPeerChannelFromMessage(peer: _1!, msgId: _2!, channelId: _3!)) + } + else { + return nil + } } public static func parse_inputPeerChat(_ reader: BufferReader) -> InputPeer? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputPeer.inputPeerChat(chatId: _1!) + if _c1 { + return Api.InputPeer.inputPeerChat(Cons_inputPeerChat(chatId: _1!)) + } + else { + return nil + } } public static func parse_inputPeerEmpty(_ reader: BufferReader) -> InputPeer? { return Api.InputPeer.inputPeerEmpty @@ -224,9 +314,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputPeer.inputPeerUser(userId: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputPeer.inputPeerUser(Cons_inputPeerUser(userId: _1!, accessHash: _2!)) + } + else { + return nil + } } public static func parse_inputPeerUserFromMessage(_ reader: BufferReader) -> InputPeer? { var _1: Api.InputPeer? @@ -240,72 +333,121 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputPeer.inputPeerUserFromMessage(peer: _1!, msgId: _2!, userId: _3!) + if _c1 && _c2 && _c3 { + return Api.InputPeer.inputPeerUserFromMessage(Cons_inputPeerUserFromMessage(peer: _1!, msgId: _2!, userId: _3!)) + } + else { + return nil + } } - } } public extension Api { enum InputPeerNotifySettings: TypeConstructorDescription { - case inputPeerNotifySettings(flags: Int32, showPreviews: Api.Bool?, silent: Api.Bool?, muteUntil: Int32?, sound: Api.NotificationSound?, storiesMuted: Api.Bool?, storiesHideSender: Api.Bool?, storiesSound: Api.NotificationSound?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputPeerNotifySettings(let flags, let showPreviews, let silent, let muteUntil, let sound, let storiesMuted, let storiesHideSender, let storiesSound): - if boxed { - buffer.appendInt32(-892638494) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {showPreviews!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {silent!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(muteUntil!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {sound!.serialize(buffer, true)} - if Int(flags) & Int(1 << 6) != 0 {storiesMuted!.serialize(buffer, true)} - if Int(flags) & Int(1 << 7) != 0 {storiesHideSender!.serialize(buffer, true)} - if Int(flags) & Int(1 << 8) != 0 {storiesSound!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputPeerNotifySettings(let flags, let showPreviews, let silent, let muteUntil, let sound, let storiesMuted, let storiesHideSender, let storiesSound): - return ("inputPeerNotifySettings", [("flags", flags as Any), ("showPreviews", showPreviews as Any), ("silent", silent as Any), ("muteUntil", muteUntil as Any), ("sound", sound as Any), ("storiesMuted", storiesMuted as Any), ("storiesHideSender", storiesHideSender as Any), ("storiesSound", storiesSound as Any)]) - } - } - + public class Cons_inputPeerNotifySettings { + public var flags: Int32 + public var showPreviews: Api.Bool? + public var silent: Api.Bool? + public var muteUntil: Int32? + public var sound: Api.NotificationSound? + public var storiesMuted: Api.Bool? + public var storiesHideSender: Api.Bool? + public var storiesSound: Api.NotificationSound? + public init(flags: Int32, showPreviews: Api.Bool?, silent: Api.Bool?, muteUntil: Int32?, sound: Api.NotificationSound?, storiesMuted: Api.Bool?, storiesHideSender: Api.Bool?, storiesSound: Api.NotificationSound?) { + self.flags = flags + self.showPreviews = showPreviews + self.silent = silent + self.muteUntil = muteUntil + self.sound = sound + self.storiesMuted = storiesMuted + self.storiesHideSender = storiesHideSender + self.storiesSound = storiesSound + } + } + case inputPeerNotifySettings(Cons_inputPeerNotifySettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputPeerNotifySettings(let _data): + if boxed { + buffer.appendInt32(-892638494) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.showPreviews!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.silent!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.muteUntil!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.sound!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + _data.storiesMuted!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 7) != 0 { + _data.storiesHideSender!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + _data.storiesSound!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputPeerNotifySettings(let _data): + return ("inputPeerNotifySettings", [("flags", _data.flags as Any), ("showPreviews", _data.showPreviews as Any), ("silent", _data.silent as Any), ("muteUntil", _data.muteUntil as Any), ("sound", _data.sound as Any), ("storiesMuted", _data.storiesMuted as Any), ("storiesHideSender", _data.storiesHideSender as Any), ("storiesSound", _data.storiesSound as Any)]) + } + } + public static func parse_inputPeerNotifySettings(_ reader: BufferReader) -> InputPeerNotifySettings? { var _1: Int32? _1 = reader.readInt32() var _2: Api.Bool? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Bool + } + } var _3: Api.Bool? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Bool + } + } var _4: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _4 = reader.readInt32() + } var _5: Api.NotificationSound? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.NotificationSound - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.NotificationSound + } + } var _6: Api.Bool? - if Int(_1!) & Int(1 << 6) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 6) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.Bool + } + } var _7: Api.Bool? - if Int(_1!) & Int(1 << 7) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 7) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.Bool + } + } var _8: Api.NotificationSound? - if Int(_1!) & Int(1 << 8) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.NotificationSound - } } + if Int(_1!) & Int(1 << 8) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.NotificationSound + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil @@ -314,42 +456,46 @@ public extension Api { let _c6 = (Int(_1!) & Int(1 << 6) == 0) || _6 != nil let _c7 = (Int(_1!) & Int(1 << 7) == 0) || _7 != nil let _c8 = (Int(_1!) & Int(1 << 8) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.InputPeerNotifySettings.inputPeerNotifySettings(flags: _1!, showPreviews: _2, silent: _3, muteUntil: _4, sound: _5, storiesMuted: _6, storiesHideSender: _7, storiesSound: _8) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.InputPeerNotifySettings.inputPeerNotifySettings(Cons_inputPeerNotifySettings(flags: _1!, showPreviews: _2, silent: _3, muteUntil: _4, sound: _5, storiesMuted: _6, storiesHideSender: _7, storiesSound: _8)) + } + else { + return nil + } } - } } public extension Api { enum InputPhoneCall: TypeConstructorDescription { - case inputPhoneCall(id: Int64, accessHash: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputPhoneCall(let id, let accessHash): - if boxed { - buffer.appendInt32(506920429) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputPhoneCall(let id, let accessHash): - return ("inputPhoneCall", [("id", id as Any), ("accessHash", accessHash as Any)]) - } - } - + public class Cons_inputPhoneCall { + public var id: Int64 + public var accessHash: Int64 + public init(id: Int64, accessHash: Int64) { + self.id = id + self.accessHash = accessHash + } + } + case inputPhoneCall(Cons_inputPhoneCall) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputPhoneCall(let _data): + if boxed { + buffer.appendInt32(506920429) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputPhoneCall(let _data): + return ("inputPhoneCall", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any)]) + } + } + public static func parse_inputPhoneCall(_ reader: BufferReader) -> InputPhoneCall? { var _1: Int64? _1 = reader.readInt64() @@ -357,46 +503,57 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputPhoneCall.inputPhoneCall(id: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputPhoneCall.inputPhoneCall(Cons_inputPhoneCall(id: _1!, accessHash: _2!)) + } + else { + return nil + } } - } } public extension Api { enum InputPhoto: TypeConstructorDescription { - case inputPhoto(id: Int64, accessHash: Int64, fileReference: Buffer) + public class Cons_inputPhoto { + public var id: Int64 + public var accessHash: Int64 + public var fileReference: Buffer + public init(id: Int64, accessHash: Int64, fileReference: Buffer) { + self.id = id + self.accessHash = accessHash + self.fileReference = fileReference + } + } + case inputPhoto(Cons_inputPhoto) case inputPhotoEmpty - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputPhoto(let id, let accessHash, let fileReference): - if boxed { - buffer.appendInt32(1001634122) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeBytes(fileReference, buffer: buffer, boxed: false) - break - case .inputPhotoEmpty: - if boxed { - buffer.appendInt32(483901197) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputPhoto(let id, let accessHash, let fileReference): - return ("inputPhoto", [("id", id as Any), ("accessHash", accessHash as Any), ("fileReference", fileReference as Any)]) - case .inputPhotoEmpty: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputPhoto(let _data): + if boxed { + buffer.appendInt32(1001634122) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeBytes(_data.fileReference, buffer: buffer, boxed: false) + break + case .inputPhotoEmpty: + if boxed { + buffer.appendInt32(483901197) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputPhoto(let _data): + return ("inputPhoto", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("fileReference", _data.fileReference as Any)]) + case .inputPhotoEmpty: return ("inputPhotoEmpty", []) - } - } - + } + } + public static func parse_inputPhoto(_ reader: BufferReader) -> InputPhoto? { var _1: Int64? _1 = reader.readInt64() @@ -407,15 +564,16 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputPhoto.inputPhoto(id: _1!, accessHash: _2!, fileReference: _3!) + if _c1 && _c2 && _c3 { + return Api.InputPhoto.inputPhoto(Cons_inputPhoto(id: _1!, accessHash: _2!, fileReference: _3!)) + } + else { + return nil + } } public static func parse_inputPhotoEmpty(_ reader: BufferReader) -> InputPhoto? { return Api.InputPhoto.inputPhotoEmpty } - } } public extension Api { @@ -434,129 +592,115 @@ public extension Api { case inputPrivacyKeyStarGiftsAutoSave case inputPrivacyKeyStatusTimestamp case inputPrivacyKeyVoiceMessages - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputPrivacyKeyAbout: - if boxed { - buffer.appendInt32(941870144) - } - - break - case .inputPrivacyKeyAddedByPhone: - if boxed { - buffer.appendInt32(-786326563) - } - - break - case .inputPrivacyKeyBirthday: - if boxed { - buffer.appendInt32(-698740276) - } - - break - case .inputPrivacyKeyChatInvite: - if boxed { - buffer.appendInt32(-1107622874) - } - - break - case .inputPrivacyKeyForwards: - if boxed { - buffer.appendInt32(-1529000952) - } - - break - case .inputPrivacyKeyNoPaidMessages: - if boxed { - buffer.appendInt32(-1111124044) - } - - break - case .inputPrivacyKeyPhoneCall: - if boxed { - buffer.appendInt32(-88417185) - } - - break - case .inputPrivacyKeyPhoneNumber: - if boxed { - buffer.appendInt32(55761658) - } - - break - case .inputPrivacyKeyPhoneP2P: - if boxed { - buffer.appendInt32(-610373422) - } - - break - case .inputPrivacyKeyProfilePhoto: - if boxed { - buffer.appendInt32(1461304012) - } - - break - case .inputPrivacyKeySavedMusic: - if boxed { - buffer.appendInt32(1304334886) - } - - break - case .inputPrivacyKeyStarGiftsAutoSave: - if boxed { - buffer.appendInt32(-512548031) - } - - break - case .inputPrivacyKeyStatusTimestamp: - if boxed { - buffer.appendInt32(1335282456) - } - - break - case .inputPrivacyKeyVoiceMessages: - if boxed { - buffer.appendInt32(-1360618136) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputPrivacyKeyAbout: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputPrivacyKeyAbout: + if boxed { + buffer.appendInt32(941870144) + } + break + case .inputPrivacyKeyAddedByPhone: + if boxed { + buffer.appendInt32(-786326563) + } + break + case .inputPrivacyKeyBirthday: + if boxed { + buffer.appendInt32(-698740276) + } + break + case .inputPrivacyKeyChatInvite: + if boxed { + buffer.appendInt32(-1107622874) + } + break + case .inputPrivacyKeyForwards: + if boxed { + buffer.appendInt32(-1529000952) + } + break + case .inputPrivacyKeyNoPaidMessages: + if boxed { + buffer.appendInt32(-1111124044) + } + break + case .inputPrivacyKeyPhoneCall: + if boxed { + buffer.appendInt32(-88417185) + } + break + case .inputPrivacyKeyPhoneNumber: + if boxed { + buffer.appendInt32(55761658) + } + break + case .inputPrivacyKeyPhoneP2P: + if boxed { + buffer.appendInt32(-610373422) + } + break + case .inputPrivacyKeyProfilePhoto: + if boxed { + buffer.appendInt32(1461304012) + } + break + case .inputPrivacyKeySavedMusic: + if boxed { + buffer.appendInt32(1304334886) + } + break + case .inputPrivacyKeyStarGiftsAutoSave: + if boxed { + buffer.appendInt32(-512548031) + } + break + case .inputPrivacyKeyStatusTimestamp: + if boxed { + buffer.appendInt32(1335282456) + } + break + case .inputPrivacyKeyVoiceMessages: + if boxed { + buffer.appendInt32(-1360618136) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputPrivacyKeyAbout: return ("inputPrivacyKeyAbout", []) - case .inputPrivacyKeyAddedByPhone: + case .inputPrivacyKeyAddedByPhone: return ("inputPrivacyKeyAddedByPhone", []) - case .inputPrivacyKeyBirthday: + case .inputPrivacyKeyBirthday: return ("inputPrivacyKeyBirthday", []) - case .inputPrivacyKeyChatInvite: + case .inputPrivacyKeyChatInvite: return ("inputPrivacyKeyChatInvite", []) - case .inputPrivacyKeyForwards: + case .inputPrivacyKeyForwards: return ("inputPrivacyKeyForwards", []) - case .inputPrivacyKeyNoPaidMessages: + case .inputPrivacyKeyNoPaidMessages: return ("inputPrivacyKeyNoPaidMessages", []) - case .inputPrivacyKeyPhoneCall: + case .inputPrivacyKeyPhoneCall: return ("inputPrivacyKeyPhoneCall", []) - case .inputPrivacyKeyPhoneNumber: + case .inputPrivacyKeyPhoneNumber: return ("inputPrivacyKeyPhoneNumber", []) - case .inputPrivacyKeyPhoneP2P: + case .inputPrivacyKeyPhoneP2P: return ("inputPrivacyKeyPhoneP2P", []) - case .inputPrivacyKeyProfilePhoto: + case .inputPrivacyKeyProfilePhoto: return ("inputPrivacyKeyProfilePhoto", []) - case .inputPrivacyKeySavedMusic: + case .inputPrivacyKeySavedMusic: return ("inputPrivacyKeySavedMusic", []) - case .inputPrivacyKeyStarGiftsAutoSave: + case .inputPrivacyKeyStarGiftsAutoSave: return ("inputPrivacyKeyStarGiftsAutoSave", []) - case .inputPrivacyKeyStatusTimestamp: + case .inputPrivacyKeyStatusTimestamp: return ("inputPrivacyKeyStatusTimestamp", []) - case .inputPrivacyKeyVoiceMessages: + case .inputPrivacyKeyVoiceMessages: return ("inputPrivacyKeyVoiceMessages", []) - } - } - + } + } + public static func parse_inputPrivacyKeyAbout(_ reader: BufferReader) -> InputPrivacyKey? { return Api.InputPrivacyKey.inputPrivacyKeyAbout } @@ -599,146 +743,161 @@ public extension Api { public static func parse_inputPrivacyKeyVoiceMessages(_ reader: BufferReader) -> InputPrivacyKey? { return Api.InputPrivacyKey.inputPrivacyKeyVoiceMessages } - } } public extension Api { enum InputPrivacyRule: TypeConstructorDescription { + public class Cons_inputPrivacyValueAllowChatParticipants { + public var chats: [Int64] + public init(chats: [Int64]) { + self.chats = chats + } + } + public class Cons_inputPrivacyValueAllowUsers { + public var users: [Api.InputUser] + public init(users: [Api.InputUser]) { + self.users = users + } + } + public class Cons_inputPrivacyValueDisallowChatParticipants { + public var chats: [Int64] + public init(chats: [Int64]) { + self.chats = chats + } + } + public class Cons_inputPrivacyValueDisallowUsers { + public var users: [Api.InputUser] + public init(users: [Api.InputUser]) { + self.users = users + } + } case inputPrivacyValueAllowAll case inputPrivacyValueAllowBots - case inputPrivacyValueAllowChatParticipants(chats: [Int64]) + case inputPrivacyValueAllowChatParticipants(Cons_inputPrivacyValueAllowChatParticipants) case inputPrivacyValueAllowCloseFriends case inputPrivacyValueAllowContacts case inputPrivacyValueAllowPremium - case inputPrivacyValueAllowUsers(users: [Api.InputUser]) + case inputPrivacyValueAllowUsers(Cons_inputPrivacyValueAllowUsers) case inputPrivacyValueDisallowAll case inputPrivacyValueDisallowBots - case inputPrivacyValueDisallowChatParticipants(chats: [Int64]) + case inputPrivacyValueDisallowChatParticipants(Cons_inputPrivacyValueDisallowChatParticipants) case inputPrivacyValueDisallowContacts - case inputPrivacyValueDisallowUsers(users: [Api.InputUser]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputPrivacyValueAllowAll: - if boxed { - buffer.appendInt32(407582158) - } - - break - case .inputPrivacyValueAllowBots: - if boxed { - buffer.appendInt32(1515179237) - } - - break - case .inputPrivacyValueAllowChatParticipants(let chats): - if boxed { - buffer.appendInt32(-2079962673) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - serializeInt64(item, buffer: buffer, boxed: false) - } - break - case .inputPrivacyValueAllowCloseFriends: - if boxed { - buffer.appendInt32(793067081) - } - - break - case .inputPrivacyValueAllowContacts: - if boxed { - buffer.appendInt32(218751099) - } - - break - case .inputPrivacyValueAllowPremium: - if boxed { - buffer.appendInt32(2009975281) - } - - break - case .inputPrivacyValueAllowUsers(let users): - if boxed { - buffer.appendInt32(320652927) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .inputPrivacyValueDisallowAll: - if boxed { - buffer.appendInt32(-697604407) - } - - break - case .inputPrivacyValueDisallowBots: - if boxed { - buffer.appendInt32(-991594219) - } - - break - case .inputPrivacyValueDisallowChatParticipants(let chats): - if boxed { - buffer.appendInt32(-380694650) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - serializeInt64(item, buffer: buffer, boxed: false) - } - break - case .inputPrivacyValueDisallowContacts: - if boxed { - buffer.appendInt32(195371015) - } - - break - case .inputPrivacyValueDisallowUsers(let users): - if boxed { - buffer.appendInt32(-1877932953) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputPrivacyValueAllowAll: + case inputPrivacyValueDisallowUsers(Cons_inputPrivacyValueDisallowUsers) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputPrivacyValueAllowAll: + if boxed { + buffer.appendInt32(407582158) + } + break + case .inputPrivacyValueAllowBots: + if boxed { + buffer.appendInt32(1515179237) + } + break + case .inputPrivacyValueAllowChatParticipants(let _data): + if boxed { + buffer.appendInt32(-2079962673) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + serializeInt64(item, buffer: buffer, boxed: false) + } + break + case .inputPrivacyValueAllowCloseFriends: + if boxed { + buffer.appendInt32(793067081) + } + break + case .inputPrivacyValueAllowContacts: + if boxed { + buffer.appendInt32(218751099) + } + break + case .inputPrivacyValueAllowPremium: + if boxed { + buffer.appendInt32(2009975281) + } + break + case .inputPrivacyValueAllowUsers(let _data): + if boxed { + buffer.appendInt32(320652927) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .inputPrivacyValueDisallowAll: + if boxed { + buffer.appendInt32(-697604407) + } + break + case .inputPrivacyValueDisallowBots: + if boxed { + buffer.appendInt32(-991594219) + } + break + case .inputPrivacyValueDisallowChatParticipants(let _data): + if boxed { + buffer.appendInt32(-380694650) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + serializeInt64(item, buffer: buffer, boxed: false) + } + break + case .inputPrivacyValueDisallowContacts: + if boxed { + buffer.appendInt32(195371015) + } + break + case .inputPrivacyValueDisallowUsers(let _data): + if boxed { + buffer.appendInt32(-1877932953) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputPrivacyValueAllowAll: return ("inputPrivacyValueAllowAll", []) - case .inputPrivacyValueAllowBots: + case .inputPrivacyValueAllowBots: return ("inputPrivacyValueAllowBots", []) - case .inputPrivacyValueAllowChatParticipants(let chats): - return ("inputPrivacyValueAllowChatParticipants", [("chats", chats as Any)]) - case .inputPrivacyValueAllowCloseFriends: + case .inputPrivacyValueAllowChatParticipants(let _data): + return ("inputPrivacyValueAllowChatParticipants", [("chats", _data.chats as Any)]) + case .inputPrivacyValueAllowCloseFriends: return ("inputPrivacyValueAllowCloseFriends", []) - case .inputPrivacyValueAllowContacts: + case .inputPrivacyValueAllowContacts: return ("inputPrivacyValueAllowContacts", []) - case .inputPrivacyValueAllowPremium: + case .inputPrivacyValueAllowPremium: return ("inputPrivacyValueAllowPremium", []) - case .inputPrivacyValueAllowUsers(let users): - return ("inputPrivacyValueAllowUsers", [("users", users as Any)]) - case .inputPrivacyValueDisallowAll: + case .inputPrivacyValueAllowUsers(let _data): + return ("inputPrivacyValueAllowUsers", [("users", _data.users as Any)]) + case .inputPrivacyValueDisallowAll: return ("inputPrivacyValueDisallowAll", []) - case .inputPrivacyValueDisallowBots: + case .inputPrivacyValueDisallowBots: return ("inputPrivacyValueDisallowBots", []) - case .inputPrivacyValueDisallowChatParticipants(let chats): - return ("inputPrivacyValueDisallowChatParticipants", [("chats", chats as Any)]) - case .inputPrivacyValueDisallowContacts: + case .inputPrivacyValueDisallowChatParticipants(let _data): + return ("inputPrivacyValueDisallowChatParticipants", [("chats", _data.chats as Any)]) + case .inputPrivacyValueDisallowContacts: return ("inputPrivacyValueDisallowContacts", []) - case .inputPrivacyValueDisallowUsers(let users): - return ("inputPrivacyValueDisallowUsers", [("users", users as Any)]) - } - } - + case .inputPrivacyValueDisallowUsers(let _data): + return ("inputPrivacyValueDisallowUsers", [("users", _data.users as Any)]) + } + } + public static func parse_inputPrivacyValueAllowAll(_ reader: BufferReader) -> InputPrivacyRule? { return Api.InputPrivacyRule.inputPrivacyValueAllowAll } @@ -751,8 +910,12 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputPrivacyRule.inputPrivacyValueAllowChatParticipants(chats: _1!) + if _c1 { + return Api.InputPrivacyRule.inputPrivacyValueAllowChatParticipants(Cons_inputPrivacyValueAllowChatParticipants(chats: _1!)) + } + else { + return nil + } } public static func parse_inputPrivacyValueAllowCloseFriends(_ reader: BufferReader) -> InputPrivacyRule? { return Api.InputPrivacyRule.inputPrivacyValueAllowCloseFriends @@ -769,8 +932,12 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputUser.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputPrivacyRule.inputPrivacyValueAllowUsers(users: _1!) + if _c1 { + return Api.InputPrivacyRule.inputPrivacyValueAllowUsers(Cons_inputPrivacyValueAllowUsers(users: _1!)) + } + else { + return nil + } } public static func parse_inputPrivacyValueDisallowAll(_ reader: BufferReader) -> InputPrivacyRule? { return Api.InputPrivacyRule.inputPrivacyValueDisallowAll @@ -784,8 +951,12 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputPrivacyRule.inputPrivacyValueDisallowChatParticipants(chats: _1!) + if _c1 { + return Api.InputPrivacyRule.inputPrivacyValueDisallowChatParticipants(Cons_inputPrivacyValueDisallowChatParticipants(chats: _1!)) + } + else { + return nil + } } public static func parse_inputPrivacyValueDisallowContacts(_ reader: BufferReader) -> InputPrivacyRule? { return Api.InputPrivacyRule.inputPrivacyValueDisallowContacts @@ -796,9 +967,12 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputUser.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputPrivacyRule.inputPrivacyValueDisallowUsers(users: _1!) + if _c1 { + return Api.InputPrivacyRule.inputPrivacyValueDisallowUsers(Cons_inputPrivacyValueDisallowUsers(users: _1!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api13.swift b/submodules/TelegramApi/Sources/Api13.swift index fa5243cf..85cb63ae 100644 --- a/submodules/TelegramApi/Sources/Api13.swift +++ b/submodules/TelegramApi/Sources/Api13.swift @@ -1,129 +1,212 @@ public extension Api { enum InputQuickReplyShortcut: TypeConstructorDescription { - case inputQuickReplyShortcut(shortcut: String) - case inputQuickReplyShortcutId(shortcutId: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputQuickReplyShortcut(let shortcut): - if boxed { - buffer.appendInt32(609840449) - } - serializeString(shortcut, buffer: buffer, boxed: false) - break - case .inputQuickReplyShortcutId(let shortcutId): - if boxed { - buffer.appendInt32(18418929) - } - serializeInt32(shortcutId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputQuickReplyShortcut(let shortcut): - return ("inputQuickReplyShortcut", [("shortcut", shortcut as Any)]) - case .inputQuickReplyShortcutId(let shortcutId): - return ("inputQuickReplyShortcutId", [("shortcutId", shortcutId as Any)]) - } - } - + public class Cons_inputQuickReplyShortcut { + public var shortcut: String + public init(shortcut: String) { + self.shortcut = shortcut + } + } + public class Cons_inputQuickReplyShortcutId { + public var shortcutId: Int32 + public init(shortcutId: Int32) { + self.shortcutId = shortcutId + } + } + case inputQuickReplyShortcut(Cons_inputQuickReplyShortcut) + case inputQuickReplyShortcutId(Cons_inputQuickReplyShortcutId) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputQuickReplyShortcut(let _data): + if boxed { + buffer.appendInt32(609840449) + } + serializeString(_data.shortcut, buffer: buffer, boxed: false) + break + case .inputQuickReplyShortcutId(let _data): + if boxed { + buffer.appendInt32(18418929) + } + serializeInt32(_data.shortcutId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputQuickReplyShortcut(let _data): + return ("inputQuickReplyShortcut", [("shortcut", _data.shortcut as Any)]) + case .inputQuickReplyShortcutId(let _data): + return ("inputQuickReplyShortcutId", [("shortcutId", _data.shortcutId as Any)]) + } + } + public static func parse_inputQuickReplyShortcut(_ reader: BufferReader) -> InputQuickReplyShortcut? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputQuickReplyShortcut.inputQuickReplyShortcut(shortcut: _1!) + if _c1 { + return Api.InputQuickReplyShortcut.inputQuickReplyShortcut(Cons_inputQuickReplyShortcut(shortcut: _1!)) + } + else { + return nil + } } public static func parse_inputQuickReplyShortcutId(_ reader: BufferReader) -> InputQuickReplyShortcut? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputQuickReplyShortcut.inputQuickReplyShortcutId(shortcutId: _1!) + if _c1 { + return Api.InputQuickReplyShortcut.inputQuickReplyShortcutId(Cons_inputQuickReplyShortcutId(shortcutId: _1!)) + } + else { + return nil + } } - } } public extension Api { indirect enum InputReplyTo: TypeConstructorDescription { - case inputReplyToMessage(flags: Int32, replyToMsgId: Int32, topMsgId: Int32?, replyToPeerId: Api.InputPeer?, quoteText: String?, quoteEntities: [Api.MessageEntity]?, quoteOffset: Int32?, monoforumPeerId: Api.InputPeer?, todoItemId: Int32?) - case inputReplyToMonoForum(monoforumPeerId: Api.InputPeer) - case inputReplyToStory(peer: Api.InputPeer, storyId: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputReplyToMessage(let flags, let replyToMsgId, let topMsgId, let replyToPeerId, let quoteText, let quoteEntities, let quoteOffset, let monoforumPeerId, let todoItemId): - if boxed { - buffer.appendInt32(-2036351472) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(replyToMsgId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {replyToPeerId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(quoteText!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(quoteEntities!.count)) - for item in quoteEntities! { + public class Cons_inputReplyToMessage { + public var flags: Int32 + public var replyToMsgId: Int32 + public var topMsgId: Int32? + public var replyToPeerId: Api.InputPeer? + public var quoteText: String? + public var quoteEntities: [Api.MessageEntity]? + public var quoteOffset: Int32? + public var monoforumPeerId: Api.InputPeer? + public var todoItemId: Int32? + public init(flags: Int32, replyToMsgId: Int32, topMsgId: Int32?, replyToPeerId: Api.InputPeer?, quoteText: String?, quoteEntities: [Api.MessageEntity]?, quoteOffset: Int32?, monoforumPeerId: Api.InputPeer?, todoItemId: Int32?) { + self.flags = flags + self.replyToMsgId = replyToMsgId + self.topMsgId = topMsgId + self.replyToPeerId = replyToPeerId + self.quoteText = quoteText + self.quoteEntities = quoteEntities + self.quoteOffset = quoteOffset + self.monoforumPeerId = monoforumPeerId + self.todoItemId = todoItemId + } + } + public class Cons_inputReplyToMonoForum { + public var monoforumPeerId: Api.InputPeer + public init(monoforumPeerId: Api.InputPeer) { + self.monoforumPeerId = monoforumPeerId + } + } + public class Cons_inputReplyToStory { + public var peer: Api.InputPeer + public var storyId: Int32 + public init(peer: Api.InputPeer, storyId: Int32) { + self.peer = peer + self.storyId = storyId + } + } + case inputReplyToMessage(Cons_inputReplyToMessage) + case inputReplyToMonoForum(Cons_inputReplyToMonoForum) + case inputReplyToStory(Cons_inputReplyToStory) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputReplyToMessage(let _data): + if boxed { + buffer.appendInt32(-2036351472) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.replyToMsgId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.topMsgId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.replyToPeerId!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.quoteText!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.quoteEntities!.count)) + for item in _data.quoteEntities! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(quoteOffset!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {monoforumPeerId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 6) != 0 {serializeInt32(todoItemId!, buffer: buffer, boxed: false)} - break - case .inputReplyToMonoForum(let monoforumPeerId): - if boxed { - buffer.appendInt32(1775660101) } - monoforumPeerId.serialize(buffer, true) - break - case .inputReplyToStory(let peer, let storyId): - if boxed { - buffer.appendInt32(1484862010) - } - peer.serialize(buffer, true) - serializeInt32(storyId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputReplyToMessage(let flags, let replyToMsgId, let topMsgId, let replyToPeerId, let quoteText, let quoteEntities, let quoteOffset, let monoforumPeerId, let todoItemId): - return ("inputReplyToMessage", [("flags", flags as Any), ("replyToMsgId", replyToMsgId as Any), ("topMsgId", topMsgId as Any), ("replyToPeerId", replyToPeerId as Any), ("quoteText", quoteText as Any), ("quoteEntities", quoteEntities as Any), ("quoteOffset", quoteOffset as Any), ("monoforumPeerId", monoforumPeerId as Any), ("todoItemId", todoItemId as Any)]) - case .inputReplyToMonoForum(let monoforumPeerId): - return ("inputReplyToMonoForum", [("monoforumPeerId", monoforumPeerId as Any)]) - case .inputReplyToStory(let peer, let storyId): - return ("inputReplyToStory", [("peer", peer as Any), ("storyId", storyId as Any)]) - } - } - + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.quoteOffset!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + _data.monoforumPeerId!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + serializeInt32(_data.todoItemId!, buffer: buffer, boxed: false) + } + break + case .inputReplyToMonoForum(let _data): + if boxed { + buffer.appendInt32(1775660101) + } + _data.monoforumPeerId.serialize(buffer, true) + break + case .inputReplyToStory(let _data): + if boxed { + buffer.appendInt32(1484862010) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.storyId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputReplyToMessage(let _data): + return ("inputReplyToMessage", [("flags", _data.flags as Any), ("replyToMsgId", _data.replyToMsgId as Any), ("topMsgId", _data.topMsgId as Any), ("replyToPeerId", _data.replyToPeerId as Any), ("quoteText", _data.quoteText as Any), ("quoteEntities", _data.quoteEntities as Any), ("quoteOffset", _data.quoteOffset as Any), ("monoforumPeerId", _data.monoforumPeerId as Any), ("todoItemId", _data.todoItemId as Any)]) + case .inputReplyToMonoForum(let _data): + return ("inputReplyToMonoForum", [("monoforumPeerId", _data.monoforumPeerId as Any)]) + case .inputReplyToStory(let _data): + return ("inputReplyToStory", [("peer", _data.peer as Any), ("storyId", _data.storyId as Any)]) + } + } + public static func parse_inputReplyToMessage(_ reader: BufferReader) -> InputReplyTo? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? _2 = reader.readInt32() var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } var _4: Api.InputPeer? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.InputPeer - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.InputPeer + } + } var _5: String? - if Int(_1!) & Int(1 << 2) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _5 = parseString(reader) + } var _6: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 3) != 0 {if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } var _7: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_7 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _7 = reader.readInt32() + } var _8: Api.InputPeer? - if Int(_1!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.InputPeer - } } + if Int(_1!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.InputPeer + } + } var _9: Int32? - if Int(_1!) & Int(1 << 6) != 0 {_9 = reader.readInt32() } + if Int(_1!) & Int(1 << 6) != 0 { + _9 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil @@ -133,16 +216,12 @@ public extension Api { let _c7 = (Int(_1!) & Int(1 << 4) == 0) || _7 != nil let _c8 = (Int(_1!) & Int(1 << 5) == 0) || _8 != nil let _c9 = (Int(_1!) & Int(1 << 6) == 0) || _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.InputReplyTo.inputReplyToMessage(flags: _1!, replyToMsgId: _2!, topMsgId: _3, replyToPeerId: _4, quoteText: _5, quoteEntities: _6, quoteOffset: _7, monoforumPeerId: _8, todoItemId: _9) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.InputReplyTo.inputReplyToMessage(Cons_inputReplyToMessage(flags: _1!, replyToMsgId: _2!, topMsgId: _3, replyToPeerId: _4, quoteText: _5, quoteEntities: _6, quoteOffset: _7, monoforumPeerId: _8, todoItemId: _9)) + } + else { + return nil + } } public static func parse_inputReplyToMonoForum(_ reader: BufferReader) -> InputReplyTo? { var _1: Api.InputPeer? @@ -150,8 +229,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.InputPeer } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputReplyTo.inputReplyToMonoForum(monoforumPeerId: _1!) + if _c1 { + return Api.InputReplyTo.inputReplyToMonoForum(Cons_inputReplyToMonoForum(monoforumPeerId: _1!)) + } + else { + return nil + } } public static func parse_inputReplyToStory(_ reader: BufferReader) -> InputReplyTo? { var _1: Api.InputPeer? @@ -162,54 +245,76 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputReplyTo.inputReplyToStory(peer: _1!, storyId: _2!) + if _c1 && _c2 { + return Api.InputReplyTo.inputReplyToStory(Cons_inputReplyToStory(peer: _1!, storyId: _2!)) + } + else { + return nil + } } - } } public extension Api { indirect enum InputSavedStarGift: TypeConstructorDescription { - case inputSavedStarGiftChat(peer: Api.InputPeer, savedId: Int64) - case inputSavedStarGiftSlug(slug: String) - case inputSavedStarGiftUser(msgId: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputSavedStarGiftChat(let peer, let savedId): - if boxed { - buffer.appendInt32(-251549057) - } - peer.serialize(buffer, true) - serializeInt64(savedId, buffer: buffer, boxed: false) - break - case .inputSavedStarGiftSlug(let slug): - if boxed { - buffer.appendInt32(545636920) - } - serializeString(slug, buffer: buffer, boxed: false) - break - case .inputSavedStarGiftUser(let msgId): - if boxed { - buffer.appendInt32(1764202389) - } - serializeInt32(msgId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputSavedStarGiftChat(let peer, let savedId): - return ("inputSavedStarGiftChat", [("peer", peer as Any), ("savedId", savedId as Any)]) - case .inputSavedStarGiftSlug(let slug): - return ("inputSavedStarGiftSlug", [("slug", slug as Any)]) - case .inputSavedStarGiftUser(let msgId): - return ("inputSavedStarGiftUser", [("msgId", msgId as Any)]) - } - } - + public class Cons_inputSavedStarGiftChat { + public var peer: Api.InputPeer + public var savedId: Int64 + public init(peer: Api.InputPeer, savedId: Int64) { + self.peer = peer + self.savedId = savedId + } + } + public class Cons_inputSavedStarGiftSlug { + public var slug: String + public init(slug: String) { + self.slug = slug + } + } + public class Cons_inputSavedStarGiftUser { + public var msgId: Int32 + public init(msgId: Int32) { + self.msgId = msgId + } + } + case inputSavedStarGiftChat(Cons_inputSavedStarGiftChat) + case inputSavedStarGiftSlug(Cons_inputSavedStarGiftSlug) + case inputSavedStarGiftUser(Cons_inputSavedStarGiftUser) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputSavedStarGiftChat(let _data): + if boxed { + buffer.appendInt32(-251549057) + } + _data.peer.serialize(buffer, true) + serializeInt64(_data.savedId, buffer: buffer, boxed: false) + break + case .inputSavedStarGiftSlug(let _data): + if boxed { + buffer.appendInt32(545636920) + } + serializeString(_data.slug, buffer: buffer, boxed: false) + break + case .inputSavedStarGiftUser(let _data): + if boxed { + buffer.appendInt32(1764202389) + } + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputSavedStarGiftChat(let _data): + return ("inputSavedStarGiftChat", [("peer", _data.peer as Any), ("savedId", _data.savedId as Any)]) + case .inputSavedStarGiftSlug(let _data): + return ("inputSavedStarGiftSlug", [("slug", _data.slug as Any)]) + case .inputSavedStarGiftUser(let _data): + return ("inputSavedStarGiftUser", [("msgId", _data.msgId as Any)]) + } + } + public static func parse_inputSavedStarGiftChat(_ reader: BufferReader) -> InputSavedStarGift? { var _1: Api.InputPeer? if let signature = reader.readInt32() { @@ -219,63 +324,95 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputSavedStarGift.inputSavedStarGiftChat(peer: _1!, savedId: _2!) + if _c1 && _c2 { + return Api.InputSavedStarGift.inputSavedStarGiftChat(Cons_inputSavedStarGiftChat(peer: _1!, savedId: _2!)) + } + else { + return nil + } } public static func parse_inputSavedStarGiftSlug(_ reader: BufferReader) -> InputSavedStarGift? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputSavedStarGift.inputSavedStarGiftSlug(slug: _1!) + if _c1 { + return Api.InputSavedStarGift.inputSavedStarGiftSlug(Cons_inputSavedStarGiftSlug(slug: _1!)) + } + else { + return nil + } } public static func parse_inputSavedStarGiftUser(_ reader: BufferReader) -> InputSavedStarGift? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputSavedStarGift.inputSavedStarGiftUser(msgId: _1!) + if _c1 { + return Api.InputSavedStarGift.inputSavedStarGiftUser(Cons_inputSavedStarGiftUser(msgId: _1!)) + } + else { + return nil + } } - } } public extension Api { enum InputSecureFile: TypeConstructorDescription { - case inputSecureFile(id: Int64, accessHash: Int64) - case inputSecureFileUploaded(id: Int64, parts: Int32, md5Checksum: String, fileHash: Buffer, secret: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputSecureFile(let id, let accessHash): - if boxed { - buffer.appendInt32(1399317950) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - case .inputSecureFileUploaded(let id, let parts, let md5Checksum, let fileHash, let secret): - if boxed { - buffer.appendInt32(859091184) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt32(parts, buffer: buffer, boxed: false) - serializeString(md5Checksum, buffer: buffer, boxed: false) - serializeBytes(fileHash, buffer: buffer, boxed: false) - serializeBytes(secret, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputSecureFile(let id, let accessHash): - return ("inputSecureFile", [("id", id as Any), ("accessHash", accessHash as Any)]) - case .inputSecureFileUploaded(let id, let parts, let md5Checksum, let fileHash, let secret): - return ("inputSecureFileUploaded", [("id", id as Any), ("parts", parts as Any), ("md5Checksum", md5Checksum as Any), ("fileHash", fileHash as Any), ("secret", secret as Any)]) - } - } - + public class Cons_inputSecureFile { + public var id: Int64 + public var accessHash: Int64 + public init(id: Int64, accessHash: Int64) { + self.id = id + self.accessHash = accessHash + } + } + public class Cons_inputSecureFileUploaded { + public var id: Int64 + public var parts: Int32 + public var md5Checksum: String + public var fileHash: Buffer + public var secret: Buffer + public init(id: Int64, parts: Int32, md5Checksum: String, fileHash: Buffer, secret: Buffer) { + self.id = id + self.parts = parts + self.md5Checksum = md5Checksum + self.fileHash = fileHash + self.secret = secret + } + } + case inputSecureFile(Cons_inputSecureFile) + case inputSecureFileUploaded(Cons_inputSecureFileUploaded) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputSecureFile(let _data): + if boxed { + buffer.appendInt32(1399317950) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + case .inputSecureFileUploaded(let _data): + if boxed { + buffer.appendInt32(859091184) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.parts, buffer: buffer, boxed: false) + serializeString(_data.md5Checksum, buffer: buffer, boxed: false) + serializeBytes(_data.fileHash, buffer: buffer, boxed: false) + serializeBytes(_data.secret, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputSecureFile(let _data): + return ("inputSecureFile", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any)]) + case .inputSecureFileUploaded(let _data): + return ("inputSecureFileUploaded", [("id", _data.id as Any), ("parts", _data.parts as Any), ("md5Checksum", _data.md5Checksum as Any), ("fileHash", _data.fileHash as Any), ("secret", _data.secret as Any)]) + } + } + public static func parse_inputSecureFile(_ reader: BufferReader) -> InputSecureFile? { var _1: Int64? _1 = reader.readInt64() @@ -283,9 +420,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputSecureFile.inputSecureFile(id: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputSecureFile.inputSecureFile(Cons_inputSecureFile(id: _1!, accessHash: _2!)) + } + else { + return nil + } } public static func parse_inputSecureFileUploaded(_ reader: BufferReader) -> InputSecureFile? { var _1: Int64? @@ -303,54 +443,89 @@ public extension Api { let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.InputSecureFile.inputSecureFileUploaded(id: _1!, parts: _2!, md5Checksum: _3!, fileHash: _4!, secret: _5!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.InputSecureFile.inputSecureFileUploaded(Cons_inputSecureFileUploaded(id: _1!, parts: _2!, md5Checksum: _3!, fileHash: _4!, secret: _5!)) + } + else { + return nil + } } - } } public extension Api { enum InputSecureValue: TypeConstructorDescription { - case inputSecureValue(flags: Int32, type: Api.SecureValueType, data: Api.SecureData?, frontSide: Api.InputSecureFile?, reverseSide: Api.InputSecureFile?, selfie: Api.InputSecureFile?, translation: [Api.InputSecureFile]?, files: [Api.InputSecureFile]?, plainData: Api.SecurePlainData?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputSecureValue(let flags, let type, let data, let frontSide, let reverseSide, let selfie, let translation, let files, let plainData): - if boxed { - buffer.appendInt32(-618540889) + public class Cons_inputSecureValue { + public var flags: Int32 + public var type: Api.SecureValueType + public var data: Api.SecureData? + public var frontSide: Api.InputSecureFile? + public var reverseSide: Api.InputSecureFile? + public var selfie: Api.InputSecureFile? + public var translation: [Api.InputSecureFile]? + public var files: [Api.InputSecureFile]? + public var plainData: Api.SecurePlainData? + public init(flags: Int32, type: Api.SecureValueType, data: Api.SecureData?, frontSide: Api.InputSecureFile?, reverseSide: Api.InputSecureFile?, selfie: Api.InputSecureFile?, translation: [Api.InputSecureFile]?, files: [Api.InputSecureFile]?, plainData: Api.SecurePlainData?) { + self.flags = flags + self.type = type + self.data = data + self.frontSide = frontSide + self.reverseSide = reverseSide + self.selfie = selfie + self.translation = translation + self.files = files + self.plainData = plainData + } + } + case inputSecureValue(Cons_inputSecureValue) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputSecureValue(let _data): + if boxed { + buffer.appendInt32(-618540889) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.type.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.data!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.frontSide!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.reverseSide!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.selfie!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.translation!.count)) + for item in _data.translation! { + item.serialize(buffer, true) } - serializeInt32(flags, buffer: buffer, boxed: false) - type.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {data!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {frontSide!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {reverseSide!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {selfie!.serialize(buffer, true)} - if Int(flags) & Int(1 << 6) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(translation!.count)) - for item in translation! { + } + if Int(_data.flags) & Int(1 << 4) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.files!.count)) + for item in _data.files! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 4) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(files!.count)) - for item in files! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 5) != 0 {plainData!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputSecureValue(let flags, let type, let data, let frontSide, let reverseSide, let selfie, let translation, let files, let plainData): - return ("inputSecureValue", [("flags", flags as Any), ("type", type as Any), ("data", data as Any), ("frontSide", frontSide as Any), ("reverseSide", reverseSide as Any), ("selfie", selfie as Any), ("translation", translation as Any), ("files", files as Any), ("plainData", plainData as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 5) != 0 { + _data.plainData!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputSecureValue(let _data): + return ("inputSecureValue", [("flags", _data.flags as Any), ("type", _data.type as Any), ("data", _data.data as Any), ("frontSide", _data.frontSide as Any), ("reverseSide", _data.reverseSide as Any), ("selfie", _data.selfie as Any), ("translation", _data.translation as Any), ("files", _data.files as Any), ("plainData", _data.plainData as Any)]) + } + } + public static func parse_inputSecureValue(_ reader: BufferReader) -> InputSecureValue? { var _1: Int32? _1 = reader.readInt32() @@ -359,33 +534,47 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.SecureValueType } var _3: Api.SecureData? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.SecureData - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.SecureData + } + } var _4: Api.InputSecureFile? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.InputSecureFile - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.InputSecureFile + } + } var _5: Api.InputSecureFile? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.InputSecureFile - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.InputSecureFile + } + } var _6: Api.InputSecureFile? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.InputSecureFile - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.InputSecureFile + } + } var _7: [Api.InputSecureFile]? - if Int(_1!) & Int(1 << 6) != 0 {if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputSecureFile.self) - } } + if Int(_1!) & Int(1 << 6) != 0 { + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputSecureFile.self) + } + } var _8: [Api.InputSecureFile]? - if Int(_1!) & Int(1 << 4) != 0 {if let _ = reader.readInt32() { - _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputSecureFile.self) - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let _ = reader.readInt32() { + _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputSecureFile.self) + } + } var _9: Api.SecurePlainData? - if Int(_1!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.SecurePlainData - } } + if Int(_1!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.SecurePlainData + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil @@ -395,50 +584,61 @@ public extension Api { let _c7 = (Int(_1!) & Int(1 << 6) == 0) || _7 != nil let _c8 = (Int(_1!) & Int(1 << 4) == 0) || _8 != nil let _c9 = (Int(_1!) & Int(1 << 5) == 0) || _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.InputSecureValue.inputSecureValue(flags: _1!, type: _2!, data: _3, frontSide: _4, reverseSide: _5, selfie: _6, translation: _7, files: _8, plainData: _9) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.InputSecureValue.inputSecureValue(Cons_inputSecureValue(flags: _1!, type: _2!, data: _3, frontSide: _4, reverseSide: _5, selfie: _6, translation: _7, files: _8, plainData: _9)) + } + else { + return nil + } } - } } public extension Api { indirect enum InputSingleMedia: TypeConstructorDescription { - case inputSingleMedia(flags: Int32, media: Api.InputMedia, randomId: Int64, message: String, entities: [Api.MessageEntity]?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputSingleMedia(let flags, let media, let randomId, let message, let entities): - if boxed { - buffer.appendInt32(482797855) - } - serializeInt32(flags, buffer: buffer, boxed: false) - media.serialize(buffer, true) - serializeInt64(randomId, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { + public class Cons_inputSingleMedia { + public var flags: Int32 + public var media: Api.InputMedia + public var randomId: Int64 + public var message: String + public var entities: [Api.MessageEntity]? + public init(flags: Int32, media: Api.InputMedia, randomId: Int64, message: String, entities: [Api.MessageEntity]?) { + self.flags = flags + self.media = media + self.randomId = randomId + self.message = message + self.entities = entities + } + } + case inputSingleMedia(Cons_inputSingleMedia) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputSingleMedia(let _data): + if boxed { + buffer.appendInt32(482797855) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.media.serialize(buffer, true) + serializeInt64(_data.randomId, buffer: buffer, boxed: false) + serializeString(_data.message, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { item.serialize(buffer, true) - }} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputSingleMedia(let flags, let media, let randomId, let message, let entities): - return ("inputSingleMedia", [("flags", flags as Any), ("media", media as Any), ("randomId", randomId as Any), ("message", message as Any), ("entities", entities as Any)]) - } - } - + } + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputSingleMedia(let _data): + return ("inputSingleMedia", [("flags", _data.flags as Any), ("media", _data.media as Any), ("randomId", _data.randomId as Any), ("message", _data.message as Any), ("entities", _data.entities as Any)]) + } + } + public static func parse_inputSingleMedia(_ reader: BufferReader) -> InputSingleMedia? { var _1: Int32? _1 = reader.readInt32() @@ -451,95 +651,123 @@ public extension Api { var _4: String? _4 = parseString(reader) var _5: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.InputSingleMedia.inputSingleMedia(flags: _1!, media: _2!, randomId: _3!, message: _4!, entities: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.InputSingleMedia.inputSingleMedia(Cons_inputSingleMedia(flags: _1!, media: _2!, randomId: _3!, message: _4!, entities: _5)) + } + else { + return nil + } } - } } public extension Api { enum InputStarGiftAuction: TypeConstructorDescription { - case inputStarGiftAuction(giftId: Int64) - case inputStarGiftAuctionSlug(slug: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputStarGiftAuction(let giftId): - if boxed { - buffer.appendInt32(48327832) - } - serializeInt64(giftId, buffer: buffer, boxed: false) - break - case .inputStarGiftAuctionSlug(let slug): - if boxed { - buffer.appendInt32(2058715912) - } - serializeString(slug, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputStarGiftAuction(let giftId): - return ("inputStarGiftAuction", [("giftId", giftId as Any)]) - case .inputStarGiftAuctionSlug(let slug): - return ("inputStarGiftAuctionSlug", [("slug", slug as Any)]) - } - } - + public class Cons_inputStarGiftAuction { + public var giftId: Int64 + public init(giftId: Int64) { + self.giftId = giftId + } + } + public class Cons_inputStarGiftAuctionSlug { + public var slug: String + public init(slug: String) { + self.slug = slug + } + } + case inputStarGiftAuction(Cons_inputStarGiftAuction) + case inputStarGiftAuctionSlug(Cons_inputStarGiftAuctionSlug) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputStarGiftAuction(let _data): + if boxed { + buffer.appendInt32(48327832) + } + serializeInt64(_data.giftId, buffer: buffer, boxed: false) + break + case .inputStarGiftAuctionSlug(let _data): + if boxed { + buffer.appendInt32(2058715912) + } + serializeString(_data.slug, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputStarGiftAuction(let _data): + return ("inputStarGiftAuction", [("giftId", _data.giftId as Any)]) + case .inputStarGiftAuctionSlug(let _data): + return ("inputStarGiftAuctionSlug", [("slug", _data.slug as Any)]) + } + } + public static func parse_inputStarGiftAuction(_ reader: BufferReader) -> InputStarGiftAuction? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputStarGiftAuction.inputStarGiftAuction(giftId: _1!) + if _c1 { + return Api.InputStarGiftAuction.inputStarGiftAuction(Cons_inputStarGiftAuction(giftId: _1!)) + } + else { + return nil + } } public static func parse_inputStarGiftAuctionSlug(_ reader: BufferReader) -> InputStarGiftAuction? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputStarGiftAuction.inputStarGiftAuctionSlug(slug: _1!) + if _c1 { + return Api.InputStarGiftAuction.inputStarGiftAuctionSlug(Cons_inputStarGiftAuctionSlug(slug: _1!)) + } + else { + return nil + } } - } } public extension Api { enum InputStarsTransaction: TypeConstructorDescription { - case inputStarsTransaction(flags: Int32, id: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputStarsTransaction(let flags, let id): - if boxed { - buffer.appendInt32(543876817) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(id, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputStarsTransaction(let flags, let id): - return ("inputStarsTransaction", [("flags", flags as Any), ("id", id as Any)]) - } - } - + public class Cons_inputStarsTransaction { + public var flags: Int32 + public var id: String + public init(flags: Int32, id: String) { + self.flags = flags + self.id = id + } + } + case inputStarsTransaction(Cons_inputStarsTransaction) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputStarsTransaction(let _data): + if boxed { + buffer.appendInt32(543876817) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.id, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputStarsTransaction(let _data): + return ("inputStarsTransaction", [("flags", _data.flags as Any), ("id", _data.id as Any)]) + } + } + public static func parse_inputStarsTransaction(_ reader: BufferReader) -> InputStarsTransaction? { var _1: Int32? _1 = reader.readInt32() @@ -547,135 +775,148 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputStarsTransaction.inputStarsTransaction(flags: _1!, id: _2!) + if _c1 && _c2 { + return Api.InputStarsTransaction.inputStarsTransaction(Cons_inputStarsTransaction(flags: _1!, id: _2!)) + } + else { + return nil + } } - } } public extension Api { enum InputStickerSet: TypeConstructorDescription { + public class Cons_inputStickerSetDice { + public var emoticon: String + public init(emoticon: String) { + self.emoticon = emoticon + } + } + public class Cons_inputStickerSetID { + public var id: Int64 + public var accessHash: Int64 + public init(id: Int64, accessHash: Int64) { + self.id = id + self.accessHash = accessHash + } + } + public class Cons_inputStickerSetShortName { + public var shortName: String + public init(shortName: String) { + self.shortName = shortName + } + } case inputStickerSetAnimatedEmoji case inputStickerSetAnimatedEmojiAnimations - case inputStickerSetDice(emoticon: String) + case inputStickerSetDice(Cons_inputStickerSetDice) case inputStickerSetEmojiChannelDefaultStatuses case inputStickerSetEmojiDefaultStatuses case inputStickerSetEmojiDefaultTopicIcons case inputStickerSetEmojiGenericAnimations case inputStickerSetEmpty - case inputStickerSetID(id: Int64, accessHash: Int64) + case inputStickerSetID(Cons_inputStickerSetID) case inputStickerSetPremiumGifts - case inputStickerSetShortName(shortName: String) + case inputStickerSetShortName(Cons_inputStickerSetShortName) case inputStickerSetTonGifts - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputStickerSetAnimatedEmoji: - if boxed { - buffer.appendInt32(42402760) - } - - break - case .inputStickerSetAnimatedEmojiAnimations: - if boxed { - buffer.appendInt32(215889721) - } - - break - case .inputStickerSetDice(let emoticon): - if boxed { - buffer.appendInt32(-427863538) - } - serializeString(emoticon, buffer: buffer, boxed: false) - break - case .inputStickerSetEmojiChannelDefaultStatuses: - if boxed { - buffer.appendInt32(1232373075) - } - - break - case .inputStickerSetEmojiDefaultStatuses: - if boxed { - buffer.appendInt32(701560302) - } - - break - case .inputStickerSetEmojiDefaultTopicIcons: - if boxed { - buffer.appendInt32(1153562857) - } - - break - case .inputStickerSetEmojiGenericAnimations: - if boxed { - buffer.appendInt32(80008398) - } - - break - case .inputStickerSetEmpty: - if boxed { - buffer.appendInt32(-4838507) - } - - break - case .inputStickerSetID(let id, let accessHash): - if boxed { - buffer.appendInt32(-1645763991) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - case .inputStickerSetPremiumGifts: - if boxed { - buffer.appendInt32(-930399486) - } - - break - case .inputStickerSetShortName(let shortName): - if boxed { - buffer.appendInt32(-2044933984) - } - serializeString(shortName, buffer: buffer, boxed: false) - break - case .inputStickerSetTonGifts: - if boxed { - buffer.appendInt32(485912992) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputStickerSetAnimatedEmoji: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputStickerSetAnimatedEmoji: + if boxed { + buffer.appendInt32(42402760) + } + break + case .inputStickerSetAnimatedEmojiAnimations: + if boxed { + buffer.appendInt32(215889721) + } + break + case .inputStickerSetDice(let _data): + if boxed { + buffer.appendInt32(-427863538) + } + serializeString(_data.emoticon, buffer: buffer, boxed: false) + break + case .inputStickerSetEmojiChannelDefaultStatuses: + if boxed { + buffer.appendInt32(1232373075) + } + break + case .inputStickerSetEmojiDefaultStatuses: + if boxed { + buffer.appendInt32(701560302) + } + break + case .inputStickerSetEmojiDefaultTopicIcons: + if boxed { + buffer.appendInt32(1153562857) + } + break + case .inputStickerSetEmojiGenericAnimations: + if boxed { + buffer.appendInt32(80008398) + } + break + case .inputStickerSetEmpty: + if boxed { + buffer.appendInt32(-4838507) + } + break + case .inputStickerSetID(let _data): + if boxed { + buffer.appendInt32(-1645763991) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + case .inputStickerSetPremiumGifts: + if boxed { + buffer.appendInt32(-930399486) + } + break + case .inputStickerSetShortName(let _data): + if boxed { + buffer.appendInt32(-2044933984) + } + serializeString(_data.shortName, buffer: buffer, boxed: false) + break + case .inputStickerSetTonGifts: + if boxed { + buffer.appendInt32(485912992) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputStickerSetAnimatedEmoji: return ("inputStickerSetAnimatedEmoji", []) - case .inputStickerSetAnimatedEmojiAnimations: + case .inputStickerSetAnimatedEmojiAnimations: return ("inputStickerSetAnimatedEmojiAnimations", []) - case .inputStickerSetDice(let emoticon): - return ("inputStickerSetDice", [("emoticon", emoticon as Any)]) - case .inputStickerSetEmojiChannelDefaultStatuses: + case .inputStickerSetDice(let _data): + return ("inputStickerSetDice", [("emoticon", _data.emoticon as Any)]) + case .inputStickerSetEmojiChannelDefaultStatuses: return ("inputStickerSetEmojiChannelDefaultStatuses", []) - case .inputStickerSetEmojiDefaultStatuses: + case .inputStickerSetEmojiDefaultStatuses: return ("inputStickerSetEmojiDefaultStatuses", []) - case .inputStickerSetEmojiDefaultTopicIcons: + case .inputStickerSetEmojiDefaultTopicIcons: return ("inputStickerSetEmojiDefaultTopicIcons", []) - case .inputStickerSetEmojiGenericAnimations: + case .inputStickerSetEmojiGenericAnimations: return ("inputStickerSetEmojiGenericAnimations", []) - case .inputStickerSetEmpty: + case .inputStickerSetEmpty: return ("inputStickerSetEmpty", []) - case .inputStickerSetID(let id, let accessHash): - return ("inputStickerSetID", [("id", id as Any), ("accessHash", accessHash as Any)]) - case .inputStickerSetPremiumGifts: + case .inputStickerSetID(let _data): + return ("inputStickerSetID", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any)]) + case .inputStickerSetPremiumGifts: return ("inputStickerSetPremiumGifts", []) - case .inputStickerSetShortName(let shortName): - return ("inputStickerSetShortName", [("shortName", shortName as Any)]) - case .inputStickerSetTonGifts: + case .inputStickerSetShortName(let _data): + return ("inputStickerSetShortName", [("shortName", _data.shortName as Any)]) + case .inputStickerSetTonGifts: return ("inputStickerSetTonGifts", []) - } - } - + } + } + public static func parse_inputStickerSetAnimatedEmoji(_ reader: BufferReader) -> InputStickerSet? { return Api.InputStickerSet.inputStickerSetAnimatedEmoji } @@ -686,8 +927,12 @@ public extension Api { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputStickerSet.inputStickerSetDice(emoticon: _1!) + if _c1 { + return Api.InputStickerSet.inputStickerSetDice(Cons_inputStickerSetDice(emoticon: _1!)) + } + else { + return nil + } } public static func parse_inputStickerSetEmojiChannelDefaultStatuses(_ reader: BufferReader) -> InputStickerSet? { return Api.InputStickerSet.inputStickerSetEmojiChannelDefaultStatuses @@ -711,9 +956,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputStickerSet.inputStickerSetID(id: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputStickerSet.inputStickerSetID(Cons_inputStickerSetID(id: _1!, accessHash: _2!)) + } + else { + return nil + } } public static func parse_inputStickerSetPremiumGifts(_ reader: BufferReader) -> InputStickerSet? { return Api.InputStickerSet.inputStickerSetPremiumGifts @@ -722,41 +970,62 @@ public extension Api { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputStickerSet.inputStickerSetShortName(shortName: _1!) + if _c1 { + return Api.InputStickerSet.inputStickerSetShortName(Cons_inputStickerSetShortName(shortName: _1!)) + } + else { + return nil + } } public static func parse_inputStickerSetTonGifts(_ reader: BufferReader) -> InputStickerSet? { return Api.InputStickerSet.inputStickerSetTonGifts } - } } public extension Api { enum InputStickerSetItem: TypeConstructorDescription { - case inputStickerSetItem(flags: Int32, document: Api.InputDocument, emoji: String, maskCoords: Api.MaskCoords?, keywords: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputStickerSetItem(let flags, let document, let emoji, let maskCoords, let keywords): - if boxed { - buffer.appendInt32(853188252) - } - serializeInt32(flags, buffer: buffer, boxed: false) - document.serialize(buffer, true) - serializeString(emoji, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {maskCoords!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(keywords!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputStickerSetItem(let flags, let document, let emoji, let maskCoords, let keywords): - return ("inputStickerSetItem", [("flags", flags as Any), ("document", document as Any), ("emoji", emoji as Any), ("maskCoords", maskCoords as Any), ("keywords", keywords as Any)]) - } - } - + public class Cons_inputStickerSetItem { + public var flags: Int32 + public var document: Api.InputDocument + public var emoji: String + public var maskCoords: Api.MaskCoords? + public var keywords: String? + public init(flags: Int32, document: Api.InputDocument, emoji: String, maskCoords: Api.MaskCoords?, keywords: String?) { + self.flags = flags + self.document = document + self.emoji = emoji + self.maskCoords = maskCoords + self.keywords = keywords + } + } + case inputStickerSetItem(Cons_inputStickerSetItem) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputStickerSetItem(let _data): + if boxed { + buffer.appendInt32(853188252) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.document.serialize(buffer, true) + serializeString(_data.emoji, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.maskCoords!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.keywords!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputStickerSetItem(let _data): + return ("inputStickerSetItem", [("flags", _data.flags as Any), ("document", _data.document as Any), ("emoji", _data.emoji as Any), ("maskCoords", _data.maskCoords as Any), ("keywords", _data.keywords as Any)]) + } + } + public static func parse_inputStickerSetItem(_ reader: BufferReader) -> InputStickerSetItem? { var _1: Int32? _1 = reader.readInt32() @@ -767,65 +1036,84 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: Api.MaskCoords? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.MaskCoords - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.MaskCoords + } + } var _5: String? - if Int(_1!) & Int(1 << 1) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _5 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.InputStickerSetItem.inputStickerSetItem(flags: _1!, document: _2!, emoji: _3!, maskCoords: _4, keywords: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.InputStickerSetItem.inputStickerSetItem(Cons_inputStickerSetItem(flags: _1!, document: _2!, emoji: _3!, maskCoords: _4, keywords: _5)) + } + else { + return nil + } } - } } public extension Api { enum InputStickeredMedia: TypeConstructorDescription { - case inputStickeredMediaDocument(id: Api.InputDocument) - case inputStickeredMediaPhoto(id: Api.InputPhoto) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputStickeredMediaDocument(let id): - if boxed { - buffer.appendInt32(70813275) - } - id.serialize(buffer, true) - break - case .inputStickeredMediaPhoto(let id): - if boxed { - buffer.appendInt32(1251549527) - } - id.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputStickeredMediaDocument(let id): - return ("inputStickeredMediaDocument", [("id", id as Any)]) - case .inputStickeredMediaPhoto(let id): - return ("inputStickeredMediaPhoto", [("id", id as Any)]) - } - } - + public class Cons_inputStickeredMediaDocument { + public var id: Api.InputDocument + public init(id: Api.InputDocument) { + self.id = id + } + } + public class Cons_inputStickeredMediaPhoto { + public var id: Api.InputPhoto + public init(id: Api.InputPhoto) { + self.id = id + } + } + case inputStickeredMediaDocument(Cons_inputStickeredMediaDocument) + case inputStickeredMediaPhoto(Cons_inputStickeredMediaPhoto) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputStickeredMediaDocument(let _data): + if boxed { + buffer.appendInt32(70813275) + } + _data.id.serialize(buffer, true) + break + case .inputStickeredMediaPhoto(let _data): + if boxed { + buffer.appendInt32(1251549527) + } + _data.id.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputStickeredMediaDocument(let _data): + return ("inputStickeredMediaDocument", [("id", _data.id as Any)]) + case .inputStickeredMediaPhoto(let _data): + return ("inputStickeredMediaPhoto", [("id", _data.id as Any)]) + } + } + public static func parse_inputStickeredMediaDocument(_ reader: BufferReader) -> InputStickeredMedia? { var _1: Api.InputDocument? if let signature = reader.readInt32() { _1 = Api.parse(reader, signature: signature) as? Api.InputDocument } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputStickeredMedia.inputStickeredMediaDocument(id: _1!) + if _c1 { + return Api.InputStickeredMedia.inputStickeredMediaDocument(Cons_inputStickeredMediaDocument(id: _1!)) + } + else { + return nil + } } public static func parse_inputStickeredMediaPhoto(_ reader: BufferReader) -> InputStickeredMedia? { var _1: Api.InputPhoto? @@ -833,153 +1121,294 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.InputPhoto } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputStickeredMedia.inputStickeredMediaPhoto(id: _1!) + if _c1 { + return Api.InputStickeredMedia.inputStickeredMediaPhoto(Cons_inputStickeredMediaPhoto(id: _1!)) + } + else { + return nil + } } - } } public extension Api { indirect enum InputStorePaymentPurpose: TypeConstructorDescription { - case inputStorePaymentAuthCode(flags: Int32, phoneNumber: String, phoneCodeHash: String, currency: String, amount: Int64) - case inputStorePaymentGiftPremium(userId: Api.InputUser, currency: String, amount: Int64) - case inputStorePaymentPremiumGiftCode(flags: Int32, users: [Api.InputUser], boostPeer: Api.InputPeer?, currency: String, amount: Int64, message: Api.TextWithEntities?) - case inputStorePaymentPremiumGiveaway(flags: Int32, boostPeer: Api.InputPeer, additionalPeers: [Api.InputPeer]?, countriesIso2: [String]?, prizeDescription: String?, randomId: Int64, untilDate: Int32, currency: String, amount: Int64) - case inputStorePaymentPremiumSubscription(flags: Int32) - case inputStorePaymentStarsGift(userId: Api.InputUser, stars: Int64, currency: String, amount: Int64) - case inputStorePaymentStarsGiveaway(flags: Int32, stars: Int64, boostPeer: Api.InputPeer, additionalPeers: [Api.InputPeer]?, countriesIso2: [String]?, prizeDescription: String?, randomId: Int64, untilDate: Int32, currency: String, amount: Int64, users: Int32) - case inputStorePaymentStarsTopup(flags: Int32, stars: Int64, currency: String, amount: Int64, spendPurposePeer: Api.InputPeer?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputStorePaymentAuthCode(let flags, let phoneNumber, let phoneCodeHash, let currency, let amount): - if boxed { - buffer.appendInt32(-1682807955) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(phoneCodeHash, buffer: buffer, boxed: false) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - break - case .inputStorePaymentGiftPremium(let userId, let currency, let amount): - if boxed { - buffer.appendInt32(1634697192) - } - userId.serialize(buffer, true) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - break - case .inputStorePaymentPremiumGiftCode(let flags, let users, let boostPeer, let currency, let amount, let message): - if boxed { - buffer.appendInt32(-75955309) - } - serializeInt32(flags, buffer: buffer, boxed: false) + public class Cons_inputStorePaymentAuthCode { + public var flags: Int32 + public var phoneNumber: String + public var phoneCodeHash: String + public var currency: String + public var amount: Int64 + public init(flags: Int32, phoneNumber: String, phoneCodeHash: String, currency: String, amount: Int64) { + self.flags = flags + self.phoneNumber = phoneNumber + self.phoneCodeHash = phoneCodeHash + self.currency = currency + self.amount = amount + } + } + public class Cons_inputStorePaymentGiftPremium { + public var userId: Api.InputUser + public var currency: String + public var amount: Int64 + public init(userId: Api.InputUser, currency: String, amount: Int64) { + self.userId = userId + self.currency = currency + self.amount = amount + } + } + public class Cons_inputStorePaymentPremiumGiftCode { + public var flags: Int32 + public var users: [Api.InputUser] + public var boostPeer: Api.InputPeer? + public var currency: String + public var amount: Int64 + public var message: Api.TextWithEntities? + public init(flags: Int32, users: [Api.InputUser], boostPeer: Api.InputPeer?, currency: String, amount: Int64, message: Api.TextWithEntities?) { + self.flags = flags + self.users = users + self.boostPeer = boostPeer + self.currency = currency + self.amount = amount + self.message = message + } + } + public class Cons_inputStorePaymentPremiumGiveaway { + public var flags: Int32 + public var boostPeer: Api.InputPeer + public var additionalPeers: [Api.InputPeer]? + public var countriesIso2: [String]? + public var prizeDescription: String? + public var randomId: Int64 + public var untilDate: Int32 + public var currency: String + public var amount: Int64 + public init(flags: Int32, boostPeer: Api.InputPeer, additionalPeers: [Api.InputPeer]?, countriesIso2: [String]?, prizeDescription: String?, randomId: Int64, untilDate: Int32, currency: String, amount: Int64) { + self.flags = flags + self.boostPeer = boostPeer + self.additionalPeers = additionalPeers + self.countriesIso2 = countriesIso2 + self.prizeDescription = prizeDescription + self.randomId = randomId + self.untilDate = untilDate + self.currency = currency + self.amount = amount + } + } + public class Cons_inputStorePaymentPremiumSubscription { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } + public class Cons_inputStorePaymentStarsGift { + public var userId: Api.InputUser + public var stars: Int64 + public var currency: String + public var amount: Int64 + public init(userId: Api.InputUser, stars: Int64, currency: String, amount: Int64) { + self.userId = userId + self.stars = stars + self.currency = currency + self.amount = amount + } + } + public class Cons_inputStorePaymentStarsGiveaway { + public var flags: Int32 + public var stars: Int64 + public var boostPeer: Api.InputPeer + public var additionalPeers: [Api.InputPeer]? + public var countriesIso2: [String]? + public var prizeDescription: String? + public var randomId: Int64 + public var untilDate: Int32 + public var currency: String + public var amount: Int64 + public var users: Int32 + public init(flags: Int32, stars: Int64, boostPeer: Api.InputPeer, additionalPeers: [Api.InputPeer]?, countriesIso2: [String]?, prizeDescription: String?, randomId: Int64, untilDate: Int32, currency: String, amount: Int64, users: Int32) { + self.flags = flags + self.stars = stars + self.boostPeer = boostPeer + self.additionalPeers = additionalPeers + self.countriesIso2 = countriesIso2 + self.prizeDescription = prizeDescription + self.randomId = randomId + self.untilDate = untilDate + self.currency = currency + self.amount = amount + self.users = users + } + } + public class Cons_inputStorePaymentStarsTopup { + public var flags: Int32 + public var stars: Int64 + public var currency: String + public var amount: Int64 + public var spendPurposePeer: Api.InputPeer? + public init(flags: Int32, stars: Int64, currency: String, amount: Int64, spendPurposePeer: Api.InputPeer?) { + self.flags = flags + self.stars = stars + self.currency = currency + self.amount = amount + self.spendPurposePeer = spendPurposePeer + } + } + case inputStorePaymentAuthCode(Cons_inputStorePaymentAuthCode) + case inputStorePaymentGiftPremium(Cons_inputStorePaymentGiftPremium) + case inputStorePaymentPremiumGiftCode(Cons_inputStorePaymentPremiumGiftCode) + case inputStorePaymentPremiumGiveaway(Cons_inputStorePaymentPremiumGiveaway) + case inputStorePaymentPremiumSubscription(Cons_inputStorePaymentPremiumSubscription) + case inputStorePaymentStarsGift(Cons_inputStorePaymentStarsGift) + case inputStorePaymentStarsGiveaway(Cons_inputStorePaymentStarsGiveaway) + case inputStorePaymentStarsTopup(Cons_inputStorePaymentStarsTopup) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputStorePaymentAuthCode(let _data): + if boxed { + buffer.appendInt32(-1682807955) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.phoneNumber, buffer: buffer, boxed: false) + serializeString(_data.phoneCodeHash, buffer: buffer, boxed: false) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + break + case .inputStorePaymentGiftPremium(let _data): + if boxed { + buffer.appendInt32(1634697192) + } + _data.userId.serialize(buffer, true) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + break + case .inputStorePaymentPremiumGiftCode(let _data): + if boxed { + buffer.appendInt32(-75955309) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.boostPeer!.serialize(buffer, true) + } + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.message!.serialize(buffer, true) + } + break + case .inputStorePaymentPremiumGiveaway(let _data): + if boxed { + buffer.appendInt32(369444042) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.boostPeer.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 1) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { + buffer.appendInt32(Int32(_data.additionalPeers!.count)) + for item in _data.additionalPeers! { item.serialize(buffer, true) } - if Int(flags) & Int(1 << 0) != 0 {boostPeer!.serialize(buffer, true)} - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {message!.serialize(buffer, true)} - break - case .inputStorePaymentPremiumGiveaway(let flags, let boostPeer, let additionalPeers, let countriesIso2, let prizeDescription, let randomId, let untilDate, let currency, let amount): - if boxed { - buffer.appendInt32(369444042) - } - serializeInt32(flags, buffer: buffer, boxed: false) - boostPeer.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(additionalPeers!.count)) - for item in additionalPeers! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 2) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(countriesIso2!.count)) - for item in countriesIso2! { + } + if Int(_data.flags) & Int(1 << 2) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.countriesIso2!.count)) + for item in _data.countriesIso2! { serializeString(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 4) != 0 {serializeString(prizeDescription!, buffer: buffer, boxed: false)} - serializeInt64(randomId, buffer: buffer, boxed: false) - serializeInt32(untilDate, buffer: buffer, boxed: false) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - break - case .inputStorePaymentPremiumSubscription(let flags): - if boxed { - buffer.appendInt32(-1502273946) } - serializeInt32(flags, buffer: buffer, boxed: false) - break - case .inputStorePaymentStarsGift(let userId, let stars, let currency, let amount): - if boxed { - buffer.appendInt32(494149367) - } - userId.serialize(buffer, true) - serializeInt64(stars, buffer: buffer, boxed: false) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - break - case .inputStorePaymentStarsGiveaway(let flags, let stars, let boostPeer, let additionalPeers, let countriesIso2, let prizeDescription, let randomId, let untilDate, let currency, let amount, let users): - if boxed { - buffer.appendInt32(1964968186) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(stars, buffer: buffer, boxed: false) - boostPeer.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(additionalPeers!.count)) - for item in additionalPeers! { + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeString(_data.prizeDescription!, buffer: buffer, boxed: false) + } + serializeInt64(_data.randomId, buffer: buffer, boxed: false) + serializeInt32(_data.untilDate, buffer: buffer, boxed: false) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + break + case .inputStorePaymentPremiumSubscription(let _data): + if boxed { + buffer.appendInt32(-1502273946) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + case .inputStorePaymentStarsGift(let _data): + if boxed { + buffer.appendInt32(494149367) + } + _data.userId.serialize(buffer, true) + serializeInt64(_data.stars, buffer: buffer, boxed: false) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + break + case .inputStorePaymentStarsGiveaway(let _data): + if boxed { + buffer.appendInt32(1964968186) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.stars, buffer: buffer, boxed: false) + _data.boostPeer.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.additionalPeers!.count)) + for item in _data.additionalPeers! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 2) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(countriesIso2!.count)) - for item in countriesIso2! { - serializeString(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 4) != 0 {serializeString(prizeDescription!, buffer: buffer, boxed: false)} - serializeInt64(randomId, buffer: buffer, boxed: false) - serializeInt32(untilDate, buffer: buffer, boxed: false) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - serializeInt32(users, buffer: buffer, boxed: false) - break - case .inputStorePaymentStarsTopup(let flags, let stars, let currency, let amount, let spendPurposePeer): - if boxed { - buffer.appendInt32(-106780981) } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(stars, buffer: buffer, boxed: false) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {spendPurposePeer!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputStorePaymentAuthCode(let flags, let phoneNumber, let phoneCodeHash, let currency, let amount): - return ("inputStorePaymentAuthCode", [("flags", flags as Any), ("phoneNumber", phoneNumber as Any), ("phoneCodeHash", phoneCodeHash as Any), ("currency", currency as Any), ("amount", amount as Any)]) - case .inputStorePaymentGiftPremium(let userId, let currency, let amount): - return ("inputStorePaymentGiftPremium", [("userId", userId as Any), ("currency", currency as Any), ("amount", amount as Any)]) - case .inputStorePaymentPremiumGiftCode(let flags, let users, let boostPeer, let currency, let amount, let message): - return ("inputStorePaymentPremiumGiftCode", [("flags", flags as Any), ("users", users as Any), ("boostPeer", boostPeer as Any), ("currency", currency as Any), ("amount", amount as Any), ("message", message as Any)]) - case .inputStorePaymentPremiumGiveaway(let flags, let boostPeer, let additionalPeers, let countriesIso2, let prizeDescription, let randomId, let untilDate, let currency, let amount): - return ("inputStorePaymentPremiumGiveaway", [("flags", flags as Any), ("boostPeer", boostPeer as Any), ("additionalPeers", additionalPeers as Any), ("countriesIso2", countriesIso2 as Any), ("prizeDescription", prizeDescription as Any), ("randomId", randomId as Any), ("untilDate", untilDate as Any), ("currency", currency as Any), ("amount", amount as Any)]) - case .inputStorePaymentPremiumSubscription(let flags): - return ("inputStorePaymentPremiumSubscription", [("flags", flags as Any)]) - case .inputStorePaymentStarsGift(let userId, let stars, let currency, let amount): - return ("inputStorePaymentStarsGift", [("userId", userId as Any), ("stars", stars as Any), ("currency", currency as Any), ("amount", amount as Any)]) - case .inputStorePaymentStarsGiveaway(let flags, let stars, let boostPeer, let additionalPeers, let countriesIso2, let prizeDescription, let randomId, let untilDate, let currency, let amount, let users): - return ("inputStorePaymentStarsGiveaway", [("flags", flags as Any), ("stars", stars as Any), ("boostPeer", boostPeer as Any), ("additionalPeers", additionalPeers as Any), ("countriesIso2", countriesIso2 as Any), ("prizeDescription", prizeDescription as Any), ("randomId", randomId as Any), ("untilDate", untilDate as Any), ("currency", currency as Any), ("amount", amount as Any), ("users", users as Any)]) - case .inputStorePaymentStarsTopup(let flags, let stars, let currency, let amount, let spendPurposePeer): - return ("inputStorePaymentStarsTopup", [("flags", flags as Any), ("stars", stars as Any), ("currency", currency as Any), ("amount", amount as Any), ("spendPurposePeer", spendPurposePeer as Any)]) - } - } - + } + if Int(_data.flags) & Int(1 << 2) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.countriesIso2!.count)) + for item in _data.countriesIso2! { + serializeString(item, buffer: buffer, boxed: false) + } + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeString(_data.prizeDescription!, buffer: buffer, boxed: false) + } + serializeInt64(_data.randomId, buffer: buffer, boxed: false) + serializeInt32(_data.untilDate, buffer: buffer, boxed: false) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + serializeInt32(_data.users, buffer: buffer, boxed: false) + break + case .inputStorePaymentStarsTopup(let _data): + if boxed { + buffer.appendInt32(-106780981) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.stars, buffer: buffer, boxed: false) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.spendPurposePeer!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputStorePaymentAuthCode(let _data): + return ("inputStorePaymentAuthCode", [("flags", _data.flags as Any), ("phoneNumber", _data.phoneNumber as Any), ("phoneCodeHash", _data.phoneCodeHash as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any)]) + case .inputStorePaymentGiftPremium(let _data): + return ("inputStorePaymentGiftPremium", [("userId", _data.userId as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any)]) + case .inputStorePaymentPremiumGiftCode(let _data): + return ("inputStorePaymentPremiumGiftCode", [("flags", _data.flags as Any), ("users", _data.users as Any), ("boostPeer", _data.boostPeer as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any), ("message", _data.message as Any)]) + case .inputStorePaymentPremiumGiveaway(let _data): + return ("inputStorePaymentPremiumGiveaway", [("flags", _data.flags as Any), ("boostPeer", _data.boostPeer as Any), ("additionalPeers", _data.additionalPeers as Any), ("countriesIso2", _data.countriesIso2 as Any), ("prizeDescription", _data.prizeDescription as Any), ("randomId", _data.randomId as Any), ("untilDate", _data.untilDate as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any)]) + case .inputStorePaymentPremiumSubscription(let _data): + return ("inputStorePaymentPremiumSubscription", [("flags", _data.flags as Any)]) + case .inputStorePaymentStarsGift(let _data): + return ("inputStorePaymentStarsGift", [("userId", _data.userId as Any), ("stars", _data.stars as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any)]) + case .inputStorePaymentStarsGiveaway(let _data): + return ("inputStorePaymentStarsGiveaway", [("flags", _data.flags as Any), ("stars", _data.stars as Any), ("boostPeer", _data.boostPeer as Any), ("additionalPeers", _data.additionalPeers as Any), ("countriesIso2", _data.countriesIso2 as Any), ("prizeDescription", _data.prizeDescription as Any), ("randomId", _data.randomId as Any), ("untilDate", _data.untilDate as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any), ("users", _data.users as Any)]) + case .inputStorePaymentStarsTopup(let _data): + return ("inputStorePaymentStarsTopup", [("flags", _data.flags as Any), ("stars", _data.stars as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any), ("spendPurposePeer", _data.spendPurposePeer as Any)]) + } + } + public static func parse_inputStorePaymentAuthCode(_ reader: BufferReader) -> InputStorePaymentPurpose? { var _1: Int32? _1 = reader.readInt32() @@ -996,12 +1425,12 @@ public extension Api { let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.InputStorePaymentPurpose.inputStorePaymentAuthCode(flags: _1!, phoneNumber: _2!, phoneCodeHash: _3!, currency: _4!, amount: _5!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.InputStorePaymentPurpose.inputStorePaymentAuthCode(Cons_inputStorePaymentAuthCode(flags: _1!, phoneNumber: _2!, phoneCodeHash: _3!, currency: _4!, amount: _5!)) + } + else { + return nil + } } public static func parse_inputStorePaymentGiftPremium(_ reader: BufferReader) -> InputStorePaymentPurpose? { var _1: Api.InputUser? @@ -1015,10 +1444,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputStorePaymentPurpose.inputStorePaymentGiftPremium(userId: _1!, currency: _2!, amount: _3!) + if _c1 && _c2 && _c3 { + return Api.InputStorePaymentPurpose.inputStorePaymentGiftPremium(Cons_inputStorePaymentGiftPremium(userId: _1!, currency: _2!, amount: _3!)) + } + else { + return nil + } } public static func parse_inputStorePaymentPremiumGiftCode(_ reader: BufferReader) -> InputStorePaymentPurpose? { var _1: Int32? @@ -1028,30 +1459,33 @@ public extension Api { _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputUser.self) } var _3: Api.InputPeer? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.InputPeer - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.InputPeer + } + } var _4: String? _4 = parseString(reader) var _5: Int64? _5 = reader.readInt64() var _6: Api.TextWithEntities? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.TextWithEntities - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.TextWithEntities + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.InputStorePaymentPurpose.inputStorePaymentPremiumGiftCode(flags: _1!, users: _2!, boostPeer: _3, currency: _4!, amount: _5!, message: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.InputStorePaymentPurpose.inputStorePaymentPremiumGiftCode(Cons_inputStorePaymentPremiumGiftCode(flags: _1!, users: _2!, boostPeer: _3, currency: _4!, amount: _5!, message: _6)) + } + else { + return nil + } } public static func parse_inputStorePaymentPremiumGiveaway(_ reader: BufferReader) -> InputStorePaymentPurpose? { var _1: Int32? @@ -1061,15 +1495,21 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.InputPeer } var _3: [Api.InputPeer]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputPeer.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputPeer.self) + } + } var _4: [String]? - if Int(_1!) & Int(1 << 2) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) + } + } var _5: String? - if Int(_1!) & Int(1 << 4) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 4) != 0 { + _5 = parseString(reader) + } var _6: Int64? _6 = reader.readInt64() var _7: Int32? @@ -1087,23 +1527,23 @@ public extension Api { let _c7 = _7 != nil let _c8 = _8 != nil let _c9 = _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.InputStorePaymentPurpose.inputStorePaymentPremiumGiveaway(flags: _1!, boostPeer: _2!, additionalPeers: _3, countriesIso2: _4, prizeDescription: _5, randomId: _6!, untilDate: _7!, currency: _8!, amount: _9!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.InputStorePaymentPurpose.inputStorePaymentPremiumGiveaway(Cons_inputStorePaymentPremiumGiveaway(flags: _1!, boostPeer: _2!, additionalPeers: _3, countriesIso2: _4, prizeDescription: _5, randomId: _6!, untilDate: _7!, currency: _8!, amount: _9!)) + } + else { + return nil + } } public static func parse_inputStorePaymentPremiumSubscription(_ reader: BufferReader) -> InputStorePaymentPurpose? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputStorePaymentPurpose.inputStorePaymentPremiumSubscription(flags: _1!) + if _c1 { + return Api.InputStorePaymentPurpose.inputStorePaymentPremiumSubscription(Cons_inputStorePaymentPremiumSubscription(flags: _1!)) + } + else { + return nil + } } public static func parse_inputStorePaymentStarsGift(_ reader: BufferReader) -> InputStorePaymentPurpose? { var _1: Api.InputUser? @@ -1120,11 +1560,12 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputStorePaymentPurpose.inputStorePaymentStarsGift(userId: _1!, stars: _2!, currency: _3!, amount: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputStorePaymentPurpose.inputStorePaymentStarsGift(Cons_inputStorePaymentStarsGift(userId: _1!, stars: _2!, currency: _3!, amount: _4!)) + } + else { + return nil + } } public static func parse_inputStorePaymentStarsGiveaway(_ reader: BufferReader) -> InputStorePaymentPurpose? { var _1: Int32? @@ -1136,15 +1577,21 @@ public extension Api { _3 = Api.parse(reader, signature: signature) as? Api.InputPeer } var _4: [Api.InputPeer]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputPeer.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputPeer.self) + } + } var _5: [String]? - if Int(_1!) & Int(1 << 2) != 0 {if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) + } + } var _6: String? - if Int(_1!) & Int(1 << 4) != 0 {_6 = parseString(reader) } + if Int(_1!) & Int(1 << 4) != 0 { + _6 = parseString(reader) + } var _7: Int64? _7 = reader.readInt64() var _8: Int32? @@ -1166,18 +1613,12 @@ public extension Api { let _c9 = _9 != nil let _c10 = _10 != nil let _c11 = _11 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - return Api.InputStorePaymentPurpose.inputStorePaymentStarsGiveaway(flags: _1!, stars: _2!, boostPeer: _3!, additionalPeers: _4, countriesIso2: _5, prizeDescription: _6, randomId: _7!, untilDate: _8!, currency: _9!, amount: _10!, users: _11!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 { + return Api.InputStorePaymentPurpose.inputStorePaymentStarsGiveaway(Cons_inputStorePaymentStarsGiveaway(flags: _1!, stars: _2!, boostPeer: _3!, additionalPeers: _4, countriesIso2: _5, prizeDescription: _6, randomId: _7!, untilDate: _8!, currency: _9!, amount: _10!, users: _11!)) + } + else { + return nil + } } public static func parse_inputStorePaymentStarsTopup(_ reader: BufferReader) -> InputStorePaymentPurpose? { var _1: Int32? @@ -1189,21 +1630,22 @@ public extension Api { var _4: Int64? _4 = reader.readInt64() var _5: Api.InputPeer? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.InputPeer - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.InputPeer + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.InputStorePaymentPurpose.inputStorePaymentStarsTopup(flags: _1!, stars: _2!, currency: _3!, amount: _4!, spendPurposePeer: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.InputStorePaymentPurpose.inputStorePaymentStarsTopup(Cons_inputStorePaymentStarsTopup(flags: _1!, stars: _2!, currency: _3!, amount: _4!, spendPurposePeer: _5)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api14.swift b/submodules/TelegramApi/Sources/Api14.swift index 4b917cf6..00754213 100644 --- a/submodules/TelegramApi/Sources/Api14.swift +++ b/submodules/TelegramApi/Sources/Api14.swift @@ -1,35 +1,49 @@ public extension Api { enum InputTheme: TypeConstructorDescription { - case inputTheme(id: Int64, accessHash: Int64) - case inputThemeSlug(slug: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputTheme(let id, let accessHash): - if boxed { - buffer.appendInt32(1012306921) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - case .inputThemeSlug(let slug): - if boxed { - buffer.appendInt32(-175567375) - } - serializeString(slug, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputTheme(let id, let accessHash): - return ("inputTheme", [("id", id as Any), ("accessHash", accessHash as Any)]) - case .inputThemeSlug(let slug): - return ("inputThemeSlug", [("slug", slug as Any)]) - } - } - + public class Cons_inputTheme { + public var id: Int64 + public var accessHash: Int64 + public init(id: Int64, accessHash: Int64) { + self.id = id + self.accessHash = accessHash + } + } + public class Cons_inputThemeSlug { + public var slug: String + public init(slug: String) { + self.slug = slug + } + } + case inputTheme(Cons_inputTheme) + case inputThemeSlug(Cons_inputThemeSlug) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputTheme(let _data): + if boxed { + buffer.appendInt32(1012306921) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + case .inputThemeSlug(let _data): + if boxed { + buffer.appendInt32(-175567375) + } + serializeString(_data.slug, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputTheme(let _data): + return ("inputTheme", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any)]) + case .inputThemeSlug(let _data): + return ("inputThemeSlug", [("slug", _data.slug as Any)]) + } + } + public static func parse_inputTheme(_ reader: BufferReader) -> InputTheme? { var _1: Int64? _1 = reader.readInt64() @@ -37,52 +51,84 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputTheme.inputTheme(id: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputTheme.inputTheme(Cons_inputTheme(id: _1!, accessHash: _2!)) + } + else { + return nil + } } public static func parse_inputThemeSlug(_ reader: BufferReader) -> InputTheme? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputTheme.inputThemeSlug(slug: _1!) + if _c1 { + return Api.InputTheme.inputThemeSlug(Cons_inputThemeSlug(slug: _1!)) + } + else { + return nil + } } - } } public extension Api { enum InputThemeSettings: TypeConstructorDescription { - case inputThemeSettings(flags: Int32, baseTheme: Api.BaseTheme, accentColor: Int32, outboxAccentColor: Int32?, messageColors: [Int32]?, wallpaper: Api.InputWallPaper?, wallpaperSettings: Api.WallPaperSettings?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputThemeSettings(let flags, let baseTheme, let accentColor, let outboxAccentColor, let messageColors, let wallpaper, let wallpaperSettings): - if boxed { - buffer.appendInt32(-1881255857) - } - serializeInt32(flags, buffer: buffer, boxed: false) - baseTheme.serialize(buffer, true) - serializeInt32(accentColor, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(outboxAccentColor!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messageColors!.count)) - for item in messageColors! { + public class Cons_inputThemeSettings { + public var flags: Int32 + public var baseTheme: Api.BaseTheme + public var accentColor: Int32 + public var outboxAccentColor: Int32? + public var messageColors: [Int32]? + public var wallpaper: Api.InputWallPaper? + public var wallpaperSettings: Api.WallPaperSettings? + public init(flags: Int32, baseTheme: Api.BaseTheme, accentColor: Int32, outboxAccentColor: Int32?, messageColors: [Int32]?, wallpaper: Api.InputWallPaper?, wallpaperSettings: Api.WallPaperSettings?) { + self.flags = flags + self.baseTheme = baseTheme + self.accentColor = accentColor + self.outboxAccentColor = outboxAccentColor + self.messageColors = messageColors + self.wallpaper = wallpaper + self.wallpaperSettings = wallpaperSettings + } + } + case inputThemeSettings(Cons_inputThemeSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputThemeSettings(let _data): + if boxed { + buffer.appendInt32(-1881255857) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.baseTheme.serialize(buffer, true) + serializeInt32(_data.accentColor, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.outboxAccentColor!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messageColors!.count)) + for item in _data.messageColors! { serializeInt32(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 1) != 0 {wallpaper!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {wallpaperSettings!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputThemeSettings(let flags, let baseTheme, let accentColor, let outboxAccentColor, let messageColors, let wallpaper, let wallpaperSettings): - return ("inputThemeSettings", [("flags", flags as Any), ("baseTheme", baseTheme as Any), ("accentColor", accentColor as Any), ("outboxAccentColor", outboxAccentColor as Any), ("messageColors", messageColors as Any), ("wallpaper", wallpaper as Any), ("wallpaperSettings", wallpaperSettings as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.wallpaper!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.wallpaperSettings!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputThemeSettings(let _data): + return ("inputThemeSettings", [("flags", _data.flags as Any), ("baseTheme", _data.baseTheme as Any), ("accentColor", _data.accentColor as Any), ("outboxAccentColor", _data.outboxAccentColor as Any), ("messageColors", _data.messageColors as Any), ("wallpaper", _data.wallpaper as Any), ("wallpaperSettings", _data.wallpaperSettings as Any)]) + } + } + public static func parse_inputThemeSettings(_ reader: BufferReader) -> InputThemeSettings? { var _1: Int32? _1 = reader.readInt32() @@ -93,19 +139,27 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 3) != 0 { + _4 = reader.readInt32() + } var _5: [Int32]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + } var _6: Api.InputWallPaper? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.InputWallPaper - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.InputWallPaper + } + } var _7: Api.WallPaperSettings? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.WallPaperSettings - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.WallPaperSettings + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -113,70 +167,83 @@ public extension Api { let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.InputThemeSettings.inputThemeSettings(flags: _1!, baseTheme: _2!, accentColor: _3!, outboxAccentColor: _4, messageColors: _5, wallpaper: _6, wallpaperSettings: _7) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.InputThemeSettings.inputThemeSettings(Cons_inputThemeSettings(flags: _1!, baseTheme: _2!, accentColor: _3!, outboxAccentColor: _4, messageColors: _5, wallpaper: _6, wallpaperSettings: _7)) + } + else { + return nil + } } - } } public extension Api { indirect enum InputUser: TypeConstructorDescription { - case inputUser(userId: Int64, accessHash: Int64) + public class Cons_inputUser { + public var userId: Int64 + public var accessHash: Int64 + public init(userId: Int64, accessHash: Int64) { + self.userId = userId + self.accessHash = accessHash + } + } + public class Cons_inputUserFromMessage { + public var peer: Api.InputPeer + public var msgId: Int32 + public var userId: Int64 + public init(peer: Api.InputPeer, msgId: Int32, userId: Int64) { + self.peer = peer + self.msgId = msgId + self.userId = userId + } + } + case inputUser(Cons_inputUser) case inputUserEmpty - case inputUserFromMessage(peer: Api.InputPeer, msgId: Int32, userId: Int64) + case inputUserFromMessage(Cons_inputUserFromMessage) case inputUserSelf - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputUser(let userId, let accessHash): - if boxed { - buffer.appendInt32(-233744186) - } - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - case .inputUserEmpty: - if boxed { - buffer.appendInt32(-1182234929) - } - - break - case .inputUserFromMessage(let peer, let msgId, let userId): - if boxed { - buffer.appendInt32(497305826) - } - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - break - case .inputUserSelf: - if boxed { - buffer.appendInt32(-138301121) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputUser(let userId, let accessHash): - return ("inputUser", [("userId", userId as Any), ("accessHash", accessHash as Any)]) - case .inputUserEmpty: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputUser(let _data): + if boxed { + buffer.appendInt32(-233744186) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + case .inputUserEmpty: + if boxed { + buffer.appendInt32(-1182234929) + } + break + case .inputUserFromMessage(let _data): + if boxed { + buffer.appendInt32(497305826) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + break + case .inputUserSelf: + if boxed { + buffer.appendInt32(-138301121) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputUser(let _data): + return ("inputUser", [("userId", _data.userId as Any), ("accessHash", _data.accessHash as Any)]) + case .inputUserEmpty: return ("inputUserEmpty", []) - case .inputUserFromMessage(let peer, let msgId, let userId): - return ("inputUserFromMessage", [("peer", peer as Any), ("msgId", msgId as Any), ("userId", userId as Any)]) - case .inputUserSelf: + case .inputUserFromMessage(let _data): + return ("inputUserFromMessage", [("peer", _data.peer as Any), ("msgId", _data.msgId as Any), ("userId", _data.userId as Any)]) + case .inputUserSelf: return ("inputUserSelf", []) - } - } - + } + } + public static func parse_inputUser(_ reader: BufferReader) -> InputUser? { var _1: Int64? _1 = reader.readInt64() @@ -184,9 +251,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputUser.inputUser(userId: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputUser.inputUser(Cons_inputUser(userId: _1!, accessHash: _2!)) + } + else { + return nil + } } public static func parse_inputUserEmpty(_ reader: BufferReader) -> InputUser? { return Api.InputUser.inputUserEmpty @@ -203,58 +273,79 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputUser.inputUserFromMessage(peer: _1!, msgId: _2!, userId: _3!) + if _c1 && _c2 && _c3 { + return Api.InputUser.inputUserFromMessage(Cons_inputUserFromMessage(peer: _1!, msgId: _2!, userId: _3!)) + } + else { + return nil + } } public static func parse_inputUserSelf(_ reader: BufferReader) -> InputUser? { return Api.InputUser.inputUserSelf } - } } public extension Api { enum InputWallPaper: TypeConstructorDescription { - case inputWallPaper(id: Int64, accessHash: Int64) - case inputWallPaperNoFile(id: Int64) - case inputWallPaperSlug(slug: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputWallPaper(let id, let accessHash): - if boxed { - buffer.appendInt32(-433014407) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - case .inputWallPaperNoFile(let id): - if boxed { - buffer.appendInt32(-1770371538) - } - serializeInt64(id, buffer: buffer, boxed: false) - break - case .inputWallPaperSlug(let slug): - if boxed { - buffer.appendInt32(1913199744) - } - serializeString(slug, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputWallPaper(let id, let accessHash): - return ("inputWallPaper", [("id", id as Any), ("accessHash", accessHash as Any)]) - case .inputWallPaperNoFile(let id): - return ("inputWallPaperNoFile", [("id", id as Any)]) - case .inputWallPaperSlug(let slug): - return ("inputWallPaperSlug", [("slug", slug as Any)]) - } - } - + public class Cons_inputWallPaper { + public var id: Int64 + public var accessHash: Int64 + public init(id: Int64, accessHash: Int64) { + self.id = id + self.accessHash = accessHash + } + } + public class Cons_inputWallPaperNoFile { + public var id: Int64 + public init(id: Int64) { + self.id = id + } + } + public class Cons_inputWallPaperSlug { + public var slug: String + public init(slug: String) { + self.slug = slug + } + } + case inputWallPaper(Cons_inputWallPaper) + case inputWallPaperNoFile(Cons_inputWallPaperNoFile) + case inputWallPaperSlug(Cons_inputWallPaperSlug) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputWallPaper(let _data): + if boxed { + buffer.appendInt32(-433014407) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + case .inputWallPaperNoFile(let _data): + if boxed { + buffer.appendInt32(-1770371538) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + break + case .inputWallPaperSlug(let _data): + if boxed { + buffer.appendInt32(1913199744) + } + serializeString(_data.slug, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputWallPaper(let _data): + return ("inputWallPaper", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any)]) + case .inputWallPaperNoFile(let _data): + return ("inputWallPaperNoFile", [("id", _data.id as Any)]) + case .inputWallPaperSlug(let _data): + return ("inputWallPaperSlug", [("slug", _data.slug as Any)]) + } + } + public static func parse_inputWallPaper(_ reader: BufferReader) -> InputWallPaper? { var _1: Int64? _1 = reader.readInt64() @@ -262,56 +353,78 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputWallPaper.inputWallPaper(id: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputWallPaper.inputWallPaper(Cons_inputWallPaper(id: _1!, accessHash: _2!)) + } + else { + return nil + } } public static func parse_inputWallPaperNoFile(_ reader: BufferReader) -> InputWallPaper? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputWallPaper.inputWallPaperNoFile(id: _1!) + if _c1 { + return Api.InputWallPaper.inputWallPaperNoFile(Cons_inputWallPaperNoFile(id: _1!)) + } + else { + return nil + } } public static func parse_inputWallPaperSlug(_ reader: BufferReader) -> InputWallPaper? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputWallPaper.inputWallPaperSlug(slug: _1!) + if _c1 { + return Api.InputWallPaper.inputWallPaperSlug(Cons_inputWallPaperSlug(slug: _1!)) + } + else { + return nil + } } - } } public extension Api { enum InputWebDocument: TypeConstructorDescription { - case inputWebDocument(url: String, size: Int32, mimeType: String, attributes: [Api.DocumentAttribute]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputWebDocument(let url, let size, let mimeType, let attributes): - if boxed { - buffer.appendInt32(-1678949555) - } - serializeString(url, buffer: buffer, boxed: false) - serializeInt32(size, buffer: buffer, boxed: false) - serializeString(mimeType, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(attributes.count)) - for item in attributes { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputWebDocument(let url, let size, let mimeType, let attributes): - return ("inputWebDocument", [("url", url as Any), ("size", size as Any), ("mimeType", mimeType as Any), ("attributes", attributes as Any)]) - } - } - + public class Cons_inputWebDocument { + public var url: String + public var size: Int32 + public var mimeType: String + public var attributes: [Api.DocumentAttribute] + public init(url: String, size: Int32, mimeType: String, attributes: [Api.DocumentAttribute]) { + self.url = url + self.size = size + self.mimeType = mimeType + self.attributes = attributes + } + } + case inputWebDocument(Cons_inputWebDocument) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputWebDocument(let _data): + if boxed { + buffer.appendInt32(-1678949555) + } + serializeString(_data.url, buffer: buffer, boxed: false) + serializeInt32(_data.size, buffer: buffer, boxed: false) + serializeString(_data.mimeType, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.attributes.count)) + for item in _data.attributes { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputWebDocument(let _data): + return ("inputWebDocument", [("url", _data.url as Any), ("size", _data.size as Any), ("mimeType", _data.mimeType as Any), ("attributes", _data.attributes as Any)]) + } + } + public static func parse_inputWebDocument(_ reader: BufferReader) -> InputWebDocument? { var _1: String? _1 = parseString(reader) @@ -327,84 +440,133 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputWebDocument.inputWebDocument(url: _1!, size: _2!, mimeType: _3!, attributes: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputWebDocument.inputWebDocument(Cons_inputWebDocument(url: _1!, size: _2!, mimeType: _3!, attributes: _4!)) + } + else { + return nil + } } - } } public extension Api { enum InputWebFileLocation: TypeConstructorDescription { - case inputWebFileAudioAlbumThumbLocation(flags: Int32, document: Api.InputDocument?, title: String?, performer: String?) - case inputWebFileGeoPointLocation(geoPoint: Api.InputGeoPoint, accessHash: Int64, w: Int32, h: Int32, zoom: Int32, scale: Int32) - case inputWebFileLocation(url: String, accessHash: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputWebFileAudioAlbumThumbLocation(let flags, let document, let title, let performer): - if boxed { - buffer.appendInt32(-193992412) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {document!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(performer!, buffer: buffer, boxed: false)} - break - case .inputWebFileGeoPointLocation(let geoPoint, let accessHash, let w, let h, let zoom, let scale): - if boxed { - buffer.appendInt32(-1625153079) - } - geoPoint.serialize(buffer, true) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeInt32(w, buffer: buffer, boxed: false) - serializeInt32(h, buffer: buffer, boxed: false) - serializeInt32(zoom, buffer: buffer, boxed: false) - serializeInt32(scale, buffer: buffer, boxed: false) - break - case .inputWebFileLocation(let url, let accessHash): - if boxed { - buffer.appendInt32(-1036396922) - } - serializeString(url, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputWebFileAudioAlbumThumbLocation(let flags, let document, let title, let performer): - return ("inputWebFileAudioAlbumThumbLocation", [("flags", flags as Any), ("document", document as Any), ("title", title as Any), ("performer", performer as Any)]) - case .inputWebFileGeoPointLocation(let geoPoint, let accessHash, let w, let h, let zoom, let scale): - return ("inputWebFileGeoPointLocation", [("geoPoint", geoPoint as Any), ("accessHash", accessHash as Any), ("w", w as Any), ("h", h as Any), ("zoom", zoom as Any), ("scale", scale as Any)]) - case .inputWebFileLocation(let url, let accessHash): - return ("inputWebFileLocation", [("url", url as Any), ("accessHash", accessHash as Any)]) - } - } - + public class Cons_inputWebFileAudioAlbumThumbLocation { + public var flags: Int32 + public var document: Api.InputDocument? + public var title: String? + public var performer: String? + public init(flags: Int32, document: Api.InputDocument?, title: String?, performer: String?) { + self.flags = flags + self.document = document + self.title = title + self.performer = performer + } + } + public class Cons_inputWebFileGeoPointLocation { + public var geoPoint: Api.InputGeoPoint + public var accessHash: Int64 + public var w: Int32 + public var h: Int32 + public var zoom: Int32 + public var scale: Int32 + public init(geoPoint: Api.InputGeoPoint, accessHash: Int64, w: Int32, h: Int32, zoom: Int32, scale: Int32) { + self.geoPoint = geoPoint + self.accessHash = accessHash + self.w = w + self.h = h + self.zoom = zoom + self.scale = scale + } + } + public class Cons_inputWebFileLocation { + public var url: String + public var accessHash: Int64 + public init(url: String, accessHash: Int64) { + self.url = url + self.accessHash = accessHash + } + } + case inputWebFileAudioAlbumThumbLocation(Cons_inputWebFileAudioAlbumThumbLocation) + case inputWebFileGeoPointLocation(Cons_inputWebFileGeoPointLocation) + case inputWebFileLocation(Cons_inputWebFileLocation) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputWebFileAudioAlbumThumbLocation(let _data): + if boxed { + buffer.appendInt32(-193992412) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.document!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.performer!, buffer: buffer, boxed: false) + } + break + case .inputWebFileGeoPointLocation(let _data): + if boxed { + buffer.appendInt32(-1625153079) + } + _data.geoPoint.serialize(buffer, true) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeInt32(_data.w, buffer: buffer, boxed: false) + serializeInt32(_data.h, buffer: buffer, boxed: false) + serializeInt32(_data.zoom, buffer: buffer, boxed: false) + serializeInt32(_data.scale, buffer: buffer, boxed: false) + break + case .inputWebFileLocation(let _data): + if boxed { + buffer.appendInt32(-1036396922) + } + serializeString(_data.url, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputWebFileAudioAlbumThumbLocation(let _data): + return ("inputWebFileAudioAlbumThumbLocation", [("flags", _data.flags as Any), ("document", _data.document as Any), ("title", _data.title as Any), ("performer", _data.performer as Any)]) + case .inputWebFileGeoPointLocation(let _data): + return ("inputWebFileGeoPointLocation", [("geoPoint", _data.geoPoint as Any), ("accessHash", _data.accessHash as Any), ("w", _data.w as Any), ("h", _data.h as Any), ("zoom", _data.zoom as Any), ("scale", _data.scale as Any)]) + case .inputWebFileLocation(let _data): + return ("inputWebFileLocation", [("url", _data.url as Any), ("accessHash", _data.accessHash as Any)]) + } + } + public static func parse_inputWebFileAudioAlbumThumbLocation(_ reader: BufferReader) -> InputWebFileLocation? { var _1: Int32? _1 = reader.readInt32() var _2: Api.InputDocument? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.InputDocument - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.InputDocument + } + } var _3: String? - if Int(_1!) & Int(1 << 1) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _3 = parseString(reader) + } var _4: String? - if Int(_1!) & Int(1 << 1) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = parseString(reader) + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputWebFileLocation.inputWebFileAudioAlbumThumbLocation(flags: _1!, document: _2, title: _3, performer: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputWebFileLocation.inputWebFileAudioAlbumThumbLocation(Cons_inputWebFileAudioAlbumThumbLocation(flags: _1!, document: _2, title: _3, performer: _4)) + } + else { + return nil + } } public static func parse_inputWebFileGeoPointLocation(_ reader: BufferReader) -> InputWebFileLocation? { var _1: Api.InputGeoPoint? @@ -427,13 +589,12 @@ public extension Api { let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.InputWebFileLocation.inputWebFileGeoPointLocation(geoPoint: _1!, accessHash: _2!, w: _3!, h: _4!, zoom: _5!, scale: _6!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.InputWebFileLocation.inputWebFileGeoPointLocation(Cons_inputWebFileGeoPointLocation(geoPoint: _1!, accessHash: _2!, w: _3!, h: _4!, zoom: _5!, scale: _6!)) + } + else { + return nil + } } public static func parse_inputWebFileLocation(_ reader: BufferReader) -> InputWebFileLocation? { var _1: String? @@ -442,49 +603,77 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputWebFileLocation.inputWebFileLocation(url: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputWebFileLocation.inputWebFileLocation(Cons_inputWebFileLocation(url: _1!, accessHash: _2!)) + } + else { + return nil + } } - } } public extension Api { enum Invoice: TypeConstructorDescription { - case invoice(flags: Int32, currency: String, prices: [Api.LabeledPrice], maxTipAmount: Int64?, suggestedTipAmounts: [Int64]?, termsUrl: String?, subscriptionPeriod: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .invoice(let flags, let currency, let prices, let maxTipAmount, let suggestedTipAmounts, let termsUrl, let subscriptionPeriod): - if boxed { - buffer.appendInt32(77522308) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(currency, buffer: buffer, boxed: false) + public class Cons_invoice { + public var flags: Int32 + public var currency: String + public var prices: [Api.LabeledPrice] + public var maxTipAmount: Int64? + public var suggestedTipAmounts: [Int64]? + public var termsUrl: String? + public var subscriptionPeriod: Int32? + public init(flags: Int32, currency: String, prices: [Api.LabeledPrice], maxTipAmount: Int64?, suggestedTipAmounts: [Int64]?, termsUrl: String?, subscriptionPeriod: Int32?) { + self.flags = flags + self.currency = currency + self.prices = prices + self.maxTipAmount = maxTipAmount + self.suggestedTipAmounts = suggestedTipAmounts + self.termsUrl = termsUrl + self.subscriptionPeriod = subscriptionPeriod + } + } + case invoice(Cons_invoice) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .invoice(let _data): + if boxed { + buffer.appendInt32(77522308) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.currency, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.prices.count)) + for item in _data.prices { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + serializeInt64(_data.maxTipAmount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(prices.count)) - for item in prices { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 8) != 0 {serializeInt64(maxTipAmount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(suggestedTipAmounts!.count)) - for item in suggestedTipAmounts! { + buffer.appendInt32(Int32(_data.suggestedTipAmounts!.count)) + for item in _data.suggestedTipAmounts! { serializeInt64(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 10) != 0 {serializeString(termsUrl!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 11) != 0 {serializeInt32(subscriptionPeriod!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .invoice(let flags, let currency, let prices, let maxTipAmount, let suggestedTipAmounts, let termsUrl, let subscriptionPeriod): - return ("invoice", [("flags", flags as Any), ("currency", currency as Any), ("prices", prices as Any), ("maxTipAmount", maxTipAmount as Any), ("suggestedTipAmounts", suggestedTipAmounts as Any), ("termsUrl", termsUrl as Any), ("subscriptionPeriod", subscriptionPeriod as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 10) != 0 { + serializeString(_data.termsUrl!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 11) != 0 { + serializeInt32(_data.subscriptionPeriod!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .invoice(let _data): + return ("invoice", [("flags", _data.flags as Any), ("currency", _data.currency as Any), ("prices", _data.prices as Any), ("maxTipAmount", _data.maxTipAmount as Any), ("suggestedTipAmounts", _data.suggestedTipAmounts as Any), ("termsUrl", _data.termsUrl as Any), ("subscriptionPeriod", _data.subscriptionPeriod as Any)]) + } + } + public static func parse_invoice(_ reader: BufferReader) -> Invoice? { var _1: Int32? _1 = reader.readInt32() @@ -495,15 +684,23 @@ public extension Api { _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.LabeledPrice.self) } var _4: Int64? - if Int(_1!) & Int(1 << 8) != 0 {_4 = reader.readInt64() } + if Int(_1!) & Int(1 << 8) != 0 { + _4 = reader.readInt64() + } var _5: [Int64]? - if Int(_1!) & Int(1 << 8) != 0 {if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) - } } + if Int(_1!) & Int(1 << 8) != 0 { + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) + } + } var _6: String? - if Int(_1!) & Int(1 << 10) != 0 {_6 = parseString(reader) } + if Int(_1!) & Int(1 << 10) != 0 { + _6 = parseString(reader) + } var _7: Int32? - if Int(_1!) & Int(1 << 11) != 0 {_7 = reader.readInt32() } + if Int(_1!) & Int(1 << 11) != 0 { + _7 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -511,41 +708,46 @@ public extension Api { let _c5 = (Int(_1!) & Int(1 << 8) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 10) == 0) || _6 != nil let _c7 = (Int(_1!) & Int(1 << 11) == 0) || _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.Invoice.invoice(flags: _1!, currency: _2!, prices: _3!, maxTipAmount: _4, suggestedTipAmounts: _5, termsUrl: _6, subscriptionPeriod: _7) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.Invoice.invoice(Cons_invoice(flags: _1!, currency: _2!, prices: _3!, maxTipAmount: _4, suggestedTipAmounts: _5, termsUrl: _6, subscriptionPeriod: _7)) + } + else { + return nil + } } - } } public extension Api { enum JSONObjectValue: TypeConstructorDescription { - case jsonObjectValue(key: String, value: Api.JSONValue) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .jsonObjectValue(let key, let value): - if boxed { - buffer.appendInt32(-1059185703) - } - serializeString(key, buffer: buffer, boxed: false) - value.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .jsonObjectValue(let key, let value): - return ("jsonObjectValue", [("key", key as Any), ("value", value as Any)]) - } - } - + public class Cons_jsonObjectValue { + public var key: String + public var value: Api.JSONValue + public init(key: String, value: Api.JSONValue) { + self.key = key + self.value = value + } + } + case jsonObjectValue(Cons_jsonObjectValue) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .jsonObjectValue(let _data): + if boxed { + buffer.appendInt32(-1059185703) + } + serializeString(_data.key, buffer: buffer, boxed: false) + _data.value.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .jsonObjectValue(let _data): + return ("jsonObjectValue", [("key", _data.key as Any), ("value", _data.value as Any)]) + } + } + public static func parse_jsonObjectValue(_ reader: BufferReader) -> JSONObjectValue? { var _1: String? _1 = parseString(reader) @@ -555,96 +757,131 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.JSONObjectValue.jsonObjectValue(key: _1!, value: _2!) + if _c1 && _c2 { + return Api.JSONObjectValue.jsonObjectValue(Cons_jsonObjectValue(key: _1!, value: _2!)) + } + else { + return nil + } } - } } public extension Api { enum JSONValue: TypeConstructorDescription { - case jsonArray(value: [Api.JSONValue]) - case jsonBool(value: Api.Bool) + public class Cons_jsonArray { + public var value: [Api.JSONValue] + public init(value: [Api.JSONValue]) { + self.value = value + } + } + public class Cons_jsonBool { + public var value: Api.Bool + public init(value: Api.Bool) { + self.value = value + } + } + public class Cons_jsonNumber { + public var value: Double + public init(value: Double) { + self.value = value + } + } + public class Cons_jsonObject { + public var value: [Api.JSONObjectValue] + public init(value: [Api.JSONObjectValue]) { + self.value = value + } + } + public class Cons_jsonString { + public var value: String + public init(value: String) { + self.value = value + } + } + case jsonArray(Cons_jsonArray) + case jsonBool(Cons_jsonBool) case jsonNull - case jsonNumber(value: Double) - case jsonObject(value: [Api.JSONObjectValue]) - case jsonString(value: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .jsonArray(let value): - if boxed { - buffer.appendInt32(-146520221) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(value.count)) - for item in value { - item.serialize(buffer, true) - } - break - case .jsonBool(let value): - if boxed { - buffer.appendInt32(-952869270) - } - value.serialize(buffer, true) - break - case .jsonNull: - if boxed { - buffer.appendInt32(1064139624) - } - - break - case .jsonNumber(let value): - if boxed { - buffer.appendInt32(736157604) - } - serializeDouble(value, buffer: buffer, boxed: false) - break - case .jsonObject(let value): - if boxed { - buffer.appendInt32(-1715350371) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(value.count)) - for item in value { - item.serialize(buffer, true) - } - break - case .jsonString(let value): - if boxed { - buffer.appendInt32(-1222740358) - } - serializeString(value, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .jsonArray(let value): - return ("jsonArray", [("value", value as Any)]) - case .jsonBool(let value): - return ("jsonBool", [("value", value as Any)]) - case .jsonNull: + case jsonNumber(Cons_jsonNumber) + case jsonObject(Cons_jsonObject) + case jsonString(Cons_jsonString) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .jsonArray(let _data): + if boxed { + buffer.appendInt32(-146520221) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.value.count)) + for item in _data.value { + item.serialize(buffer, true) + } + break + case .jsonBool(let _data): + if boxed { + buffer.appendInt32(-952869270) + } + _data.value.serialize(buffer, true) + break + case .jsonNull: + if boxed { + buffer.appendInt32(1064139624) + } + break + case .jsonNumber(let _data): + if boxed { + buffer.appendInt32(736157604) + } + serializeDouble(_data.value, buffer: buffer, boxed: false) + break + case .jsonObject(let _data): + if boxed { + buffer.appendInt32(-1715350371) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.value.count)) + for item in _data.value { + item.serialize(buffer, true) + } + break + case .jsonString(let _data): + if boxed { + buffer.appendInt32(-1222740358) + } + serializeString(_data.value, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .jsonArray(let _data): + return ("jsonArray", [("value", _data.value as Any)]) + case .jsonBool(let _data): + return ("jsonBool", [("value", _data.value as Any)]) + case .jsonNull: return ("jsonNull", []) - case .jsonNumber(let value): - return ("jsonNumber", [("value", value as Any)]) - case .jsonObject(let value): - return ("jsonObject", [("value", value as Any)]) - case .jsonString(let value): - return ("jsonString", [("value", value as Any)]) - } - } - + case .jsonNumber(let _data): + return ("jsonNumber", [("value", _data.value as Any)]) + case .jsonObject(let _data): + return ("jsonObject", [("value", _data.value as Any)]) + case .jsonString(let _data): + return ("jsonString", [("value", _data.value as Any)]) + } + } + public static func parse_jsonArray(_ reader: BufferReader) -> JSONValue? { var _1: [Api.JSONValue]? if let _ = reader.readInt32() { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.JSONValue.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.JSONValue.jsonArray(value: _1!) + if _c1 { + return Api.JSONValue.jsonArray(Cons_jsonArray(value: _1!)) + } + else { + return nil + } } public static func parse_jsonBool(_ reader: BufferReader) -> JSONValue? { var _1: Api.Bool? @@ -652,8 +889,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Bool } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.JSONValue.jsonBool(value: _1!) + if _c1 { + return Api.JSONValue.jsonBool(Cons_jsonBool(value: _1!)) + } + else { + return nil + } } public static func parse_jsonNull(_ reader: BufferReader) -> JSONValue? { return Api.JSONValue.jsonNull @@ -662,8 +903,12 @@ public extension Api { var _1: Double? _1 = reader.readDouble() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.JSONValue.jsonNumber(value: _1!) + if _c1 { + return Api.JSONValue.jsonNumber(Cons_jsonNumber(value: _1!)) + } + else { + return nil + } } public static func parse_jsonObject(_ reader: BufferReader) -> JSONValue? { var _1: [Api.JSONObjectValue]? @@ -671,476 +916,994 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.JSONObjectValue.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.JSONValue.jsonObject(value: _1!) + if _c1 { + return Api.JSONValue.jsonObject(Cons_jsonObject(value: _1!)) + } + else { + return nil + } } public static func parse_jsonString(_ reader: BufferReader) -> JSONValue? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.JSONValue.jsonString(value: _1!) + if _c1 { + return Api.JSONValue.jsonString(Cons_jsonString(value: _1!)) + } + else { + return nil + } } - } } public extension Api { indirect enum KeyboardButton: TypeConstructorDescription { - case inputKeyboardButtonRequestPeer(flags: Int32, text: String, buttonId: Int32, peerType: Api.RequestPeerType, maxQuantity: Int32) - case inputKeyboardButtonUrlAuth(flags: Int32, text: String, fwdText: String?, url: String, bot: Api.InputUser) - case inputKeyboardButtonUserProfile(text: String, userId: Api.InputUser) - case keyboardButton(text: String) - case keyboardButtonBuy(text: String) - case keyboardButtonCallback(flags: Int32, text: String, data: Buffer) - case keyboardButtonCopy(text: String, copyText: String) - case keyboardButtonGame(text: String) - case keyboardButtonRequestGeoLocation(text: String) - case keyboardButtonRequestPeer(text: String, buttonId: Int32, peerType: Api.RequestPeerType, maxQuantity: Int32) - case keyboardButtonRequestPhone(text: String) - case keyboardButtonRequestPoll(flags: Int32, quiz: Api.Bool?, text: String) - case keyboardButtonSimpleWebView(text: String, url: String) - case keyboardButtonSwitchInline(flags: Int32, text: String, query: String, peerTypes: [Api.InlineQueryPeerType]?) - case keyboardButtonUrl(text: String, url: String) - case keyboardButtonUrlAuth(flags: Int32, text: String, fwdText: String?, url: String, buttonId: Int32) - case keyboardButtonUserProfile(text: String, userId: Int64) - case keyboardButtonWebView(text: String, url: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputKeyboardButtonRequestPeer(let flags, let text, let buttonId, let peerType, let maxQuantity): - if boxed { - buffer.appendInt32(-916050683) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - serializeInt32(buttonId, buffer: buffer, boxed: false) - peerType.serialize(buffer, true) - serializeInt32(maxQuantity, buffer: buffer, boxed: false) - break - case .inputKeyboardButtonUrlAuth(let flags, let text, let fwdText, let url, let bot): - if boxed { - buffer.appendInt32(-802258988) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeString(fwdText!, buffer: buffer, boxed: false)} - serializeString(url, buffer: buffer, boxed: false) - bot.serialize(buffer, true) - break - case .inputKeyboardButtonUserProfile(let text, let userId): - if boxed { - buffer.appendInt32(-376962181) - } - serializeString(text, buffer: buffer, boxed: false) - userId.serialize(buffer, true) - break - case .keyboardButton(let text): - if boxed { - buffer.appendInt32(-1560655744) - } - serializeString(text, buffer: buffer, boxed: false) - break - case .keyboardButtonBuy(let text): - if boxed { - buffer.appendInt32(-1344716869) - } - serializeString(text, buffer: buffer, boxed: false) - break - case .keyboardButtonCallback(let flags, let text, let data): - if boxed { - buffer.appendInt32(901503851) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - serializeBytes(data, buffer: buffer, boxed: false) - break - case .keyboardButtonCopy(let text, let copyText): - if boxed { - buffer.appendInt32(1976723854) - } - serializeString(text, buffer: buffer, boxed: false) - serializeString(copyText, buffer: buffer, boxed: false) - break - case .keyboardButtonGame(let text): - if boxed { - buffer.appendInt32(1358175439) - } - serializeString(text, buffer: buffer, boxed: false) - break - case .keyboardButtonRequestGeoLocation(let text): - if boxed { - buffer.appendInt32(-59151553) - } - serializeString(text, buffer: buffer, boxed: false) - break - case .keyboardButtonRequestPeer(let text, let buttonId, let peerType, let maxQuantity): - if boxed { - buffer.appendInt32(1406648280) - } - serializeString(text, buffer: buffer, boxed: false) - serializeInt32(buttonId, buffer: buffer, boxed: false) - peerType.serialize(buffer, true) - serializeInt32(maxQuantity, buffer: buffer, boxed: false) - break - case .keyboardButtonRequestPhone(let text): - if boxed { - buffer.appendInt32(-1318425559) - } - serializeString(text, buffer: buffer, boxed: false) - break - case .keyboardButtonRequestPoll(let flags, let quiz, let text): - if boxed { - buffer.appendInt32(-1144565411) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {quiz!.serialize(buffer, true)} - serializeString(text, buffer: buffer, boxed: false) - break - case .keyboardButtonSimpleWebView(let text, let url): - if boxed { - buffer.appendInt32(-1598009252) - } - serializeString(text, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - break - case .keyboardButtonSwitchInline(let flags, let text, let query, let peerTypes): - if boxed { - buffer.appendInt32(-1816527947) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - serializeString(query, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peerTypes!.count)) - for item in peerTypes! { + public class Cons_inputKeyboardButtonRequestPeer { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public var buttonId: Int32 + public var peerType: Api.RequestPeerType + public var maxQuantity: Int32 + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String, buttonId: Int32, peerType: Api.RequestPeerType, maxQuantity: Int32) { + self.flags = flags + self.style = style + self.text = text + self.buttonId = buttonId + self.peerType = peerType + self.maxQuantity = maxQuantity + } + } + public class Cons_inputKeyboardButtonUrlAuth { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public var fwdText: String? + public var url: String + public var bot: Api.InputUser + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String, fwdText: String?, url: String, bot: Api.InputUser) { + self.flags = flags + self.style = style + self.text = text + self.fwdText = fwdText + self.url = url + self.bot = bot + } + } + public class Cons_inputKeyboardButtonUserProfile { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public var userId: Api.InputUser + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String, userId: Api.InputUser) { + self.flags = flags + self.style = style + self.text = text + self.userId = userId + } + } + public class Cons_keyboardButton { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String) { + self.flags = flags + self.style = style + self.text = text + } + } + public class Cons_keyboardButtonBuy { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String) { + self.flags = flags + self.style = style + self.text = text + } + } + public class Cons_keyboardButtonCallback { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public var data: Buffer + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String, data: Buffer) { + self.flags = flags + self.style = style + self.text = text + self.data = data + } + } + public class Cons_keyboardButtonCopy { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public var copyText: String + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String, copyText: String) { + self.flags = flags + self.style = style + self.text = text + self.copyText = copyText + } + } + public class Cons_keyboardButtonGame { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String) { + self.flags = flags + self.style = style + self.text = text + } + } + public class Cons_keyboardButtonRequestGeoLocation { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String) { + self.flags = flags + self.style = style + self.text = text + } + } + public class Cons_keyboardButtonRequestPeer { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public var buttonId: Int32 + public var peerType: Api.RequestPeerType + public var maxQuantity: Int32 + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String, buttonId: Int32, peerType: Api.RequestPeerType, maxQuantity: Int32) { + self.flags = flags + self.style = style + self.text = text + self.buttonId = buttonId + self.peerType = peerType + self.maxQuantity = maxQuantity + } + } + public class Cons_keyboardButtonRequestPhone { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String) { + self.flags = flags + self.style = style + self.text = text + } + } + public class Cons_keyboardButtonRequestPoll { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var quiz: Api.Bool? + public var text: String + public init(flags: Int32, style: Api.KeyboardButtonStyle?, quiz: Api.Bool?, text: String) { + self.flags = flags + self.style = style + self.quiz = quiz + self.text = text + } + } + public class Cons_keyboardButtonSimpleWebView { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public var url: String + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String, url: String) { + self.flags = flags + self.style = style + self.text = text + self.url = url + } + } + public class Cons_keyboardButtonSwitchInline { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public var query: String + public var peerTypes: [Api.InlineQueryPeerType]? + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String, query: String, peerTypes: [Api.InlineQueryPeerType]?) { + self.flags = flags + self.style = style + self.text = text + self.query = query + self.peerTypes = peerTypes + } + } + public class Cons_keyboardButtonUrl { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public var url: String + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String, url: String) { + self.flags = flags + self.style = style + self.text = text + self.url = url + } + } + public class Cons_keyboardButtonUrlAuth { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public var fwdText: String? + public var url: String + public var buttonId: Int32 + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String, fwdText: String?, url: String, buttonId: Int32) { + self.flags = flags + self.style = style + self.text = text + self.fwdText = fwdText + self.url = url + self.buttonId = buttonId + } + } + public class Cons_keyboardButtonUserProfile { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public var userId: Int64 + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String, userId: Int64) { + self.flags = flags + self.style = style + self.text = text + self.userId = userId + } + } + public class Cons_keyboardButtonWebView { + public var flags: Int32 + public var style: Api.KeyboardButtonStyle? + public var text: String + public var url: String + public init(flags: Int32, style: Api.KeyboardButtonStyle?, text: String, url: String) { + self.flags = flags + self.style = style + self.text = text + self.url = url + } + } + case inputKeyboardButtonRequestPeer(Cons_inputKeyboardButtonRequestPeer) + case inputKeyboardButtonUrlAuth(Cons_inputKeyboardButtonUrlAuth) + case inputKeyboardButtonUserProfile(Cons_inputKeyboardButtonUserProfile) + case keyboardButton(Cons_keyboardButton) + case keyboardButtonBuy(Cons_keyboardButtonBuy) + case keyboardButtonCallback(Cons_keyboardButtonCallback) + case keyboardButtonCopy(Cons_keyboardButtonCopy) + case keyboardButtonGame(Cons_keyboardButtonGame) + case keyboardButtonRequestGeoLocation(Cons_keyboardButtonRequestGeoLocation) + case keyboardButtonRequestPeer(Cons_keyboardButtonRequestPeer) + case keyboardButtonRequestPhone(Cons_keyboardButtonRequestPhone) + case keyboardButtonRequestPoll(Cons_keyboardButtonRequestPoll) + case keyboardButtonSimpleWebView(Cons_keyboardButtonSimpleWebView) + case keyboardButtonSwitchInline(Cons_keyboardButtonSwitchInline) + case keyboardButtonUrl(Cons_keyboardButtonUrl) + case keyboardButtonUrlAuth(Cons_keyboardButtonUrlAuth) + case keyboardButtonUserProfile(Cons_keyboardButtonUserProfile) + case keyboardButtonWebView(Cons_keyboardButtonWebView) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputKeyboardButtonRequestPeer(let _data): + if boxed { + buffer.appendInt32(45580630) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + serializeInt32(_data.buttonId, buffer: buffer, boxed: false) + _data.peerType.serialize(buffer, true) + serializeInt32(_data.maxQuantity, buffer: buffer, boxed: false) + break + case .inputKeyboardButtonUrlAuth(let _data): + if boxed { + buffer.appendInt32(1744911986) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.fwdText!, buffer: buffer, boxed: false) + } + serializeString(_data.url, buffer: buffer, boxed: false) + _data.bot.serialize(buffer, true) + break + case .inputKeyboardButtonUserProfile(let _data): + if boxed { + buffer.appendInt32(2103314375) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + _data.userId.serialize(buffer, true) + break + case .keyboardButton(let _data): + if boxed { + buffer.appendInt32(2098662655) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .keyboardButtonBuy(let _data): + if boxed { + buffer.appendInt32(1067792645) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .keyboardButtonCallback(let _data): + if boxed { + buffer.appendInt32(-433338016) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + serializeBytes(_data.data, buffer: buffer, boxed: false) + break + case .keyboardButtonCopy(let _data): + if boxed { + buffer.appendInt32(-1127960816) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + serializeString(_data.copyText, buffer: buffer, boxed: false) + break + case .keyboardButtonGame(let _data): + if boxed { + buffer.appendInt32(-1983540999) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .keyboardButtonRequestGeoLocation(let _data): + if boxed { + buffer.appendInt32(-1438582451) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .keyboardButtonRequestPeer(let _data): + if boxed { + buffer.appendInt32(1527715317) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + serializeInt32(_data.buttonId, buffer: buffer, boxed: false) + _data.peerType.serialize(buffer, true) + serializeInt32(_data.maxQuantity, buffer: buffer, boxed: false) + break + case .keyboardButtonRequestPhone(let _data): + if boxed { + buffer.appendInt32(1098841487) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .keyboardButtonRequestPoll(let _data): + if boxed { + buffer.appendInt32(2047989634) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.quiz!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .keyboardButtonSimpleWebView(let _data): + if boxed { + buffer.appendInt32(-514047120) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + break + case .keyboardButtonSwitchInline(let _data): + if boxed { + buffer.appendInt32(-1726768644) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + serializeString(_data.query, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.peerTypes!.count)) + for item in _data.peerTypes! { item.serialize(buffer, true) - }} - break - case .keyboardButtonUrl(let text, let url): - if boxed { - buffer.appendInt32(629866245) } - serializeString(text, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - break - case .keyboardButtonUrlAuth(let flags, let text, let fwdText, let url, let buttonId): - if boxed { - buffer.appendInt32(280464681) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(fwdText!, buffer: buffer, boxed: false)} - serializeString(url, buffer: buffer, boxed: false) - serializeInt32(buttonId, buffer: buffer, boxed: false) - break - case .keyboardButtonUserProfile(let text, let userId): - if boxed { - buffer.appendInt32(814112961) - } - serializeString(text, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - break - case .keyboardButtonWebView(let text, let url): - if boxed { - buffer.appendInt32(326529584) - } - serializeString(text, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputKeyboardButtonRequestPeer(let flags, let text, let buttonId, let peerType, let maxQuantity): - return ("inputKeyboardButtonRequestPeer", [("flags", flags as Any), ("text", text as Any), ("buttonId", buttonId as Any), ("peerType", peerType as Any), ("maxQuantity", maxQuantity as Any)]) - case .inputKeyboardButtonUrlAuth(let flags, let text, let fwdText, let url, let bot): - return ("inputKeyboardButtonUrlAuth", [("flags", flags as Any), ("text", text as Any), ("fwdText", fwdText as Any), ("url", url as Any), ("bot", bot as Any)]) - case .inputKeyboardButtonUserProfile(let text, let userId): - return ("inputKeyboardButtonUserProfile", [("text", text as Any), ("userId", userId as Any)]) - case .keyboardButton(let text): - return ("keyboardButton", [("text", text as Any)]) - case .keyboardButtonBuy(let text): - return ("keyboardButtonBuy", [("text", text as Any)]) - case .keyboardButtonCallback(let flags, let text, let data): - return ("keyboardButtonCallback", [("flags", flags as Any), ("text", text as Any), ("data", data as Any)]) - case .keyboardButtonCopy(let text, let copyText): - return ("keyboardButtonCopy", [("text", text as Any), ("copyText", copyText as Any)]) - case .keyboardButtonGame(let text): - return ("keyboardButtonGame", [("text", text as Any)]) - case .keyboardButtonRequestGeoLocation(let text): - return ("keyboardButtonRequestGeoLocation", [("text", text as Any)]) - case .keyboardButtonRequestPeer(let text, let buttonId, let peerType, let maxQuantity): - return ("keyboardButtonRequestPeer", [("text", text as Any), ("buttonId", buttonId as Any), ("peerType", peerType as Any), ("maxQuantity", maxQuantity as Any)]) - case .keyboardButtonRequestPhone(let text): - return ("keyboardButtonRequestPhone", [("text", text as Any)]) - case .keyboardButtonRequestPoll(let flags, let quiz, let text): - return ("keyboardButtonRequestPoll", [("flags", flags as Any), ("quiz", quiz as Any), ("text", text as Any)]) - case .keyboardButtonSimpleWebView(let text, let url): - return ("keyboardButtonSimpleWebView", [("text", text as Any), ("url", url as Any)]) - case .keyboardButtonSwitchInline(let flags, let text, let query, let peerTypes): - return ("keyboardButtonSwitchInline", [("flags", flags as Any), ("text", text as Any), ("query", query as Any), ("peerTypes", peerTypes as Any)]) - case .keyboardButtonUrl(let text, let url): - return ("keyboardButtonUrl", [("text", text as Any), ("url", url as Any)]) - case .keyboardButtonUrlAuth(let flags, let text, let fwdText, let url, let buttonId): - return ("keyboardButtonUrlAuth", [("flags", flags as Any), ("text", text as Any), ("fwdText", fwdText as Any), ("url", url as Any), ("buttonId", buttonId as Any)]) - case .keyboardButtonUserProfile(let text, let userId): - return ("keyboardButtonUserProfile", [("text", text as Any), ("userId", userId as Any)]) - case .keyboardButtonWebView(let text, let url): - return ("keyboardButtonWebView", [("text", text as Any), ("url", url as Any)]) - } - } - + } + break + case .keyboardButtonUrl(let _data): + if boxed { + buffer.appendInt32(-670292500) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + break + case .keyboardButtonUrlAuth(let _data): + if boxed { + buffer.appendInt32(-183499015) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.fwdText!, buffer: buffer, boxed: false) + } + serializeString(_data.url, buffer: buffer, boxed: false) + serializeInt32(_data.buttonId, buffer: buffer, boxed: false) + break + case .keyboardButtonUserProfile(let _data): + if boxed { + buffer.appendInt32(-1057137399) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + break + case .keyboardButtonWebView(let _data): + if boxed { + buffer.appendInt32(-398020192) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.style!.serialize(buffer, true) + } + serializeString(_data.text, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputKeyboardButtonRequestPeer(let _data): + return ("inputKeyboardButtonRequestPeer", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any), ("buttonId", _data.buttonId as Any), ("peerType", _data.peerType as Any), ("maxQuantity", _data.maxQuantity as Any)]) + case .inputKeyboardButtonUrlAuth(let _data): + return ("inputKeyboardButtonUrlAuth", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any), ("fwdText", _data.fwdText as Any), ("url", _data.url as Any), ("bot", _data.bot as Any)]) + case .inputKeyboardButtonUserProfile(let _data): + return ("inputKeyboardButtonUserProfile", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any), ("userId", _data.userId as Any)]) + case .keyboardButton(let _data): + return ("keyboardButton", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any)]) + case .keyboardButtonBuy(let _data): + return ("keyboardButtonBuy", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any)]) + case .keyboardButtonCallback(let _data): + return ("keyboardButtonCallback", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any), ("data", _data.data as Any)]) + case .keyboardButtonCopy(let _data): + return ("keyboardButtonCopy", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any), ("copyText", _data.copyText as Any)]) + case .keyboardButtonGame(let _data): + return ("keyboardButtonGame", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any)]) + case .keyboardButtonRequestGeoLocation(let _data): + return ("keyboardButtonRequestGeoLocation", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any)]) + case .keyboardButtonRequestPeer(let _data): + return ("keyboardButtonRequestPeer", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any), ("buttonId", _data.buttonId as Any), ("peerType", _data.peerType as Any), ("maxQuantity", _data.maxQuantity as Any)]) + case .keyboardButtonRequestPhone(let _data): + return ("keyboardButtonRequestPhone", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any)]) + case .keyboardButtonRequestPoll(let _data): + return ("keyboardButtonRequestPoll", [("flags", _data.flags as Any), ("style", _data.style as Any), ("quiz", _data.quiz as Any), ("text", _data.text as Any)]) + case .keyboardButtonSimpleWebView(let _data): + return ("keyboardButtonSimpleWebView", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any), ("url", _data.url as Any)]) + case .keyboardButtonSwitchInline(let _data): + return ("keyboardButtonSwitchInline", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any), ("query", _data.query as Any), ("peerTypes", _data.peerTypes as Any)]) + case .keyboardButtonUrl(let _data): + return ("keyboardButtonUrl", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any), ("url", _data.url as Any)]) + case .keyboardButtonUrlAuth(let _data): + return ("keyboardButtonUrlAuth", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any), ("fwdText", _data.fwdText as Any), ("url", _data.url as Any), ("buttonId", _data.buttonId as Any)]) + case .keyboardButtonUserProfile(let _data): + return ("keyboardButtonUserProfile", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any), ("userId", _data.userId as Any)]) + case .keyboardButtonWebView(let _data): + return ("keyboardButtonWebView", [("flags", _data.flags as Any), ("style", _data.style as Any), ("text", _data.text as Any), ("url", _data.url as Any)]) + } + } + public static func parse_inputKeyboardButtonRequestPeer(_ reader: BufferReader) -> KeyboardButton? { var _1: Int32? _1 = reader.readInt32() - var _2: String? - _2 = parseString(reader) - var _3: Int32? - _3 = reader.readInt32() - var _4: Api.RequestPeerType? - if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.RequestPeerType + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } } - var _5: Int32? - _5 = reader.readInt32() + var _3: String? + _3 = parseString(reader) + var _4: Int32? + _4 = reader.readInt32() + var _5: Api.RequestPeerType? + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.RequestPeerType + } + var _6: Int32? + _6 = reader.readInt32() let _c1 = _1 != nil - let _c2 = _2 != nil + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.KeyboardButton.inputKeyboardButtonRequestPeer(flags: _1!, text: _2!, buttonId: _3!, peerType: _4!, maxQuantity: _5!) + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.KeyboardButton.inputKeyboardButtonRequestPeer(Cons_inputKeyboardButtonRequestPeer(flags: _1!, style: _2, text: _3!, buttonId: _4!, peerType: _5!, maxQuantity: _6!)) + } + else { + return nil + } } public static func parse_inputKeyboardButtonUrlAuth(_ reader: BufferReader) -> KeyboardButton? { var _1: Int32? _1 = reader.readInt32() - var _2: String? - _2 = parseString(reader) + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } var _3: String? - if Int(_1!) & Int(1 << 1) != 0 {_3 = parseString(reader) } + _3 = parseString(reader) var _4: String? - _4 = parseString(reader) - var _5: Api.InputUser? + if Int(_1!) & Int(1 << 1) != 0 { + _4 = parseString(reader) + } + var _5: String? + _5 = parseString(reader) + var _6: Api.InputUser? if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.InputUser + _6 = Api.parse(reader, signature: signature) as? Api.InputUser } let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - let _c4 = _4 != nil + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.KeyboardButton.inputKeyboardButtonUrlAuth(flags: _1!, text: _2!, fwdText: _3, url: _4!, bot: _5!) + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.KeyboardButton.inputKeyboardButtonUrlAuth(Cons_inputKeyboardButtonUrlAuth(flags: _1!, style: _2, text: _3!, fwdText: _4, url: _5!, bot: _6!)) + } + else { + return nil + } } public static func parse_inputKeyboardButtonUserProfile(_ reader: BufferReader) -> KeyboardButton? { - var _1: String? - _1 = parseString(reader) - var _2: Api.InputUser? + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } + var _3: String? + _3 = parseString(reader) + var _4: Api.InputUser? if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.InputUser + _4 = Api.parse(reader, signature: signature) as? Api.InputUser } let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.KeyboardButton.inputKeyboardButtonUserProfile(text: _1!, userId: _2!) + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.KeyboardButton.inputKeyboardButtonUserProfile(Cons_inputKeyboardButtonUserProfile(flags: _1!, style: _2, text: _3!, userId: _4!)) + } + else { + return nil + } } public static func parse_keyboardButton(_ reader: BufferReader) -> KeyboardButton? { - var _1: String? - _1 = parseString(reader) + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } + var _3: String? + _3 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.KeyboardButton.keyboardButton(text: _1!) + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.KeyboardButton.keyboardButton(Cons_keyboardButton(flags: _1!, style: _2, text: _3!)) + } + else { + return nil + } } public static func parse_keyboardButtonBuy(_ reader: BufferReader) -> KeyboardButton? { - var _1: String? - _1 = parseString(reader) + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } + var _3: String? + _3 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.KeyboardButton.keyboardButtonBuy(text: _1!) + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.KeyboardButton.keyboardButtonBuy(Cons_keyboardButtonBuy(flags: _1!, style: _2, text: _3!)) + } + else { + return nil + } } public static func parse_keyboardButtonCallback(_ reader: BufferReader) -> KeyboardButton? { var _1: Int32? _1 = reader.readInt32() - var _2: String? - _2 = parseString(reader) - var _3: Buffer? - _3 = parseBytes(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.KeyboardButton.keyboardButtonCallback(flags: _1!, text: _2!, data: _3!) - } - public static func parse_keyboardButtonCopy(_ reader: BufferReader) -> KeyboardButton? { - var _1: String? - _1 = parseString(reader) - var _2: String? - _2 = parseString(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.KeyboardButton.keyboardButtonCopy(text: _1!, copyText: _2!) - } - public static func parse_keyboardButtonGame(_ reader: BufferReader) -> KeyboardButton? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.KeyboardButton.keyboardButtonGame(text: _1!) - } - public static func parse_keyboardButtonRequestGeoLocation(_ reader: BufferReader) -> KeyboardButton? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.KeyboardButton.keyboardButtonRequestGeoLocation(text: _1!) - } - public static func parse_keyboardButtonRequestPeer(_ reader: BufferReader) -> KeyboardButton? { - var _1: String? - _1 = parseString(reader) - var _2: Int32? - _2 = reader.readInt32() - var _3: Api.RequestPeerType? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.RequestPeerType + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } } - var _4: Int32? - _4 = reader.readInt32() + var _3: String? + _3 = parseString(reader) + var _4: Buffer? + _4 = parseBytes(reader) let _c1 = _1 != nil - let _c2 = _2 != nil + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.KeyboardButton.keyboardButtonRequestPeer(text: _1!, buttonId: _2!, peerType: _3!, maxQuantity: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.KeyboardButton.keyboardButtonCallback(Cons_keyboardButtonCallback(flags: _1!, style: _2, text: _3!, data: _4!)) + } + else { + return nil + } + } + public static func parse_keyboardButtonCopy(_ reader: BufferReader) -> KeyboardButton? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } + var _3: String? + _3 = parseString(reader) + var _4: String? + _4 = parseString(reader) + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.KeyboardButton.keyboardButtonCopy(Cons_keyboardButtonCopy(flags: _1!, style: _2, text: _3!, copyText: _4!)) + } + else { + return nil + } + } + public static func parse_keyboardButtonGame(_ reader: BufferReader) -> KeyboardButton? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } + var _3: String? + _3 = parseString(reader) + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.KeyboardButton.keyboardButtonGame(Cons_keyboardButtonGame(flags: _1!, style: _2, text: _3!)) + } + else { + return nil + } + } + public static func parse_keyboardButtonRequestGeoLocation(_ reader: BufferReader) -> KeyboardButton? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } + var _3: String? + _3 = parseString(reader) + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.KeyboardButton.keyboardButtonRequestGeoLocation(Cons_keyboardButtonRequestGeoLocation(flags: _1!, style: _2, text: _3!)) + } + else { + return nil + } + } + public static func parse_keyboardButtonRequestPeer(_ reader: BufferReader) -> KeyboardButton? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } + var _3: String? + _3 = parseString(reader) + var _4: Int32? + _4 = reader.readInt32() + var _5: Api.RequestPeerType? + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.RequestPeerType + } + var _6: Int32? + _6 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.KeyboardButton.keyboardButtonRequestPeer(Cons_keyboardButtonRequestPeer(flags: _1!, style: _2, text: _3!, buttonId: _4!, peerType: _5!, maxQuantity: _6!)) + } + else { + return nil + } } public static func parse_keyboardButtonRequestPhone(_ reader: BufferReader) -> KeyboardButton? { - var _1: String? - _1 = parseString(reader) + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } + var _3: String? + _3 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.KeyboardButton.keyboardButtonRequestPhone(text: _1!) + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.KeyboardButton.keyboardButtonRequestPhone(Cons_keyboardButtonRequestPhone(flags: _1!, style: _2, text: _3!)) + } + else { + return nil + } } public static func parse_keyboardButtonRequestPoll(_ reader: BufferReader) -> KeyboardButton? { var _1: Int32? _1 = reader.readInt32() - var _2: Api.Bool? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Bool - } } - var _3: String? - _3 = parseString(reader) + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } + var _3: Api.Bool? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Bool + } + } + var _4: String? + _4 = parseString(reader) let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.KeyboardButton.keyboardButtonRequestPoll(flags: _1!, quiz: _2, text: _3!) + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.KeyboardButton.keyboardButtonRequestPoll(Cons_keyboardButtonRequestPoll(flags: _1!, style: _2, quiz: _3, text: _4!)) + } + else { + return nil + } } public static func parse_keyboardButtonSimpleWebView(_ reader: BufferReader) -> KeyboardButton? { - var _1: String? - _1 = parseString(reader) - var _2: String? - _2 = parseString(reader) + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } + var _3: String? + _3 = parseString(reader) + var _4: String? + _4 = parseString(reader) let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.KeyboardButton.keyboardButtonSimpleWebView(text: _1!, url: _2!) + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.KeyboardButton.keyboardButtonSimpleWebView(Cons_keyboardButtonSimpleWebView(flags: _1!, style: _2, text: _3!, url: _4!)) + } + else { + return nil + } } public static func parse_keyboardButtonSwitchInline(_ reader: BufferReader) -> KeyboardButton? { var _1: Int32? _1 = reader.readInt32() - var _2: String? - _2 = parseString(reader) + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } var _3: String? _3 = parseString(reader) - var _4: [Api.InlineQueryPeerType]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InlineQueryPeerType.self) - } } + var _4: String? + _4 = parseString(reader) + var _5: [Api.InlineQueryPeerType]? + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InlineQueryPeerType.self) + } + } let _c1 = _1 != nil - let _c2 = _2 != nil + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.KeyboardButton.keyboardButtonSwitchInline(flags: _1!, text: _2!, query: _3!, peerTypes: _4) + let _c4 = _4 != nil + let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.KeyboardButton.keyboardButtonSwitchInline(Cons_keyboardButtonSwitchInline(flags: _1!, style: _2, text: _3!, query: _4!, peerTypes: _5)) + } + else { + return nil + } } public static func parse_keyboardButtonUrl(_ reader: BufferReader) -> KeyboardButton? { - var _1: String? - _1 = parseString(reader) - var _2: String? - _2 = parseString(reader) + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } + var _3: String? + _3 = parseString(reader) + var _4: String? + _4 = parseString(reader) let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.KeyboardButton.keyboardButtonUrl(text: _1!, url: _2!) + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.KeyboardButton.keyboardButtonUrl(Cons_keyboardButtonUrl(flags: _1!, style: _2, text: _3!, url: _4!)) + } + else { + return nil + } } public static func parse_keyboardButtonUrlAuth(_ reader: BufferReader) -> KeyboardButton? { var _1: Int32? _1 = reader.readInt32() - var _2: String? - _2 = parseString(reader) + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } var _3: String? - if Int(_1!) & Int(1 << 0) != 0 {_3 = parseString(reader) } + _3 = parseString(reader) var _4: String? - _4 = parseString(reader) - var _5: Int32? - _5 = reader.readInt32() + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) + } + var _5: String? + _5 = parseString(reader) + var _6: Int32? + _6 = reader.readInt32() let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - let _c4 = _4 != nil + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.KeyboardButton.keyboardButtonUrlAuth(flags: _1!, text: _2!, fwdText: _3, url: _4!, buttonId: _5!) + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.KeyboardButton.keyboardButtonUrlAuth(Cons_keyboardButtonUrlAuth(flags: _1!, style: _2, text: _3!, fwdText: _4, url: _5!, buttonId: _6!)) + } + else { + return nil + } } public static func parse_keyboardButtonUserProfile(_ reader: BufferReader) -> KeyboardButton? { - var _1: String? - _1 = parseString(reader) - var _2: Int64? - _2 = reader.readInt64() + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } + var _3: String? + _3 = parseString(reader) + var _4: Int64? + _4 = reader.readInt64() let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.KeyboardButton.keyboardButtonUserProfile(text: _1!, userId: _2!) + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.KeyboardButton.keyboardButtonUserProfile(Cons_keyboardButtonUserProfile(flags: _1!, style: _2, text: _3!, userId: _4!)) + } + else { + return nil + } } public static func parse_keyboardButtonWebView(_ reader: BufferReader) -> KeyboardButton? { - var _1: String? - _1 = parseString(reader) - var _2: String? - _2 = parseString(reader) + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.KeyboardButtonStyle? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.KeyboardButtonStyle + } + } + var _3: String? + _3 = parseString(reader) + var _4: String? + _4 = parseString(reader) let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.KeyboardButton.keyboardButtonWebView(text: _1!, url: _2!) + let _c2 = (Int(_1!) & Int(1 << 10) == 0) || _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.KeyboardButton.keyboardButtonWebView(Cons_keyboardButtonWebView(flags: _1!, style: _2, text: _3!, url: _4!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api15.swift b/submodules/TelegramApi/Sources/Api15.swift index 6b606c80..494d5df7 100644 --- a/submodules/TelegramApi/Sources/Api15.swift +++ b/submodules/TelegramApi/Sources/Api15.swift @@ -1,64 +1,132 @@ public extension Api { enum KeyboardButtonRow: TypeConstructorDescription { - case keyboardButtonRow(buttons: [Api.KeyboardButton]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .keyboardButtonRow(let buttons): - if boxed { - buffer.appendInt32(2002815875) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(buttons.count)) - for item in buttons { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .keyboardButtonRow(let buttons): - return ("keyboardButtonRow", [("buttons", buttons as Any)]) - } - } - + public class Cons_keyboardButtonRow { + public var buttons: [Api.KeyboardButton] + public init(buttons: [Api.KeyboardButton]) { + self.buttons = buttons + } + } + case keyboardButtonRow(Cons_keyboardButtonRow) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .keyboardButtonRow(let _data): + if boxed { + buffer.appendInt32(2002815875) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.buttons.count)) + for item in _data.buttons { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .keyboardButtonRow(let _data): + return ("keyboardButtonRow", [("buttons", _data.buttons as Any)]) + } + } + public static func parse_keyboardButtonRow(_ reader: BufferReader) -> KeyboardButtonRow? { var _1: [Api.KeyboardButton]? if let _ = reader.readInt32() { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.KeyboardButton.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.KeyboardButtonRow.keyboardButtonRow(buttons: _1!) + if _c1 { + return Api.KeyboardButtonRow.keyboardButtonRow(Cons_keyboardButtonRow(buttons: _1!)) + } + else { + return nil + } + } + } +} +public extension Api { + enum KeyboardButtonStyle: TypeConstructorDescription { + public class Cons_keyboardButtonStyle { + public var flags: Int32 + public var icon: Int64? + public init(flags: Int32, icon: Int64?) { + self.flags = flags + self.icon = icon + } + } + case keyboardButtonStyle(Cons_keyboardButtonStyle) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .keyboardButtonStyle(let _data): + if boxed { + buffer.appendInt32(1339896880) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt64(_data.icon!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .keyboardButtonStyle(let _data): + return ("keyboardButtonStyle", [("flags", _data.flags as Any), ("icon", _data.icon as Any)]) + } + } + + public static func parse_keyboardButtonStyle(_ reader: BufferReader) -> KeyboardButtonStyle? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + if Int(_1!) & Int(1 << 3) != 0 { + _2 = reader.readInt64() + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 3) == 0) || _2 != nil + if _c1 && _c2 { + return Api.KeyboardButtonStyle.keyboardButtonStyle(Cons_keyboardButtonStyle(flags: _1!, icon: _2)) + } + else { + return nil + } } - } } public extension Api { enum LabeledPrice: TypeConstructorDescription { - case labeledPrice(label: String, amount: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .labeledPrice(let label, let amount): - if boxed { - buffer.appendInt32(-886477832) - } - serializeString(label, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .labeledPrice(let label, let amount): - return ("labeledPrice", [("label", label as Any), ("amount", amount as Any)]) - } - } - + public class Cons_labeledPrice { + public var label: String + public var amount: Int64 + public init(label: String, amount: Int64) { + self.label = label + self.amount = amount + } + } + case labeledPrice(Cons_labeledPrice) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .labeledPrice(let _data): + if boxed { + buffer.appendInt32(-886477832) + } + serializeString(_data.label, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .labeledPrice(let _data): + return ("labeledPrice", [("label", _data.label as Any), ("amount", _data.amount as Any)]) + } + } + public static func parse_labeledPrice(_ reader: BufferReader) -> LabeledPrice? { var _1: String? _1 = parseString(reader) @@ -66,42 +134,56 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.LabeledPrice.labeledPrice(label: _1!, amount: _2!) + if _c1 && _c2 { + return Api.LabeledPrice.labeledPrice(Cons_labeledPrice(label: _1!, amount: _2!)) + } + else { + return nil + } } - } } public extension Api { enum LangPackDifference: TypeConstructorDescription { - case langPackDifference(langCode: String, fromVersion: Int32, version: Int32, strings: [Api.LangPackString]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .langPackDifference(let langCode, let fromVersion, let version, let strings): - if boxed { - buffer.appendInt32(-209337866) - } - serializeString(langCode, buffer: buffer, boxed: false) - serializeInt32(fromVersion, buffer: buffer, boxed: false) - serializeInt32(version, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(strings.count)) - for item in strings { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .langPackDifference(let langCode, let fromVersion, let version, let strings): - return ("langPackDifference", [("langCode", langCode as Any), ("fromVersion", fromVersion as Any), ("version", version as Any), ("strings", strings as Any)]) - } - } - + public class Cons_langPackDifference { + public var langCode: String + public var fromVersion: Int32 + public var version: Int32 + public var strings: [Api.LangPackString] + public init(langCode: String, fromVersion: Int32, version: Int32, strings: [Api.LangPackString]) { + self.langCode = langCode + self.fromVersion = fromVersion + self.version = version + self.strings = strings + } + } + case langPackDifference(Cons_langPackDifference) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .langPackDifference(let _data): + if boxed { + buffer.appendInt32(-209337866) + } + serializeString(_data.langCode, buffer: buffer, boxed: false) + serializeInt32(_data.fromVersion, buffer: buffer, boxed: false) + serializeInt32(_data.version, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.strings.count)) + for item in _data.strings { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .langPackDifference(let _data): + return ("langPackDifference", [("langCode", _data.langCode as Any), ("fromVersion", _data.fromVersion as Any), ("version", _data.version as Any), ("strings", _data.strings as Any)]) + } + } + public static func parse_langPackDifference(_ reader: BufferReader) -> LangPackDifference? { var _1: String? _1 = parseString(reader) @@ -117,45 +199,69 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.LangPackDifference.langPackDifference(langCode: _1!, fromVersion: _2!, version: _3!, strings: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.LangPackDifference.langPackDifference(Cons_langPackDifference(langCode: _1!, fromVersion: _2!, version: _3!, strings: _4!)) + } + else { + return nil + } } - } } public extension Api { enum LangPackLanguage: TypeConstructorDescription { - case langPackLanguage(flags: Int32, name: String, nativeName: String, langCode: String, baseLangCode: String?, pluralCode: String, stringsCount: Int32, translatedCount: Int32, translationsUrl: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .langPackLanguage(let flags, let name, let nativeName, let langCode, let baseLangCode, let pluralCode, let stringsCount, let translatedCount, let translationsUrl): - if boxed { - buffer.appendInt32(-288727837) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(name, buffer: buffer, boxed: false) - serializeString(nativeName, buffer: buffer, boxed: false) - serializeString(langCode, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeString(baseLangCode!, buffer: buffer, boxed: false)} - serializeString(pluralCode, buffer: buffer, boxed: false) - serializeInt32(stringsCount, buffer: buffer, boxed: false) - serializeInt32(translatedCount, buffer: buffer, boxed: false) - serializeString(translationsUrl, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .langPackLanguage(let flags, let name, let nativeName, let langCode, let baseLangCode, let pluralCode, let stringsCount, let translatedCount, let translationsUrl): - return ("langPackLanguage", [("flags", flags as Any), ("name", name as Any), ("nativeName", nativeName as Any), ("langCode", langCode as Any), ("baseLangCode", baseLangCode as Any), ("pluralCode", pluralCode as Any), ("stringsCount", stringsCount as Any), ("translatedCount", translatedCount as Any), ("translationsUrl", translationsUrl as Any)]) - } - } - + public class Cons_langPackLanguage { + public var flags: Int32 + public var name: String + public var nativeName: String + public var langCode: String + public var baseLangCode: String? + public var pluralCode: String + public var stringsCount: Int32 + public var translatedCount: Int32 + public var translationsUrl: String + public init(flags: Int32, name: String, nativeName: String, langCode: String, baseLangCode: String?, pluralCode: String, stringsCount: Int32, translatedCount: Int32, translationsUrl: String) { + self.flags = flags + self.name = name + self.nativeName = nativeName + self.langCode = langCode + self.baseLangCode = baseLangCode + self.pluralCode = pluralCode + self.stringsCount = stringsCount + self.translatedCount = translatedCount + self.translationsUrl = translationsUrl + } + } + case langPackLanguage(Cons_langPackLanguage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .langPackLanguage(let _data): + if boxed { + buffer.appendInt32(-288727837) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.name, buffer: buffer, boxed: false) + serializeString(_data.nativeName, buffer: buffer, boxed: false) + serializeString(_data.langCode, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.baseLangCode!, buffer: buffer, boxed: false) + } + serializeString(_data.pluralCode, buffer: buffer, boxed: false) + serializeInt32(_data.stringsCount, buffer: buffer, boxed: false) + serializeInt32(_data.translatedCount, buffer: buffer, boxed: false) + serializeString(_data.translationsUrl, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .langPackLanguage(let _data): + return ("langPackLanguage", [("flags", _data.flags as Any), ("name", _data.name as Any), ("nativeName", _data.nativeName as Any), ("langCode", _data.langCode as Any), ("baseLangCode", _data.baseLangCode as Any), ("pluralCode", _data.pluralCode as Any), ("stringsCount", _data.stringsCount as Any), ("translatedCount", _data.translatedCount as Any), ("translationsUrl", _data.translationsUrl as Any)]) + } + } + public static func parse_langPackLanguage(_ reader: BufferReader) -> LangPackLanguage? { var _1: Int32? _1 = reader.readInt32() @@ -166,7 +272,9 @@ public extension Api { var _4: String? _4 = parseString(reader) var _5: String? - if Int(_1!) & Int(1 << 1) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _5 = parseString(reader) + } var _6: String? _6 = parseString(reader) var _7: Int32? @@ -184,68 +292,107 @@ public extension Api { let _c7 = _7 != nil let _c8 = _8 != nil let _c9 = _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.LangPackLanguage.langPackLanguage(flags: _1!, name: _2!, nativeName: _3!, langCode: _4!, baseLangCode: _5, pluralCode: _6!, stringsCount: _7!, translatedCount: _8!, translationsUrl: _9!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.LangPackLanguage.langPackLanguage(Cons_langPackLanguage(flags: _1!, name: _2!, nativeName: _3!, langCode: _4!, baseLangCode: _5, pluralCode: _6!, stringsCount: _7!, translatedCount: _8!, translationsUrl: _9!)) + } + else { + return nil + } } - } } public extension Api { enum LangPackString: TypeConstructorDescription { - case langPackString(key: String, value: String) - case langPackStringDeleted(key: String) - case langPackStringPluralized(flags: Int32, key: String, zeroValue: String?, oneValue: String?, twoValue: String?, fewValue: String?, manyValue: String?, otherValue: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .langPackString(let key, let value): - if boxed { - buffer.appendInt32(-892239370) - } - serializeString(key, buffer: buffer, boxed: false) - serializeString(value, buffer: buffer, boxed: false) - break - case .langPackStringDeleted(let key): - if boxed { - buffer.appendInt32(695856818) - } - serializeString(key, buffer: buffer, boxed: false) - break - case .langPackStringPluralized(let flags, let key, let zeroValue, let oneValue, let twoValue, let fewValue, let manyValue, let otherValue): - if boxed { - buffer.appendInt32(1816636575) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(key, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(zeroValue!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(oneValue!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(twoValue!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeString(fewValue!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeString(manyValue!, buffer: buffer, boxed: false)} - serializeString(otherValue, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .langPackString(let key, let value): - return ("langPackString", [("key", key as Any), ("value", value as Any)]) - case .langPackStringDeleted(let key): - return ("langPackStringDeleted", [("key", key as Any)]) - case .langPackStringPluralized(let flags, let key, let zeroValue, let oneValue, let twoValue, let fewValue, let manyValue, let otherValue): - return ("langPackStringPluralized", [("flags", flags as Any), ("key", key as Any), ("zeroValue", zeroValue as Any), ("oneValue", oneValue as Any), ("twoValue", twoValue as Any), ("fewValue", fewValue as Any), ("manyValue", manyValue as Any), ("otherValue", otherValue as Any)]) - } - } - + public class Cons_langPackString { + public var key: String + public var value: String + public init(key: String, value: String) { + self.key = key + self.value = value + } + } + public class Cons_langPackStringDeleted { + public var key: String + public init(key: String) { + self.key = key + } + } + public class Cons_langPackStringPluralized { + public var flags: Int32 + public var key: String + public var zeroValue: String? + public var oneValue: String? + public var twoValue: String? + public var fewValue: String? + public var manyValue: String? + public var otherValue: String + public init(flags: Int32, key: String, zeroValue: String?, oneValue: String?, twoValue: String?, fewValue: String?, manyValue: String?, otherValue: String) { + self.flags = flags + self.key = key + self.zeroValue = zeroValue + self.oneValue = oneValue + self.twoValue = twoValue + self.fewValue = fewValue + self.manyValue = manyValue + self.otherValue = otherValue + } + } + case langPackString(Cons_langPackString) + case langPackStringDeleted(Cons_langPackStringDeleted) + case langPackStringPluralized(Cons_langPackStringPluralized) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .langPackString(let _data): + if boxed { + buffer.appendInt32(-892239370) + } + serializeString(_data.key, buffer: buffer, boxed: false) + serializeString(_data.value, buffer: buffer, boxed: false) + break + case .langPackStringDeleted(let _data): + if boxed { + buffer.appendInt32(695856818) + } + serializeString(_data.key, buffer: buffer, boxed: false) + break + case .langPackStringPluralized(let _data): + if boxed { + buffer.appendInt32(1816636575) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.key, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.zeroValue!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.oneValue!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.twoValue!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.fewValue!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeString(_data.manyValue!, buffer: buffer, boxed: false) + } + serializeString(_data.otherValue, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .langPackString(let _data): + return ("langPackString", [("key", _data.key as Any), ("value", _data.value as Any)]) + case .langPackStringDeleted(let _data): + return ("langPackStringDeleted", [("key", _data.key as Any)]) + case .langPackStringPluralized(let _data): + return ("langPackStringPluralized", [("flags", _data.flags as Any), ("key", _data.key as Any), ("zeroValue", _data.zeroValue as Any), ("oneValue", _data.oneValue as Any), ("twoValue", _data.twoValue as Any), ("fewValue", _data.fewValue as Any), ("manyValue", _data.manyValue as Any), ("otherValue", _data.otherValue as Any)]) + } + } + public static func parse_langPackString(_ reader: BufferReader) -> LangPackString? { var _1: String? _1 = parseString(reader) @@ -253,16 +400,23 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.LangPackString.langPackString(key: _1!, value: _2!) + if _c1 && _c2 { + return Api.LangPackString.langPackString(Cons_langPackString(key: _1!, value: _2!)) + } + else { + return nil + } } public static func parse_langPackStringDeleted(_ reader: BufferReader) -> LangPackString? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.LangPackString.langPackStringDeleted(key: _1!) + if _c1 { + return Api.LangPackString.langPackStringDeleted(Cons_langPackStringDeleted(key: _1!)) + } + else { + return nil + } } public static func parse_langPackStringPluralized(_ reader: BufferReader) -> LangPackString? { var _1: Int32? @@ -270,15 +424,25 @@ public extension Api { var _2: String? _2 = parseString(reader) var _3: String? - if Int(_1!) & Int(1 << 0) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = parseString(reader) + } var _4: String? - if Int(_1!) & Int(1 << 1) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = parseString(reader) + } var _5: String? - if Int(_1!) & Int(1 << 2) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _5 = parseString(reader) + } var _6: String? - if Int(_1!) & Int(1 << 3) != 0 {_6 = parseString(reader) } + if Int(_1!) & Int(1 << 3) != 0 { + _6 = parseString(reader) + } var _7: String? - if Int(_1!) & Int(1 << 4) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 4) != 0 { + _7 = parseString(reader) + } var _8: String? _8 = parseString(reader) let _c1 = _1 != nil @@ -289,44 +453,52 @@ public extension Api { let _c6 = (Int(_1!) & Int(1 << 3) == 0) || _6 != nil let _c7 = (Int(_1!) & Int(1 << 4) == 0) || _7 != nil let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.LangPackString.langPackStringPluralized(flags: _1!, key: _2!, zeroValue: _3, oneValue: _4, twoValue: _5, fewValue: _6, manyValue: _7, otherValue: _8!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.LangPackString.langPackStringPluralized(Cons_langPackStringPluralized(flags: _1!, key: _2!, zeroValue: _3, oneValue: _4, twoValue: _5, fewValue: _6, manyValue: _7, otherValue: _8!)) + } + else { + return nil + } } - } } public extension Api { enum MaskCoords: TypeConstructorDescription { - case maskCoords(n: Int32, x: Double, y: Double, zoom: Double) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .maskCoords(let n, let x, let y, let zoom): - if boxed { - buffer.appendInt32(-1361650766) - } - serializeInt32(n, buffer: buffer, boxed: false) - serializeDouble(x, buffer: buffer, boxed: false) - serializeDouble(y, buffer: buffer, boxed: false) - serializeDouble(zoom, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .maskCoords(let n, let x, let y, let zoom): - return ("maskCoords", [("n", n as Any), ("x", x as Any), ("y", y as Any), ("zoom", zoom as Any)]) - } - } - + public class Cons_maskCoords { + public var n: Int32 + public var x: Double + public var y: Double + public var zoom: Double + public init(n: Int32, x: Double, y: Double, zoom: Double) { + self.n = n + self.x = x + self.y = y + self.zoom = zoom + } + } + case maskCoords(Cons_maskCoords) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .maskCoords(let _data): + if boxed { + buffer.appendInt32(-1361650766) + } + serializeInt32(_data.n, buffer: buffer, boxed: false) + serializeDouble(_data.x, buffer: buffer, boxed: false) + serializeDouble(_data.y, buffer: buffer, boxed: false) + serializeDouble(_data.zoom, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .maskCoords(let _data): + return ("maskCoords", [("n", _data.n as Any), ("x", _data.x as Any), ("y", _data.y as Any), ("zoom", _data.zoom as Any)]) + } + } + public static func parse_maskCoords(_ reader: BufferReader) -> MaskCoords? { var _1: Int32? _1 = reader.readInt32() @@ -340,131 +512,231 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.MaskCoords.maskCoords(n: _1!, x: _2!, y: _3!, zoom: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.MaskCoords.maskCoords(Cons_maskCoords(n: _1!, x: _2!, y: _3!, zoom: _4!)) + } + else { + return nil + } } - } } public extension Api { indirect enum MediaArea: TypeConstructorDescription { - case inputMediaAreaChannelPost(coordinates: Api.MediaAreaCoordinates, channel: Api.InputChannel, msgId: Int32) - case inputMediaAreaVenue(coordinates: Api.MediaAreaCoordinates, queryId: Int64, resultId: String) - case mediaAreaChannelPost(coordinates: Api.MediaAreaCoordinates, channelId: Int64, msgId: Int32) - case mediaAreaGeoPoint(flags: Int32, coordinates: Api.MediaAreaCoordinates, geo: Api.GeoPoint, address: Api.GeoPointAddress?) - case mediaAreaStarGift(coordinates: Api.MediaAreaCoordinates, slug: String) - case mediaAreaSuggestedReaction(flags: Int32, coordinates: Api.MediaAreaCoordinates, reaction: Api.Reaction) - case mediaAreaUrl(coordinates: Api.MediaAreaCoordinates, url: String) - case mediaAreaVenue(coordinates: Api.MediaAreaCoordinates, geo: Api.GeoPoint, title: String, address: String, provider: String, venueId: String, venueType: String) - case mediaAreaWeather(coordinates: Api.MediaAreaCoordinates, emoji: String, temperatureC: Double, color: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputMediaAreaChannelPost(let coordinates, let channel, let msgId): - if boxed { - buffer.appendInt32(577893055) - } - coordinates.serialize(buffer, true) - channel.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - break - case .inputMediaAreaVenue(let coordinates, let queryId, let resultId): - if boxed { - buffer.appendInt32(-1300094593) - } - coordinates.serialize(buffer, true) - serializeInt64(queryId, buffer: buffer, boxed: false) - serializeString(resultId, buffer: buffer, boxed: false) - break - case .mediaAreaChannelPost(let coordinates, let channelId, let msgId): - if boxed { - buffer.appendInt32(1996756655) - } - coordinates.serialize(buffer, true) - serializeInt64(channelId, buffer: buffer, boxed: false) - serializeInt32(msgId, buffer: buffer, boxed: false) - break - case .mediaAreaGeoPoint(let flags, let coordinates, let geo, let address): - if boxed { - buffer.appendInt32(-891992787) - } - serializeInt32(flags, buffer: buffer, boxed: false) - coordinates.serialize(buffer, true) - geo.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {address!.serialize(buffer, true)} - break - case .mediaAreaStarGift(let coordinates, let slug): - if boxed { - buffer.appendInt32(1468491885) - } - coordinates.serialize(buffer, true) - serializeString(slug, buffer: buffer, boxed: false) - break - case .mediaAreaSuggestedReaction(let flags, let coordinates, let reaction): - if boxed { - buffer.appendInt32(340088945) - } - serializeInt32(flags, buffer: buffer, boxed: false) - coordinates.serialize(buffer, true) - reaction.serialize(buffer, true) - break - case .mediaAreaUrl(let coordinates, let url): - if boxed { - buffer.appendInt32(926421125) - } - coordinates.serialize(buffer, true) - serializeString(url, buffer: buffer, boxed: false) - break - case .mediaAreaVenue(let coordinates, let geo, let title, let address, let provider, let venueId, let venueType): - if boxed { - buffer.appendInt32(-1098720356) - } - coordinates.serialize(buffer, true) - geo.serialize(buffer, true) - serializeString(title, buffer: buffer, boxed: false) - serializeString(address, buffer: buffer, boxed: false) - serializeString(provider, buffer: buffer, boxed: false) - serializeString(venueId, buffer: buffer, boxed: false) - serializeString(venueType, buffer: buffer, boxed: false) - break - case .mediaAreaWeather(let coordinates, let emoji, let temperatureC, let color): - if boxed { - buffer.appendInt32(1235637404) - } - coordinates.serialize(buffer, true) - serializeString(emoji, buffer: buffer, boxed: false) - serializeDouble(temperatureC, buffer: buffer, boxed: false) - serializeInt32(color, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputMediaAreaChannelPost(let coordinates, let channel, let msgId): - return ("inputMediaAreaChannelPost", [("coordinates", coordinates as Any), ("channel", channel as Any), ("msgId", msgId as Any)]) - case .inputMediaAreaVenue(let coordinates, let queryId, let resultId): - return ("inputMediaAreaVenue", [("coordinates", coordinates as Any), ("queryId", queryId as Any), ("resultId", resultId as Any)]) - case .mediaAreaChannelPost(let coordinates, let channelId, let msgId): - return ("mediaAreaChannelPost", [("coordinates", coordinates as Any), ("channelId", channelId as Any), ("msgId", msgId as Any)]) - case .mediaAreaGeoPoint(let flags, let coordinates, let geo, let address): - return ("mediaAreaGeoPoint", [("flags", flags as Any), ("coordinates", coordinates as Any), ("geo", geo as Any), ("address", address as Any)]) - case .mediaAreaStarGift(let coordinates, let slug): - return ("mediaAreaStarGift", [("coordinates", coordinates as Any), ("slug", slug as Any)]) - case .mediaAreaSuggestedReaction(let flags, let coordinates, let reaction): - return ("mediaAreaSuggestedReaction", [("flags", flags as Any), ("coordinates", coordinates as Any), ("reaction", reaction as Any)]) - case .mediaAreaUrl(let coordinates, let url): - return ("mediaAreaUrl", [("coordinates", coordinates as Any), ("url", url as Any)]) - case .mediaAreaVenue(let coordinates, let geo, let title, let address, let provider, let venueId, let venueType): - return ("mediaAreaVenue", [("coordinates", coordinates as Any), ("geo", geo as Any), ("title", title as Any), ("address", address as Any), ("provider", provider as Any), ("venueId", venueId as Any), ("venueType", venueType as Any)]) - case .mediaAreaWeather(let coordinates, let emoji, let temperatureC, let color): - return ("mediaAreaWeather", [("coordinates", coordinates as Any), ("emoji", emoji as Any), ("temperatureC", temperatureC as Any), ("color", color as Any)]) - } - } - + public class Cons_inputMediaAreaChannelPost { + public var coordinates: Api.MediaAreaCoordinates + public var channel: Api.InputChannel + public var msgId: Int32 + public init(coordinates: Api.MediaAreaCoordinates, channel: Api.InputChannel, msgId: Int32) { + self.coordinates = coordinates + self.channel = channel + self.msgId = msgId + } + } + public class Cons_inputMediaAreaVenue { + public var coordinates: Api.MediaAreaCoordinates + public var queryId: Int64 + public var resultId: String + public init(coordinates: Api.MediaAreaCoordinates, queryId: Int64, resultId: String) { + self.coordinates = coordinates + self.queryId = queryId + self.resultId = resultId + } + } + public class Cons_mediaAreaChannelPost { + public var coordinates: Api.MediaAreaCoordinates + public var channelId: Int64 + public var msgId: Int32 + public init(coordinates: Api.MediaAreaCoordinates, channelId: Int64, msgId: Int32) { + self.coordinates = coordinates + self.channelId = channelId + self.msgId = msgId + } + } + public class Cons_mediaAreaGeoPoint { + public var flags: Int32 + public var coordinates: Api.MediaAreaCoordinates + public var geo: Api.GeoPoint + public var address: Api.GeoPointAddress? + public init(flags: Int32, coordinates: Api.MediaAreaCoordinates, geo: Api.GeoPoint, address: Api.GeoPointAddress?) { + self.flags = flags + self.coordinates = coordinates + self.geo = geo + self.address = address + } + } + public class Cons_mediaAreaStarGift { + public var coordinates: Api.MediaAreaCoordinates + public var slug: String + public init(coordinates: Api.MediaAreaCoordinates, slug: String) { + self.coordinates = coordinates + self.slug = slug + } + } + public class Cons_mediaAreaSuggestedReaction { + public var flags: Int32 + public var coordinates: Api.MediaAreaCoordinates + public var reaction: Api.Reaction + public init(flags: Int32, coordinates: Api.MediaAreaCoordinates, reaction: Api.Reaction) { + self.flags = flags + self.coordinates = coordinates + self.reaction = reaction + } + } + public class Cons_mediaAreaUrl { + public var coordinates: Api.MediaAreaCoordinates + public var url: String + public init(coordinates: Api.MediaAreaCoordinates, url: String) { + self.coordinates = coordinates + self.url = url + } + } + public class Cons_mediaAreaVenue { + public var coordinates: Api.MediaAreaCoordinates + public var geo: Api.GeoPoint + public var title: String + public var address: String + public var provider: String + public var venueId: String + public var venueType: String + public init(coordinates: Api.MediaAreaCoordinates, geo: Api.GeoPoint, title: String, address: String, provider: String, venueId: String, venueType: String) { + self.coordinates = coordinates + self.geo = geo + self.title = title + self.address = address + self.provider = provider + self.venueId = venueId + self.venueType = venueType + } + } + public class Cons_mediaAreaWeather { + public var coordinates: Api.MediaAreaCoordinates + public var emoji: String + public var temperatureC: Double + public var color: Int32 + public init(coordinates: Api.MediaAreaCoordinates, emoji: String, temperatureC: Double, color: Int32) { + self.coordinates = coordinates + self.emoji = emoji + self.temperatureC = temperatureC + self.color = color + } + } + case inputMediaAreaChannelPost(Cons_inputMediaAreaChannelPost) + case inputMediaAreaVenue(Cons_inputMediaAreaVenue) + case mediaAreaChannelPost(Cons_mediaAreaChannelPost) + case mediaAreaGeoPoint(Cons_mediaAreaGeoPoint) + case mediaAreaStarGift(Cons_mediaAreaStarGift) + case mediaAreaSuggestedReaction(Cons_mediaAreaSuggestedReaction) + case mediaAreaUrl(Cons_mediaAreaUrl) + case mediaAreaVenue(Cons_mediaAreaVenue) + case mediaAreaWeather(Cons_mediaAreaWeather) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputMediaAreaChannelPost(let _data): + if boxed { + buffer.appendInt32(577893055) + } + _data.coordinates.serialize(buffer, true) + _data.channel.serialize(buffer, true) + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + break + case .inputMediaAreaVenue(let _data): + if boxed { + buffer.appendInt32(-1300094593) + } + _data.coordinates.serialize(buffer, true) + serializeInt64(_data.queryId, buffer: buffer, boxed: false) + serializeString(_data.resultId, buffer: buffer, boxed: false) + break + case .mediaAreaChannelPost(let _data): + if boxed { + buffer.appendInt32(1996756655) + } + _data.coordinates.serialize(buffer, true) + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + break + case .mediaAreaGeoPoint(let _data): + if boxed { + buffer.appendInt32(-891992787) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.coordinates.serialize(buffer, true) + _data.geo.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.address!.serialize(buffer, true) + } + break + case .mediaAreaStarGift(let _data): + if boxed { + buffer.appendInt32(1468491885) + } + _data.coordinates.serialize(buffer, true) + serializeString(_data.slug, buffer: buffer, boxed: false) + break + case .mediaAreaSuggestedReaction(let _data): + if boxed { + buffer.appendInt32(340088945) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.coordinates.serialize(buffer, true) + _data.reaction.serialize(buffer, true) + break + case .mediaAreaUrl(let _data): + if boxed { + buffer.appendInt32(926421125) + } + _data.coordinates.serialize(buffer, true) + serializeString(_data.url, buffer: buffer, boxed: false) + break + case .mediaAreaVenue(let _data): + if boxed { + buffer.appendInt32(-1098720356) + } + _data.coordinates.serialize(buffer, true) + _data.geo.serialize(buffer, true) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.address, buffer: buffer, boxed: false) + serializeString(_data.provider, buffer: buffer, boxed: false) + serializeString(_data.venueId, buffer: buffer, boxed: false) + serializeString(_data.venueType, buffer: buffer, boxed: false) + break + case .mediaAreaWeather(let _data): + if boxed { + buffer.appendInt32(1235637404) + } + _data.coordinates.serialize(buffer, true) + serializeString(_data.emoji, buffer: buffer, boxed: false) + serializeDouble(_data.temperatureC, buffer: buffer, boxed: false) + serializeInt32(_data.color, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputMediaAreaChannelPost(let _data): + return ("inputMediaAreaChannelPost", [("coordinates", _data.coordinates as Any), ("channel", _data.channel as Any), ("msgId", _data.msgId as Any)]) + case .inputMediaAreaVenue(let _data): + return ("inputMediaAreaVenue", [("coordinates", _data.coordinates as Any), ("queryId", _data.queryId as Any), ("resultId", _data.resultId as Any)]) + case .mediaAreaChannelPost(let _data): + return ("mediaAreaChannelPost", [("coordinates", _data.coordinates as Any), ("channelId", _data.channelId as Any), ("msgId", _data.msgId as Any)]) + case .mediaAreaGeoPoint(let _data): + return ("mediaAreaGeoPoint", [("flags", _data.flags as Any), ("coordinates", _data.coordinates as Any), ("geo", _data.geo as Any), ("address", _data.address as Any)]) + case .mediaAreaStarGift(let _data): + return ("mediaAreaStarGift", [("coordinates", _data.coordinates as Any), ("slug", _data.slug as Any)]) + case .mediaAreaSuggestedReaction(let _data): + return ("mediaAreaSuggestedReaction", [("flags", _data.flags as Any), ("coordinates", _data.coordinates as Any), ("reaction", _data.reaction as Any)]) + case .mediaAreaUrl(let _data): + return ("mediaAreaUrl", [("coordinates", _data.coordinates as Any), ("url", _data.url as Any)]) + case .mediaAreaVenue(let _data): + return ("mediaAreaVenue", [("coordinates", _data.coordinates as Any), ("geo", _data.geo as Any), ("title", _data.title as Any), ("address", _data.address as Any), ("provider", _data.provider as Any), ("venueId", _data.venueId as Any), ("venueType", _data.venueType as Any)]) + case .mediaAreaWeather(let _data): + return ("mediaAreaWeather", [("coordinates", _data.coordinates as Any), ("emoji", _data.emoji as Any), ("temperatureC", _data.temperatureC as Any), ("color", _data.color as Any)]) + } + } + public static func parse_inputMediaAreaChannelPost(_ reader: BufferReader) -> MediaArea? { var _1: Api.MediaAreaCoordinates? if let signature = reader.readInt32() { @@ -479,10 +751,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MediaArea.inputMediaAreaChannelPost(coordinates: _1!, channel: _2!, msgId: _3!) + if _c1 && _c2 && _c3 { + return Api.MediaArea.inputMediaAreaChannelPost(Cons_inputMediaAreaChannelPost(coordinates: _1!, channel: _2!, msgId: _3!)) + } + else { + return nil + } } public static func parse_inputMediaAreaVenue(_ reader: BufferReader) -> MediaArea? { var _1: Api.MediaAreaCoordinates? @@ -496,10 +770,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MediaArea.inputMediaAreaVenue(coordinates: _1!, queryId: _2!, resultId: _3!) + if _c1 && _c2 && _c3 { + return Api.MediaArea.inputMediaAreaVenue(Cons_inputMediaAreaVenue(coordinates: _1!, queryId: _2!, resultId: _3!)) + } + else { + return nil + } } public static func parse_mediaAreaChannelPost(_ reader: BufferReader) -> MediaArea? { var _1: Api.MediaAreaCoordinates? @@ -513,10 +789,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MediaArea.mediaAreaChannelPost(coordinates: _1!, channelId: _2!, msgId: _3!) + if _c1 && _c2 && _c3 { + return Api.MediaArea.mediaAreaChannelPost(Cons_mediaAreaChannelPost(coordinates: _1!, channelId: _2!, msgId: _3!)) + } + else { + return nil + } } public static func parse_mediaAreaGeoPoint(_ reader: BufferReader) -> MediaArea? { var _1: Int32? @@ -530,18 +808,21 @@ public extension Api { _3 = Api.parse(reader, signature: signature) as? Api.GeoPoint } var _4: Api.GeoPointAddress? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.GeoPointAddress - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.GeoPointAddress + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.MediaArea.mediaAreaGeoPoint(flags: _1!, coordinates: _2!, geo: _3!, address: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.MediaArea.mediaAreaGeoPoint(Cons_mediaAreaGeoPoint(flags: _1!, coordinates: _2!, geo: _3!, address: _4)) + } + else { + return nil + } } public static func parse_mediaAreaStarGift(_ reader: BufferReader) -> MediaArea? { var _1: Api.MediaAreaCoordinates? @@ -552,9 +833,12 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MediaArea.mediaAreaStarGift(coordinates: _1!, slug: _2!) + if _c1 && _c2 { + return Api.MediaArea.mediaAreaStarGift(Cons_mediaAreaStarGift(coordinates: _1!, slug: _2!)) + } + else { + return nil + } } public static func parse_mediaAreaSuggestedReaction(_ reader: BufferReader) -> MediaArea? { var _1: Int32? @@ -570,10 +854,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MediaArea.mediaAreaSuggestedReaction(flags: _1!, coordinates: _2!, reaction: _3!) + if _c1 && _c2 && _c3 { + return Api.MediaArea.mediaAreaSuggestedReaction(Cons_mediaAreaSuggestedReaction(flags: _1!, coordinates: _2!, reaction: _3!)) + } + else { + return nil + } } public static func parse_mediaAreaUrl(_ reader: BufferReader) -> MediaArea? { var _1: Api.MediaAreaCoordinates? @@ -584,9 +870,12 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MediaArea.mediaAreaUrl(coordinates: _1!, url: _2!) + if _c1 && _c2 { + return Api.MediaArea.mediaAreaUrl(Cons_mediaAreaUrl(coordinates: _1!, url: _2!)) + } + else { + return nil + } } public static func parse_mediaAreaVenue(_ reader: BufferReader) -> MediaArea? { var _1: Api.MediaAreaCoordinates? @@ -614,14 +903,12 @@ public extension Api { let _c5 = _5 != nil let _c6 = _6 != nil let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.MediaArea.mediaAreaVenue(coordinates: _1!, geo: _2!, title: _3!, address: _4!, provider: _5!, venueId: _6!, venueType: _7!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.MediaArea.mediaAreaVenue(Cons_mediaAreaVenue(coordinates: _1!, geo: _2!, title: _3!, address: _4!, provider: _5!, venueId: _6!, venueType: _7!)) + } + else { + return nil + } } public static func parse_mediaAreaWeather(_ reader: BufferReader) -> MediaArea? { var _1: Api.MediaAreaCoordinates? @@ -638,43 +925,63 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.MediaArea.mediaAreaWeather(coordinates: _1!, emoji: _2!, temperatureC: _3!, color: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.MediaArea.mediaAreaWeather(Cons_mediaAreaWeather(coordinates: _1!, emoji: _2!, temperatureC: _3!, color: _4!)) + } + else { + return nil + } } - } } public extension Api { enum MediaAreaCoordinates: TypeConstructorDescription { - case mediaAreaCoordinates(flags: Int32, x: Double, y: Double, w: Double, h: Double, rotation: Double, radius: Double?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .mediaAreaCoordinates(let flags, let x, let y, let w, let h, let rotation, let radius): - if boxed { - buffer.appendInt32(-808853502) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeDouble(x, buffer: buffer, boxed: false) - serializeDouble(y, buffer: buffer, boxed: false) - serializeDouble(w, buffer: buffer, boxed: false) - serializeDouble(h, buffer: buffer, boxed: false) - serializeDouble(rotation, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeDouble(radius!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .mediaAreaCoordinates(let flags, let x, let y, let w, let h, let rotation, let radius): - return ("mediaAreaCoordinates", [("flags", flags as Any), ("x", x as Any), ("y", y as Any), ("w", w as Any), ("h", h as Any), ("rotation", rotation as Any), ("radius", radius as Any)]) - } - } - + public class Cons_mediaAreaCoordinates { + public var flags: Int32 + public var x: Double + public var y: Double + public var w: Double + public var h: Double + public var rotation: Double + public var radius: Double? + public init(flags: Int32, x: Double, y: Double, w: Double, h: Double, rotation: Double, radius: Double?) { + self.flags = flags + self.x = x + self.y = y + self.w = w + self.h = h + self.rotation = rotation + self.radius = radius + } + } + case mediaAreaCoordinates(Cons_mediaAreaCoordinates) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .mediaAreaCoordinates(let _data): + if boxed { + buffer.appendInt32(-808853502) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeDouble(_data.x, buffer: buffer, boxed: false) + serializeDouble(_data.y, buffer: buffer, boxed: false) + serializeDouble(_data.w, buffer: buffer, boxed: false) + serializeDouble(_data.h, buffer: buffer, boxed: false) + serializeDouble(_data.rotation, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeDouble(_data.radius!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .mediaAreaCoordinates(let _data): + return ("mediaAreaCoordinates", [("flags", _data.flags as Any), ("x", _data.x as Any), ("y", _data.y as Any), ("w", _data.w as Any), ("h", _data.h as Any), ("rotation", _data.rotation as Any), ("radius", _data.radius as Any)]) + } + } + public static func parse_mediaAreaCoordinates(_ reader: BufferReader) -> MediaAreaCoordinates? { var _1: Int32? _1 = reader.readInt32() @@ -689,7 +996,9 @@ public extension Api { var _6: Double? _6 = reader.readDouble() var _7: Double? - if Int(_1!) & Int(1 << 0) != 0 {_7 = reader.readDouble() } + if Int(_1!) & Int(1 << 0) != 0 { + _7 = reader.readDouble() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -697,109 +1006,276 @@ public extension Api { let _c5 = _5 != nil let _c6 = _6 != nil let _c7 = (Int(_1!) & Int(1 << 0) == 0) || _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.MediaAreaCoordinates.mediaAreaCoordinates(flags: _1!, x: _2!, y: _3!, w: _4!, h: _5!, rotation: _6!, radius: _7) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.MediaAreaCoordinates.mediaAreaCoordinates(Cons_mediaAreaCoordinates(flags: _1!, x: _2!, y: _3!, w: _4!, h: _5!, rotation: _6!, radius: _7)) + } + else { + return nil + } } - } } public extension Api { indirect enum Message: TypeConstructorDescription { - case message(flags: Int32, flags2: Int32, id: Int32, fromId: Api.Peer?, fromBoostsApplied: Int32?, peerId: Api.Peer, savedPeerId: Api.Peer?, fwdFrom: Api.MessageFwdHeader?, viaBotId: Int64?, viaBusinessBotId: Int64?, replyTo: Api.MessageReplyHeader?, date: Int32, message: String, media: Api.MessageMedia?, replyMarkup: Api.ReplyMarkup?, entities: [Api.MessageEntity]?, views: Int32?, forwards: Int32?, replies: Api.MessageReplies?, editDate: Int32?, postAuthor: String?, groupedId: Int64?, reactions: Api.MessageReactions?, restrictionReason: [Api.RestrictionReason]?, ttlPeriod: Int32?, quickReplyShortcutId: Int32?, effect: Int64?, factcheck: Api.FactCheck?, reportDeliveryUntilDate: Int32?, paidMessageStars: Int64?, suggestedPost: Api.SuggestedPost?, scheduleRepeatPeriod: Int32?, summaryFromLanguage: String?) - case messageEmpty(flags: Int32, id: Int32, peerId: Api.Peer?) - case messageService(flags: Int32, id: Int32, fromId: Api.Peer?, peerId: Api.Peer, savedPeerId: Api.Peer?, replyTo: Api.MessageReplyHeader?, date: Int32, action: Api.MessageAction, reactions: Api.MessageReactions?, ttlPeriod: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .message(let flags, let flags2, let id, let fromId, let fromBoostsApplied, let peerId, let savedPeerId, let fwdFrom, let viaBotId, let viaBusinessBotId, let replyTo, let date, let message, let media, let replyMarkup, let entities, let views, let forwards, let replies, let editDate, let postAuthor, let groupedId, let reactions, let restrictionReason, let ttlPeriod, let quickReplyShortcutId, let effect, let factcheck, let reportDeliveryUntilDate, let paidMessageStars, let suggestedPost, let scheduleRepeatPeriod, let summaryFromLanguage): - if boxed { - buffer.appendInt32(-1665888023) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(flags2, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 8) != 0 {fromId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 29) != 0 {serializeInt32(fromBoostsApplied!, buffer: buffer, boxed: false)} - peerId.serialize(buffer, true) - if Int(flags) & Int(1 << 28) != 0 {savedPeerId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {fwdFrom!.serialize(buffer, true)} - if Int(flags) & Int(1 << 11) != 0 {serializeInt64(viaBotId!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 0) != 0 {serializeInt64(viaBusinessBotId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {replyTo!.serialize(buffer, true)} - serializeInt32(date, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 9) != 0 {media!.serialize(buffer, true)} - if Int(flags) & Int(1 << 6) != 0 {replyMarkup!.serialize(buffer, true)} - if Int(flags) & Int(1 << 7) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { + public class Cons_message { + public var flags: Int32 + public var flags2: Int32 + public var id: Int32 + public var fromId: Api.Peer? + public var fromBoostsApplied: Int32? + public var peerId: Api.Peer + public var savedPeerId: Api.Peer? + public var fwdFrom: Api.MessageFwdHeader? + public var viaBotId: Int64? + public var viaBusinessBotId: Int64? + public var replyTo: Api.MessageReplyHeader? + public var date: Int32 + public var message: String + public var media: Api.MessageMedia? + public var replyMarkup: Api.ReplyMarkup? + public var entities: [Api.MessageEntity]? + public var views: Int32? + public var forwards: Int32? + public var replies: Api.MessageReplies? + public var editDate: Int32? + public var postAuthor: String? + public var groupedId: Int64? + public var reactions: Api.MessageReactions? + public var restrictionReason: [Api.RestrictionReason]? + public var ttlPeriod: Int32? + public var quickReplyShortcutId: Int32? + public var effect: Int64? + public var factcheck: Api.FactCheck? + public var reportDeliveryUntilDate: Int32? + public var paidMessageStars: Int64? + public var suggestedPost: Api.SuggestedPost? + public var scheduleRepeatPeriod: Int32? + public var summaryFromLanguage: String? + public init(flags: Int32, flags2: Int32, id: Int32, fromId: Api.Peer?, fromBoostsApplied: Int32?, peerId: Api.Peer, savedPeerId: Api.Peer?, fwdFrom: Api.MessageFwdHeader?, viaBotId: Int64?, viaBusinessBotId: Int64?, replyTo: Api.MessageReplyHeader?, date: Int32, message: String, media: Api.MessageMedia?, replyMarkup: Api.ReplyMarkup?, entities: [Api.MessageEntity]?, views: Int32?, forwards: Int32?, replies: Api.MessageReplies?, editDate: Int32?, postAuthor: String?, groupedId: Int64?, reactions: Api.MessageReactions?, restrictionReason: [Api.RestrictionReason]?, ttlPeriod: Int32?, quickReplyShortcutId: Int32?, effect: Int64?, factcheck: Api.FactCheck?, reportDeliveryUntilDate: Int32?, paidMessageStars: Int64?, suggestedPost: Api.SuggestedPost?, scheduleRepeatPeriod: Int32?, summaryFromLanguage: String?) { + self.flags = flags + self.flags2 = flags2 + self.id = id + self.fromId = fromId + self.fromBoostsApplied = fromBoostsApplied + self.peerId = peerId + self.savedPeerId = savedPeerId + self.fwdFrom = fwdFrom + self.viaBotId = viaBotId + self.viaBusinessBotId = viaBusinessBotId + self.replyTo = replyTo + self.date = date + self.message = message + self.media = media + self.replyMarkup = replyMarkup + self.entities = entities + self.views = views + self.forwards = forwards + self.replies = replies + self.editDate = editDate + self.postAuthor = postAuthor + self.groupedId = groupedId + self.reactions = reactions + self.restrictionReason = restrictionReason + self.ttlPeriod = ttlPeriod + self.quickReplyShortcutId = quickReplyShortcutId + self.effect = effect + self.factcheck = factcheck + self.reportDeliveryUntilDate = reportDeliveryUntilDate + self.paidMessageStars = paidMessageStars + self.suggestedPost = suggestedPost + self.scheduleRepeatPeriod = scheduleRepeatPeriod + self.summaryFromLanguage = summaryFromLanguage + } + } + public class Cons_messageEmpty { + public var flags: Int32 + public var id: Int32 + public var peerId: Api.Peer? + public init(flags: Int32, id: Int32, peerId: Api.Peer?) { + self.flags = flags + self.id = id + self.peerId = peerId + } + } + public class Cons_messageService { + public var flags: Int32 + public var id: Int32 + public var fromId: Api.Peer? + public var peerId: Api.Peer + public var savedPeerId: Api.Peer? + public var replyTo: Api.MessageReplyHeader? + public var date: Int32 + public var action: Api.MessageAction + public var reactions: Api.MessageReactions? + public var ttlPeriod: Int32? + public init(flags: Int32, id: Int32, fromId: Api.Peer?, peerId: Api.Peer, savedPeerId: Api.Peer?, replyTo: Api.MessageReplyHeader?, date: Int32, action: Api.MessageAction, reactions: Api.MessageReactions?, ttlPeriod: Int32?) { + self.flags = flags + self.id = id + self.fromId = fromId + self.peerId = peerId + self.savedPeerId = savedPeerId + self.replyTo = replyTo + self.date = date + self.action = action + self.reactions = reactions + self.ttlPeriod = ttlPeriod + } + } + case message(Cons_message) + case messageEmpty(Cons_messageEmpty) + case messageService(Cons_messageService) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .message(let _data): + if boxed { + buffer.appendInt32(-1665888023) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.flags2, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 8) != 0 { + _data.fromId!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 29) != 0 { + serializeInt32(_data.fromBoostsApplied!, buffer: buffer, boxed: false) + } + _data.peerId.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 28) != 0 { + _data.savedPeerId!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.fwdFrom!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 11) != 0 { + serializeInt64(_data.viaBotId!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 0) != 0 { + serializeInt64(_data.viaBusinessBotId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.replyTo!.serialize(buffer, true) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeString(_data.message, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 9) != 0 { + _data.media!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 7) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 10) != 0 {serializeInt32(views!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 10) != 0 {serializeInt32(forwards!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 23) != 0 {replies!.serialize(buffer, true)} - if Int(flags) & Int(1 << 15) != 0 {serializeInt32(editDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 16) != 0 {serializeString(postAuthor!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 17) != 0 {serializeInt64(groupedId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 20) != 0 {reactions!.serialize(buffer, true)} - if Int(flags) & Int(1 << 22) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(restrictionReason!.count)) - for item in restrictionReason! { + } + } + if Int(_data.flags) & Int(1 << 10) != 0 { + serializeInt32(_data.views!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 10) != 0 { + serializeInt32(_data.forwards!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 23) != 0 { + _data.replies!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 15) != 0 { + serializeInt32(_data.editDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 16) != 0 { + serializeString(_data.postAuthor!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 17) != 0 { + serializeInt64(_data.groupedId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 20) != 0 { + _data.reactions!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 22) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.restrictionReason!.count)) + for item in _data.restrictionReason! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 25) != 0 {serializeInt32(ttlPeriod!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 30) != 0 {serializeInt32(quickReplyShortcutId!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 2) != 0 {serializeInt64(effect!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 3) != 0 {factcheck!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 5) != 0 {serializeInt32(reportDeliveryUntilDate!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 6) != 0 {serializeInt64(paidMessageStars!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 7) != 0 {suggestedPost!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 10) != 0 {serializeInt32(scheduleRepeatPeriod!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 11) != 0 {serializeString(summaryFromLanguage!, buffer: buffer, boxed: false)} - break - case .messageEmpty(let flags, let id, let peerId): - if boxed { - buffer.appendInt32(-1868117372) } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {peerId!.serialize(buffer, true)} - break - case .messageService(let flags, let id, let fromId, let peerId, let savedPeerId, let replyTo, let date, let action, let reactions, let ttlPeriod): - if boxed { - buffer.appendInt32(2055212554) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 8) != 0 {fromId!.serialize(buffer, true)} - peerId.serialize(buffer, true) - if Int(flags) & Int(1 << 28) != 0 {savedPeerId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {replyTo!.serialize(buffer, true)} - serializeInt32(date, buffer: buffer, boxed: false) - action.serialize(buffer, true) - if Int(flags) & Int(1 << 20) != 0 {reactions!.serialize(buffer, true)} - if Int(flags) & Int(1 << 25) != 0 {serializeInt32(ttlPeriod!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .message(let flags, let flags2, let id, let fromId, let fromBoostsApplied, let peerId, let savedPeerId, let fwdFrom, let viaBotId, let viaBusinessBotId, let replyTo, let date, let message, let media, let replyMarkup, let entities, let views, let forwards, let replies, let editDate, let postAuthor, let groupedId, let reactions, let restrictionReason, let ttlPeriod, let quickReplyShortcutId, let effect, let factcheck, let reportDeliveryUntilDate, let paidMessageStars, let suggestedPost, let scheduleRepeatPeriod, let summaryFromLanguage): - return ("message", [("flags", flags as Any), ("flags2", flags2 as Any), ("id", id as Any), ("fromId", fromId as Any), ("fromBoostsApplied", fromBoostsApplied as Any), ("peerId", peerId as Any), ("savedPeerId", savedPeerId as Any), ("fwdFrom", fwdFrom as Any), ("viaBotId", viaBotId as Any), ("viaBusinessBotId", viaBusinessBotId as Any), ("replyTo", replyTo as Any), ("date", date as Any), ("message", message as Any), ("media", media as Any), ("replyMarkup", replyMarkup as Any), ("entities", entities as Any), ("views", views as Any), ("forwards", forwards as Any), ("replies", replies as Any), ("editDate", editDate as Any), ("postAuthor", postAuthor as Any), ("groupedId", groupedId as Any), ("reactions", reactions as Any), ("restrictionReason", restrictionReason as Any), ("ttlPeriod", ttlPeriod as Any), ("quickReplyShortcutId", quickReplyShortcutId as Any), ("effect", effect as Any), ("factcheck", factcheck as Any), ("reportDeliveryUntilDate", reportDeliveryUntilDate as Any), ("paidMessageStars", paidMessageStars as Any), ("suggestedPost", suggestedPost as Any), ("scheduleRepeatPeriod", scheduleRepeatPeriod as Any), ("summaryFromLanguage", summaryFromLanguage as Any)]) - case .messageEmpty(let flags, let id, let peerId): - return ("messageEmpty", [("flags", flags as Any), ("id", id as Any), ("peerId", peerId as Any)]) - case .messageService(let flags, let id, let fromId, let peerId, let savedPeerId, let replyTo, let date, let action, let reactions, let ttlPeriod): - return ("messageService", [("flags", flags as Any), ("id", id as Any), ("fromId", fromId as Any), ("peerId", peerId as Any), ("savedPeerId", savedPeerId as Any), ("replyTo", replyTo as Any), ("date", date as Any), ("action", action as Any), ("reactions", reactions as Any), ("ttlPeriod", ttlPeriod as Any)]) - } - } - + } + if Int(_data.flags) & Int(1 << 25) != 0 { + serializeInt32(_data.ttlPeriod!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 30) != 0 { + serializeInt32(_data.quickReplyShortcutId!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 2) != 0 { + serializeInt64(_data.effect!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 3) != 0 { + _data.factcheck!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 5) != 0 { + serializeInt32(_data.reportDeliveryUntilDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 6) != 0 { + serializeInt64(_data.paidMessageStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 7) != 0 { + _data.suggestedPost!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 10) != 0 { + serializeInt32(_data.scheduleRepeatPeriod!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 11) != 0 { + serializeString(_data.summaryFromLanguage!, buffer: buffer, boxed: false) + } + break + case .messageEmpty(let _data): + if boxed { + buffer.appendInt32(-1868117372) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.peerId!.serialize(buffer, true) + } + break + case .messageService(let _data): + if boxed { + buffer.appendInt32(2055212554) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 8) != 0 { + _data.fromId!.serialize(buffer, true) + } + _data.peerId.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 28) != 0 { + _data.savedPeerId!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.replyTo!.serialize(buffer, true) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + _data.action.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 20) != 0 { + _data.reactions!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 25) != 0 { + serializeInt32(_data.ttlPeriod!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .message(let _data): + return ("message", [("flags", _data.flags as Any), ("flags2", _data.flags2 as Any), ("id", _data.id as Any), ("fromId", _data.fromId as Any), ("fromBoostsApplied", _data.fromBoostsApplied as Any), ("peerId", _data.peerId as Any), ("savedPeerId", _data.savedPeerId as Any), ("fwdFrom", _data.fwdFrom as Any), ("viaBotId", _data.viaBotId as Any), ("viaBusinessBotId", _data.viaBusinessBotId as Any), ("replyTo", _data.replyTo as Any), ("date", _data.date as Any), ("message", _data.message as Any), ("media", _data.media as Any), ("replyMarkup", _data.replyMarkup as Any), ("entities", _data.entities as Any), ("views", _data.views as Any), ("forwards", _data.forwards as Any), ("replies", _data.replies as Any), ("editDate", _data.editDate as Any), ("postAuthor", _data.postAuthor as Any), ("groupedId", _data.groupedId as Any), ("reactions", _data.reactions as Any), ("restrictionReason", _data.restrictionReason as Any), ("ttlPeriod", _data.ttlPeriod as Any), ("quickReplyShortcutId", _data.quickReplyShortcutId as Any), ("effect", _data.effect as Any), ("factcheck", _data.factcheck as Any), ("reportDeliveryUntilDate", _data.reportDeliveryUntilDate as Any), ("paidMessageStars", _data.paidMessageStars as Any), ("suggestedPost", _data.suggestedPost as Any), ("scheduleRepeatPeriod", _data.scheduleRepeatPeriod as Any), ("summaryFromLanguage", _data.summaryFromLanguage as Any)]) + case .messageEmpty(let _data): + return ("messageEmpty", [("flags", _data.flags as Any), ("id", _data.id as Any), ("peerId", _data.peerId as Any)]) + case .messageService(let _data): + return ("messageService", [("flags", _data.flags as Any), ("id", _data.id as Any), ("fromId", _data.fromId as Any), ("peerId", _data.peerId as Any), ("savedPeerId", _data.savedPeerId as Any), ("replyTo", _data.replyTo as Any), ("date", _data.date as Any), ("action", _data.action as Any), ("reactions", _data.reactions as Any), ("ttlPeriod", _data.ttlPeriod as Any)]) + } + } + public static func parse_message(_ reader: BufferReader) -> Message? { var _1: Int32? _1 = reader.readInt32() @@ -808,91 +1284,145 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: Api.Peer? - if Int(_1!) & Int(1 << 8) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 8) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _5: Int32? - if Int(_1!) & Int(1 << 29) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 29) != 0 { + _5 = reader.readInt32() + } var _6: Api.Peer? if let signature = reader.readInt32() { _6 = Api.parse(reader, signature: signature) as? Api.Peer } var _7: Api.Peer? - if Int(_1!) & Int(1 << 28) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 28) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _8: Api.MessageFwdHeader? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.MessageFwdHeader - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.MessageFwdHeader + } + } var _9: Int64? - if Int(_1!) & Int(1 << 11) != 0 {_9 = reader.readInt64() } + if Int(_1!) & Int(1 << 11) != 0 { + _9 = reader.readInt64() + } var _10: Int64? - if Int(_2!) & Int(1 << 0) != 0 {_10 = reader.readInt64() } + if Int(_2!) & Int(1 << 0) != 0 { + _10 = reader.readInt64() + } var _11: Api.MessageReplyHeader? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _11 = Api.parse(reader, signature: signature) as? Api.MessageReplyHeader - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _11 = Api.parse(reader, signature: signature) as? Api.MessageReplyHeader + } + } var _12: Int32? _12 = reader.readInt32() var _13: String? _13 = parseString(reader) var _14: Api.MessageMedia? - if Int(_1!) & Int(1 << 9) != 0 {if let signature = reader.readInt32() { - _14 = Api.parse(reader, signature: signature) as? Api.MessageMedia - } } + if Int(_1!) & Int(1 << 9) != 0 { + if let signature = reader.readInt32() { + _14 = Api.parse(reader, signature: signature) as? Api.MessageMedia + } + } var _15: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 6) != 0 {if let signature = reader.readInt32() { - _15 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 6) != 0 { + if let signature = reader.readInt32() { + _15 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } var _16: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 7) != 0 {if let _ = reader.readInt32() { - _16 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 7) != 0 { + if let _ = reader.readInt32() { + _16 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } var _17: Int32? - if Int(_1!) & Int(1 << 10) != 0 {_17 = reader.readInt32() } + if Int(_1!) & Int(1 << 10) != 0 { + _17 = reader.readInt32() + } var _18: Int32? - if Int(_1!) & Int(1 << 10) != 0 {_18 = reader.readInt32() } + if Int(_1!) & Int(1 << 10) != 0 { + _18 = reader.readInt32() + } var _19: Api.MessageReplies? - if Int(_1!) & Int(1 << 23) != 0 {if let signature = reader.readInt32() { - _19 = Api.parse(reader, signature: signature) as? Api.MessageReplies - } } + if Int(_1!) & Int(1 << 23) != 0 { + if let signature = reader.readInt32() { + _19 = Api.parse(reader, signature: signature) as? Api.MessageReplies + } + } var _20: Int32? - if Int(_1!) & Int(1 << 15) != 0 {_20 = reader.readInt32() } + if Int(_1!) & Int(1 << 15) != 0 { + _20 = reader.readInt32() + } var _21: String? - if Int(_1!) & Int(1 << 16) != 0 {_21 = parseString(reader) } + if Int(_1!) & Int(1 << 16) != 0 { + _21 = parseString(reader) + } var _22: Int64? - if Int(_1!) & Int(1 << 17) != 0 {_22 = reader.readInt64() } + if Int(_1!) & Int(1 << 17) != 0 { + _22 = reader.readInt64() + } var _23: Api.MessageReactions? - if Int(_1!) & Int(1 << 20) != 0 {if let signature = reader.readInt32() { - _23 = Api.parse(reader, signature: signature) as? Api.MessageReactions - } } + if Int(_1!) & Int(1 << 20) != 0 { + if let signature = reader.readInt32() { + _23 = Api.parse(reader, signature: signature) as? Api.MessageReactions + } + } var _24: [Api.RestrictionReason]? - if Int(_1!) & Int(1 << 22) != 0 {if let _ = reader.readInt32() { - _24 = Api.parseVector(reader, elementSignature: 0, elementType: Api.RestrictionReason.self) - } } + if Int(_1!) & Int(1 << 22) != 0 { + if let _ = reader.readInt32() { + _24 = Api.parseVector(reader, elementSignature: 0, elementType: Api.RestrictionReason.self) + } + } var _25: Int32? - if Int(_1!) & Int(1 << 25) != 0 {_25 = reader.readInt32() } + if Int(_1!) & Int(1 << 25) != 0 { + _25 = reader.readInt32() + } var _26: Int32? - if Int(_1!) & Int(1 << 30) != 0 {_26 = reader.readInt32() } + if Int(_1!) & Int(1 << 30) != 0 { + _26 = reader.readInt32() + } var _27: Int64? - if Int(_2!) & Int(1 << 2) != 0 {_27 = reader.readInt64() } + if Int(_2!) & Int(1 << 2) != 0 { + _27 = reader.readInt64() + } var _28: Api.FactCheck? - if Int(_2!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _28 = Api.parse(reader, signature: signature) as? Api.FactCheck - } } + if Int(_2!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _28 = Api.parse(reader, signature: signature) as? Api.FactCheck + } + } var _29: Int32? - if Int(_2!) & Int(1 << 5) != 0 {_29 = reader.readInt32() } + if Int(_2!) & Int(1 << 5) != 0 { + _29 = reader.readInt32() + } var _30: Int64? - if Int(_2!) & Int(1 << 6) != 0 {_30 = reader.readInt64() } + if Int(_2!) & Int(1 << 6) != 0 { + _30 = reader.readInt64() + } var _31: Api.SuggestedPost? - if Int(_2!) & Int(1 << 7) != 0 {if let signature = reader.readInt32() { - _31 = Api.parse(reader, signature: signature) as? Api.SuggestedPost - } } + if Int(_2!) & Int(1 << 7) != 0 { + if let signature = reader.readInt32() { + _31 = Api.parse(reader, signature: signature) as? Api.SuggestedPost + } + } var _32: Int32? - if Int(_2!) & Int(1 << 10) != 0 {_32 = reader.readInt32() } + if Int(_2!) & Int(1 << 10) != 0 { + _32 = reader.readInt32() + } var _33: String? - if Int(_2!) & Int(1 << 11) != 0 {_33 = parseString(reader) } + if Int(_2!) & Int(1 << 11) != 0 { + _33 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -926,40 +1456,12 @@ public extension Api { let _c31 = (Int(_2!) & Int(1 << 7) == 0) || _31 != nil let _c32 = (Int(_2!) & Int(1 << 10) == 0) || _32 != nil let _c33 = (Int(_2!) & Int(1 << 11) == 0) || _33 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - if !_c16 { return nil } - if !_c17 { return nil } - if !_c18 { return nil } - if !_c19 { return nil } - if !_c20 { return nil } - if !_c21 { return nil } - if !_c22 { return nil } - if !_c23 { return nil } - if !_c24 { return nil } - if !_c25 { return nil } - if !_c26 { return nil } - if !_c27 { return nil } - if !_c28 { return nil } - if !_c29 { return nil } - if !_c30 { return nil } - if !_c31 { return nil } - if !_c32 { return nil } - if !_c33 { return nil } - return Api.Message.message(flags: _1!, flags2: _2!, id: _3!, fromId: _4, fromBoostsApplied: _5, peerId: _6!, savedPeerId: _7, fwdFrom: _8, viaBotId: _9, viaBusinessBotId: _10, replyTo: _11, date: _12!, message: _13!, media: _14, replyMarkup: _15, entities: _16, views: _17, forwards: _18, replies: _19, editDate: _20, postAuthor: _21, groupedId: _22, reactions: _23, restrictionReason: _24, ttlPeriod: _25, quickReplyShortcutId: _26, effect: _27, factcheck: _28, reportDeliveryUntilDate: _29, paidMessageStars: _30, suggestedPost: _31, scheduleRepeatPeriod: _32, summaryFromLanguage: _33) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 && _c18 && _c19 && _c20 && _c21 && _c22 && _c23 && _c24 && _c25 && _c26 && _c27 && _c28 && _c29 && _c30 && _c31 && _c32 && _c33 { + return Api.Message.message(Cons_message(flags: _1!, flags2: _2!, id: _3!, fromId: _4, fromBoostsApplied: _5, peerId: _6!, savedPeerId: _7, fwdFrom: _8, viaBotId: _9, viaBusinessBotId: _10, replyTo: _11, date: _12!, message: _13!, media: _14, replyMarkup: _15, entities: _16, views: _17, forwards: _18, replies: _19, editDate: _20, postAuthor: _21, groupedId: _22, reactions: _23, restrictionReason: _24, ttlPeriod: _25, quickReplyShortcutId: _26, effect: _27, factcheck: _28, reportDeliveryUntilDate: _29, paidMessageStars: _30, suggestedPost: _31, scheduleRepeatPeriod: _32, summaryFromLanguage: _33)) + } + else { + return nil + } } public static func parse_messageEmpty(_ reader: BufferReader) -> Message? { var _1: Int32? @@ -967,16 +1469,20 @@ public extension Api { var _2: Int32? _2 = reader.readInt32() var _3: Api.Peer? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Peer + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Message.messageEmpty(flags: _1!, id: _2!, peerId: _3) + if _c1 && _c2 && _c3 { + return Api.Message.messageEmpty(Cons_messageEmpty(flags: _1!, id: _2!, peerId: _3)) + } + else { + return nil + } } public static func parse_messageService(_ reader: BufferReader) -> Message? { var _1: Int32? @@ -984,21 +1490,27 @@ public extension Api { var _2: Int32? _2 = reader.readInt32() var _3: Api.Peer? - if Int(_1!) & Int(1 << 8) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 8) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _4: Api.Peer? if let signature = reader.readInt32() { _4 = Api.parse(reader, signature: signature) as? Api.Peer } var _5: Api.Peer? - if Int(_1!) & Int(1 << 28) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 28) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _6: Api.MessageReplyHeader? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.MessageReplyHeader - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.MessageReplyHeader + } + } var _7: Int32? _7 = reader.readInt32() var _8: Api.MessageAction? @@ -1006,11 +1518,15 @@ public extension Api { _8 = Api.parse(reader, signature: signature) as? Api.MessageAction } var _9: Api.MessageReactions? - if Int(_1!) & Int(1 << 20) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.MessageReactions - } } + if Int(_1!) & Int(1 << 20) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.MessageReactions + } + } var _10: Int32? - if Int(_1!) & Int(1 << 25) != 0 {_10 = reader.readInt32() } + if Int(_1!) & Int(1 << 25) != 0 { + _10 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 8) == 0) || _3 != nil @@ -1021,760 +1537,1461 @@ public extension Api { let _c8 = _8 != nil let _c9 = (Int(_1!) & Int(1 << 20) == 0) || _9 != nil let _c10 = (Int(_1!) & Int(1 << 25) == 0) || _10 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - return Api.Message.messageService(flags: _1!, id: _2!, fromId: _3, peerId: _4!, savedPeerId: _5, replyTo: _6, date: _7!, action: _8!, reactions: _9, ttlPeriod: _10) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 { + return Api.Message.messageService(Cons_messageService(flags: _1!, id: _2!, fromId: _3, peerId: _4!, savedPeerId: _5, replyTo: _6, date: _7!, action: _8!, reactions: _9, ttlPeriod: _10)) + } + else { + return nil + } } - } } public extension Api { enum MessageAction: TypeConstructorDescription { - case messageActionBoostApply(boosts: Int32) - case messageActionBotAllowed(flags: Int32, domain: String?, app: Api.BotApp?) - case messageActionChannelCreate(title: String) - case messageActionChannelMigrateFrom(title: String, chatId: Int64) - case messageActionChatAddUser(users: [Int64]) - case messageActionChatCreate(title: String, users: [Int64]) + public class Cons_messageActionBoostApply { + public var boosts: Int32 + public init(boosts: Int32) { + self.boosts = boosts + } + } + public class Cons_messageActionBotAllowed { + public var flags: Int32 + public var domain: String? + public var app: Api.BotApp? + public init(flags: Int32, domain: String?, app: Api.BotApp?) { + self.flags = flags + self.domain = domain + self.app = app + } + } + public class Cons_messageActionChangeCreator { + public var newCreatorId: Int64 + public init(newCreatorId: Int64) { + self.newCreatorId = newCreatorId + } + } + public class Cons_messageActionChannelCreate { + public var title: String + public init(title: String) { + self.title = title + } + } + public class Cons_messageActionChannelMigrateFrom { + public var title: String + public var chatId: Int64 + public init(title: String, chatId: Int64) { + self.title = title + self.chatId = chatId + } + } + public class Cons_messageActionChatAddUser { + public var users: [Int64] + public init(users: [Int64]) { + self.users = users + } + } + public class Cons_messageActionChatCreate { + public var title: String + public var users: [Int64] + public init(title: String, users: [Int64]) { + self.title = title + self.users = users + } + } + public class Cons_messageActionChatDeleteUser { + public var userId: Int64 + public init(userId: Int64) { + self.userId = userId + } + } + public class Cons_messageActionChatEditPhoto { + public var photo: Api.Photo + public init(photo: Api.Photo) { + self.photo = photo + } + } + public class Cons_messageActionChatEditTitle { + public var title: String + public init(title: String) { + self.title = title + } + } + public class Cons_messageActionChatJoinedByLink { + public var inviterId: Int64 + public init(inviterId: Int64) { + self.inviterId = inviterId + } + } + public class Cons_messageActionChatMigrateTo { + public var channelId: Int64 + public init(channelId: Int64) { + self.channelId = channelId + } + } + public class Cons_messageActionConferenceCall { + public var flags: Int32 + public var callId: Int64 + public var duration: Int32? + public var otherParticipants: [Api.Peer]? + public init(flags: Int32, callId: Int64, duration: Int32?, otherParticipants: [Api.Peer]?) { + self.flags = flags + self.callId = callId + self.duration = duration + self.otherParticipants = otherParticipants + } + } + public class Cons_messageActionCustomAction { + public var message: String + public init(message: String) { + self.message = message + } + } + public class Cons_messageActionGameScore { + public var gameId: Int64 + public var score: Int32 + public init(gameId: Int64, score: Int32) { + self.gameId = gameId + self.score = score + } + } + public class Cons_messageActionGeoProximityReached { + public var fromId: Api.Peer + public var toId: Api.Peer + public var distance: Int32 + public init(fromId: Api.Peer, toId: Api.Peer, distance: Int32) { + self.fromId = fromId + self.toId = toId + self.distance = distance + } + } + public class Cons_messageActionGiftCode { + public var flags: Int32 + public var boostPeer: Api.Peer? + public var days: Int32 + public var slug: String + public var currency: String? + public var amount: Int64? + public var cryptoCurrency: String? + public var cryptoAmount: Int64? + public var message: Api.TextWithEntities? + public init(flags: Int32, boostPeer: Api.Peer?, days: Int32, slug: String, currency: String?, amount: Int64?, cryptoCurrency: String?, cryptoAmount: Int64?, message: Api.TextWithEntities?) { + self.flags = flags + self.boostPeer = boostPeer + self.days = days + self.slug = slug + self.currency = currency + self.amount = amount + self.cryptoCurrency = cryptoCurrency + self.cryptoAmount = cryptoAmount + self.message = message + } + } + public class Cons_messageActionGiftPremium { + public var flags: Int32 + public var currency: String + public var amount: Int64 + public var days: Int32 + public var cryptoCurrency: String? + public var cryptoAmount: Int64? + public var message: Api.TextWithEntities? + public init(flags: Int32, currency: String, amount: Int64, days: Int32, cryptoCurrency: String?, cryptoAmount: Int64?, message: Api.TextWithEntities?) { + self.flags = flags + self.currency = currency + self.amount = amount + self.days = days + self.cryptoCurrency = cryptoCurrency + self.cryptoAmount = cryptoAmount + self.message = message + } + } + public class Cons_messageActionGiftStars { + public var flags: Int32 + public var currency: String + public var amount: Int64 + public var stars: Int64 + public var cryptoCurrency: String? + public var cryptoAmount: Int64? + public var transactionId: String? + public init(flags: Int32, currency: String, amount: Int64, stars: Int64, cryptoCurrency: String?, cryptoAmount: Int64?, transactionId: String?) { + self.flags = flags + self.currency = currency + self.amount = amount + self.stars = stars + self.cryptoCurrency = cryptoCurrency + self.cryptoAmount = cryptoAmount + self.transactionId = transactionId + } + } + public class Cons_messageActionGiftTon { + public var flags: Int32 + public var currency: String + public var amount: Int64 + public var cryptoCurrency: String + public var cryptoAmount: Int64 + public var transactionId: String? + public init(flags: Int32, currency: String, amount: Int64, cryptoCurrency: String, cryptoAmount: Int64, transactionId: String?) { + self.flags = flags + self.currency = currency + self.amount = amount + self.cryptoCurrency = cryptoCurrency + self.cryptoAmount = cryptoAmount + self.transactionId = transactionId + } + } + public class Cons_messageActionGiveawayLaunch { + public var flags: Int32 + public var stars: Int64? + public init(flags: Int32, stars: Int64?) { + self.flags = flags + self.stars = stars + } + } + public class Cons_messageActionGiveawayResults { + public var flags: Int32 + public var winnersCount: Int32 + public var unclaimedCount: Int32 + public init(flags: Int32, winnersCount: Int32, unclaimedCount: Int32) { + self.flags = flags + self.winnersCount = winnersCount + self.unclaimedCount = unclaimedCount + } + } + public class Cons_messageActionGroupCall { + public var flags: Int32 + public var call: Api.InputGroupCall + public var duration: Int32? + public init(flags: Int32, call: Api.InputGroupCall, duration: Int32?) { + self.flags = flags + self.call = call + self.duration = duration + } + } + public class Cons_messageActionGroupCallScheduled { + public var call: Api.InputGroupCall + public var scheduleDate: Int32 + public init(call: Api.InputGroupCall, scheduleDate: Int32) { + self.call = call + self.scheduleDate = scheduleDate + } + } + public class Cons_messageActionInviteToGroupCall { + public var call: Api.InputGroupCall + public var users: [Int64] + public init(call: Api.InputGroupCall, users: [Int64]) { + self.call = call + self.users = users + } + } + public class Cons_messageActionNewCreatorPending { + public var newCreatorId: Int64 + public init(newCreatorId: Int64) { + self.newCreatorId = newCreatorId + } + } + public class Cons_messageActionPaidMessagesPrice { + public var flags: Int32 + public var stars: Int64 + public init(flags: Int32, stars: Int64) { + self.flags = flags + self.stars = stars + } + } + public class Cons_messageActionPaidMessagesRefunded { + public var count: Int32 + public var stars: Int64 + public init(count: Int32, stars: Int64) { + self.count = count + self.stars = stars + } + } + public class Cons_messageActionPaymentRefunded { + public var flags: Int32 + public var peer: Api.Peer + public var currency: String + public var totalAmount: Int64 + public var payload: Buffer? + public var charge: Api.PaymentCharge + public init(flags: Int32, peer: Api.Peer, currency: String, totalAmount: Int64, payload: Buffer?, charge: Api.PaymentCharge) { + self.flags = flags + self.peer = peer + self.currency = currency + self.totalAmount = totalAmount + self.payload = payload + self.charge = charge + } + } + public class Cons_messageActionPaymentSent { + public var flags: Int32 + public var currency: String + public var totalAmount: Int64 + public var invoiceSlug: String? + public var subscriptionUntilDate: Int32? + public init(flags: Int32, currency: String, totalAmount: Int64, invoiceSlug: String?, subscriptionUntilDate: Int32?) { + self.flags = flags + self.currency = currency + self.totalAmount = totalAmount + self.invoiceSlug = invoiceSlug + self.subscriptionUntilDate = subscriptionUntilDate + } + } + public class Cons_messageActionPaymentSentMe { + public var flags: Int32 + public var currency: String + public var totalAmount: Int64 + public var payload: Buffer + public var info: Api.PaymentRequestedInfo? + public var shippingOptionId: String? + public var charge: Api.PaymentCharge + public var subscriptionUntilDate: Int32? + public init(flags: Int32, currency: String, totalAmount: Int64, payload: Buffer, info: Api.PaymentRequestedInfo?, shippingOptionId: String?, charge: Api.PaymentCharge, subscriptionUntilDate: Int32?) { + self.flags = flags + self.currency = currency + self.totalAmount = totalAmount + self.payload = payload + self.info = info + self.shippingOptionId = shippingOptionId + self.charge = charge + self.subscriptionUntilDate = subscriptionUntilDate + } + } + public class Cons_messageActionPhoneCall { + public var flags: Int32 + public var callId: Int64 + public var reason: Api.PhoneCallDiscardReason? + public var duration: Int32? + public init(flags: Int32, callId: Int64, reason: Api.PhoneCallDiscardReason?, duration: Int32?) { + self.flags = flags + self.callId = callId + self.reason = reason + self.duration = duration + } + } + public class Cons_messageActionPrizeStars { + public var flags: Int32 + public var stars: Int64 + public var transactionId: String + public var boostPeer: Api.Peer + public var giveawayMsgId: Int32 + public init(flags: Int32, stars: Int64, transactionId: String, boostPeer: Api.Peer, giveawayMsgId: Int32) { + self.flags = flags + self.stars = stars + self.transactionId = transactionId + self.boostPeer = boostPeer + self.giveawayMsgId = giveawayMsgId + } + } + public class Cons_messageActionRequestedPeer { + public var buttonId: Int32 + public var peers: [Api.Peer] + public init(buttonId: Int32, peers: [Api.Peer]) { + self.buttonId = buttonId + self.peers = peers + } + } + public class Cons_messageActionRequestedPeerSentMe { + public var buttonId: Int32 + public var peers: [Api.RequestedPeer] + public init(buttonId: Int32, peers: [Api.RequestedPeer]) { + self.buttonId = buttonId + self.peers = peers + } + } + public class Cons_messageActionSecureValuesSent { + public var types: [Api.SecureValueType] + public init(types: [Api.SecureValueType]) { + self.types = types + } + } + public class Cons_messageActionSecureValuesSentMe { + public var values: [Api.SecureValue] + public var credentials: Api.SecureCredentialsEncrypted + public init(values: [Api.SecureValue], credentials: Api.SecureCredentialsEncrypted) { + self.values = values + self.credentials = credentials + } + } + public class Cons_messageActionSetChatTheme { + public var theme: Api.ChatTheme + public init(theme: Api.ChatTheme) { + self.theme = theme + } + } + public class Cons_messageActionSetChatWallPaper { + public var flags: Int32 + public var wallpaper: Api.WallPaper + public init(flags: Int32, wallpaper: Api.WallPaper) { + self.flags = flags + self.wallpaper = wallpaper + } + } + public class Cons_messageActionSetMessagesTTL { + public var flags: Int32 + public var period: Int32 + public var autoSettingFrom: Int64? + public init(flags: Int32, period: Int32, autoSettingFrom: Int64?) { + self.flags = flags + self.period = period + self.autoSettingFrom = autoSettingFrom + } + } + public class Cons_messageActionStarGift { + public var flags: Int32 + public var gift: Api.StarGift + public var message: Api.TextWithEntities? + public var convertStars: Int64? + public var upgradeMsgId: Int32? + public var upgradeStars: Int64? + public var fromId: Api.Peer? + public var peer: Api.Peer? + public var savedId: Int64? + public var prepaidUpgradeHash: String? + public var giftMsgId: Int32? + public var toId: Api.Peer? + public var giftNum: Int32? + public init(flags: Int32, gift: Api.StarGift, message: Api.TextWithEntities?, convertStars: Int64?, upgradeMsgId: Int32?, upgradeStars: Int64?, fromId: Api.Peer?, peer: Api.Peer?, savedId: Int64?, prepaidUpgradeHash: String?, giftMsgId: Int32?, toId: Api.Peer?, giftNum: Int32?) { + self.flags = flags + self.gift = gift + self.message = message + self.convertStars = convertStars + self.upgradeMsgId = upgradeMsgId + self.upgradeStars = upgradeStars + self.fromId = fromId + self.peer = peer + self.savedId = savedId + self.prepaidUpgradeHash = prepaidUpgradeHash + self.giftMsgId = giftMsgId + self.toId = toId + self.giftNum = giftNum + } + } + public class Cons_messageActionStarGiftPurchaseOffer { + public var flags: Int32 + public var gift: Api.StarGift + public var price: Api.StarsAmount + public var expiresAt: Int32 + public init(flags: Int32, gift: Api.StarGift, price: Api.StarsAmount, expiresAt: Int32) { + self.flags = flags + self.gift = gift + self.price = price + self.expiresAt = expiresAt + } + } + public class Cons_messageActionStarGiftPurchaseOfferDeclined { + public var flags: Int32 + public var gift: Api.StarGift + public var price: Api.StarsAmount + public init(flags: Int32, gift: Api.StarGift, price: Api.StarsAmount) { + self.flags = flags + self.gift = gift + self.price = price + } + } + public class Cons_messageActionStarGiftUnique { + public var flags: Int32 + public var gift: Api.StarGift + public var canExportAt: Int32? + public var transferStars: Int64? + public var fromId: Api.Peer? + public var peer: Api.Peer? + public var savedId: Int64? + public var resaleAmount: Api.StarsAmount? + public var canTransferAt: Int32? + public var canResellAt: Int32? + public var dropOriginalDetailsStars: Int64? + public var canCraftAt: Int32? + public init(flags: Int32, gift: Api.StarGift, canExportAt: Int32?, transferStars: Int64?, fromId: Api.Peer?, peer: Api.Peer?, savedId: Int64?, resaleAmount: Api.StarsAmount?, canTransferAt: Int32?, canResellAt: Int32?, dropOriginalDetailsStars: Int64?, canCraftAt: Int32?) { + self.flags = flags + self.gift = gift + self.canExportAt = canExportAt + self.transferStars = transferStars + self.fromId = fromId + self.peer = peer + self.savedId = savedId + self.resaleAmount = resaleAmount + self.canTransferAt = canTransferAt + self.canResellAt = canResellAt + self.dropOriginalDetailsStars = dropOriginalDetailsStars + self.canCraftAt = canCraftAt + } + } + public class Cons_messageActionSuggestBirthday { + public var birthday: Api.Birthday + public init(birthday: Api.Birthday) { + self.birthday = birthday + } + } + public class Cons_messageActionSuggestProfilePhoto { + public var photo: Api.Photo + public init(photo: Api.Photo) { + self.photo = photo + } + } + public class Cons_messageActionSuggestedPostApproval { + public var flags: Int32 + public var rejectComment: String? + public var scheduleDate: Int32? + public var price: Api.StarsAmount? + public init(flags: Int32, rejectComment: String?, scheduleDate: Int32?, price: Api.StarsAmount?) { + self.flags = flags + self.rejectComment = rejectComment + self.scheduleDate = scheduleDate + self.price = price + } + } + public class Cons_messageActionSuggestedPostRefund { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } + public class Cons_messageActionSuggestedPostSuccess { + public var price: Api.StarsAmount + public init(price: Api.StarsAmount) { + self.price = price + } + } + public class Cons_messageActionTodoAppendTasks { + public var list: [Api.TodoItem] + public init(list: [Api.TodoItem]) { + self.list = list + } + } + public class Cons_messageActionTodoCompletions { + public var completed: [Int32] + public var incompleted: [Int32] + public init(completed: [Int32], incompleted: [Int32]) { + self.completed = completed + self.incompleted = incompleted + } + } + public class Cons_messageActionTopicCreate { + public var flags: Int32 + public var title: String + public var iconColor: Int32 + public var iconEmojiId: Int64? + public init(flags: Int32, title: String, iconColor: Int32, iconEmojiId: Int64?) { + self.flags = flags + self.title = title + self.iconColor = iconColor + self.iconEmojiId = iconEmojiId + } + } + public class Cons_messageActionTopicEdit { + public var flags: Int32 + public var title: String? + public var iconEmojiId: Int64? + public var closed: Api.Bool? + public var hidden: Api.Bool? + public init(flags: Int32, title: String?, iconEmojiId: Int64?, closed: Api.Bool?, hidden: Api.Bool?) { + self.flags = flags + self.title = title + self.iconEmojiId = iconEmojiId + self.closed = closed + self.hidden = hidden + } + } + public class Cons_messageActionWebViewDataSent { + public var text: String + public init(text: String) { + self.text = text + } + } + public class Cons_messageActionWebViewDataSentMe { + public var text: String + public var data: String + public init(text: String, data: String) { + self.text = text + self.data = data + } + } + case messageActionBoostApply(Cons_messageActionBoostApply) + case messageActionBotAllowed(Cons_messageActionBotAllowed) + case messageActionChangeCreator(Cons_messageActionChangeCreator) + case messageActionChannelCreate(Cons_messageActionChannelCreate) + case messageActionChannelMigrateFrom(Cons_messageActionChannelMigrateFrom) + case messageActionChatAddUser(Cons_messageActionChatAddUser) + case messageActionChatCreate(Cons_messageActionChatCreate) case messageActionChatDeletePhoto - case messageActionChatDeleteUser(userId: Int64) - case messageActionChatEditPhoto(photo: Api.Photo) - case messageActionChatEditTitle(title: String) - case messageActionChatJoinedByLink(inviterId: Int64) + case messageActionChatDeleteUser(Cons_messageActionChatDeleteUser) + case messageActionChatEditPhoto(Cons_messageActionChatEditPhoto) + case messageActionChatEditTitle(Cons_messageActionChatEditTitle) + case messageActionChatJoinedByLink(Cons_messageActionChatJoinedByLink) case messageActionChatJoinedByRequest - case messageActionChatMigrateTo(channelId: Int64) - case messageActionConferenceCall(flags: Int32, callId: Int64, duration: Int32?, otherParticipants: [Api.Peer]?) + case messageActionChatMigrateTo(Cons_messageActionChatMigrateTo) + case messageActionConferenceCall(Cons_messageActionConferenceCall) case messageActionContactSignUp - case messageActionCustomAction(message: String) + case messageActionCustomAction(Cons_messageActionCustomAction) case messageActionEmpty - case messageActionGameScore(gameId: Int64, score: Int32) - case messageActionGeoProximityReached(fromId: Api.Peer, toId: Api.Peer, distance: Int32) - case messageActionGiftCode(flags: Int32, boostPeer: Api.Peer?, days: Int32, slug: String, currency: String?, amount: Int64?, cryptoCurrency: String?, cryptoAmount: Int64?, message: Api.TextWithEntities?) - case messageActionGiftPremium(flags: Int32, currency: String, amount: Int64, days: Int32, cryptoCurrency: String?, cryptoAmount: Int64?, message: Api.TextWithEntities?) - case messageActionGiftStars(flags: Int32, currency: String, amount: Int64, stars: Int64, cryptoCurrency: String?, cryptoAmount: Int64?, transactionId: String?) - case messageActionGiftTon(flags: Int32, currency: String, amount: Int64, cryptoCurrency: String, cryptoAmount: Int64, transactionId: String?) - case messageActionGiveawayLaunch(flags: Int32, stars: Int64?) - case messageActionGiveawayResults(flags: Int32, winnersCount: Int32, unclaimedCount: Int32) - case messageActionGroupCall(flags: Int32, call: Api.InputGroupCall, duration: Int32?) - case messageActionGroupCallScheduled(call: Api.InputGroupCall, scheduleDate: Int32) + case messageActionGameScore(Cons_messageActionGameScore) + case messageActionGeoProximityReached(Cons_messageActionGeoProximityReached) + case messageActionGiftCode(Cons_messageActionGiftCode) + case messageActionGiftPremium(Cons_messageActionGiftPremium) + case messageActionGiftStars(Cons_messageActionGiftStars) + case messageActionGiftTon(Cons_messageActionGiftTon) + case messageActionGiveawayLaunch(Cons_messageActionGiveawayLaunch) + case messageActionGiveawayResults(Cons_messageActionGiveawayResults) + case messageActionGroupCall(Cons_messageActionGroupCall) + case messageActionGroupCallScheduled(Cons_messageActionGroupCallScheduled) case messageActionHistoryClear - case messageActionInviteToGroupCall(call: Api.InputGroupCall, users: [Int64]) - case messageActionPaidMessagesPrice(flags: Int32, stars: Int64) - case messageActionPaidMessagesRefunded(count: Int32, stars: Int64) - case messageActionPaymentRefunded(flags: Int32, peer: Api.Peer, currency: String, totalAmount: Int64, payload: Buffer?, charge: Api.PaymentCharge) - case messageActionPaymentSent(flags: Int32, currency: String, totalAmount: Int64, invoiceSlug: String?, subscriptionUntilDate: Int32?) - case messageActionPaymentSentMe(flags: Int32, currency: String, totalAmount: Int64, payload: Buffer, info: Api.PaymentRequestedInfo?, shippingOptionId: String?, charge: Api.PaymentCharge, subscriptionUntilDate: Int32?) - case messageActionPhoneCall(flags: Int32, callId: Int64, reason: Api.PhoneCallDiscardReason?, duration: Int32?) + case messageActionInviteToGroupCall(Cons_messageActionInviteToGroupCall) + case messageActionNewCreatorPending(Cons_messageActionNewCreatorPending) + case messageActionPaidMessagesPrice(Cons_messageActionPaidMessagesPrice) + case messageActionPaidMessagesRefunded(Cons_messageActionPaidMessagesRefunded) + case messageActionPaymentRefunded(Cons_messageActionPaymentRefunded) + case messageActionPaymentSent(Cons_messageActionPaymentSent) + case messageActionPaymentSentMe(Cons_messageActionPaymentSentMe) + case messageActionPhoneCall(Cons_messageActionPhoneCall) case messageActionPinMessage - case messageActionPrizeStars(flags: Int32, stars: Int64, transactionId: String, boostPeer: Api.Peer, giveawayMsgId: Int32) - case messageActionRequestedPeer(buttonId: Int32, peers: [Api.Peer]) - case messageActionRequestedPeerSentMe(buttonId: Int32, peers: [Api.RequestedPeer]) + case messageActionPrizeStars(Cons_messageActionPrizeStars) + case messageActionRequestedPeer(Cons_messageActionRequestedPeer) + case messageActionRequestedPeerSentMe(Cons_messageActionRequestedPeerSentMe) case messageActionScreenshotTaken - case messageActionSecureValuesSent(types: [Api.SecureValueType]) - case messageActionSecureValuesSentMe(values: [Api.SecureValue], credentials: Api.SecureCredentialsEncrypted) - case messageActionSetChatTheme(theme: Api.ChatTheme) - case messageActionSetChatWallPaper(flags: Int32, wallpaper: Api.WallPaper) - case messageActionSetMessagesTTL(flags: Int32, period: Int32, autoSettingFrom: Int64?) - case messageActionStarGift(flags: Int32, gift: Api.StarGift, message: Api.TextWithEntities?, convertStars: Int64?, upgradeMsgId: Int32?, upgradeStars: Int64?, fromId: Api.Peer?, peer: Api.Peer?, savedId: Int64?, prepaidUpgradeHash: String?, giftMsgId: Int32?, toId: Api.Peer?, giftNum: Int32?) - case messageActionStarGiftPurchaseOffer(flags: Int32, gift: Api.StarGift, price: Api.StarsAmount, expiresAt: Int32) - case messageActionStarGiftPurchaseOfferDeclined(flags: Int32, gift: Api.StarGift, price: Api.StarsAmount) - case messageActionStarGiftUnique(flags: Int32, gift: Api.StarGift, canExportAt: Int32?, transferStars: Int64?, fromId: Api.Peer?, peer: Api.Peer?, savedId: Int64?, resaleAmount: Api.StarsAmount?, canTransferAt: Int32?, canResellAt: Int32?, dropOriginalDetailsStars: Int64?) - case messageActionSuggestBirthday(birthday: Api.Birthday) - case messageActionSuggestProfilePhoto(photo: Api.Photo) - case messageActionSuggestedPostApproval(flags: Int32, rejectComment: String?, scheduleDate: Int32?, price: Api.StarsAmount?) - case messageActionSuggestedPostRefund(flags: Int32) - case messageActionSuggestedPostSuccess(price: Api.StarsAmount) - case messageActionTodoAppendTasks(list: [Api.TodoItem]) - case messageActionTodoCompletions(completed: [Int32], incompleted: [Int32]) - case messageActionTopicCreate(flags: Int32, title: String, iconColor: Int32, iconEmojiId: Int64?) - case messageActionTopicEdit(flags: Int32, title: String?, iconEmojiId: Int64?, closed: Api.Bool?, hidden: Api.Bool?) - case messageActionWebViewDataSent(text: String) - case messageActionWebViewDataSentMe(text: String, data: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messageActionBoostApply(let boosts): - if boxed { - buffer.appendInt32(-872240531) - } - serializeInt32(boosts, buffer: buffer, boxed: false) - break - case .messageActionBotAllowed(let flags, let domain, let app): - if boxed { - buffer.appendInt32(-988359047) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(domain!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {app!.serialize(buffer, true)} - break - case .messageActionChannelCreate(let title): - if boxed { - buffer.appendInt32(-1781355374) - } - serializeString(title, buffer: buffer, boxed: false) - break - case .messageActionChannelMigrateFrom(let title, let chatId): - if boxed { - buffer.appendInt32(-365344535) - } - serializeString(title, buffer: buffer, boxed: false) - serializeInt64(chatId, buffer: buffer, boxed: false) - break - case .messageActionChatAddUser(let users): - if boxed { - buffer.appendInt32(365886720) - } + case messageActionSecureValuesSent(Cons_messageActionSecureValuesSent) + case messageActionSecureValuesSentMe(Cons_messageActionSecureValuesSentMe) + case messageActionSetChatTheme(Cons_messageActionSetChatTheme) + case messageActionSetChatWallPaper(Cons_messageActionSetChatWallPaper) + case messageActionSetMessagesTTL(Cons_messageActionSetMessagesTTL) + case messageActionStarGift(Cons_messageActionStarGift) + case messageActionStarGiftPurchaseOffer(Cons_messageActionStarGiftPurchaseOffer) + case messageActionStarGiftPurchaseOfferDeclined(Cons_messageActionStarGiftPurchaseOfferDeclined) + case messageActionStarGiftUnique(Cons_messageActionStarGiftUnique) + case messageActionSuggestBirthday(Cons_messageActionSuggestBirthday) + case messageActionSuggestProfilePhoto(Cons_messageActionSuggestProfilePhoto) + case messageActionSuggestedPostApproval(Cons_messageActionSuggestedPostApproval) + case messageActionSuggestedPostRefund(Cons_messageActionSuggestedPostRefund) + case messageActionSuggestedPostSuccess(Cons_messageActionSuggestedPostSuccess) + case messageActionTodoAppendTasks(Cons_messageActionTodoAppendTasks) + case messageActionTodoCompletions(Cons_messageActionTodoCompletions) + case messageActionTopicCreate(Cons_messageActionTopicCreate) + case messageActionTopicEdit(Cons_messageActionTopicEdit) + case messageActionWebViewDataSent(Cons_messageActionWebViewDataSent) + case messageActionWebViewDataSentMe(Cons_messageActionWebViewDataSentMe) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messageActionBoostApply(let _data): + if boxed { + buffer.appendInt32(-872240531) + } + serializeInt32(_data.boosts, buffer: buffer, boxed: false) + break + case .messageActionBotAllowed(let _data): + if boxed { + buffer.appendInt32(-988359047) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.domain!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.app!.serialize(buffer, true) + } + break + case .messageActionChangeCreator(let _data): + if boxed { + buffer.appendInt32(-511160261) + } + serializeInt64(_data.newCreatorId, buffer: buffer, boxed: false) + break + case .messageActionChannelCreate(let _data): + if boxed { + buffer.appendInt32(-1781355374) + } + serializeString(_data.title, buffer: buffer, boxed: false) + break + case .messageActionChannelMigrateFrom(let _data): + if boxed { + buffer.appendInt32(-365344535) + } + serializeString(_data.title, buffer: buffer, boxed: false) + serializeInt64(_data.chatId, buffer: buffer, boxed: false) + break + case .messageActionChatAddUser(let _data): + if boxed { + buffer.appendInt32(365886720) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + serializeInt64(item, buffer: buffer, boxed: false) + } + break + case .messageActionChatCreate(let _data): + if boxed { + buffer.appendInt32(-1119368275) + } + serializeString(_data.title, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + serializeInt64(item, buffer: buffer, boxed: false) + } + break + case .messageActionChatDeletePhoto: + if boxed { + buffer.appendInt32(-1780220945) + } + break + case .messageActionChatDeleteUser(let _data): + if boxed { + buffer.appendInt32(-1539362612) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + break + case .messageActionChatEditPhoto(let _data): + if boxed { + buffer.appendInt32(2144015272) + } + _data.photo.serialize(buffer, true) + break + case .messageActionChatEditTitle(let _data): + if boxed { + buffer.appendInt32(-1247687078) + } + serializeString(_data.title, buffer: buffer, boxed: false) + break + case .messageActionChatJoinedByLink(let _data): + if boxed { + buffer.appendInt32(51520707) + } + serializeInt64(_data.inviterId, buffer: buffer, boxed: false) + break + case .messageActionChatJoinedByRequest: + if boxed { + buffer.appendInt32(-339958837) + } + break + case .messageActionChatMigrateTo(let _data): + if boxed { + buffer.appendInt32(-519864430) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + break + case .messageActionConferenceCall(let _data): + if boxed { + buffer.appendInt32(805187450) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.callId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.duration!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - serializeInt64(item, buffer: buffer, boxed: false) - } - break - case .messageActionChatCreate(let title, let users): - if boxed { - buffer.appendInt32(-1119368275) - } - serializeString(title, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - serializeInt64(item, buffer: buffer, boxed: false) - } - break - case .messageActionChatDeletePhoto: - if boxed { - buffer.appendInt32(-1780220945) - } - - break - case .messageActionChatDeleteUser(let userId): - if boxed { - buffer.appendInt32(-1539362612) - } - serializeInt64(userId, buffer: buffer, boxed: false) - break - case .messageActionChatEditPhoto(let photo): - if boxed { - buffer.appendInt32(2144015272) - } - photo.serialize(buffer, true) - break - case .messageActionChatEditTitle(let title): - if boxed { - buffer.appendInt32(-1247687078) - } - serializeString(title, buffer: buffer, boxed: false) - break - case .messageActionChatJoinedByLink(let inviterId): - if boxed { - buffer.appendInt32(51520707) - } - serializeInt64(inviterId, buffer: buffer, boxed: false) - break - case .messageActionChatJoinedByRequest: - if boxed { - buffer.appendInt32(-339958837) - } - - break - case .messageActionChatMigrateTo(let channelId): - if boxed { - buffer.appendInt32(-519864430) - } - serializeInt64(channelId, buffer: buffer, boxed: false) - break - case .messageActionConferenceCall(let flags, let callId, let duration, let otherParticipants): - if boxed { - buffer.appendInt32(805187450) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(callId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(duration!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(otherParticipants!.count)) - for item in otherParticipants! { - item.serialize(buffer, true) - }} - break - case .messageActionContactSignUp: - if boxed { - buffer.appendInt32(-202219658) - } - - break - case .messageActionCustomAction(let message): - if boxed { - buffer.appendInt32(-85549226) - } - serializeString(message, buffer: buffer, boxed: false) - break - case .messageActionEmpty: - if boxed { - buffer.appendInt32(-1230047312) - } - - break - case .messageActionGameScore(let gameId, let score): - if boxed { - buffer.appendInt32(-1834538890) - } - serializeInt64(gameId, buffer: buffer, boxed: false) - serializeInt32(score, buffer: buffer, boxed: false) - break - case .messageActionGeoProximityReached(let fromId, let toId, let distance): - if boxed { - buffer.appendInt32(-1730095465) - } - fromId.serialize(buffer, true) - toId.serialize(buffer, true) - serializeInt32(distance, buffer: buffer, boxed: false) - break - case .messageActionGiftCode(let flags, let boostPeer, let days, let slug, let currency, let amount, let cryptoCurrency, let cryptoAmount, let message): - if boxed { - buffer.appendInt32(834962247) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {boostPeer!.serialize(buffer, true)} - serializeInt32(days, buffer: buffer, boxed: false) - serializeString(slug, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeString(currency!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt64(amount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeString(cryptoCurrency!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt64(cryptoAmount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {message!.serialize(buffer, true)} - break - case .messageActionGiftPremium(let flags, let currency, let amount, let days, let cryptoCurrency, let cryptoAmount, let message): - if boxed { - buffer.appendInt32(1223234306) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - serializeInt32(days, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(cryptoCurrency!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(cryptoAmount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {message!.serialize(buffer, true)} - break - case .messageActionGiftStars(let flags, let currency, let amount, let stars, let cryptoCurrency, let cryptoAmount, let transactionId): - if boxed { - buffer.appendInt32(1171632161) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - serializeInt64(stars, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(cryptoCurrency!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(cryptoAmount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(transactionId!, buffer: buffer, boxed: false)} - break - case .messageActionGiftTon(let flags, let currency, let amount, let cryptoCurrency, let cryptoAmount, let transactionId): - if boxed { - buffer.appendInt32(-1465661799) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - serializeString(cryptoCurrency, buffer: buffer, boxed: false) - serializeInt64(cryptoAmount, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(transactionId!, buffer: buffer, boxed: false)} - break - case .messageActionGiveawayLaunch(let flags, let stars): - if boxed { - buffer.appendInt32(-1475391004) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(stars!, buffer: buffer, boxed: false)} - break - case .messageActionGiveawayResults(let flags, let winnersCount, let unclaimedCount): - if boxed { - buffer.appendInt32(-2015170219) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(winnersCount, buffer: buffer, boxed: false) - serializeInt32(unclaimedCount, buffer: buffer, boxed: false) - break - case .messageActionGroupCall(let flags, let call, let duration): - if boxed { - buffer.appendInt32(2047704898) - } - serializeInt32(flags, buffer: buffer, boxed: false) - call.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(duration!, buffer: buffer, boxed: false)} - break - case .messageActionGroupCallScheduled(let call, let scheduleDate): - if boxed { - buffer.appendInt32(-1281329567) - } - call.serialize(buffer, true) - serializeInt32(scheduleDate, buffer: buffer, boxed: false) - break - case .messageActionHistoryClear: - if boxed { - buffer.appendInt32(-1615153660) - } - - break - case .messageActionInviteToGroupCall(let call, let users): - if boxed { - buffer.appendInt32(1345295095) - } - call.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - serializeInt64(item, buffer: buffer, boxed: false) - } - break - case .messageActionPaidMessagesPrice(let flags, let stars): - if boxed { - buffer.appendInt32(-2068281992) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(stars, buffer: buffer, boxed: false) - break - case .messageActionPaidMessagesRefunded(let count, let stars): - if boxed { - buffer.appendInt32(-1407246387) - } - serializeInt32(count, buffer: buffer, boxed: false) - serializeInt64(stars, buffer: buffer, boxed: false) - break - case .messageActionPaymentRefunded(let flags, let peer, let currency, let totalAmount, let payload, let charge): - if boxed { - buffer.appendInt32(1102307842) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(totalAmount, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeBytes(payload!, buffer: buffer, boxed: false)} - charge.serialize(buffer, true) - break - case .messageActionPaymentSent(let flags, let currency, let totalAmount, let invoiceSlug, let subscriptionUntilDate): - if boxed { - buffer.appendInt32(-970673810) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(totalAmount, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(invoiceSlug!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(subscriptionUntilDate!, buffer: buffer, boxed: false)} - break - case .messageActionPaymentSentMe(let flags, let currency, let totalAmount, let payload, let info, let shippingOptionId, let charge, let subscriptionUntilDate): - if boxed { - buffer.appendInt32(-6288180) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(totalAmount, buffer: buffer, boxed: false) - serializeBytes(payload, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {info!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(shippingOptionId!, buffer: buffer, boxed: false)} - charge.serialize(buffer, true) - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(subscriptionUntilDate!, buffer: buffer, boxed: false)} - break - case .messageActionPhoneCall(let flags, let callId, let reason, let duration): - if boxed { - buffer.appendInt32(-2132731265) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(callId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {reason!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(duration!, buffer: buffer, boxed: false)} - break - case .messageActionPinMessage: - if boxed { - buffer.appendInt32(-1799538451) - } - - break - case .messageActionPrizeStars(let flags, let stars, let transactionId, let boostPeer, let giveawayMsgId): - if boxed { - buffer.appendInt32(-1341372510) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(stars, buffer: buffer, boxed: false) - serializeString(transactionId, buffer: buffer, boxed: false) - boostPeer.serialize(buffer, true) - serializeInt32(giveawayMsgId, buffer: buffer, boxed: false) - break - case .messageActionRequestedPeer(let buttonId, let peers): - if boxed { - buffer.appendInt32(827428507) - } - serializeInt32(buttonId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peers.count)) - for item in peers { + buffer.appendInt32(Int32(_data.otherParticipants!.count)) + for item in _data.otherParticipants! { item.serialize(buffer, true) } - break - case .messageActionRequestedPeerSentMe(let buttonId, let peers): - if boxed { - buffer.appendInt32(-1816979384) - } - serializeInt32(buttonId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peers.count)) - for item in peers { - item.serialize(buffer, true) - } - break - case .messageActionScreenshotTaken: - if boxed { - buffer.appendInt32(1200788123) - } - - break - case .messageActionSecureValuesSent(let types): - if boxed { - buffer.appendInt32(-648257196) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(types.count)) - for item in types { - item.serialize(buffer, true) - } - break - case .messageActionSecureValuesSentMe(let values, let credentials): - if boxed { - buffer.appendInt32(455635795) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(values.count)) - for item in values { - item.serialize(buffer, true) - } - credentials.serialize(buffer, true) - break - case .messageActionSetChatTheme(let theme): - if boxed { - buffer.appendInt32(-1189364422) - } - theme.serialize(buffer, true) - break - case .messageActionSetChatWallPaper(let flags, let wallpaper): - if boxed { - buffer.appendInt32(1348510708) - } - serializeInt32(flags, buffer: buffer, boxed: false) - wallpaper.serialize(buffer, true) - break - case .messageActionSetMessagesTTL(let flags, let period, let autoSettingFrom): - if boxed { - buffer.appendInt32(1007897979) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(period, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(autoSettingFrom!, buffer: buffer, boxed: false)} - break - case .messageActionStarGift(let flags, let gift, let message, let convertStars, let upgradeMsgId, let upgradeStars, let fromId, let peer, let savedId, let prepaidUpgradeHash, let giftMsgId, let toId, let giftNum): - if boxed { - buffer.appendInt32(-366202413) - } - serializeInt32(flags, buffer: buffer, boxed: false) - gift.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {message!.serialize(buffer, true)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt64(convertStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeInt32(upgradeMsgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {serializeInt64(upgradeStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 11) != 0 {fromId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 12) != 0 {peer!.serialize(buffer, true)} - if Int(flags) & Int(1 << 12) != 0 {serializeInt64(savedId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 14) != 0 {serializeString(prepaidUpgradeHash!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 15) != 0 {serializeInt32(giftMsgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 18) != 0 {toId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 19) != 0 {serializeInt32(giftNum!, buffer: buffer, boxed: false)} - break - case .messageActionStarGiftPurchaseOffer(let flags, let gift, let price, let expiresAt): - if boxed { - buffer.appendInt32(2000845012) - } - serializeInt32(flags, buffer: buffer, boxed: false) - gift.serialize(buffer, true) - price.serialize(buffer, true) - serializeInt32(expiresAt, buffer: buffer, boxed: false) - break - case .messageActionStarGiftPurchaseOfferDeclined(let flags, let gift, let price): - if boxed { - buffer.appendInt32(1940760427) - } - serializeInt32(flags, buffer: buffer, boxed: false) - gift.serialize(buffer, true) - price.serialize(buffer, true) - break - case .messageActionStarGiftUnique(let flags, let gift, let canExportAt, let transferStars, let fromId, let peer, let savedId, let resaleAmount, let canTransferAt, let canResellAt, let dropOriginalDetailsStars): - if boxed { - buffer.appendInt32(-1787656893) - } - serializeInt32(flags, buffer: buffer, boxed: false) - gift.serialize(buffer, true) - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(canExportAt!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt64(transferStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 6) != 0 {fromId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 7) != 0 {peer!.serialize(buffer, true)} - if Int(flags) & Int(1 << 7) != 0 {serializeInt64(savedId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {resaleAmount!.serialize(buffer, true)} - if Int(flags) & Int(1 << 9) != 0 {serializeInt32(canTransferAt!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 10) != 0 {serializeInt32(canResellAt!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 12) != 0 {serializeInt64(dropOriginalDetailsStars!, buffer: buffer, boxed: false)} - break - case .messageActionSuggestBirthday(let birthday): - if boxed { - buffer.appendInt32(747579941) - } - birthday.serialize(buffer, true) - break - case .messageActionSuggestProfilePhoto(let photo): - if boxed { - buffer.appendInt32(1474192222) - } - photo.serialize(buffer, true) - break - case .messageActionSuggestedPostApproval(let flags, let rejectComment, let scheduleDate, let price): - if boxed { - buffer.appendInt32(-293988970) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeString(rejectComment!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(scheduleDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {price!.serialize(buffer, true)} - break - case .messageActionSuggestedPostRefund(let flags): - if boxed { - buffer.appendInt32(1777932024) - } - serializeInt32(flags, buffer: buffer, boxed: false) - break - case .messageActionSuggestedPostSuccess(let price): - if boxed { - buffer.appendInt32(-1780625559) - } - price.serialize(buffer, true) - break - case .messageActionTodoAppendTasks(let list): - if boxed { - buffer.appendInt32(-940721021) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(list.count)) - for item in list { - item.serialize(buffer, true) - } - break - case .messageActionTodoCompletions(let completed, let incompleted): - if boxed { - buffer.appendInt32(-864265079) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(completed.count)) - for item in completed { - serializeInt32(item, buffer: buffer, boxed: false) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(incompleted.count)) - for item in incompleted { - serializeInt32(item, buffer: buffer, boxed: false) - } - break - case .messageActionTopicCreate(let flags, let title, let iconColor, let iconEmojiId): - if boxed { - buffer.appendInt32(228168278) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeInt32(iconColor, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(iconEmojiId!, buffer: buffer, boxed: false)} - break - case .messageActionTopicEdit(let flags, let title, let iconEmojiId, let closed, let hidden): - if boxed { - buffer.appendInt32(-1064024032) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt64(iconEmojiId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {closed!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {hidden!.serialize(buffer, true)} - break - case .messageActionWebViewDataSent(let text): - if boxed { - buffer.appendInt32(-1262252875) - } - serializeString(text, buffer: buffer, boxed: false) - break - case .messageActionWebViewDataSentMe(let text, let data): - if boxed { - buffer.appendInt32(1205698681) - } - serializeString(text, buffer: buffer, boxed: false) - serializeString(data, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messageActionBoostApply(let boosts): - return ("messageActionBoostApply", [("boosts", boosts as Any)]) - case .messageActionBotAllowed(let flags, let domain, let app): - return ("messageActionBotAllowed", [("flags", flags as Any), ("domain", domain as Any), ("app", app as Any)]) - case .messageActionChannelCreate(let title): - return ("messageActionChannelCreate", [("title", title as Any)]) - case .messageActionChannelMigrateFrom(let title, let chatId): - return ("messageActionChannelMigrateFrom", [("title", title as Any), ("chatId", chatId as Any)]) - case .messageActionChatAddUser(let users): - return ("messageActionChatAddUser", [("users", users as Any)]) - case .messageActionChatCreate(let title, let users): - return ("messageActionChatCreate", [("title", title as Any), ("users", users as Any)]) - case .messageActionChatDeletePhoto: + } + break + case .messageActionContactSignUp: + if boxed { + buffer.appendInt32(-202219658) + } + break + case .messageActionCustomAction(let _data): + if boxed { + buffer.appendInt32(-85549226) + } + serializeString(_data.message, buffer: buffer, boxed: false) + break + case .messageActionEmpty: + if boxed { + buffer.appendInt32(-1230047312) + } + break + case .messageActionGameScore(let _data): + if boxed { + buffer.appendInt32(-1834538890) + } + serializeInt64(_data.gameId, buffer: buffer, boxed: false) + serializeInt32(_data.score, buffer: buffer, boxed: false) + break + case .messageActionGeoProximityReached(let _data): + if boxed { + buffer.appendInt32(-1730095465) + } + _data.fromId.serialize(buffer, true) + _data.toId.serialize(buffer, true) + serializeInt32(_data.distance, buffer: buffer, boxed: false) + break + case .messageActionGiftCode(let _data): + if boxed { + buffer.appendInt32(834962247) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.boostPeer!.serialize(buffer, true) + } + serializeInt32(_data.days, buffer: buffer, boxed: false) + serializeString(_data.slug, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.currency!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt64(_data.amount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.cryptoCurrency!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt64(_data.cryptoAmount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + _data.message!.serialize(buffer, true) + } + break + case .messageActionGiftPremium(let _data): + if boxed { + buffer.appendInt32(1223234306) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + serializeInt32(_data.days, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.cryptoCurrency!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.cryptoAmount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.message!.serialize(buffer, true) + } + break + case .messageActionGiftStars(let _data): + if boxed { + buffer.appendInt32(1171632161) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + serializeInt64(_data.stars, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.cryptoCurrency!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.cryptoAmount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.transactionId!, buffer: buffer, boxed: false) + } + break + case .messageActionGiftTon(let _data): + if boxed { + buffer.appendInt32(-1465661799) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + serializeString(_data.cryptoCurrency, buffer: buffer, boxed: false) + serializeInt64(_data.cryptoAmount, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.transactionId!, buffer: buffer, boxed: false) + } + break + case .messageActionGiveawayLaunch(let _data): + if boxed { + buffer.appendInt32(-1475391004) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.stars!, buffer: buffer, boxed: false) + } + break + case .messageActionGiveawayResults(let _data): + if boxed { + buffer.appendInt32(-2015170219) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.winnersCount, buffer: buffer, boxed: false) + serializeInt32(_data.unclaimedCount, buffer: buffer, boxed: false) + break + case .messageActionGroupCall(let _data): + if boxed { + buffer.appendInt32(2047704898) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.call.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.duration!, buffer: buffer, boxed: false) + } + break + case .messageActionGroupCallScheduled(let _data): + if boxed { + buffer.appendInt32(-1281329567) + } + _data.call.serialize(buffer, true) + serializeInt32(_data.scheduleDate, buffer: buffer, boxed: false) + break + case .messageActionHistoryClear: + if boxed { + buffer.appendInt32(-1615153660) + } + break + case .messageActionInviteToGroupCall(let _data): + if boxed { + buffer.appendInt32(1345295095) + } + _data.call.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + serializeInt64(item, buffer: buffer, boxed: false) + } + break + case .messageActionNewCreatorPending(let _data): + if boxed { + buffer.appendInt32(-1333866363) + } + serializeInt64(_data.newCreatorId, buffer: buffer, boxed: false) + break + case .messageActionPaidMessagesPrice(let _data): + if boxed { + buffer.appendInt32(-2068281992) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.stars, buffer: buffer, boxed: false) + break + case .messageActionPaidMessagesRefunded(let _data): + if boxed { + buffer.appendInt32(-1407246387) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + serializeInt64(_data.stars, buffer: buffer, boxed: false) + break + case .messageActionPaymentRefunded(let _data): + if boxed { + buffer.appendInt32(1102307842) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.totalAmount, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeBytes(_data.payload!, buffer: buffer, boxed: false) + } + _data.charge.serialize(buffer, true) + break + case .messageActionPaymentSent(let _data): + if boxed { + buffer.appendInt32(-970673810) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.totalAmount, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.invoiceSlug!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.subscriptionUntilDate!, buffer: buffer, boxed: false) + } + break + case .messageActionPaymentSentMe(let _data): + if boxed { + buffer.appendInt32(-6288180) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.totalAmount, buffer: buffer, boxed: false) + serializeBytes(_data.payload, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.info!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.shippingOptionId!, buffer: buffer, boxed: false) + } + _data.charge.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.subscriptionUntilDate!, buffer: buffer, boxed: false) + } + break + case .messageActionPhoneCall(let _data): + if boxed { + buffer.appendInt32(-2132731265) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.callId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.reason!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.duration!, buffer: buffer, boxed: false) + } + break + case .messageActionPinMessage: + if boxed { + buffer.appendInt32(-1799538451) + } + break + case .messageActionPrizeStars(let _data): + if boxed { + buffer.appendInt32(-1341372510) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.stars, buffer: buffer, boxed: false) + serializeString(_data.transactionId, buffer: buffer, boxed: false) + _data.boostPeer.serialize(buffer, true) + serializeInt32(_data.giveawayMsgId, buffer: buffer, boxed: false) + break + case .messageActionRequestedPeer(let _data): + if boxed { + buffer.appendInt32(827428507) + } + serializeInt32(_data.buttonId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.peers.count)) + for item in _data.peers { + item.serialize(buffer, true) + } + break + case .messageActionRequestedPeerSentMe(let _data): + if boxed { + buffer.appendInt32(-1816979384) + } + serializeInt32(_data.buttonId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.peers.count)) + for item in _data.peers { + item.serialize(buffer, true) + } + break + case .messageActionScreenshotTaken: + if boxed { + buffer.appendInt32(1200788123) + } + break + case .messageActionSecureValuesSent(let _data): + if boxed { + buffer.appendInt32(-648257196) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.types.count)) + for item in _data.types { + item.serialize(buffer, true) + } + break + case .messageActionSecureValuesSentMe(let _data): + if boxed { + buffer.appendInt32(455635795) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.values.count)) + for item in _data.values { + item.serialize(buffer, true) + } + _data.credentials.serialize(buffer, true) + break + case .messageActionSetChatTheme(let _data): + if boxed { + buffer.appendInt32(-1189364422) + } + _data.theme.serialize(buffer, true) + break + case .messageActionSetChatWallPaper(let _data): + if boxed { + buffer.appendInt32(1348510708) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.wallpaper.serialize(buffer, true) + break + case .messageActionSetMessagesTTL(let _data): + if boxed { + buffer.appendInt32(1007897979) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.period, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.autoSettingFrom!, buffer: buffer, boxed: false) + } + break + case .messageActionStarGift(let _data): + if boxed { + buffer.appendInt32(-366202413) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.gift.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.message!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt64(_data.convertStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeInt32(_data.upgradeMsgId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + serializeInt64(_data.upgradeStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 11) != 0 { + _data.fromId!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 12) != 0 { + _data.peer!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 12) != 0 { + serializeInt64(_data.savedId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 14) != 0 { + serializeString(_data.prepaidUpgradeHash!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 15) != 0 { + serializeInt32(_data.giftMsgId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 18) != 0 { + _data.toId!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 19) != 0 { + serializeInt32(_data.giftNum!, buffer: buffer, boxed: false) + } + break + case .messageActionStarGiftPurchaseOffer(let _data): + if boxed { + buffer.appendInt32(2000845012) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.gift.serialize(buffer, true) + _data.price.serialize(buffer, true) + serializeInt32(_data.expiresAt, buffer: buffer, boxed: false) + break + case .messageActionStarGiftPurchaseOfferDeclined(let _data): + if boxed { + buffer.appendInt32(1940760427) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.gift.serialize(buffer, true) + _data.price.serialize(buffer, true) + break + case .messageActionStarGiftUnique(let _data): + if boxed { + buffer.appendInt32(-423422686) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.gift.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.canExportAt!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt64(_data.transferStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + _data.fromId!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 7) != 0 { + _data.peer!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 7) != 0 { + serializeInt64(_data.savedId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + _data.resaleAmount!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 9) != 0 { + serializeInt32(_data.canTransferAt!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 10) != 0 { + serializeInt32(_data.canResellAt!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 12) != 0 { + serializeInt64(_data.dropOriginalDetailsStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 15) != 0 { + serializeInt32(_data.canCraftAt!, buffer: buffer, boxed: false) + } + break + case .messageActionSuggestBirthday(let _data): + if boxed { + buffer.appendInt32(747579941) + } + _data.birthday.serialize(buffer, true) + break + case .messageActionSuggestProfilePhoto(let _data): + if boxed { + buffer.appendInt32(1474192222) + } + _data.photo.serialize(buffer, true) + break + case .messageActionSuggestedPostApproval(let _data): + if boxed { + buffer.appendInt32(-293988970) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.rejectComment!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.scheduleDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + _data.price!.serialize(buffer, true) + } + break + case .messageActionSuggestedPostRefund(let _data): + if boxed { + buffer.appendInt32(1777932024) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + case .messageActionSuggestedPostSuccess(let _data): + if boxed { + buffer.appendInt32(-1780625559) + } + _data.price.serialize(buffer, true) + break + case .messageActionTodoAppendTasks(let _data): + if boxed { + buffer.appendInt32(-940721021) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.list.count)) + for item in _data.list { + item.serialize(buffer, true) + } + break + case .messageActionTodoCompletions(let _data): + if boxed { + buffer.appendInt32(-864265079) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.completed.count)) + for item in _data.completed { + serializeInt32(item, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.incompleted.count)) + for item in _data.incompleted { + serializeInt32(item, buffer: buffer, boxed: false) + } + break + case .messageActionTopicCreate(let _data): + if boxed { + buffer.appendInt32(228168278) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeInt32(_data.iconColor, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.iconEmojiId!, buffer: buffer, boxed: false) + } + break + case .messageActionTopicEdit(let _data): + if boxed { + buffer.appendInt32(-1064024032) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt64(_data.iconEmojiId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.closed!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.hidden!.serialize(buffer, true) + } + break + case .messageActionWebViewDataSent(let _data): + if boxed { + buffer.appendInt32(-1262252875) + } + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .messageActionWebViewDataSentMe(let _data): + if boxed { + buffer.appendInt32(1205698681) + } + serializeString(_data.text, buffer: buffer, boxed: false) + serializeString(_data.data, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messageActionBoostApply(let _data): + return ("messageActionBoostApply", [("boosts", _data.boosts as Any)]) + case .messageActionBotAllowed(let _data): + return ("messageActionBotAllowed", [("flags", _data.flags as Any), ("domain", _data.domain as Any), ("app", _data.app as Any)]) + case .messageActionChangeCreator(let _data): + return ("messageActionChangeCreator", [("newCreatorId", _data.newCreatorId as Any)]) + case .messageActionChannelCreate(let _data): + return ("messageActionChannelCreate", [("title", _data.title as Any)]) + case .messageActionChannelMigrateFrom(let _data): + return ("messageActionChannelMigrateFrom", [("title", _data.title as Any), ("chatId", _data.chatId as Any)]) + case .messageActionChatAddUser(let _data): + return ("messageActionChatAddUser", [("users", _data.users as Any)]) + case .messageActionChatCreate(let _data): + return ("messageActionChatCreate", [("title", _data.title as Any), ("users", _data.users as Any)]) + case .messageActionChatDeletePhoto: return ("messageActionChatDeletePhoto", []) - case .messageActionChatDeleteUser(let userId): - return ("messageActionChatDeleteUser", [("userId", userId as Any)]) - case .messageActionChatEditPhoto(let photo): - return ("messageActionChatEditPhoto", [("photo", photo as Any)]) - case .messageActionChatEditTitle(let title): - return ("messageActionChatEditTitle", [("title", title as Any)]) - case .messageActionChatJoinedByLink(let inviterId): - return ("messageActionChatJoinedByLink", [("inviterId", inviterId as Any)]) - case .messageActionChatJoinedByRequest: + case .messageActionChatDeleteUser(let _data): + return ("messageActionChatDeleteUser", [("userId", _data.userId as Any)]) + case .messageActionChatEditPhoto(let _data): + return ("messageActionChatEditPhoto", [("photo", _data.photo as Any)]) + case .messageActionChatEditTitle(let _data): + return ("messageActionChatEditTitle", [("title", _data.title as Any)]) + case .messageActionChatJoinedByLink(let _data): + return ("messageActionChatJoinedByLink", [("inviterId", _data.inviterId as Any)]) + case .messageActionChatJoinedByRequest: return ("messageActionChatJoinedByRequest", []) - case .messageActionChatMigrateTo(let channelId): - return ("messageActionChatMigrateTo", [("channelId", channelId as Any)]) - case .messageActionConferenceCall(let flags, let callId, let duration, let otherParticipants): - return ("messageActionConferenceCall", [("flags", flags as Any), ("callId", callId as Any), ("duration", duration as Any), ("otherParticipants", otherParticipants as Any)]) - case .messageActionContactSignUp: + case .messageActionChatMigrateTo(let _data): + return ("messageActionChatMigrateTo", [("channelId", _data.channelId as Any)]) + case .messageActionConferenceCall(let _data): + return ("messageActionConferenceCall", [("flags", _data.flags as Any), ("callId", _data.callId as Any), ("duration", _data.duration as Any), ("otherParticipants", _data.otherParticipants as Any)]) + case .messageActionContactSignUp: return ("messageActionContactSignUp", []) - case .messageActionCustomAction(let message): - return ("messageActionCustomAction", [("message", message as Any)]) - case .messageActionEmpty: + case .messageActionCustomAction(let _data): + return ("messageActionCustomAction", [("message", _data.message as Any)]) + case .messageActionEmpty: return ("messageActionEmpty", []) - case .messageActionGameScore(let gameId, let score): - return ("messageActionGameScore", [("gameId", gameId as Any), ("score", score as Any)]) - case .messageActionGeoProximityReached(let fromId, let toId, let distance): - return ("messageActionGeoProximityReached", [("fromId", fromId as Any), ("toId", toId as Any), ("distance", distance as Any)]) - case .messageActionGiftCode(let flags, let boostPeer, let days, let slug, let currency, let amount, let cryptoCurrency, let cryptoAmount, let message): - return ("messageActionGiftCode", [("flags", flags as Any), ("boostPeer", boostPeer as Any), ("days", days as Any), ("slug", slug as Any), ("currency", currency as Any), ("amount", amount as Any), ("cryptoCurrency", cryptoCurrency as Any), ("cryptoAmount", cryptoAmount as Any), ("message", message as Any)]) - case .messageActionGiftPremium(let flags, let currency, let amount, let days, let cryptoCurrency, let cryptoAmount, let message): - return ("messageActionGiftPremium", [("flags", flags as Any), ("currency", currency as Any), ("amount", amount as Any), ("days", days as Any), ("cryptoCurrency", cryptoCurrency as Any), ("cryptoAmount", cryptoAmount as Any), ("message", message as Any)]) - case .messageActionGiftStars(let flags, let currency, let amount, let stars, let cryptoCurrency, let cryptoAmount, let transactionId): - return ("messageActionGiftStars", [("flags", flags as Any), ("currency", currency as Any), ("amount", amount as Any), ("stars", stars as Any), ("cryptoCurrency", cryptoCurrency as Any), ("cryptoAmount", cryptoAmount as Any), ("transactionId", transactionId as Any)]) - case .messageActionGiftTon(let flags, let currency, let amount, let cryptoCurrency, let cryptoAmount, let transactionId): - return ("messageActionGiftTon", [("flags", flags as Any), ("currency", currency as Any), ("amount", amount as Any), ("cryptoCurrency", cryptoCurrency as Any), ("cryptoAmount", cryptoAmount as Any), ("transactionId", transactionId as Any)]) - case .messageActionGiveawayLaunch(let flags, let stars): - return ("messageActionGiveawayLaunch", [("flags", flags as Any), ("stars", stars as Any)]) - case .messageActionGiveawayResults(let flags, let winnersCount, let unclaimedCount): - return ("messageActionGiveawayResults", [("flags", flags as Any), ("winnersCount", winnersCount as Any), ("unclaimedCount", unclaimedCount as Any)]) - case .messageActionGroupCall(let flags, let call, let duration): - return ("messageActionGroupCall", [("flags", flags as Any), ("call", call as Any), ("duration", duration as Any)]) - case .messageActionGroupCallScheduled(let call, let scheduleDate): - return ("messageActionGroupCallScheduled", [("call", call as Any), ("scheduleDate", scheduleDate as Any)]) - case .messageActionHistoryClear: + case .messageActionGameScore(let _data): + return ("messageActionGameScore", [("gameId", _data.gameId as Any), ("score", _data.score as Any)]) + case .messageActionGeoProximityReached(let _data): + return ("messageActionGeoProximityReached", [("fromId", _data.fromId as Any), ("toId", _data.toId as Any), ("distance", _data.distance as Any)]) + case .messageActionGiftCode(let _data): + return ("messageActionGiftCode", [("flags", _data.flags as Any), ("boostPeer", _data.boostPeer as Any), ("days", _data.days as Any), ("slug", _data.slug as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any), ("cryptoCurrency", _data.cryptoCurrency as Any), ("cryptoAmount", _data.cryptoAmount as Any), ("message", _data.message as Any)]) + case .messageActionGiftPremium(let _data): + return ("messageActionGiftPremium", [("flags", _data.flags as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any), ("days", _data.days as Any), ("cryptoCurrency", _data.cryptoCurrency as Any), ("cryptoAmount", _data.cryptoAmount as Any), ("message", _data.message as Any)]) + case .messageActionGiftStars(let _data): + return ("messageActionGiftStars", [("flags", _data.flags as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any), ("stars", _data.stars as Any), ("cryptoCurrency", _data.cryptoCurrency as Any), ("cryptoAmount", _data.cryptoAmount as Any), ("transactionId", _data.transactionId as Any)]) + case .messageActionGiftTon(let _data): + return ("messageActionGiftTon", [("flags", _data.flags as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any), ("cryptoCurrency", _data.cryptoCurrency as Any), ("cryptoAmount", _data.cryptoAmount as Any), ("transactionId", _data.transactionId as Any)]) + case .messageActionGiveawayLaunch(let _data): + return ("messageActionGiveawayLaunch", [("flags", _data.flags as Any), ("stars", _data.stars as Any)]) + case .messageActionGiveawayResults(let _data): + return ("messageActionGiveawayResults", [("flags", _data.flags as Any), ("winnersCount", _data.winnersCount as Any), ("unclaimedCount", _data.unclaimedCount as Any)]) + case .messageActionGroupCall(let _data): + return ("messageActionGroupCall", [("flags", _data.flags as Any), ("call", _data.call as Any), ("duration", _data.duration as Any)]) + case .messageActionGroupCallScheduled(let _data): + return ("messageActionGroupCallScheduled", [("call", _data.call as Any), ("scheduleDate", _data.scheduleDate as Any)]) + case .messageActionHistoryClear: return ("messageActionHistoryClear", []) - case .messageActionInviteToGroupCall(let call, let users): - return ("messageActionInviteToGroupCall", [("call", call as Any), ("users", users as Any)]) - case .messageActionPaidMessagesPrice(let flags, let stars): - return ("messageActionPaidMessagesPrice", [("flags", flags as Any), ("stars", stars as Any)]) - case .messageActionPaidMessagesRefunded(let count, let stars): - return ("messageActionPaidMessagesRefunded", [("count", count as Any), ("stars", stars as Any)]) - case .messageActionPaymentRefunded(let flags, let peer, let currency, let totalAmount, let payload, let charge): - return ("messageActionPaymentRefunded", [("flags", flags as Any), ("peer", peer as Any), ("currency", currency as Any), ("totalAmount", totalAmount as Any), ("payload", payload as Any), ("charge", charge as Any)]) - case .messageActionPaymentSent(let flags, let currency, let totalAmount, let invoiceSlug, let subscriptionUntilDate): - return ("messageActionPaymentSent", [("flags", flags as Any), ("currency", currency as Any), ("totalAmount", totalAmount as Any), ("invoiceSlug", invoiceSlug as Any), ("subscriptionUntilDate", subscriptionUntilDate as Any)]) - case .messageActionPaymentSentMe(let flags, let currency, let totalAmount, let payload, let info, let shippingOptionId, let charge, let subscriptionUntilDate): - return ("messageActionPaymentSentMe", [("flags", flags as Any), ("currency", currency as Any), ("totalAmount", totalAmount as Any), ("payload", payload as Any), ("info", info as Any), ("shippingOptionId", shippingOptionId as Any), ("charge", charge as Any), ("subscriptionUntilDate", subscriptionUntilDate as Any)]) - case .messageActionPhoneCall(let flags, let callId, let reason, let duration): - return ("messageActionPhoneCall", [("flags", flags as Any), ("callId", callId as Any), ("reason", reason as Any), ("duration", duration as Any)]) - case .messageActionPinMessage: + case .messageActionInviteToGroupCall(let _data): + return ("messageActionInviteToGroupCall", [("call", _data.call as Any), ("users", _data.users as Any)]) + case .messageActionNewCreatorPending(let _data): + return ("messageActionNewCreatorPending", [("newCreatorId", _data.newCreatorId as Any)]) + case .messageActionPaidMessagesPrice(let _data): + return ("messageActionPaidMessagesPrice", [("flags", _data.flags as Any), ("stars", _data.stars as Any)]) + case .messageActionPaidMessagesRefunded(let _data): + return ("messageActionPaidMessagesRefunded", [("count", _data.count as Any), ("stars", _data.stars as Any)]) + case .messageActionPaymentRefunded(let _data): + return ("messageActionPaymentRefunded", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("currency", _data.currency as Any), ("totalAmount", _data.totalAmount as Any), ("payload", _data.payload as Any), ("charge", _data.charge as Any)]) + case .messageActionPaymentSent(let _data): + return ("messageActionPaymentSent", [("flags", _data.flags as Any), ("currency", _data.currency as Any), ("totalAmount", _data.totalAmount as Any), ("invoiceSlug", _data.invoiceSlug as Any), ("subscriptionUntilDate", _data.subscriptionUntilDate as Any)]) + case .messageActionPaymentSentMe(let _data): + return ("messageActionPaymentSentMe", [("flags", _data.flags as Any), ("currency", _data.currency as Any), ("totalAmount", _data.totalAmount as Any), ("payload", _data.payload as Any), ("info", _data.info as Any), ("shippingOptionId", _data.shippingOptionId as Any), ("charge", _data.charge as Any), ("subscriptionUntilDate", _data.subscriptionUntilDate as Any)]) + case .messageActionPhoneCall(let _data): + return ("messageActionPhoneCall", [("flags", _data.flags as Any), ("callId", _data.callId as Any), ("reason", _data.reason as Any), ("duration", _data.duration as Any)]) + case .messageActionPinMessage: return ("messageActionPinMessage", []) - case .messageActionPrizeStars(let flags, let stars, let transactionId, let boostPeer, let giveawayMsgId): - return ("messageActionPrizeStars", [("flags", flags as Any), ("stars", stars as Any), ("transactionId", transactionId as Any), ("boostPeer", boostPeer as Any), ("giveawayMsgId", giveawayMsgId as Any)]) - case .messageActionRequestedPeer(let buttonId, let peers): - return ("messageActionRequestedPeer", [("buttonId", buttonId as Any), ("peers", peers as Any)]) - case .messageActionRequestedPeerSentMe(let buttonId, let peers): - return ("messageActionRequestedPeerSentMe", [("buttonId", buttonId as Any), ("peers", peers as Any)]) - case .messageActionScreenshotTaken: + case .messageActionPrizeStars(let _data): + return ("messageActionPrizeStars", [("flags", _data.flags as Any), ("stars", _data.stars as Any), ("transactionId", _data.transactionId as Any), ("boostPeer", _data.boostPeer as Any), ("giveawayMsgId", _data.giveawayMsgId as Any)]) + case .messageActionRequestedPeer(let _data): + return ("messageActionRequestedPeer", [("buttonId", _data.buttonId as Any), ("peers", _data.peers as Any)]) + case .messageActionRequestedPeerSentMe(let _data): + return ("messageActionRequestedPeerSentMe", [("buttonId", _data.buttonId as Any), ("peers", _data.peers as Any)]) + case .messageActionScreenshotTaken: return ("messageActionScreenshotTaken", []) - case .messageActionSecureValuesSent(let types): - return ("messageActionSecureValuesSent", [("types", types as Any)]) - case .messageActionSecureValuesSentMe(let values, let credentials): - return ("messageActionSecureValuesSentMe", [("values", values as Any), ("credentials", credentials as Any)]) - case .messageActionSetChatTheme(let theme): - return ("messageActionSetChatTheme", [("theme", theme as Any)]) - case .messageActionSetChatWallPaper(let flags, let wallpaper): - return ("messageActionSetChatWallPaper", [("flags", flags as Any), ("wallpaper", wallpaper as Any)]) - case .messageActionSetMessagesTTL(let flags, let period, let autoSettingFrom): - return ("messageActionSetMessagesTTL", [("flags", flags as Any), ("period", period as Any), ("autoSettingFrom", autoSettingFrom as Any)]) - case .messageActionStarGift(let flags, let gift, let message, let convertStars, let upgradeMsgId, let upgradeStars, let fromId, let peer, let savedId, let prepaidUpgradeHash, let giftMsgId, let toId, let giftNum): - return ("messageActionStarGift", [("flags", flags as Any), ("gift", gift as Any), ("message", message as Any), ("convertStars", convertStars as Any), ("upgradeMsgId", upgradeMsgId as Any), ("upgradeStars", upgradeStars as Any), ("fromId", fromId as Any), ("peer", peer as Any), ("savedId", savedId as Any), ("prepaidUpgradeHash", prepaidUpgradeHash as Any), ("giftMsgId", giftMsgId as Any), ("toId", toId as Any), ("giftNum", giftNum as Any)]) - case .messageActionStarGiftPurchaseOffer(let flags, let gift, let price, let expiresAt): - return ("messageActionStarGiftPurchaseOffer", [("flags", flags as Any), ("gift", gift as Any), ("price", price as Any), ("expiresAt", expiresAt as Any)]) - case .messageActionStarGiftPurchaseOfferDeclined(let flags, let gift, let price): - return ("messageActionStarGiftPurchaseOfferDeclined", [("flags", flags as Any), ("gift", gift as Any), ("price", price as Any)]) - case .messageActionStarGiftUnique(let flags, let gift, let canExportAt, let transferStars, let fromId, let peer, let savedId, let resaleAmount, let canTransferAt, let canResellAt, let dropOriginalDetailsStars): - return ("messageActionStarGiftUnique", [("flags", flags as Any), ("gift", gift as Any), ("canExportAt", canExportAt as Any), ("transferStars", transferStars as Any), ("fromId", fromId as Any), ("peer", peer as Any), ("savedId", savedId as Any), ("resaleAmount", resaleAmount as Any), ("canTransferAt", canTransferAt as Any), ("canResellAt", canResellAt as Any), ("dropOriginalDetailsStars", dropOriginalDetailsStars as Any)]) - case .messageActionSuggestBirthday(let birthday): - return ("messageActionSuggestBirthday", [("birthday", birthday as Any)]) - case .messageActionSuggestProfilePhoto(let photo): - return ("messageActionSuggestProfilePhoto", [("photo", photo as Any)]) - case .messageActionSuggestedPostApproval(let flags, let rejectComment, let scheduleDate, let price): - return ("messageActionSuggestedPostApproval", [("flags", flags as Any), ("rejectComment", rejectComment as Any), ("scheduleDate", scheduleDate as Any), ("price", price as Any)]) - case .messageActionSuggestedPostRefund(let flags): - return ("messageActionSuggestedPostRefund", [("flags", flags as Any)]) - case .messageActionSuggestedPostSuccess(let price): - return ("messageActionSuggestedPostSuccess", [("price", price as Any)]) - case .messageActionTodoAppendTasks(let list): - return ("messageActionTodoAppendTasks", [("list", list as Any)]) - case .messageActionTodoCompletions(let completed, let incompleted): - return ("messageActionTodoCompletions", [("completed", completed as Any), ("incompleted", incompleted as Any)]) - case .messageActionTopicCreate(let flags, let title, let iconColor, let iconEmojiId): - return ("messageActionTopicCreate", [("flags", flags as Any), ("title", title as Any), ("iconColor", iconColor as Any), ("iconEmojiId", iconEmojiId as Any)]) - case .messageActionTopicEdit(let flags, let title, let iconEmojiId, let closed, let hidden): - return ("messageActionTopicEdit", [("flags", flags as Any), ("title", title as Any), ("iconEmojiId", iconEmojiId as Any), ("closed", closed as Any), ("hidden", hidden as Any)]) - case .messageActionWebViewDataSent(let text): - return ("messageActionWebViewDataSent", [("text", text as Any)]) - case .messageActionWebViewDataSentMe(let text, let data): - return ("messageActionWebViewDataSentMe", [("text", text as Any), ("data", data as Any)]) - } - } - + case .messageActionSecureValuesSent(let _data): + return ("messageActionSecureValuesSent", [("types", _data.types as Any)]) + case .messageActionSecureValuesSentMe(let _data): + return ("messageActionSecureValuesSentMe", [("values", _data.values as Any), ("credentials", _data.credentials as Any)]) + case .messageActionSetChatTheme(let _data): + return ("messageActionSetChatTheme", [("theme", _data.theme as Any)]) + case .messageActionSetChatWallPaper(let _data): + return ("messageActionSetChatWallPaper", [("flags", _data.flags as Any), ("wallpaper", _data.wallpaper as Any)]) + case .messageActionSetMessagesTTL(let _data): + return ("messageActionSetMessagesTTL", [("flags", _data.flags as Any), ("period", _data.period as Any), ("autoSettingFrom", _data.autoSettingFrom as Any)]) + case .messageActionStarGift(let _data): + return ("messageActionStarGift", [("flags", _data.flags as Any), ("gift", _data.gift as Any), ("message", _data.message as Any), ("convertStars", _data.convertStars as Any), ("upgradeMsgId", _data.upgradeMsgId as Any), ("upgradeStars", _data.upgradeStars as Any), ("fromId", _data.fromId as Any), ("peer", _data.peer as Any), ("savedId", _data.savedId as Any), ("prepaidUpgradeHash", _data.prepaidUpgradeHash as Any), ("giftMsgId", _data.giftMsgId as Any), ("toId", _data.toId as Any), ("giftNum", _data.giftNum as Any)]) + case .messageActionStarGiftPurchaseOffer(let _data): + return ("messageActionStarGiftPurchaseOffer", [("flags", _data.flags as Any), ("gift", _data.gift as Any), ("price", _data.price as Any), ("expiresAt", _data.expiresAt as Any)]) + case .messageActionStarGiftPurchaseOfferDeclined(let _data): + return ("messageActionStarGiftPurchaseOfferDeclined", [("flags", _data.flags as Any), ("gift", _data.gift as Any), ("price", _data.price as Any)]) + case .messageActionStarGiftUnique(let _data): + return ("messageActionStarGiftUnique", [("flags", _data.flags as Any), ("gift", _data.gift as Any), ("canExportAt", _data.canExportAt as Any), ("transferStars", _data.transferStars as Any), ("fromId", _data.fromId as Any), ("peer", _data.peer as Any), ("savedId", _data.savedId as Any), ("resaleAmount", _data.resaleAmount as Any), ("canTransferAt", _data.canTransferAt as Any), ("canResellAt", _data.canResellAt as Any), ("dropOriginalDetailsStars", _data.dropOriginalDetailsStars as Any), ("canCraftAt", _data.canCraftAt as Any)]) + case .messageActionSuggestBirthday(let _data): + return ("messageActionSuggestBirthday", [("birthday", _data.birthday as Any)]) + case .messageActionSuggestProfilePhoto(let _data): + return ("messageActionSuggestProfilePhoto", [("photo", _data.photo as Any)]) + case .messageActionSuggestedPostApproval(let _data): + return ("messageActionSuggestedPostApproval", [("flags", _data.flags as Any), ("rejectComment", _data.rejectComment as Any), ("scheduleDate", _data.scheduleDate as Any), ("price", _data.price as Any)]) + case .messageActionSuggestedPostRefund(let _data): + return ("messageActionSuggestedPostRefund", [("flags", _data.flags as Any)]) + case .messageActionSuggestedPostSuccess(let _data): + return ("messageActionSuggestedPostSuccess", [("price", _data.price as Any)]) + case .messageActionTodoAppendTasks(let _data): + return ("messageActionTodoAppendTasks", [("list", _data.list as Any)]) + case .messageActionTodoCompletions(let _data): + return ("messageActionTodoCompletions", [("completed", _data.completed as Any), ("incompleted", _data.incompleted as Any)]) + case .messageActionTopicCreate(let _data): + return ("messageActionTopicCreate", [("flags", _data.flags as Any), ("title", _data.title as Any), ("iconColor", _data.iconColor as Any), ("iconEmojiId", _data.iconEmojiId as Any)]) + case .messageActionTopicEdit(let _data): + return ("messageActionTopicEdit", [("flags", _data.flags as Any), ("title", _data.title as Any), ("iconEmojiId", _data.iconEmojiId as Any), ("closed", _data.closed as Any), ("hidden", _data.hidden as Any)]) + case .messageActionWebViewDataSent(let _data): + return ("messageActionWebViewDataSent", [("text", _data.text as Any)]) + case .messageActionWebViewDataSentMe(let _data): + return ("messageActionWebViewDataSentMe", [("text", _data.text as Any), ("data", _data.data as Any)]) + } + } + public static func parse_messageActionBoostApply(_ reader: BufferReader) -> MessageAction? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionBoostApply(boosts: _1!) + if _c1 { + return Api.MessageAction.messageActionBoostApply(Cons_messageActionBoostApply(boosts: _1!)) + } + else { + return nil + } } public static func parse_messageActionBotAllowed(_ reader: BufferReader) -> MessageAction? { var _1: Int32? _1 = reader.readInt32() var _2: String? - if Int(_1!) & Int(1 << 0) != 0 {_2 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = parseString(reader) + } var _3: Api.BotApp? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.BotApp - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.BotApp + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 2) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessageAction.messageActionBotAllowed(flags: _1!, domain: _2, app: _3) + if _c1 && _c2 && _c3 { + return Api.MessageAction.messageActionBotAllowed(Cons_messageActionBotAllowed(flags: _1!, domain: _2, app: _3)) + } + else { + return nil + } + } + public static func parse_messageActionChangeCreator(_ reader: BufferReader) -> MessageAction? { + var _1: Int64? + _1 = reader.readInt64() + let _c1 = _1 != nil + if _c1 { + return Api.MessageAction.messageActionChangeCreator(Cons_messageActionChangeCreator(newCreatorId: _1!)) + } + else { + return nil + } } public static func parse_messageActionChannelCreate(_ reader: BufferReader) -> MessageAction? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionChannelCreate(title: _1!) + if _c1 { + return Api.MessageAction.messageActionChannelCreate(Cons_messageActionChannelCreate(title: _1!)) + } + else { + return nil + } } public static func parse_messageActionChannelMigrateFrom(_ reader: BufferReader) -> MessageAction? { var _1: String? @@ -1783,9 +3000,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageAction.messageActionChannelMigrateFrom(title: _1!, chatId: _2!) + if _c1 && _c2 { + return Api.MessageAction.messageActionChannelMigrateFrom(Cons_messageActionChannelMigrateFrom(title: _1!, chatId: _2!)) + } + else { + return nil + } } public static func parse_messageActionChatAddUser(_ reader: BufferReader) -> MessageAction? { var _1: [Int64]? @@ -1793,8 +3013,12 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionChatAddUser(users: _1!) + if _c1 { + return Api.MessageAction.messageActionChatAddUser(Cons_messageActionChatAddUser(users: _1!)) + } + else { + return nil + } } public static func parse_messageActionChatCreate(_ reader: BufferReader) -> MessageAction? { var _1: String? @@ -1805,9 +3029,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageAction.messageActionChatCreate(title: _1!, users: _2!) + if _c1 && _c2 { + return Api.MessageAction.messageActionChatCreate(Cons_messageActionChatCreate(title: _1!, users: _2!)) + } + else { + return nil + } } public static func parse_messageActionChatDeletePhoto(_ reader: BufferReader) -> MessageAction? { return Api.MessageAction.messageActionChatDeletePhoto @@ -1816,8 +3043,12 @@ public extension Api { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionChatDeleteUser(userId: _1!) + if _c1 { + return Api.MessageAction.messageActionChatDeleteUser(Cons_messageActionChatDeleteUser(userId: _1!)) + } + else { + return nil + } } public static func parse_messageActionChatEditPhoto(_ reader: BufferReader) -> MessageAction? { var _1: Api.Photo? @@ -1825,22 +3056,34 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Photo } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionChatEditPhoto(photo: _1!) + if _c1 { + return Api.MessageAction.messageActionChatEditPhoto(Cons_messageActionChatEditPhoto(photo: _1!)) + } + else { + return nil + } } public static func parse_messageActionChatEditTitle(_ reader: BufferReader) -> MessageAction? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionChatEditTitle(title: _1!) + if _c1 { + return Api.MessageAction.messageActionChatEditTitle(Cons_messageActionChatEditTitle(title: _1!)) + } + else { + return nil + } } public static func parse_messageActionChatJoinedByLink(_ reader: BufferReader) -> MessageAction? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionChatJoinedByLink(inviterId: _1!) + if _c1 { + return Api.MessageAction.messageActionChatJoinedByLink(Cons_messageActionChatJoinedByLink(inviterId: _1!)) + } + else { + return nil + } } public static func parse_messageActionChatJoinedByRequest(_ reader: BufferReader) -> MessageAction? { return Api.MessageAction.messageActionChatJoinedByRequest @@ -1849,8 +3092,12 @@ public extension Api { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionChatMigrateTo(channelId: _1!) + if _c1 { + return Api.MessageAction.messageActionChatMigrateTo(Cons_messageActionChatMigrateTo(channelId: _1!)) + } + else { + return nil + } } public static func parse_messageActionConferenceCall(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -1858,20 +3105,25 @@ public extension Api { var _2: Int64? _2 = reader.readInt64() var _3: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _3 = reader.readInt32() + } var _4: [Api.Peer]? - if Int(_1!) & Int(1 << 3) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 2) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 3) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.MessageAction.messageActionConferenceCall(flags: _1!, callId: _2!, duration: _3, otherParticipants: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.MessageAction.messageActionConferenceCall(Cons_messageActionConferenceCall(flags: _1!, callId: _2!, duration: _3, otherParticipants: _4)) + } + else { + return nil + } } public static func parse_messageActionContactSignUp(_ reader: BufferReader) -> MessageAction? { return Api.MessageAction.messageActionContactSignUp @@ -1880,8 +3132,12 @@ public extension Api { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionCustomAction(message: _1!) + if _c1 { + return Api.MessageAction.messageActionCustomAction(Cons_messageActionCustomAction(message: _1!)) + } + else { + return nil + } } public static func parse_messageActionEmpty(_ reader: BufferReader) -> MessageAction? { return Api.MessageAction.messageActionEmpty @@ -1893,9 +3149,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageAction.messageActionGameScore(gameId: _1!, score: _2!) + if _c1 && _c2 { + return Api.MessageAction.messageActionGameScore(Cons_messageActionGameScore(gameId: _1!, score: _2!)) + } + else { + return nil + } } public static func parse_messageActionGeoProximityReached(_ reader: BufferReader) -> MessageAction? { var _1: Api.Peer? @@ -1911,34 +3170,48 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessageAction.messageActionGeoProximityReached(fromId: _1!, toId: _2!, distance: _3!) + if _c1 && _c2 && _c3 { + return Api.MessageAction.messageActionGeoProximityReached(Cons_messageActionGeoProximityReached(fromId: _1!, toId: _2!, distance: _3!)) + } + else { + return nil + } } public static func parse_messageActionGiftCode(_ reader: BufferReader) -> MessageAction? { var _1: Int32? _1 = reader.readInt32() var _2: Api.Peer? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _3: Int32? _3 = reader.readInt32() var _4: String? _4 = parseString(reader) var _5: String? - if Int(_1!) & Int(1 << 2) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _5 = parseString(reader) + } var _6: Int64? - if Int(_1!) & Int(1 << 2) != 0 {_6 = reader.readInt64() } + if Int(_1!) & Int(1 << 2) != 0 { + _6 = reader.readInt64() + } var _7: String? - if Int(_1!) & Int(1 << 3) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 3) != 0 { + _7 = parseString(reader) + } var _8: Int64? - if Int(_1!) & Int(1 << 3) != 0 {_8 = reader.readInt64() } + if Int(_1!) & Int(1 << 3) != 0 { + _8 = reader.readInt64() + } var _9: Api.TextWithEntities? - if Int(_1!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.TextWithEntities - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.TextWithEntities + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil let _c3 = _3 != nil @@ -1948,16 +3221,12 @@ public extension Api { let _c7 = (Int(_1!) & Int(1 << 3) == 0) || _7 != nil let _c8 = (Int(_1!) & Int(1 << 3) == 0) || _8 != nil let _c9 = (Int(_1!) & Int(1 << 4) == 0) || _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.MessageAction.messageActionGiftCode(flags: _1!, boostPeer: _2, days: _3!, slug: _4!, currency: _5, amount: _6, cryptoCurrency: _7, cryptoAmount: _8, message: _9) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.MessageAction.messageActionGiftCode(Cons_messageActionGiftCode(flags: _1!, boostPeer: _2, days: _3!, slug: _4!, currency: _5, amount: _6, cryptoCurrency: _7, cryptoAmount: _8, message: _9)) + } + else { + return nil + } } public static func parse_messageActionGiftPremium(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -1969,13 +3238,19 @@ public extension Api { var _4: Int32? _4 = reader.readInt32() var _5: String? - if Int(_1!) & Int(1 << 0) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _5 = parseString(reader) + } var _6: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_6 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _6 = reader.readInt64() + } var _7: Api.TextWithEntities? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.TextWithEntities - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.TextWithEntities + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -1983,14 +3258,12 @@ public extension Api { let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.MessageAction.messageActionGiftPremium(flags: _1!, currency: _2!, amount: _3!, days: _4!, cryptoCurrency: _5, cryptoAmount: _6, message: _7) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.MessageAction.messageActionGiftPremium(Cons_messageActionGiftPremium(flags: _1!, currency: _2!, amount: _3!, days: _4!, cryptoCurrency: _5, cryptoAmount: _6, message: _7)) + } + else { + return nil + } } public static func parse_messageActionGiftStars(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2002,11 +3275,17 @@ public extension Api { var _4: Int64? _4 = reader.readInt64() var _5: String? - if Int(_1!) & Int(1 << 0) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _5 = parseString(reader) + } var _6: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_6 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _6 = reader.readInt64() + } var _7: String? - if Int(_1!) & Int(1 << 1) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _7 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -2014,14 +3293,12 @@ public extension Api { let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.MessageAction.messageActionGiftStars(flags: _1!, currency: _2!, amount: _3!, stars: _4!, cryptoCurrency: _5, cryptoAmount: _6, transactionId: _7) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.MessageAction.messageActionGiftStars(Cons_messageActionGiftStars(flags: _1!, currency: _2!, amount: _3!, stars: _4!, cryptoCurrency: _5, cryptoAmount: _6, transactionId: _7)) + } + else { + return nil + } } public static func parse_messageActionGiftTon(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2035,31 +3312,37 @@ public extension Api { var _5: Int64? _5 = reader.readInt64() var _6: String? - if Int(_1!) & Int(1 << 0) != 0 {_6 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _6 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.MessageAction.messageActionGiftTon(flags: _1!, currency: _2!, amount: _3!, cryptoCurrency: _4!, cryptoAmount: _5!, transactionId: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.MessageAction.messageActionGiftTon(Cons_messageActionGiftTon(flags: _1!, currency: _2!, amount: _3!, cryptoCurrency: _4!, cryptoAmount: _5!, transactionId: _6)) + } + else { + return nil + } } public static func parse_messageActionGiveawayLaunch(_ reader: BufferReader) -> MessageAction? { var _1: Int32? _1 = reader.readInt32() var _2: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt64() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageAction.messageActionGiveawayLaunch(flags: _1!, stars: _2) + if _c1 && _c2 { + return Api.MessageAction.messageActionGiveawayLaunch(Cons_messageActionGiveawayLaunch(flags: _1!, stars: _2)) + } + else { + return nil + } } public static func parse_messageActionGiveawayResults(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2071,10 +3354,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessageAction.messageActionGiveawayResults(flags: _1!, winnersCount: _2!, unclaimedCount: _3!) + if _c1 && _c2 && _c3 { + return Api.MessageAction.messageActionGiveawayResults(Cons_messageActionGiveawayResults(flags: _1!, winnersCount: _2!, unclaimedCount: _3!)) + } + else { + return nil + } } public static func parse_messageActionGroupCall(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2084,14 +3369,18 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.InputGroupCall } var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessageAction.messageActionGroupCall(flags: _1!, call: _2!, duration: _3) + if _c1 && _c2 && _c3 { + return Api.MessageAction.messageActionGroupCall(Cons_messageActionGroupCall(flags: _1!, call: _2!, duration: _3)) + } + else { + return nil + } } public static func parse_messageActionGroupCallScheduled(_ reader: BufferReader) -> MessageAction? { var _1: Api.InputGroupCall? @@ -2102,9 +3391,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageAction.messageActionGroupCallScheduled(call: _1!, scheduleDate: _2!) + if _c1 && _c2 { + return Api.MessageAction.messageActionGroupCallScheduled(Cons_messageActionGroupCallScheduled(call: _1!, scheduleDate: _2!)) + } + else { + return nil + } } public static func parse_messageActionHistoryClear(_ reader: BufferReader) -> MessageAction? { return Api.MessageAction.messageActionHistoryClear @@ -2120,9 +3412,23 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageAction.messageActionInviteToGroupCall(call: _1!, users: _2!) + if _c1 && _c2 { + return Api.MessageAction.messageActionInviteToGroupCall(Cons_messageActionInviteToGroupCall(call: _1!, users: _2!)) + } + else { + return nil + } + } + public static func parse_messageActionNewCreatorPending(_ reader: BufferReader) -> MessageAction? { + var _1: Int64? + _1 = reader.readInt64() + let _c1 = _1 != nil + if _c1 { + return Api.MessageAction.messageActionNewCreatorPending(Cons_messageActionNewCreatorPending(newCreatorId: _1!)) + } + else { + return nil + } } public static func parse_messageActionPaidMessagesPrice(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2131,9 +3437,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageAction.messageActionPaidMessagesPrice(flags: _1!, stars: _2!) + if _c1 && _c2 { + return Api.MessageAction.messageActionPaidMessagesPrice(Cons_messageActionPaidMessagesPrice(flags: _1!, stars: _2!)) + } + else { + return nil + } } public static func parse_messageActionPaidMessagesRefunded(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2142,9 +3451,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageAction.messageActionPaidMessagesRefunded(count: _1!, stars: _2!) + if _c1 && _c2 { + return Api.MessageAction.messageActionPaidMessagesRefunded(Cons_messageActionPaidMessagesRefunded(count: _1!, stars: _2!)) + } + else { + return nil + } } public static func parse_messageActionPaymentRefunded(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2158,7 +3470,9 @@ public extension Api { var _4: Int64? _4 = reader.readInt64() var _5: Buffer? - if Int(_1!) & Int(1 << 0) != 0 {_5 = parseBytes(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _5 = parseBytes(reader) + } var _6: Api.PaymentCharge? if let signature = reader.readInt32() { _6 = Api.parse(reader, signature: signature) as? Api.PaymentCharge @@ -2169,13 +3483,12 @@ public extension Api { let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.MessageAction.messageActionPaymentRefunded(flags: _1!, peer: _2!, currency: _3!, totalAmount: _4!, payload: _5, charge: _6!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.MessageAction.messageActionPaymentRefunded(Cons_messageActionPaymentRefunded(flags: _1!, peer: _2!, currency: _3!, totalAmount: _4!, payload: _5, charge: _6!)) + } + else { + return nil + } } public static func parse_messageActionPaymentSent(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2185,20 +3498,24 @@ public extension Api { var _3: Int64? _3 = reader.readInt64() var _4: String? - if Int(_1!) & Int(1 << 0) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) + } var _5: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _5 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 4) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.MessageAction.messageActionPaymentSent(flags: _1!, currency: _2!, totalAmount: _3!, invoiceSlug: _4, subscriptionUntilDate: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.MessageAction.messageActionPaymentSent(Cons_messageActionPaymentSent(flags: _1!, currency: _2!, totalAmount: _3!, invoiceSlug: _4, subscriptionUntilDate: _5)) + } + else { + return nil + } } public static func parse_messageActionPaymentSentMe(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2210,17 +3527,23 @@ public extension Api { var _4: Buffer? _4 = parseBytes(reader) var _5: Api.PaymentRequestedInfo? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.PaymentRequestedInfo - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.PaymentRequestedInfo + } + } var _6: String? - if Int(_1!) & Int(1 << 1) != 0 {_6 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _6 = parseString(reader) + } var _7: Api.PaymentCharge? if let signature = reader.readInt32() { _7 = Api.parse(reader, signature: signature) as? Api.PaymentCharge } var _8: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_8 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _8 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -2229,15 +3552,12 @@ public extension Api { let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil let _c7 = _7 != nil let _c8 = (Int(_1!) & Int(1 << 4) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.MessageAction.messageActionPaymentSentMe(flags: _1!, currency: _2!, totalAmount: _3!, payload: _4!, info: _5, shippingOptionId: _6, charge: _7!, subscriptionUntilDate: _8) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.MessageAction.messageActionPaymentSentMe(Cons_messageActionPaymentSentMe(flags: _1!, currency: _2!, totalAmount: _3!, payload: _4!, info: _5, shippingOptionId: _6, charge: _7!, subscriptionUntilDate: _8)) + } + else { + return nil + } } public static func parse_messageActionPhoneCall(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2245,20 +3565,25 @@ public extension Api { var _2: Int64? _2 = reader.readInt64() var _3: Api.PhoneCallDiscardReason? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.PhoneCallDiscardReason - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.PhoneCallDiscardReason + } + } var _4: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.MessageAction.messageActionPhoneCall(flags: _1!, callId: _2!, reason: _3, duration: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.MessageAction.messageActionPhoneCall(Cons_messageActionPhoneCall(flags: _1!, callId: _2!, reason: _3, duration: _4)) + } + else { + return nil + } } public static func parse_messageActionPinMessage(_ reader: BufferReader) -> MessageAction? { return Api.MessageAction.messageActionPinMessage @@ -2281,12 +3606,12 @@ public extension Api { let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.MessageAction.messageActionPrizeStars(flags: _1!, stars: _2!, transactionId: _3!, boostPeer: _4!, giveawayMsgId: _5!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.MessageAction.messageActionPrizeStars(Cons_messageActionPrizeStars(flags: _1!, stars: _2!, transactionId: _3!, boostPeer: _4!, giveawayMsgId: _5!)) + } + else { + return nil + } } public static func parse_messageActionRequestedPeer(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2297,9 +3622,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageAction.messageActionRequestedPeer(buttonId: _1!, peers: _2!) + if _c1 && _c2 { + return Api.MessageAction.messageActionRequestedPeer(Cons_messageActionRequestedPeer(buttonId: _1!, peers: _2!)) + } + else { + return nil + } } public static func parse_messageActionRequestedPeerSentMe(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2310,9 +3638,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageAction.messageActionRequestedPeerSentMe(buttonId: _1!, peers: _2!) + if _c1 && _c2 { + return Api.MessageAction.messageActionRequestedPeerSentMe(Cons_messageActionRequestedPeerSentMe(buttonId: _1!, peers: _2!)) + } + else { + return nil + } } public static func parse_messageActionScreenshotTaken(_ reader: BufferReader) -> MessageAction? { return Api.MessageAction.messageActionScreenshotTaken @@ -2323,8 +3654,12 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureValueType.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionSecureValuesSent(types: _1!) + if _c1 { + return Api.MessageAction.messageActionSecureValuesSent(Cons_messageActionSecureValuesSent(types: _1!)) + } + else { + return nil + } } public static func parse_messageActionSecureValuesSentMe(_ reader: BufferReader) -> MessageAction? { var _1: [Api.SecureValue]? @@ -2337,9 +3672,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageAction.messageActionSecureValuesSentMe(values: _1!, credentials: _2!) + if _c1 && _c2 { + return Api.MessageAction.messageActionSecureValuesSentMe(Cons_messageActionSecureValuesSentMe(values: _1!, credentials: _2!)) + } + else { + return nil + } } public static func parse_messageActionSetChatTheme(_ reader: BufferReader) -> MessageAction? { var _1: Api.ChatTheme? @@ -2347,8 +3685,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.ChatTheme } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionSetChatTheme(theme: _1!) + if _c1 { + return Api.MessageAction.messageActionSetChatTheme(Cons_messageActionSetChatTheme(theme: _1!)) + } + else { + return nil + } } public static func parse_messageActionSetChatWallPaper(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2359,9 +3701,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageAction.messageActionSetChatWallPaper(flags: _1!, wallpaper: _2!) + if _c1 && _c2 { + return Api.MessageAction.messageActionSetChatWallPaper(Cons_messageActionSetChatWallPaper(flags: _1!, wallpaper: _2!)) + } + else { + return nil + } } public static func parse_messageActionSetMessagesTTL(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2369,14 +3714,18 @@ public extension Api { var _2: Int32? _2 = reader.readInt32() var _3: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt64() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessageAction.messageActionSetMessagesTTL(flags: _1!, period: _2!, autoSettingFrom: _3) + if _c1 && _c2 && _c3 { + return Api.MessageAction.messageActionSetMessagesTTL(Cons_messageActionSetMessagesTTL(flags: _1!, period: _2!, autoSettingFrom: _3)) + } + else { + return nil + } } public static func parse_messageActionStarGift(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2386,35 +3735,57 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.StarGift } var _3: Api.TextWithEntities? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.TextWithEntities - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.TextWithEntities + } + } var _4: Int64? - if Int(_1!) & Int(1 << 4) != 0 {_4 = reader.readInt64() } + if Int(_1!) & Int(1 << 4) != 0 { + _4 = reader.readInt64() + } var _5: Int32? - if Int(_1!) & Int(1 << 5) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 5) != 0 { + _5 = reader.readInt32() + } var _6: Int64? - if Int(_1!) & Int(1 << 8) != 0 {_6 = reader.readInt64() } + if Int(_1!) & Int(1 << 8) != 0 { + _6 = reader.readInt64() + } var _7: Api.Peer? - if Int(_1!) & Int(1 << 11) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 11) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _8: Api.Peer? - if Int(_1!) & Int(1 << 12) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 12) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _9: Int64? - if Int(_1!) & Int(1 << 12) != 0 {_9 = reader.readInt64() } + if Int(_1!) & Int(1 << 12) != 0 { + _9 = reader.readInt64() + } var _10: String? - if Int(_1!) & Int(1 << 14) != 0 {_10 = parseString(reader) } + if Int(_1!) & Int(1 << 14) != 0 { + _10 = parseString(reader) + } var _11: Int32? - if Int(_1!) & Int(1 << 15) != 0 {_11 = reader.readInt32() } + if Int(_1!) & Int(1 << 15) != 0 { + _11 = reader.readInt32() + } var _12: Api.Peer? - if Int(_1!) & Int(1 << 18) != 0 {if let signature = reader.readInt32() { - _12 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 18) != 0 { + if let signature = reader.readInt32() { + _12 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _13: Int32? - if Int(_1!) & Int(1 << 19) != 0 {_13 = reader.readInt32() } + if Int(_1!) & Int(1 << 19) != 0 { + _13 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil @@ -2428,20 +3799,12 @@ public extension Api { let _c11 = (Int(_1!) & Int(1 << 15) == 0) || _11 != nil let _c12 = (Int(_1!) & Int(1 << 18) == 0) || _12 != nil let _c13 = (Int(_1!) & Int(1 << 19) == 0) || _13 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - return Api.MessageAction.messageActionStarGift(flags: _1!, gift: _2!, message: _3, convertStars: _4, upgradeMsgId: _5, upgradeStars: _6, fromId: _7, peer: _8, savedId: _9, prepaidUpgradeHash: _10, giftMsgId: _11, toId: _12, giftNum: _13) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 { + return Api.MessageAction.messageActionStarGift(Cons_messageActionStarGift(flags: _1!, gift: _2!, message: _3, convertStars: _4, upgradeMsgId: _5, upgradeStars: _6, fromId: _7, peer: _8, savedId: _9, prepaidUpgradeHash: _10, giftMsgId: _11, toId: _12, giftNum: _13)) + } + else { + return nil + } } public static func parse_messageActionStarGiftPurchaseOffer(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2460,11 +3823,12 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.MessageAction.messageActionStarGiftPurchaseOffer(flags: _1!, gift: _2!, price: _3!, expiresAt: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.MessageAction.messageActionStarGiftPurchaseOffer(Cons_messageActionStarGiftPurchaseOffer(flags: _1!, gift: _2!, price: _3!, expiresAt: _4!)) + } + else { + return nil + } } public static func parse_messageActionStarGiftPurchaseOfferDeclined(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2480,10 +3844,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessageAction.messageActionStarGiftPurchaseOfferDeclined(flags: _1!, gift: _2!, price: _3!) + if _c1 && _c2 && _c3 { + return Api.MessageAction.messageActionStarGiftPurchaseOfferDeclined(Cons_messageActionStarGiftPurchaseOfferDeclined(flags: _1!, gift: _2!, price: _3!)) + } + else { + return nil + } } public static func parse_messageActionStarGiftUnique(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2493,29 +3859,51 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.StarGift } var _3: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 3) != 0 { + _3 = reader.readInt32() + } var _4: Int64? - if Int(_1!) & Int(1 << 4) != 0 {_4 = reader.readInt64() } + if Int(_1!) & Int(1 << 4) != 0 { + _4 = reader.readInt64() + } var _5: Api.Peer? - if Int(_1!) & Int(1 << 6) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 6) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _6: Api.Peer? - if Int(_1!) & Int(1 << 7) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 7) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _7: Int64? - if Int(_1!) & Int(1 << 7) != 0 {_7 = reader.readInt64() } + if Int(_1!) & Int(1 << 7) != 0 { + _7 = reader.readInt64() + } var _8: Api.StarsAmount? - if Int(_1!) & Int(1 << 8) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.StarsAmount - } } + if Int(_1!) & Int(1 << 8) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.StarsAmount + } + } var _9: Int32? - if Int(_1!) & Int(1 << 9) != 0 {_9 = reader.readInt32() } + if Int(_1!) & Int(1 << 9) != 0 { + _9 = reader.readInt32() + } var _10: Int32? - if Int(_1!) & Int(1 << 10) != 0 {_10 = reader.readInt32() } + if Int(_1!) & Int(1 << 10) != 0 { + _10 = reader.readInt32() + } var _11: Int64? - if Int(_1!) & Int(1 << 12) != 0 {_11 = reader.readInt64() } + if Int(_1!) & Int(1 << 12) != 0 { + _11 = reader.readInt64() + } + var _12: Int32? + if Int(_1!) & Int(1 << 15) != 0 { + _12 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 3) == 0) || _3 != nil @@ -2527,18 +3915,13 @@ public extension Api { let _c9 = (Int(_1!) & Int(1 << 9) == 0) || _9 != nil let _c10 = (Int(_1!) & Int(1 << 10) == 0) || _10 != nil let _c11 = (Int(_1!) & Int(1 << 12) == 0) || _11 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - return Api.MessageAction.messageActionStarGiftUnique(flags: _1!, gift: _2!, canExportAt: _3, transferStars: _4, fromId: _5, peer: _6, savedId: _7, resaleAmount: _8, canTransferAt: _9, canResellAt: _10, dropOriginalDetailsStars: _11) + let _c12 = (Int(_1!) & Int(1 << 15) == 0) || _12 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 { + return Api.MessageAction.messageActionStarGiftUnique(Cons_messageActionStarGiftUnique(flags: _1!, gift: _2!, canExportAt: _3, transferStars: _4, fromId: _5, peer: _6, savedId: _7, resaleAmount: _8, canTransferAt: _9, canResellAt: _10, dropOriginalDetailsStars: _11, canCraftAt: _12)) + } + else { + return nil + } } public static func parse_messageActionSuggestBirthday(_ reader: BufferReader) -> MessageAction? { var _1: Api.Birthday? @@ -2546,8 +3929,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Birthday } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionSuggestBirthday(birthday: _1!) + if _c1 { + return Api.MessageAction.messageActionSuggestBirthday(Cons_messageActionSuggestBirthday(birthday: _1!)) + } + else { + return nil + } } public static func parse_messageActionSuggestProfilePhoto(_ reader: BufferReader) -> MessageAction? { var _1: Api.Photo? @@ -2555,36 +3942,51 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Photo } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionSuggestProfilePhoto(photo: _1!) + if _c1 { + return Api.MessageAction.messageActionSuggestProfilePhoto(Cons_messageActionSuggestProfilePhoto(photo: _1!)) + } + else { + return nil + } } public static func parse_messageActionSuggestedPostApproval(_ reader: BufferReader) -> MessageAction? { var _1: Int32? _1 = reader.readInt32() var _2: String? - if Int(_1!) & Int(1 << 2) != 0 {_2 = parseString(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _2 = parseString(reader) + } var _3: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 3) != 0 { + _3 = reader.readInt32() + } var _4: Api.StarsAmount? - if Int(_1!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.StarsAmount - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.StarsAmount + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 2) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 3) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 4) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.MessageAction.messageActionSuggestedPostApproval(flags: _1!, rejectComment: _2, scheduleDate: _3, price: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.MessageAction.messageActionSuggestedPostApproval(Cons_messageActionSuggestedPostApproval(flags: _1!, rejectComment: _2, scheduleDate: _3, price: _4)) + } + else { + return nil + } } public static func parse_messageActionSuggestedPostRefund(_ reader: BufferReader) -> MessageAction? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionSuggestedPostRefund(flags: _1!) + if _c1 { + return Api.MessageAction.messageActionSuggestedPostRefund(Cons_messageActionSuggestedPostRefund(flags: _1!)) + } + else { + return nil + } } public static func parse_messageActionSuggestedPostSuccess(_ reader: BufferReader) -> MessageAction? { var _1: Api.StarsAmount? @@ -2592,8 +3994,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.StarsAmount } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionSuggestedPostSuccess(price: _1!) + if _c1 { + return Api.MessageAction.messageActionSuggestedPostSuccess(Cons_messageActionSuggestedPostSuccess(price: _1!)) + } + else { + return nil + } } public static func parse_messageActionTodoAppendTasks(_ reader: BufferReader) -> MessageAction? { var _1: [Api.TodoItem]? @@ -2601,8 +4007,12 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.TodoItem.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionTodoAppendTasks(list: _1!) + if _c1 { + return Api.MessageAction.messageActionTodoAppendTasks(Cons_messageActionTodoAppendTasks(list: _1!)) + } + else { + return nil + } } public static func parse_messageActionTodoCompletions(_ reader: BufferReader) -> MessageAction? { var _1: [Int32]? @@ -2615,9 +4025,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageAction.messageActionTodoCompletions(completed: _1!, incompleted: _2!) + if _c1 && _c2 { + return Api.MessageAction.messageActionTodoCompletions(Cons_messageActionTodoCompletions(completed: _1!, incompleted: _2!)) + } + else { + return nil + } } public static func parse_messageActionTopicCreate(_ reader: BufferReader) -> MessageAction? { var _1: Int32? @@ -2627,50 +4040,65 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_4 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = reader.readInt64() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.MessageAction.messageActionTopicCreate(flags: _1!, title: _2!, iconColor: _3!, iconEmojiId: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.MessageAction.messageActionTopicCreate(Cons_messageActionTopicCreate(flags: _1!, title: _2!, iconColor: _3!, iconEmojiId: _4)) + } + else { + return nil + } } public static func parse_messageActionTopicEdit(_ reader: BufferReader) -> MessageAction? { var _1: Int32? _1 = reader.readInt32() var _2: String? - if Int(_1!) & Int(1 << 0) != 0 {_2 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = parseString(reader) + } var _3: Int64? - if Int(_1!) & Int(1 << 1) != 0 {_3 = reader.readInt64() } + if Int(_1!) & Int(1 << 1) != 0 { + _3 = reader.readInt64() + } var _4: Api.Bool? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Bool + } + } var _5: Api.Bool? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.Bool + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 3) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.MessageAction.messageActionTopicEdit(flags: _1!, title: _2, iconEmojiId: _3, closed: _4, hidden: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.MessageAction.messageActionTopicEdit(Cons_messageActionTopicEdit(flags: _1!, title: _2, iconEmojiId: _3, closed: _4, hidden: _5)) + } + else { + return nil + } } public static func parse_messageActionWebViewDataSent(_ reader: BufferReader) -> MessageAction? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageAction.messageActionWebViewDataSent(text: _1!) + if _c1 { + return Api.MessageAction.messageActionWebViewDataSent(Cons_messageActionWebViewDataSent(text: _1!)) + } + else { + return nil + } } public static func parse_messageActionWebViewDataSentMe(_ reader: BufferReader) -> MessageAction? { var _1: String? @@ -2679,10 +4107,12 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageAction.messageActionWebViewDataSentMe(text: _1!, data: _2!) + if _c1 && _c2 { + return Api.MessageAction.messageActionWebViewDataSentMe(Cons_messageActionWebViewDataSentMe(text: _1!, data: _2!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api16.swift b/submodules/TelegramApi/Sources/Api16.swift index 1cec7d62..c06f1756 100644 --- a/submodules/TelegramApi/Sources/Api16.swift +++ b/submodules/TelegramApi/Sources/Api16.swift @@ -1,232 +1,412 @@ public extension Api { indirect enum MessageEntity: TypeConstructorDescription { - case inputMessageEntityMentionName(offset: Int32, length: Int32, userId: Api.InputUser) - case messageEntityBankCard(offset: Int32, length: Int32) - case messageEntityBlockquote(flags: Int32, offset: Int32, length: Int32) - case messageEntityBold(offset: Int32, length: Int32) - case messageEntityBotCommand(offset: Int32, length: Int32) - case messageEntityCashtag(offset: Int32, length: Int32) - case messageEntityCode(offset: Int32, length: Int32) - case messageEntityCustomEmoji(offset: Int32, length: Int32, documentId: Int64) - case messageEntityEmail(offset: Int32, length: Int32) - case messageEntityHashtag(offset: Int32, length: Int32) - case messageEntityItalic(offset: Int32, length: Int32) - case messageEntityMention(offset: Int32, length: Int32) - case messageEntityMentionName(offset: Int32, length: Int32, userId: Int64) - case messageEntityPhone(offset: Int32, length: Int32) - case messageEntityPre(offset: Int32, length: Int32, language: String) - case messageEntitySpoiler(offset: Int32, length: Int32) - case messageEntityStrike(offset: Int32, length: Int32) - case messageEntityTextUrl(offset: Int32, length: Int32, url: String) - case messageEntityUnderline(offset: Int32, length: Int32) - case messageEntityUnknown(offset: Int32, length: Int32) - case messageEntityUrl(offset: Int32, length: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputMessageEntityMentionName(let offset, let length, let userId): - if boxed { - buffer.appendInt32(546203849) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - userId.serialize(buffer, true) - break - case .messageEntityBankCard(let offset, let length): - if boxed { - buffer.appendInt32(1981704948) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .messageEntityBlockquote(let flags, let offset, let length): - if boxed { - buffer.appendInt32(-238245204) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .messageEntityBold(let offset, let length): - if boxed { - buffer.appendInt32(-1117713463) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .messageEntityBotCommand(let offset, let length): - if boxed { - buffer.appendInt32(1827637959) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .messageEntityCashtag(let offset, let length): - if boxed { - buffer.appendInt32(1280209983) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .messageEntityCode(let offset, let length): - if boxed { - buffer.appendInt32(681706865) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .messageEntityCustomEmoji(let offset, let length, let documentId): - if boxed { - buffer.appendInt32(-925956616) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - serializeInt64(documentId, buffer: buffer, boxed: false) - break - case .messageEntityEmail(let offset, let length): - if boxed { - buffer.appendInt32(1692693954) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .messageEntityHashtag(let offset, let length): - if boxed { - buffer.appendInt32(1868782349) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .messageEntityItalic(let offset, let length): - if boxed { - buffer.appendInt32(-2106619040) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .messageEntityMention(let offset, let length): - if boxed { - buffer.appendInt32(-100378723) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .messageEntityMentionName(let offset, let length, let userId): - if boxed { - buffer.appendInt32(-595914432) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - break - case .messageEntityPhone(let offset, let length): - if boxed { - buffer.appendInt32(-1687559349) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .messageEntityPre(let offset, let length, let language): - if boxed { - buffer.appendInt32(1938967520) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - serializeString(language, buffer: buffer, boxed: false) - break - case .messageEntitySpoiler(let offset, let length): - if boxed { - buffer.appendInt32(852137487) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .messageEntityStrike(let offset, let length): - if boxed { - buffer.appendInt32(-1090087980) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .messageEntityTextUrl(let offset, let length, let url): - if boxed { - buffer.appendInt32(1990644519) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - break - case .messageEntityUnderline(let offset, let length): - if boxed { - buffer.appendInt32(-1672577397) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .messageEntityUnknown(let offset, let length): - if boxed { - buffer.appendInt32(-1148011883) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .messageEntityUrl(let offset, let length): - if boxed { - buffer.appendInt32(1859134776) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputMessageEntityMentionName(let offset, let length, let userId): - return ("inputMessageEntityMentionName", [("offset", offset as Any), ("length", length as Any), ("userId", userId as Any)]) - case .messageEntityBankCard(let offset, let length): - return ("messageEntityBankCard", [("offset", offset as Any), ("length", length as Any)]) - case .messageEntityBlockquote(let flags, let offset, let length): - return ("messageEntityBlockquote", [("flags", flags as Any), ("offset", offset as Any), ("length", length as Any)]) - case .messageEntityBold(let offset, let length): - return ("messageEntityBold", [("offset", offset as Any), ("length", length as Any)]) - case .messageEntityBotCommand(let offset, let length): - return ("messageEntityBotCommand", [("offset", offset as Any), ("length", length as Any)]) - case .messageEntityCashtag(let offset, let length): - return ("messageEntityCashtag", [("offset", offset as Any), ("length", length as Any)]) - case .messageEntityCode(let offset, let length): - return ("messageEntityCode", [("offset", offset as Any), ("length", length as Any)]) - case .messageEntityCustomEmoji(let offset, let length, let documentId): - return ("messageEntityCustomEmoji", [("offset", offset as Any), ("length", length as Any), ("documentId", documentId as Any)]) - case .messageEntityEmail(let offset, let length): - return ("messageEntityEmail", [("offset", offset as Any), ("length", length as Any)]) - case .messageEntityHashtag(let offset, let length): - return ("messageEntityHashtag", [("offset", offset as Any), ("length", length as Any)]) - case .messageEntityItalic(let offset, let length): - return ("messageEntityItalic", [("offset", offset as Any), ("length", length as Any)]) - case .messageEntityMention(let offset, let length): - return ("messageEntityMention", [("offset", offset as Any), ("length", length as Any)]) - case .messageEntityMentionName(let offset, let length, let userId): - return ("messageEntityMentionName", [("offset", offset as Any), ("length", length as Any), ("userId", userId as Any)]) - case .messageEntityPhone(let offset, let length): - return ("messageEntityPhone", [("offset", offset as Any), ("length", length as Any)]) - case .messageEntityPre(let offset, let length, let language): - return ("messageEntityPre", [("offset", offset as Any), ("length", length as Any), ("language", language as Any)]) - case .messageEntitySpoiler(let offset, let length): - return ("messageEntitySpoiler", [("offset", offset as Any), ("length", length as Any)]) - case .messageEntityStrike(let offset, let length): - return ("messageEntityStrike", [("offset", offset as Any), ("length", length as Any)]) - case .messageEntityTextUrl(let offset, let length, let url): - return ("messageEntityTextUrl", [("offset", offset as Any), ("length", length as Any), ("url", url as Any)]) - case .messageEntityUnderline(let offset, let length): - return ("messageEntityUnderline", [("offset", offset as Any), ("length", length as Any)]) - case .messageEntityUnknown(let offset, let length): - return ("messageEntityUnknown", [("offset", offset as Any), ("length", length as Any)]) - case .messageEntityUrl(let offset, let length): - return ("messageEntityUrl", [("offset", offset as Any), ("length", length as Any)]) - } - } - + public class Cons_inputMessageEntityMentionName { + public var offset: Int32 + public var length: Int32 + public var userId: Api.InputUser + public init(offset: Int32, length: Int32, userId: Api.InputUser) { + self.offset = offset + self.length = length + self.userId = userId + } + } + public class Cons_messageEntityBankCard { + public var offset: Int32 + public var length: Int32 + public init(offset: Int32, length: Int32) { + self.offset = offset + self.length = length + } + } + public class Cons_messageEntityBlockquote { + public var flags: Int32 + public var offset: Int32 + public var length: Int32 + public init(flags: Int32, offset: Int32, length: Int32) { + self.flags = flags + self.offset = offset + self.length = length + } + } + public class Cons_messageEntityBold { + public var offset: Int32 + public var length: Int32 + public init(offset: Int32, length: Int32) { + self.offset = offset + self.length = length + } + } + public class Cons_messageEntityBotCommand { + public var offset: Int32 + public var length: Int32 + public init(offset: Int32, length: Int32) { + self.offset = offset + self.length = length + } + } + public class Cons_messageEntityCashtag { + public var offset: Int32 + public var length: Int32 + public init(offset: Int32, length: Int32) { + self.offset = offset + self.length = length + } + } + public class Cons_messageEntityCode { + public var offset: Int32 + public var length: Int32 + public init(offset: Int32, length: Int32) { + self.offset = offset + self.length = length + } + } + public class Cons_messageEntityCustomEmoji { + public var offset: Int32 + public var length: Int32 + public var documentId: Int64 + public init(offset: Int32, length: Int32, documentId: Int64) { + self.offset = offset + self.length = length + self.documentId = documentId + } + } + public class Cons_messageEntityEmail { + public var offset: Int32 + public var length: Int32 + public init(offset: Int32, length: Int32) { + self.offset = offset + self.length = length + } + } + public class Cons_messageEntityHashtag { + public var offset: Int32 + public var length: Int32 + public init(offset: Int32, length: Int32) { + self.offset = offset + self.length = length + } + } + public class Cons_messageEntityItalic { + public var offset: Int32 + public var length: Int32 + public init(offset: Int32, length: Int32) { + self.offset = offset + self.length = length + } + } + public class Cons_messageEntityMention { + public var offset: Int32 + public var length: Int32 + public init(offset: Int32, length: Int32) { + self.offset = offset + self.length = length + } + } + public class Cons_messageEntityMentionName { + public var offset: Int32 + public var length: Int32 + public var userId: Int64 + public init(offset: Int32, length: Int32, userId: Int64) { + self.offset = offset + self.length = length + self.userId = userId + } + } + public class Cons_messageEntityPhone { + public var offset: Int32 + public var length: Int32 + public init(offset: Int32, length: Int32) { + self.offset = offset + self.length = length + } + } + public class Cons_messageEntityPre { + public var offset: Int32 + public var length: Int32 + public var language: String + public init(offset: Int32, length: Int32, language: String) { + self.offset = offset + self.length = length + self.language = language + } + } + public class Cons_messageEntitySpoiler { + public var offset: Int32 + public var length: Int32 + public init(offset: Int32, length: Int32) { + self.offset = offset + self.length = length + } + } + public class Cons_messageEntityStrike { + public var offset: Int32 + public var length: Int32 + public init(offset: Int32, length: Int32) { + self.offset = offset + self.length = length + } + } + public class Cons_messageEntityTextUrl { + public var offset: Int32 + public var length: Int32 + public var url: String + public init(offset: Int32, length: Int32, url: String) { + self.offset = offset + self.length = length + self.url = url + } + } + public class Cons_messageEntityUnderline { + public var offset: Int32 + public var length: Int32 + public init(offset: Int32, length: Int32) { + self.offset = offset + self.length = length + } + } + public class Cons_messageEntityUnknown { + public var offset: Int32 + public var length: Int32 + public init(offset: Int32, length: Int32) { + self.offset = offset + self.length = length + } + } + public class Cons_messageEntityUrl { + public var offset: Int32 + public var length: Int32 + public init(offset: Int32, length: Int32) { + self.offset = offset + self.length = length + } + } + case inputMessageEntityMentionName(Cons_inputMessageEntityMentionName) + case messageEntityBankCard(Cons_messageEntityBankCard) + case messageEntityBlockquote(Cons_messageEntityBlockquote) + case messageEntityBold(Cons_messageEntityBold) + case messageEntityBotCommand(Cons_messageEntityBotCommand) + case messageEntityCashtag(Cons_messageEntityCashtag) + case messageEntityCode(Cons_messageEntityCode) + case messageEntityCustomEmoji(Cons_messageEntityCustomEmoji) + case messageEntityEmail(Cons_messageEntityEmail) + case messageEntityHashtag(Cons_messageEntityHashtag) + case messageEntityItalic(Cons_messageEntityItalic) + case messageEntityMention(Cons_messageEntityMention) + case messageEntityMentionName(Cons_messageEntityMentionName) + case messageEntityPhone(Cons_messageEntityPhone) + case messageEntityPre(Cons_messageEntityPre) + case messageEntitySpoiler(Cons_messageEntitySpoiler) + case messageEntityStrike(Cons_messageEntityStrike) + case messageEntityTextUrl(Cons_messageEntityTextUrl) + case messageEntityUnderline(Cons_messageEntityUnderline) + case messageEntityUnknown(Cons_messageEntityUnknown) + case messageEntityUrl(Cons_messageEntityUrl) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputMessageEntityMentionName(let _data): + if boxed { + buffer.appendInt32(546203849) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + _data.userId.serialize(buffer, true) + break + case .messageEntityBankCard(let _data): + if boxed { + buffer.appendInt32(1981704948) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .messageEntityBlockquote(let _data): + if boxed { + buffer.appendInt32(-238245204) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .messageEntityBold(let _data): + if boxed { + buffer.appendInt32(-1117713463) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .messageEntityBotCommand(let _data): + if boxed { + buffer.appendInt32(1827637959) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .messageEntityCashtag(let _data): + if boxed { + buffer.appendInt32(1280209983) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .messageEntityCode(let _data): + if boxed { + buffer.appendInt32(681706865) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .messageEntityCustomEmoji(let _data): + if boxed { + buffer.appendInt32(-925956616) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + serializeInt64(_data.documentId, buffer: buffer, boxed: false) + break + case .messageEntityEmail(let _data): + if boxed { + buffer.appendInt32(1692693954) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .messageEntityHashtag(let _data): + if boxed { + buffer.appendInt32(1868782349) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .messageEntityItalic(let _data): + if boxed { + buffer.appendInt32(-2106619040) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .messageEntityMention(let _data): + if boxed { + buffer.appendInt32(-100378723) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .messageEntityMentionName(let _data): + if boxed { + buffer.appendInt32(-595914432) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + break + case .messageEntityPhone(let _data): + if boxed { + buffer.appendInt32(-1687559349) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .messageEntityPre(let _data): + if boxed { + buffer.appendInt32(1938967520) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + serializeString(_data.language, buffer: buffer, boxed: false) + break + case .messageEntitySpoiler(let _data): + if boxed { + buffer.appendInt32(852137487) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .messageEntityStrike(let _data): + if boxed { + buffer.appendInt32(-1090087980) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .messageEntityTextUrl(let _data): + if boxed { + buffer.appendInt32(1990644519) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + break + case .messageEntityUnderline(let _data): + if boxed { + buffer.appendInt32(-1672577397) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .messageEntityUnknown(let _data): + if boxed { + buffer.appendInt32(-1148011883) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .messageEntityUrl(let _data): + if boxed { + buffer.appendInt32(1859134776) + } + serializeInt32(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputMessageEntityMentionName(let _data): + return ("inputMessageEntityMentionName", [("offset", _data.offset as Any), ("length", _data.length as Any), ("userId", _data.userId as Any)]) + case .messageEntityBankCard(let _data): + return ("messageEntityBankCard", [("offset", _data.offset as Any), ("length", _data.length as Any)]) + case .messageEntityBlockquote(let _data): + return ("messageEntityBlockquote", [("flags", _data.flags as Any), ("offset", _data.offset as Any), ("length", _data.length as Any)]) + case .messageEntityBold(let _data): + return ("messageEntityBold", [("offset", _data.offset as Any), ("length", _data.length as Any)]) + case .messageEntityBotCommand(let _data): + return ("messageEntityBotCommand", [("offset", _data.offset as Any), ("length", _data.length as Any)]) + case .messageEntityCashtag(let _data): + return ("messageEntityCashtag", [("offset", _data.offset as Any), ("length", _data.length as Any)]) + case .messageEntityCode(let _data): + return ("messageEntityCode", [("offset", _data.offset as Any), ("length", _data.length as Any)]) + case .messageEntityCustomEmoji(let _data): + return ("messageEntityCustomEmoji", [("offset", _data.offset as Any), ("length", _data.length as Any), ("documentId", _data.documentId as Any)]) + case .messageEntityEmail(let _data): + return ("messageEntityEmail", [("offset", _data.offset as Any), ("length", _data.length as Any)]) + case .messageEntityHashtag(let _data): + return ("messageEntityHashtag", [("offset", _data.offset as Any), ("length", _data.length as Any)]) + case .messageEntityItalic(let _data): + return ("messageEntityItalic", [("offset", _data.offset as Any), ("length", _data.length as Any)]) + case .messageEntityMention(let _data): + return ("messageEntityMention", [("offset", _data.offset as Any), ("length", _data.length as Any)]) + case .messageEntityMentionName(let _data): + return ("messageEntityMentionName", [("offset", _data.offset as Any), ("length", _data.length as Any), ("userId", _data.userId as Any)]) + case .messageEntityPhone(let _data): + return ("messageEntityPhone", [("offset", _data.offset as Any), ("length", _data.length as Any)]) + case .messageEntityPre(let _data): + return ("messageEntityPre", [("offset", _data.offset as Any), ("length", _data.length as Any), ("language", _data.language as Any)]) + case .messageEntitySpoiler(let _data): + return ("messageEntitySpoiler", [("offset", _data.offset as Any), ("length", _data.length as Any)]) + case .messageEntityStrike(let _data): + return ("messageEntityStrike", [("offset", _data.offset as Any), ("length", _data.length as Any)]) + case .messageEntityTextUrl(let _data): + return ("messageEntityTextUrl", [("offset", _data.offset as Any), ("length", _data.length as Any), ("url", _data.url as Any)]) + case .messageEntityUnderline(let _data): + return ("messageEntityUnderline", [("offset", _data.offset as Any), ("length", _data.length as Any)]) + case .messageEntityUnknown(let _data): + return ("messageEntityUnknown", [("offset", _data.offset as Any), ("length", _data.length as Any)]) + case .messageEntityUrl(let _data): + return ("messageEntityUrl", [("offset", _data.offset as Any), ("length", _data.length as Any)]) + } + } + public static func parse_inputMessageEntityMentionName(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? _1 = reader.readInt32() @@ -239,10 +419,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessageEntity.inputMessageEntityMentionName(offset: _1!, length: _2!, userId: _3!) + if _c1 && _c2 && _c3 { + return Api.MessageEntity.inputMessageEntityMentionName(Cons_inputMessageEntityMentionName(offset: _1!, length: _2!, userId: _3!)) + } + else { + return nil + } } public static func parse_messageEntityBankCard(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -251,9 +433,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageEntity.messageEntityBankCard(offset: _1!, length: _2!) + if _c1 && _c2 { + return Api.MessageEntity.messageEntityBankCard(Cons_messageEntityBankCard(offset: _1!, length: _2!)) + } + else { + return nil + } } public static func parse_messageEntityBlockquote(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -265,10 +450,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessageEntity.messageEntityBlockquote(flags: _1!, offset: _2!, length: _3!) + if _c1 && _c2 && _c3 { + return Api.MessageEntity.messageEntityBlockquote(Cons_messageEntityBlockquote(flags: _1!, offset: _2!, length: _3!)) + } + else { + return nil + } } public static func parse_messageEntityBold(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -277,9 +464,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageEntity.messageEntityBold(offset: _1!, length: _2!) + if _c1 && _c2 { + return Api.MessageEntity.messageEntityBold(Cons_messageEntityBold(offset: _1!, length: _2!)) + } + else { + return nil + } } public static func parse_messageEntityBotCommand(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -288,9 +478,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageEntity.messageEntityBotCommand(offset: _1!, length: _2!) + if _c1 && _c2 { + return Api.MessageEntity.messageEntityBotCommand(Cons_messageEntityBotCommand(offset: _1!, length: _2!)) + } + else { + return nil + } } public static func parse_messageEntityCashtag(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -299,9 +492,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageEntity.messageEntityCashtag(offset: _1!, length: _2!) + if _c1 && _c2 { + return Api.MessageEntity.messageEntityCashtag(Cons_messageEntityCashtag(offset: _1!, length: _2!)) + } + else { + return nil + } } public static func parse_messageEntityCode(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -310,9 +506,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageEntity.messageEntityCode(offset: _1!, length: _2!) + if _c1 && _c2 { + return Api.MessageEntity.messageEntityCode(Cons_messageEntityCode(offset: _1!, length: _2!)) + } + else { + return nil + } } public static func parse_messageEntityCustomEmoji(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -324,10 +523,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessageEntity.messageEntityCustomEmoji(offset: _1!, length: _2!, documentId: _3!) + if _c1 && _c2 && _c3 { + return Api.MessageEntity.messageEntityCustomEmoji(Cons_messageEntityCustomEmoji(offset: _1!, length: _2!, documentId: _3!)) + } + else { + return nil + } } public static func parse_messageEntityEmail(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -336,9 +537,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageEntity.messageEntityEmail(offset: _1!, length: _2!) + if _c1 && _c2 { + return Api.MessageEntity.messageEntityEmail(Cons_messageEntityEmail(offset: _1!, length: _2!)) + } + else { + return nil + } } public static func parse_messageEntityHashtag(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -347,9 +551,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageEntity.messageEntityHashtag(offset: _1!, length: _2!) + if _c1 && _c2 { + return Api.MessageEntity.messageEntityHashtag(Cons_messageEntityHashtag(offset: _1!, length: _2!)) + } + else { + return nil + } } public static func parse_messageEntityItalic(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -358,9 +565,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageEntity.messageEntityItalic(offset: _1!, length: _2!) + if _c1 && _c2 { + return Api.MessageEntity.messageEntityItalic(Cons_messageEntityItalic(offset: _1!, length: _2!)) + } + else { + return nil + } } public static func parse_messageEntityMention(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -369,9 +579,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageEntity.messageEntityMention(offset: _1!, length: _2!) + if _c1 && _c2 { + return Api.MessageEntity.messageEntityMention(Cons_messageEntityMention(offset: _1!, length: _2!)) + } + else { + return nil + } } public static func parse_messageEntityMentionName(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -383,10 +596,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessageEntity.messageEntityMentionName(offset: _1!, length: _2!, userId: _3!) + if _c1 && _c2 && _c3 { + return Api.MessageEntity.messageEntityMentionName(Cons_messageEntityMentionName(offset: _1!, length: _2!, userId: _3!)) + } + else { + return nil + } } public static func parse_messageEntityPhone(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -395,9 +610,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageEntity.messageEntityPhone(offset: _1!, length: _2!) + if _c1 && _c2 { + return Api.MessageEntity.messageEntityPhone(Cons_messageEntityPhone(offset: _1!, length: _2!)) + } + else { + return nil + } } public static func parse_messageEntityPre(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -409,10 +627,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessageEntity.messageEntityPre(offset: _1!, length: _2!, language: _3!) + if _c1 && _c2 && _c3 { + return Api.MessageEntity.messageEntityPre(Cons_messageEntityPre(offset: _1!, length: _2!, language: _3!)) + } + else { + return nil + } } public static func parse_messageEntitySpoiler(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -421,9 +641,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageEntity.messageEntitySpoiler(offset: _1!, length: _2!) + if _c1 && _c2 { + return Api.MessageEntity.messageEntitySpoiler(Cons_messageEntitySpoiler(offset: _1!, length: _2!)) + } + else { + return nil + } } public static func parse_messageEntityStrike(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -432,9 +655,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageEntity.messageEntityStrike(offset: _1!, length: _2!) + if _c1 && _c2 { + return Api.MessageEntity.messageEntityStrike(Cons_messageEntityStrike(offset: _1!, length: _2!)) + } + else { + return nil + } } public static func parse_messageEntityTextUrl(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -446,10 +672,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessageEntity.messageEntityTextUrl(offset: _1!, length: _2!, url: _3!) + if _c1 && _c2 && _c3 { + return Api.MessageEntity.messageEntityTextUrl(Cons_messageEntityTextUrl(offset: _1!, length: _2!, url: _3!)) + } + else { + return nil + } } public static func parse_messageEntityUnderline(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -458,9 +686,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageEntity.messageEntityUnderline(offset: _1!, length: _2!) + if _c1 && _c2 { + return Api.MessageEntity.messageEntityUnderline(Cons_messageEntityUnderline(offset: _1!, length: _2!)) + } + else { + return nil + } } public static func parse_messageEntityUnknown(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -469,9 +700,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageEntity.messageEntityUnknown(offset: _1!, length: _2!) + if _c1 && _c2 { + return Api.MessageEntity.messageEntityUnknown(Cons_messageEntityUnknown(offset: _1!, length: _2!)) + } + else { + return nil + } } public static func parse_messageEntityUrl(_ reader: BufferReader) -> MessageEntity? { var _1: Int32? @@ -480,149 +714,258 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageEntity.messageEntityUrl(offset: _1!, length: _2!) + if _c1 && _c2 { + return Api.MessageEntity.messageEntityUrl(Cons_messageEntityUrl(offset: _1!, length: _2!)) + } + else { + return nil + } } - } } public extension Api { indirect enum MessageExtendedMedia: TypeConstructorDescription { - case messageExtendedMedia(media: Api.MessageMedia) - case messageExtendedMediaPreview(flags: Int32, w: Int32?, h: Int32?, thumb: Api.PhotoSize?, videoDuration: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messageExtendedMedia(let media): - if boxed { - buffer.appendInt32(-297296796) - } - media.serialize(buffer, true) - break - case .messageExtendedMediaPreview(let flags, let w, let h, let thumb, let videoDuration): - if boxed { - buffer.appendInt32(-1386050360) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(w!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(h!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {thumb!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(videoDuration!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messageExtendedMedia(let media): - return ("messageExtendedMedia", [("media", media as Any)]) - case .messageExtendedMediaPreview(let flags, let w, let h, let thumb, let videoDuration): - return ("messageExtendedMediaPreview", [("flags", flags as Any), ("w", w as Any), ("h", h as Any), ("thumb", thumb as Any), ("videoDuration", videoDuration as Any)]) - } - } - + public class Cons_messageExtendedMedia { + public var media: Api.MessageMedia + public init(media: Api.MessageMedia) { + self.media = media + } + } + public class Cons_messageExtendedMediaPreview { + public var flags: Int32 + public var w: Int32? + public var h: Int32? + public var thumb: Api.PhotoSize? + public var videoDuration: Int32? + public init(flags: Int32, w: Int32?, h: Int32?, thumb: Api.PhotoSize?, videoDuration: Int32?) { + self.flags = flags + self.w = w + self.h = h + self.thumb = thumb + self.videoDuration = videoDuration + } + } + case messageExtendedMedia(Cons_messageExtendedMedia) + case messageExtendedMediaPreview(Cons_messageExtendedMediaPreview) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messageExtendedMedia(let _data): + if boxed { + buffer.appendInt32(-297296796) + } + _data.media.serialize(buffer, true) + break + case .messageExtendedMediaPreview(let _data): + if boxed { + buffer.appendInt32(-1386050360) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.w!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.h!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.thumb!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.videoDuration!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messageExtendedMedia(let _data): + return ("messageExtendedMedia", [("media", _data.media as Any)]) + case .messageExtendedMediaPreview(let _data): + return ("messageExtendedMediaPreview", [("flags", _data.flags as Any), ("w", _data.w as Any), ("h", _data.h as Any), ("thumb", _data.thumb as Any), ("videoDuration", _data.videoDuration as Any)]) + } + } + public static func parse_messageExtendedMedia(_ reader: BufferReader) -> MessageExtendedMedia? { var _1: Api.MessageMedia? if let signature = reader.readInt32() { _1 = Api.parse(reader, signature: signature) as? Api.MessageMedia } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageExtendedMedia.messageExtendedMedia(media: _1!) + if _c1 { + return Api.MessageExtendedMedia.messageExtendedMedia(Cons_messageExtendedMedia(media: _1!)) + } + else { + return nil + } } public static func parse_messageExtendedMediaPreview(_ reader: BufferReader) -> MessageExtendedMedia? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt32() + } var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } var _4: Api.PhotoSize? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.PhotoSize - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.PhotoSize + } + } var _5: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _5 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 2) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.MessageExtendedMedia.messageExtendedMediaPreview(flags: _1!, w: _2, h: _3, thumb: _4, videoDuration: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.MessageExtendedMedia.messageExtendedMediaPreview(Cons_messageExtendedMediaPreview(flags: _1!, w: _2, h: _3, thumb: _4, videoDuration: _5)) + } + else { + return nil + } } - } } public extension Api { enum MessageFwdHeader: TypeConstructorDescription { - case messageFwdHeader(flags: Int32, fromId: Api.Peer?, fromName: String?, date: Int32, channelPost: Int32?, postAuthor: String?, savedFromPeer: Api.Peer?, savedFromMsgId: Int32?, savedFromId: Api.Peer?, savedFromName: String?, savedDate: Int32?, psaType: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messageFwdHeader(let flags, let fromId, let fromName, let date, let channelPost, let postAuthor, let savedFromPeer, let savedFromMsgId, let savedFromId, let savedFromName, let savedDate, let psaType): - if boxed { - buffer.appendInt32(1313731771) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {fromId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 5) != 0 {serializeString(fromName!, buffer: buffer, boxed: false)} - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(channelPost!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeString(postAuthor!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {savedFromPeer!.serialize(buffer, true)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(savedFromMsgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {savedFromId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 9) != 0 {serializeString(savedFromName!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 10) != 0 {serializeInt32(savedDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 6) != 0 {serializeString(psaType!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messageFwdHeader(let flags, let fromId, let fromName, let date, let channelPost, let postAuthor, let savedFromPeer, let savedFromMsgId, let savedFromId, let savedFromName, let savedDate, let psaType): - return ("messageFwdHeader", [("flags", flags as Any), ("fromId", fromId as Any), ("fromName", fromName as Any), ("date", date as Any), ("channelPost", channelPost as Any), ("postAuthor", postAuthor as Any), ("savedFromPeer", savedFromPeer as Any), ("savedFromMsgId", savedFromMsgId as Any), ("savedFromId", savedFromId as Any), ("savedFromName", savedFromName as Any), ("savedDate", savedDate as Any), ("psaType", psaType as Any)]) - } - } - + public class Cons_messageFwdHeader { + public var flags: Int32 + public var fromId: Api.Peer? + public var fromName: String? + public var date: Int32 + public var channelPost: Int32? + public var postAuthor: String? + public var savedFromPeer: Api.Peer? + public var savedFromMsgId: Int32? + public var savedFromId: Api.Peer? + public var savedFromName: String? + public var savedDate: Int32? + public var psaType: String? + public init(flags: Int32, fromId: Api.Peer?, fromName: String?, date: Int32, channelPost: Int32?, postAuthor: String?, savedFromPeer: Api.Peer?, savedFromMsgId: Int32?, savedFromId: Api.Peer?, savedFromName: String?, savedDate: Int32?, psaType: String?) { + self.flags = flags + self.fromId = fromId + self.fromName = fromName + self.date = date + self.channelPost = channelPost + self.postAuthor = postAuthor + self.savedFromPeer = savedFromPeer + self.savedFromMsgId = savedFromMsgId + self.savedFromId = savedFromId + self.savedFromName = savedFromName + self.savedDate = savedDate + self.psaType = psaType + } + } + case messageFwdHeader(Cons_messageFwdHeader) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messageFwdHeader(let _data): + if boxed { + buffer.appendInt32(1313731771) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.fromId!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeString(_data.fromName!, buffer: buffer, boxed: false) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.channelPost!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.postAuthor!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + _data.savedFromPeer!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.savedFromMsgId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + _data.savedFromId!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 9) != 0 { + serializeString(_data.savedFromName!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 10) != 0 { + serializeInt32(_data.savedDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + serializeString(_data.psaType!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messageFwdHeader(let _data): + return ("messageFwdHeader", [("flags", _data.flags as Any), ("fromId", _data.fromId as Any), ("fromName", _data.fromName as Any), ("date", _data.date as Any), ("channelPost", _data.channelPost as Any), ("postAuthor", _data.postAuthor as Any), ("savedFromPeer", _data.savedFromPeer as Any), ("savedFromMsgId", _data.savedFromMsgId as Any), ("savedFromId", _data.savedFromId as Any), ("savedFromName", _data.savedFromName as Any), ("savedDate", _data.savedDate as Any), ("psaType", _data.psaType as Any)]) + } + } + public static func parse_messageFwdHeader(_ reader: BufferReader) -> MessageFwdHeader? { var _1: Int32? _1 = reader.readInt32() var _2: Api.Peer? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _3: String? - if Int(_1!) & Int(1 << 5) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 5) != 0 { + _3 = parseString(reader) + } var _4: Int32? _4 = reader.readInt32() var _5: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _5 = reader.readInt32() + } var _6: String? - if Int(_1!) & Int(1 << 3) != 0 {_6 = parseString(reader) } + if Int(_1!) & Int(1 << 3) != 0 { + _6 = parseString(reader) + } var _7: Api.Peer? - if Int(_1!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _8: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_8 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _8 = reader.readInt32() + } var _9: Api.Peer? - if Int(_1!) & Int(1 << 8) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 8) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _10: String? - if Int(_1!) & Int(1 << 9) != 0 {_10 = parseString(reader) } + if Int(_1!) & Int(1 << 9) != 0 { + _10 = parseString(reader) + } var _11: Int32? - if Int(_1!) & Int(1 << 10) != 0 {_11 = reader.readInt32() } + if Int(_1!) & Int(1 << 10) != 0 { + _11 = reader.readInt32() + } var _12: String? - if Int(_1!) & Int(1 << 6) != 0 {_12 = parseString(reader) } + if Int(_1!) & Int(1 << 6) != 0 { + _12 = parseString(reader) + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 5) == 0) || _3 != nil @@ -635,288 +978,540 @@ public extension Api { let _c10 = (Int(_1!) & Int(1 << 9) == 0) || _10 != nil let _c11 = (Int(_1!) & Int(1 << 10) == 0) || _11 != nil let _c12 = (Int(_1!) & Int(1 << 6) == 0) || _12 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - return Api.MessageFwdHeader.messageFwdHeader(flags: _1!, fromId: _2, fromName: _3, date: _4!, channelPost: _5, postAuthor: _6, savedFromPeer: _7, savedFromMsgId: _8, savedFromId: _9, savedFromName: _10, savedDate: _11, psaType: _12) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 { + return Api.MessageFwdHeader.messageFwdHeader(Cons_messageFwdHeader(flags: _1!, fromId: _2, fromName: _3, date: _4!, channelPost: _5, postAuthor: _6, savedFromPeer: _7, savedFromMsgId: _8, savedFromId: _9, savedFromName: _10, savedDate: _11, psaType: _12)) + } + else { + return nil + } } - } } public extension Api { indirect enum MessageMedia: TypeConstructorDescription { - case messageMediaContact(phoneNumber: String, firstName: String, lastName: String, vcard: String, userId: Int64) - case messageMediaDice(flags: Int32, value: Int32, emoticon: String, gameOutcome: Api.messages.EmojiGameOutcome?) - case messageMediaDocument(flags: Int32, document: Api.Document?, altDocuments: [Api.Document]?, videoCover: Api.Photo?, videoTimestamp: Int32?, ttlSeconds: Int32?) + public class Cons_messageMediaContact { + public var phoneNumber: String + public var firstName: String + public var lastName: String + public var vcard: String + public var userId: Int64 + public init(phoneNumber: String, firstName: String, lastName: String, vcard: String, userId: Int64) { + self.phoneNumber = phoneNumber + self.firstName = firstName + self.lastName = lastName + self.vcard = vcard + self.userId = userId + } + } + public class Cons_messageMediaDice { + public var flags: Int32 + public var value: Int32 + public var emoticon: String + public var gameOutcome: Api.messages.EmojiGameOutcome? + public init(flags: Int32, value: Int32, emoticon: String, gameOutcome: Api.messages.EmojiGameOutcome?) { + self.flags = flags + self.value = value + self.emoticon = emoticon + self.gameOutcome = gameOutcome + } + } + public class Cons_messageMediaDocument { + public var flags: Int32 + public var document: Api.Document? + public var altDocuments: [Api.Document]? + public var videoCover: Api.Photo? + public var videoTimestamp: Int32? + public var ttlSeconds: Int32? + public init(flags: Int32, document: Api.Document?, altDocuments: [Api.Document]?, videoCover: Api.Photo?, videoTimestamp: Int32?, ttlSeconds: Int32?) { + self.flags = flags + self.document = document + self.altDocuments = altDocuments + self.videoCover = videoCover + self.videoTimestamp = videoTimestamp + self.ttlSeconds = ttlSeconds + } + } + public class Cons_messageMediaGame { + public var game: Api.Game + public init(game: Api.Game) { + self.game = game + } + } + public class Cons_messageMediaGeo { + public var geo: Api.GeoPoint + public init(geo: Api.GeoPoint) { + self.geo = geo + } + } + public class Cons_messageMediaGeoLive { + public var flags: Int32 + public var geo: Api.GeoPoint + public var heading: Int32? + public var period: Int32 + public var proximityNotificationRadius: Int32? + public init(flags: Int32, geo: Api.GeoPoint, heading: Int32?, period: Int32, proximityNotificationRadius: Int32?) { + self.flags = flags + self.geo = geo + self.heading = heading + self.period = period + self.proximityNotificationRadius = proximityNotificationRadius + } + } + public class Cons_messageMediaGiveaway { + public var flags: Int32 + public var channels: [Int64] + public var countriesIso2: [String]? + public var prizeDescription: String? + public var quantity: Int32 + public var months: Int32? + public var stars: Int64? + public var untilDate: Int32 + public init(flags: Int32, channels: [Int64], countriesIso2: [String]?, prizeDescription: String?, quantity: Int32, months: Int32?, stars: Int64?, untilDate: Int32) { + self.flags = flags + self.channels = channels + self.countriesIso2 = countriesIso2 + self.prizeDescription = prizeDescription + self.quantity = quantity + self.months = months + self.stars = stars + self.untilDate = untilDate + } + } + public class Cons_messageMediaGiveawayResults { + public var flags: Int32 + public var channelId: Int64 + public var additionalPeersCount: Int32? + public var launchMsgId: Int32 + public var winnersCount: Int32 + public var unclaimedCount: Int32 + public var winners: [Int64] + public var months: Int32? + public var stars: Int64? + public var prizeDescription: String? + public var untilDate: Int32 + public init(flags: Int32, channelId: Int64, additionalPeersCount: Int32?, launchMsgId: Int32, winnersCount: Int32, unclaimedCount: Int32, winners: [Int64], months: Int32?, stars: Int64?, prizeDescription: String?, untilDate: Int32) { + self.flags = flags + self.channelId = channelId + self.additionalPeersCount = additionalPeersCount + self.launchMsgId = launchMsgId + self.winnersCount = winnersCount + self.unclaimedCount = unclaimedCount + self.winners = winners + self.months = months + self.stars = stars + self.prizeDescription = prizeDescription + self.untilDate = untilDate + } + } + public class Cons_messageMediaInvoice { + public var flags: Int32 + public var title: String + public var description: String + public var photo: Api.WebDocument? + public var receiptMsgId: Int32? + public var currency: String + public var totalAmount: Int64 + public var startParam: String + public var extendedMedia: Api.MessageExtendedMedia? + public init(flags: Int32, title: String, description: String, photo: Api.WebDocument?, receiptMsgId: Int32?, currency: String, totalAmount: Int64, startParam: String, extendedMedia: Api.MessageExtendedMedia?) { + self.flags = flags + self.title = title + self.description = description + self.photo = photo + self.receiptMsgId = receiptMsgId + self.currency = currency + self.totalAmount = totalAmount + self.startParam = startParam + self.extendedMedia = extendedMedia + } + } + public class Cons_messageMediaPaidMedia { + public var starsAmount: Int64 + public var extendedMedia: [Api.MessageExtendedMedia] + public init(starsAmount: Int64, extendedMedia: [Api.MessageExtendedMedia]) { + self.starsAmount = starsAmount + self.extendedMedia = extendedMedia + } + } + public class Cons_messageMediaPhoto { + public var flags: Int32 + public var photo: Api.Photo? + public var ttlSeconds: Int32? + public init(flags: Int32, photo: Api.Photo?, ttlSeconds: Int32?) { + self.flags = flags + self.photo = photo + self.ttlSeconds = ttlSeconds + } + } + public class Cons_messageMediaPoll { + public var poll: Api.Poll + public var results: Api.PollResults + public init(poll: Api.Poll, results: Api.PollResults) { + self.poll = poll + self.results = results + } + } + public class Cons_messageMediaStory { + public var flags: Int32 + public var peer: Api.Peer + public var id: Int32 + public var story: Api.StoryItem? + public init(flags: Int32, peer: Api.Peer, id: Int32, story: Api.StoryItem?) { + self.flags = flags + self.peer = peer + self.id = id + self.story = story + } + } + public class Cons_messageMediaToDo { + public var flags: Int32 + public var todo: Api.TodoList + public var completions: [Api.TodoCompletion]? + public init(flags: Int32, todo: Api.TodoList, completions: [Api.TodoCompletion]?) { + self.flags = flags + self.todo = todo + self.completions = completions + } + } + public class Cons_messageMediaVenue { + public var geo: Api.GeoPoint + public var title: String + public var address: String + public var provider: String + public var venueId: String + public var venueType: String + public init(geo: Api.GeoPoint, title: String, address: String, provider: String, venueId: String, venueType: String) { + self.geo = geo + self.title = title + self.address = address + self.provider = provider + self.venueId = venueId + self.venueType = venueType + } + } + public class Cons_messageMediaVideoStream { + public var flags: Int32 + public var call: Api.InputGroupCall + public init(flags: Int32, call: Api.InputGroupCall) { + self.flags = flags + self.call = call + } + } + public class Cons_messageMediaWebPage { + public var flags: Int32 + public var webpage: Api.WebPage + public init(flags: Int32, webpage: Api.WebPage) { + self.flags = flags + self.webpage = webpage + } + } + case messageMediaContact(Cons_messageMediaContact) + case messageMediaDice(Cons_messageMediaDice) + case messageMediaDocument(Cons_messageMediaDocument) case messageMediaEmpty - case messageMediaGame(game: Api.Game) - case messageMediaGeo(geo: Api.GeoPoint) - case messageMediaGeoLive(flags: Int32, geo: Api.GeoPoint, heading: Int32?, period: Int32, proximityNotificationRadius: Int32?) - case messageMediaGiveaway(flags: Int32, channels: [Int64], countriesIso2: [String]?, prizeDescription: String?, quantity: Int32, months: Int32?, stars: Int64?, untilDate: Int32) - case messageMediaGiveawayResults(flags: Int32, channelId: Int64, additionalPeersCount: Int32?, launchMsgId: Int32, winnersCount: Int32, unclaimedCount: Int32, winners: [Int64], months: Int32?, stars: Int64?, prizeDescription: String?, untilDate: Int32) - case messageMediaInvoice(flags: Int32, title: String, description: String, photo: Api.WebDocument?, receiptMsgId: Int32?, currency: String, totalAmount: Int64, startParam: String, extendedMedia: Api.MessageExtendedMedia?) - case messageMediaPaidMedia(starsAmount: Int64, extendedMedia: [Api.MessageExtendedMedia]) - case messageMediaPhoto(flags: Int32, photo: Api.Photo?, ttlSeconds: Int32?) - case messageMediaPoll(poll: Api.Poll, results: Api.PollResults) - case messageMediaStory(flags: Int32, peer: Api.Peer, id: Int32, story: Api.StoryItem?) - case messageMediaToDo(flags: Int32, todo: Api.TodoList, completions: [Api.TodoCompletion]?) + case messageMediaGame(Cons_messageMediaGame) + case messageMediaGeo(Cons_messageMediaGeo) + case messageMediaGeoLive(Cons_messageMediaGeoLive) + case messageMediaGiveaway(Cons_messageMediaGiveaway) + case messageMediaGiveawayResults(Cons_messageMediaGiveawayResults) + case messageMediaInvoice(Cons_messageMediaInvoice) + case messageMediaPaidMedia(Cons_messageMediaPaidMedia) + case messageMediaPhoto(Cons_messageMediaPhoto) + case messageMediaPoll(Cons_messageMediaPoll) + case messageMediaStory(Cons_messageMediaStory) + case messageMediaToDo(Cons_messageMediaToDo) case messageMediaUnsupported - case messageMediaVenue(geo: Api.GeoPoint, title: String, address: String, provider: String, venueId: String, venueType: String) - case messageMediaVideoStream(flags: Int32, call: Api.InputGroupCall) - case messageMediaWebPage(flags: Int32, webpage: Api.WebPage) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messageMediaContact(let phoneNumber, let firstName, let lastName, let vcard, let userId): - if boxed { - buffer.appendInt32(1882335561) - } - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(firstName, buffer: buffer, boxed: false) - serializeString(lastName, buffer: buffer, boxed: false) - serializeString(vcard, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - break - case .messageMediaDice(let flags, let value, let emoticon, let gameOutcome): - if boxed { - buffer.appendInt32(147581959) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(value, buffer: buffer, boxed: false) - serializeString(emoticon, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {gameOutcome!.serialize(buffer, true)} - break - case .messageMediaDocument(let flags, let document, let altDocuments, let videoCover, let videoTimestamp, let ttlSeconds): - if boxed { - buffer.appendInt32(1389939929) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {document!.serialize(buffer, true)} - if Int(flags) & Int(1 << 5) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(altDocuments!.count)) - for item in altDocuments! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 9) != 0 {videoCover!.serialize(buffer, true)} - if Int(flags) & Int(1 << 10) != 0 {serializeInt32(videoTimestamp!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(ttlSeconds!, buffer: buffer, boxed: false)} - break - case .messageMediaEmpty: - if boxed { - buffer.appendInt32(1038967584) - } - - break - case .messageMediaGame(let game): - if boxed { - buffer.appendInt32(-38694904) - } - game.serialize(buffer, true) - break - case .messageMediaGeo(let geo): - if boxed { - buffer.appendInt32(1457575028) - } - geo.serialize(buffer, true) - break - case .messageMediaGeoLive(let flags, let geo, let heading, let period, let proximityNotificationRadius): - if boxed { - buffer.appendInt32(-1186937242) - } - serializeInt32(flags, buffer: buffer, boxed: false) - geo.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(heading!, buffer: buffer, boxed: false)} - serializeInt32(period, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(proximityNotificationRadius!, buffer: buffer, boxed: false)} - break - case .messageMediaGiveaway(let flags, let channels, let countriesIso2, let prizeDescription, let quantity, let months, let stars, let untilDate): - if boxed { - buffer.appendInt32(-1442366485) - } - serializeInt32(flags, buffer: buffer, boxed: false) + case messageMediaVenue(Cons_messageMediaVenue) + case messageMediaVideoStream(Cons_messageMediaVideoStream) + case messageMediaWebPage(Cons_messageMediaWebPage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messageMediaContact(let _data): + if boxed { + buffer.appendInt32(1882335561) + } + serializeString(_data.phoneNumber, buffer: buffer, boxed: false) + serializeString(_data.firstName, buffer: buffer, boxed: false) + serializeString(_data.lastName, buffer: buffer, boxed: false) + serializeString(_data.vcard, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + break + case .messageMediaDice(let _data): + if boxed { + buffer.appendInt32(147581959) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.value, buffer: buffer, boxed: false) + serializeString(_data.emoticon, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.gameOutcome!.serialize(buffer, true) + } + break + case .messageMediaDocument(let _data): + if boxed { + buffer.appendInt32(1389939929) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.document!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 5) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(channels.count)) - for item in channels { - serializeInt64(item, buffer: buffer, boxed: false) + buffer.appendInt32(Int32(_data.altDocuments!.count)) + for item in _data.altDocuments! { + item.serialize(buffer, true) } - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(countriesIso2!.count)) - for item in countriesIso2! { + } + if Int(_data.flags) & Int(1 << 9) != 0 { + _data.videoCover!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 10) != 0 { + serializeInt32(_data.videoTimestamp!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.ttlSeconds!, buffer: buffer, boxed: false) + } + break + case .messageMediaEmpty: + if boxed { + buffer.appendInt32(1038967584) + } + break + case .messageMediaGame(let _data): + if boxed { + buffer.appendInt32(-38694904) + } + _data.game.serialize(buffer, true) + break + case .messageMediaGeo(let _data): + if boxed { + buffer.appendInt32(1457575028) + } + _data.geo.serialize(buffer, true) + break + case .messageMediaGeoLive(let _data): + if boxed { + buffer.appendInt32(-1186937242) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.geo.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.heading!, buffer: buffer, boxed: false) + } + serializeInt32(_data.period, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.proximityNotificationRadius!, buffer: buffer, boxed: false) + } + break + case .messageMediaGiveaway(let _data): + if boxed { + buffer.appendInt32(-1442366485) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.channels.count)) + for item in _data.channels { + serializeInt64(item, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.countriesIso2!.count)) + for item in _data.countriesIso2! { serializeString(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 3) != 0 {serializeString(prizeDescription!, buffer: buffer, boxed: false)} - serializeInt32(quantity, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(months!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeInt64(stars!, buffer: buffer, boxed: false)} - serializeInt32(untilDate, buffer: buffer, boxed: false) - break - case .messageMediaGiveawayResults(let flags, let channelId, let additionalPeersCount, let launchMsgId, let winnersCount, let unclaimedCount, let winners, let months, let stars, let prizeDescription, let untilDate): - if boxed { - buffer.appendInt32(-827703647) } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(channelId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(additionalPeersCount!, buffer: buffer, boxed: false)} - serializeInt32(launchMsgId, buffer: buffer, boxed: false) - serializeInt32(winnersCount, buffer: buffer, boxed: false) - serializeInt32(unclaimedCount, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.prizeDescription!, buffer: buffer, boxed: false) + } + serializeInt32(_data.quantity, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.months!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeInt64(_data.stars!, buffer: buffer, boxed: false) + } + serializeInt32(_data.untilDate, buffer: buffer, boxed: false) + break + case .messageMediaGiveawayResults(let _data): + if boxed { + buffer.appendInt32(-827703647) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.additionalPeersCount!, buffer: buffer, boxed: false) + } + serializeInt32(_data.launchMsgId, buffer: buffer, boxed: false) + serializeInt32(_data.winnersCount, buffer: buffer, boxed: false) + serializeInt32(_data.unclaimedCount, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.winners.count)) + for item in _data.winners { + serializeInt64(item, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.months!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeInt64(_data.stars!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.prizeDescription!, buffer: buffer, boxed: false) + } + serializeInt32(_data.untilDate, buffer: buffer, boxed: false) + break + case .messageMediaInvoice(let _data): + if boxed { + buffer.appendInt32(-156940077) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.description, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.photo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.receiptMsgId!, buffer: buffer, boxed: false) + } + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.totalAmount, buffer: buffer, boxed: false) + serializeString(_data.startParam, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 4) != 0 { + _data.extendedMedia!.serialize(buffer, true) + } + break + case .messageMediaPaidMedia(let _data): + if boxed { + buffer.appendInt32(-1467669359) + } + serializeInt64(_data.starsAmount, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.extendedMedia.count)) + for item in _data.extendedMedia { + item.serialize(buffer, true) + } + break + case .messageMediaPhoto(let _data): + if boxed { + buffer.appendInt32(1766936791) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.photo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.ttlSeconds!, buffer: buffer, boxed: false) + } + break + case .messageMediaPoll(let _data): + if boxed { + buffer.appendInt32(1272375192) + } + _data.poll.serialize(buffer, true) + _data.results.serialize(buffer, true) + break + case .messageMediaStory(let _data): + if boxed { + buffer.appendInt32(1758159491) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeInt32(_data.id, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.story!.serialize(buffer, true) + } + break + case .messageMediaToDo(let _data): + if boxed { + buffer.appendInt32(-1974226924) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.todo.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(winners.count)) - for item in winners { - serializeInt64(item, buffer: buffer, boxed: false) - } - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(months!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeInt64(stars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(prizeDescription!, buffer: buffer, boxed: false)} - serializeInt32(untilDate, buffer: buffer, boxed: false) - break - case .messageMediaInvoice(let flags, let title, let description, let photo, let receiptMsgId, let currency, let totalAmount, let startParam, let extendedMedia): - if boxed { - buffer.appendInt32(-156940077) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(description, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {photo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(receiptMsgId!, buffer: buffer, boxed: false)} - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(totalAmount, buffer: buffer, boxed: false) - serializeString(startParam, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {extendedMedia!.serialize(buffer, true)} - break - case .messageMediaPaidMedia(let starsAmount, let extendedMedia): - if boxed { - buffer.appendInt32(-1467669359) - } - serializeInt64(starsAmount, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(extendedMedia.count)) - for item in extendedMedia { + buffer.appendInt32(Int32(_data.completions!.count)) + for item in _data.completions! { item.serialize(buffer, true) } - break - case .messageMediaPhoto(let flags, let photo, let ttlSeconds): - if boxed { - buffer.appendInt32(1766936791) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {photo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(ttlSeconds!, buffer: buffer, boxed: false)} - break - case .messageMediaPoll(let poll, let results): - if boxed { - buffer.appendInt32(1272375192) - } - poll.serialize(buffer, true) - results.serialize(buffer, true) - break - case .messageMediaStory(let flags, let peer, let id, let story): - if boxed { - buffer.appendInt32(1758159491) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {story!.serialize(buffer, true)} - break - case .messageMediaToDo(let flags, let todo, let completions): - if boxed { - buffer.appendInt32(-1974226924) - } - serializeInt32(flags, buffer: buffer, boxed: false) - todo.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(completions!.count)) - for item in completions! { - item.serialize(buffer, true) - }} - break - case .messageMediaUnsupported: - if boxed { - buffer.appendInt32(-1618676578) - } - - break - case .messageMediaVenue(let geo, let title, let address, let provider, let venueId, let venueType): - if boxed { - buffer.appendInt32(784356159) - } - geo.serialize(buffer, true) - serializeString(title, buffer: buffer, boxed: false) - serializeString(address, buffer: buffer, boxed: false) - serializeString(provider, buffer: buffer, boxed: false) - serializeString(venueId, buffer: buffer, boxed: false) - serializeString(venueType, buffer: buffer, boxed: false) - break - case .messageMediaVideoStream(let flags, let call): - if boxed { - buffer.appendInt32(-899896439) - } - serializeInt32(flags, buffer: buffer, boxed: false) - call.serialize(buffer, true) - break - case .messageMediaWebPage(let flags, let webpage): - if boxed { - buffer.appendInt32(-571405253) - } - serializeInt32(flags, buffer: buffer, boxed: false) - webpage.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messageMediaContact(let phoneNumber, let firstName, let lastName, let vcard, let userId): - return ("messageMediaContact", [("phoneNumber", phoneNumber as Any), ("firstName", firstName as Any), ("lastName", lastName as Any), ("vcard", vcard as Any), ("userId", userId as Any)]) - case .messageMediaDice(let flags, let value, let emoticon, let gameOutcome): - return ("messageMediaDice", [("flags", flags as Any), ("value", value as Any), ("emoticon", emoticon as Any), ("gameOutcome", gameOutcome as Any)]) - case .messageMediaDocument(let flags, let document, let altDocuments, let videoCover, let videoTimestamp, let ttlSeconds): - return ("messageMediaDocument", [("flags", flags as Any), ("document", document as Any), ("altDocuments", altDocuments as Any), ("videoCover", videoCover as Any), ("videoTimestamp", videoTimestamp as Any), ("ttlSeconds", ttlSeconds as Any)]) - case .messageMediaEmpty: + } + break + case .messageMediaUnsupported: + if boxed { + buffer.appendInt32(-1618676578) + } + break + case .messageMediaVenue(let _data): + if boxed { + buffer.appendInt32(784356159) + } + _data.geo.serialize(buffer, true) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.address, buffer: buffer, boxed: false) + serializeString(_data.provider, buffer: buffer, boxed: false) + serializeString(_data.venueId, buffer: buffer, boxed: false) + serializeString(_data.venueType, buffer: buffer, boxed: false) + break + case .messageMediaVideoStream(let _data): + if boxed { + buffer.appendInt32(-899896439) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.call.serialize(buffer, true) + break + case .messageMediaWebPage(let _data): + if boxed { + buffer.appendInt32(-571405253) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.webpage.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messageMediaContact(let _data): + return ("messageMediaContact", [("phoneNumber", _data.phoneNumber as Any), ("firstName", _data.firstName as Any), ("lastName", _data.lastName as Any), ("vcard", _data.vcard as Any), ("userId", _data.userId as Any)]) + case .messageMediaDice(let _data): + return ("messageMediaDice", [("flags", _data.flags as Any), ("value", _data.value as Any), ("emoticon", _data.emoticon as Any), ("gameOutcome", _data.gameOutcome as Any)]) + case .messageMediaDocument(let _data): + return ("messageMediaDocument", [("flags", _data.flags as Any), ("document", _data.document as Any), ("altDocuments", _data.altDocuments as Any), ("videoCover", _data.videoCover as Any), ("videoTimestamp", _data.videoTimestamp as Any), ("ttlSeconds", _data.ttlSeconds as Any)]) + case .messageMediaEmpty: return ("messageMediaEmpty", []) - case .messageMediaGame(let game): - return ("messageMediaGame", [("game", game as Any)]) - case .messageMediaGeo(let geo): - return ("messageMediaGeo", [("geo", geo as Any)]) - case .messageMediaGeoLive(let flags, let geo, let heading, let period, let proximityNotificationRadius): - return ("messageMediaGeoLive", [("flags", flags as Any), ("geo", geo as Any), ("heading", heading as Any), ("period", period as Any), ("proximityNotificationRadius", proximityNotificationRadius as Any)]) - case .messageMediaGiveaway(let flags, let channels, let countriesIso2, let prizeDescription, let quantity, let months, let stars, let untilDate): - return ("messageMediaGiveaway", [("flags", flags as Any), ("channels", channels as Any), ("countriesIso2", countriesIso2 as Any), ("prizeDescription", prizeDescription as Any), ("quantity", quantity as Any), ("months", months as Any), ("stars", stars as Any), ("untilDate", untilDate as Any)]) - case .messageMediaGiveawayResults(let flags, let channelId, let additionalPeersCount, let launchMsgId, let winnersCount, let unclaimedCount, let winners, let months, let stars, let prizeDescription, let untilDate): - return ("messageMediaGiveawayResults", [("flags", flags as Any), ("channelId", channelId as Any), ("additionalPeersCount", additionalPeersCount as Any), ("launchMsgId", launchMsgId as Any), ("winnersCount", winnersCount as Any), ("unclaimedCount", unclaimedCount as Any), ("winners", winners as Any), ("months", months as Any), ("stars", stars as Any), ("prizeDescription", prizeDescription as Any), ("untilDate", untilDate as Any)]) - case .messageMediaInvoice(let flags, let title, let description, let photo, let receiptMsgId, let currency, let totalAmount, let startParam, let extendedMedia): - return ("messageMediaInvoice", [("flags", flags as Any), ("title", title as Any), ("description", description as Any), ("photo", photo as Any), ("receiptMsgId", receiptMsgId as Any), ("currency", currency as Any), ("totalAmount", totalAmount as Any), ("startParam", startParam as Any), ("extendedMedia", extendedMedia as Any)]) - case .messageMediaPaidMedia(let starsAmount, let extendedMedia): - return ("messageMediaPaidMedia", [("starsAmount", starsAmount as Any), ("extendedMedia", extendedMedia as Any)]) - case .messageMediaPhoto(let flags, let photo, let ttlSeconds): - return ("messageMediaPhoto", [("flags", flags as Any), ("photo", photo as Any), ("ttlSeconds", ttlSeconds as Any)]) - case .messageMediaPoll(let poll, let results): - return ("messageMediaPoll", [("poll", poll as Any), ("results", results as Any)]) - case .messageMediaStory(let flags, let peer, let id, let story): - return ("messageMediaStory", [("flags", flags as Any), ("peer", peer as Any), ("id", id as Any), ("story", story as Any)]) - case .messageMediaToDo(let flags, let todo, let completions): - return ("messageMediaToDo", [("flags", flags as Any), ("todo", todo as Any), ("completions", completions as Any)]) - case .messageMediaUnsupported: + case .messageMediaGame(let _data): + return ("messageMediaGame", [("game", _data.game as Any)]) + case .messageMediaGeo(let _data): + return ("messageMediaGeo", [("geo", _data.geo as Any)]) + case .messageMediaGeoLive(let _data): + return ("messageMediaGeoLive", [("flags", _data.flags as Any), ("geo", _data.geo as Any), ("heading", _data.heading as Any), ("period", _data.period as Any), ("proximityNotificationRadius", _data.proximityNotificationRadius as Any)]) + case .messageMediaGiveaway(let _data): + return ("messageMediaGiveaway", [("flags", _data.flags as Any), ("channels", _data.channels as Any), ("countriesIso2", _data.countriesIso2 as Any), ("prizeDescription", _data.prizeDescription as Any), ("quantity", _data.quantity as Any), ("months", _data.months as Any), ("stars", _data.stars as Any), ("untilDate", _data.untilDate as Any)]) + case .messageMediaGiveawayResults(let _data): + return ("messageMediaGiveawayResults", [("flags", _data.flags as Any), ("channelId", _data.channelId as Any), ("additionalPeersCount", _data.additionalPeersCount as Any), ("launchMsgId", _data.launchMsgId as Any), ("winnersCount", _data.winnersCount as Any), ("unclaimedCount", _data.unclaimedCount as Any), ("winners", _data.winners as Any), ("months", _data.months as Any), ("stars", _data.stars as Any), ("prizeDescription", _data.prizeDescription as Any), ("untilDate", _data.untilDate as Any)]) + case .messageMediaInvoice(let _data): + return ("messageMediaInvoice", [("flags", _data.flags as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("photo", _data.photo as Any), ("receiptMsgId", _data.receiptMsgId as Any), ("currency", _data.currency as Any), ("totalAmount", _data.totalAmount as Any), ("startParam", _data.startParam as Any), ("extendedMedia", _data.extendedMedia as Any)]) + case .messageMediaPaidMedia(let _data): + return ("messageMediaPaidMedia", [("starsAmount", _data.starsAmount as Any), ("extendedMedia", _data.extendedMedia as Any)]) + case .messageMediaPhoto(let _data): + return ("messageMediaPhoto", [("flags", _data.flags as Any), ("photo", _data.photo as Any), ("ttlSeconds", _data.ttlSeconds as Any)]) + case .messageMediaPoll(let _data): + return ("messageMediaPoll", [("poll", _data.poll as Any), ("results", _data.results as Any)]) + case .messageMediaStory(let _data): + return ("messageMediaStory", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("id", _data.id as Any), ("story", _data.story as Any)]) + case .messageMediaToDo(let _data): + return ("messageMediaToDo", [("flags", _data.flags as Any), ("todo", _data.todo as Any), ("completions", _data.completions as Any)]) + case .messageMediaUnsupported: return ("messageMediaUnsupported", []) - case .messageMediaVenue(let geo, let title, let address, let provider, let venueId, let venueType): - return ("messageMediaVenue", [("geo", geo as Any), ("title", title as Any), ("address", address as Any), ("provider", provider as Any), ("venueId", venueId as Any), ("venueType", venueType as Any)]) - case .messageMediaVideoStream(let flags, let call): - return ("messageMediaVideoStream", [("flags", flags as Any), ("call", call as Any)]) - case .messageMediaWebPage(let flags, let webpage): - return ("messageMediaWebPage", [("flags", flags as Any), ("webpage", webpage as Any)]) - } - } - + case .messageMediaVenue(let _data): + return ("messageMediaVenue", [("geo", _data.geo as Any), ("title", _data.title as Any), ("address", _data.address as Any), ("provider", _data.provider as Any), ("venueId", _data.venueId as Any), ("venueType", _data.venueType as Any)]) + case .messageMediaVideoStream(let _data): + return ("messageMediaVideoStream", [("flags", _data.flags as Any), ("call", _data.call as Any)]) + case .messageMediaWebPage(let _data): + return ("messageMediaWebPage", [("flags", _data.flags as Any), ("webpage", _data.webpage as Any)]) + } + } + public static func parse_messageMediaContact(_ reader: BufferReader) -> MessageMedia? { var _1: String? _1 = parseString(reader) @@ -933,12 +1528,12 @@ public extension Api { let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.MessageMedia.messageMediaContact(phoneNumber: _1!, firstName: _2!, lastName: _3!, vcard: _4!, userId: _5!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.MessageMedia.messageMediaContact(Cons_messageMediaContact(phoneNumber: _1!, firstName: _2!, lastName: _3!, vcard: _4!, userId: _5!)) + } + else { + return nil + } } public static func parse_messageMediaDice(_ reader: BufferReader) -> MessageMedia? { var _1: Int32? @@ -948,51 +1543,63 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: Api.messages.EmojiGameOutcome? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.messages.EmojiGameOutcome - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.messages.EmojiGameOutcome + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.MessageMedia.messageMediaDice(flags: _1!, value: _2!, emoticon: _3!, gameOutcome: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.MessageMedia.messageMediaDice(Cons_messageMediaDice(flags: _1!, value: _2!, emoticon: _3!, gameOutcome: _4)) + } + else { + return nil + } } public static func parse_messageMediaDocument(_ reader: BufferReader) -> MessageMedia? { var _1: Int32? _1 = reader.readInt32() var _2: Api.Document? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Document - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Document + } + } var _3: [Api.Document]? - if Int(_1!) & Int(1 << 5) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) - } } + if Int(_1!) & Int(1 << 5) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + } + } var _4: Api.Photo? - if Int(_1!) & Int(1 << 9) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Photo - } } + if Int(_1!) & Int(1 << 9) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Photo + } + } var _5: Int32? - if Int(_1!) & Int(1 << 10) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 10) != 0 { + _5 = reader.readInt32() + } var _6: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _6 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 5) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 9) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 10) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.MessageMedia.messageMediaDocument(flags: _1!, document: _2, altDocuments: _3, videoCover: _4, videoTimestamp: _5, ttlSeconds: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.MessageMedia.messageMediaDocument(Cons_messageMediaDocument(flags: _1!, document: _2, altDocuments: _3, videoCover: _4, videoTimestamp: _5, ttlSeconds: _6)) + } + else { + return nil + } } public static func parse_messageMediaEmpty(_ reader: BufferReader) -> MessageMedia? { return Api.MessageMedia.messageMediaEmpty @@ -1003,8 +1610,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Game } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageMedia.messageMediaGame(game: _1!) + if _c1 { + return Api.MessageMedia.messageMediaGame(Cons_messageMediaGame(game: _1!)) + } + else { + return nil + } } public static func parse_messageMediaGeo(_ reader: BufferReader) -> MessageMedia? { var _1: Api.GeoPoint? @@ -1012,8 +1623,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.GeoPoint } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessageMedia.messageMediaGeo(geo: _1!) + if _c1 { + return Api.MessageMedia.messageMediaGeo(Cons_messageMediaGeo(geo: _1!)) + } + else { + return nil + } } public static func parse_messageMediaGeoLive(_ reader: BufferReader) -> MessageMedia? { var _1: Int32? @@ -1023,22 +1638,26 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.GeoPoint } var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } var _4: Int32? _4 = reader.readInt32() var _5: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _5 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.MessageMedia.messageMediaGeoLive(flags: _1!, geo: _2!, heading: _3, period: _4!, proximityNotificationRadius: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.MessageMedia.messageMediaGeoLive(Cons_messageMediaGeoLive(flags: _1!, geo: _2!, heading: _3, period: _4!, proximityNotificationRadius: _5)) + } + else { + return nil + } } public static func parse_messageMediaGiveaway(_ reader: BufferReader) -> MessageMedia? { var _1: Int32? @@ -1048,17 +1667,25 @@ public extension Api { _2 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) } var _3: [String]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) + } + } var _4: String? - if Int(_1!) & Int(1 << 3) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 3) != 0 { + _4 = parseString(reader) + } var _5: Int32? _5 = reader.readInt32() var _6: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _6 = reader.readInt32() + } var _7: Int64? - if Int(_1!) & Int(1 << 5) != 0 {_7 = reader.readInt64() } + if Int(_1!) & Int(1 << 5) != 0 { + _7 = reader.readInt64() + } var _8: Int32? _8 = reader.readInt32() let _c1 = _1 != nil @@ -1069,15 +1696,12 @@ public extension Api { let _c6 = (Int(_1!) & Int(1 << 4) == 0) || _6 != nil let _c7 = (Int(_1!) & Int(1 << 5) == 0) || _7 != nil let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.MessageMedia.messageMediaGiveaway(flags: _1!, channels: _2!, countriesIso2: _3, prizeDescription: _4, quantity: _5!, months: _6, stars: _7, untilDate: _8!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.MessageMedia.messageMediaGiveaway(Cons_messageMediaGiveaway(flags: _1!, channels: _2!, countriesIso2: _3, prizeDescription: _4, quantity: _5!, months: _6, stars: _7, untilDate: _8!)) + } + else { + return nil + } } public static func parse_messageMediaGiveawayResults(_ reader: BufferReader) -> MessageMedia? { var _1: Int32? @@ -1085,7 +1709,9 @@ public extension Api { var _2: Int64? _2 = reader.readInt64() var _3: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 3) != 0 { + _3 = reader.readInt32() + } var _4: Int32? _4 = reader.readInt32() var _5: Int32? @@ -1097,11 +1723,17 @@ public extension Api { _7 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) } var _8: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_8 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _8 = reader.readInt32() + } var _9: Int64? - if Int(_1!) & Int(1 << 5) != 0 {_9 = reader.readInt64() } + if Int(_1!) & Int(1 << 5) != 0 { + _9 = reader.readInt64() + } var _10: String? - if Int(_1!) & Int(1 << 1) != 0 {_10 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _10 = parseString(reader) + } var _11: Int32? _11 = reader.readInt32() let _c1 = _1 != nil @@ -1115,18 +1747,12 @@ public extension Api { let _c9 = (Int(_1!) & Int(1 << 5) == 0) || _9 != nil let _c10 = (Int(_1!) & Int(1 << 1) == 0) || _10 != nil let _c11 = _11 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - return Api.MessageMedia.messageMediaGiveawayResults(flags: _1!, channelId: _2!, additionalPeersCount: _3, launchMsgId: _4!, winnersCount: _5!, unclaimedCount: _6!, winners: _7!, months: _8, stars: _9, prizeDescription: _10, untilDate: _11!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 { + return Api.MessageMedia.messageMediaGiveawayResults(Cons_messageMediaGiveawayResults(flags: _1!, channelId: _2!, additionalPeersCount: _3, launchMsgId: _4!, winnersCount: _5!, unclaimedCount: _6!, winners: _7!, months: _8, stars: _9, prizeDescription: _10, untilDate: _11!)) + } + else { + return nil + } } public static func parse_messageMediaInvoice(_ reader: BufferReader) -> MessageMedia? { var _1: Int32? @@ -1136,11 +1762,15 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: Api.WebDocument? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.WebDocument - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.WebDocument + } + } var _5: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _5 = reader.readInt32() + } var _6: String? _6 = parseString(reader) var _7: Int64? @@ -1148,9 +1778,11 @@ public extension Api { var _8: String? _8 = parseString(reader) var _9: Api.MessageExtendedMedia? - if Int(_1!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.MessageExtendedMedia - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.MessageExtendedMedia + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -1160,16 +1792,12 @@ public extension Api { let _c7 = _7 != nil let _c8 = _8 != nil let _c9 = (Int(_1!) & Int(1 << 4) == 0) || _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.MessageMedia.messageMediaInvoice(flags: _1!, title: _2!, description: _3!, photo: _4, receiptMsgId: _5, currency: _6!, totalAmount: _7!, startParam: _8!, extendedMedia: _9) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.MessageMedia.messageMediaInvoice(Cons_messageMediaInvoice(flags: _1!, title: _2!, description: _3!, photo: _4, receiptMsgId: _5, currency: _6!, totalAmount: _7!, startParam: _8!, extendedMedia: _9)) + } + else { + return nil + } } public static func parse_messageMediaPaidMedia(_ reader: BufferReader) -> MessageMedia? { var _1: Int64? @@ -1180,26 +1808,35 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageMedia.messageMediaPaidMedia(starsAmount: _1!, extendedMedia: _2!) + if _c1 && _c2 { + return Api.MessageMedia.messageMediaPaidMedia(Cons_messageMediaPaidMedia(starsAmount: _1!, extendedMedia: _2!)) + } + else { + return nil + } } public static func parse_messageMediaPhoto(_ reader: BufferReader) -> MessageMedia? { var _1: Int32? _1 = reader.readInt32() var _2: Api.Photo? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Photo - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Photo + } + } var _3: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _3 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 2) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessageMedia.messageMediaPhoto(flags: _1!, photo: _2, ttlSeconds: _3) + if _c1 && _c2 && _c3 { + return Api.MessageMedia.messageMediaPhoto(Cons_messageMediaPhoto(flags: _1!, photo: _2, ttlSeconds: _3)) + } + else { + return nil + } } public static func parse_messageMediaPoll(_ reader: BufferReader) -> MessageMedia? { var _1: Api.Poll? @@ -1212,9 +1849,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageMedia.messageMediaPoll(poll: _1!, results: _2!) + if _c1 && _c2 { + return Api.MessageMedia.messageMediaPoll(Cons_messageMediaPoll(poll: _1!, results: _2!)) + } + else { + return nil + } } public static func parse_messageMediaStory(_ reader: BufferReader) -> MessageMedia? { var _1: Int32? @@ -1226,18 +1866,21 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: Api.StoryItem? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.StoryItem - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.StoryItem + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.MessageMedia.messageMediaStory(flags: _1!, peer: _2!, id: _3!, story: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.MessageMedia.messageMediaStory(Cons_messageMediaStory(flags: _1!, peer: _2!, id: _3!, story: _4)) + } + else { + return nil + } } public static func parse_messageMediaToDo(_ reader: BufferReader) -> MessageMedia? { var _1: Int32? @@ -1247,16 +1890,20 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.TodoList } var _3: [Api.TodoCompletion]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.TodoCompletion.self) - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.TodoCompletion.self) + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessageMedia.messageMediaToDo(flags: _1!, todo: _2!, completions: _3) + if _c1 && _c2 && _c3 { + return Api.MessageMedia.messageMediaToDo(Cons_messageMediaToDo(flags: _1!, todo: _2!, completions: _3)) + } + else { + return nil + } } public static func parse_messageMediaUnsupported(_ reader: BufferReader) -> MessageMedia? { return Api.MessageMedia.messageMediaUnsupported @@ -1282,13 +1929,12 @@ public extension Api { let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.MessageMedia.messageMediaVenue(geo: _1!, title: _2!, address: _3!, provider: _4!, venueId: _5!, venueType: _6!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.MessageMedia.messageMediaVenue(Cons_messageMediaVenue(geo: _1!, title: _2!, address: _3!, provider: _4!, venueId: _5!, venueType: _6!)) + } + else { + return nil + } } public static func parse_messageMediaVideoStream(_ reader: BufferReader) -> MessageMedia? { var _1: Int32? @@ -1299,9 +1945,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageMedia.messageMediaVideoStream(flags: _1!, call: _2!) + if _c1 && _c2 { + return Api.MessageMedia.messageMediaVideoStream(Cons_messageMediaVideoStream(flags: _1!, call: _2!)) + } + else { + return nil + } } public static func parse_messageMediaWebPage(_ reader: BufferReader) -> MessageMedia? { var _1: Int32? @@ -1312,10 +1961,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageMedia.messageMediaWebPage(flags: _1!, webpage: _2!) + if _c1 && _c2 { + return Api.MessageMedia.messageMediaWebPage(Cons_messageMediaWebPage(flags: _1!, webpage: _2!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api17.swift b/submodules/TelegramApi/Sources/Api17.swift index 5cc52b37..ce9899e3 100644 --- a/submodules/TelegramApi/Sources/Api17.swift +++ b/submodules/TelegramApi/Sources/Api17.swift @@ -1,28 +1,40 @@ public extension Api { enum MessagePeerReaction: TypeConstructorDescription { - case messagePeerReaction(flags: Int32, peerId: Api.Peer, date: Int32, reaction: Api.Reaction) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messagePeerReaction(let flags, let peerId, let date, let reaction): - if boxed { - buffer.appendInt32(-1938180548) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peerId.serialize(buffer, true) - serializeInt32(date, buffer: buffer, boxed: false) - reaction.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messagePeerReaction(let flags, let peerId, let date, let reaction): - return ("messagePeerReaction", [("flags", flags as Any), ("peerId", peerId as Any), ("date", date as Any), ("reaction", reaction as Any)]) - } - } - + public class Cons_messagePeerReaction { + public var flags: Int32 + public var peerId: Api.Peer + public var date: Int32 + public var reaction: Api.Reaction + public init(flags: Int32, peerId: Api.Peer, date: Int32, reaction: Api.Reaction) { + self.flags = flags + self.peerId = peerId + self.date = date + self.reaction = reaction + } + } + case messagePeerReaction(Cons_messagePeerReaction) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messagePeerReaction(let _data): + if boxed { + buffer.appendInt32(-1938180548) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peerId.serialize(buffer, true) + serializeInt32(_data.date, buffer: buffer, boxed: false) + _data.reaction.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messagePeerReaction(let _data): + return ("messagePeerReaction", [("flags", _data.flags as Any), ("peerId", _data.peerId as Any), ("date", _data.date as Any), ("reaction", _data.reaction as Any)]) + } + } + public static func parse_messagePeerReaction(_ reader: BufferReader) -> MessagePeerReaction? { var _1: Int32? _1 = reader.readInt32() @@ -40,64 +52,92 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.MessagePeerReaction.messagePeerReaction(flags: _1!, peerId: _2!, date: _3!, reaction: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.MessagePeerReaction.messagePeerReaction(Cons_messagePeerReaction(flags: _1!, peerId: _2!, date: _3!, reaction: _4!)) + } + else { + return nil + } } - } } public extension Api { enum MessagePeerVote: TypeConstructorDescription { - case messagePeerVote(peer: Api.Peer, option: Buffer, date: Int32) - case messagePeerVoteInputOption(peer: Api.Peer, date: Int32) - case messagePeerVoteMultiple(peer: Api.Peer, options: [Buffer], date: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messagePeerVote(let peer, let option, let date): - if boxed { - buffer.appendInt32(-1228133028) - } - peer.serialize(buffer, true) - serializeBytes(option, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - break - case .messagePeerVoteInputOption(let peer, let date): - if boxed { - buffer.appendInt32(1959634180) - } - peer.serialize(buffer, true) - serializeInt32(date, buffer: buffer, boxed: false) - break - case .messagePeerVoteMultiple(let peer, let options, let date): - if boxed { - buffer.appendInt32(1177089766) - } - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(options.count)) - for item in options { - serializeBytes(item, buffer: buffer, boxed: false) - } - serializeInt32(date, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messagePeerVote(let peer, let option, let date): - return ("messagePeerVote", [("peer", peer as Any), ("option", option as Any), ("date", date as Any)]) - case .messagePeerVoteInputOption(let peer, let date): - return ("messagePeerVoteInputOption", [("peer", peer as Any), ("date", date as Any)]) - case .messagePeerVoteMultiple(let peer, let options, let date): - return ("messagePeerVoteMultiple", [("peer", peer as Any), ("options", options as Any), ("date", date as Any)]) - } - } - + public class Cons_messagePeerVote { + public var peer: Api.Peer + public var option: Buffer + public var date: Int32 + public init(peer: Api.Peer, option: Buffer, date: Int32) { + self.peer = peer + self.option = option + self.date = date + } + } + public class Cons_messagePeerVoteInputOption { + public var peer: Api.Peer + public var date: Int32 + public init(peer: Api.Peer, date: Int32) { + self.peer = peer + self.date = date + } + } + public class Cons_messagePeerVoteMultiple { + public var peer: Api.Peer + public var options: [Buffer] + public var date: Int32 + public init(peer: Api.Peer, options: [Buffer], date: Int32) { + self.peer = peer + self.options = options + self.date = date + } + } + case messagePeerVote(Cons_messagePeerVote) + case messagePeerVoteInputOption(Cons_messagePeerVoteInputOption) + case messagePeerVoteMultiple(Cons_messagePeerVoteMultiple) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messagePeerVote(let _data): + if boxed { + buffer.appendInt32(-1228133028) + } + _data.peer.serialize(buffer, true) + serializeBytes(_data.option, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + case .messagePeerVoteInputOption(let _data): + if boxed { + buffer.appendInt32(1959634180) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + case .messagePeerVoteMultiple(let _data): + if boxed { + buffer.appendInt32(1177089766) + } + _data.peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.options.count)) + for item in _data.options { + serializeBytes(item, buffer: buffer, boxed: false) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messagePeerVote(let _data): + return ("messagePeerVote", [("peer", _data.peer as Any), ("option", _data.option as Any), ("date", _data.date as Any)]) + case .messagePeerVoteInputOption(let _data): + return ("messagePeerVoteInputOption", [("peer", _data.peer as Any), ("date", _data.date as Any)]) + case .messagePeerVoteMultiple(let _data): + return ("messagePeerVoteMultiple", [("peer", _data.peer as Any), ("options", _data.options as Any), ("date", _data.date as Any)]) + } + } + public static func parse_messagePeerVote(_ reader: BufferReader) -> MessagePeerVote? { var _1: Api.Peer? if let signature = reader.readInt32() { @@ -110,10 +150,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessagePeerVote.messagePeerVote(peer: _1!, option: _2!, date: _3!) + if _c1 && _c2 && _c3 { + return Api.MessagePeerVote.messagePeerVote(Cons_messagePeerVote(peer: _1!, option: _2!, date: _3!)) + } + else { + return nil + } } public static func parse_messagePeerVoteInputOption(_ reader: BufferReader) -> MessagePeerVote? { var _1: Api.Peer? @@ -124,9 +166,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessagePeerVote.messagePeerVoteInputOption(peer: _1!, date: _2!) + if _c1 && _c2 { + return Api.MessagePeerVote.messagePeerVoteInputOption(Cons_messagePeerVoteInputOption(peer: _1!, date: _2!)) + } + else { + return nil + } } public static func parse_messagePeerVoteMultiple(_ reader: BufferReader) -> MessagePeerVote? { var _1: Api.Peer? @@ -142,37 +187,46 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessagePeerVote.messagePeerVoteMultiple(peer: _1!, options: _2!, date: _3!) + if _c1 && _c2 && _c3 { + return Api.MessagePeerVote.messagePeerVoteMultiple(Cons_messagePeerVoteMultiple(peer: _1!, options: _2!, date: _3!)) + } + else { + return nil + } } - } } public extension Api { enum MessageRange: TypeConstructorDescription { - case messageRange(minId: Int32, maxId: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messageRange(let minId, let maxId): - if boxed { - buffer.appendInt32(182649427) - } - serializeInt32(minId, buffer: buffer, boxed: false) - serializeInt32(maxId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messageRange(let minId, let maxId): - return ("messageRange", [("minId", minId as Any), ("maxId", maxId as Any)]) - } - } - + public class Cons_messageRange { + public var minId: Int32 + public var maxId: Int32 + public init(minId: Int32, maxId: Int32) { + self.minId = minId + self.maxId = maxId + } + } + case messageRange(Cons_messageRange) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messageRange(let _data): + if boxed { + buffer.appendInt32(182649427) + } + serializeInt32(_data.minId, buffer: buffer, boxed: false) + serializeInt32(_data.maxId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messageRange(let _data): + return ("messageRange", [("minId", _data.minId as Any), ("maxId", _data.maxId as Any)]) + } + } + public static func parse_messageRange(_ reader: BufferReader) -> MessageRange? { var _1: Int32? _1 = reader.readInt32() @@ -180,50 +234,68 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageRange.messageRange(minId: _1!, maxId: _2!) + if _c1 && _c2 { + return Api.MessageRange.messageRange(Cons_messageRange(minId: _1!, maxId: _2!)) + } + else { + return nil + } } - } } public extension Api { enum MessageReactions: TypeConstructorDescription { - case messageReactions(flags: Int32, results: [Api.ReactionCount], recentReactions: [Api.MessagePeerReaction]?, topReactors: [Api.MessageReactor]?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messageReactions(let flags, let results, let recentReactions, let topReactors): - if boxed { - buffer.appendInt32(171155211) - } - serializeInt32(flags, buffer: buffer, boxed: false) + public class Cons_messageReactions { + public var flags: Int32 + public var results: [Api.ReactionCount] + public var recentReactions: [Api.MessagePeerReaction]? + public var topReactors: [Api.MessageReactor]? + public init(flags: Int32, results: [Api.ReactionCount], recentReactions: [Api.MessagePeerReaction]?, topReactors: [Api.MessageReactor]?) { + self.flags = flags + self.results = results + self.recentReactions = recentReactions + self.topReactors = topReactors + } + } + case messageReactions(Cons_messageReactions) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messageReactions(let _data): + if boxed { + buffer.appendInt32(171155211) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.results.count)) + for item in _data.results { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(results.count)) - for item in results { + buffer.appendInt32(Int32(_data.recentReactions!.count)) + for item in _data.recentReactions! { item.serialize(buffer, true) } - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(recentReactions!.count)) - for item in recentReactions! { + } + if Int(_data.flags) & Int(1 << 4) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.topReactors!.count)) + for item in _data.topReactors! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 4) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(topReactors!.count)) - for item in topReactors! { - item.serialize(buffer, true) - }} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messageReactions(let flags, let results, let recentReactions, let topReactors): - return ("messageReactions", [("flags", flags as Any), ("results", results as Any), ("recentReactions", recentReactions as Any), ("topReactors", topReactors as Any)]) - } - } - + } + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messageReactions(let _data): + return ("messageReactions", [("flags", _data.flags as Any), ("results", _data.results as Any), ("recentReactions", _data.recentReactions as Any), ("topReactors", _data.topReactors as Any)]) + } + } + public static func parse_messageReactions(_ reader: BufferReader) -> MessageReactions? { var _1: Int32? _1 = reader.readInt32() @@ -232,102 +304,147 @@ public extension Api { _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ReactionCount.self) } var _3: [Api.MessagePeerReaction]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessagePeerReaction.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessagePeerReaction.self) + } + } var _4: [Api.MessageReactor]? - if Int(_1!) & Int(1 << 4) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageReactor.self) - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageReactor.self) + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 4) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.MessageReactions.messageReactions(flags: _1!, results: _2!, recentReactions: _3, topReactors: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.MessageReactions.messageReactions(Cons_messageReactions(flags: _1!, results: _2!, recentReactions: _3, topReactors: _4)) + } + else { + return nil + } } - } } public extension Api { enum MessageReactor: TypeConstructorDescription { - case messageReactor(flags: Int32, peerId: Api.Peer?, count: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messageReactor(let flags, let peerId, let count): - if boxed { - buffer.appendInt32(1269016922) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {peerId!.serialize(buffer, true)} - serializeInt32(count, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messageReactor(let flags, let peerId, let count): - return ("messageReactor", [("flags", flags as Any), ("peerId", peerId as Any), ("count", count as Any)]) - } - } - + public class Cons_messageReactor { + public var flags: Int32 + public var peerId: Api.Peer? + public var count: Int32 + public init(flags: Int32, peerId: Api.Peer?, count: Int32) { + self.flags = flags + self.peerId = peerId + self.count = count + } + } + case messageReactor(Cons_messageReactor) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messageReactor(let _data): + if boxed { + buffer.appendInt32(1269016922) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.peerId!.serialize(buffer, true) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messageReactor(let _data): + return ("messageReactor", [("flags", _data.flags as Any), ("peerId", _data.peerId as Any), ("count", _data.count as Any)]) + } + } + public static func parse_messageReactor(_ reader: BufferReader) -> MessageReactor? { var _1: Int32? _1 = reader.readInt32() var _2: Api.Peer? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _3: Int32? _3 = reader.readInt32() let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 3) == 0) || _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.MessageReactor.messageReactor(flags: _1!, peerId: _2, count: _3!) + if _c1 && _c2 && _c3 { + return Api.MessageReactor.messageReactor(Cons_messageReactor(flags: _1!, peerId: _2, count: _3!)) + } + else { + return nil + } } - } } public extension Api { enum MessageReplies: TypeConstructorDescription { - case messageReplies(flags: Int32, replies: Int32, repliesPts: Int32, recentRepliers: [Api.Peer]?, channelId: Int64?, maxId: Int32?, readMaxId: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messageReplies(let flags, let replies, let repliesPts, let recentRepliers, let channelId, let maxId, let readMaxId): - if boxed { - buffer.appendInt32(-2083123262) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(replies, buffer: buffer, boxed: false) - serializeInt32(repliesPts, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(recentRepliers!.count)) - for item in recentRepliers! { + public class Cons_messageReplies { + public var flags: Int32 + public var replies: Int32 + public var repliesPts: Int32 + public var recentRepliers: [Api.Peer]? + public var channelId: Int64? + public var maxId: Int32? + public var readMaxId: Int32? + public init(flags: Int32, replies: Int32, repliesPts: Int32, recentRepliers: [Api.Peer]?, channelId: Int64?, maxId: Int32?, readMaxId: Int32?) { + self.flags = flags + self.replies = replies + self.repliesPts = repliesPts + self.recentRepliers = recentRepliers + self.channelId = channelId + self.maxId = maxId + self.readMaxId = readMaxId + } + } + case messageReplies(Cons_messageReplies) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messageReplies(let _data): + if boxed { + buffer.appendInt32(-2083123262) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.replies, buffer: buffer, boxed: false) + serializeInt32(_data.repliesPts, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.recentRepliers!.count)) + for item in _data.recentRepliers! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(channelId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(maxId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(readMaxId!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messageReplies(let flags, let replies, let repliesPts, let recentRepliers, let channelId, let maxId, let readMaxId): - return ("messageReplies", [("flags", flags as Any), ("replies", replies as Any), ("repliesPts", repliesPts as Any), ("recentRepliers", recentRepliers as Any), ("channelId", channelId as Any), ("maxId", maxId as Any), ("readMaxId", readMaxId as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.channelId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.maxId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.readMaxId!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messageReplies(let _data): + return ("messageReplies", [("flags", _data.flags as Any), ("replies", _data.replies as Any), ("repliesPts", _data.repliesPts as Any), ("recentRepliers", _data.recentRepliers as Any), ("channelId", _data.channelId as Any), ("maxId", _data.maxId as Any), ("readMaxId", _data.readMaxId as Any)]) + } + } + public static func parse_messageReplies(_ reader: BufferReader) -> MessageReplies? { var _1: Int32? _1 = reader.readInt32() @@ -336,15 +453,23 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: [Api.Peer]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) + } + } var _5: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_5 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _5 = reader.readInt64() + } var _6: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _6 = reader.readInt32() + } var _7: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_7 = reader.readInt32() } + if Int(_1!) & Int(1 << 3) != 0 { + _7 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -352,92 +477,157 @@ public extension Api { let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil let _c7 = (Int(_1!) & Int(1 << 3) == 0) || _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.MessageReplies.messageReplies(flags: _1!, replies: _2!, repliesPts: _3!, recentRepliers: _4, channelId: _5, maxId: _6, readMaxId: _7) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.MessageReplies.messageReplies(Cons_messageReplies(flags: _1!, replies: _2!, repliesPts: _3!, recentRepliers: _4, channelId: _5, maxId: _6, readMaxId: _7)) + } + else { + return nil + } } - } } public extension Api { indirect enum MessageReplyHeader: TypeConstructorDescription { - case messageReplyHeader(flags: Int32, replyToMsgId: Int32?, replyToPeerId: Api.Peer?, replyFrom: Api.MessageFwdHeader?, replyMedia: Api.MessageMedia?, replyToTopId: Int32?, quoteText: String?, quoteEntities: [Api.MessageEntity]?, quoteOffset: Int32?, todoItemId: Int32?) - case messageReplyStoryHeader(peer: Api.Peer, storyId: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messageReplyHeader(let flags, let replyToMsgId, let replyToPeerId, let replyFrom, let replyMedia, let replyToTopId, let quoteText, let quoteEntities, let quoteOffset, let todoItemId): - if boxed { - buffer.appendInt32(1763137035) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(replyToMsgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {replyToPeerId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 5) != 0 {replyFrom!.serialize(buffer, true)} - if Int(flags) & Int(1 << 8) != 0 {replyMedia!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(replyToTopId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 6) != 0 {serializeString(quoteText!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 7) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(quoteEntities!.count)) - for item in quoteEntities! { + public class Cons_messageReplyHeader { + public var flags: Int32 + public var replyToMsgId: Int32? + public var replyToPeerId: Api.Peer? + public var replyFrom: Api.MessageFwdHeader? + public var replyMedia: Api.MessageMedia? + public var replyToTopId: Int32? + public var quoteText: String? + public var quoteEntities: [Api.MessageEntity]? + public var quoteOffset: Int32? + public var todoItemId: Int32? + public init(flags: Int32, replyToMsgId: Int32?, replyToPeerId: Api.Peer?, replyFrom: Api.MessageFwdHeader?, replyMedia: Api.MessageMedia?, replyToTopId: Int32?, quoteText: String?, quoteEntities: [Api.MessageEntity]?, quoteOffset: Int32?, todoItemId: Int32?) { + self.flags = flags + self.replyToMsgId = replyToMsgId + self.replyToPeerId = replyToPeerId + self.replyFrom = replyFrom + self.replyMedia = replyMedia + self.replyToTopId = replyToTopId + self.quoteText = quoteText + self.quoteEntities = quoteEntities + self.quoteOffset = quoteOffset + self.todoItemId = todoItemId + } + } + public class Cons_messageReplyStoryHeader { + public var peer: Api.Peer + public var storyId: Int32 + public init(peer: Api.Peer, storyId: Int32) { + self.peer = peer + self.storyId = storyId + } + } + case messageReplyHeader(Cons_messageReplyHeader) + case messageReplyStoryHeader(Cons_messageReplyStoryHeader) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messageReplyHeader(let _data): + if boxed { + buffer.appendInt32(1763137035) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.replyToMsgId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.replyToPeerId!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + _data.replyFrom!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + _data.replyMedia!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.replyToTopId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + serializeString(_data.quoteText!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 7) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.quoteEntities!.count)) + for item in _data.quoteEntities! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 10) != 0 {serializeInt32(quoteOffset!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 11) != 0 {serializeInt32(todoItemId!, buffer: buffer, boxed: false)} - break - case .messageReplyStoryHeader(let peer, let storyId): - if boxed { - buffer.appendInt32(240843065) } - peer.serialize(buffer, true) - serializeInt32(storyId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messageReplyHeader(let flags, let replyToMsgId, let replyToPeerId, let replyFrom, let replyMedia, let replyToTopId, let quoteText, let quoteEntities, let quoteOffset, let todoItemId): - return ("messageReplyHeader", [("flags", flags as Any), ("replyToMsgId", replyToMsgId as Any), ("replyToPeerId", replyToPeerId as Any), ("replyFrom", replyFrom as Any), ("replyMedia", replyMedia as Any), ("replyToTopId", replyToTopId as Any), ("quoteText", quoteText as Any), ("quoteEntities", quoteEntities as Any), ("quoteOffset", quoteOffset as Any), ("todoItemId", todoItemId as Any)]) - case .messageReplyStoryHeader(let peer, let storyId): - return ("messageReplyStoryHeader", [("peer", peer as Any), ("storyId", storyId as Any)]) - } - } - + } + if Int(_data.flags) & Int(1 << 10) != 0 { + serializeInt32(_data.quoteOffset!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 11) != 0 { + serializeInt32(_data.todoItemId!, buffer: buffer, boxed: false) + } + break + case .messageReplyStoryHeader(let _data): + if boxed { + buffer.appendInt32(240843065) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.storyId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messageReplyHeader(let _data): + return ("messageReplyHeader", [("flags", _data.flags as Any), ("replyToMsgId", _data.replyToMsgId as Any), ("replyToPeerId", _data.replyToPeerId as Any), ("replyFrom", _data.replyFrom as Any), ("replyMedia", _data.replyMedia as Any), ("replyToTopId", _data.replyToTopId as Any), ("quoteText", _data.quoteText as Any), ("quoteEntities", _data.quoteEntities as Any), ("quoteOffset", _data.quoteOffset as Any), ("todoItemId", _data.todoItemId as Any)]) + case .messageReplyStoryHeader(let _data): + return ("messageReplyStoryHeader", [("peer", _data.peer as Any), ("storyId", _data.storyId as Any)]) + } + } + public static func parse_messageReplyHeader(_ reader: BufferReader) -> MessageReplyHeader? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_2 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _2 = reader.readInt32() + } var _3: Api.Peer? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _4: Api.MessageFwdHeader? - if Int(_1!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.MessageFwdHeader - } } + if Int(_1!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.MessageFwdHeader + } + } var _5: Api.MessageMedia? - if Int(_1!) & Int(1 << 8) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.MessageMedia - } } + if Int(_1!) & Int(1 << 8) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.MessageMedia + } + } var _6: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _6 = reader.readInt32() + } var _7: String? - if Int(_1!) & Int(1 << 6) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 6) != 0 { + _7 = parseString(reader) + } var _8: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 7) != 0 {if let _ = reader.readInt32() { - _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 7) != 0 { + if let _ = reader.readInt32() { + _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } var _9: Int32? - if Int(_1!) & Int(1 << 10) != 0 {_9 = reader.readInt32() } + if Int(_1!) & Int(1 << 10) != 0 { + _9 = reader.readInt32() + } var _10: Int32? - if Int(_1!) & Int(1 << 11) != 0 {_10 = reader.readInt32() } + if Int(_1!) & Int(1 << 11) != 0 { + _10 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 4) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil @@ -448,17 +638,12 @@ public extension Api { let _c8 = (Int(_1!) & Int(1 << 7) == 0) || _8 != nil let _c9 = (Int(_1!) & Int(1 << 10) == 0) || _9 != nil let _c10 = (Int(_1!) & Int(1 << 11) == 0) || _10 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - return Api.MessageReplyHeader.messageReplyHeader(flags: _1!, replyToMsgId: _2, replyToPeerId: _3, replyFrom: _4, replyMedia: _5, replyToTopId: _6, quoteText: _7, quoteEntities: _8, quoteOffset: _9, todoItemId: _10) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 { + return Api.MessageReplyHeader.messageReplyHeader(Cons_messageReplyHeader(flags: _1!, replyToMsgId: _2, replyToPeerId: _3, replyFrom: _4, replyMedia: _5, replyToTopId: _6, quoteText: _7, quoteEntities: _8, quoteOffset: _9, todoItemId: _10)) + } + else { + return nil + } } public static func parse_messageReplyStoryHeader(_ reader: BufferReader) -> MessageReplyHeader? { var _1: Api.Peer? @@ -469,36 +654,46 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageReplyHeader.messageReplyStoryHeader(peer: _1!, storyId: _2!) + if _c1 && _c2 { + return Api.MessageReplyHeader.messageReplyStoryHeader(Cons_messageReplyStoryHeader(peer: _1!, storyId: _2!)) + } + else { + return nil + } } - } } public extension Api { enum MessageReportOption: TypeConstructorDescription { - case messageReportOption(text: String, option: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messageReportOption(let text, let option): - if boxed { - buffer.appendInt32(2030298073) - } - serializeString(text, buffer: buffer, boxed: false) - serializeBytes(option, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messageReportOption(let text, let option): - return ("messageReportOption", [("text", text as Any), ("option", option as Any)]) - } - } - + public class Cons_messageReportOption { + public var text: String + public var option: Buffer + public init(text: String, option: Buffer) { + self.text = text + self.option = option + } + } + case messageReportOption(Cons_messageReportOption) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messageReportOption(let _data): + if boxed { + buffer.appendInt32(2030298073) + } + serializeString(_data.text, buffer: buffer, boxed: false) + serializeBytes(_data.option, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messageReportOption(let _data): + return ("messageReportOption", [("text", _data.text as Any), ("option", _data.option as Any)]) + } + } + public static func parse_messageReportOption(_ reader: BufferReader) -> MessageReportOption? { var _1: String? _1 = parseString(reader) @@ -506,64 +701,96 @@ public extension Api { _2 = parseBytes(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MessageReportOption.messageReportOption(text: _1!, option: _2!) + if _c1 && _c2 { + return Api.MessageReportOption.messageReportOption(Cons_messageReportOption(text: _1!, option: _2!)) + } + else { + return nil + } } - } } public extension Api { enum MessageViews: TypeConstructorDescription { - case messageViews(flags: Int32, views: Int32?, forwards: Int32?, replies: Api.MessageReplies?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messageViews(let flags, let views, let forwards, let replies): - if boxed { - buffer.appendInt32(1163625789) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(views!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(forwards!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {replies!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messageViews(let flags, let views, let forwards, let replies): - return ("messageViews", [("flags", flags as Any), ("views", views as Any), ("forwards", forwards as Any), ("replies", replies as Any)]) - } - } - + public class Cons_messageViews { + public var flags: Int32 + public var views: Int32? + public var forwards: Int32? + public var replies: Api.MessageReplies? + public init(flags: Int32, views: Int32?, forwards: Int32?, replies: Api.MessageReplies?) { + self.flags = flags + self.views = views + self.forwards = forwards + self.replies = replies + } + } + case messageViews(Cons_messageViews) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messageViews(let _data): + if boxed { + buffer.appendInt32(1163625789) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.views!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.forwards!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replies!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messageViews(let _data): + return ("messageViews", [("flags", _data.flags as Any), ("views", _data.views as Any), ("forwards", _data.forwards as Any), ("replies", _data.replies as Any)]) + } + } + public static func parse_messageViews(_ reader: BufferReader) -> MessageViews? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt32() + } var _3: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _3 = reader.readInt32() + } var _4: Api.MessageReplies? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.MessageReplies - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.MessageReplies + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.MessageViews.messageViews(flags: _1!, views: _2, forwards: _3, replies: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.MessageViews.messageViews(Cons_messageViews(flags: _1!, views: _2, forwards: _3, replies: _4)) + } + else { + return nil + } } - } } public extension Api { enum MessagesFilter: TypeConstructorDescription { + public class Cons_inputMessagesFilterPhoneCalls { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } case inputMessagesFilterChatPhotos case inputMessagesFilterContacts case inputMessagesFilterDocument @@ -572,7 +799,7 @@ public extension Api { case inputMessagesFilterGif case inputMessagesFilterMusic case inputMessagesFilterMyMentions - case inputMessagesFilterPhoneCalls(flags: Int32) + case inputMessagesFilterPhoneCalls(Cons_inputMessagesFilterPhoneCalls) case inputMessagesFilterPhotoVideo case inputMessagesFilterPhotos case inputMessagesFilterPinned @@ -581,153 +808,137 @@ public extension Api { case inputMessagesFilterUrl case inputMessagesFilterVideo case inputMessagesFilterVoice - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputMessagesFilterChatPhotos: - if boxed { - buffer.appendInt32(975236280) - } - - break - case .inputMessagesFilterContacts: - if boxed { - buffer.appendInt32(-530392189) - } - - break - case .inputMessagesFilterDocument: - if boxed { - buffer.appendInt32(-1629621880) - } - - break - case .inputMessagesFilterEmpty: - if boxed { - buffer.appendInt32(1474492012) - } - - break - case .inputMessagesFilterGeo: - if boxed { - buffer.appendInt32(-419271411) - } - - break - case .inputMessagesFilterGif: - if boxed { - buffer.appendInt32(-3644025) - } - - break - case .inputMessagesFilterMusic: - if boxed { - buffer.appendInt32(928101534) - } - - break - case .inputMessagesFilterMyMentions: - if boxed { - buffer.appendInt32(-1040652646) - } - - break - case .inputMessagesFilterPhoneCalls(let flags): - if boxed { - buffer.appendInt32(-2134272152) - } - serializeInt32(flags, buffer: buffer, boxed: false) - break - case .inputMessagesFilterPhotoVideo: - if boxed { - buffer.appendInt32(1458172132) - } - - break - case .inputMessagesFilterPhotos: - if boxed { - buffer.appendInt32(-1777752804) - } - - break - case .inputMessagesFilterPinned: - if boxed { - buffer.appendInt32(464520273) - } - - break - case .inputMessagesFilterRoundVideo: - if boxed { - buffer.appendInt32(-1253451181) - } - - break - case .inputMessagesFilterRoundVoice: - if boxed { - buffer.appendInt32(2054952868) - } - - break - case .inputMessagesFilterUrl: - if boxed { - buffer.appendInt32(2129714567) - } - - break - case .inputMessagesFilterVideo: - if boxed { - buffer.appendInt32(-1614803355) - } - - break - case .inputMessagesFilterVoice: - if boxed { - buffer.appendInt32(1358283666) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputMessagesFilterChatPhotos: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputMessagesFilterChatPhotos: + if boxed { + buffer.appendInt32(975236280) + } + break + case .inputMessagesFilterContacts: + if boxed { + buffer.appendInt32(-530392189) + } + break + case .inputMessagesFilterDocument: + if boxed { + buffer.appendInt32(-1629621880) + } + break + case .inputMessagesFilterEmpty: + if boxed { + buffer.appendInt32(1474492012) + } + break + case .inputMessagesFilterGeo: + if boxed { + buffer.appendInt32(-419271411) + } + break + case .inputMessagesFilterGif: + if boxed { + buffer.appendInt32(-3644025) + } + break + case .inputMessagesFilterMusic: + if boxed { + buffer.appendInt32(928101534) + } + break + case .inputMessagesFilterMyMentions: + if boxed { + buffer.appendInt32(-1040652646) + } + break + case .inputMessagesFilterPhoneCalls(let _data): + if boxed { + buffer.appendInt32(-2134272152) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + case .inputMessagesFilterPhotoVideo: + if boxed { + buffer.appendInt32(1458172132) + } + break + case .inputMessagesFilterPhotos: + if boxed { + buffer.appendInt32(-1777752804) + } + break + case .inputMessagesFilterPinned: + if boxed { + buffer.appendInt32(464520273) + } + break + case .inputMessagesFilterRoundVideo: + if boxed { + buffer.appendInt32(-1253451181) + } + break + case .inputMessagesFilterRoundVoice: + if boxed { + buffer.appendInt32(2054952868) + } + break + case .inputMessagesFilterUrl: + if boxed { + buffer.appendInt32(2129714567) + } + break + case .inputMessagesFilterVideo: + if boxed { + buffer.appendInt32(-1614803355) + } + break + case .inputMessagesFilterVoice: + if boxed { + buffer.appendInt32(1358283666) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputMessagesFilterChatPhotos: return ("inputMessagesFilterChatPhotos", []) - case .inputMessagesFilterContacts: + case .inputMessagesFilterContacts: return ("inputMessagesFilterContacts", []) - case .inputMessagesFilterDocument: + case .inputMessagesFilterDocument: return ("inputMessagesFilterDocument", []) - case .inputMessagesFilterEmpty: + case .inputMessagesFilterEmpty: return ("inputMessagesFilterEmpty", []) - case .inputMessagesFilterGeo: + case .inputMessagesFilterGeo: return ("inputMessagesFilterGeo", []) - case .inputMessagesFilterGif: + case .inputMessagesFilterGif: return ("inputMessagesFilterGif", []) - case .inputMessagesFilterMusic: + case .inputMessagesFilterMusic: return ("inputMessagesFilterMusic", []) - case .inputMessagesFilterMyMentions: + case .inputMessagesFilterMyMentions: return ("inputMessagesFilterMyMentions", []) - case .inputMessagesFilterPhoneCalls(let flags): - return ("inputMessagesFilterPhoneCalls", [("flags", flags as Any)]) - case .inputMessagesFilterPhotoVideo: + case .inputMessagesFilterPhoneCalls(let _data): + return ("inputMessagesFilterPhoneCalls", [("flags", _data.flags as Any)]) + case .inputMessagesFilterPhotoVideo: return ("inputMessagesFilterPhotoVideo", []) - case .inputMessagesFilterPhotos: + case .inputMessagesFilterPhotos: return ("inputMessagesFilterPhotos", []) - case .inputMessagesFilterPinned: + case .inputMessagesFilterPinned: return ("inputMessagesFilterPinned", []) - case .inputMessagesFilterRoundVideo: + case .inputMessagesFilterRoundVideo: return ("inputMessagesFilterRoundVideo", []) - case .inputMessagesFilterRoundVoice: + case .inputMessagesFilterRoundVoice: return ("inputMessagesFilterRoundVoice", []) - case .inputMessagesFilterUrl: + case .inputMessagesFilterUrl: return ("inputMessagesFilterUrl", []) - case .inputMessagesFilterVideo: + case .inputMessagesFilterVideo: return ("inputMessagesFilterVideo", []) - case .inputMessagesFilterVoice: + case .inputMessagesFilterVoice: return ("inputMessagesFilterVoice", []) - } - } - + } + } + public static func parse_inputMessagesFilterChatPhotos(_ reader: BufferReader) -> MessagesFilter? { return Api.MessagesFilter.inputMessagesFilterChatPhotos } @@ -756,8 +967,12 @@ public extension Api { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.MessagesFilter.inputMessagesFilterPhoneCalls(flags: _1!) + if _c1 { + return Api.MessagesFilter.inputMessagesFilterPhoneCalls(Cons_inputMessagesFilterPhoneCalls(flags: _1!)) + } + else { + return nil + } } public static func parse_inputMessagesFilterPhotoVideo(_ reader: BufferReader) -> MessagesFilter? { return Api.MessagesFilter.inputMessagesFilterPhotoVideo @@ -783,32 +998,39 @@ public extension Api { public static func parse_inputMessagesFilterVoice(_ reader: BufferReader) -> MessagesFilter? { return Api.MessagesFilter.inputMessagesFilterVoice } - } } public extension Api { enum MissingInvitee: TypeConstructorDescription { - case missingInvitee(flags: Int32, userId: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .missingInvitee(let flags, let userId): - if boxed { - buffer.appendInt32(1653379620) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .missingInvitee(let flags, let userId): - return ("missingInvitee", [("flags", flags as Any), ("userId", userId as Any)]) - } - } - + public class Cons_missingInvitee { + public var flags: Int32 + public var userId: Int64 + public init(flags: Int32, userId: Int64) { + self.flags = flags + self.userId = userId + } + } + case missingInvitee(Cons_missingInvitee) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .missingInvitee(let _data): + if boxed { + buffer.appendInt32(1653379620) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .missingInvitee(let _data): + return ("missingInvitee", [("flags", _data.flags as Any), ("userId", _data.userId as Any)]) + } + } + public static func parse_missingInvitee(_ reader: BufferReader) -> MissingInvitee? { var _1: Int32? _1 = reader.readInt32() @@ -816,96 +1038,130 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.MissingInvitee.missingInvitee(flags: _1!, userId: _2!) + if _c1 && _c2 { + return Api.MissingInvitee.missingInvitee(Cons_missingInvitee(flags: _1!, userId: _2!)) + } + else { + return nil + } } - } } public extension Api { enum MyBoost: TypeConstructorDescription { - case myBoost(flags: Int32, slot: Int32, peer: Api.Peer?, date: Int32, expires: Int32, cooldownUntilDate: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .myBoost(let flags, let slot, let peer, let date, let expires, let cooldownUntilDate): - if boxed { - buffer.appendInt32(-1001897636) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(slot, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {peer!.serialize(buffer, true)} - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt32(expires, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(cooldownUntilDate!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .myBoost(let flags, let slot, let peer, let date, let expires, let cooldownUntilDate): - return ("myBoost", [("flags", flags as Any), ("slot", slot as Any), ("peer", peer as Any), ("date", date as Any), ("expires", expires as Any), ("cooldownUntilDate", cooldownUntilDate as Any)]) - } - } - + public class Cons_myBoost { + public var flags: Int32 + public var slot: Int32 + public var peer: Api.Peer? + public var date: Int32 + public var expires: Int32 + public var cooldownUntilDate: Int32? + public init(flags: Int32, slot: Int32, peer: Api.Peer?, date: Int32, expires: Int32, cooldownUntilDate: Int32?) { + self.flags = flags + self.slot = slot + self.peer = peer + self.date = date + self.expires = expires + self.cooldownUntilDate = cooldownUntilDate + } + } + case myBoost(Cons_myBoost) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .myBoost(let _data): + if boxed { + buffer.appendInt32(-1001897636) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.slot, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.peer!.serialize(buffer, true) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt32(_data.expires, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.cooldownUntilDate!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .myBoost(let _data): + return ("myBoost", [("flags", _data.flags as Any), ("slot", _data.slot as Any), ("peer", _data.peer as Any), ("date", _data.date as Any), ("expires", _data.expires as Any), ("cooldownUntilDate", _data.cooldownUntilDate as Any)]) + } + } + public static func parse_myBoost(_ reader: BufferReader) -> MyBoost? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? _2 = reader.readInt32() var _3: Api.Peer? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _4: Int32? _4 = reader.readInt32() var _5: Int32? _5 = reader.readInt32() var _6: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _6 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.MyBoost.myBoost(flags: _1!, slot: _2!, peer: _3, date: _4!, expires: _5!, cooldownUntilDate: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.MyBoost.myBoost(Cons_myBoost(flags: _1!, slot: _2!, peer: _3, date: _4!, expires: _5!, cooldownUntilDate: _6)) + } + else { + return nil + } } - } } public extension Api { enum NearestDc: TypeConstructorDescription { - case nearestDc(country: String, thisDc: Int32, nearestDc: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .nearestDc(let country, let thisDc, let nearestDc): - if boxed { - buffer.appendInt32(-1910892683) - } - serializeString(country, buffer: buffer, boxed: false) - serializeInt32(thisDc, buffer: buffer, boxed: false) - serializeInt32(nearestDc, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .nearestDc(let country, let thisDc, let nearestDc): - return ("nearestDc", [("country", country as Any), ("thisDc", thisDc as Any), ("nearestDc", nearestDc as Any)]) - } - } - + public class Cons_nearestDc { + public var country: String + public var thisDc: Int32 + public var nearestDc: Int32 + public init(country: String, thisDc: Int32, nearestDc: Int32) { + self.country = country + self.thisDc = thisDc + self.nearestDc = nearestDc + } + } + case nearestDc(Cons_nearestDc) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .nearestDc(let _data): + if boxed { + buffer.appendInt32(-1910892683) + } + serializeString(_data.country, buffer: buffer, boxed: false) + serializeInt32(_data.thisDc, buffer: buffer, boxed: false) + serializeInt32(_data.nearestDc, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .nearestDc(let _data): + return ("nearestDc", [("country", _data.country as Any), ("thisDc", _data.thisDc as Any), ("nearestDc", _data.nearestDc as Any)]) + } + } + public static func parse_nearestDc(_ reader: BufferReader) -> NearestDc? { var _1: String? _1 = parseString(reader) @@ -916,11 +1172,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.NearestDc.nearestDc(country: _1!, thisDc: _2!, nearestDc: _3!) + if _c1 && _c2 && _c3 { + return Api.NearestDc.nearestDc(Cons_nearestDc(country: _1!, thisDc: _2!, nearestDc: _3!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api18.swift b/submodules/TelegramApi/Sources/Api18.swift index f14c2c27..5cd98a21 100644 --- a/submodules/TelegramApi/Sources/Api18.swift +++ b/submodules/TelegramApi/Sources/Api18.swift @@ -1,53 +1,65 @@ public extension Api { enum NotificationSound: TypeConstructorDescription { + public class Cons_notificationSoundLocal { + public var title: String + public var data: String + public init(title: String, data: String) { + self.title = title + self.data = data + } + } + public class Cons_notificationSoundRingtone { + public var id: Int64 + public init(id: Int64) { + self.id = id + } + } case notificationSoundDefault - case notificationSoundLocal(title: String, data: String) + case notificationSoundLocal(Cons_notificationSoundLocal) case notificationSoundNone - case notificationSoundRingtone(id: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .notificationSoundDefault: - if boxed { - buffer.appendInt32(-1746354498) - } - - break - case .notificationSoundLocal(let title, let data): - if boxed { - buffer.appendInt32(-2096391452) - } - serializeString(title, buffer: buffer, boxed: false) - serializeString(data, buffer: buffer, boxed: false) - break - case .notificationSoundNone: - if boxed { - buffer.appendInt32(1863070943) - } - - break - case .notificationSoundRingtone(let id): - if boxed { - buffer.appendInt32(-9666487) - } - serializeInt64(id, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .notificationSoundDefault: + case notificationSoundRingtone(Cons_notificationSoundRingtone) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .notificationSoundDefault: + if boxed { + buffer.appendInt32(-1746354498) + } + break + case .notificationSoundLocal(let _data): + if boxed { + buffer.appendInt32(-2096391452) + } + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.data, buffer: buffer, boxed: false) + break + case .notificationSoundNone: + if boxed { + buffer.appendInt32(1863070943) + } + break + case .notificationSoundRingtone(let _data): + if boxed { + buffer.appendInt32(-9666487) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .notificationSoundDefault: return ("notificationSoundDefault", []) - case .notificationSoundLocal(let title, let data): - return ("notificationSoundLocal", [("title", title as Any), ("data", data as Any)]) - case .notificationSoundNone: + case .notificationSoundLocal(let _data): + return ("notificationSoundLocal", [("title", _data.title as Any), ("data", _data.data as Any)]) + case .notificationSoundNone: return ("notificationSoundNone", []) - case .notificationSoundRingtone(let id): - return ("notificationSoundRingtone", [("id", id as Any)]) - } - } - + case .notificationSoundRingtone(let _data): + return ("notificationSoundRingtone", [("id", _data.id as Any)]) + } + } + public static func parse_notificationSoundDefault(_ reader: BufferReader) -> NotificationSound? { return Api.NotificationSound.notificationSoundDefault } @@ -58,9 +70,12 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.NotificationSound.notificationSoundLocal(title: _1!, data: _2!) + if _c1 && _c2 { + return Api.NotificationSound.notificationSoundLocal(Cons_notificationSoundLocal(title: _1!, data: _2!)) + } + else { + return nil + } } public static func parse_notificationSoundNone(_ reader: BufferReader) -> NotificationSound? { return Api.NotificationSound.notificationSoundNone @@ -69,71 +84,85 @@ public extension Api { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.NotificationSound.notificationSoundRingtone(id: _1!) + if _c1 { + return Api.NotificationSound.notificationSoundRingtone(Cons_notificationSoundRingtone(id: _1!)) + } + else { + return nil + } } - } } public extension Api { enum NotifyPeer: TypeConstructorDescription { + public class Cons_notifyForumTopic { + public var peer: Api.Peer + public var topMsgId: Int32 + public init(peer: Api.Peer, topMsgId: Int32) { + self.peer = peer + self.topMsgId = topMsgId + } + } + public class Cons_notifyPeer { + public var peer: Api.Peer + public init(peer: Api.Peer) { + self.peer = peer + } + } case notifyBroadcasts case notifyChats - case notifyForumTopic(peer: Api.Peer, topMsgId: Int32) - case notifyPeer(peer: Api.Peer) + case notifyForumTopic(Cons_notifyForumTopic) + case notifyPeer(Cons_notifyPeer) case notifyUsers - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .notifyBroadcasts: - if boxed { - buffer.appendInt32(-703403793) - } - - break - case .notifyChats: - if boxed { - buffer.appendInt32(-1073230141) - } - - break - case .notifyForumTopic(let peer, let topMsgId): - if boxed { - buffer.appendInt32(577659656) - } - peer.serialize(buffer, true) - serializeInt32(topMsgId, buffer: buffer, boxed: false) - break - case .notifyPeer(let peer): - if boxed { - buffer.appendInt32(-1613493288) - } - peer.serialize(buffer, true) - break - case .notifyUsers: - if boxed { - buffer.appendInt32(-1261946036) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .notifyBroadcasts: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .notifyBroadcasts: + if boxed { + buffer.appendInt32(-703403793) + } + break + case .notifyChats: + if boxed { + buffer.appendInt32(-1073230141) + } + break + case .notifyForumTopic(let _data): + if boxed { + buffer.appendInt32(577659656) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.topMsgId, buffer: buffer, boxed: false) + break + case .notifyPeer(let _data): + if boxed { + buffer.appendInt32(-1613493288) + } + _data.peer.serialize(buffer, true) + break + case .notifyUsers: + if boxed { + buffer.appendInt32(-1261946036) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .notifyBroadcasts: return ("notifyBroadcasts", []) - case .notifyChats: + case .notifyChats: return ("notifyChats", []) - case .notifyForumTopic(let peer, let topMsgId): - return ("notifyForumTopic", [("peer", peer as Any), ("topMsgId", topMsgId as Any)]) - case .notifyPeer(let peer): - return ("notifyPeer", [("peer", peer as Any)]) - case .notifyUsers: + case .notifyForumTopic(let _data): + return ("notifyForumTopic", [("peer", _data.peer as Any), ("topMsgId", _data.topMsgId as Any)]) + case .notifyPeer(let _data): + return ("notifyPeer", [("peer", _data.peer as Any)]) + case .notifyUsers: return ("notifyUsers", []) - } - } - + } + } + public static func parse_notifyBroadcasts(_ reader: BufferReader) -> NotifyPeer? { return Api.NotifyPeer.notifyBroadcasts } @@ -149,9 +178,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.NotifyPeer.notifyForumTopic(peer: _1!, topMsgId: _2!) + if _c1 && _c2 { + return Api.NotifyPeer.notifyForumTopic(Cons_notifyForumTopic(peer: _1!, topMsgId: _2!)) + } + else { + return nil + } } public static func parse_notifyPeer(_ reader: BufferReader) -> NotifyPeer? { var _1: Api.Peer? @@ -159,86 +191,116 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Peer } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.NotifyPeer.notifyPeer(peer: _1!) + if _c1 { + return Api.NotifyPeer.notifyPeer(Cons_notifyPeer(peer: _1!)) + } + else { + return nil + } } public static func parse_notifyUsers(_ reader: BufferReader) -> NotifyPeer? { return Api.NotifyPeer.notifyUsers } - } } public extension Api { enum OutboxReadDate: TypeConstructorDescription { - case outboxReadDate(date: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .outboxReadDate(let date): - if boxed { - buffer.appendInt32(1001931436) - } - serializeInt32(date, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .outboxReadDate(let date): - return ("outboxReadDate", [("date", date as Any)]) - } - } - + public class Cons_outboxReadDate { + public var date: Int32 + public init(date: Int32) { + self.date = date + } + } + case outboxReadDate(Cons_outboxReadDate) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .outboxReadDate(let _data): + if boxed { + buffer.appendInt32(1001931436) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .outboxReadDate(let _data): + return ("outboxReadDate", [("date", _data.date as Any)]) + } + } + public static func parse_outboxReadDate(_ reader: BufferReader) -> OutboxReadDate? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.OutboxReadDate.outboxReadDate(date: _1!) + if _c1 { + return Api.OutboxReadDate.outboxReadDate(Cons_outboxReadDate(date: _1!)) + } + else { + return nil + } } - } } public extension Api { enum Page: TypeConstructorDescription { - case page(flags: Int32, url: String, blocks: [Api.PageBlock], photos: [Api.Photo], documents: [Api.Document], views: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .page(let flags, let url, let blocks, let photos, let documents, let views): - if boxed { - buffer.appendInt32(-1738178803) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(blocks.count)) - for item in blocks { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(photos.count)) - for item in photos { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(documents.count)) - for item in documents { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(views!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .page(let flags, let url, let blocks, let photos, let documents, let views): - return ("page", [("flags", flags as Any), ("url", url as Any), ("blocks", blocks as Any), ("photos", photos as Any), ("documents", documents as Any), ("views", views as Any)]) - } - } - + public class Cons_page { + public var flags: Int32 + public var url: String + public var blocks: [Api.PageBlock] + public var photos: [Api.Photo] + public var documents: [Api.Document] + public var views: Int32? + public init(flags: Int32, url: String, blocks: [Api.PageBlock], photos: [Api.Photo], documents: [Api.Document], views: Int32?) { + self.flags = flags + self.url = url + self.blocks = blocks + self.photos = photos + self.documents = documents + self.views = views + } + } + case page(Cons_page) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .page(let _data): + if boxed { + buffer.appendInt32(-1738178803) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.blocks.count)) + for item in _data.blocks { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.photos.count)) + for item in _data.photos { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.documents.count)) + for item in _data.documents { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.views!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .page(let _data): + return ("page", [("flags", _data.flags as Any), ("url", _data.url as Any), ("blocks", _data.blocks as Any), ("photos", _data.photos as Any), ("documents", _data.documents as Any), ("views", _data.views as Any)]) + } + } + public static func parse_page(_ reader: BufferReader) -> Page? { var _1: Int32? _1 = reader.readInt32() @@ -257,370 +319,616 @@ public extension Api { _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) } var _6: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 3) != 0 { + _6 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = (Int(_1!) & Int(1 << 3) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.Page.page(flags: _1!, url: _2!, blocks: _3!, photos: _4!, documents: _5!, views: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.Page.page(Cons_page(flags: _1!, url: _2!, blocks: _3!, photos: _4!, documents: _5!, views: _6)) + } + else { + return nil + } } - } } public extension Api { indirect enum PageBlock: TypeConstructorDescription { - case pageBlockAnchor(name: String) - case pageBlockAudio(audioId: Int64, caption: Api.PageCaption) - case pageBlockAuthorDate(author: Api.RichText, publishedDate: Int32) - case pageBlockBlockquote(text: Api.RichText, caption: Api.RichText) - case pageBlockChannel(channel: Api.Chat) - case pageBlockCollage(items: [Api.PageBlock], caption: Api.PageCaption) - case pageBlockCover(cover: Api.PageBlock) - case pageBlockDetails(flags: Int32, blocks: [Api.PageBlock], title: Api.RichText) + public class Cons_pageBlockAnchor { + public var name: String + public init(name: String) { + self.name = name + } + } + public class Cons_pageBlockAudio { + public var audioId: Int64 + public var caption: Api.PageCaption + public init(audioId: Int64, caption: Api.PageCaption) { + self.audioId = audioId + self.caption = caption + } + } + public class Cons_pageBlockAuthorDate { + public var author: Api.RichText + public var publishedDate: Int32 + public init(author: Api.RichText, publishedDate: Int32) { + self.author = author + self.publishedDate = publishedDate + } + } + public class Cons_pageBlockBlockquote { + public var text: Api.RichText + public var caption: Api.RichText + public init(text: Api.RichText, caption: Api.RichText) { + self.text = text + self.caption = caption + } + } + public class Cons_pageBlockChannel { + public var channel: Api.Chat + public init(channel: Api.Chat) { + self.channel = channel + } + } + public class Cons_pageBlockCollage { + public var items: [Api.PageBlock] + public var caption: Api.PageCaption + public init(items: [Api.PageBlock], caption: Api.PageCaption) { + self.items = items + self.caption = caption + } + } + public class Cons_pageBlockCover { + public var cover: Api.PageBlock + public init(cover: Api.PageBlock) { + self.cover = cover + } + } + public class Cons_pageBlockDetails { + public var flags: Int32 + public var blocks: [Api.PageBlock] + public var title: Api.RichText + public init(flags: Int32, blocks: [Api.PageBlock], title: Api.RichText) { + self.flags = flags + self.blocks = blocks + self.title = title + } + } + public class Cons_pageBlockEmbed { + public var flags: Int32 + public var url: String? + public var html: String? + public var posterPhotoId: Int64? + public var w: Int32? + public var h: Int32? + public var caption: Api.PageCaption + public init(flags: Int32, url: String?, html: String?, posterPhotoId: Int64?, w: Int32?, h: Int32?, caption: Api.PageCaption) { + self.flags = flags + self.url = url + self.html = html + self.posterPhotoId = posterPhotoId + self.w = w + self.h = h + self.caption = caption + } + } + public class Cons_pageBlockEmbedPost { + public var url: String + public var webpageId: Int64 + public var authorPhotoId: Int64 + public var author: String + public var date: Int32 + public var blocks: [Api.PageBlock] + public var caption: Api.PageCaption + public init(url: String, webpageId: Int64, authorPhotoId: Int64, author: String, date: Int32, blocks: [Api.PageBlock], caption: Api.PageCaption) { + self.url = url + self.webpageId = webpageId + self.authorPhotoId = authorPhotoId + self.author = author + self.date = date + self.blocks = blocks + self.caption = caption + } + } + public class Cons_pageBlockFooter { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + public class Cons_pageBlockHeader { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + public class Cons_pageBlockKicker { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + public class Cons_pageBlockList { + public var items: [Api.PageListItem] + public init(items: [Api.PageListItem]) { + self.items = items + } + } + public class Cons_pageBlockMap { + public var geo: Api.GeoPoint + public var zoom: Int32 + public var w: Int32 + public var h: Int32 + public var caption: Api.PageCaption + public init(geo: Api.GeoPoint, zoom: Int32, w: Int32, h: Int32, caption: Api.PageCaption) { + self.geo = geo + self.zoom = zoom + self.w = w + self.h = h + self.caption = caption + } + } + public class Cons_pageBlockOrderedList { + public var items: [Api.PageListOrderedItem] + public init(items: [Api.PageListOrderedItem]) { + self.items = items + } + } + public class Cons_pageBlockParagraph { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + public class Cons_pageBlockPhoto { + public var flags: Int32 + public var photoId: Int64 + public var caption: Api.PageCaption + public var url: String? + public var webpageId: Int64? + public init(flags: Int32, photoId: Int64, caption: Api.PageCaption, url: String?, webpageId: Int64?) { + self.flags = flags + self.photoId = photoId + self.caption = caption + self.url = url + self.webpageId = webpageId + } + } + public class Cons_pageBlockPreformatted { + public var text: Api.RichText + public var language: String + public init(text: Api.RichText, language: String) { + self.text = text + self.language = language + } + } + public class Cons_pageBlockPullquote { + public var text: Api.RichText + public var caption: Api.RichText + public init(text: Api.RichText, caption: Api.RichText) { + self.text = text + self.caption = caption + } + } + public class Cons_pageBlockRelatedArticles { + public var title: Api.RichText + public var articles: [Api.PageRelatedArticle] + public init(title: Api.RichText, articles: [Api.PageRelatedArticle]) { + self.title = title + self.articles = articles + } + } + public class Cons_pageBlockSlideshow { + public var items: [Api.PageBlock] + public var caption: Api.PageCaption + public init(items: [Api.PageBlock], caption: Api.PageCaption) { + self.items = items + self.caption = caption + } + } + public class Cons_pageBlockSubheader { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + public class Cons_pageBlockSubtitle { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + public class Cons_pageBlockTable { + public var flags: Int32 + public var title: Api.RichText + public var rows: [Api.PageTableRow] + public init(flags: Int32, title: Api.RichText, rows: [Api.PageTableRow]) { + self.flags = flags + self.title = title + self.rows = rows + } + } + public class Cons_pageBlockTitle { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + public class Cons_pageBlockVideo { + public var flags: Int32 + public var videoId: Int64 + public var caption: Api.PageCaption + public init(flags: Int32, videoId: Int64, caption: Api.PageCaption) { + self.flags = flags + self.videoId = videoId + self.caption = caption + } + } + case pageBlockAnchor(Cons_pageBlockAnchor) + case pageBlockAudio(Cons_pageBlockAudio) + case pageBlockAuthorDate(Cons_pageBlockAuthorDate) + case pageBlockBlockquote(Cons_pageBlockBlockquote) + case pageBlockChannel(Cons_pageBlockChannel) + case pageBlockCollage(Cons_pageBlockCollage) + case pageBlockCover(Cons_pageBlockCover) + case pageBlockDetails(Cons_pageBlockDetails) case pageBlockDivider - case pageBlockEmbed(flags: Int32, url: String?, html: String?, posterPhotoId: Int64?, w: Int32?, h: Int32?, caption: Api.PageCaption) - case pageBlockEmbedPost(url: String, webpageId: Int64, authorPhotoId: Int64, author: String, date: Int32, blocks: [Api.PageBlock], caption: Api.PageCaption) - case pageBlockFooter(text: Api.RichText) - case pageBlockHeader(text: Api.RichText) - case pageBlockKicker(text: Api.RichText) - case pageBlockList(items: [Api.PageListItem]) - case pageBlockMap(geo: Api.GeoPoint, zoom: Int32, w: Int32, h: Int32, caption: Api.PageCaption) - case pageBlockOrderedList(items: [Api.PageListOrderedItem]) - case pageBlockParagraph(text: Api.RichText) - case pageBlockPhoto(flags: Int32, photoId: Int64, caption: Api.PageCaption, url: String?, webpageId: Int64?) - case pageBlockPreformatted(text: Api.RichText, language: String) - case pageBlockPullquote(text: Api.RichText, caption: Api.RichText) - case pageBlockRelatedArticles(title: Api.RichText, articles: [Api.PageRelatedArticle]) - case pageBlockSlideshow(items: [Api.PageBlock], caption: Api.PageCaption) - case pageBlockSubheader(text: Api.RichText) - case pageBlockSubtitle(text: Api.RichText) - case pageBlockTable(flags: Int32, title: Api.RichText, rows: [Api.PageTableRow]) - case pageBlockTitle(text: Api.RichText) + case pageBlockEmbed(Cons_pageBlockEmbed) + case pageBlockEmbedPost(Cons_pageBlockEmbedPost) + case pageBlockFooter(Cons_pageBlockFooter) + case pageBlockHeader(Cons_pageBlockHeader) + case pageBlockKicker(Cons_pageBlockKicker) + case pageBlockList(Cons_pageBlockList) + case pageBlockMap(Cons_pageBlockMap) + case pageBlockOrderedList(Cons_pageBlockOrderedList) + case pageBlockParagraph(Cons_pageBlockParagraph) + case pageBlockPhoto(Cons_pageBlockPhoto) + case pageBlockPreformatted(Cons_pageBlockPreformatted) + case pageBlockPullquote(Cons_pageBlockPullquote) + case pageBlockRelatedArticles(Cons_pageBlockRelatedArticles) + case pageBlockSlideshow(Cons_pageBlockSlideshow) + case pageBlockSubheader(Cons_pageBlockSubheader) + case pageBlockSubtitle(Cons_pageBlockSubtitle) + case pageBlockTable(Cons_pageBlockTable) + case pageBlockTitle(Cons_pageBlockTitle) case pageBlockUnsupported - case pageBlockVideo(flags: Int32, videoId: Int64, caption: Api.PageCaption) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .pageBlockAnchor(let name): - if boxed { - buffer.appendInt32(-837994576) - } - serializeString(name, buffer: buffer, boxed: false) - break - case .pageBlockAudio(let audioId, let caption): - if boxed { - buffer.appendInt32(-2143067670) - } - serializeInt64(audioId, buffer: buffer, boxed: false) - caption.serialize(buffer, true) - break - case .pageBlockAuthorDate(let author, let publishedDate): - if boxed { - buffer.appendInt32(-1162877472) - } - author.serialize(buffer, true) - serializeInt32(publishedDate, buffer: buffer, boxed: false) - break - case .pageBlockBlockquote(let text, let caption): - if boxed { - buffer.appendInt32(641563686) - } - text.serialize(buffer, true) - caption.serialize(buffer, true) - break - case .pageBlockChannel(let channel): - if boxed { - buffer.appendInt32(-283684427) - } - channel.serialize(buffer, true) - break - case .pageBlockCollage(let items, let caption): - if boxed { - buffer.appendInt32(1705048653) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(items.count)) - for item in items { - item.serialize(buffer, true) - } - caption.serialize(buffer, true) - break - case .pageBlockCover(let cover): - if boxed { - buffer.appendInt32(972174080) - } - cover.serialize(buffer, true) - break - case .pageBlockDetails(let flags, let blocks, let title): - if boxed { - buffer.appendInt32(1987480557) - } - serializeInt32(flags, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(blocks.count)) - for item in blocks { - item.serialize(buffer, true) - } - title.serialize(buffer, true) - break - case .pageBlockDivider: - if boxed { - buffer.appendInt32(-618614392) - } - - break - case .pageBlockEmbed(let flags, let url, let html, let posterPhotoId, let w, let h, let caption): - if boxed { - buffer.appendInt32(-1468953147) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeString(url!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(html!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt64(posterPhotoId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeInt32(w!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeInt32(h!, buffer: buffer, boxed: false)} - caption.serialize(buffer, true) - break - case .pageBlockEmbedPost(let url, let webpageId, let authorPhotoId, let author, let date, let blocks, let caption): - if boxed { - buffer.appendInt32(-229005301) - } - serializeString(url, buffer: buffer, boxed: false) - serializeInt64(webpageId, buffer: buffer, boxed: false) - serializeInt64(authorPhotoId, buffer: buffer, boxed: false) - serializeString(author, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(blocks.count)) - for item in blocks { - item.serialize(buffer, true) - } - caption.serialize(buffer, true) - break - case .pageBlockFooter(let text): - if boxed { - buffer.appendInt32(1216809369) - } - text.serialize(buffer, true) - break - case .pageBlockHeader(let text): - if boxed { - buffer.appendInt32(-1076861716) - } - text.serialize(buffer, true) - break - case .pageBlockKicker(let text): - if boxed { - buffer.appendInt32(504660880) - } - text.serialize(buffer, true) - break - case .pageBlockList(let items): - if boxed { - buffer.appendInt32(-454524911) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(items.count)) - for item in items { - item.serialize(buffer, true) - } - break - case .pageBlockMap(let geo, let zoom, let w, let h, let caption): - if boxed { - buffer.appendInt32(-1538310410) - } - geo.serialize(buffer, true) - serializeInt32(zoom, buffer: buffer, boxed: false) - serializeInt32(w, buffer: buffer, boxed: false) - serializeInt32(h, buffer: buffer, boxed: false) - caption.serialize(buffer, true) - break - case .pageBlockOrderedList(let items): - if boxed { - buffer.appendInt32(-1702174239) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(items.count)) - for item in items { - item.serialize(buffer, true) - } - break - case .pageBlockParagraph(let text): - if boxed { - buffer.appendInt32(1182402406) - } - text.serialize(buffer, true) - break - case .pageBlockPhoto(let flags, let photoId, let caption, let url, let webpageId): - if boxed { - buffer.appendInt32(391759200) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(photoId, buffer: buffer, boxed: false) - caption.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeString(url!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(webpageId!, buffer: buffer, boxed: false)} - break - case .pageBlockPreformatted(let text, let language): - if boxed { - buffer.appendInt32(-1066346178) - } - text.serialize(buffer, true) - serializeString(language, buffer: buffer, boxed: false) - break - case .pageBlockPullquote(let text, let caption): - if boxed { - buffer.appendInt32(1329878739) - } - text.serialize(buffer, true) - caption.serialize(buffer, true) - break - case .pageBlockRelatedArticles(let title, let articles): - if boxed { - buffer.appendInt32(370236054) - } - title.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(articles.count)) - for item in articles { - item.serialize(buffer, true) - } - break - case .pageBlockSlideshow(let items, let caption): - if boxed { - buffer.appendInt32(52401552) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(items.count)) - for item in items { - item.serialize(buffer, true) - } - caption.serialize(buffer, true) - break - case .pageBlockSubheader(let text): - if boxed { - buffer.appendInt32(-248793375) - } - text.serialize(buffer, true) - break - case .pageBlockSubtitle(let text): - if boxed { - buffer.appendInt32(-1879401953) - } - text.serialize(buffer, true) - break - case .pageBlockTable(let flags, let title, let rows): - if boxed { - buffer.appendInt32(-1085412734) - } - serializeInt32(flags, buffer: buffer, boxed: false) - title.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(rows.count)) - for item in rows { - item.serialize(buffer, true) - } - break - case .pageBlockTitle(let text): - if boxed { - buffer.appendInt32(1890305021) - } - text.serialize(buffer, true) - break - case .pageBlockUnsupported: - if boxed { - buffer.appendInt32(324435594) - } - - break - case .pageBlockVideo(let flags, let videoId, let caption): - if boxed { - buffer.appendInt32(2089805750) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(videoId, buffer: buffer, boxed: false) - caption.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .pageBlockAnchor(let name): - return ("pageBlockAnchor", [("name", name as Any)]) - case .pageBlockAudio(let audioId, let caption): - return ("pageBlockAudio", [("audioId", audioId as Any), ("caption", caption as Any)]) - case .pageBlockAuthorDate(let author, let publishedDate): - return ("pageBlockAuthorDate", [("author", author as Any), ("publishedDate", publishedDate as Any)]) - case .pageBlockBlockquote(let text, let caption): - return ("pageBlockBlockquote", [("text", text as Any), ("caption", caption as Any)]) - case .pageBlockChannel(let channel): - return ("pageBlockChannel", [("channel", channel as Any)]) - case .pageBlockCollage(let items, let caption): - return ("pageBlockCollage", [("items", items as Any), ("caption", caption as Any)]) - case .pageBlockCover(let cover): - return ("pageBlockCover", [("cover", cover as Any)]) - case .pageBlockDetails(let flags, let blocks, let title): - return ("pageBlockDetails", [("flags", flags as Any), ("blocks", blocks as Any), ("title", title as Any)]) - case .pageBlockDivider: + case pageBlockVideo(Cons_pageBlockVideo) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .pageBlockAnchor(let _data): + if boxed { + buffer.appendInt32(-837994576) + } + serializeString(_data.name, buffer: buffer, boxed: false) + break + case .pageBlockAudio(let _data): + if boxed { + buffer.appendInt32(-2143067670) + } + serializeInt64(_data.audioId, buffer: buffer, boxed: false) + _data.caption.serialize(buffer, true) + break + case .pageBlockAuthorDate(let _data): + if boxed { + buffer.appendInt32(-1162877472) + } + _data.author.serialize(buffer, true) + serializeInt32(_data.publishedDate, buffer: buffer, boxed: false) + break + case .pageBlockBlockquote(let _data): + if boxed { + buffer.appendInt32(641563686) + } + _data.text.serialize(buffer, true) + _data.caption.serialize(buffer, true) + break + case .pageBlockChannel(let _data): + if boxed { + buffer.appendInt32(-283684427) + } + _data.channel.serialize(buffer, true) + break + case .pageBlockCollage(let _data): + if boxed { + buffer.appendInt32(1705048653) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.items.count)) + for item in _data.items { + item.serialize(buffer, true) + } + _data.caption.serialize(buffer, true) + break + case .pageBlockCover(let _data): + if boxed { + buffer.appendInt32(972174080) + } + _data.cover.serialize(buffer, true) + break + case .pageBlockDetails(let _data): + if boxed { + buffer.appendInt32(1987480557) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.blocks.count)) + for item in _data.blocks { + item.serialize(buffer, true) + } + _data.title.serialize(buffer, true) + break + case .pageBlockDivider: + if boxed { + buffer.appendInt32(-618614392) + } + break + case .pageBlockEmbed(let _data): + if boxed { + buffer.appendInt32(-1468953147) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.url!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.html!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt64(_data.posterPhotoId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeInt32(_data.w!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeInt32(_data.h!, buffer: buffer, boxed: false) + } + _data.caption.serialize(buffer, true) + break + case .pageBlockEmbedPost(let _data): + if boxed { + buffer.appendInt32(-229005301) + } + serializeString(_data.url, buffer: buffer, boxed: false) + serializeInt64(_data.webpageId, buffer: buffer, boxed: false) + serializeInt64(_data.authorPhotoId, buffer: buffer, boxed: false) + serializeString(_data.author, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.blocks.count)) + for item in _data.blocks { + item.serialize(buffer, true) + } + _data.caption.serialize(buffer, true) + break + case .pageBlockFooter(let _data): + if boxed { + buffer.appendInt32(1216809369) + } + _data.text.serialize(buffer, true) + break + case .pageBlockHeader(let _data): + if boxed { + buffer.appendInt32(-1076861716) + } + _data.text.serialize(buffer, true) + break + case .pageBlockKicker(let _data): + if boxed { + buffer.appendInt32(504660880) + } + _data.text.serialize(buffer, true) + break + case .pageBlockList(let _data): + if boxed { + buffer.appendInt32(-454524911) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.items.count)) + for item in _data.items { + item.serialize(buffer, true) + } + break + case .pageBlockMap(let _data): + if boxed { + buffer.appendInt32(-1538310410) + } + _data.geo.serialize(buffer, true) + serializeInt32(_data.zoom, buffer: buffer, boxed: false) + serializeInt32(_data.w, buffer: buffer, boxed: false) + serializeInt32(_data.h, buffer: buffer, boxed: false) + _data.caption.serialize(buffer, true) + break + case .pageBlockOrderedList(let _data): + if boxed { + buffer.appendInt32(-1702174239) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.items.count)) + for item in _data.items { + item.serialize(buffer, true) + } + break + case .pageBlockParagraph(let _data): + if boxed { + buffer.appendInt32(1182402406) + } + _data.text.serialize(buffer, true) + break + case .pageBlockPhoto(let _data): + if boxed { + buffer.appendInt32(391759200) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.photoId, buffer: buffer, boxed: false) + _data.caption.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.url!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.webpageId!, buffer: buffer, boxed: false) + } + break + case .pageBlockPreformatted(let _data): + if boxed { + buffer.appendInt32(-1066346178) + } + _data.text.serialize(buffer, true) + serializeString(_data.language, buffer: buffer, boxed: false) + break + case .pageBlockPullquote(let _data): + if boxed { + buffer.appendInt32(1329878739) + } + _data.text.serialize(buffer, true) + _data.caption.serialize(buffer, true) + break + case .pageBlockRelatedArticles(let _data): + if boxed { + buffer.appendInt32(370236054) + } + _data.title.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.articles.count)) + for item in _data.articles { + item.serialize(buffer, true) + } + break + case .pageBlockSlideshow(let _data): + if boxed { + buffer.appendInt32(52401552) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.items.count)) + for item in _data.items { + item.serialize(buffer, true) + } + _data.caption.serialize(buffer, true) + break + case .pageBlockSubheader(let _data): + if boxed { + buffer.appendInt32(-248793375) + } + _data.text.serialize(buffer, true) + break + case .pageBlockSubtitle(let _data): + if boxed { + buffer.appendInt32(-1879401953) + } + _data.text.serialize(buffer, true) + break + case .pageBlockTable(let _data): + if boxed { + buffer.appendInt32(-1085412734) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.title.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.rows.count)) + for item in _data.rows { + item.serialize(buffer, true) + } + break + case .pageBlockTitle(let _data): + if boxed { + buffer.appendInt32(1890305021) + } + _data.text.serialize(buffer, true) + break + case .pageBlockUnsupported: + if boxed { + buffer.appendInt32(324435594) + } + break + case .pageBlockVideo(let _data): + if boxed { + buffer.appendInt32(2089805750) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.videoId, buffer: buffer, boxed: false) + _data.caption.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .pageBlockAnchor(let _data): + return ("pageBlockAnchor", [("name", _data.name as Any)]) + case .pageBlockAudio(let _data): + return ("pageBlockAudio", [("audioId", _data.audioId as Any), ("caption", _data.caption as Any)]) + case .pageBlockAuthorDate(let _data): + return ("pageBlockAuthorDate", [("author", _data.author as Any), ("publishedDate", _data.publishedDate as Any)]) + case .pageBlockBlockquote(let _data): + return ("pageBlockBlockquote", [("text", _data.text as Any), ("caption", _data.caption as Any)]) + case .pageBlockChannel(let _data): + return ("pageBlockChannel", [("channel", _data.channel as Any)]) + case .pageBlockCollage(let _data): + return ("pageBlockCollage", [("items", _data.items as Any), ("caption", _data.caption as Any)]) + case .pageBlockCover(let _data): + return ("pageBlockCover", [("cover", _data.cover as Any)]) + case .pageBlockDetails(let _data): + return ("pageBlockDetails", [("flags", _data.flags as Any), ("blocks", _data.blocks as Any), ("title", _data.title as Any)]) + case .pageBlockDivider: return ("pageBlockDivider", []) - case .pageBlockEmbed(let flags, let url, let html, let posterPhotoId, let w, let h, let caption): - return ("pageBlockEmbed", [("flags", flags as Any), ("url", url as Any), ("html", html as Any), ("posterPhotoId", posterPhotoId as Any), ("w", w as Any), ("h", h as Any), ("caption", caption as Any)]) - case .pageBlockEmbedPost(let url, let webpageId, let authorPhotoId, let author, let date, let blocks, let caption): - return ("pageBlockEmbedPost", [("url", url as Any), ("webpageId", webpageId as Any), ("authorPhotoId", authorPhotoId as Any), ("author", author as Any), ("date", date as Any), ("blocks", blocks as Any), ("caption", caption as Any)]) - case .pageBlockFooter(let text): - return ("pageBlockFooter", [("text", text as Any)]) - case .pageBlockHeader(let text): - return ("pageBlockHeader", [("text", text as Any)]) - case .pageBlockKicker(let text): - return ("pageBlockKicker", [("text", text as Any)]) - case .pageBlockList(let items): - return ("pageBlockList", [("items", items as Any)]) - case .pageBlockMap(let geo, let zoom, let w, let h, let caption): - return ("pageBlockMap", [("geo", geo as Any), ("zoom", zoom as Any), ("w", w as Any), ("h", h as Any), ("caption", caption as Any)]) - case .pageBlockOrderedList(let items): - return ("pageBlockOrderedList", [("items", items as Any)]) - case .pageBlockParagraph(let text): - return ("pageBlockParagraph", [("text", text as Any)]) - case .pageBlockPhoto(let flags, let photoId, let caption, let url, let webpageId): - return ("pageBlockPhoto", [("flags", flags as Any), ("photoId", photoId as Any), ("caption", caption as Any), ("url", url as Any), ("webpageId", webpageId as Any)]) - case .pageBlockPreformatted(let text, let language): - return ("pageBlockPreformatted", [("text", text as Any), ("language", language as Any)]) - case .pageBlockPullquote(let text, let caption): - return ("pageBlockPullquote", [("text", text as Any), ("caption", caption as Any)]) - case .pageBlockRelatedArticles(let title, let articles): - return ("pageBlockRelatedArticles", [("title", title as Any), ("articles", articles as Any)]) - case .pageBlockSlideshow(let items, let caption): - return ("pageBlockSlideshow", [("items", items as Any), ("caption", caption as Any)]) - case .pageBlockSubheader(let text): - return ("pageBlockSubheader", [("text", text as Any)]) - case .pageBlockSubtitle(let text): - return ("pageBlockSubtitle", [("text", text as Any)]) - case .pageBlockTable(let flags, let title, let rows): - return ("pageBlockTable", [("flags", flags as Any), ("title", title as Any), ("rows", rows as Any)]) - case .pageBlockTitle(let text): - return ("pageBlockTitle", [("text", text as Any)]) - case .pageBlockUnsupported: + case .pageBlockEmbed(let _data): + return ("pageBlockEmbed", [("flags", _data.flags as Any), ("url", _data.url as Any), ("html", _data.html as Any), ("posterPhotoId", _data.posterPhotoId as Any), ("w", _data.w as Any), ("h", _data.h as Any), ("caption", _data.caption as Any)]) + case .pageBlockEmbedPost(let _data): + return ("pageBlockEmbedPost", [("url", _data.url as Any), ("webpageId", _data.webpageId as Any), ("authorPhotoId", _data.authorPhotoId as Any), ("author", _data.author as Any), ("date", _data.date as Any), ("blocks", _data.blocks as Any), ("caption", _data.caption as Any)]) + case .pageBlockFooter(let _data): + return ("pageBlockFooter", [("text", _data.text as Any)]) + case .pageBlockHeader(let _data): + return ("pageBlockHeader", [("text", _data.text as Any)]) + case .pageBlockKicker(let _data): + return ("pageBlockKicker", [("text", _data.text as Any)]) + case .pageBlockList(let _data): + return ("pageBlockList", [("items", _data.items as Any)]) + case .pageBlockMap(let _data): + return ("pageBlockMap", [("geo", _data.geo as Any), ("zoom", _data.zoom as Any), ("w", _data.w as Any), ("h", _data.h as Any), ("caption", _data.caption as Any)]) + case .pageBlockOrderedList(let _data): + return ("pageBlockOrderedList", [("items", _data.items as Any)]) + case .pageBlockParagraph(let _data): + return ("pageBlockParagraph", [("text", _data.text as Any)]) + case .pageBlockPhoto(let _data): + return ("pageBlockPhoto", [("flags", _data.flags as Any), ("photoId", _data.photoId as Any), ("caption", _data.caption as Any), ("url", _data.url as Any), ("webpageId", _data.webpageId as Any)]) + case .pageBlockPreformatted(let _data): + return ("pageBlockPreformatted", [("text", _data.text as Any), ("language", _data.language as Any)]) + case .pageBlockPullquote(let _data): + return ("pageBlockPullquote", [("text", _data.text as Any), ("caption", _data.caption as Any)]) + case .pageBlockRelatedArticles(let _data): + return ("pageBlockRelatedArticles", [("title", _data.title as Any), ("articles", _data.articles as Any)]) + case .pageBlockSlideshow(let _data): + return ("pageBlockSlideshow", [("items", _data.items as Any), ("caption", _data.caption as Any)]) + case .pageBlockSubheader(let _data): + return ("pageBlockSubheader", [("text", _data.text as Any)]) + case .pageBlockSubtitle(let _data): + return ("pageBlockSubtitle", [("text", _data.text as Any)]) + case .pageBlockTable(let _data): + return ("pageBlockTable", [("flags", _data.flags as Any), ("title", _data.title as Any), ("rows", _data.rows as Any)]) + case .pageBlockTitle(let _data): + return ("pageBlockTitle", [("text", _data.text as Any)]) + case .pageBlockUnsupported: return ("pageBlockUnsupported", []) - case .pageBlockVideo(let flags, let videoId, let caption): - return ("pageBlockVideo", [("flags", flags as Any), ("videoId", videoId as Any), ("caption", caption as Any)]) - } - } - + case .pageBlockVideo(let _data): + return ("pageBlockVideo", [("flags", _data.flags as Any), ("videoId", _data.videoId as Any), ("caption", _data.caption as Any)]) + } + } + public static func parse_pageBlockAnchor(_ reader: BufferReader) -> PageBlock? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PageBlock.pageBlockAnchor(name: _1!) + if _c1 { + return Api.PageBlock.pageBlockAnchor(Cons_pageBlockAnchor(name: _1!)) + } + else { + return nil + } } public static func parse_pageBlockAudio(_ reader: BufferReader) -> PageBlock? { var _1: Int64? @@ -631,9 +939,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PageBlock.pageBlockAudio(audioId: _1!, caption: _2!) + if _c1 && _c2 { + return Api.PageBlock.pageBlockAudio(Cons_pageBlockAudio(audioId: _1!, caption: _2!)) + } + else { + return nil + } } public static func parse_pageBlockAuthorDate(_ reader: BufferReader) -> PageBlock? { var _1: Api.RichText? @@ -644,9 +955,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PageBlock.pageBlockAuthorDate(author: _1!, publishedDate: _2!) + if _c1 && _c2 { + return Api.PageBlock.pageBlockAuthorDate(Cons_pageBlockAuthorDate(author: _1!, publishedDate: _2!)) + } + else { + return nil + } } public static func parse_pageBlockBlockquote(_ reader: BufferReader) -> PageBlock? { var _1: Api.RichText? @@ -659,9 +973,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PageBlock.pageBlockBlockquote(text: _1!, caption: _2!) + if _c1 && _c2 { + return Api.PageBlock.pageBlockBlockquote(Cons_pageBlockBlockquote(text: _1!, caption: _2!)) + } + else { + return nil + } } public static func parse_pageBlockChannel(_ reader: BufferReader) -> PageBlock? { var _1: Api.Chat? @@ -669,8 +986,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Chat } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PageBlock.pageBlockChannel(channel: _1!) + if _c1 { + return Api.PageBlock.pageBlockChannel(Cons_pageBlockChannel(channel: _1!)) + } + else { + return nil + } } public static func parse_pageBlockCollage(_ reader: BufferReader) -> PageBlock? { var _1: [Api.PageBlock]? @@ -683,9 +1004,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PageBlock.pageBlockCollage(items: _1!, caption: _2!) + if _c1 && _c2 { + return Api.PageBlock.pageBlockCollage(Cons_pageBlockCollage(items: _1!, caption: _2!)) + } + else { + return nil + } } public static func parse_pageBlockCover(_ reader: BufferReader) -> PageBlock? { var _1: Api.PageBlock? @@ -693,8 +1017,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.PageBlock } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PageBlock.pageBlockCover(cover: _1!) + if _c1 { + return Api.PageBlock.pageBlockCover(Cons_pageBlockCover(cover: _1!)) + } + else { + return nil + } } public static func parse_pageBlockDetails(_ reader: BufferReader) -> PageBlock? { var _1: Int32? @@ -710,10 +1038,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.PageBlock.pageBlockDetails(flags: _1!, blocks: _2!, title: _3!) + if _c1 && _c2 && _c3 { + return Api.PageBlock.pageBlockDetails(Cons_pageBlockDetails(flags: _1!, blocks: _2!, title: _3!)) + } + else { + return nil + } } public static func parse_pageBlockDivider(_ reader: BufferReader) -> PageBlock? { return Api.PageBlock.pageBlockDivider @@ -722,15 +1052,25 @@ public extension Api { var _1: Int32? _1 = reader.readInt32() var _2: String? - if Int(_1!) & Int(1 << 1) != 0 {_2 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _2 = parseString(reader) + } var _3: String? - if Int(_1!) & Int(1 << 2) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _3 = parseString(reader) + } var _4: Int64? - if Int(_1!) & Int(1 << 4) != 0 {_4 = reader.readInt64() } + if Int(_1!) & Int(1 << 4) != 0 { + _4 = reader.readInt64() + } var _5: Int32? - if Int(_1!) & Int(1 << 5) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 5) != 0 { + _5 = reader.readInt32() + } var _6: Int32? - if Int(_1!) & Int(1 << 5) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 5) != 0 { + _6 = reader.readInt32() + } var _7: Api.PageCaption? if let signature = reader.readInt32() { _7 = Api.parse(reader, signature: signature) as? Api.PageCaption @@ -742,14 +1082,12 @@ public extension Api { let _c5 = (Int(_1!) & Int(1 << 5) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 5) == 0) || _6 != nil let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.PageBlock.pageBlockEmbed(flags: _1!, url: _2, html: _3, posterPhotoId: _4, w: _5, h: _6, caption: _7!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.PageBlock.pageBlockEmbed(Cons_pageBlockEmbed(flags: _1!, url: _2, html: _3, posterPhotoId: _4, w: _5, h: _6, caption: _7!)) + } + else { + return nil + } } public static func parse_pageBlockEmbedPost(_ reader: BufferReader) -> PageBlock? { var _1: String? @@ -777,14 +1115,12 @@ public extension Api { let _c5 = _5 != nil let _c6 = _6 != nil let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.PageBlock.pageBlockEmbedPost(url: _1!, webpageId: _2!, authorPhotoId: _3!, author: _4!, date: _5!, blocks: _6!, caption: _7!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.PageBlock.pageBlockEmbedPost(Cons_pageBlockEmbedPost(url: _1!, webpageId: _2!, authorPhotoId: _3!, author: _4!, date: _5!, blocks: _6!, caption: _7!)) + } + else { + return nil + } } public static func parse_pageBlockFooter(_ reader: BufferReader) -> PageBlock? { var _1: Api.RichText? @@ -792,8 +1128,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PageBlock.pageBlockFooter(text: _1!) + if _c1 { + return Api.PageBlock.pageBlockFooter(Cons_pageBlockFooter(text: _1!)) + } + else { + return nil + } } public static func parse_pageBlockHeader(_ reader: BufferReader) -> PageBlock? { var _1: Api.RichText? @@ -801,8 +1141,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PageBlock.pageBlockHeader(text: _1!) + if _c1 { + return Api.PageBlock.pageBlockHeader(Cons_pageBlockHeader(text: _1!)) + } + else { + return nil + } } public static func parse_pageBlockKicker(_ reader: BufferReader) -> PageBlock? { var _1: Api.RichText? @@ -810,8 +1154,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PageBlock.pageBlockKicker(text: _1!) + if _c1 { + return Api.PageBlock.pageBlockKicker(Cons_pageBlockKicker(text: _1!)) + } + else { + return nil + } } public static func parse_pageBlockList(_ reader: BufferReader) -> PageBlock? { var _1: [Api.PageListItem]? @@ -819,8 +1167,12 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PageListItem.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PageBlock.pageBlockList(items: _1!) + if _c1 { + return Api.PageBlock.pageBlockList(Cons_pageBlockList(items: _1!)) + } + else { + return nil + } } public static func parse_pageBlockMap(_ reader: BufferReader) -> PageBlock? { var _1: Api.GeoPoint? @@ -842,12 +1194,12 @@ public extension Api { let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.PageBlock.pageBlockMap(geo: _1!, zoom: _2!, w: _3!, h: _4!, caption: _5!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.PageBlock.pageBlockMap(Cons_pageBlockMap(geo: _1!, zoom: _2!, w: _3!, h: _4!, caption: _5!)) + } + else { + return nil + } } public static func parse_pageBlockOrderedList(_ reader: BufferReader) -> PageBlock? { var _1: [Api.PageListOrderedItem]? @@ -855,8 +1207,12 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PageListOrderedItem.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PageBlock.pageBlockOrderedList(items: _1!) + if _c1 { + return Api.PageBlock.pageBlockOrderedList(Cons_pageBlockOrderedList(items: _1!)) + } + else { + return nil + } } public static func parse_pageBlockParagraph(_ reader: BufferReader) -> PageBlock? { var _1: Api.RichText? @@ -864,8 +1220,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PageBlock.pageBlockParagraph(text: _1!) + if _c1 { + return Api.PageBlock.pageBlockParagraph(Cons_pageBlockParagraph(text: _1!)) + } + else { + return nil + } } public static func parse_pageBlockPhoto(_ reader: BufferReader) -> PageBlock? { var _1: Int32? @@ -877,20 +1237,24 @@ public extension Api { _3 = Api.parse(reader, signature: signature) as? Api.PageCaption } var _4: String? - if Int(_1!) & Int(1 << 0) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) + } var _5: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_5 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _5 = reader.readInt64() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.PageBlock.pageBlockPhoto(flags: _1!, photoId: _2!, caption: _3!, url: _4, webpageId: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.PageBlock.pageBlockPhoto(Cons_pageBlockPhoto(flags: _1!, photoId: _2!, caption: _3!, url: _4, webpageId: _5)) + } + else { + return nil + } } public static func parse_pageBlockPreformatted(_ reader: BufferReader) -> PageBlock? { var _1: Api.RichText? @@ -901,9 +1265,12 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PageBlock.pageBlockPreformatted(text: _1!, language: _2!) + if _c1 && _c2 { + return Api.PageBlock.pageBlockPreformatted(Cons_pageBlockPreformatted(text: _1!, language: _2!)) + } + else { + return nil + } } public static func parse_pageBlockPullquote(_ reader: BufferReader) -> PageBlock? { var _1: Api.RichText? @@ -916,9 +1283,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PageBlock.pageBlockPullquote(text: _1!, caption: _2!) + if _c1 && _c2 { + return Api.PageBlock.pageBlockPullquote(Cons_pageBlockPullquote(text: _1!, caption: _2!)) + } + else { + return nil + } } public static func parse_pageBlockRelatedArticles(_ reader: BufferReader) -> PageBlock? { var _1: Api.RichText? @@ -931,9 +1301,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PageBlock.pageBlockRelatedArticles(title: _1!, articles: _2!) + if _c1 && _c2 { + return Api.PageBlock.pageBlockRelatedArticles(Cons_pageBlockRelatedArticles(title: _1!, articles: _2!)) + } + else { + return nil + } } public static func parse_pageBlockSlideshow(_ reader: BufferReader) -> PageBlock? { var _1: [Api.PageBlock]? @@ -946,9 +1319,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PageBlock.pageBlockSlideshow(items: _1!, caption: _2!) + if _c1 && _c2 { + return Api.PageBlock.pageBlockSlideshow(Cons_pageBlockSlideshow(items: _1!, caption: _2!)) + } + else { + return nil + } } public static func parse_pageBlockSubheader(_ reader: BufferReader) -> PageBlock? { var _1: Api.RichText? @@ -956,8 +1332,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PageBlock.pageBlockSubheader(text: _1!) + if _c1 { + return Api.PageBlock.pageBlockSubheader(Cons_pageBlockSubheader(text: _1!)) + } + else { + return nil + } } public static func parse_pageBlockSubtitle(_ reader: BufferReader) -> PageBlock? { var _1: Api.RichText? @@ -965,8 +1345,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PageBlock.pageBlockSubtitle(text: _1!) + if _c1 { + return Api.PageBlock.pageBlockSubtitle(Cons_pageBlockSubtitle(text: _1!)) + } + else { + return nil + } } public static func parse_pageBlockTable(_ reader: BufferReader) -> PageBlock? { var _1: Int32? @@ -982,10 +1366,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.PageBlock.pageBlockTable(flags: _1!, title: _2!, rows: _3!) + if _c1 && _c2 && _c3 { + return Api.PageBlock.pageBlockTable(Cons_pageBlockTable(flags: _1!, title: _2!, rows: _3!)) + } + else { + return nil + } } public static func parse_pageBlockTitle(_ reader: BufferReader) -> PageBlock? { var _1: Api.RichText? @@ -993,8 +1379,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PageBlock.pageBlockTitle(text: _1!) + if _c1 { + return Api.PageBlock.pageBlockTitle(Cons_pageBlockTitle(text: _1!)) + } + else { + return nil + } } public static func parse_pageBlockUnsupported(_ reader: BufferReader) -> PageBlock? { return Api.PageBlock.pageBlockUnsupported @@ -1011,11 +1401,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.PageBlock.pageBlockVideo(flags: _1!, videoId: _2!, caption: _3!) + if _c1 && _c2 && _c3 { + return Api.PageBlock.pageBlockVideo(Cons_pageBlockVideo(flags: _1!, videoId: _2!, caption: _3!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api19.swift b/submodules/TelegramApi/Sources/Api19.swift index 76f9fd8e..42f2e03a 100644 --- a/submodules/TelegramApi/Sources/Api19.swift +++ b/submodules/TelegramApi/Sources/Api19.swift @@ -1,26 +1,34 @@ public extension Api { indirect enum PageCaption: TypeConstructorDescription { - case pageCaption(text: Api.RichText, credit: Api.RichText) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .pageCaption(let text, let credit): - if boxed { - buffer.appendInt32(1869903447) - } - text.serialize(buffer, true) - credit.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .pageCaption(let text, let credit): - return ("pageCaption", [("text", text as Any), ("credit", credit as Any)]) - } - } - + public class Cons_pageCaption { + public var text: Api.RichText + public var credit: Api.RichText + public init(text: Api.RichText, credit: Api.RichText) { + self.text = text + self.credit = credit + } + } + case pageCaption(Cons_pageCaption) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .pageCaption(let _data): + if boxed { + buffer.appendInt32(1869903447) + } + _data.text.serialize(buffer, true) + _data.credit.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .pageCaption(let _data): + return ("pageCaption", [("text", _data.text as Any), ("credit", _data.credit as Any)]) + } + } + public static func parse_pageCaption(_ reader: BufferReader) -> PageCaption? { var _1: Api.RichText? if let signature = reader.readInt32() { @@ -32,56 +40,74 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PageCaption.pageCaption(text: _1!, credit: _2!) + if _c1 && _c2 { + return Api.PageCaption.pageCaption(Cons_pageCaption(text: _1!, credit: _2!)) + } + else { + return nil + } } - } } public extension Api { indirect enum PageListItem: TypeConstructorDescription { - case pageListItemBlocks(blocks: [Api.PageBlock]) - case pageListItemText(text: Api.RichText) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .pageListItemBlocks(let blocks): - if boxed { - buffer.appendInt32(635466748) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(blocks.count)) - for item in blocks { - item.serialize(buffer, true) - } - break - case .pageListItemText(let text): - if boxed { - buffer.appendInt32(-1188055347) - } - text.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .pageListItemBlocks(let blocks): - return ("pageListItemBlocks", [("blocks", blocks as Any)]) - case .pageListItemText(let text): - return ("pageListItemText", [("text", text as Any)]) - } - } - + public class Cons_pageListItemBlocks { + public var blocks: [Api.PageBlock] + public init(blocks: [Api.PageBlock]) { + self.blocks = blocks + } + } + public class Cons_pageListItemText { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + case pageListItemBlocks(Cons_pageListItemBlocks) + case pageListItemText(Cons_pageListItemText) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .pageListItemBlocks(let _data): + if boxed { + buffer.appendInt32(635466748) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.blocks.count)) + for item in _data.blocks { + item.serialize(buffer, true) + } + break + case .pageListItemText(let _data): + if boxed { + buffer.appendInt32(-1188055347) + } + _data.text.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .pageListItemBlocks(let _data): + return ("pageListItemBlocks", [("blocks", _data.blocks as Any)]) + case .pageListItemText(let _data): + return ("pageListItemText", [("text", _data.text as Any)]) + } + } + public static func parse_pageListItemBlocks(_ reader: BufferReader) -> PageListItem? { var _1: [Api.PageBlock]? if let _ = reader.readInt32() { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PageBlock.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PageListItem.pageListItemBlocks(blocks: _1!) + if _c1 { + return Api.PageListItem.pageListItemBlocks(Cons_pageListItemBlocks(blocks: _1!)) + } + else { + return nil + } } public static func parse_pageListItemText(_ reader: BufferReader) -> PageListItem? { var _1: Api.RichText? @@ -89,49 +115,68 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PageListItem.pageListItemText(text: _1!) + if _c1 { + return Api.PageListItem.pageListItemText(Cons_pageListItemText(text: _1!)) + } + else { + return nil + } } - } } public extension Api { indirect enum PageListOrderedItem: TypeConstructorDescription { - case pageListOrderedItemBlocks(num: String, blocks: [Api.PageBlock]) - case pageListOrderedItemText(num: String, text: Api.RichText) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .pageListOrderedItemBlocks(let num, let blocks): - if boxed { - buffer.appendInt32(-1730311882) - } - serializeString(num, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(blocks.count)) - for item in blocks { - item.serialize(buffer, true) - } - break - case .pageListOrderedItemText(let num, let text): - if boxed { - buffer.appendInt32(1577484359) - } - serializeString(num, buffer: buffer, boxed: false) - text.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .pageListOrderedItemBlocks(let num, let blocks): - return ("pageListOrderedItemBlocks", [("num", num as Any), ("blocks", blocks as Any)]) - case .pageListOrderedItemText(let num, let text): - return ("pageListOrderedItemText", [("num", num as Any), ("text", text as Any)]) - } - } - + public class Cons_pageListOrderedItemBlocks { + public var num: String + public var blocks: [Api.PageBlock] + public init(num: String, blocks: [Api.PageBlock]) { + self.num = num + self.blocks = blocks + } + } + public class Cons_pageListOrderedItemText { + public var num: String + public var text: Api.RichText + public init(num: String, text: Api.RichText) { + self.num = num + self.text = text + } + } + case pageListOrderedItemBlocks(Cons_pageListOrderedItemBlocks) + case pageListOrderedItemText(Cons_pageListOrderedItemText) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .pageListOrderedItemBlocks(let _data): + if boxed { + buffer.appendInt32(-1730311882) + } + serializeString(_data.num, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.blocks.count)) + for item in _data.blocks { + item.serialize(buffer, true) + } + break + case .pageListOrderedItemText(let _data): + if boxed { + buffer.appendInt32(1577484359) + } + serializeString(_data.num, buffer: buffer, boxed: false) + _data.text.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .pageListOrderedItemBlocks(let _data): + return ("pageListOrderedItemBlocks", [("num", _data.num as Any), ("blocks", _data.blocks as Any)]) + case .pageListOrderedItemText(let _data): + return ("pageListOrderedItemText", [("num", _data.num as Any), ("text", _data.text as Any)]) + } + } + public static func parse_pageListOrderedItemBlocks(_ reader: BufferReader) -> PageListOrderedItem? { var _1: String? _1 = parseString(reader) @@ -141,9 +186,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PageListOrderedItem.pageListOrderedItemBlocks(num: _1!, blocks: _2!) + if _c1 && _c2 { + return Api.PageListOrderedItem.pageListOrderedItemBlocks(Cons_pageListOrderedItemBlocks(num: _1!, blocks: _2!)) + } + else { + return nil + } } public static func parse_pageListOrderedItemText(_ reader: BufferReader) -> PageListOrderedItem? { var _1: String? @@ -154,42 +202,74 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PageListOrderedItem.pageListOrderedItemText(num: _1!, text: _2!) + if _c1 && _c2 { + return Api.PageListOrderedItem.pageListOrderedItemText(Cons_pageListOrderedItemText(num: _1!, text: _2!)) + } + else { + return nil + } } - } } public extension Api { enum PageRelatedArticle: TypeConstructorDescription { - case pageRelatedArticle(flags: Int32, url: String, webpageId: Int64, title: String?, description: String?, photoId: Int64?, author: String?, publishedDate: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .pageRelatedArticle(let flags, let url, let webpageId, let title, let description, let photoId, let author, let publishedDate): - if boxed { - buffer.appendInt32(-1282352120) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - serializeInt64(webpageId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(description!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt64(photoId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeString(author!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(publishedDate!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .pageRelatedArticle(let flags, let url, let webpageId, let title, let description, let photoId, let author, let publishedDate): - return ("pageRelatedArticle", [("flags", flags as Any), ("url", url as Any), ("webpageId", webpageId as Any), ("title", title as Any), ("description", description as Any), ("photoId", photoId as Any), ("author", author as Any), ("publishedDate", publishedDate as Any)]) - } - } - + public class Cons_pageRelatedArticle { + public var flags: Int32 + public var url: String + public var webpageId: Int64 + public var title: String? + public var description: String? + public var photoId: Int64? + public var author: String? + public var publishedDate: Int32? + public init(flags: Int32, url: String, webpageId: Int64, title: String?, description: String?, photoId: Int64?, author: String?, publishedDate: Int32?) { + self.flags = flags + self.url = url + self.webpageId = webpageId + self.title = title + self.description = description + self.photoId = photoId + self.author = author + self.publishedDate = publishedDate + } + } + case pageRelatedArticle(Cons_pageRelatedArticle) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .pageRelatedArticle(let _data): + if boxed { + buffer.appendInt32(-1282352120) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + serializeInt64(_data.webpageId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.description!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt64(_data.photoId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.author!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.publishedDate!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .pageRelatedArticle(let _data): + return ("pageRelatedArticle", [("flags", _data.flags as Any), ("url", _data.url as Any), ("webpageId", _data.webpageId as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("photoId", _data.photoId as Any), ("author", _data.author as Any), ("publishedDate", _data.publishedDate as Any)]) + } + } + public static func parse_pageRelatedArticle(_ reader: BufferReader) -> PageRelatedArticle? { var _1: Int32? _1 = reader.readInt32() @@ -198,15 +278,25 @@ public extension Api { var _3: Int64? _3 = reader.readInt64() var _4: String? - if Int(_1!) & Int(1 << 0) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) + } var _5: String? - if Int(_1!) & Int(1 << 1) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _5 = parseString(reader) + } var _6: Int64? - if Int(_1!) & Int(1 << 2) != 0 {_6 = reader.readInt64() } + if Int(_1!) & Int(1 << 2) != 0 { + _6 = reader.readInt64() + } var _7: String? - if Int(_1!) & Int(1 << 3) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 3) != 0 { + _7 = parseString(reader) + } var _8: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_8 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _8 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -215,146 +305,179 @@ public extension Api { let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil let _c7 = (Int(_1!) & Int(1 << 3) == 0) || _7 != nil let _c8 = (Int(_1!) & Int(1 << 4) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.PageRelatedArticle.pageRelatedArticle(flags: _1!, url: _2!, webpageId: _3!, title: _4, description: _5, photoId: _6, author: _7, publishedDate: _8) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.PageRelatedArticle.pageRelatedArticle(Cons_pageRelatedArticle(flags: _1!, url: _2!, webpageId: _3!, title: _4, description: _5, photoId: _6, author: _7, publishedDate: _8)) + } + else { + return nil + } } - } } public extension Api { indirect enum PageTableCell: TypeConstructorDescription { - case pageTableCell(flags: Int32, text: Api.RichText?, colspan: Int32?, rowspan: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .pageTableCell(let flags, let text, let colspan, let rowspan): - if boxed { - buffer.appendInt32(878078826) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 7) != 0 {text!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(colspan!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(rowspan!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .pageTableCell(let flags, let text, let colspan, let rowspan): - return ("pageTableCell", [("flags", flags as Any), ("text", text as Any), ("colspan", colspan as Any), ("rowspan", rowspan as Any)]) - } - } - + public class Cons_pageTableCell { + public var flags: Int32 + public var text: Api.RichText? + public var colspan: Int32? + public var rowspan: Int32? + public init(flags: Int32, text: Api.RichText?, colspan: Int32?, rowspan: Int32?) { + self.flags = flags + self.text = text + self.colspan = colspan + self.rowspan = rowspan + } + } + case pageTableCell(Cons_pageTableCell) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .pageTableCell(let _data): + if boxed { + buffer.appendInt32(878078826) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 7) != 0 { + _data.text!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.colspan!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.rowspan!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .pageTableCell(let _data): + return ("pageTableCell", [("flags", _data.flags as Any), ("text", _data.text as Any), ("colspan", _data.colspan as Any), ("rowspan", _data.rowspan as Any)]) + } + } + public static func parse_pageTableCell(_ reader: BufferReader) -> PageTableCell? { var _1: Int32? _1 = reader.readInt32() var _2: Api.RichText? - if Int(_1!) & Int(1 << 7) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.RichText - } } + if Int(_1!) & Int(1 << 7) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.RichText + } + } var _3: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _3 = reader.readInt32() + } var _4: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _4 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 7) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.PageTableCell.pageTableCell(flags: _1!, text: _2, colspan: _3, rowspan: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.PageTableCell.pageTableCell(Cons_pageTableCell(flags: _1!, text: _2, colspan: _3, rowspan: _4)) + } + else { + return nil + } } - } } public extension Api { enum PageTableRow: TypeConstructorDescription { - case pageTableRow(cells: [Api.PageTableCell]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .pageTableRow(let cells): - if boxed { - buffer.appendInt32(-524237339) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(cells.count)) - for item in cells { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .pageTableRow(let cells): - return ("pageTableRow", [("cells", cells as Any)]) - } - } - + public class Cons_pageTableRow { + public var cells: [Api.PageTableCell] + public init(cells: [Api.PageTableCell]) { + self.cells = cells + } + } + case pageTableRow(Cons_pageTableRow) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .pageTableRow(let _data): + if boxed { + buffer.appendInt32(-524237339) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.cells.count)) + for item in _data.cells { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .pageTableRow(let _data): + return ("pageTableRow", [("cells", _data.cells as Any)]) + } + } + public static func parse_pageTableRow(_ reader: BufferReader) -> PageTableRow? { var _1: [Api.PageTableCell]? if let _ = reader.readInt32() { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PageTableCell.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PageTableRow.pageTableRow(cells: _1!) + if _c1 { + return Api.PageTableRow.pageTableRow(Cons_pageTableRow(cells: _1!)) + } + else { + return nil + } } - } } public extension Api { indirect enum PaidReactionPrivacy: TypeConstructorDescription { + public class Cons_paidReactionPrivacyPeer { + public var peer: Api.InputPeer + public init(peer: Api.InputPeer) { + self.peer = peer + } + } case paidReactionPrivacyAnonymous case paidReactionPrivacyDefault - case paidReactionPrivacyPeer(peer: Api.InputPeer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .paidReactionPrivacyAnonymous: - if boxed { - buffer.appendInt32(520887001) - } - - break - case .paidReactionPrivacyDefault: - if boxed { - buffer.appendInt32(543872158) - } - - break - case .paidReactionPrivacyPeer(let peer): - if boxed { - buffer.appendInt32(-596837136) - } - peer.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .paidReactionPrivacyAnonymous: + case paidReactionPrivacyPeer(Cons_paidReactionPrivacyPeer) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .paidReactionPrivacyAnonymous: + if boxed { + buffer.appendInt32(520887001) + } + break + case .paidReactionPrivacyDefault: + if boxed { + buffer.appendInt32(543872158) + } + break + case .paidReactionPrivacyPeer(let _data): + if boxed { + buffer.appendInt32(-596837136) + } + _data.peer.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .paidReactionPrivacyAnonymous: return ("paidReactionPrivacyAnonymous", []) - case .paidReactionPrivacyDefault: + case .paidReactionPrivacyDefault: return ("paidReactionPrivacyDefault", []) - case .paidReactionPrivacyPeer(let peer): - return ("paidReactionPrivacyPeer", [("peer", peer as Any)]) - } - } - + case .paidReactionPrivacyPeer(let _data): + return ("paidReactionPrivacyPeer", [("peer", _data.peer as Any)]) + } + } + public static func parse_paidReactionPrivacyAnonymous(_ reader: BufferReader) -> PaidReactionPrivacy? { return Api.PaidReactionPrivacy.paidReactionPrivacyAnonymous } @@ -367,39 +490,62 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.InputPeer } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PaidReactionPrivacy.paidReactionPrivacyPeer(peer: _1!) + if _c1 { + return Api.PaidReactionPrivacy.paidReactionPrivacyPeer(Cons_paidReactionPrivacyPeer(peer: _1!)) + } + else { + return nil + } } - } } public extension Api { enum Passkey: TypeConstructorDescription { - case passkey(flags: Int32, id: String, name: String, date: Int32, softwareEmojiId: Int64?, lastUsageDate: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .passkey(let flags, let id, let name, let date, let softwareEmojiId, let lastUsageDate): - if boxed { - buffer.appendInt32(-1738457409) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(id, buffer: buffer, boxed: false) - serializeString(name, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(softwareEmojiId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(lastUsageDate!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .passkey(let flags, let id, let name, let date, let softwareEmojiId, let lastUsageDate): - return ("passkey", [("flags", flags as Any), ("id", id as Any), ("name", name as Any), ("date", date as Any), ("softwareEmojiId", softwareEmojiId as Any), ("lastUsageDate", lastUsageDate as Any)]) - } - } - + public class Cons_passkey { + public var flags: Int32 + public var id: String + public var name: String + public var date: Int32 + public var softwareEmojiId: Int64? + public var lastUsageDate: Int32? + public init(flags: Int32, id: String, name: String, date: Int32, softwareEmojiId: Int64?, lastUsageDate: Int32?) { + self.flags = flags + self.id = id + self.name = name + self.date = date + self.softwareEmojiId = softwareEmojiId + self.lastUsageDate = lastUsageDate + } + } + case passkey(Cons_passkey) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .passkey(let _data): + if boxed { + buffer.appendInt32(-1738457409) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.id, buffer: buffer, boxed: false) + serializeString(_data.name, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.softwareEmojiId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.lastUsageDate!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .passkey(let _data): + return ("passkey", [("flags", _data.flags as Any), ("id", _data.id as Any), ("name", _data.name as Any), ("date", _data.date as Any), ("softwareEmojiId", _data.softwareEmojiId as Any), ("lastUsageDate", _data.lastUsageDate as Any)]) + } + } + public static func parse_passkey(_ reader: BufferReader) -> Passkey? { var _1: Int32? _1 = reader.readInt32() @@ -410,60 +556,73 @@ public extension Api { var _4: Int32? _4 = reader.readInt32() var _5: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_5 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _5 = reader.readInt64() + } var _6: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _6 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.Passkey.passkey(flags: _1!, id: _2!, name: _3!, date: _4!, softwareEmojiId: _5, lastUsageDate: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.Passkey.passkey(Cons_passkey(flags: _1!, id: _2!, name: _3!, date: _4!, softwareEmojiId: _5, lastUsageDate: _6)) + } + else { + return nil + } } - } } public extension Api { enum PasswordKdfAlgo: TypeConstructorDescription { - case passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow(salt1: Buffer, salt2: Buffer, g: Int32, p: Buffer) + public class Cons_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow { + public var salt1: Buffer + public var salt2: Buffer + public var g: Int32 + public var p: Buffer + public init(salt1: Buffer, salt2: Buffer, g: Int32, p: Buffer) { + self.salt1 = salt1 + self.salt2 = salt2 + self.g = g + self.p = p + } + } + case passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow(Cons_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow) case passwordKdfAlgoUnknown - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow(let salt1, let salt2, let g, let p): - if boxed { - buffer.appendInt32(982592842) - } - serializeBytes(salt1, buffer: buffer, boxed: false) - serializeBytes(salt2, buffer: buffer, boxed: false) - serializeInt32(g, buffer: buffer, boxed: false) - serializeBytes(p, buffer: buffer, boxed: false) - break - case .passwordKdfAlgoUnknown: - if boxed { - buffer.appendInt32(-732254058) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow(let salt1, let salt2, let g, let p): - return ("passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow", [("salt1", salt1 as Any), ("salt2", salt2 as Any), ("g", g as Any), ("p", p as Any)]) - case .passwordKdfAlgoUnknown: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow(let _data): + if boxed { + buffer.appendInt32(982592842) + } + serializeBytes(_data.salt1, buffer: buffer, boxed: false) + serializeBytes(_data.salt2, buffer: buffer, boxed: false) + serializeInt32(_data.g, buffer: buffer, boxed: false) + serializeBytes(_data.p, buffer: buffer, boxed: false) + break + case .passwordKdfAlgoUnknown: + if boxed { + buffer.appendInt32(-732254058) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow(let _data): + return ("passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow", [("salt1", _data.salt1 as Any), ("salt2", _data.salt2 as Any), ("g", _data.g as Any), ("p", _data.p as Any)]) + case .passwordKdfAlgoUnknown: return ("passwordKdfAlgoUnknown", []) - } - } - + } + } + public static func parse_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow(_ reader: BufferReader) -> PasswordKdfAlgo? { var _1: Buffer? _1 = parseBytes(reader) @@ -477,41 +636,49 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.PasswordKdfAlgo.passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow(salt1: _1!, salt2: _2!, g: _3!, p: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.PasswordKdfAlgo.passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow(Cons_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow(salt1: _1!, salt2: _2!, g: _3!, p: _4!)) + } + else { + return nil + } } public static func parse_passwordKdfAlgoUnknown(_ reader: BufferReader) -> PasswordKdfAlgo? { return Api.PasswordKdfAlgo.passwordKdfAlgoUnknown } - } } public extension Api { enum PaymentCharge: TypeConstructorDescription { - case paymentCharge(id: String, providerChargeId: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .paymentCharge(let id, let providerChargeId): - if boxed { - buffer.appendInt32(-368917890) - } - serializeString(id, buffer: buffer, boxed: false) - serializeString(providerChargeId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .paymentCharge(let id, let providerChargeId): - return ("paymentCharge", [("id", id as Any), ("providerChargeId", providerChargeId as Any)]) - } - } - + public class Cons_paymentCharge { + public var id: String + public var providerChargeId: String + public init(id: String, providerChargeId: String) { + self.id = id + self.providerChargeId = providerChargeId + } + } + case paymentCharge(Cons_paymentCharge) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .paymentCharge(let _data): + if boxed { + buffer.appendInt32(-368917890) + } + serializeString(_data.id, buffer: buffer, boxed: false) + serializeString(_data.providerChargeId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .paymentCharge(let _data): + return ("paymentCharge", [("id", _data.id as Any), ("providerChargeId", _data.providerChargeId as Any)]) + } + } + public static func parse_paymentCharge(_ reader: BufferReader) -> PaymentCharge? { var _1: String? _1 = parseString(reader) @@ -519,36 +686,46 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PaymentCharge.paymentCharge(id: _1!, providerChargeId: _2!) + if _c1 && _c2 { + return Api.PaymentCharge.paymentCharge(Cons_paymentCharge(id: _1!, providerChargeId: _2!)) + } + else { + return nil + } } - } } public extension Api { enum PaymentFormMethod: TypeConstructorDescription { - case paymentFormMethod(url: String, title: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .paymentFormMethod(let url, let title): - if boxed { - buffer.appendInt32(-1996951013) - } - serializeString(url, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .paymentFormMethod(let url, let title): - return ("paymentFormMethod", [("url", url as Any), ("title", title as Any)]) - } - } - + public class Cons_paymentFormMethod { + public var url: String + public var title: String + public init(url: String, title: String) { + self.url = url + self.title = title + } + } + case paymentFormMethod(Cons_paymentFormMethod) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .paymentFormMethod(let _data): + if boxed { + buffer.appendInt32(-1996951013) + } + serializeString(_data.url, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .paymentFormMethod(let _data): + return ("paymentFormMethod", [("url", _data.url as Any), ("title", _data.title as Any)]) + } + } + public static func parse_paymentFormMethod(_ reader: BufferReader) -> PaymentFormMethod? { var _1: String? _1 = parseString(reader) @@ -556,90 +733,129 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PaymentFormMethod.paymentFormMethod(url: _1!, title: _2!) + if _c1 && _c2 { + return Api.PaymentFormMethod.paymentFormMethod(Cons_paymentFormMethod(url: _1!, title: _2!)) + } + else { + return nil + } } - } } public extension Api { enum PaymentRequestedInfo: TypeConstructorDescription { - case paymentRequestedInfo(flags: Int32, name: String?, phone: String?, email: String?, shippingAddress: Api.PostAddress?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .paymentRequestedInfo(let flags, let name, let phone, let email, let shippingAddress): - if boxed { - buffer.appendInt32(-1868808300) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(name!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(phone!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(email!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {shippingAddress!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .paymentRequestedInfo(let flags, let name, let phone, let email, let shippingAddress): - return ("paymentRequestedInfo", [("flags", flags as Any), ("name", name as Any), ("phone", phone as Any), ("email", email as Any), ("shippingAddress", shippingAddress as Any)]) - } - } - + public class Cons_paymentRequestedInfo { + public var flags: Int32 + public var name: String? + public var phone: String? + public var email: String? + public var shippingAddress: Api.PostAddress? + public init(flags: Int32, name: String?, phone: String?, email: String?, shippingAddress: Api.PostAddress?) { + self.flags = flags + self.name = name + self.phone = phone + self.email = email + self.shippingAddress = shippingAddress + } + } + case paymentRequestedInfo(Cons_paymentRequestedInfo) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .paymentRequestedInfo(let _data): + if boxed { + buffer.appendInt32(-1868808300) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.name!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.phone!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.email!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.shippingAddress!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .paymentRequestedInfo(let _data): + return ("paymentRequestedInfo", [("flags", _data.flags as Any), ("name", _data.name as Any), ("phone", _data.phone as Any), ("email", _data.email as Any), ("shippingAddress", _data.shippingAddress as Any)]) + } + } + public static func parse_paymentRequestedInfo(_ reader: BufferReader) -> PaymentRequestedInfo? { var _1: Int32? _1 = reader.readInt32() var _2: String? - if Int(_1!) & Int(1 << 0) != 0 {_2 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = parseString(reader) + } var _3: String? - if Int(_1!) & Int(1 << 1) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _3 = parseString(reader) + } var _4: String? - if Int(_1!) & Int(1 << 2) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _4 = parseString(reader) + } var _5: Api.PostAddress? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.PostAddress - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.PostAddress + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 3) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.PaymentRequestedInfo.paymentRequestedInfo(flags: _1!, name: _2, phone: _3, email: _4, shippingAddress: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.PaymentRequestedInfo.paymentRequestedInfo(Cons_paymentRequestedInfo(flags: _1!, name: _2, phone: _3, email: _4, shippingAddress: _5)) + } + else { + return nil + } } - } } public extension Api { enum PaymentSavedCredentials: TypeConstructorDescription { - case paymentSavedCredentialsCard(id: String, title: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .paymentSavedCredentialsCard(let id, let title): - if boxed { - buffer.appendInt32(-842892769) - } - serializeString(id, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .paymentSavedCredentialsCard(let id, let title): - return ("paymentSavedCredentialsCard", [("id", id as Any), ("title", title as Any)]) - } - } - + public class Cons_paymentSavedCredentialsCard { + public var id: String + public var title: String + public init(id: String, title: String) { + self.id = id + self.title = title + } + } + case paymentSavedCredentialsCard(Cons_paymentSavedCredentialsCard) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .paymentSavedCredentialsCard(let _data): + if boxed { + buffer.appendInt32(-842892769) + } + serializeString(_data.id, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .paymentSavedCredentialsCard(let _data): + return ("paymentSavedCredentialsCard", [("id", _data.id as Any), ("title", _data.title as Any)]) + } + } + public static func parse_paymentSavedCredentialsCard(_ reader: BufferReader) -> PaymentSavedCredentials? { var _1: String? _1 = parseString(reader) @@ -647,100 +863,139 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PaymentSavedCredentials.paymentSavedCredentialsCard(id: _1!, title: _2!) + if _c1 && _c2 { + return Api.PaymentSavedCredentials.paymentSavedCredentialsCard(Cons_paymentSavedCredentialsCard(id: _1!, title: _2!)) + } + else { + return nil + } } - } } public extension Api { enum Peer: TypeConstructorDescription { - case peerChannel(channelId: Int64) - case peerChat(chatId: Int64) - case peerUser(userId: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .peerChannel(let channelId): - if boxed { - buffer.appendInt32(-1566230754) - } - serializeInt64(channelId, buffer: buffer, boxed: false) - break - case .peerChat(let chatId): - if boxed { - buffer.appendInt32(918946202) - } - serializeInt64(chatId, buffer: buffer, boxed: false) - break - case .peerUser(let userId): - if boxed { - buffer.appendInt32(1498486562) - } - serializeInt64(userId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .peerChannel(let channelId): - return ("peerChannel", [("channelId", channelId as Any)]) - case .peerChat(let chatId): - return ("peerChat", [("chatId", chatId as Any)]) - case .peerUser(let userId): - return ("peerUser", [("userId", userId as Any)]) - } - } - + public class Cons_peerChannel { + public var channelId: Int64 + public init(channelId: Int64) { + self.channelId = channelId + } + } + public class Cons_peerChat { + public var chatId: Int64 + public init(chatId: Int64) { + self.chatId = chatId + } + } + public class Cons_peerUser { + public var userId: Int64 + public init(userId: Int64) { + self.userId = userId + } + } + case peerChannel(Cons_peerChannel) + case peerChat(Cons_peerChat) + case peerUser(Cons_peerUser) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .peerChannel(let _data): + if boxed { + buffer.appendInt32(-1566230754) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + break + case .peerChat(let _data): + if boxed { + buffer.appendInt32(918946202) + } + serializeInt64(_data.chatId, buffer: buffer, boxed: false) + break + case .peerUser(let _data): + if boxed { + buffer.appendInt32(1498486562) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .peerChannel(let _data): + return ("peerChannel", [("channelId", _data.channelId as Any)]) + case .peerChat(let _data): + return ("peerChat", [("chatId", _data.chatId as Any)]) + case .peerUser(let _data): + return ("peerUser", [("userId", _data.userId as Any)]) + } + } + public static func parse_peerChannel(_ reader: BufferReader) -> Peer? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Peer.peerChannel(channelId: _1!) + if _c1 { + return Api.Peer.peerChannel(Cons_peerChannel(channelId: _1!)) + } + else { + return nil + } } public static func parse_peerChat(_ reader: BufferReader) -> Peer? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Peer.peerChat(chatId: _1!) + if _c1 { + return Api.Peer.peerChat(Cons_peerChat(chatId: _1!)) + } + else { + return nil + } } public static func parse_peerUser(_ reader: BufferReader) -> Peer? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Peer.peerUser(userId: _1!) + if _c1 { + return Api.Peer.peerUser(Cons_peerUser(userId: _1!)) + } + else { + return nil + } } - } } public extension Api { enum PeerBlocked: TypeConstructorDescription { - case peerBlocked(peerId: Api.Peer, date: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .peerBlocked(let peerId, let date): - if boxed { - buffer.appendInt32(-386039788) - } - peerId.serialize(buffer, true) - serializeInt32(date, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .peerBlocked(let peerId, let date): - return ("peerBlocked", [("peerId", peerId as Any), ("date", date as Any)]) - } - } - + public class Cons_peerBlocked { + public var peerId: Api.Peer + public var date: Int32 + public init(peerId: Api.Peer, date: Int32) { + self.peerId = peerId + self.date = date + } + } + case peerBlocked(Cons_peerBlocked) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .peerBlocked(let _data): + if boxed { + buffer.appendInt32(-386039788) + } + _data.peerId.serialize(buffer, true) + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .peerBlocked(let _data): + return ("peerBlocked", [("peerId", _data.peerId as Any), ("date", _data.date as Any)]) + } + } + public static func parse_peerBlocked(_ reader: BufferReader) -> PeerBlocked? { var _1: Api.Peer? if let signature = reader.readInt32() { @@ -750,91 +1005,147 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PeerBlocked.peerBlocked(peerId: _1!, date: _2!) + if _c1 && _c2 { + return Api.PeerBlocked.peerBlocked(Cons_peerBlocked(peerId: _1!, date: _2!)) + } + else { + return nil + } } - } } public extension Api { enum PeerColor: TypeConstructorDescription { - case inputPeerColorCollectible(collectibleId: Int64) - case peerColor(flags: Int32, color: Int32?, backgroundEmojiId: Int64?) - case peerColorCollectible(flags: Int32, collectibleId: Int64, giftEmojiId: Int64, backgroundEmojiId: Int64, accentColor: Int32, colors: [Int32], darkAccentColor: Int32?, darkColors: [Int32]?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputPeerColorCollectible(let collectibleId): - if boxed { - buffer.appendInt32(-1192589655) - } - serializeInt64(collectibleId, buffer: buffer, boxed: false) - break - case .peerColor(let flags, let color, let backgroundEmojiId): - if boxed { - buffer.appendInt32(-1253352753) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(color!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt64(backgroundEmojiId!, buffer: buffer, boxed: false)} - break - case .peerColorCollectible(let flags, let collectibleId, let giftEmojiId, let backgroundEmojiId, let accentColor, let colors, let darkAccentColor, let darkColors): - if boxed { - buffer.appendInt32(-1178573926) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(collectibleId, buffer: buffer, boxed: false) - serializeInt64(giftEmojiId, buffer: buffer, boxed: false) - serializeInt64(backgroundEmojiId, buffer: buffer, boxed: false) - serializeInt32(accentColor, buffer: buffer, boxed: false) + public class Cons_inputPeerColorCollectible { + public var collectibleId: Int64 + public init(collectibleId: Int64) { + self.collectibleId = collectibleId + } + } + public class Cons_peerColor { + public var flags: Int32 + public var color: Int32? + public var backgroundEmojiId: Int64? + public init(flags: Int32, color: Int32?, backgroundEmojiId: Int64?) { + self.flags = flags + self.color = color + self.backgroundEmojiId = backgroundEmojiId + } + } + public class Cons_peerColorCollectible { + public var flags: Int32 + public var collectibleId: Int64 + public var giftEmojiId: Int64 + public var backgroundEmojiId: Int64 + public var accentColor: Int32 + public var colors: [Int32] + public var darkAccentColor: Int32? + public var darkColors: [Int32]? + public init(flags: Int32, collectibleId: Int64, giftEmojiId: Int64, backgroundEmojiId: Int64, accentColor: Int32, colors: [Int32], darkAccentColor: Int32?, darkColors: [Int32]?) { + self.flags = flags + self.collectibleId = collectibleId + self.giftEmojiId = giftEmojiId + self.backgroundEmojiId = backgroundEmojiId + self.accentColor = accentColor + self.colors = colors + self.darkAccentColor = darkAccentColor + self.darkColors = darkColors + } + } + case inputPeerColorCollectible(Cons_inputPeerColorCollectible) + case peerColor(Cons_peerColor) + case peerColorCollectible(Cons_peerColorCollectible) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputPeerColorCollectible(let _data): + if boxed { + buffer.appendInt32(-1192589655) + } + serializeInt64(_data.collectibleId, buffer: buffer, boxed: false) + break + case .peerColor(let _data): + if boxed { + buffer.appendInt32(-1253352753) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.color!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt64(_data.backgroundEmojiId!, buffer: buffer, boxed: false) + } + break + case .peerColorCollectible(let _data): + if boxed { + buffer.appendInt32(-1178573926) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.collectibleId, buffer: buffer, boxed: false) + serializeInt64(_data.giftEmojiId, buffer: buffer, boxed: false) + serializeInt64(_data.backgroundEmojiId, buffer: buffer, boxed: false) + serializeInt32(_data.accentColor, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.colors.count)) + for item in _data.colors { + serializeInt32(item, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.darkAccentColor!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(colors.count)) - for item in colors { + buffer.appendInt32(Int32(_data.darkColors!.count)) + for item in _data.darkColors! { serializeInt32(item, buffer: buffer, boxed: false) } - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(darkAccentColor!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(darkColors!.count)) - for item in darkColors! { - serializeInt32(item, buffer: buffer, boxed: false) - }} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputPeerColorCollectible(let collectibleId): - return ("inputPeerColorCollectible", [("collectibleId", collectibleId as Any)]) - case .peerColor(let flags, let color, let backgroundEmojiId): - return ("peerColor", [("flags", flags as Any), ("color", color as Any), ("backgroundEmojiId", backgroundEmojiId as Any)]) - case .peerColorCollectible(let flags, let collectibleId, let giftEmojiId, let backgroundEmojiId, let accentColor, let colors, let darkAccentColor, let darkColors): - return ("peerColorCollectible", [("flags", flags as Any), ("collectibleId", collectibleId as Any), ("giftEmojiId", giftEmojiId as Any), ("backgroundEmojiId", backgroundEmojiId as Any), ("accentColor", accentColor as Any), ("colors", colors as Any), ("darkAccentColor", darkAccentColor as Any), ("darkColors", darkColors as Any)]) - } - } - + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputPeerColorCollectible(let _data): + return ("inputPeerColorCollectible", [("collectibleId", _data.collectibleId as Any)]) + case .peerColor(let _data): + return ("peerColor", [("flags", _data.flags as Any), ("color", _data.color as Any), ("backgroundEmojiId", _data.backgroundEmojiId as Any)]) + case .peerColorCollectible(let _data): + return ("peerColorCollectible", [("flags", _data.flags as Any), ("collectibleId", _data.collectibleId as Any), ("giftEmojiId", _data.giftEmojiId as Any), ("backgroundEmojiId", _data.backgroundEmojiId as Any), ("accentColor", _data.accentColor as Any), ("colors", _data.colors as Any), ("darkAccentColor", _data.darkAccentColor as Any), ("darkColors", _data.darkColors as Any)]) + } + } + public static func parse_inputPeerColorCollectible(_ reader: BufferReader) -> PeerColor? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PeerColor.inputPeerColorCollectible(collectibleId: _1!) + if _c1 { + return Api.PeerColor.inputPeerColorCollectible(Cons_inputPeerColorCollectible(collectibleId: _1!)) + } + else { + return nil + } } public static func parse_peerColor(_ reader: BufferReader) -> PeerColor? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt32() + } var _3: Int64? - if Int(_1!) & Int(1 << 1) != 0 {_3 = reader.readInt64() } + if Int(_1!) & Int(1 << 1) != 0 { + _3 = reader.readInt64() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.PeerColor.peerColor(flags: _1!, color: _2, backgroundEmojiId: _3) + if _c1 && _c2 && _c3 { + return Api.PeerColor.peerColor(Cons_peerColor(flags: _1!, color: _2, backgroundEmojiId: _3)) + } + else { + return nil + } } public static func parse_peerColorCollectible(_ reader: BufferReader) -> PeerColor? { var _1: Int32? @@ -852,11 +1163,15 @@ public extension Api { _6 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) } var _7: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_7 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _7 = reader.readInt32() + } var _8: [Int32]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _8 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _8 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -865,52 +1180,64 @@ public extension Api { let _c6 = _6 != nil let _c7 = (Int(_1!) & Int(1 << 0) == 0) || _7 != nil let _c8 = (Int(_1!) & Int(1 << 1) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.PeerColor.peerColorCollectible(flags: _1!, collectibleId: _2!, giftEmojiId: _3!, backgroundEmojiId: _4!, accentColor: _5!, colors: _6!, darkAccentColor: _7, darkColors: _8) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.PeerColor.peerColorCollectible(Cons_peerColorCollectible(flags: _1!, collectibleId: _2!, giftEmojiId: _3!, backgroundEmojiId: _4!, accentColor: _5!, colors: _6!, darkAccentColor: _7, darkColors: _8)) + } + else { + return nil + } } - } } public extension Api { enum PeerLocated: TypeConstructorDescription { - case peerLocated(peer: Api.Peer, expires: Int32, distance: Int32) - case peerSelfLocated(expires: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .peerLocated(let peer, let expires, let distance): - if boxed { - buffer.appendInt32(-901375139) - } - peer.serialize(buffer, true) - serializeInt32(expires, buffer: buffer, boxed: false) - serializeInt32(distance, buffer: buffer, boxed: false) - break - case .peerSelfLocated(let expires): - if boxed { - buffer.appendInt32(-118740917) - } - serializeInt32(expires, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .peerLocated(let peer, let expires, let distance): - return ("peerLocated", [("peer", peer as Any), ("expires", expires as Any), ("distance", distance as Any)]) - case .peerSelfLocated(let expires): - return ("peerSelfLocated", [("expires", expires as Any)]) - } - } - + public class Cons_peerLocated { + public var peer: Api.Peer + public var expires: Int32 + public var distance: Int32 + public init(peer: Api.Peer, expires: Int32, distance: Int32) { + self.peer = peer + self.expires = expires + self.distance = distance + } + } + public class Cons_peerSelfLocated { + public var expires: Int32 + public init(expires: Int32) { + self.expires = expires + } + } + case peerLocated(Cons_peerLocated) + case peerSelfLocated(Cons_peerSelfLocated) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .peerLocated(let _data): + if boxed { + buffer.appendInt32(-901375139) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.expires, buffer: buffer, boxed: false) + serializeInt32(_data.distance, buffer: buffer, boxed: false) + break + case .peerSelfLocated(let _data): + if boxed { + buffer.appendInt32(-118740917) + } + serializeInt32(_data.expires, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .peerLocated(let _data): + return ("peerLocated", [("peer", _data.peer as Any), ("expires", _data.expires as Any), ("distance", _data.distance as Any)]) + case .peerSelfLocated(let _data): + return ("peerSelfLocated", [("expires", _data.expires as Any)]) + } + } + public static func parse_peerLocated(_ reader: BufferReader) -> PeerLocated? { var _1: Api.Peer? if let signature = reader.readInt32() { @@ -923,99 +1250,176 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.PeerLocated.peerLocated(peer: _1!, expires: _2!, distance: _3!) + if _c1 && _c2 && _c3 { + return Api.PeerLocated.peerLocated(Cons_peerLocated(peer: _1!, expires: _2!, distance: _3!)) + } + else { + return nil + } } public static func parse_peerSelfLocated(_ reader: BufferReader) -> PeerLocated? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PeerLocated.peerSelfLocated(expires: _1!) + if _c1 { + return Api.PeerLocated.peerSelfLocated(Cons_peerSelfLocated(expires: _1!)) + } + else { + return nil + } } - } } public extension Api { enum PeerNotifySettings: TypeConstructorDescription { - case peerNotifySettings(flags: Int32, showPreviews: Api.Bool?, silent: Api.Bool?, muteUntil: Int32?, iosSound: Api.NotificationSound?, androidSound: Api.NotificationSound?, otherSound: Api.NotificationSound?, storiesMuted: Api.Bool?, storiesHideSender: Api.Bool?, storiesIosSound: Api.NotificationSound?, storiesAndroidSound: Api.NotificationSound?, storiesOtherSound: Api.NotificationSound?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .peerNotifySettings(let flags, let showPreviews, let silent, let muteUntil, let iosSound, let androidSound, let otherSound, let storiesMuted, let storiesHideSender, let storiesIosSound, let storiesAndroidSound, let storiesOtherSound): - if boxed { - buffer.appendInt32(-1721619444) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {showPreviews!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {silent!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(muteUntil!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {iosSound!.serialize(buffer, true)} - if Int(flags) & Int(1 << 4) != 0 {androidSound!.serialize(buffer, true)} - if Int(flags) & Int(1 << 5) != 0 {otherSound!.serialize(buffer, true)} - if Int(flags) & Int(1 << 6) != 0 {storiesMuted!.serialize(buffer, true)} - if Int(flags) & Int(1 << 7) != 0 {storiesHideSender!.serialize(buffer, true)} - if Int(flags) & Int(1 << 8) != 0 {storiesIosSound!.serialize(buffer, true)} - if Int(flags) & Int(1 << 9) != 0 {storiesAndroidSound!.serialize(buffer, true)} - if Int(flags) & Int(1 << 10) != 0 {storiesOtherSound!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .peerNotifySettings(let flags, let showPreviews, let silent, let muteUntil, let iosSound, let androidSound, let otherSound, let storiesMuted, let storiesHideSender, let storiesIosSound, let storiesAndroidSound, let storiesOtherSound): - return ("peerNotifySettings", [("flags", flags as Any), ("showPreviews", showPreviews as Any), ("silent", silent as Any), ("muteUntil", muteUntil as Any), ("iosSound", iosSound as Any), ("androidSound", androidSound as Any), ("otherSound", otherSound as Any), ("storiesMuted", storiesMuted as Any), ("storiesHideSender", storiesHideSender as Any), ("storiesIosSound", storiesIosSound as Any), ("storiesAndroidSound", storiesAndroidSound as Any), ("storiesOtherSound", storiesOtherSound as Any)]) - } - } - + public class Cons_peerNotifySettings { + public var flags: Int32 + public var showPreviews: Api.Bool? + public var silent: Api.Bool? + public var muteUntil: Int32? + public var iosSound: Api.NotificationSound? + public var androidSound: Api.NotificationSound? + public var otherSound: Api.NotificationSound? + public var storiesMuted: Api.Bool? + public var storiesHideSender: Api.Bool? + public var storiesIosSound: Api.NotificationSound? + public var storiesAndroidSound: Api.NotificationSound? + public var storiesOtherSound: Api.NotificationSound? + public init(flags: Int32, showPreviews: Api.Bool?, silent: Api.Bool?, muteUntil: Int32?, iosSound: Api.NotificationSound?, androidSound: Api.NotificationSound?, otherSound: Api.NotificationSound?, storiesMuted: Api.Bool?, storiesHideSender: Api.Bool?, storiesIosSound: Api.NotificationSound?, storiesAndroidSound: Api.NotificationSound?, storiesOtherSound: Api.NotificationSound?) { + self.flags = flags + self.showPreviews = showPreviews + self.silent = silent + self.muteUntil = muteUntil + self.iosSound = iosSound + self.androidSound = androidSound + self.otherSound = otherSound + self.storiesMuted = storiesMuted + self.storiesHideSender = storiesHideSender + self.storiesIosSound = storiesIosSound + self.storiesAndroidSound = storiesAndroidSound + self.storiesOtherSound = storiesOtherSound + } + } + case peerNotifySettings(Cons_peerNotifySettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .peerNotifySettings(let _data): + if boxed { + buffer.appendInt32(-1721619444) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.showPreviews!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.silent!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.muteUntil!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.iosSound!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + _data.androidSound!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + _data.otherSound!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + _data.storiesMuted!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 7) != 0 { + _data.storiesHideSender!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + _data.storiesIosSound!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 9) != 0 { + _data.storiesAndroidSound!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.storiesOtherSound!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .peerNotifySettings(let _data): + return ("peerNotifySettings", [("flags", _data.flags as Any), ("showPreviews", _data.showPreviews as Any), ("silent", _data.silent as Any), ("muteUntil", _data.muteUntil as Any), ("iosSound", _data.iosSound as Any), ("androidSound", _data.androidSound as Any), ("otherSound", _data.otherSound as Any), ("storiesMuted", _data.storiesMuted as Any), ("storiesHideSender", _data.storiesHideSender as Any), ("storiesIosSound", _data.storiesIosSound as Any), ("storiesAndroidSound", _data.storiesAndroidSound as Any), ("storiesOtherSound", _data.storiesOtherSound as Any)]) + } + } + public static func parse_peerNotifySettings(_ reader: BufferReader) -> PeerNotifySettings? { var _1: Int32? _1 = reader.readInt32() var _2: Api.Bool? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Bool + } + } var _3: Api.Bool? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Bool + } + } var _4: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _4 = reader.readInt32() + } var _5: Api.NotificationSound? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.NotificationSound - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.NotificationSound + } + } var _6: Api.NotificationSound? - if Int(_1!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.NotificationSound - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.NotificationSound + } + } var _7: Api.NotificationSound? - if Int(_1!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.NotificationSound - } } + if Int(_1!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.NotificationSound + } + } var _8: Api.Bool? - if Int(_1!) & Int(1 << 6) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 6) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.Bool + } + } var _9: Api.Bool? - if Int(_1!) & Int(1 << 7) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 7) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.Bool + } + } var _10: Api.NotificationSound? - if Int(_1!) & Int(1 << 8) != 0 {if let signature = reader.readInt32() { - _10 = Api.parse(reader, signature: signature) as? Api.NotificationSound - } } + if Int(_1!) & Int(1 << 8) != 0 { + if let signature = reader.readInt32() { + _10 = Api.parse(reader, signature: signature) as? Api.NotificationSound + } + } var _11: Api.NotificationSound? - if Int(_1!) & Int(1 << 9) != 0 {if let signature = reader.readInt32() { - _11 = Api.parse(reader, signature: signature) as? Api.NotificationSound - } } + if Int(_1!) & Int(1 << 9) != 0 { + if let signature = reader.readInt32() { + _11 = Api.parse(reader, signature: signature) as? Api.NotificationSound + } + } var _12: Api.NotificationSound? - if Int(_1!) & Int(1 << 10) != 0 {if let signature = reader.readInt32() { - _12 = Api.parse(reader, signature: signature) as? Api.NotificationSound - } } + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _12 = Api.parse(reader, signature: signature) as? Api.NotificationSound + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil @@ -1028,78 +1432,136 @@ public extension Api { let _c10 = (Int(_1!) & Int(1 << 8) == 0) || _10 != nil let _c11 = (Int(_1!) & Int(1 << 9) == 0) || _11 != nil let _c12 = (Int(_1!) & Int(1 << 10) == 0) || _12 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - return Api.PeerNotifySettings.peerNotifySettings(flags: _1!, showPreviews: _2, silent: _3, muteUntil: _4, iosSound: _5, androidSound: _6, otherSound: _7, storiesMuted: _8, storiesHideSender: _9, storiesIosSound: _10, storiesAndroidSound: _11, storiesOtherSound: _12) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 { + return Api.PeerNotifySettings.peerNotifySettings(Cons_peerNotifySettings(flags: _1!, showPreviews: _2, silent: _3, muteUntil: _4, iosSound: _5, androidSound: _6, otherSound: _7, storiesMuted: _8, storiesHideSender: _9, storiesIosSound: _10, storiesAndroidSound: _11, storiesOtherSound: _12)) + } + else { + return nil + } } - } } public extension Api { enum PeerSettings: TypeConstructorDescription { - case peerSettings(flags: Int32, geoDistance: Int32?, requestChatTitle: String?, requestChatDate: Int32?, businessBotId: Int64?, businessBotManageUrl: String?, chargePaidMessageStars: Int64?, registrationMonth: String?, phoneCountry: String?, nameChangeDate: Int32?, photoChangeDate: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .peerSettings(let flags, let geoDistance, let requestChatTitle, let requestChatDate, let businessBotId, let businessBotManageUrl, let chargePaidMessageStars, let registrationMonth, let phoneCountry, let nameChangeDate, let photoChangeDate): - if boxed { - buffer.appendInt32(-193510921) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 6) != 0 {serializeInt32(geoDistance!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 9) != 0 {serializeString(requestChatTitle!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 9) != 0 {serializeInt32(requestChatDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 13) != 0 {serializeInt64(businessBotId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 13) != 0 {serializeString(businessBotManageUrl!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 14) != 0 {serializeInt64(chargePaidMessageStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 15) != 0 {serializeString(registrationMonth!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 16) != 0 {serializeString(phoneCountry!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 17) != 0 {serializeInt32(nameChangeDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 18) != 0 {serializeInt32(photoChangeDate!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .peerSettings(let flags, let geoDistance, let requestChatTitle, let requestChatDate, let businessBotId, let businessBotManageUrl, let chargePaidMessageStars, let registrationMonth, let phoneCountry, let nameChangeDate, let photoChangeDate): - return ("peerSettings", [("flags", flags as Any), ("geoDistance", geoDistance as Any), ("requestChatTitle", requestChatTitle as Any), ("requestChatDate", requestChatDate as Any), ("businessBotId", businessBotId as Any), ("businessBotManageUrl", businessBotManageUrl as Any), ("chargePaidMessageStars", chargePaidMessageStars as Any), ("registrationMonth", registrationMonth as Any), ("phoneCountry", phoneCountry as Any), ("nameChangeDate", nameChangeDate as Any), ("photoChangeDate", photoChangeDate as Any)]) - } - } - + public class Cons_peerSettings { + public var flags: Int32 + public var geoDistance: Int32? + public var requestChatTitle: String? + public var requestChatDate: Int32? + public var businessBotId: Int64? + public var businessBotManageUrl: String? + public var chargePaidMessageStars: Int64? + public var registrationMonth: String? + public var phoneCountry: String? + public var nameChangeDate: Int32? + public var photoChangeDate: Int32? + public init(flags: Int32, geoDistance: Int32?, requestChatTitle: String?, requestChatDate: Int32?, businessBotId: Int64?, businessBotManageUrl: String?, chargePaidMessageStars: Int64?, registrationMonth: String?, phoneCountry: String?, nameChangeDate: Int32?, photoChangeDate: Int32?) { + self.flags = flags + self.geoDistance = geoDistance + self.requestChatTitle = requestChatTitle + self.requestChatDate = requestChatDate + self.businessBotId = businessBotId + self.businessBotManageUrl = businessBotManageUrl + self.chargePaidMessageStars = chargePaidMessageStars + self.registrationMonth = registrationMonth + self.phoneCountry = phoneCountry + self.nameChangeDate = nameChangeDate + self.photoChangeDate = photoChangeDate + } + } + case peerSettings(Cons_peerSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .peerSettings(let _data): + if boxed { + buffer.appendInt32(-193510921) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 6) != 0 { + serializeInt32(_data.geoDistance!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 9) != 0 { + serializeString(_data.requestChatTitle!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 9) != 0 { + serializeInt32(_data.requestChatDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 13) != 0 { + serializeInt64(_data.businessBotId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 13) != 0 { + serializeString(_data.businessBotManageUrl!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 14) != 0 { + serializeInt64(_data.chargePaidMessageStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 15) != 0 { + serializeString(_data.registrationMonth!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 16) != 0 { + serializeString(_data.phoneCountry!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 17) != 0 { + serializeInt32(_data.nameChangeDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 18) != 0 { + serializeInt32(_data.photoChangeDate!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .peerSettings(let _data): + return ("peerSettings", [("flags", _data.flags as Any), ("geoDistance", _data.geoDistance as Any), ("requestChatTitle", _data.requestChatTitle as Any), ("requestChatDate", _data.requestChatDate as Any), ("businessBotId", _data.businessBotId as Any), ("businessBotManageUrl", _data.businessBotManageUrl as Any), ("chargePaidMessageStars", _data.chargePaidMessageStars as Any), ("registrationMonth", _data.registrationMonth as Any), ("phoneCountry", _data.phoneCountry as Any), ("nameChangeDate", _data.nameChangeDate as Any), ("photoChangeDate", _data.photoChangeDate as Any)]) + } + } + public static func parse_peerSettings(_ reader: BufferReader) -> PeerSettings? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? - if Int(_1!) & Int(1 << 6) != 0 {_2 = reader.readInt32() } + if Int(_1!) & Int(1 << 6) != 0 { + _2 = reader.readInt32() + } var _3: String? - if Int(_1!) & Int(1 << 9) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 9) != 0 { + _3 = parseString(reader) + } var _4: Int32? - if Int(_1!) & Int(1 << 9) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 9) != 0 { + _4 = reader.readInt32() + } var _5: Int64? - if Int(_1!) & Int(1 << 13) != 0 {_5 = reader.readInt64() } + if Int(_1!) & Int(1 << 13) != 0 { + _5 = reader.readInt64() + } var _6: String? - if Int(_1!) & Int(1 << 13) != 0 {_6 = parseString(reader) } + if Int(_1!) & Int(1 << 13) != 0 { + _6 = parseString(reader) + } var _7: Int64? - if Int(_1!) & Int(1 << 14) != 0 {_7 = reader.readInt64() } + if Int(_1!) & Int(1 << 14) != 0 { + _7 = reader.readInt64() + } var _8: String? - if Int(_1!) & Int(1 << 15) != 0 {_8 = parseString(reader) } + if Int(_1!) & Int(1 << 15) != 0 { + _8 = parseString(reader) + } var _9: String? - if Int(_1!) & Int(1 << 16) != 0 {_9 = parseString(reader) } + if Int(_1!) & Int(1 << 16) != 0 { + _9 = parseString(reader) + } var _10: Int32? - if Int(_1!) & Int(1 << 17) != 0 {_10 = reader.readInt32() } + if Int(_1!) & Int(1 << 17) != 0 { + _10 = reader.readInt32() + } var _11: Int32? - if Int(_1!) & Int(1 << 18) != 0 {_11 = reader.readInt32() } + if Int(_1!) & Int(1 << 18) != 0 { + _11 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 6) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 9) == 0) || _3 != nil @@ -1111,51 +1573,58 @@ public extension Api { let _c9 = (Int(_1!) & Int(1 << 16) == 0) || _9 != nil let _c10 = (Int(_1!) & Int(1 << 17) == 0) || _10 != nil let _c11 = (Int(_1!) & Int(1 << 18) == 0) || _11 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - return Api.PeerSettings.peerSettings(flags: _1!, geoDistance: _2, requestChatTitle: _3, requestChatDate: _4, businessBotId: _5, businessBotManageUrl: _6, chargePaidMessageStars: _7, registrationMonth: _8, phoneCountry: _9, nameChangeDate: _10, photoChangeDate: _11) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 { + return Api.PeerSettings.peerSettings(Cons_peerSettings(flags: _1!, geoDistance: _2, requestChatTitle: _3, requestChatDate: _4, businessBotId: _5, businessBotManageUrl: _6, chargePaidMessageStars: _7, registrationMonth: _8, phoneCountry: _9, nameChangeDate: _10, photoChangeDate: _11)) + } + else { + return nil + } } - } } public extension Api { enum PeerStories: TypeConstructorDescription { - case peerStories(flags: Int32, peer: Api.Peer, maxReadId: Int32?, stories: [Api.StoryItem]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .peerStories(let flags, let peer, let maxReadId, let stories): - if boxed { - buffer.appendInt32(-1707742823) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(maxReadId!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stories.count)) - for item in stories { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .peerStories(let flags, let peer, let maxReadId, let stories): - return ("peerStories", [("flags", flags as Any), ("peer", peer as Any), ("maxReadId", maxReadId as Any), ("stories", stories as Any)]) - } - } - + public class Cons_peerStories { + public var flags: Int32 + public var peer: Api.Peer + public var maxReadId: Int32? + public var stories: [Api.StoryItem] + public init(flags: Int32, peer: Api.Peer, maxReadId: Int32?, stories: [Api.StoryItem]) { + self.flags = flags + self.peer = peer + self.maxReadId = maxReadId + self.stories = stories + } + } + case peerStories(Cons_peerStories) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .peerStories(let _data): + if boxed { + buffer.appendInt32(-1707742823) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.maxReadId!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.stories.count)) + for item in _data.stories { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .peerStories(let _data): + return ("peerStories", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("maxReadId", _data.maxReadId as Any), ("stories", _data.stories as Any)]) + } + } + public static func parse_peerStories(_ reader: BufferReader) -> PeerStories? { var _1: Int32? _1 = reader.readInt32() @@ -1164,7 +1633,9 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.Peer } var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } var _4: [Api.StoryItem]? if let _ = reader.readInt32() { _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StoryItem.self) @@ -1173,40 +1644,52 @@ public extension Api { let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.PeerStories.peerStories(flags: _1!, peer: _2!, maxReadId: _3, stories: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.PeerStories.peerStories(Cons_peerStories(flags: _1!, peer: _2!, maxReadId: _3, stories: _4!)) + } + else { + return nil + } } - } } public extension Api { enum PendingSuggestion: TypeConstructorDescription { - case pendingSuggestion(suggestion: String, title: Api.TextWithEntities, description: Api.TextWithEntities, url: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .pendingSuggestion(let suggestion, let title, let description, let url): - if boxed { - buffer.appendInt32(-404214254) - } - serializeString(suggestion, buffer: buffer, boxed: false) - title.serialize(buffer, true) - description.serialize(buffer, true) - serializeString(url, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .pendingSuggestion(let suggestion, let title, let description, let url): - return ("pendingSuggestion", [("suggestion", suggestion as Any), ("title", title as Any), ("description", description as Any), ("url", url as Any)]) - } - } - + public class Cons_pendingSuggestion { + public var suggestion: String + public var title: Api.TextWithEntities + public var description: Api.TextWithEntities + public var url: String + public init(suggestion: String, title: Api.TextWithEntities, description: Api.TextWithEntities, url: String) { + self.suggestion = suggestion + self.title = title + self.description = description + self.url = url + } + } + case pendingSuggestion(Cons_pendingSuggestion) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .pendingSuggestion(let _data): + if boxed { + buffer.appendInt32(-404214254) + } + serializeString(_data.suggestion, buffer: buffer, boxed: false) + _data.title.serialize(buffer, true) + _data.description.serialize(buffer, true) + serializeString(_data.url, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .pendingSuggestion(let _data): + return ("pendingSuggestion", [("suggestion", _data.suggestion as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("url", _data.url as Any)]) + } + } + public static func parse_pendingSuggestion(_ reader: BufferReader) -> PendingSuggestion? { var _1: String? _1 = parseString(reader) @@ -1224,121 +1707,235 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.PendingSuggestion.pendingSuggestion(suggestion: _1!, title: _2!, description: _3!, url: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.PendingSuggestion.pendingSuggestion(Cons_pendingSuggestion(suggestion: _1!, title: _2!, description: _3!, url: _4!)) + } + else { + return nil + } } - } } public extension Api { enum PhoneCall: TypeConstructorDescription { - case phoneCall(flags: Int32, id: Int64, accessHash: Int64, date: Int32, adminId: Int64, participantId: Int64, gAOrB: Buffer, keyFingerprint: Int64, protocol: Api.PhoneCallProtocol, connections: [Api.PhoneConnection], startDate: Int32, customParameters: Api.DataJSON?) - case phoneCallAccepted(flags: Int32, id: Int64, accessHash: Int64, date: Int32, adminId: Int64, participantId: Int64, gB: Buffer, protocol: Api.PhoneCallProtocol) - case phoneCallDiscarded(flags: Int32, id: Int64, reason: Api.PhoneCallDiscardReason?, duration: Int32?) - case phoneCallEmpty(id: Int64) - case phoneCallRequested(flags: Int32, id: Int64, accessHash: Int64, date: Int32, adminId: Int64, participantId: Int64, gAHash: Buffer, protocol: Api.PhoneCallProtocol) - case phoneCallWaiting(flags: Int32, id: Int64, accessHash: Int64, date: Int32, adminId: Int64, participantId: Int64, protocol: Api.PhoneCallProtocol, receiveDate: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .phoneCall(let flags, let id, let accessHash, let date, let adminId, let participantId, let gAOrB, let keyFingerprint, let `protocol`, let connections, let startDate, let customParameters): - if boxed { - buffer.appendInt32(810769141) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(adminId, buffer: buffer, boxed: false) - serializeInt64(participantId, buffer: buffer, boxed: false) - serializeBytes(gAOrB, buffer: buffer, boxed: false) - serializeInt64(keyFingerprint, buffer: buffer, boxed: false) - `protocol`.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(connections.count)) - for item in connections { - item.serialize(buffer, true) - } - serializeInt32(startDate, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 7) != 0 {customParameters!.serialize(buffer, true)} - break - case .phoneCallAccepted(let flags, let id, let accessHash, let date, let adminId, let participantId, let gB, let `protocol`): - if boxed { - buffer.appendInt32(912311057) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(adminId, buffer: buffer, boxed: false) - serializeInt64(participantId, buffer: buffer, boxed: false) - serializeBytes(gB, buffer: buffer, boxed: false) - `protocol`.serialize(buffer, true) - break - case .phoneCallDiscarded(let flags, let id, let reason, let duration): - if boxed { - buffer.appendInt32(1355435489) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {reason!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(duration!, buffer: buffer, boxed: false)} - break - case .phoneCallEmpty(let id): - if boxed { - buffer.appendInt32(1399245077) - } - serializeInt64(id, buffer: buffer, boxed: false) - break - case .phoneCallRequested(let flags, let id, let accessHash, let date, let adminId, let participantId, let gAHash, let `protocol`): - if boxed { - buffer.appendInt32(347139340) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(adminId, buffer: buffer, boxed: false) - serializeInt64(participantId, buffer: buffer, boxed: false) - serializeBytes(gAHash, buffer: buffer, boxed: false) - `protocol`.serialize(buffer, true) - break - case .phoneCallWaiting(let flags, let id, let accessHash, let date, let adminId, let participantId, let `protocol`, let receiveDate): - if boxed { - buffer.appendInt32(-987599081) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(adminId, buffer: buffer, boxed: false) - serializeInt64(participantId, buffer: buffer, boxed: false) - `protocol`.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(receiveDate!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .phoneCall(let flags, let id, let accessHash, let date, let adminId, let participantId, let gAOrB, let keyFingerprint, let `protocol`, let connections, let startDate, let customParameters): - return ("phoneCall", [("flags", flags as Any), ("id", id as Any), ("accessHash", accessHash as Any), ("date", date as Any), ("adminId", adminId as Any), ("participantId", participantId as Any), ("gAOrB", gAOrB as Any), ("keyFingerprint", keyFingerprint as Any), ("`protocol`", `protocol` as Any), ("connections", connections as Any), ("startDate", startDate as Any), ("customParameters", customParameters as Any)]) - case .phoneCallAccepted(let flags, let id, let accessHash, let date, let adminId, let participantId, let gB, let `protocol`): - return ("phoneCallAccepted", [("flags", flags as Any), ("id", id as Any), ("accessHash", accessHash as Any), ("date", date as Any), ("adminId", adminId as Any), ("participantId", participantId as Any), ("gB", gB as Any), ("`protocol`", `protocol` as Any)]) - case .phoneCallDiscarded(let flags, let id, let reason, let duration): - return ("phoneCallDiscarded", [("flags", flags as Any), ("id", id as Any), ("reason", reason as Any), ("duration", duration as Any)]) - case .phoneCallEmpty(let id): - return ("phoneCallEmpty", [("id", id as Any)]) - case .phoneCallRequested(let flags, let id, let accessHash, let date, let adminId, let participantId, let gAHash, let `protocol`): - return ("phoneCallRequested", [("flags", flags as Any), ("id", id as Any), ("accessHash", accessHash as Any), ("date", date as Any), ("adminId", adminId as Any), ("participantId", participantId as Any), ("gAHash", gAHash as Any), ("`protocol`", `protocol` as Any)]) - case .phoneCallWaiting(let flags, let id, let accessHash, let date, let adminId, let participantId, let `protocol`, let receiveDate): - return ("phoneCallWaiting", [("flags", flags as Any), ("id", id as Any), ("accessHash", accessHash as Any), ("date", date as Any), ("adminId", adminId as Any), ("participantId", participantId as Any), ("`protocol`", `protocol` as Any), ("receiveDate", receiveDate as Any)]) - } - } - + public class Cons_phoneCall { + public var flags: Int32 + public var id: Int64 + public var accessHash: Int64 + public var date: Int32 + public var adminId: Int64 + public var participantId: Int64 + public var gAOrB: Buffer + public var keyFingerprint: Int64 + public var `protocol`: Api.PhoneCallProtocol + public var connections: [Api.PhoneConnection] + public var startDate: Int32 + public var customParameters: Api.DataJSON? + public init(flags: Int32, id: Int64, accessHash: Int64, date: Int32, adminId: Int64, participantId: Int64, gAOrB: Buffer, keyFingerprint: Int64, `protocol`: Api.PhoneCallProtocol, connections: [Api.PhoneConnection], startDate: Int32, customParameters: Api.DataJSON?) { + self.flags = flags + self.id = id + self.accessHash = accessHash + self.date = date + self.adminId = adminId + self.participantId = participantId + self.gAOrB = gAOrB + self.keyFingerprint = keyFingerprint + self.`protocol` = `protocol` + self.connections = connections + self.startDate = startDate + self.customParameters = customParameters + } + } + public class Cons_phoneCallAccepted { + public var flags: Int32 + public var id: Int64 + public var accessHash: Int64 + public var date: Int32 + public var adminId: Int64 + public var participantId: Int64 + public var gB: Buffer + public var `protocol`: Api.PhoneCallProtocol + public init(flags: Int32, id: Int64, accessHash: Int64, date: Int32, adminId: Int64, participantId: Int64, gB: Buffer, `protocol`: Api.PhoneCallProtocol) { + self.flags = flags + self.id = id + self.accessHash = accessHash + self.date = date + self.adminId = adminId + self.participantId = participantId + self.gB = gB + self.`protocol` = `protocol` + } + } + public class Cons_phoneCallDiscarded { + public var flags: Int32 + public var id: Int64 + public var reason: Api.PhoneCallDiscardReason? + public var duration: Int32? + public init(flags: Int32, id: Int64, reason: Api.PhoneCallDiscardReason?, duration: Int32?) { + self.flags = flags + self.id = id + self.reason = reason + self.duration = duration + } + } + public class Cons_phoneCallEmpty { + public var id: Int64 + public init(id: Int64) { + self.id = id + } + } + public class Cons_phoneCallRequested { + public var flags: Int32 + public var id: Int64 + public var accessHash: Int64 + public var date: Int32 + public var adminId: Int64 + public var participantId: Int64 + public var gAHash: Buffer + public var `protocol`: Api.PhoneCallProtocol + public init(flags: Int32, id: Int64, accessHash: Int64, date: Int32, adminId: Int64, participantId: Int64, gAHash: Buffer, `protocol`: Api.PhoneCallProtocol) { + self.flags = flags + self.id = id + self.accessHash = accessHash + self.date = date + self.adminId = adminId + self.participantId = participantId + self.gAHash = gAHash + self.`protocol` = `protocol` + } + } + public class Cons_phoneCallWaiting { + public var flags: Int32 + public var id: Int64 + public var accessHash: Int64 + public var date: Int32 + public var adminId: Int64 + public var participantId: Int64 + public var `protocol`: Api.PhoneCallProtocol + public var receiveDate: Int32? + public init(flags: Int32, id: Int64, accessHash: Int64, date: Int32, adminId: Int64, participantId: Int64, `protocol`: Api.PhoneCallProtocol, receiveDate: Int32?) { + self.flags = flags + self.id = id + self.accessHash = accessHash + self.date = date + self.adminId = adminId + self.participantId = participantId + self.`protocol` = `protocol` + self.receiveDate = receiveDate + } + } + case phoneCall(Cons_phoneCall) + case phoneCallAccepted(Cons_phoneCallAccepted) + case phoneCallDiscarded(Cons_phoneCallDiscarded) + case phoneCallEmpty(Cons_phoneCallEmpty) + case phoneCallRequested(Cons_phoneCallRequested) + case phoneCallWaiting(Cons_phoneCallWaiting) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .phoneCall(let _data): + if boxed { + buffer.appendInt32(810769141) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.adminId, buffer: buffer, boxed: false) + serializeInt64(_data.participantId, buffer: buffer, boxed: false) + serializeBytes(_data.gAOrB, buffer: buffer, boxed: false) + serializeInt64(_data.keyFingerprint, buffer: buffer, boxed: false) + _data.`protocol`.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.connections.count)) + for item in _data.connections { + item.serialize(buffer, true) + } + serializeInt32(_data.startDate, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 7) != 0 { + _data.customParameters!.serialize(buffer, true) + } + break + case .phoneCallAccepted(let _data): + if boxed { + buffer.appendInt32(912311057) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.adminId, buffer: buffer, boxed: false) + serializeInt64(_data.participantId, buffer: buffer, boxed: false) + serializeBytes(_data.gB, buffer: buffer, boxed: false) + _data.`protocol`.serialize(buffer, true) + break + case .phoneCallDiscarded(let _data): + if boxed { + buffer.appendInt32(1355435489) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.reason!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.duration!, buffer: buffer, boxed: false) + } + break + case .phoneCallEmpty(let _data): + if boxed { + buffer.appendInt32(1399245077) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + break + case .phoneCallRequested(let _data): + if boxed { + buffer.appendInt32(347139340) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.adminId, buffer: buffer, boxed: false) + serializeInt64(_data.participantId, buffer: buffer, boxed: false) + serializeBytes(_data.gAHash, buffer: buffer, boxed: false) + _data.`protocol`.serialize(buffer, true) + break + case .phoneCallWaiting(let _data): + if boxed { + buffer.appendInt32(-987599081) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.adminId, buffer: buffer, boxed: false) + serializeInt64(_data.participantId, buffer: buffer, boxed: false) + _data.`protocol`.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.receiveDate!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .phoneCall(let _data): + return ("phoneCall", [("flags", _data.flags as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("date", _data.date as Any), ("adminId", _data.adminId as Any), ("participantId", _data.participantId as Any), ("gAOrB", _data.gAOrB as Any), ("keyFingerprint", _data.keyFingerprint as Any), ("`protocol`", _data.`protocol` as Any), ("connections", _data.connections as Any), ("startDate", _data.startDate as Any), ("customParameters", _data.customParameters as Any)]) + case .phoneCallAccepted(let _data): + return ("phoneCallAccepted", [("flags", _data.flags as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("date", _data.date as Any), ("adminId", _data.adminId as Any), ("participantId", _data.participantId as Any), ("gB", _data.gB as Any), ("`protocol`", _data.`protocol` as Any)]) + case .phoneCallDiscarded(let _data): + return ("phoneCallDiscarded", [("flags", _data.flags as Any), ("id", _data.id as Any), ("reason", _data.reason as Any), ("duration", _data.duration as Any)]) + case .phoneCallEmpty(let _data): + return ("phoneCallEmpty", [("id", _data.id as Any)]) + case .phoneCallRequested(let _data): + return ("phoneCallRequested", [("flags", _data.flags as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("date", _data.date as Any), ("adminId", _data.adminId as Any), ("participantId", _data.participantId as Any), ("gAHash", _data.gAHash as Any), ("`protocol`", _data.`protocol` as Any)]) + case .phoneCallWaiting(let _data): + return ("phoneCallWaiting", [("flags", _data.flags as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("date", _data.date as Any), ("adminId", _data.adminId as Any), ("participantId", _data.participantId as Any), ("`protocol`", _data.`protocol` as Any), ("receiveDate", _data.receiveDate as Any)]) + } + } + public static func parse_phoneCall(_ reader: BufferReader) -> PhoneCall? { var _1: Int32? _1 = reader.readInt32() @@ -1367,9 +1964,11 @@ public extension Api { var _11: Int32? _11 = reader.readInt32() var _12: Api.DataJSON? - if Int(_1!) & Int(1 << 7) != 0 {if let signature = reader.readInt32() { - _12 = Api.parse(reader, signature: signature) as? Api.DataJSON - } } + if Int(_1!) & Int(1 << 7) != 0 { + if let signature = reader.readInt32() { + _12 = Api.parse(reader, signature: signature) as? Api.DataJSON + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -1382,19 +1981,12 @@ public extension Api { let _c10 = _10 != nil let _c11 = _11 != nil let _c12 = (Int(_1!) & Int(1 << 7) == 0) || _12 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - return Api.PhoneCall.phoneCall(flags: _1!, id: _2!, accessHash: _3!, date: _4!, adminId: _5!, participantId: _6!, gAOrB: _7!, keyFingerprint: _8!, protocol: _9!, connections: _10!, startDate: _11!, customParameters: _12) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 { + return Api.PhoneCall.phoneCall(Cons_phoneCall(flags: _1!, id: _2!, accessHash: _3!, date: _4!, adminId: _5!, participantId: _6!, gAOrB: _7!, keyFingerprint: _8!, protocol: _9!, connections: _10!, startDate: _11!, customParameters: _12)) + } + else { + return nil + } } public static func parse_phoneCallAccepted(_ reader: BufferReader) -> PhoneCall? { var _1: Int32? @@ -1423,15 +2015,12 @@ public extension Api { let _c6 = _6 != nil let _c7 = _7 != nil let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.PhoneCall.phoneCallAccepted(flags: _1!, id: _2!, accessHash: _3!, date: _4!, adminId: _5!, participantId: _6!, gB: _7!, protocol: _8!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.PhoneCall.phoneCallAccepted(Cons_phoneCallAccepted(flags: _1!, id: _2!, accessHash: _3!, date: _4!, adminId: _5!, participantId: _6!, gB: _7!, protocol: _8!)) + } + else { + return nil + } } public static func parse_phoneCallDiscarded(_ reader: BufferReader) -> PhoneCall? { var _1: Int32? @@ -1439,27 +2028,36 @@ public extension Api { var _2: Int64? _2 = reader.readInt64() var _3: Api.PhoneCallDiscardReason? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.PhoneCallDiscardReason - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.PhoneCallDiscardReason + } + } var _4: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.PhoneCall.phoneCallDiscarded(flags: _1!, id: _2!, reason: _3, duration: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.PhoneCall.phoneCallDiscarded(Cons_phoneCallDiscarded(flags: _1!, id: _2!, reason: _3, duration: _4)) + } + else { + return nil + } } public static func parse_phoneCallEmpty(_ reader: BufferReader) -> PhoneCall? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PhoneCall.phoneCallEmpty(id: _1!) + if _c1 { + return Api.PhoneCall.phoneCallEmpty(Cons_phoneCallEmpty(id: _1!)) + } + else { + return nil + } } public static func parse_phoneCallRequested(_ reader: BufferReader) -> PhoneCall? { var _1: Int32? @@ -1488,15 +2086,12 @@ public extension Api { let _c6 = _6 != nil let _c7 = _7 != nil let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.PhoneCall.phoneCallRequested(flags: _1!, id: _2!, accessHash: _3!, date: _4!, adminId: _5!, participantId: _6!, gAHash: _7!, protocol: _8!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.PhoneCall.phoneCallRequested(Cons_phoneCallRequested(flags: _1!, id: _2!, accessHash: _3!, date: _4!, adminId: _5!, participantId: _6!, gAHash: _7!, protocol: _8!)) + } + else { + return nil + } } public static func parse_phoneCallWaiting(_ reader: BufferReader) -> PhoneCall? { var _1: Int32? @@ -1516,7 +2111,9 @@ public extension Api { _7 = Api.parse(reader, signature: signature) as? Api.PhoneCallProtocol } var _8: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_8 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _8 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -1525,16 +2122,12 @@ public extension Api { let _c6 = _6 != nil let _c7 = _7 != nil let _c8 = (Int(_1!) & Int(1 << 0) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.PhoneCall.phoneCallWaiting(flags: _1!, id: _2!, accessHash: _3!, date: _4!, adminId: _5!, participantId: _6!, protocol: _7!, receiveDate: _8) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.PhoneCall.phoneCallWaiting(Cons_phoneCallWaiting(flags: _1!, id: _2!, accessHash: _3!, date: _4!, adminId: _5!, participantId: _6!, protocol: _7!, receiveDate: _8)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api2.swift b/submodules/TelegramApi/Sources/Api2.swift index 3bc728b1..fb227263 100644 --- a/submodules/TelegramApi/Sources/Api2.swift +++ b/submodules/TelegramApi/Sources/Api2.swift @@ -1,30 +1,48 @@ public extension Api { enum BotBusinessConnection: TypeConstructorDescription { - case botBusinessConnection(flags: Int32, connectionId: String, userId: Int64, dcId: Int32, date: Int32, rights: Api.BusinessBotRights?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botBusinessConnection(let flags, let connectionId, let userId, let dcId, let date, let rights): - if boxed { - buffer.appendInt32(-1892371723) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(connectionId, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt32(dcId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {rights!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botBusinessConnection(let flags, let connectionId, let userId, let dcId, let date, let rights): - return ("botBusinessConnection", [("flags", flags as Any), ("connectionId", connectionId as Any), ("userId", userId as Any), ("dcId", dcId as Any), ("date", date as Any), ("rights", rights as Any)]) - } - } - + public class Cons_botBusinessConnection { + public var flags: Int32 + public var connectionId: String + public var userId: Int64 + public var dcId: Int32 + public var date: Int32 + public var rights: Api.BusinessBotRights? + public init(flags: Int32, connectionId: String, userId: Int64, dcId: Int32, date: Int32, rights: Api.BusinessBotRights?) { + self.flags = flags + self.connectionId = connectionId + self.userId = userId + self.dcId = dcId + self.date = date + self.rights = rights + } + } + case botBusinessConnection(Cons_botBusinessConnection) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botBusinessConnection(let _data): + if boxed { + buffer.appendInt32(-1892371723) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.connectionId, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt32(_data.dcId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.rights!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botBusinessConnection(let _data): + return ("botBusinessConnection", [("flags", _data.flags as Any), ("connectionId", _data.connectionId as Any), ("userId", _data.userId as Any), ("dcId", _data.dcId as Any), ("date", _data.date as Any), ("rights", _data.rights as Any)]) + } + } + public static func parse_botBusinessConnection(_ reader: BufferReader) -> BotBusinessConnection? { var _1: Int32? _1 = reader.readInt32() @@ -37,49 +55,57 @@ public extension Api { var _5: Int32? _5 = reader.readInt32() var _6: Api.BusinessBotRights? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.BusinessBotRights - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.BusinessBotRights + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.BotBusinessConnection.botBusinessConnection(flags: _1!, connectionId: _2!, userId: _3!, dcId: _4!, date: _5!, rights: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.BotBusinessConnection.botBusinessConnection(Cons_botBusinessConnection(flags: _1!, connectionId: _2!, userId: _3!, dcId: _4!, date: _5!, rights: _6)) + } + else { + return nil + } } - } } public extension Api { enum BotCommand: TypeConstructorDescription { - case botCommand(command: String, description: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botCommand(let command, let description): - if boxed { - buffer.appendInt32(-1032140601) - } - serializeString(command, buffer: buffer, boxed: false) - serializeString(description, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botCommand(let command, let description): - return ("botCommand", [("command", command as Any), ("description", description as Any)]) - } - } - + public class Cons_botCommand { + public var command: String + public var description: String + public init(command: String, description: String) { + self.command = command + self.description = description + } + } + case botCommand(Cons_botCommand) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botCommand(let _data): + if boxed { + buffer.appendInt32(-1032140601) + } + serializeString(_data.command, buffer: buffer, boxed: false) + serializeString(_data.description, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botCommand(let _data): + return ("botCommand", [("command", _data.command as Any), ("description", _data.description as Any)]) + } + } + public static func parse_botCommand(_ reader: BufferReader) -> BotCommand? { var _1: String? _1 = parseString(reader) @@ -87,90 +113,108 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.BotCommand.botCommand(command: _1!, description: _2!) + if _c1 && _c2 { + return Api.BotCommand.botCommand(Cons_botCommand(command: _1!, description: _2!)) + } + else { + return nil + } } - } } public extension Api { indirect enum BotCommandScope: TypeConstructorDescription { + public class Cons_botCommandScopePeer { + public var peer: Api.InputPeer + public init(peer: Api.InputPeer) { + self.peer = peer + } + } + public class Cons_botCommandScopePeerAdmins { + public var peer: Api.InputPeer + public init(peer: Api.InputPeer) { + self.peer = peer + } + } + public class Cons_botCommandScopePeerUser { + public var peer: Api.InputPeer + public var userId: Api.InputUser + public init(peer: Api.InputPeer, userId: Api.InputUser) { + self.peer = peer + self.userId = userId + } + } case botCommandScopeChatAdmins case botCommandScopeChats case botCommandScopeDefault - case botCommandScopePeer(peer: Api.InputPeer) - case botCommandScopePeerAdmins(peer: Api.InputPeer) - case botCommandScopePeerUser(peer: Api.InputPeer, userId: Api.InputUser) + case botCommandScopePeer(Cons_botCommandScopePeer) + case botCommandScopePeerAdmins(Cons_botCommandScopePeerAdmins) + case botCommandScopePeerUser(Cons_botCommandScopePeerUser) case botCommandScopeUsers - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botCommandScopeChatAdmins: - if boxed { - buffer.appendInt32(-1180016534) - } - - break - case .botCommandScopeChats: - if boxed { - buffer.appendInt32(1877059713) - } - - break - case .botCommandScopeDefault: - if boxed { - buffer.appendInt32(795652779) - } - - break - case .botCommandScopePeer(let peer): - if boxed { - buffer.appendInt32(-610432643) - } - peer.serialize(buffer, true) - break - case .botCommandScopePeerAdmins(let peer): - if boxed { - buffer.appendInt32(1071145937) - } - peer.serialize(buffer, true) - break - case .botCommandScopePeerUser(let peer, let userId): - if boxed { - buffer.appendInt32(169026035) - } - peer.serialize(buffer, true) - userId.serialize(buffer, true) - break - case .botCommandScopeUsers: - if boxed { - buffer.appendInt32(1011811544) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botCommandScopeChatAdmins: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botCommandScopeChatAdmins: + if boxed { + buffer.appendInt32(-1180016534) + } + break + case .botCommandScopeChats: + if boxed { + buffer.appendInt32(1877059713) + } + break + case .botCommandScopeDefault: + if boxed { + buffer.appendInt32(795652779) + } + break + case .botCommandScopePeer(let _data): + if boxed { + buffer.appendInt32(-610432643) + } + _data.peer.serialize(buffer, true) + break + case .botCommandScopePeerAdmins(let _data): + if boxed { + buffer.appendInt32(1071145937) + } + _data.peer.serialize(buffer, true) + break + case .botCommandScopePeerUser(let _data): + if boxed { + buffer.appendInt32(169026035) + } + _data.peer.serialize(buffer, true) + _data.userId.serialize(buffer, true) + break + case .botCommandScopeUsers: + if boxed { + buffer.appendInt32(1011811544) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botCommandScopeChatAdmins: return ("botCommandScopeChatAdmins", []) - case .botCommandScopeChats: + case .botCommandScopeChats: return ("botCommandScopeChats", []) - case .botCommandScopeDefault: + case .botCommandScopeDefault: return ("botCommandScopeDefault", []) - case .botCommandScopePeer(let peer): - return ("botCommandScopePeer", [("peer", peer as Any)]) - case .botCommandScopePeerAdmins(let peer): - return ("botCommandScopePeerAdmins", [("peer", peer as Any)]) - case .botCommandScopePeerUser(let peer, let userId): - return ("botCommandScopePeerUser", [("peer", peer as Any), ("userId", userId as Any)]) - case .botCommandScopeUsers: + case .botCommandScopePeer(let _data): + return ("botCommandScopePeer", [("peer", _data.peer as Any)]) + case .botCommandScopePeerAdmins(let _data): + return ("botCommandScopePeerAdmins", [("peer", _data.peer as Any)]) + case .botCommandScopePeerUser(let _data): + return ("botCommandScopePeerUser", [("peer", _data.peer as Any), ("userId", _data.userId as Any)]) + case .botCommandScopeUsers: return ("botCommandScopeUsers", []) - } - } - + } + } + public static func parse_botCommandScopeChatAdmins(_ reader: BufferReader) -> BotCommandScope? { return Api.BotCommandScope.botCommandScopeChatAdmins } @@ -186,8 +230,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.InputPeer } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.BotCommandScope.botCommandScopePeer(peer: _1!) + if _c1 { + return Api.BotCommandScope.botCommandScopePeer(Cons_botCommandScopePeer(peer: _1!)) + } + else { + return nil + } } public static func parse_botCommandScopePeerAdmins(_ reader: BufferReader) -> BotCommandScope? { var _1: Api.InputPeer? @@ -195,8 +243,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.InputPeer } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.BotCommandScope.botCommandScopePeerAdmins(peer: _1!) + if _c1 { + return Api.BotCommandScope.botCommandScopePeerAdmins(Cons_botCommandScopePeerAdmins(peer: _1!)) + } + else { + return nil + } } public static func parse_botCommandScopePeerUser(_ reader: BufferReader) -> BotCommandScope? { var _1: Api.InputPeer? @@ -209,84 +261,146 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.BotCommandScope.botCommandScopePeerUser(peer: _1!, userId: _2!) + if _c1 && _c2 { + return Api.BotCommandScope.botCommandScopePeerUser(Cons_botCommandScopePeerUser(peer: _1!, userId: _2!)) + } + else { + return nil + } } public static func parse_botCommandScopeUsers(_ reader: BufferReader) -> BotCommandScope? { return Api.BotCommandScope.botCommandScopeUsers } - } } public extension Api { enum BotInfo: TypeConstructorDescription { - case botInfo(flags: Int32, userId: Int64?, description: String?, descriptionPhoto: Api.Photo?, descriptionDocument: Api.Document?, commands: [Api.BotCommand]?, menuButton: Api.BotMenuButton?, privacyPolicyUrl: String?, appSettings: Api.BotAppSettings?, verifierSettings: Api.BotVerifierSettings?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botInfo(let flags, let userId, let description, let descriptionPhoto, let descriptionDocument, let commands, let menuButton, let privacyPolicyUrl, let appSettings, let verifierSettings): - if boxed { - buffer.appendInt32(1300890265) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(userId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(description!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {descriptionPhoto!.serialize(buffer, true)} - if Int(flags) & Int(1 << 5) != 0 {descriptionDocument!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(commands!.count)) - for item in commands! { + public class Cons_botInfo { + public var flags: Int32 + public var userId: Int64? + public var description: String? + public var descriptionPhoto: Api.Photo? + public var descriptionDocument: Api.Document? + public var commands: [Api.BotCommand]? + public var menuButton: Api.BotMenuButton? + public var privacyPolicyUrl: String? + public var appSettings: Api.BotAppSettings? + public var verifierSettings: Api.BotVerifierSettings? + public init(flags: Int32, userId: Int64?, description: String?, descriptionPhoto: Api.Photo?, descriptionDocument: Api.Document?, commands: [Api.BotCommand]?, menuButton: Api.BotMenuButton?, privacyPolicyUrl: String?, appSettings: Api.BotAppSettings?, verifierSettings: Api.BotVerifierSettings?) { + self.flags = flags + self.userId = userId + self.description = description + self.descriptionPhoto = descriptionPhoto + self.descriptionDocument = descriptionDocument + self.commands = commands + self.menuButton = menuButton + self.privacyPolicyUrl = privacyPolicyUrl + self.appSettings = appSettings + self.verifierSettings = verifierSettings + } + } + case botInfo(Cons_botInfo) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botInfo(let _data): + if boxed { + buffer.appendInt32(1300890265) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.userId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.description!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + _data.descriptionPhoto!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + _data.descriptionDocument!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.commands!.count)) + for item in _data.commands! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 3) != 0 {menuButton!.serialize(buffer, true)} - if Int(flags) & Int(1 << 7) != 0 {serializeString(privacyPolicyUrl!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {appSettings!.serialize(buffer, true)} - if Int(flags) & Int(1 << 9) != 0 {verifierSettings!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botInfo(let flags, let userId, let description, let descriptionPhoto, let descriptionDocument, let commands, let menuButton, let privacyPolicyUrl, let appSettings, let verifierSettings): - return ("botInfo", [("flags", flags as Any), ("userId", userId as Any), ("description", description as Any), ("descriptionPhoto", descriptionPhoto as Any), ("descriptionDocument", descriptionDocument as Any), ("commands", commands as Any), ("menuButton", menuButton as Any), ("privacyPolicyUrl", privacyPolicyUrl as Any), ("appSettings", appSettings as Any), ("verifierSettings", verifierSettings as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.menuButton!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 7) != 0 { + serializeString(_data.privacyPolicyUrl!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + _data.appSettings!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 9) != 0 { + _data.verifierSettings!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botInfo(let _data): + return ("botInfo", [("flags", _data.flags as Any), ("userId", _data.userId as Any), ("description", _data.description as Any), ("descriptionPhoto", _data.descriptionPhoto as Any), ("descriptionDocument", _data.descriptionDocument as Any), ("commands", _data.commands as Any), ("menuButton", _data.menuButton as Any), ("privacyPolicyUrl", _data.privacyPolicyUrl as Any), ("appSettings", _data.appSettings as Any), ("verifierSettings", _data.verifierSettings as Any)]) + } + } + public static func parse_botInfo(_ reader: BufferReader) -> BotInfo? { var _1: Int32? _1 = reader.readInt32() var _2: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt64() + } var _3: String? - if Int(_1!) & Int(1 << 1) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _3 = parseString(reader) + } var _4: Api.Photo? - if Int(_1!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Photo - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Photo + } + } var _5: Api.Document? - if Int(_1!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.Document - } } + if Int(_1!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.Document + } + } var _6: [Api.BotCommand]? - if Int(_1!) & Int(1 << 2) != 0 {if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.BotCommand.self) - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.BotCommand.self) + } + } var _7: Api.BotMenuButton? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.BotMenuButton - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.BotMenuButton + } + } var _8: String? - if Int(_1!) & Int(1 << 7) != 0 {_8 = parseString(reader) } + if Int(_1!) & Int(1 << 7) != 0 { + _8 = parseString(reader) + } var _9: Api.BotAppSettings? - if Int(_1!) & Int(1 << 8) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.BotAppSettings - } } + if Int(_1!) & Int(1 << 8) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.BotAppSettings + } + } var _10: Api.BotVerifierSettings? - if Int(_1!) & Int(1 << 9) != 0 {if let signature = reader.readInt32() { - _10 = Api.parse(reader, signature: signature) as? Api.BotVerifierSettings - } } + if Int(_1!) & Int(1 << 9) != 0 { + if let signature = reader.readInt32() { + _10 = Api.parse(reader, signature: signature) as? Api.BotVerifierSettings + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil @@ -297,164 +411,299 @@ public extension Api { let _c8 = (Int(_1!) & Int(1 << 7) == 0) || _8 != nil let _c9 = (Int(_1!) & Int(1 << 8) == 0) || _9 != nil let _c10 = (Int(_1!) & Int(1 << 9) == 0) || _10 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - return Api.BotInfo.botInfo(flags: _1!, userId: _2, description: _3, descriptionPhoto: _4, descriptionDocument: _5, commands: _6, menuButton: _7, privacyPolicyUrl: _8, appSettings: _9, verifierSettings: _10) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 { + return Api.BotInfo.botInfo(Cons_botInfo(flags: _1!, userId: _2, description: _3, descriptionPhoto: _4, descriptionDocument: _5, commands: _6, menuButton: _7, privacyPolicyUrl: _8, appSettings: _9, verifierSettings: _10)) + } + else { + return nil + } } - } } public extension Api { enum BotInlineMessage: TypeConstructorDescription { - case botInlineMessageMediaAuto(flags: Int32, message: String, entities: [Api.MessageEntity]?, replyMarkup: Api.ReplyMarkup?) - case botInlineMessageMediaContact(flags: Int32, phoneNumber: String, firstName: String, lastName: String, vcard: String, replyMarkup: Api.ReplyMarkup?) - case botInlineMessageMediaGeo(flags: Int32, geo: Api.GeoPoint, heading: Int32?, period: Int32?, proximityNotificationRadius: Int32?, replyMarkup: Api.ReplyMarkup?) - case botInlineMessageMediaInvoice(flags: Int32, title: String, description: String, photo: Api.WebDocument?, currency: String, totalAmount: Int64, replyMarkup: Api.ReplyMarkup?) - case botInlineMessageMediaVenue(flags: Int32, geo: Api.GeoPoint, title: String, address: String, provider: String, venueId: String, venueType: String, replyMarkup: Api.ReplyMarkup?) - case botInlineMessageMediaWebPage(flags: Int32, message: String, entities: [Api.MessageEntity]?, url: String, replyMarkup: Api.ReplyMarkup?) - case botInlineMessageText(flags: Int32, message: String, entities: [Api.MessageEntity]?, replyMarkup: Api.ReplyMarkup?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botInlineMessageMediaAuto(let flags, let message, let entities, let replyMarkup): - if boxed { - buffer.appendInt32(1984755728) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { + public class Cons_botInlineMessageMediaAuto { + public var flags: Int32 + public var message: String + public var entities: [Api.MessageEntity]? + public var replyMarkup: Api.ReplyMarkup? + public init(flags: Int32, message: String, entities: [Api.MessageEntity]?, replyMarkup: Api.ReplyMarkup?) { + self.flags = flags + self.message = message + self.entities = entities + self.replyMarkup = replyMarkup + } + } + public class Cons_botInlineMessageMediaContact { + public var flags: Int32 + public var phoneNumber: String + public var firstName: String + public var lastName: String + public var vcard: String + public var replyMarkup: Api.ReplyMarkup? + public init(flags: Int32, phoneNumber: String, firstName: String, lastName: String, vcard: String, replyMarkup: Api.ReplyMarkup?) { + self.flags = flags + self.phoneNumber = phoneNumber + self.firstName = firstName + self.lastName = lastName + self.vcard = vcard + self.replyMarkup = replyMarkup + } + } + public class Cons_botInlineMessageMediaGeo { + public var flags: Int32 + public var geo: Api.GeoPoint + public var heading: Int32? + public var period: Int32? + public var proximityNotificationRadius: Int32? + public var replyMarkup: Api.ReplyMarkup? + public init(flags: Int32, geo: Api.GeoPoint, heading: Int32?, period: Int32?, proximityNotificationRadius: Int32?, replyMarkup: Api.ReplyMarkup?) { + self.flags = flags + self.geo = geo + self.heading = heading + self.period = period + self.proximityNotificationRadius = proximityNotificationRadius + self.replyMarkup = replyMarkup + } + } + public class Cons_botInlineMessageMediaInvoice { + public var flags: Int32 + public var title: String + public var description: String + public var photo: Api.WebDocument? + public var currency: String + public var totalAmount: Int64 + public var replyMarkup: Api.ReplyMarkup? + public init(flags: Int32, title: String, description: String, photo: Api.WebDocument?, currency: String, totalAmount: Int64, replyMarkup: Api.ReplyMarkup?) { + self.flags = flags + self.title = title + self.description = description + self.photo = photo + self.currency = currency + self.totalAmount = totalAmount + self.replyMarkup = replyMarkup + } + } + public class Cons_botInlineMessageMediaVenue { + public var flags: Int32 + public var geo: Api.GeoPoint + public var title: String + public var address: String + public var provider: String + public var venueId: String + public var venueType: String + public var replyMarkup: Api.ReplyMarkup? + public init(flags: Int32, geo: Api.GeoPoint, title: String, address: String, provider: String, venueId: String, venueType: String, replyMarkup: Api.ReplyMarkup?) { + self.flags = flags + self.geo = geo + self.title = title + self.address = address + self.provider = provider + self.venueId = venueId + self.venueType = venueType + self.replyMarkup = replyMarkup + } + } + public class Cons_botInlineMessageMediaWebPage { + public var flags: Int32 + public var message: String + public var entities: [Api.MessageEntity]? + public var url: String + public var replyMarkup: Api.ReplyMarkup? + public init(flags: Int32, message: String, entities: [Api.MessageEntity]?, url: String, replyMarkup: Api.ReplyMarkup?) { + self.flags = flags + self.message = message + self.entities = entities + self.url = url + self.replyMarkup = replyMarkup + } + } + public class Cons_botInlineMessageText { + public var flags: Int32 + public var message: String + public var entities: [Api.MessageEntity]? + public var replyMarkup: Api.ReplyMarkup? + public init(flags: Int32, message: String, entities: [Api.MessageEntity]?, replyMarkup: Api.ReplyMarkup?) { + self.flags = flags + self.message = message + self.entities = entities + self.replyMarkup = replyMarkup + } + } + case botInlineMessageMediaAuto(Cons_botInlineMessageMediaAuto) + case botInlineMessageMediaContact(Cons_botInlineMessageMediaContact) + case botInlineMessageMediaGeo(Cons_botInlineMessageMediaGeo) + case botInlineMessageMediaInvoice(Cons_botInlineMessageMediaInvoice) + case botInlineMessageMediaVenue(Cons_botInlineMessageMediaVenue) + case botInlineMessageMediaWebPage(Cons_botInlineMessageMediaWebPage) + case botInlineMessageText(Cons_botInlineMessageText) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botInlineMessageMediaAuto(let _data): + if boxed { + buffer.appendInt32(1984755728) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.message, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - break - case .botInlineMessageMediaContact(let flags, let phoneNumber, let firstName, let lastName, let vcard, let replyMarkup): - if boxed { - buffer.appendInt32(416402882) } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(firstName, buffer: buffer, boxed: false) - serializeString(lastName, buffer: buffer, boxed: false) - serializeString(vcard, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - break - case .botInlineMessageMediaGeo(let flags, let geo, let heading, let period, let proximityNotificationRadius, let replyMarkup): - if boxed { - buffer.appendInt32(85477117) - } - serializeInt32(flags, buffer: buffer, boxed: false) - geo.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(heading!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(period!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(proximityNotificationRadius!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - break - case .botInlineMessageMediaInvoice(let flags, let title, let description, let photo, let currency, let totalAmount, let replyMarkup): - if boxed { - buffer.appendInt32(894081801) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(description, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {photo!.serialize(buffer, true)} - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(totalAmount, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - break - case .botInlineMessageMediaVenue(let flags, let geo, let title, let address, let provider, let venueId, let venueType, let replyMarkup): - if boxed { - buffer.appendInt32(-1970903652) - } - serializeInt32(flags, buffer: buffer, boxed: false) - geo.serialize(buffer, true) - serializeString(title, buffer: buffer, boxed: false) - serializeString(address, buffer: buffer, boxed: false) - serializeString(provider, buffer: buffer, boxed: false) - serializeString(venueId, buffer: buffer, boxed: false) - serializeString(venueType, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - break - case .botInlineMessageMediaWebPage(let flags, let message, let entities, let url, let replyMarkup): - if boxed { - buffer.appendInt32(-2137335386) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + break + case .botInlineMessageMediaContact(let _data): + if boxed { + buffer.appendInt32(416402882) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.phoneNumber, buffer: buffer, boxed: false) + serializeString(_data.firstName, buffer: buffer, boxed: false) + serializeString(_data.lastName, buffer: buffer, boxed: false) + serializeString(_data.vcard, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + break + case .botInlineMessageMediaGeo(let _data): + if boxed { + buffer.appendInt32(85477117) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.geo.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.heading!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.period!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.proximityNotificationRadius!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + break + case .botInlineMessageMediaInvoice(let _data): + if boxed { + buffer.appendInt32(894081801) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.description, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.photo!.serialize(buffer, true) + } + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.totalAmount, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + break + case .botInlineMessageMediaVenue(let _data): + if boxed { + buffer.appendInt32(-1970903652) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.geo.serialize(buffer, true) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.address, buffer: buffer, boxed: false) + serializeString(_data.provider, buffer: buffer, boxed: false) + serializeString(_data.venueId, buffer: buffer, boxed: false) + serializeString(_data.venueType, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + break + case .botInlineMessageMediaWebPage(let _data): + if boxed { + buffer.appendInt32(-2137335386) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.message, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { item.serialize(buffer, true) - }} - serializeString(url, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - break - case .botInlineMessageText(let flags, let message, let entities, let replyMarkup): - if boxed { - buffer.appendInt32(-1937807902) } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { + } + serializeString(_data.url, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + break + case .botInlineMessageText(let _data): + if boxed { + buffer.appendInt32(-1937807902) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.message, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botInlineMessageMediaAuto(let flags, let message, let entities, let replyMarkup): - return ("botInlineMessageMediaAuto", [("flags", flags as Any), ("message", message as Any), ("entities", entities as Any), ("replyMarkup", replyMarkup as Any)]) - case .botInlineMessageMediaContact(let flags, let phoneNumber, let firstName, let lastName, let vcard, let replyMarkup): - return ("botInlineMessageMediaContact", [("flags", flags as Any), ("phoneNumber", phoneNumber as Any), ("firstName", firstName as Any), ("lastName", lastName as Any), ("vcard", vcard as Any), ("replyMarkup", replyMarkup as Any)]) - case .botInlineMessageMediaGeo(let flags, let geo, let heading, let period, let proximityNotificationRadius, let replyMarkup): - return ("botInlineMessageMediaGeo", [("flags", flags as Any), ("geo", geo as Any), ("heading", heading as Any), ("period", period as Any), ("proximityNotificationRadius", proximityNotificationRadius as Any), ("replyMarkup", replyMarkup as Any)]) - case .botInlineMessageMediaInvoice(let flags, let title, let description, let photo, let currency, let totalAmount, let replyMarkup): - return ("botInlineMessageMediaInvoice", [("flags", flags as Any), ("title", title as Any), ("description", description as Any), ("photo", photo as Any), ("currency", currency as Any), ("totalAmount", totalAmount as Any), ("replyMarkup", replyMarkup as Any)]) - case .botInlineMessageMediaVenue(let flags, let geo, let title, let address, let provider, let venueId, let venueType, let replyMarkup): - return ("botInlineMessageMediaVenue", [("flags", flags as Any), ("geo", geo as Any), ("title", title as Any), ("address", address as Any), ("provider", provider as Any), ("venueId", venueId as Any), ("venueType", venueType as Any), ("replyMarkup", replyMarkup as Any)]) - case .botInlineMessageMediaWebPage(let flags, let message, let entities, let url, let replyMarkup): - return ("botInlineMessageMediaWebPage", [("flags", flags as Any), ("message", message as Any), ("entities", entities as Any), ("url", url as Any), ("replyMarkup", replyMarkup as Any)]) - case .botInlineMessageText(let flags, let message, let entities, let replyMarkup): - return ("botInlineMessageText", [("flags", flags as Any), ("message", message as Any), ("entities", entities as Any), ("replyMarkup", replyMarkup as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botInlineMessageMediaAuto(let _data): + return ("botInlineMessageMediaAuto", [("flags", _data.flags as Any), ("message", _data.message as Any), ("entities", _data.entities as Any), ("replyMarkup", _data.replyMarkup as Any)]) + case .botInlineMessageMediaContact(let _data): + return ("botInlineMessageMediaContact", [("flags", _data.flags as Any), ("phoneNumber", _data.phoneNumber as Any), ("firstName", _data.firstName as Any), ("lastName", _data.lastName as Any), ("vcard", _data.vcard as Any), ("replyMarkup", _data.replyMarkup as Any)]) + case .botInlineMessageMediaGeo(let _data): + return ("botInlineMessageMediaGeo", [("flags", _data.flags as Any), ("geo", _data.geo as Any), ("heading", _data.heading as Any), ("period", _data.period as Any), ("proximityNotificationRadius", _data.proximityNotificationRadius as Any), ("replyMarkup", _data.replyMarkup as Any)]) + case .botInlineMessageMediaInvoice(let _data): + return ("botInlineMessageMediaInvoice", [("flags", _data.flags as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("photo", _data.photo as Any), ("currency", _data.currency as Any), ("totalAmount", _data.totalAmount as Any), ("replyMarkup", _data.replyMarkup as Any)]) + case .botInlineMessageMediaVenue(let _data): + return ("botInlineMessageMediaVenue", [("flags", _data.flags as Any), ("geo", _data.geo as Any), ("title", _data.title as Any), ("address", _data.address as Any), ("provider", _data.provider as Any), ("venueId", _data.venueId as Any), ("venueType", _data.venueType as Any), ("replyMarkup", _data.replyMarkup as Any)]) + case .botInlineMessageMediaWebPage(let _data): + return ("botInlineMessageMediaWebPage", [("flags", _data.flags as Any), ("message", _data.message as Any), ("entities", _data.entities as Any), ("url", _data.url as Any), ("replyMarkup", _data.replyMarkup as Any)]) + case .botInlineMessageText(let _data): + return ("botInlineMessageText", [("flags", _data.flags as Any), ("message", _data.message as Any), ("entities", _data.entities as Any), ("replyMarkup", _data.replyMarkup as Any)]) + } + } + public static func parse_botInlineMessageMediaAuto(_ reader: BufferReader) -> BotInlineMessage? { var _1: Int32? _1 = reader.readInt32() var _2: String? _2 = parseString(reader) var _3: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } var _4: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.BotInlineMessage.botInlineMessageMediaAuto(flags: _1!, message: _2!, entities: _3, replyMarkup: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.BotInlineMessage.botInlineMessageMediaAuto(Cons_botInlineMessageMediaAuto(flags: _1!, message: _2!, entities: _3, replyMarkup: _4)) + } + else { + return nil + } } public static func parse_botInlineMessageMediaContact(_ reader: BufferReader) -> BotInlineMessage? { var _1: Int32? @@ -468,22 +717,23 @@ public extension Api { var _5: String? _5 = parseString(reader) var _6: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.BotInlineMessage.botInlineMessageMediaContact(flags: _1!, phoneNumber: _2!, firstName: _3!, lastName: _4!, vcard: _5!, replyMarkup: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.BotInlineMessage.botInlineMessageMediaContact(Cons_botInlineMessageMediaContact(flags: _1!, phoneNumber: _2!, firstName: _3!, lastName: _4!, vcard: _5!, replyMarkup: _6)) + } + else { + return nil + } } public static func parse_botInlineMessageMediaGeo(_ reader: BufferReader) -> BotInlineMessage? { var _1: Int32? @@ -493,28 +743,35 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.GeoPoint } var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } var _4: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = reader.readInt32() + } var _5: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 3) != 0 { + _5 = reader.readInt32() + } var _6: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 3) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.BotInlineMessage.botInlineMessageMediaGeo(flags: _1!, geo: _2!, heading: _3, period: _4, proximityNotificationRadius: _5, replyMarkup: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.BotInlineMessage.botInlineMessageMediaGeo(Cons_botInlineMessageMediaGeo(flags: _1!, geo: _2!, heading: _3, period: _4, proximityNotificationRadius: _5, replyMarkup: _6)) + } + else { + return nil + } } public static func parse_botInlineMessageMediaInvoice(_ reader: BufferReader) -> BotInlineMessage? { var _1: Int32? @@ -524,17 +781,21 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: Api.WebDocument? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.WebDocument - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.WebDocument + } + } var _5: String? _5 = parseString(reader) var _6: Int64? _6 = reader.readInt64() var _7: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -542,14 +803,12 @@ public extension Api { let _c5 = _5 != nil let _c6 = _6 != nil let _c7 = (Int(_1!) & Int(1 << 2) == 0) || _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.BotInlineMessage.botInlineMessageMediaInvoice(flags: _1!, title: _2!, description: _3!, photo: _4, currency: _5!, totalAmount: _6!, replyMarkup: _7) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.BotInlineMessage.botInlineMessageMediaInvoice(Cons_botInlineMessageMediaInvoice(flags: _1!, title: _2!, description: _3!, photo: _4, currency: _5!, totalAmount: _6!, replyMarkup: _7)) + } + else { + return nil + } } public static func parse_botInlineMessageMediaVenue(_ reader: BufferReader) -> BotInlineMessage? { var _1: Int32? @@ -569,9 +828,11 @@ public extension Api { var _7: String? _7 = parseString(reader) var _8: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -580,15 +841,12 @@ public extension Api { let _c6 = _6 != nil let _c7 = _7 != nil let _c8 = (Int(_1!) & Int(1 << 2) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.BotInlineMessage.botInlineMessageMediaVenue(flags: _1!, geo: _2!, title: _3!, address: _4!, provider: _5!, venueId: _6!, venueType: _7!, replyMarkup: _8) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.BotInlineMessage.botInlineMessageMediaVenue(Cons_botInlineMessageMediaVenue(flags: _1!, geo: _2!, title: _3!, address: _4!, provider: _5!, venueId: _6!, venueType: _7!, replyMarkup: _8)) + } + else { + return nil + } } public static func parse_botInlineMessageMediaWebPage(_ reader: BufferReader) -> BotInlineMessage? { var _1: Int32? @@ -596,26 +854,30 @@ public extension Api { var _2: String? _2 = parseString(reader) var _3: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } var _4: String? _4 = parseString(reader) var _5: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 2) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.BotInlineMessage.botInlineMessageMediaWebPage(flags: _1!, message: _2!, entities: _3, url: _4!, replyMarkup: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.BotInlineMessage.botInlineMessageMediaWebPage(Cons_botInlineMessageMediaWebPage(flags: _1!, message: _2!, entities: _3, url: _4!, replyMarkup: _5)) + } + else { + return nil + } } public static func parse_botInlineMessageText(_ reader: BufferReader) -> BotInlineMessage? { var _1: Int32? @@ -623,72 +885,136 @@ public extension Api { var _2: String? _2 = parseString(reader) var _3: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } var _4: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.BotInlineMessage.botInlineMessageText(flags: _1!, message: _2!, entities: _3, replyMarkup: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.BotInlineMessage.botInlineMessageText(Cons_botInlineMessageText(flags: _1!, message: _2!, entities: _3, replyMarkup: _4)) + } + else { + return nil + } } - } } public extension Api { enum BotInlineResult: TypeConstructorDescription { - case botInlineMediaResult(flags: Int32, id: String, type: String, photo: Api.Photo?, document: Api.Document?, title: String?, description: String?, sendMessage: Api.BotInlineMessage) - case botInlineResult(flags: Int32, id: String, type: String, title: String?, description: String?, url: String?, thumb: Api.WebDocument?, content: Api.WebDocument?, sendMessage: Api.BotInlineMessage) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botInlineMediaResult(let flags, let id, let type, let photo, let document, let title, let description, let sendMessage): - if boxed { - buffer.appendInt32(400266251) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(id, buffer: buffer, boxed: false) - serializeString(type, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {photo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {document!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeString(description!, buffer: buffer, boxed: false)} - sendMessage.serialize(buffer, true) - break - case .botInlineResult(let flags, let id, let type, let title, let description, let url, let thumb, let content, let sendMessage): - if boxed { - buffer.appendInt32(295067450) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(id, buffer: buffer, boxed: false) - serializeString(type, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(description!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeString(url!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {thumb!.serialize(buffer, true)} - if Int(flags) & Int(1 << 5) != 0 {content!.serialize(buffer, true)} - sendMessage.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botInlineMediaResult(let flags, let id, let type, let photo, let document, let title, let description, let sendMessage): - return ("botInlineMediaResult", [("flags", flags as Any), ("id", id as Any), ("type", type as Any), ("photo", photo as Any), ("document", document as Any), ("title", title as Any), ("description", description as Any), ("sendMessage", sendMessage as Any)]) - case .botInlineResult(let flags, let id, let type, let title, let description, let url, let thumb, let content, let sendMessage): - return ("botInlineResult", [("flags", flags as Any), ("id", id as Any), ("type", type as Any), ("title", title as Any), ("description", description as Any), ("url", url as Any), ("thumb", thumb as Any), ("content", content as Any), ("sendMessage", sendMessage as Any)]) - } - } - + public class Cons_botInlineMediaResult { + public var flags: Int32 + public var id: String + public var type: String + public var photo: Api.Photo? + public var document: Api.Document? + public var title: String? + public var description: String? + public var sendMessage: Api.BotInlineMessage + public init(flags: Int32, id: String, type: String, photo: Api.Photo?, document: Api.Document?, title: String?, description: String?, sendMessage: Api.BotInlineMessage) { + self.flags = flags + self.id = id + self.type = type + self.photo = photo + self.document = document + self.title = title + self.description = description + self.sendMessage = sendMessage + } + } + public class Cons_botInlineResult { + public var flags: Int32 + public var id: String + public var type: String + public var title: String? + public var description: String? + public var url: String? + public var thumb: Api.WebDocument? + public var content: Api.WebDocument? + public var sendMessage: Api.BotInlineMessage + public init(flags: Int32, id: String, type: String, title: String?, description: String?, url: String?, thumb: Api.WebDocument?, content: Api.WebDocument?, sendMessage: Api.BotInlineMessage) { + self.flags = flags + self.id = id + self.type = type + self.title = title + self.description = description + self.url = url + self.thumb = thumb + self.content = content + self.sendMessage = sendMessage + } + } + case botInlineMediaResult(Cons_botInlineMediaResult) + case botInlineResult(Cons_botInlineResult) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botInlineMediaResult(let _data): + if boxed { + buffer.appendInt32(400266251) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.id, buffer: buffer, boxed: false) + serializeString(_data.type, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.photo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.document!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.description!, buffer: buffer, boxed: false) + } + _data.sendMessage.serialize(buffer, true) + break + case .botInlineResult(let _data): + if boxed { + buffer.appendInt32(295067450) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.id, buffer: buffer, boxed: false) + serializeString(_data.type, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.description!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.url!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + _data.thumb!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + _data.content!.serialize(buffer, true) + } + _data.sendMessage.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botInlineMediaResult(let _data): + return ("botInlineMediaResult", [("flags", _data.flags as Any), ("id", _data.id as Any), ("type", _data.type as Any), ("photo", _data.photo as Any), ("document", _data.document as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("sendMessage", _data.sendMessage as Any)]) + case .botInlineResult(let _data): + return ("botInlineResult", [("flags", _data.flags as Any), ("id", _data.id as Any), ("type", _data.type as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("url", _data.url as Any), ("thumb", _data.thumb as Any), ("content", _data.content as Any), ("sendMessage", _data.sendMessage as Any)]) + } + } + public static func parse_botInlineMediaResult(_ reader: BufferReader) -> BotInlineResult? { var _1: Int32? _1 = reader.readInt32() @@ -697,17 +1023,25 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: Api.Photo? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Photo - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Photo + } + } var _5: Api.Document? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.Document - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.Document + } + } var _6: String? - if Int(_1!) & Int(1 << 2) != 0 {_6 = parseString(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _6 = parseString(reader) + } var _7: String? - if Int(_1!) & Int(1 << 3) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 3) != 0 { + _7 = parseString(reader) + } var _8: Api.BotInlineMessage? if let signature = reader.readInt32() { _8 = Api.parse(reader, signature: signature) as? Api.BotInlineMessage @@ -720,15 +1054,12 @@ public extension Api { let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil let _c7 = (Int(_1!) & Int(1 << 3) == 0) || _7 != nil let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.BotInlineResult.botInlineMediaResult(flags: _1!, id: _2!, type: _3!, photo: _4, document: _5, title: _6, description: _7, sendMessage: _8!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.BotInlineResult.botInlineMediaResult(Cons_botInlineMediaResult(flags: _1!, id: _2!, type: _3!, photo: _4, document: _5, title: _6, description: _7, sendMessage: _8!)) + } + else { + return nil + } } public static func parse_botInlineResult(_ reader: BufferReader) -> BotInlineResult? { var _1: Int32? @@ -738,19 +1069,29 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: String? - if Int(_1!) & Int(1 << 1) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = parseString(reader) + } var _5: String? - if Int(_1!) & Int(1 << 2) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _5 = parseString(reader) + } var _6: String? - if Int(_1!) & Int(1 << 3) != 0 {_6 = parseString(reader) } + if Int(_1!) & Int(1 << 3) != 0 { + _6 = parseString(reader) + } var _7: Api.WebDocument? - if Int(_1!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.WebDocument - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.WebDocument + } + } var _8: Api.WebDocument? - if Int(_1!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.WebDocument - } } + if Int(_1!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.WebDocument + } + } var _9: Api.BotInlineMessage? if let signature = reader.readInt32() { _9 = Api.parse(reader, signature: signature) as? Api.BotInlineMessage @@ -764,61 +1105,62 @@ public extension Api { let _c7 = (Int(_1!) & Int(1 << 4) == 0) || _7 != nil let _c8 = (Int(_1!) & Int(1 << 5) == 0) || _8 != nil let _c9 = _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.BotInlineResult.botInlineResult(flags: _1!, id: _2!, type: _3!, title: _4, description: _5, url: _6, thumb: _7, content: _8, sendMessage: _9!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.BotInlineResult.botInlineResult(Cons_botInlineResult(flags: _1!, id: _2!, type: _3!, title: _4, description: _5, url: _6, thumb: _7, content: _8, sendMessage: _9!)) + } + else { + return nil + } } - } } public extension Api { enum BotMenuButton: TypeConstructorDescription { - case botMenuButton(text: String, url: String) + public class Cons_botMenuButton { + public var text: String + public var url: String + public init(text: String, url: String) { + self.text = text + self.url = url + } + } + case botMenuButton(Cons_botMenuButton) case botMenuButtonCommands case botMenuButtonDefault - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botMenuButton(let text, let url): - if boxed { - buffer.appendInt32(-944407322) - } - serializeString(text, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - break - case .botMenuButtonCommands: - if boxed { - buffer.appendInt32(1113113093) - } - - break - case .botMenuButtonDefault: - if boxed { - buffer.appendInt32(1966318984) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botMenuButton(let text, let url): - return ("botMenuButton", [("text", text as Any), ("url", url as Any)]) - case .botMenuButtonCommands: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botMenuButton(let _data): + if boxed { + buffer.appendInt32(-944407322) + } + serializeString(_data.text, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + break + case .botMenuButtonCommands: + if boxed { + buffer.appendInt32(1113113093) + } + break + case .botMenuButtonDefault: + if boxed { + buffer.appendInt32(1966318984) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botMenuButton(let _data): + return ("botMenuButton", [("text", _data.text as Any), ("url", _data.url as Any)]) + case .botMenuButtonCommands: return ("botMenuButtonCommands", []) - case .botMenuButtonDefault: + case .botMenuButtonDefault: return ("botMenuButtonDefault", []) - } - } - + } + } + public static func parse_botMenuButton(_ reader: BufferReader) -> BotMenuButton? { var _1: String? _1 = parseString(reader) @@ -826,9 +1168,12 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.BotMenuButton.botMenuButton(text: _1!, url: _2!) + if _c1 && _c2 { + return Api.BotMenuButton.botMenuButton(Cons_botMenuButton(text: _1!, url: _2!)) + } + else { + return nil + } } public static func parse_botMenuButtonCommands(_ reader: BufferReader) -> BotMenuButton? { return Api.BotMenuButton.botMenuButtonCommands @@ -836,32 +1181,39 @@ public extension Api { public static func parse_botMenuButtonDefault(_ reader: BufferReader) -> BotMenuButton? { return Api.BotMenuButton.botMenuButtonDefault } - } } public extension Api { indirect enum BotPreviewMedia: TypeConstructorDescription { - case botPreviewMedia(date: Int32, media: Api.MessageMedia) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botPreviewMedia(let date, let media): - if boxed { - buffer.appendInt32(602479523) - } - serializeInt32(date, buffer: buffer, boxed: false) - media.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botPreviewMedia(let date, let media): - return ("botPreviewMedia", [("date", date as Any), ("media", media as Any)]) - } - } - + public class Cons_botPreviewMedia { + public var date: Int32 + public var media: Api.MessageMedia + public init(date: Int32, media: Api.MessageMedia) { + self.date = date + self.media = media + } + } + case botPreviewMedia(Cons_botPreviewMedia) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botPreviewMedia(let _data): + if boxed { + buffer.appendInt32(602479523) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + _data.media.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botPreviewMedia(let _data): + return ("botPreviewMedia", [("date", _data.date as Any), ("media", _data.media as Any)]) + } + } + public static func parse_botPreviewMedia(_ reader: BufferReader) -> BotPreviewMedia? { var _1: Int32? _1 = reader.readInt32() @@ -871,37 +1223,49 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.BotPreviewMedia.botPreviewMedia(date: _1!, media: _2!) + if _c1 && _c2 { + return Api.BotPreviewMedia.botPreviewMedia(Cons_botPreviewMedia(date: _1!, media: _2!)) + } + else { + return nil + } } - } } public extension Api { enum BotVerification: TypeConstructorDescription { - case botVerification(botId: Int64, icon: Int64, description: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botVerification(let botId, let icon, let description): - if boxed { - buffer.appendInt32(-113453988) - } - serializeInt64(botId, buffer: buffer, boxed: false) - serializeInt64(icon, buffer: buffer, boxed: false) - serializeString(description, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botVerification(let botId, let icon, let description): - return ("botVerification", [("botId", botId as Any), ("icon", icon as Any), ("description", description as Any)]) - } - } - + public class Cons_botVerification { + public var botId: Int64 + public var icon: Int64 + public var description: String + public init(botId: Int64, icon: Int64, description: String) { + self.botId = botId + self.icon = icon + self.description = description + } + } + case botVerification(Cons_botVerification) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botVerification(let _data): + if boxed { + buffer.appendInt32(-113453988) + } + serializeInt64(_data.botId, buffer: buffer, boxed: false) + serializeInt64(_data.icon, buffer: buffer, boxed: false) + serializeString(_data.description, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botVerification(let _data): + return ("botVerification", [("botId", _data.botId as Any), ("icon", _data.icon as Any), ("description", _data.description as Any)]) + } + } + public static func parse_botVerification(_ reader: BufferReader) -> BotVerification? { var _1: Int64? _1 = reader.readInt64() @@ -912,39 +1276,54 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.BotVerification.botVerification(botId: _1!, icon: _2!, description: _3!) + if _c1 && _c2 && _c3 { + return Api.BotVerification.botVerification(Cons_botVerification(botId: _1!, icon: _2!, description: _3!)) + } + else { + return nil + } } - } } public extension Api { enum BotVerifierSettings: TypeConstructorDescription { - case botVerifierSettings(flags: Int32, icon: Int64, company: String, customDescription: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botVerifierSettings(let flags, let icon, let company, let customDescription): - if boxed { - buffer.appendInt32(-1328716265) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(icon, buffer: buffer, boxed: false) - serializeString(company, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(customDescription!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botVerifierSettings(let flags, let icon, let company, let customDescription): - return ("botVerifierSettings", [("flags", flags as Any), ("icon", icon as Any), ("company", company as Any), ("customDescription", customDescription as Any)]) - } - } - + public class Cons_botVerifierSettings { + public var flags: Int32 + public var icon: Int64 + public var company: String + public var customDescription: String? + public init(flags: Int32, icon: Int64, company: String, customDescription: String?) { + self.flags = flags + self.icon = icon + self.company = company + self.customDescription = customDescription + } + } + case botVerifierSettings(Cons_botVerifierSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botVerifierSettings(let _data): + if boxed { + buffer.appendInt32(-1328716265) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.icon, buffer: buffer, boxed: false) + serializeString(_data.company, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.customDescription!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botVerifierSettings(let _data): + return ("botVerifierSettings", [("flags", _data.flags as Any), ("icon", _data.icon as Any), ("company", _data.company as Any), ("customDescription", _data.customDescription as Any)]) + } + } + public static func parse_botVerifierSettings(_ reader: BufferReader) -> BotVerifierSettings? { var _1: Int32? _1 = reader.readInt32() @@ -953,45 +1332,59 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: String? - if Int(_1!) & Int(1 << 0) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.BotVerifierSettings.botVerifierSettings(flags: _1!, icon: _2!, company: _3!, customDescription: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.BotVerifierSettings.botVerifierSettings(Cons_botVerifierSettings(flags: _1!, icon: _2!, company: _3!, customDescription: _4)) + } + else { + return nil + } } - } } public extension Api { enum BusinessAwayMessage: TypeConstructorDescription { - case businessAwayMessage(flags: Int32, shortcutId: Int32, schedule: Api.BusinessAwayMessageSchedule, recipients: Api.BusinessRecipients) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .businessAwayMessage(let flags, let shortcutId, let schedule, let recipients): - if boxed { - buffer.appendInt32(-283809188) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(shortcutId, buffer: buffer, boxed: false) - schedule.serialize(buffer, true) - recipients.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .businessAwayMessage(let flags, let shortcutId, let schedule, let recipients): - return ("businessAwayMessage", [("flags", flags as Any), ("shortcutId", shortcutId as Any), ("schedule", schedule as Any), ("recipients", recipients as Any)]) - } - } - + public class Cons_businessAwayMessage { + public var flags: Int32 + public var shortcutId: Int32 + public var schedule: Api.BusinessAwayMessageSchedule + public var recipients: Api.BusinessRecipients + public init(flags: Int32, shortcutId: Int32, schedule: Api.BusinessAwayMessageSchedule, recipients: Api.BusinessRecipients) { + self.flags = flags + self.shortcutId = shortcutId + self.schedule = schedule + self.recipients = recipients + } + } + case businessAwayMessage(Cons_businessAwayMessage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .businessAwayMessage(let _data): + if boxed { + buffer.appendInt32(-283809188) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.shortcutId, buffer: buffer, boxed: false) + _data.schedule.serialize(buffer, true) + _data.recipients.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .businessAwayMessage(let _data): + return ("businessAwayMessage", [("flags", _data.flags as Any), ("shortcutId", _data.shortcutId as Any), ("schedule", _data.schedule as Any), ("recipients", _data.recipients as Any)]) + } + } + public static func parse_businessAwayMessage(_ reader: BufferReader) -> BusinessAwayMessage? { var _1: Int32? _1 = reader.readInt32() @@ -1009,56 +1402,62 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.BusinessAwayMessage.businessAwayMessage(flags: _1!, shortcutId: _2!, schedule: _3!, recipients: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.BusinessAwayMessage.businessAwayMessage(Cons_businessAwayMessage(flags: _1!, shortcutId: _2!, schedule: _3!, recipients: _4!)) + } + else { + return nil + } } - } } public extension Api { enum BusinessAwayMessageSchedule: TypeConstructorDescription { + public class Cons_businessAwayMessageScheduleCustom { + public var startDate: Int32 + public var endDate: Int32 + public init(startDate: Int32, endDate: Int32) { + self.startDate = startDate + self.endDate = endDate + } + } case businessAwayMessageScheduleAlways - case businessAwayMessageScheduleCustom(startDate: Int32, endDate: Int32) + case businessAwayMessageScheduleCustom(Cons_businessAwayMessageScheduleCustom) case businessAwayMessageScheduleOutsideWorkHours - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .businessAwayMessageScheduleAlways: - if boxed { - buffer.appendInt32(-910564679) - } - - break - case .businessAwayMessageScheduleCustom(let startDate, let endDate): - if boxed { - buffer.appendInt32(-867328308) - } - serializeInt32(startDate, buffer: buffer, boxed: false) - serializeInt32(endDate, buffer: buffer, boxed: false) - break - case .businessAwayMessageScheduleOutsideWorkHours: - if boxed { - buffer.appendInt32(-1007487743) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .businessAwayMessageScheduleAlways: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .businessAwayMessageScheduleAlways: + if boxed { + buffer.appendInt32(-910564679) + } + break + case .businessAwayMessageScheduleCustom(let _data): + if boxed { + buffer.appendInt32(-867328308) + } + serializeInt32(_data.startDate, buffer: buffer, boxed: false) + serializeInt32(_data.endDate, buffer: buffer, boxed: false) + break + case .businessAwayMessageScheduleOutsideWorkHours: + if boxed { + buffer.appendInt32(-1007487743) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .businessAwayMessageScheduleAlways: return ("businessAwayMessageScheduleAlways", []) - case .businessAwayMessageScheduleCustom(let startDate, let endDate): - return ("businessAwayMessageScheduleCustom", [("startDate", startDate as Any), ("endDate", endDate as Any)]) - case .businessAwayMessageScheduleOutsideWorkHours: + case .businessAwayMessageScheduleCustom(let _data): + return ("businessAwayMessageScheduleCustom", [("startDate", _data.startDate as Any), ("endDate", _data.endDate as Any)]) + case .businessAwayMessageScheduleOutsideWorkHours: return ("businessAwayMessageScheduleOutsideWorkHours", []) - } - } - + } + } + public static func parse_businessAwayMessageScheduleAlways(_ reader: BufferReader) -> BusinessAwayMessageSchedule? { return Api.BusinessAwayMessageSchedule.businessAwayMessageScheduleAlways } @@ -1069,133 +1468,183 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.BusinessAwayMessageSchedule.businessAwayMessageScheduleCustom(startDate: _1!, endDate: _2!) + if _c1 && _c2 { + return Api.BusinessAwayMessageSchedule.businessAwayMessageScheduleCustom(Cons_businessAwayMessageScheduleCustom(startDate: _1!, endDate: _2!)) + } + else { + return nil + } } public static func parse_businessAwayMessageScheduleOutsideWorkHours(_ reader: BufferReader) -> BusinessAwayMessageSchedule? { return Api.BusinessAwayMessageSchedule.businessAwayMessageScheduleOutsideWorkHours } - } } public extension Api { enum BusinessBotRecipients: TypeConstructorDescription { - case businessBotRecipients(flags: Int32, users: [Int64]?, excludeUsers: [Int64]?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .businessBotRecipients(let flags, let users, let excludeUsers): - if boxed { - buffer.appendInt32(-1198722189) + public class Cons_businessBotRecipients { + public var flags: Int32 + public var users: [Int64]? + public var excludeUsers: [Int64]? + public init(flags: Int32, users: [Int64]?, excludeUsers: [Int64]?) { + self.flags = flags + self.users = users + self.excludeUsers = excludeUsers + } + } + case businessBotRecipients(Cons_businessBotRecipients) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .businessBotRecipients(let _data): + if boxed { + buffer.appendInt32(-1198722189) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 4) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users!.count)) + for item in _data.users! { + serializeInt64(item, buffer: buffer, boxed: false) } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users!.count)) - for item in users! { + } + if Int(_data.flags) & Int(1 << 6) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.excludeUsers!.count)) + for item in _data.excludeUsers! { serializeInt64(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 6) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(excludeUsers!.count)) - for item in excludeUsers! { - serializeInt64(item, buffer: buffer, boxed: false) - }} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .businessBotRecipients(let flags, let users, let excludeUsers): - return ("businessBotRecipients", [("flags", flags as Any), ("users", users as Any), ("excludeUsers", excludeUsers as Any)]) - } - } - + } + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .businessBotRecipients(let _data): + return ("businessBotRecipients", [("flags", _data.flags as Any), ("users", _data.users as Any), ("excludeUsers", _data.excludeUsers as Any)]) + } + } + public static func parse_businessBotRecipients(_ reader: BufferReader) -> BusinessBotRecipients? { var _1: Int32? _1 = reader.readInt32() var _2: [Int64]? - if Int(_1!) & Int(1 << 4) != 0 {if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) + } + } var _3: [Int64]? - if Int(_1!) & Int(1 << 6) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) - } } + if Int(_1!) & Int(1 << 6) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 4) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 6) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.BusinessBotRecipients.businessBotRecipients(flags: _1!, users: _2, excludeUsers: _3) + if _c1 && _c2 && _c3 { + return Api.BusinessBotRecipients.businessBotRecipients(Cons_businessBotRecipients(flags: _1!, users: _2, excludeUsers: _3)) + } + else { + return nil + } } - } } public extension Api { enum BusinessBotRights: TypeConstructorDescription { - case businessBotRights(flags: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .businessBotRights(let flags): - if boxed { - buffer.appendInt32(-1604170505) - } - serializeInt32(flags, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .businessBotRights(let flags): - return ("businessBotRights", [("flags", flags as Any)]) - } - } - + public class Cons_businessBotRights { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } + case businessBotRights(Cons_businessBotRights) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .businessBotRights(let _data): + if boxed { + buffer.appendInt32(-1604170505) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .businessBotRights(let _data): + return ("businessBotRights", [("flags", _data.flags as Any)]) + } + } + public static func parse_businessBotRights(_ reader: BufferReader) -> BusinessBotRights? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.BusinessBotRights.businessBotRights(flags: _1!) + if _c1 { + return Api.BusinessBotRights.businessBotRights(Cons_businessBotRights(flags: _1!)) + } + else { + return nil + } } - } } public extension Api { enum BusinessChatLink: TypeConstructorDescription { - case businessChatLink(flags: Int32, link: String, message: String, entities: [Api.MessageEntity]?, title: String?, views: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .businessChatLink(let flags, let link, let message, let entities, let title, let views): - if boxed { - buffer.appendInt32(-1263638929) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(link, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { + public class Cons_businessChatLink { + public var flags: Int32 + public var link: String + public var message: String + public var entities: [Api.MessageEntity]? + public var title: String? + public var views: Int32 + public init(flags: Int32, link: String, message: String, entities: [Api.MessageEntity]?, title: String?, views: Int32) { + self.flags = flags + self.link = link + self.message = message + self.entities = entities + self.title = title + self.views = views + } + } + case businessChatLink(Cons_businessChatLink) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .businessChatLink(let _data): + if boxed { + buffer.appendInt32(-1263638929) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.link, buffer: buffer, boxed: false) + serializeString(_data.message, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 1) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - serializeInt32(views, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .businessChatLink(let flags, let link, let message, let entities, let title, let views): - return ("businessChatLink", [("flags", flags as Any), ("link", link as Any), ("message", message as Any), ("entities", entities as Any), ("title", title as Any), ("views", views as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + serializeInt32(_data.views, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .businessChatLink(let _data): + return ("businessChatLink", [("flags", _data.flags as Any), ("link", _data.link as Any), ("message", _data.message as Any), ("entities", _data.entities as Any), ("title", _data.title as Any), ("views", _data.views as Any)]) + } + } + public static func parse_businessChatLink(_ reader: BufferReader) -> BusinessChatLink? { var _1: Int32? _1 = reader.readInt32() @@ -1204,11 +1653,15 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } var _5: String? - if Int(_1!) & Int(1 << 1) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _5 = parseString(reader) + } var _6: Int32? _6 = reader.readInt32() let _c1 = _1 != nil @@ -1217,14 +1670,12 @@ public extension Api { let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.BusinessChatLink.businessChatLink(flags: _1!, link: _2!, message: _3!, entities: _4, title: _5, views: _6!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.BusinessChatLink.businessChatLink(Cons_businessChatLink(flags: _1!, link: _2!, message: _3!, entities: _4, title: _5, views: _6!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api20.swift b/submodules/TelegramApi/Sources/Api20.swift index fff136f0..ef367505 100644 --- a/submodules/TelegramApi/Sources/Api20.swift +++ b/submodules/TelegramApi/Sources/Api20.swift @@ -1,61 +1,63 @@ public extension Api { enum PhoneCallDiscardReason: TypeConstructorDescription { + public class Cons_phoneCallDiscardReasonMigrateConferenceCall { + public var slug: String + public init(slug: String) { + self.slug = slug + } + } case phoneCallDiscardReasonBusy case phoneCallDiscardReasonDisconnect case phoneCallDiscardReasonHangup - case phoneCallDiscardReasonMigrateConferenceCall(slug: String) + case phoneCallDiscardReasonMigrateConferenceCall(Cons_phoneCallDiscardReasonMigrateConferenceCall) case phoneCallDiscardReasonMissed - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .phoneCallDiscardReasonBusy: - if boxed { - buffer.appendInt32(-84416311) - } - - break - case .phoneCallDiscardReasonDisconnect: - if boxed { - buffer.appendInt32(-527056480) - } - - break - case .phoneCallDiscardReasonHangup: - if boxed { - buffer.appendInt32(1471006352) - } - - break - case .phoneCallDiscardReasonMigrateConferenceCall(let slug): - if boxed { - buffer.appendInt32(-1615072777) - } - serializeString(slug, buffer: buffer, boxed: false) - break - case .phoneCallDiscardReasonMissed: - if boxed { - buffer.appendInt32(-2048646399) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .phoneCallDiscardReasonBusy: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .phoneCallDiscardReasonBusy: + if boxed { + buffer.appendInt32(-84416311) + } + break + case .phoneCallDiscardReasonDisconnect: + if boxed { + buffer.appendInt32(-527056480) + } + break + case .phoneCallDiscardReasonHangup: + if boxed { + buffer.appendInt32(1471006352) + } + break + case .phoneCallDiscardReasonMigrateConferenceCall(let _data): + if boxed { + buffer.appendInt32(-1615072777) + } + serializeString(_data.slug, buffer: buffer, boxed: false) + break + case .phoneCallDiscardReasonMissed: + if boxed { + buffer.appendInt32(-2048646399) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .phoneCallDiscardReasonBusy: return ("phoneCallDiscardReasonBusy", []) - case .phoneCallDiscardReasonDisconnect: + case .phoneCallDiscardReasonDisconnect: return ("phoneCallDiscardReasonDisconnect", []) - case .phoneCallDiscardReasonHangup: + case .phoneCallDiscardReasonHangup: return ("phoneCallDiscardReasonHangup", []) - case .phoneCallDiscardReasonMigrateConferenceCall(let slug): - return ("phoneCallDiscardReasonMigrateConferenceCall", [("slug", slug as Any)]) - case .phoneCallDiscardReasonMissed: + case .phoneCallDiscardReasonMigrateConferenceCall(let _data): + return ("phoneCallDiscardReasonMigrateConferenceCall", [("slug", _data.slug as Any)]) + case .phoneCallDiscardReasonMissed: return ("phoneCallDiscardReasonMissed", []) - } - } - + } + } + public static func parse_phoneCallDiscardReasonBusy(_ reader: BufferReader) -> PhoneCallDiscardReason? { return Api.PhoneCallDiscardReason.phoneCallDiscardReasonBusy } @@ -69,44 +71,59 @@ public extension Api { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PhoneCallDiscardReason.phoneCallDiscardReasonMigrateConferenceCall(slug: _1!) + if _c1 { + return Api.PhoneCallDiscardReason.phoneCallDiscardReasonMigrateConferenceCall(Cons_phoneCallDiscardReasonMigrateConferenceCall(slug: _1!)) + } + else { + return nil + } } public static func parse_phoneCallDiscardReasonMissed(_ reader: BufferReader) -> PhoneCallDiscardReason? { return Api.PhoneCallDiscardReason.phoneCallDiscardReasonMissed } - } } public extension Api { enum PhoneCallProtocol: TypeConstructorDescription { - case phoneCallProtocol(flags: Int32, minLayer: Int32, maxLayer: Int32, libraryVersions: [String]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .phoneCallProtocol(let flags, let minLayer, let maxLayer, let libraryVersions): - if boxed { - buffer.appendInt32(-58224696) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(minLayer, buffer: buffer, boxed: false) - serializeInt32(maxLayer, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(libraryVersions.count)) - for item in libraryVersions { - serializeString(item, buffer: buffer, boxed: false) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .phoneCallProtocol(let flags, let minLayer, let maxLayer, let libraryVersions): - return ("phoneCallProtocol", [("flags", flags as Any), ("minLayer", minLayer as Any), ("maxLayer", maxLayer as Any), ("libraryVersions", libraryVersions as Any)]) - } - } - + public class Cons_phoneCallProtocol { + public var flags: Int32 + public var minLayer: Int32 + public var maxLayer: Int32 + public var libraryVersions: [String] + public init(flags: Int32, minLayer: Int32, maxLayer: Int32, libraryVersions: [String]) { + self.flags = flags + self.minLayer = minLayer + self.maxLayer = maxLayer + self.libraryVersions = libraryVersions + } + } + case phoneCallProtocol(Cons_phoneCallProtocol) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .phoneCallProtocol(let _data): + if boxed { + buffer.appendInt32(-58224696) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.minLayer, buffer: buffer, boxed: false) + serializeInt32(_data.maxLayer, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.libraryVersions.count)) + for item in _data.libraryVersions { + serializeString(item, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .phoneCallProtocol(let _data): + return ("phoneCallProtocol", [("flags", _data.flags as Any), ("minLayer", _data.minLayer as Any), ("maxLayer", _data.maxLayer as Any), ("libraryVersions", _data.libraryVersions as Any)]) + } + } + public static func parse_phoneCallProtocol(_ reader: BufferReader) -> PhoneCallProtocol? { var _1: Int32? _1 = reader.readInt32() @@ -122,57 +139,91 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.PhoneCallProtocol.phoneCallProtocol(flags: _1!, minLayer: _2!, maxLayer: _3!, libraryVersions: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.PhoneCallProtocol.phoneCallProtocol(Cons_phoneCallProtocol(flags: _1!, minLayer: _2!, maxLayer: _3!, libraryVersions: _4!)) + } + else { + return nil + } } - } } public extension Api { enum PhoneConnection: TypeConstructorDescription { - case phoneConnection(flags: Int32, id: Int64, ip: String, ipv6: String, port: Int32, peerTag: Buffer) - case phoneConnectionWebrtc(flags: Int32, id: Int64, ip: String, ipv6: String, port: Int32, username: String, password: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .phoneConnection(let flags, let id, let ip, let ipv6, let port, let peerTag): - if boxed { - buffer.appendInt32(-1665063993) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeString(ip, buffer: buffer, boxed: false) - serializeString(ipv6, buffer: buffer, boxed: false) - serializeInt32(port, buffer: buffer, boxed: false) - serializeBytes(peerTag, buffer: buffer, boxed: false) - break - case .phoneConnectionWebrtc(let flags, let id, let ip, let ipv6, let port, let username, let password): - if boxed { - buffer.appendInt32(1667228533) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeString(ip, buffer: buffer, boxed: false) - serializeString(ipv6, buffer: buffer, boxed: false) - serializeInt32(port, buffer: buffer, boxed: false) - serializeString(username, buffer: buffer, boxed: false) - serializeString(password, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .phoneConnection(let flags, let id, let ip, let ipv6, let port, let peerTag): - return ("phoneConnection", [("flags", flags as Any), ("id", id as Any), ("ip", ip as Any), ("ipv6", ipv6 as Any), ("port", port as Any), ("peerTag", peerTag as Any)]) - case .phoneConnectionWebrtc(let flags, let id, let ip, let ipv6, let port, let username, let password): - return ("phoneConnectionWebrtc", [("flags", flags as Any), ("id", id as Any), ("ip", ip as Any), ("ipv6", ipv6 as Any), ("port", port as Any), ("username", username as Any), ("password", password as Any)]) - } - } - + public class Cons_phoneConnection { + public var flags: Int32 + public var id: Int64 + public var ip: String + public var ipv6: String + public var port: Int32 + public var peerTag: Buffer + public init(flags: Int32, id: Int64, ip: String, ipv6: String, port: Int32, peerTag: Buffer) { + self.flags = flags + self.id = id + self.ip = ip + self.ipv6 = ipv6 + self.port = port + self.peerTag = peerTag + } + } + public class Cons_phoneConnectionWebrtc { + public var flags: Int32 + public var id: Int64 + public var ip: String + public var ipv6: String + public var port: Int32 + public var username: String + public var password: String + public init(flags: Int32, id: Int64, ip: String, ipv6: String, port: Int32, username: String, password: String) { + self.flags = flags + self.id = id + self.ip = ip + self.ipv6 = ipv6 + self.port = port + self.username = username + self.password = password + } + } + case phoneConnection(Cons_phoneConnection) + case phoneConnectionWebrtc(Cons_phoneConnectionWebrtc) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .phoneConnection(let _data): + if boxed { + buffer.appendInt32(-1665063993) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeString(_data.ip, buffer: buffer, boxed: false) + serializeString(_data.ipv6, buffer: buffer, boxed: false) + serializeInt32(_data.port, buffer: buffer, boxed: false) + serializeBytes(_data.peerTag, buffer: buffer, boxed: false) + break + case .phoneConnectionWebrtc(let _data): + if boxed { + buffer.appendInt32(1667228533) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeString(_data.ip, buffer: buffer, boxed: false) + serializeString(_data.ipv6, buffer: buffer, boxed: false) + serializeInt32(_data.port, buffer: buffer, boxed: false) + serializeString(_data.username, buffer: buffer, boxed: false) + serializeString(_data.password, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .phoneConnection(let _data): + return ("phoneConnection", [("flags", _data.flags as Any), ("id", _data.id as Any), ("ip", _data.ip as Any), ("ipv6", _data.ipv6 as Any), ("port", _data.port as Any), ("peerTag", _data.peerTag as Any)]) + case .phoneConnectionWebrtc(let _data): + return ("phoneConnectionWebrtc", [("flags", _data.flags as Any), ("id", _data.id as Any), ("ip", _data.ip as Any), ("ipv6", _data.ipv6 as Any), ("port", _data.port as Any), ("username", _data.username as Any), ("password", _data.password as Any)]) + } + } + public static func parse_phoneConnection(_ reader: BufferReader) -> PhoneConnection? { var _1: Int32? _1 = reader.readInt32() @@ -192,13 +243,12 @@ public extension Api { let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.PhoneConnection.phoneConnection(flags: _1!, id: _2!, ip: _3!, ipv6: _4!, port: _5!, peerTag: _6!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.PhoneConnection.phoneConnection(Cons_phoneConnection(flags: _1!, id: _2!, ip: _3!, ipv6: _4!, port: _5!, peerTag: _6!)) + } + else { + return nil + } } public static func parse_phoneConnectionWebrtc(_ reader: BufferReader) -> PhoneConnection? { var _1: Int32? @@ -222,64 +272,89 @@ public extension Api { let _c5 = _5 != nil let _c6 = _6 != nil let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.PhoneConnection.phoneConnectionWebrtc(flags: _1!, id: _2!, ip: _3!, ipv6: _4!, port: _5!, username: _6!, password: _7!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.PhoneConnection.phoneConnectionWebrtc(Cons_phoneConnectionWebrtc(flags: _1!, id: _2!, ip: _3!, ipv6: _4!, port: _5!, username: _6!, password: _7!)) + } + else { + return nil + } } - } } public extension Api { enum Photo: TypeConstructorDescription { - case photo(flags: Int32, id: Int64, accessHash: Int64, fileReference: Buffer, date: Int32, sizes: [Api.PhotoSize], videoSizes: [Api.VideoSize]?, dcId: Int32) - case photoEmpty(id: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .photo(let flags, let id, let accessHash, let fileReference, let date, let sizes, let videoSizes, let dcId): - if boxed { - buffer.appendInt32(-82216347) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeBytes(fileReference, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) + public class Cons_photo { + public var flags: Int32 + public var id: Int64 + public var accessHash: Int64 + public var fileReference: Buffer + public var date: Int32 + public var sizes: [Api.PhotoSize] + public var videoSizes: [Api.VideoSize]? + public var dcId: Int32 + public init(flags: Int32, id: Int64, accessHash: Int64, fileReference: Buffer, date: Int32, sizes: [Api.PhotoSize], videoSizes: [Api.VideoSize]?, dcId: Int32) { + self.flags = flags + self.id = id + self.accessHash = accessHash + self.fileReference = fileReference + self.date = date + self.sizes = sizes + self.videoSizes = videoSizes + self.dcId = dcId + } + } + public class Cons_photoEmpty { + public var id: Int64 + public init(id: Int64) { + self.id = id + } + } + case photo(Cons_photo) + case photoEmpty(Cons_photoEmpty) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .photo(let _data): + if boxed { + buffer.appendInt32(-82216347) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeBytes(_data.fileReference, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.sizes.count)) + for item in _data.sizes { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(sizes.count)) - for item in sizes { + buffer.appendInt32(Int32(_data.videoSizes!.count)) + for item in _data.videoSizes! { item.serialize(buffer, true) } - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(videoSizes!.count)) - for item in videoSizes! { - item.serialize(buffer, true) - }} - serializeInt32(dcId, buffer: buffer, boxed: false) - break - case .photoEmpty(let id): - if boxed { - buffer.appendInt32(590459437) - } - serializeInt64(id, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .photo(let flags, let id, let accessHash, let fileReference, let date, let sizes, let videoSizes, let dcId): - return ("photo", [("flags", flags as Any), ("id", id as Any), ("accessHash", accessHash as Any), ("fileReference", fileReference as Any), ("date", date as Any), ("sizes", sizes as Any), ("videoSizes", videoSizes as Any), ("dcId", dcId as Any)]) - case .photoEmpty(let id): - return ("photoEmpty", [("id", id as Any)]) - } - } - + } + serializeInt32(_data.dcId, buffer: buffer, boxed: false) + break + case .photoEmpty(let _data): + if boxed { + buffer.appendInt32(590459437) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .photo(let _data): + return ("photo", [("flags", _data.flags as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("fileReference", _data.fileReference as Any), ("date", _data.date as Any), ("sizes", _data.sizes as Any), ("videoSizes", _data.videoSizes as Any), ("dcId", _data.dcId as Any)]) + case .photoEmpty(let _data): + return ("photoEmpty", [("id", _data.id as Any)]) + } + } + public static func parse_photo(_ reader: BufferReader) -> Photo? { var _1: Int32? _1 = reader.readInt32() @@ -296,9 +371,11 @@ public extension Api { _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PhotoSize.self) } var _7: [Api.VideoSize]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.VideoSize.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.VideoSize.self) + } + } var _8: Int32? _8 = reader.readInt32() let _c1 = _1 != nil @@ -309,108 +386,166 @@ public extension Api { let _c6 = _6 != nil let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.Photo.photo(flags: _1!, id: _2!, accessHash: _3!, fileReference: _4!, date: _5!, sizes: _6!, videoSizes: _7, dcId: _8!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.Photo.photo(Cons_photo(flags: _1!, id: _2!, accessHash: _3!, fileReference: _4!, date: _5!, sizes: _6!, videoSizes: _7, dcId: _8!)) + } + else { + return nil + } } public static func parse_photoEmpty(_ reader: BufferReader) -> Photo? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Photo.photoEmpty(id: _1!) + if _c1 { + return Api.Photo.photoEmpty(Cons_photoEmpty(id: _1!)) + } + else { + return nil + } } - } } public extension Api { enum PhotoSize: TypeConstructorDescription { - case photoCachedSize(type: String, w: Int32, h: Int32, bytes: Buffer) - case photoPathSize(type: String, bytes: Buffer) - case photoSize(type: String, w: Int32, h: Int32, size: Int32) - case photoSizeEmpty(type: String) - case photoSizeProgressive(type: String, w: Int32, h: Int32, sizes: [Int32]) - case photoStrippedSize(type: String, bytes: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .photoCachedSize(let type, let w, let h, let bytes): - if boxed { - buffer.appendInt32(35527382) - } - serializeString(type, buffer: buffer, boxed: false) - serializeInt32(w, buffer: buffer, boxed: false) - serializeInt32(h, buffer: buffer, boxed: false) - serializeBytes(bytes, buffer: buffer, boxed: false) - break - case .photoPathSize(let type, let bytes): - if boxed { - buffer.appendInt32(-668906175) - } - serializeString(type, buffer: buffer, boxed: false) - serializeBytes(bytes, buffer: buffer, boxed: false) - break - case .photoSize(let type, let w, let h, let size): - if boxed { - buffer.appendInt32(1976012384) - } - serializeString(type, buffer: buffer, boxed: false) - serializeInt32(w, buffer: buffer, boxed: false) - serializeInt32(h, buffer: buffer, boxed: false) - serializeInt32(size, buffer: buffer, boxed: false) - break - case .photoSizeEmpty(let type): - if boxed { - buffer.appendInt32(236446268) - } - serializeString(type, buffer: buffer, boxed: false) - break - case .photoSizeProgressive(let type, let w, let h, let sizes): - if boxed { - buffer.appendInt32(-96535659) - } - serializeString(type, buffer: buffer, boxed: false) - serializeInt32(w, buffer: buffer, boxed: false) - serializeInt32(h, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(sizes.count)) - for item in sizes { - serializeInt32(item, buffer: buffer, boxed: false) - } - break - case .photoStrippedSize(let type, let bytes): - if boxed { - buffer.appendInt32(-525288402) - } - serializeString(type, buffer: buffer, boxed: false) - serializeBytes(bytes, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .photoCachedSize(let type, let w, let h, let bytes): - return ("photoCachedSize", [("type", type as Any), ("w", w as Any), ("h", h as Any), ("bytes", bytes as Any)]) - case .photoPathSize(let type, let bytes): - return ("photoPathSize", [("type", type as Any), ("bytes", bytes as Any)]) - case .photoSize(let type, let w, let h, let size): - return ("photoSize", [("type", type as Any), ("w", w as Any), ("h", h as Any), ("size", size as Any)]) - case .photoSizeEmpty(let type): - return ("photoSizeEmpty", [("type", type as Any)]) - case .photoSizeProgressive(let type, let w, let h, let sizes): - return ("photoSizeProgressive", [("type", type as Any), ("w", w as Any), ("h", h as Any), ("sizes", sizes as Any)]) - case .photoStrippedSize(let type, let bytes): - return ("photoStrippedSize", [("type", type as Any), ("bytes", bytes as Any)]) - } - } - + public class Cons_photoCachedSize { + public var type: String + public var w: Int32 + public var h: Int32 + public var bytes: Buffer + public init(type: String, w: Int32, h: Int32, bytes: Buffer) { + self.type = type + self.w = w + self.h = h + self.bytes = bytes + } + } + public class Cons_photoPathSize { + public var type: String + public var bytes: Buffer + public init(type: String, bytes: Buffer) { + self.type = type + self.bytes = bytes + } + } + public class Cons_photoSize { + public var type: String + public var w: Int32 + public var h: Int32 + public var size: Int32 + public init(type: String, w: Int32, h: Int32, size: Int32) { + self.type = type + self.w = w + self.h = h + self.size = size + } + } + public class Cons_photoSizeEmpty { + public var type: String + public init(type: String) { + self.type = type + } + } + public class Cons_photoSizeProgressive { + public var type: String + public var w: Int32 + public var h: Int32 + public var sizes: [Int32] + public init(type: String, w: Int32, h: Int32, sizes: [Int32]) { + self.type = type + self.w = w + self.h = h + self.sizes = sizes + } + } + public class Cons_photoStrippedSize { + public var type: String + public var bytes: Buffer + public init(type: String, bytes: Buffer) { + self.type = type + self.bytes = bytes + } + } + case photoCachedSize(Cons_photoCachedSize) + case photoPathSize(Cons_photoPathSize) + case photoSize(Cons_photoSize) + case photoSizeEmpty(Cons_photoSizeEmpty) + case photoSizeProgressive(Cons_photoSizeProgressive) + case photoStrippedSize(Cons_photoStrippedSize) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .photoCachedSize(let _data): + if boxed { + buffer.appendInt32(35527382) + } + serializeString(_data.type, buffer: buffer, boxed: false) + serializeInt32(_data.w, buffer: buffer, boxed: false) + serializeInt32(_data.h, buffer: buffer, boxed: false) + serializeBytes(_data.bytes, buffer: buffer, boxed: false) + break + case .photoPathSize(let _data): + if boxed { + buffer.appendInt32(-668906175) + } + serializeString(_data.type, buffer: buffer, boxed: false) + serializeBytes(_data.bytes, buffer: buffer, boxed: false) + break + case .photoSize(let _data): + if boxed { + buffer.appendInt32(1976012384) + } + serializeString(_data.type, buffer: buffer, boxed: false) + serializeInt32(_data.w, buffer: buffer, boxed: false) + serializeInt32(_data.h, buffer: buffer, boxed: false) + serializeInt32(_data.size, buffer: buffer, boxed: false) + break + case .photoSizeEmpty(let _data): + if boxed { + buffer.appendInt32(236446268) + } + serializeString(_data.type, buffer: buffer, boxed: false) + break + case .photoSizeProgressive(let _data): + if boxed { + buffer.appendInt32(-96535659) + } + serializeString(_data.type, buffer: buffer, boxed: false) + serializeInt32(_data.w, buffer: buffer, boxed: false) + serializeInt32(_data.h, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.sizes.count)) + for item in _data.sizes { + serializeInt32(item, buffer: buffer, boxed: false) + } + break + case .photoStrippedSize(let _data): + if boxed { + buffer.appendInt32(-525288402) + } + serializeString(_data.type, buffer: buffer, boxed: false) + serializeBytes(_data.bytes, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .photoCachedSize(let _data): + return ("photoCachedSize", [("type", _data.type as Any), ("w", _data.w as Any), ("h", _data.h as Any), ("bytes", _data.bytes as Any)]) + case .photoPathSize(let _data): + return ("photoPathSize", [("type", _data.type as Any), ("bytes", _data.bytes as Any)]) + case .photoSize(let _data): + return ("photoSize", [("type", _data.type as Any), ("w", _data.w as Any), ("h", _data.h as Any), ("size", _data.size as Any)]) + case .photoSizeEmpty(let _data): + return ("photoSizeEmpty", [("type", _data.type as Any)]) + case .photoSizeProgressive(let _data): + return ("photoSizeProgressive", [("type", _data.type as Any), ("w", _data.w as Any), ("h", _data.h as Any), ("sizes", _data.sizes as Any)]) + case .photoStrippedSize(let _data): + return ("photoStrippedSize", [("type", _data.type as Any), ("bytes", _data.bytes as Any)]) + } + } + public static func parse_photoCachedSize(_ reader: BufferReader) -> PhotoSize? { var _1: String? _1 = parseString(reader) @@ -424,11 +559,12 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.PhotoSize.photoCachedSize(type: _1!, w: _2!, h: _3!, bytes: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.PhotoSize.photoCachedSize(Cons_photoCachedSize(type: _1!, w: _2!, h: _3!, bytes: _4!)) + } + else { + return nil + } } public static func parse_photoPathSize(_ reader: BufferReader) -> PhotoSize? { var _1: String? @@ -437,9 +573,12 @@ public extension Api { _2 = parseBytes(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PhotoSize.photoPathSize(type: _1!, bytes: _2!) + if _c1 && _c2 { + return Api.PhotoSize.photoPathSize(Cons_photoPathSize(type: _1!, bytes: _2!)) + } + else { + return nil + } } public static func parse_photoSize(_ reader: BufferReader) -> PhotoSize? { var _1: String? @@ -454,18 +593,23 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.PhotoSize.photoSize(type: _1!, w: _2!, h: _3!, size: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.PhotoSize.photoSize(Cons_photoSize(type: _1!, w: _2!, h: _3!, size: _4!)) + } + else { + return nil + } } public static func parse_photoSizeEmpty(_ reader: BufferReader) -> PhotoSize? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PhotoSize.photoSizeEmpty(type: _1!) + if _c1 { + return Api.PhotoSize.photoSizeEmpty(Cons_photoSizeEmpty(type: _1!)) + } + else { + return nil + } } public static func parse_photoSizeProgressive(_ reader: BufferReader) -> PhotoSize? { var _1: String? @@ -482,11 +626,12 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.PhotoSize.photoSizeProgressive(type: _1!, w: _2!, h: _3!, sizes: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.PhotoSize.photoSizeProgressive(Cons_photoSizeProgressive(type: _1!, w: _2!, h: _3!, sizes: _4!)) + } + else { + return nil + } } public static func parse_photoStrippedSize(_ reader: BufferReader) -> PhotoSize? { var _1: String? @@ -495,44 +640,66 @@ public extension Api { _2 = parseBytes(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PhotoSize.photoStrippedSize(type: _1!, bytes: _2!) + if _c1 && _c2 { + return Api.PhotoSize.photoStrippedSize(Cons_photoStrippedSize(type: _1!, bytes: _2!)) + } + else { + return nil + } } - } } public extension Api { enum Poll: TypeConstructorDescription { - case poll(id: Int64, flags: Int32, question: Api.TextWithEntities, answers: [Api.PollAnswer], closePeriod: Int32?, closeDate: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .poll(let id, let flags, let question, let answers, let closePeriod, let closeDate): - if boxed { - buffer.appendInt32(1484026161) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt32(flags, buffer: buffer, boxed: false) - question.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(answers.count)) - for item in answers { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(closePeriod!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeInt32(closeDate!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .poll(let id, let flags, let question, let answers, let closePeriod, let closeDate): - return ("poll", [("id", id as Any), ("flags", flags as Any), ("question", question as Any), ("answers", answers as Any), ("closePeriod", closePeriod as Any), ("closeDate", closeDate as Any)]) - } - } - + public class Cons_poll { + public var id: Int64 + public var flags: Int32 + public var question: Api.TextWithEntities + public var answers: [Api.PollAnswer] + public var closePeriod: Int32? + public var closeDate: Int32? + public init(id: Int64, flags: Int32, question: Api.TextWithEntities, answers: [Api.PollAnswer], closePeriod: Int32?, closeDate: Int32?) { + self.id = id + self.flags = flags + self.question = question + self.answers = answers + self.closePeriod = closePeriod + self.closeDate = closeDate + } + } + case poll(Cons_poll) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .poll(let _data): + if boxed { + buffer.appendInt32(1484026161) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.question.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.answers.count)) + for item in _data.answers { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.closePeriod!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeInt32(_data.closeDate!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .poll(let _data): + return ("poll", [("id", _data.id as Any), ("flags", _data.flags as Any), ("question", _data.question as Any), ("answers", _data.answers as Any), ("closePeriod", _data.closePeriod as Any), ("closeDate", _data.closeDate as Any)]) + } + } + public static func parse_poll(_ reader: BufferReader) -> Poll? { var _1: Int64? _1 = reader.readInt64() @@ -547,49 +714,59 @@ public extension Api { _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PollAnswer.self) } var _5: Int32? - if Int(_2!) & Int(1 << 4) != 0 {_5 = reader.readInt32() } + if Int(_2!) & Int(1 << 4) != 0 { + _5 = reader.readInt32() + } var _6: Int32? - if Int(_2!) & Int(1 << 5) != 0 {_6 = reader.readInt32() } + if Int(_2!) & Int(1 << 5) != 0 { + _6 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = (Int(_2!) & Int(1 << 4) == 0) || _5 != nil let _c6 = (Int(_2!) & Int(1 << 5) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.Poll.poll(id: _1!, flags: _2!, question: _3!, answers: _4!, closePeriod: _5, closeDate: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.Poll.poll(Cons_poll(id: _1!, flags: _2!, question: _3!, answers: _4!, closePeriod: _5, closeDate: _6)) + } + else { + return nil + } } - } } public extension Api { enum PollAnswer: TypeConstructorDescription { - case pollAnswer(text: Api.TextWithEntities, option: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .pollAnswer(let text, let option): - if boxed { - buffer.appendInt32(-15277366) - } - text.serialize(buffer, true) - serializeBytes(option, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .pollAnswer(let text, let option): - return ("pollAnswer", [("text", text as Any), ("option", option as Any)]) - } - } - + public class Cons_pollAnswer { + public var text: Api.TextWithEntities + public var option: Buffer + public init(text: Api.TextWithEntities, option: Buffer) { + self.text = text + self.option = option + } + } + case pollAnswer(Cons_pollAnswer) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .pollAnswer(let _data): + if boxed { + buffer.appendInt32(-15277366) + } + _data.text.serialize(buffer, true) + serializeBytes(_data.option, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .pollAnswer(let _data): + return ("pollAnswer", [("text", _data.text as Any), ("option", _data.option as Any)]) + } + } + public static func parse_pollAnswer(_ reader: BufferReader) -> PollAnswer? { var _1: Api.TextWithEntities? if let signature = reader.readInt32() { @@ -599,37 +776,49 @@ public extension Api { _2 = parseBytes(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PollAnswer.pollAnswer(text: _1!, option: _2!) + if _c1 && _c2 { + return Api.PollAnswer.pollAnswer(Cons_pollAnswer(text: _1!, option: _2!)) + } + else { + return nil + } } - } } public extension Api { enum PollAnswerVoters: TypeConstructorDescription { - case pollAnswerVoters(flags: Int32, option: Buffer, voters: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .pollAnswerVoters(let flags, let option, let voters): - if boxed { - buffer.appendInt32(997055186) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeBytes(option, buffer: buffer, boxed: false) - serializeInt32(voters, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .pollAnswerVoters(let flags, let option, let voters): - return ("pollAnswerVoters", [("flags", flags as Any), ("option", option as Any), ("voters", voters as Any)]) - } - } - + public class Cons_pollAnswerVoters { + public var flags: Int32 + public var option: Buffer + public var voters: Int32 + public init(flags: Int32, option: Buffer, voters: Int32) { + self.flags = flags + self.option = option + self.voters = voters + } + } + case pollAnswerVoters(Cons_pollAnswerVoters) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .pollAnswerVoters(let _data): + if boxed { + buffer.appendInt32(997055186) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeBytes(_data.option, buffer: buffer, boxed: false) + serializeInt32(_data.voters, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .pollAnswerVoters(let _data): + return ("pollAnswerVoters", [("flags", _data.flags as Any), ("option", _data.option as Any), ("voters", _data.voters as Any)]) + } + } + public static func parse_pollAnswerVoters(_ reader: BufferReader) -> PollAnswerVoters? { var _1: Int32? _1 = reader.readInt32() @@ -640,112 +829,155 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.PollAnswerVoters.pollAnswerVoters(flags: _1!, option: _2!, voters: _3!) + if _c1 && _c2 && _c3 { + return Api.PollAnswerVoters.pollAnswerVoters(Cons_pollAnswerVoters(flags: _1!, option: _2!, voters: _3!)) + } + else { + return nil + } } - } } public extension Api { enum PollResults: TypeConstructorDescription { - case pollResults(flags: Int32, results: [Api.PollAnswerVoters]?, totalVoters: Int32?, recentVoters: [Api.Peer]?, solution: String?, solutionEntities: [Api.MessageEntity]?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .pollResults(let flags, let results, let totalVoters, let recentVoters, let solution, let solutionEntities): - if boxed { - buffer.appendInt32(2061444128) + public class Cons_pollResults { + public var flags: Int32 + public var results: [Api.PollAnswerVoters]? + public var totalVoters: Int32? + public var recentVoters: [Api.Peer]? + public var solution: String? + public var solutionEntities: [Api.MessageEntity]? + public init(flags: Int32, results: [Api.PollAnswerVoters]?, totalVoters: Int32?, recentVoters: [Api.Peer]?, solution: String?, solutionEntities: [Api.MessageEntity]?) { + self.flags = flags + self.results = results + self.totalVoters = totalVoters + self.recentVoters = recentVoters + self.solution = solution + self.solutionEntities = solutionEntities + } + } + case pollResults(Cons_pollResults) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .pollResults(let _data): + if boxed { + buffer.appendInt32(2061444128) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.results!.count)) + for item in _data.results! { + item.serialize(buffer, true) } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(results!.count)) - for item in results! { + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.totalVoters!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.recentVoters!.count)) + for item in _data.recentVoters! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(totalVoters!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(recentVoters!.count)) - for item in recentVoters! { + } + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeString(_data.solution!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.solutionEntities!.count)) + for item in _data.solutionEntities! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 4) != 0 {serializeString(solution!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(solutionEntities!.count)) - for item in solutionEntities! { - item.serialize(buffer, true) - }} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .pollResults(let flags, let results, let totalVoters, let recentVoters, let solution, let solutionEntities): - return ("pollResults", [("flags", flags as Any), ("results", results as Any), ("totalVoters", totalVoters as Any), ("recentVoters", recentVoters as Any), ("solution", solution as Any), ("solutionEntities", solutionEntities as Any)]) - } - } - + } + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .pollResults(let _data): + return ("pollResults", [("flags", _data.flags as Any), ("results", _data.results as Any), ("totalVoters", _data.totalVoters as Any), ("recentVoters", _data.recentVoters as Any), ("solution", _data.solution as Any), ("solutionEntities", _data.solutionEntities as Any)]) + } + } + public static func parse_pollResults(_ reader: BufferReader) -> PollResults? { var _1: Int32? _1 = reader.readInt32() var _2: [Api.PollAnswerVoters]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PollAnswerVoters.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PollAnswerVoters.self) + } + } var _3: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _3 = reader.readInt32() + } var _4: [Api.Peer]? - if Int(_1!) & Int(1 << 3) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) + } + } var _5: String? - if Int(_1!) & Int(1 << 4) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 4) != 0 { + _5 = parseString(reader) + } var _6: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 4) != 0 {if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 2) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 3) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 4) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 4) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.PollResults.pollResults(flags: _1!, results: _2, totalVoters: _3, recentVoters: _4, solution: _5, solutionEntities: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.PollResults.pollResults(Cons_pollResults(flags: _1!, results: _2, totalVoters: _3, recentVoters: _4, solution: _5, solutionEntities: _6)) + } + else { + return nil + } } - } } public extension Api { enum PopularContact: TypeConstructorDescription { - case popularContact(clientId: Int64, importers: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .popularContact(let clientId, let importers): - if boxed { - buffer.appendInt32(1558266229) - } - serializeInt64(clientId, buffer: buffer, boxed: false) - serializeInt32(importers, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .popularContact(let clientId, let importers): - return ("popularContact", [("clientId", clientId as Any), ("importers", importers as Any)]) - } - } - + public class Cons_popularContact { + public var clientId: Int64 + public var importers: Int32 + public init(clientId: Int64, importers: Int32) { + self.clientId = clientId + self.importers = importers + } + } + case popularContact(Cons_popularContact) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .popularContact(let _data): + if boxed { + buffer.appendInt32(1558266229) + } + serializeInt64(_data.clientId, buffer: buffer, boxed: false) + serializeInt32(_data.importers, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .popularContact(let _data): + return ("popularContact", [("clientId", _data.clientId as Any), ("importers", _data.importers as Any)]) + } + } + public static func parse_popularContact(_ reader: BufferReader) -> PopularContact? { var _1: Int64? _1 = reader.readInt64() @@ -753,40 +985,58 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PopularContact.popularContact(clientId: _1!, importers: _2!) + if _c1 && _c2 { + return Api.PopularContact.popularContact(Cons_popularContact(clientId: _1!, importers: _2!)) + } + else { + return nil + } } - } } public extension Api { enum PostAddress: TypeConstructorDescription { - case postAddress(streetLine1: String, streetLine2: String, city: String, state: String, countryIso2: String, postCode: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .postAddress(let streetLine1, let streetLine2, let city, let state, let countryIso2, let postCode): - if boxed { - buffer.appendInt32(512535275) - } - serializeString(streetLine1, buffer: buffer, boxed: false) - serializeString(streetLine2, buffer: buffer, boxed: false) - serializeString(city, buffer: buffer, boxed: false) - serializeString(state, buffer: buffer, boxed: false) - serializeString(countryIso2, buffer: buffer, boxed: false) - serializeString(postCode, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .postAddress(let streetLine1, let streetLine2, let city, let state, let countryIso2, let postCode): - return ("postAddress", [("streetLine1", streetLine1 as Any), ("streetLine2", streetLine2 as Any), ("city", city as Any), ("state", state as Any), ("countryIso2", countryIso2 as Any), ("postCode", postCode as Any)]) - } - } - + public class Cons_postAddress { + public var streetLine1: String + public var streetLine2: String + public var city: String + public var state: String + public var countryIso2: String + public var postCode: String + public init(streetLine1: String, streetLine2: String, city: String, state: String, countryIso2: String, postCode: String) { + self.streetLine1 = streetLine1 + self.streetLine2 = streetLine2 + self.city = city + self.state = state + self.countryIso2 = countryIso2 + self.postCode = postCode + } + } + case postAddress(Cons_postAddress) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .postAddress(let _data): + if boxed { + buffer.appendInt32(512535275) + } + serializeString(_data.streetLine1, buffer: buffer, boxed: false) + serializeString(_data.streetLine2, buffer: buffer, boxed: false) + serializeString(_data.city, buffer: buffer, boxed: false) + serializeString(_data.state, buffer: buffer, boxed: false) + serializeString(_data.countryIso2, buffer: buffer, boxed: false) + serializeString(_data.postCode, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .postAddress(let _data): + return ("postAddress", [("streetLine1", _data.streetLine1 as Any), ("streetLine2", _data.streetLine2 as Any), ("city", _data.city as Any), ("state", _data.state as Any), ("countryIso2", _data.countryIso2 as Any), ("postCode", _data.postCode as Any)]) + } + } + public static func parse_postAddress(_ reader: BufferReader) -> PostAddress? { var _1: String? _1 = parseString(reader) @@ -806,54 +1056,76 @@ public extension Api { let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.PostAddress.postAddress(streetLine1: _1!, streetLine2: _2!, city: _3!, state: _4!, countryIso2: _5!, postCode: _6!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.PostAddress.postAddress(Cons_postAddress(streetLine1: _1!, streetLine2: _2!, city: _3!, state: _4!, countryIso2: _5!, postCode: _6!)) + } + else { + return nil + } } - } } public extension Api { enum PostInteractionCounters: TypeConstructorDescription { - case postInteractionCountersMessage(msgId: Int32, views: Int32, forwards: Int32, reactions: Int32) - case postInteractionCountersStory(storyId: Int32, views: Int32, forwards: Int32, reactions: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .postInteractionCountersMessage(let msgId, let views, let forwards, let reactions): - if boxed { - buffer.appendInt32(-419066241) - } - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeInt32(views, buffer: buffer, boxed: false) - serializeInt32(forwards, buffer: buffer, boxed: false) - serializeInt32(reactions, buffer: buffer, boxed: false) - break - case .postInteractionCountersStory(let storyId, let views, let forwards, let reactions): - if boxed { - buffer.appendInt32(-1974989273) - } - serializeInt32(storyId, buffer: buffer, boxed: false) - serializeInt32(views, buffer: buffer, boxed: false) - serializeInt32(forwards, buffer: buffer, boxed: false) - serializeInt32(reactions, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .postInteractionCountersMessage(let msgId, let views, let forwards, let reactions): - return ("postInteractionCountersMessage", [("msgId", msgId as Any), ("views", views as Any), ("forwards", forwards as Any), ("reactions", reactions as Any)]) - case .postInteractionCountersStory(let storyId, let views, let forwards, let reactions): - return ("postInteractionCountersStory", [("storyId", storyId as Any), ("views", views as Any), ("forwards", forwards as Any), ("reactions", reactions as Any)]) - } - } - + public class Cons_postInteractionCountersMessage { + public var msgId: Int32 + public var views: Int32 + public var forwards: Int32 + public var reactions: Int32 + public init(msgId: Int32, views: Int32, forwards: Int32, reactions: Int32) { + self.msgId = msgId + self.views = views + self.forwards = forwards + self.reactions = reactions + } + } + public class Cons_postInteractionCountersStory { + public var storyId: Int32 + public var views: Int32 + public var forwards: Int32 + public var reactions: Int32 + public init(storyId: Int32, views: Int32, forwards: Int32, reactions: Int32) { + self.storyId = storyId + self.views = views + self.forwards = forwards + self.reactions = reactions + } + } + case postInteractionCountersMessage(Cons_postInteractionCountersMessage) + case postInteractionCountersStory(Cons_postInteractionCountersStory) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .postInteractionCountersMessage(let _data): + if boxed { + buffer.appendInt32(-419066241) + } + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + serializeInt32(_data.views, buffer: buffer, boxed: false) + serializeInt32(_data.forwards, buffer: buffer, boxed: false) + serializeInt32(_data.reactions, buffer: buffer, boxed: false) + break + case .postInteractionCountersStory(let _data): + if boxed { + buffer.appendInt32(-1974989273) + } + serializeInt32(_data.storyId, buffer: buffer, boxed: false) + serializeInt32(_data.views, buffer: buffer, boxed: false) + serializeInt32(_data.forwards, buffer: buffer, boxed: false) + serializeInt32(_data.reactions, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .postInteractionCountersMessage(let _data): + return ("postInteractionCountersMessage", [("msgId", _data.msgId as Any), ("views", _data.views as Any), ("forwards", _data.forwards as Any), ("reactions", _data.reactions as Any)]) + case .postInteractionCountersStory(let _data): + return ("postInteractionCountersStory", [("storyId", _data.storyId as Any), ("views", _data.views as Any), ("forwards", _data.forwards as Any), ("reactions", _data.reactions as Any)]) + } + } + public static func parse_postInteractionCountersMessage(_ reader: BufferReader) -> PostInteractionCounters? { var _1: Int32? _1 = reader.readInt32() @@ -867,11 +1139,12 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.PostInteractionCounters.postInteractionCountersMessage(msgId: _1!, views: _2!, forwards: _3!, reactions: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.PostInteractionCounters.postInteractionCountersMessage(Cons_postInteractionCountersMessage(msgId: _1!, views: _2!, forwards: _3!, reactions: _4!)) + } + else { + return nil + } } public static func parse_postInteractionCountersStory(_ reader: BufferReader) -> PostInteractionCounters? { var _1: Int32? @@ -886,43 +1159,65 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.PostInteractionCounters.postInteractionCountersStory(storyId: _1!, views: _2!, forwards: _3!, reactions: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.PostInteractionCounters.postInteractionCountersStory(Cons_postInteractionCountersStory(storyId: _1!, views: _2!, forwards: _3!, reactions: _4!)) + } + else { + return nil + } } - } } public extension Api { enum PremiumGiftCodeOption: TypeConstructorDescription { - case premiumGiftCodeOption(flags: Int32, users: Int32, months: Int32, storeProduct: String?, storeQuantity: Int32?, currency: String, amount: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .premiumGiftCodeOption(let flags, let users, let months, let storeProduct, let storeQuantity, let currency, let amount): - if boxed { - buffer.appendInt32(629052971) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(users, buffer: buffer, boxed: false) - serializeInt32(months, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(storeProduct!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(storeQuantity!, buffer: buffer, boxed: false)} - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .premiumGiftCodeOption(let flags, let users, let months, let storeProduct, let storeQuantity, let currency, let amount): - return ("premiumGiftCodeOption", [("flags", flags as Any), ("users", users as Any), ("months", months as Any), ("storeProduct", storeProduct as Any), ("storeQuantity", storeQuantity as Any), ("currency", currency as Any), ("amount", amount as Any)]) - } - } - + public class Cons_premiumGiftCodeOption { + public var flags: Int32 + public var users: Int32 + public var months: Int32 + public var storeProduct: String? + public var storeQuantity: Int32? + public var currency: String + public var amount: Int64 + public init(flags: Int32, users: Int32, months: Int32, storeProduct: String?, storeQuantity: Int32?, currency: String, amount: Int64) { + self.flags = flags + self.users = users + self.months = months + self.storeProduct = storeProduct + self.storeQuantity = storeQuantity + self.currency = currency + self.amount = amount + } + } + case premiumGiftCodeOption(Cons_premiumGiftCodeOption) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .premiumGiftCodeOption(let _data): + if boxed { + buffer.appendInt32(629052971) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.users, buffer: buffer, boxed: false) + serializeInt32(_data.months, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.storeProduct!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.storeQuantity!, buffer: buffer, boxed: false) + } + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .premiumGiftCodeOption(let _data): + return ("premiumGiftCodeOption", [("flags", _data.flags as Any), ("users", _data.users as Any), ("months", _data.months as Any), ("storeProduct", _data.storeProduct as Any), ("storeQuantity", _data.storeQuantity as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any)]) + } + } + public static func parse_premiumGiftCodeOption(_ reader: BufferReader) -> PremiumGiftCodeOption? { var _1: Int32? _1 = reader.readInt32() @@ -931,9 +1226,13 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: String? - if Int(_1!) & Int(1 << 0) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) + } var _5: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _5 = reader.readInt32() + } var _6: String? _6 = parseString(reader) var _7: Int64? @@ -945,51 +1244,72 @@ public extension Api { let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil let _c6 = _6 != nil let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.PremiumGiftCodeOption.premiumGiftCodeOption(flags: _1!, users: _2!, months: _3!, storeProduct: _4, storeQuantity: _5, currency: _6!, amount: _7!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.PremiumGiftCodeOption.premiumGiftCodeOption(Cons_premiumGiftCodeOption(flags: _1!, users: _2!, months: _3!, storeProduct: _4, storeQuantity: _5, currency: _6!, amount: _7!)) + } + else { + return nil + } } - } } public extension Api { enum PremiumSubscriptionOption: TypeConstructorDescription { - case premiumSubscriptionOption(flags: Int32, transaction: String?, months: Int32, currency: String, amount: Int64, botUrl: String, storeProduct: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .premiumSubscriptionOption(let flags, let transaction, let months, let currency, let amount, let botUrl, let storeProduct): - if boxed { - buffer.appendInt32(1596792306) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {serializeString(transaction!, buffer: buffer, boxed: false)} - serializeInt32(months, buffer: buffer, boxed: false) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - serializeString(botUrl, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(storeProduct!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .premiumSubscriptionOption(let flags, let transaction, let months, let currency, let amount, let botUrl, let storeProduct): - return ("premiumSubscriptionOption", [("flags", flags as Any), ("transaction", transaction as Any), ("months", months as Any), ("currency", currency as Any), ("amount", amount as Any), ("botUrl", botUrl as Any), ("storeProduct", storeProduct as Any)]) - } - } - + public class Cons_premiumSubscriptionOption { + public var flags: Int32 + public var transaction: String? + public var months: Int32 + public var currency: String + public var amount: Int64 + public var botUrl: String + public var storeProduct: String? + public init(flags: Int32, transaction: String?, months: Int32, currency: String, amount: Int64, botUrl: String, storeProduct: String?) { + self.flags = flags + self.transaction = transaction + self.months = months + self.currency = currency + self.amount = amount + self.botUrl = botUrl + self.storeProduct = storeProduct + } + } + case premiumSubscriptionOption(Cons_premiumSubscriptionOption) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .premiumSubscriptionOption(let _data): + if boxed { + buffer.appendInt32(1596792306) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.transaction!, buffer: buffer, boxed: false) + } + serializeInt32(_data.months, buffer: buffer, boxed: false) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + serializeString(_data.botUrl, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.storeProduct!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .premiumSubscriptionOption(let _data): + return ("premiumSubscriptionOption", [("flags", _data.flags as Any), ("transaction", _data.transaction as Any), ("months", _data.months as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any), ("botUrl", _data.botUrl as Any), ("storeProduct", _data.storeProduct as Any)]) + } + } + public static func parse_premiumSubscriptionOption(_ reader: BufferReader) -> PremiumSubscriptionOption? { var _1: Int32? _1 = reader.readInt32() var _2: String? - if Int(_1!) & Int(1 << 3) != 0 {_2 = parseString(reader) } + if Int(_1!) & Int(1 << 3) != 0 { + _2 = parseString(reader) + } var _3: Int32? _3 = reader.readInt32() var _4: String? @@ -999,7 +1319,9 @@ public extension Api { var _6: String? _6 = parseString(reader) var _7: String? - if Int(_1!) & Int(1 << 0) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _7 = parseString(reader) + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 3) == 0) || _2 != nil let _c3 = _3 != nil @@ -1007,56 +1329,79 @@ public extension Api { let _c5 = _5 != nil let _c6 = _6 != nil let _c7 = (Int(_1!) & Int(1 << 0) == 0) || _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.PremiumSubscriptionOption.premiumSubscriptionOption(flags: _1!, transaction: _2, months: _3!, currency: _4!, amount: _5!, botUrl: _6!, storeProduct: _7) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.PremiumSubscriptionOption.premiumSubscriptionOption(Cons_premiumSubscriptionOption(flags: _1!, transaction: _2, months: _3!, currency: _4!, amount: _5!, botUrl: _6!, storeProduct: _7)) + } + else { + return nil + } } - } } public extension Api { enum PrepaidGiveaway: TypeConstructorDescription { - case prepaidGiveaway(id: Int64, months: Int32, quantity: Int32, date: Int32) - case prepaidStarsGiveaway(id: Int64, stars: Int64, quantity: Int32, boosts: Int32, date: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .prepaidGiveaway(let id, let months, let quantity, let date): - if boxed { - buffer.appendInt32(-1303143084) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt32(months, buffer: buffer, boxed: false) - serializeInt32(quantity, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - break - case .prepaidStarsGiveaway(let id, let stars, let quantity, let boosts, let date): - if boxed { - buffer.appendInt32(-1700956192) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(stars, buffer: buffer, boxed: false) - serializeInt32(quantity, buffer: buffer, boxed: false) - serializeInt32(boosts, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .prepaidGiveaway(let id, let months, let quantity, let date): - return ("prepaidGiveaway", [("id", id as Any), ("months", months as Any), ("quantity", quantity as Any), ("date", date as Any)]) - case .prepaidStarsGiveaway(let id, let stars, let quantity, let boosts, let date): - return ("prepaidStarsGiveaway", [("id", id as Any), ("stars", stars as Any), ("quantity", quantity as Any), ("boosts", boosts as Any), ("date", date as Any)]) - } - } - + public class Cons_prepaidGiveaway { + public var id: Int64 + public var months: Int32 + public var quantity: Int32 + public var date: Int32 + public init(id: Int64, months: Int32, quantity: Int32, date: Int32) { + self.id = id + self.months = months + self.quantity = quantity + self.date = date + } + } + public class Cons_prepaidStarsGiveaway { + public var id: Int64 + public var stars: Int64 + public var quantity: Int32 + public var boosts: Int32 + public var date: Int32 + public init(id: Int64, stars: Int64, quantity: Int32, boosts: Int32, date: Int32) { + self.id = id + self.stars = stars + self.quantity = quantity + self.boosts = boosts + self.date = date + } + } + case prepaidGiveaway(Cons_prepaidGiveaway) + case prepaidStarsGiveaway(Cons_prepaidStarsGiveaway) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .prepaidGiveaway(let _data): + if boxed { + buffer.appendInt32(-1303143084) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.months, buffer: buffer, boxed: false) + serializeInt32(_data.quantity, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + case .prepaidStarsGiveaway(let _data): + if boxed { + buffer.appendInt32(-1700956192) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.stars, buffer: buffer, boxed: false) + serializeInt32(_data.quantity, buffer: buffer, boxed: false) + serializeInt32(_data.boosts, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .prepaidGiveaway(let _data): + return ("prepaidGiveaway", [("id", _data.id as Any), ("months", _data.months as Any), ("quantity", _data.quantity as Any), ("date", _data.date as Any)]) + case .prepaidStarsGiveaway(let _data): + return ("prepaidStarsGiveaway", [("id", _data.id as Any), ("stars", _data.stars as Any), ("quantity", _data.quantity as Any), ("boosts", _data.boosts as Any), ("date", _data.date as Any)]) + } + } + public static func parse_prepaidGiveaway(_ reader: BufferReader) -> PrepaidGiveaway? { var _1: Int64? _1 = reader.readInt64() @@ -1070,11 +1415,12 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.PrepaidGiveaway.prepaidGiveaway(id: _1!, months: _2!, quantity: _3!, date: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.PrepaidGiveaway.prepaidGiveaway(Cons_prepaidGiveaway(id: _1!, months: _2!, quantity: _3!, date: _4!)) + } + else { + return nil + } } public static func parse_prepaidStarsGiveaway(_ reader: BufferReader) -> PrepaidGiveaway? { var _1: Int64? @@ -1092,14 +1438,13 @@ public extension Api { let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.PrepaidGiveaway.prepaidStarsGiveaway(id: _1!, stars: _2!, quantity: _3!, boosts: _4!, date: _5!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.PrepaidGiveaway.prepaidStarsGiveaway(Cons_prepaidStarsGiveaway(id: _1!, stars: _2!, quantity: _3!, boosts: _4!, date: _5!)) + } + else { + return nil + } } - } } public extension Api { @@ -1118,129 +1463,115 @@ public extension Api { case privacyKeyStarGiftsAutoSave case privacyKeyStatusTimestamp case privacyKeyVoiceMessages - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .privacyKeyAbout: - if boxed { - buffer.appendInt32(-1534675103) - } - - break - case .privacyKeyAddedByPhone: - if boxed { - buffer.appendInt32(1124062251) - } - - break - case .privacyKeyBirthday: - if boxed { - buffer.appendInt32(536913176) - } - - break - case .privacyKeyChatInvite: - if boxed { - buffer.appendInt32(1343122938) - } - - break - case .privacyKeyForwards: - if boxed { - buffer.appendInt32(1777096355) - } - - break - case .privacyKeyNoPaidMessages: - if boxed { - buffer.appendInt32(399722706) - } - - break - case .privacyKeyPhoneCall: - if boxed { - buffer.appendInt32(1030105979) - } - - break - case .privacyKeyPhoneNumber: - if boxed { - buffer.appendInt32(-778378131) - } - - break - case .privacyKeyPhoneP2P: - if boxed { - buffer.appendInt32(961092808) - } - - break - case .privacyKeyProfilePhoto: - if boxed { - buffer.appendInt32(-1777000467) - } - - break - case .privacyKeySavedMusic: - if boxed { - buffer.appendInt32(-8759525) - } - - break - case .privacyKeyStarGiftsAutoSave: - if boxed { - buffer.appendInt32(749010424) - } - - break - case .privacyKeyStatusTimestamp: - if boxed { - buffer.appendInt32(-1137792208) - } - - break - case .privacyKeyVoiceMessages: - if boxed { - buffer.appendInt32(110621716) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .privacyKeyAbout: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .privacyKeyAbout: + if boxed { + buffer.appendInt32(-1534675103) + } + break + case .privacyKeyAddedByPhone: + if boxed { + buffer.appendInt32(1124062251) + } + break + case .privacyKeyBirthday: + if boxed { + buffer.appendInt32(536913176) + } + break + case .privacyKeyChatInvite: + if boxed { + buffer.appendInt32(1343122938) + } + break + case .privacyKeyForwards: + if boxed { + buffer.appendInt32(1777096355) + } + break + case .privacyKeyNoPaidMessages: + if boxed { + buffer.appendInt32(399722706) + } + break + case .privacyKeyPhoneCall: + if boxed { + buffer.appendInt32(1030105979) + } + break + case .privacyKeyPhoneNumber: + if boxed { + buffer.appendInt32(-778378131) + } + break + case .privacyKeyPhoneP2P: + if boxed { + buffer.appendInt32(961092808) + } + break + case .privacyKeyProfilePhoto: + if boxed { + buffer.appendInt32(-1777000467) + } + break + case .privacyKeySavedMusic: + if boxed { + buffer.appendInt32(-8759525) + } + break + case .privacyKeyStarGiftsAutoSave: + if boxed { + buffer.appendInt32(749010424) + } + break + case .privacyKeyStatusTimestamp: + if boxed { + buffer.appendInt32(-1137792208) + } + break + case .privacyKeyVoiceMessages: + if boxed { + buffer.appendInt32(110621716) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .privacyKeyAbout: return ("privacyKeyAbout", []) - case .privacyKeyAddedByPhone: + case .privacyKeyAddedByPhone: return ("privacyKeyAddedByPhone", []) - case .privacyKeyBirthday: + case .privacyKeyBirthday: return ("privacyKeyBirthday", []) - case .privacyKeyChatInvite: + case .privacyKeyChatInvite: return ("privacyKeyChatInvite", []) - case .privacyKeyForwards: + case .privacyKeyForwards: return ("privacyKeyForwards", []) - case .privacyKeyNoPaidMessages: + case .privacyKeyNoPaidMessages: return ("privacyKeyNoPaidMessages", []) - case .privacyKeyPhoneCall: + case .privacyKeyPhoneCall: return ("privacyKeyPhoneCall", []) - case .privacyKeyPhoneNumber: + case .privacyKeyPhoneNumber: return ("privacyKeyPhoneNumber", []) - case .privacyKeyPhoneP2P: + case .privacyKeyPhoneP2P: return ("privacyKeyPhoneP2P", []) - case .privacyKeyProfilePhoto: + case .privacyKeyProfilePhoto: return ("privacyKeyProfilePhoto", []) - case .privacyKeySavedMusic: + case .privacyKeySavedMusic: return ("privacyKeySavedMusic", []) - case .privacyKeyStarGiftsAutoSave: + case .privacyKeyStarGiftsAutoSave: return ("privacyKeyStarGiftsAutoSave", []) - case .privacyKeyStatusTimestamp: + case .privacyKeyStatusTimestamp: return ("privacyKeyStatusTimestamp", []) - case .privacyKeyVoiceMessages: + case .privacyKeyVoiceMessages: return ("privacyKeyVoiceMessages", []) - } - } - + } + } + public static func parse_privacyKeyAbout(_ reader: BufferReader) -> PrivacyKey? { return Api.PrivacyKey.privacyKeyAbout } @@ -1283,6 +1614,5 @@ public extension Api { public static func parse_privacyKeyVoiceMessages(_ reader: BufferReader) -> PrivacyKey? { return Api.PrivacyKey.privacyKeyVoiceMessages } - } } diff --git a/submodules/TelegramApi/Sources/Api21.swift b/submodules/TelegramApi/Sources/Api21.swift index a40db16a..910a781e 100644 --- a/submodules/TelegramApi/Sources/Api21.swift +++ b/submodules/TelegramApi/Sources/Api21.swift @@ -1,140 +1,156 @@ public extension Api { enum PrivacyRule: TypeConstructorDescription { + public class Cons_privacyValueAllowChatParticipants { + public var chats: [Int64] + public init(chats: [Int64]) { + self.chats = chats + } + } + public class Cons_privacyValueAllowUsers { + public var users: [Int64] + public init(users: [Int64]) { + self.users = users + } + } + public class Cons_privacyValueDisallowChatParticipants { + public var chats: [Int64] + public init(chats: [Int64]) { + self.chats = chats + } + } + public class Cons_privacyValueDisallowUsers { + public var users: [Int64] + public init(users: [Int64]) { + self.users = users + } + } case privacyValueAllowAll case privacyValueAllowBots - case privacyValueAllowChatParticipants(chats: [Int64]) + case privacyValueAllowChatParticipants(Cons_privacyValueAllowChatParticipants) case privacyValueAllowCloseFriends case privacyValueAllowContacts case privacyValueAllowPremium - case privacyValueAllowUsers(users: [Int64]) + case privacyValueAllowUsers(Cons_privacyValueAllowUsers) case privacyValueDisallowAll case privacyValueDisallowBots - case privacyValueDisallowChatParticipants(chats: [Int64]) + case privacyValueDisallowChatParticipants(Cons_privacyValueDisallowChatParticipants) case privacyValueDisallowContacts - case privacyValueDisallowUsers(users: [Int64]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .privacyValueAllowAll: - if boxed { - buffer.appendInt32(1698855810) - } - - break - case .privacyValueAllowBots: - if boxed { - buffer.appendInt32(558242653) - } - - break - case .privacyValueAllowChatParticipants(let chats): - if boxed { - buffer.appendInt32(1796427406) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - serializeInt64(item, buffer: buffer, boxed: false) - } - break - case .privacyValueAllowCloseFriends: - if boxed { - buffer.appendInt32(-135735141) - } - - break - case .privacyValueAllowContacts: - if boxed { - buffer.appendInt32(-123988) - } - - break - case .privacyValueAllowPremium: - if boxed { - buffer.appendInt32(-320241333) - } - - break - case .privacyValueAllowUsers(let users): - if boxed { - buffer.appendInt32(-1198497870) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - serializeInt64(item, buffer: buffer, boxed: false) - } - break - case .privacyValueDisallowAll: - if boxed { - buffer.appendInt32(-1955338397) - } - - break - case .privacyValueDisallowBots: - if boxed { - buffer.appendInt32(-156895185) - } - - break - case .privacyValueDisallowChatParticipants(let chats): - if boxed { - buffer.appendInt32(1103656293) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - serializeInt64(item, buffer: buffer, boxed: false) - } - break - case .privacyValueDisallowContacts: - if boxed { - buffer.appendInt32(-125240806) - } - - break - case .privacyValueDisallowUsers(let users): - if boxed { - buffer.appendInt32(-463335103) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - serializeInt64(item, buffer: buffer, boxed: false) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .privacyValueAllowAll: + case privacyValueDisallowUsers(Cons_privacyValueDisallowUsers) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .privacyValueAllowAll: + if boxed { + buffer.appendInt32(1698855810) + } + break + case .privacyValueAllowBots: + if boxed { + buffer.appendInt32(558242653) + } + break + case .privacyValueAllowChatParticipants(let _data): + if boxed { + buffer.appendInt32(1796427406) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + serializeInt64(item, buffer: buffer, boxed: false) + } + break + case .privacyValueAllowCloseFriends: + if boxed { + buffer.appendInt32(-135735141) + } + break + case .privacyValueAllowContacts: + if boxed { + buffer.appendInt32(-123988) + } + break + case .privacyValueAllowPremium: + if boxed { + buffer.appendInt32(-320241333) + } + break + case .privacyValueAllowUsers(let _data): + if boxed { + buffer.appendInt32(-1198497870) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + serializeInt64(item, buffer: buffer, boxed: false) + } + break + case .privacyValueDisallowAll: + if boxed { + buffer.appendInt32(-1955338397) + } + break + case .privacyValueDisallowBots: + if boxed { + buffer.appendInt32(-156895185) + } + break + case .privacyValueDisallowChatParticipants(let _data): + if boxed { + buffer.appendInt32(1103656293) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + serializeInt64(item, buffer: buffer, boxed: false) + } + break + case .privacyValueDisallowContacts: + if boxed { + buffer.appendInt32(-125240806) + } + break + case .privacyValueDisallowUsers(let _data): + if boxed { + buffer.appendInt32(-463335103) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + serializeInt64(item, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .privacyValueAllowAll: return ("privacyValueAllowAll", []) - case .privacyValueAllowBots: + case .privacyValueAllowBots: return ("privacyValueAllowBots", []) - case .privacyValueAllowChatParticipants(let chats): - return ("privacyValueAllowChatParticipants", [("chats", chats as Any)]) - case .privacyValueAllowCloseFriends: + case .privacyValueAllowChatParticipants(let _data): + return ("privacyValueAllowChatParticipants", [("chats", _data.chats as Any)]) + case .privacyValueAllowCloseFriends: return ("privacyValueAllowCloseFriends", []) - case .privacyValueAllowContacts: + case .privacyValueAllowContacts: return ("privacyValueAllowContacts", []) - case .privacyValueAllowPremium: + case .privacyValueAllowPremium: return ("privacyValueAllowPremium", []) - case .privacyValueAllowUsers(let users): - return ("privacyValueAllowUsers", [("users", users as Any)]) - case .privacyValueDisallowAll: + case .privacyValueAllowUsers(let _data): + return ("privacyValueAllowUsers", [("users", _data.users as Any)]) + case .privacyValueDisallowAll: return ("privacyValueDisallowAll", []) - case .privacyValueDisallowBots: + case .privacyValueDisallowBots: return ("privacyValueDisallowBots", []) - case .privacyValueDisallowChatParticipants(let chats): - return ("privacyValueDisallowChatParticipants", [("chats", chats as Any)]) - case .privacyValueDisallowContacts: + case .privacyValueDisallowChatParticipants(let _data): + return ("privacyValueDisallowChatParticipants", [("chats", _data.chats as Any)]) + case .privacyValueDisallowContacts: return ("privacyValueDisallowContacts", []) - case .privacyValueDisallowUsers(let users): - return ("privacyValueDisallowUsers", [("users", users as Any)]) - } - } - + case .privacyValueDisallowUsers(let _data): + return ("privacyValueDisallowUsers", [("users", _data.users as Any)]) + } + } + public static func parse_privacyValueAllowAll(_ reader: BufferReader) -> PrivacyRule? { return Api.PrivacyRule.privacyValueAllowAll } @@ -147,8 +163,12 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PrivacyRule.privacyValueAllowChatParticipants(chats: _1!) + if _c1 { + return Api.PrivacyRule.privacyValueAllowChatParticipants(Cons_privacyValueAllowChatParticipants(chats: _1!)) + } + else { + return nil + } } public static func parse_privacyValueAllowCloseFriends(_ reader: BufferReader) -> PrivacyRule? { return Api.PrivacyRule.privacyValueAllowCloseFriends @@ -165,8 +185,12 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PrivacyRule.privacyValueAllowUsers(users: _1!) + if _c1 { + return Api.PrivacyRule.privacyValueAllowUsers(Cons_privacyValueAllowUsers(users: _1!)) + } + else { + return nil + } } public static func parse_privacyValueDisallowAll(_ reader: BufferReader) -> PrivacyRule? { return Api.PrivacyRule.privacyValueDisallowAll @@ -180,8 +204,12 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PrivacyRule.privacyValueDisallowChatParticipants(chats: _1!) + if _c1 { + return Api.PrivacyRule.privacyValueDisallowChatParticipants(Cons_privacyValueDisallowChatParticipants(chats: _1!)) + } + else { + return nil + } } public static func parse_privacyValueDisallowContacts(_ reader: BufferReader) -> PrivacyRule? { return Api.PrivacyRule.privacyValueDisallowContacts @@ -192,10 +220,13 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PrivacyRule.privacyValueDisallowUsers(users: _1!) + if _c1 { + return Api.PrivacyRule.privacyValueDisallowUsers(Cons_privacyValueDisallowUsers(users: _1!)) + } + else { + return nil + } } - } } public extension Api { @@ -208,81 +239,73 @@ public extension Api { case profileTabMusic case profileTabPosts case profileTabVoice - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .profileTabFiles: - if boxed { - buffer.appendInt32(-1422681088) - } - - break - case .profileTabGifs: - if boxed { - buffer.appendInt32(-1564412267) - } - - break - case .profileTabGifts: - if boxed { - buffer.appendInt32(1296815210) - } - - break - case .profileTabLinks: - if boxed { - buffer.appendInt32(-748329831) - } - - break - case .profileTabMedia: - if boxed { - buffer.appendInt32(1925597525) - } - - break - case .profileTabMusic: - if boxed { - buffer.appendInt32(-1624780178) - } - - break - case .profileTabPosts: - if boxed { - buffer.appendInt32(-1181952362) - } - - break - case .profileTabVoice: - if boxed { - buffer.appendInt32(-461960914) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .profileTabFiles: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .profileTabFiles: + if boxed { + buffer.appendInt32(-1422681088) + } + break + case .profileTabGifs: + if boxed { + buffer.appendInt32(-1564412267) + } + break + case .profileTabGifts: + if boxed { + buffer.appendInt32(1296815210) + } + break + case .profileTabLinks: + if boxed { + buffer.appendInt32(-748329831) + } + break + case .profileTabMedia: + if boxed { + buffer.appendInt32(1925597525) + } + break + case .profileTabMusic: + if boxed { + buffer.appendInt32(-1624780178) + } + break + case .profileTabPosts: + if boxed { + buffer.appendInt32(-1181952362) + } + break + case .profileTabVoice: + if boxed { + buffer.appendInt32(-461960914) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .profileTabFiles: return ("profileTabFiles", []) - case .profileTabGifs: + case .profileTabGifs: return ("profileTabGifs", []) - case .profileTabGifts: + case .profileTabGifts: return ("profileTabGifts", []) - case .profileTabLinks: + case .profileTabLinks: return ("profileTabLinks", []) - case .profileTabMedia: + case .profileTabMedia: return ("profileTabMedia", []) - case .profileTabMusic: + case .profileTabMusic: return ("profileTabMusic", []) - case .profileTabPosts: + case .profileTabPosts: return ("profileTabPosts", []) - case .profileTabVoice: + case .profileTabVoice: return ("profileTabVoice", []) - } - } - + } + } + public static func parse_profileTabFiles(_ reader: BufferReader) -> ProfileTab? { return Api.ProfileTab.profileTabFiles } @@ -307,49 +330,66 @@ public extension Api { public static func parse_profileTabVoice(_ reader: BufferReader) -> ProfileTab? { return Api.ProfileTab.profileTabVoice } - } } public extension Api { indirect enum PublicForward: TypeConstructorDescription { - case publicForwardMessage(message: Api.Message) - case publicForwardStory(peer: Api.Peer, story: Api.StoryItem) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .publicForwardMessage(let message): - if boxed { - buffer.appendInt32(32685898) - } - message.serialize(buffer, true) - break - case .publicForwardStory(let peer, let story): - if boxed { - buffer.appendInt32(-302797360) - } - peer.serialize(buffer, true) - story.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .publicForwardMessage(let message): - return ("publicForwardMessage", [("message", message as Any)]) - case .publicForwardStory(let peer, let story): - return ("publicForwardStory", [("peer", peer as Any), ("story", story as Any)]) - } - } - + public class Cons_publicForwardMessage { + public var message: Api.Message + public init(message: Api.Message) { + self.message = message + } + } + public class Cons_publicForwardStory { + public var peer: Api.Peer + public var story: Api.StoryItem + public init(peer: Api.Peer, story: Api.StoryItem) { + self.peer = peer + self.story = story + } + } + case publicForwardMessage(Cons_publicForwardMessage) + case publicForwardStory(Cons_publicForwardStory) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .publicForwardMessage(let _data): + if boxed { + buffer.appendInt32(32685898) + } + _data.message.serialize(buffer, true) + break + case .publicForwardStory(let _data): + if boxed { + buffer.appendInt32(-302797360) + } + _data.peer.serialize(buffer, true) + _data.story.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .publicForwardMessage(let _data): + return ("publicForwardMessage", [("message", _data.message as Any)]) + case .publicForwardStory(let _data): + return ("publicForwardStory", [("peer", _data.peer as Any), ("story", _data.story as Any)]) + } + } + public static func parse_publicForwardMessage(_ reader: BufferReader) -> PublicForward? { var _1: Api.Message? if let signature = reader.readInt32() { _1 = Api.parse(reader, signature: signature) as? Api.Message } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.PublicForward.publicForwardMessage(message: _1!) + if _c1 { + return Api.PublicForward.publicForwardMessage(Cons_publicForwardMessage(message: _1!)) + } + else { + return nil + } } public static func parse_publicForwardStory(_ reader: BufferReader) -> PublicForward? { var _1: Api.Peer? @@ -362,38 +402,52 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.PublicForward.publicForwardStory(peer: _1!, story: _2!) + if _c1 && _c2 { + return Api.PublicForward.publicForwardStory(Cons_publicForwardStory(peer: _1!, story: _2!)) + } + else { + return nil + } } - } } public extension Api { enum QuickReply: TypeConstructorDescription { - case quickReply(shortcutId: Int32, shortcut: String, topMessage: Int32, count: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .quickReply(let shortcutId, let shortcut, let topMessage, let count): - if boxed { - buffer.appendInt32(110563371) - } - serializeInt32(shortcutId, buffer: buffer, boxed: false) - serializeString(shortcut, buffer: buffer, boxed: false) - serializeInt32(topMessage, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .quickReply(let shortcutId, let shortcut, let topMessage, let count): - return ("quickReply", [("shortcutId", shortcutId as Any), ("shortcut", shortcut as Any), ("topMessage", topMessage as Any), ("count", count as Any)]) - } - } - + public class Cons_quickReply { + public var shortcutId: Int32 + public var shortcut: String + public var topMessage: Int32 + public var count: Int32 + public init(shortcutId: Int32, shortcut: String, topMessage: Int32, count: Int32) { + self.shortcutId = shortcutId + self.shortcut = shortcut + self.topMessage = topMessage + self.count = count + } + } + case quickReply(Cons_quickReply) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .quickReply(let _data): + if boxed { + buffer.appendInt32(110563371) + } + serializeInt32(_data.shortcutId, buffer: buffer, boxed: false) + serializeString(_data.shortcut, buffer: buffer, boxed: false) + serializeInt32(_data.topMessage, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .quickReply(let _data): + return ("quickReply", [("shortcutId", _data.shortcutId as Any), ("shortcut", _data.shortcut as Any), ("topMessage", _data.topMessage as Any), ("count", _data.count as Any)]) + } + } + public static func parse_quickReply(_ reader: BufferReader) -> QuickReply? { var _1: Int32? _1 = reader.readInt32() @@ -407,77 +461,95 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.QuickReply.quickReply(shortcutId: _1!, shortcut: _2!, topMessage: _3!, count: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.QuickReply.quickReply(Cons_quickReply(shortcutId: _1!, shortcut: _2!, topMessage: _3!, count: _4!)) + } + else { + return nil + } } - } } public extension Api { enum Reaction: TypeConstructorDescription { - case reactionCustomEmoji(documentId: Int64) - case reactionEmoji(emoticon: String) + public class Cons_reactionCustomEmoji { + public var documentId: Int64 + public init(documentId: Int64) { + self.documentId = documentId + } + } + public class Cons_reactionEmoji { + public var emoticon: String + public init(emoticon: String) { + self.emoticon = emoticon + } + } + case reactionCustomEmoji(Cons_reactionCustomEmoji) + case reactionEmoji(Cons_reactionEmoji) case reactionEmpty case reactionPaid - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .reactionCustomEmoji(let documentId): - if boxed { - buffer.appendInt32(-1992950669) - } - serializeInt64(documentId, buffer: buffer, boxed: false) - break - case .reactionEmoji(let emoticon): - if boxed { - buffer.appendInt32(455247544) - } - serializeString(emoticon, buffer: buffer, boxed: false) - break - case .reactionEmpty: - if boxed { - buffer.appendInt32(2046153753) - } - - break - case .reactionPaid: - if boxed { - buffer.appendInt32(1379771627) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .reactionCustomEmoji(let documentId): - return ("reactionCustomEmoji", [("documentId", documentId as Any)]) - case .reactionEmoji(let emoticon): - return ("reactionEmoji", [("emoticon", emoticon as Any)]) - case .reactionEmpty: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .reactionCustomEmoji(let _data): + if boxed { + buffer.appendInt32(-1992950669) + } + serializeInt64(_data.documentId, buffer: buffer, boxed: false) + break + case .reactionEmoji(let _data): + if boxed { + buffer.appendInt32(455247544) + } + serializeString(_data.emoticon, buffer: buffer, boxed: false) + break + case .reactionEmpty: + if boxed { + buffer.appendInt32(2046153753) + } + break + case .reactionPaid: + if boxed { + buffer.appendInt32(1379771627) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .reactionCustomEmoji(let _data): + return ("reactionCustomEmoji", [("documentId", _data.documentId as Any)]) + case .reactionEmoji(let _data): + return ("reactionEmoji", [("emoticon", _data.emoticon as Any)]) + case .reactionEmpty: return ("reactionEmpty", []) - case .reactionPaid: + case .reactionPaid: return ("reactionPaid", []) - } - } - + } + } + public static func parse_reactionCustomEmoji(_ reader: BufferReader) -> Reaction? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Reaction.reactionCustomEmoji(documentId: _1!) + if _c1 { + return Api.Reaction.reactionCustomEmoji(Cons_reactionCustomEmoji(documentId: _1!)) + } + else { + return nil + } } public static func parse_reactionEmoji(_ reader: BufferReader) -> Reaction? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Reaction.reactionEmoji(emoticon: _1!) + if _c1 { + return Api.Reaction.reactionEmoji(Cons_reactionEmoji(emoticon: _1!)) + } + else { + return nil + } } public static func parse_reactionEmpty(_ reader: BufferReader) -> Reaction? { return Api.Reaction.reactionEmpty @@ -485,39 +557,54 @@ public extension Api { public static func parse_reactionPaid(_ reader: BufferReader) -> Reaction? { return Api.Reaction.reactionPaid } - } } public extension Api { enum ReactionCount: TypeConstructorDescription { - case reactionCount(flags: Int32, chosenOrder: Int32?, reaction: Api.Reaction, count: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .reactionCount(let flags, let chosenOrder, let reaction, let count): - if boxed { - buffer.appendInt32(-1546531968) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(chosenOrder!, buffer: buffer, boxed: false)} - reaction.serialize(buffer, true) - serializeInt32(count, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .reactionCount(let flags, let chosenOrder, let reaction, let count): - return ("reactionCount", [("flags", flags as Any), ("chosenOrder", chosenOrder as Any), ("reaction", reaction as Any), ("count", count as Any)]) - } - } - + public class Cons_reactionCount { + public var flags: Int32 + public var chosenOrder: Int32? + public var reaction: Api.Reaction + public var count: Int32 + public init(flags: Int32, chosenOrder: Int32?, reaction: Api.Reaction, count: Int32) { + self.flags = flags + self.chosenOrder = chosenOrder + self.reaction = reaction + self.count = count + } + } + case reactionCount(Cons_reactionCount) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .reactionCount(let _data): + if boxed { + buffer.appendInt32(-1546531968) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.chosenOrder!, buffer: buffer, boxed: false) + } + _data.reaction.serialize(buffer, true) + serializeInt32(_data.count, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .reactionCount(let _data): + return ("reactionCount", [("flags", _data.flags as Any), ("chosenOrder", _data.chosenOrder as Any), ("reaction", _data.reaction as Any), ("count", _data.count as Any)]) + } + } + public static func parse_reactionCount(_ reader: BufferReader) -> ReactionCount? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt32() + } var _3: Api.Reaction? if let signature = reader.readInt32() { _3 = Api.parse(reader, signature: signature) as? Api.Reaction @@ -528,92 +615,111 @@ public extension Api { let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.ReactionCount.reactionCount(flags: _1!, chosenOrder: _2, reaction: _3!, count: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.ReactionCount.reactionCount(Cons_reactionCount(flags: _1!, chosenOrder: _2, reaction: _3!, count: _4!)) + } + else { + return nil + } } - } } public extension Api { enum ReactionNotificationsFrom: TypeConstructorDescription { case reactionNotificationsFromAll case reactionNotificationsFromContacts - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .reactionNotificationsFromAll: - if boxed { - buffer.appendInt32(1268654752) - } - - break - case .reactionNotificationsFromContacts: - if boxed { - buffer.appendInt32(-1161583078) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .reactionNotificationsFromAll: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .reactionNotificationsFromAll: + if boxed { + buffer.appendInt32(1268654752) + } + break + case .reactionNotificationsFromContacts: + if boxed { + buffer.appendInt32(-1161583078) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .reactionNotificationsFromAll: return ("reactionNotificationsFromAll", []) - case .reactionNotificationsFromContacts: + case .reactionNotificationsFromContacts: return ("reactionNotificationsFromContacts", []) - } - } - + } + } + public static func parse_reactionNotificationsFromAll(_ reader: BufferReader) -> ReactionNotificationsFrom? { return Api.ReactionNotificationsFrom.reactionNotificationsFromAll } public static func parse_reactionNotificationsFromContacts(_ reader: BufferReader) -> ReactionNotificationsFrom? { return Api.ReactionNotificationsFrom.reactionNotificationsFromContacts } - } } public extension Api { enum ReactionsNotifySettings: TypeConstructorDescription { - case reactionsNotifySettings(flags: Int32, messagesNotifyFrom: Api.ReactionNotificationsFrom?, storiesNotifyFrom: Api.ReactionNotificationsFrom?, sound: Api.NotificationSound, showPreviews: Api.Bool) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .reactionsNotifySettings(let flags, let messagesNotifyFrom, let storiesNotifyFrom, let sound, let showPreviews): - if boxed { - buffer.appendInt32(1457736048) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {messagesNotifyFrom!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {storiesNotifyFrom!.serialize(buffer, true)} - sound.serialize(buffer, true) - showPreviews.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .reactionsNotifySettings(let flags, let messagesNotifyFrom, let storiesNotifyFrom, let sound, let showPreviews): - return ("reactionsNotifySettings", [("flags", flags as Any), ("messagesNotifyFrom", messagesNotifyFrom as Any), ("storiesNotifyFrom", storiesNotifyFrom as Any), ("sound", sound as Any), ("showPreviews", showPreviews as Any)]) - } - } - + public class Cons_reactionsNotifySettings { + public var flags: Int32 + public var messagesNotifyFrom: Api.ReactionNotificationsFrom? + public var storiesNotifyFrom: Api.ReactionNotificationsFrom? + public var sound: Api.NotificationSound + public var showPreviews: Api.Bool + public init(flags: Int32, messagesNotifyFrom: Api.ReactionNotificationsFrom?, storiesNotifyFrom: Api.ReactionNotificationsFrom?, sound: Api.NotificationSound, showPreviews: Api.Bool) { + self.flags = flags + self.messagesNotifyFrom = messagesNotifyFrom + self.storiesNotifyFrom = storiesNotifyFrom + self.sound = sound + self.showPreviews = showPreviews + } + } + case reactionsNotifySettings(Cons_reactionsNotifySettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .reactionsNotifySettings(let _data): + if boxed { + buffer.appendInt32(1457736048) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.messagesNotifyFrom!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.storiesNotifyFrom!.serialize(buffer, true) + } + _data.sound.serialize(buffer, true) + _data.showPreviews.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .reactionsNotifySettings(let _data): + return ("reactionsNotifySettings", [("flags", _data.flags as Any), ("messagesNotifyFrom", _data.messagesNotifyFrom as Any), ("storiesNotifyFrom", _data.storiesNotifyFrom as Any), ("sound", _data.sound as Any), ("showPreviews", _data.showPreviews as Any)]) + } + } + public static func parse_reactionsNotifySettings(_ reader: BufferReader) -> ReactionsNotifySettings? { var _1: Int32? _1 = reader.readInt32() var _2: Api.ReactionNotificationsFrom? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.ReactionNotificationsFrom - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.ReactionNotificationsFrom + } + } var _3: Api.ReactionNotificationsFrom? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.ReactionNotificationsFrom - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.ReactionNotificationsFrom + } + } var _4: Api.NotificationSound? if let signature = reader.readInt32() { _4 = Api.parse(reader, signature: signature) as? Api.NotificationSound @@ -627,39 +733,46 @@ public extension Api { let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.ReactionsNotifySettings.reactionsNotifySettings(flags: _1!, messagesNotifyFrom: _2, storiesNotifyFrom: _3, sound: _4!, showPreviews: _5!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.ReactionsNotifySettings.reactionsNotifySettings(Cons_reactionsNotifySettings(flags: _1!, messagesNotifyFrom: _2, storiesNotifyFrom: _3, sound: _4!, showPreviews: _5!)) + } + else { + return nil + } } - } } public extension Api { enum ReadParticipantDate: TypeConstructorDescription { - case readParticipantDate(userId: Int64, date: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .readParticipantDate(let userId, let date): - if boxed { - buffer.appendInt32(1246753138) - } - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .readParticipantDate(let userId, let date): - return ("readParticipantDate", [("userId", userId as Any), ("date", date as Any)]) - } - } - + public class Cons_readParticipantDate { + public var userId: Int64 + public var date: Int32 + public init(userId: Int64, date: Int32) { + self.userId = userId + self.date = date + } + } + case readParticipantDate(Cons_readParticipantDate) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .readParticipantDate(let _data): + if boxed { + buffer.appendInt32(1246753138) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .readParticipantDate(let _data): + return ("readParticipantDate", [("userId", _data.userId as Any), ("date", _data.date as Any)]) + } + } + public static func parse_readParticipantDate(_ reader: BufferReader) -> ReadParticipantDate? { var _1: Int64? _1 = reader.readInt64() @@ -667,10 +780,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ReadParticipantDate.readParticipantDate(userId: _1!, date: _2!) + if _c1 && _c2 { + return Api.ReadParticipantDate.readParticipantDate(Cons_readParticipantDate(userId: _1!, date: _2!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api22.swift b/submodules/TelegramApi/Sources/Api22.swift index 31bf060e..d00a29c4 100644 --- a/submodules/TelegramApi/Sources/Api22.swift +++ b/submodules/TelegramApi/Sources/Api22.swift @@ -1,26 +1,34 @@ public extension Api { enum ReceivedNotifyMessage: TypeConstructorDescription { - case receivedNotifyMessage(id: Int32, flags: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .receivedNotifyMessage(let id, let flags): - if boxed { - buffer.appendInt32(-1551583367) - } - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt32(flags, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .receivedNotifyMessage(let id, let flags): - return ("receivedNotifyMessage", [("id", id as Any), ("flags", flags as Any)]) - } - } - + public class Cons_receivedNotifyMessage { + public var id: Int32 + public var flags: Int32 + public init(id: Int32, flags: Int32) { + self.id = id + self.flags = flags + } + } + case receivedNotifyMessage(Cons_receivedNotifyMessage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .receivedNotifyMessage(let _data): + if boxed { + buffer.appendInt32(-1551583367) + } + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .receivedNotifyMessage(let _data): + return ("receivedNotifyMessage", [("id", _data.id as Any), ("flags", _data.flags as Any)]) + } + } + public static func parse_receivedNotifyMessage(_ reader: BufferReader) -> ReceivedNotifyMessage? { var _1: Int32? _1 = reader.readInt32() @@ -28,75 +36,115 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ReceivedNotifyMessage.receivedNotifyMessage(id: _1!, flags: _2!) + if _c1 && _c2 { + return Api.ReceivedNotifyMessage.receivedNotifyMessage(Cons_receivedNotifyMessage(id: _1!, flags: _2!)) + } + else { + return nil + } } - } } public extension Api { indirect enum RecentMeUrl: TypeConstructorDescription { - case recentMeUrlChat(url: String, chatId: Int64) - case recentMeUrlChatInvite(url: String, chatInvite: Api.ChatInvite) - case recentMeUrlStickerSet(url: String, set: Api.StickerSetCovered) - case recentMeUrlUnknown(url: String) - case recentMeUrlUser(url: String, userId: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .recentMeUrlChat(let url, let chatId): - if boxed { - buffer.appendInt32(-1294306862) - } - serializeString(url, buffer: buffer, boxed: false) - serializeInt64(chatId, buffer: buffer, boxed: false) - break - case .recentMeUrlChatInvite(let url, let chatInvite): - if boxed { - buffer.appendInt32(-347535331) - } - serializeString(url, buffer: buffer, boxed: false) - chatInvite.serialize(buffer, true) - break - case .recentMeUrlStickerSet(let url, let set): - if boxed { - buffer.appendInt32(-1140172836) - } - serializeString(url, buffer: buffer, boxed: false) - set.serialize(buffer, true) - break - case .recentMeUrlUnknown(let url): - if boxed { - buffer.appendInt32(1189204285) - } - serializeString(url, buffer: buffer, boxed: false) - break - case .recentMeUrlUser(let url, let userId): - if boxed { - buffer.appendInt32(-1188296222) - } - serializeString(url, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .recentMeUrlChat(let url, let chatId): - return ("recentMeUrlChat", [("url", url as Any), ("chatId", chatId as Any)]) - case .recentMeUrlChatInvite(let url, let chatInvite): - return ("recentMeUrlChatInvite", [("url", url as Any), ("chatInvite", chatInvite as Any)]) - case .recentMeUrlStickerSet(let url, let set): - return ("recentMeUrlStickerSet", [("url", url as Any), ("set", set as Any)]) - case .recentMeUrlUnknown(let url): - return ("recentMeUrlUnknown", [("url", url as Any)]) - case .recentMeUrlUser(let url, let userId): - return ("recentMeUrlUser", [("url", url as Any), ("userId", userId as Any)]) - } - } - + public class Cons_recentMeUrlChat { + public var url: String + public var chatId: Int64 + public init(url: String, chatId: Int64) { + self.url = url + self.chatId = chatId + } + } + public class Cons_recentMeUrlChatInvite { + public var url: String + public var chatInvite: Api.ChatInvite + public init(url: String, chatInvite: Api.ChatInvite) { + self.url = url + self.chatInvite = chatInvite + } + } + public class Cons_recentMeUrlStickerSet { + public var url: String + public var set: Api.StickerSetCovered + public init(url: String, set: Api.StickerSetCovered) { + self.url = url + self.set = set + } + } + public class Cons_recentMeUrlUnknown { + public var url: String + public init(url: String) { + self.url = url + } + } + public class Cons_recentMeUrlUser { + public var url: String + public var userId: Int64 + public init(url: String, userId: Int64) { + self.url = url + self.userId = userId + } + } + case recentMeUrlChat(Cons_recentMeUrlChat) + case recentMeUrlChatInvite(Cons_recentMeUrlChatInvite) + case recentMeUrlStickerSet(Cons_recentMeUrlStickerSet) + case recentMeUrlUnknown(Cons_recentMeUrlUnknown) + case recentMeUrlUser(Cons_recentMeUrlUser) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .recentMeUrlChat(let _data): + if boxed { + buffer.appendInt32(-1294306862) + } + serializeString(_data.url, buffer: buffer, boxed: false) + serializeInt64(_data.chatId, buffer: buffer, boxed: false) + break + case .recentMeUrlChatInvite(let _data): + if boxed { + buffer.appendInt32(-347535331) + } + serializeString(_data.url, buffer: buffer, boxed: false) + _data.chatInvite.serialize(buffer, true) + break + case .recentMeUrlStickerSet(let _data): + if boxed { + buffer.appendInt32(-1140172836) + } + serializeString(_data.url, buffer: buffer, boxed: false) + _data.set.serialize(buffer, true) + break + case .recentMeUrlUnknown(let _data): + if boxed { + buffer.appendInt32(1189204285) + } + serializeString(_data.url, buffer: buffer, boxed: false) + break + case .recentMeUrlUser(let _data): + if boxed { + buffer.appendInt32(-1188296222) + } + serializeString(_data.url, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .recentMeUrlChat(let _data): + return ("recentMeUrlChat", [("url", _data.url as Any), ("chatId", _data.chatId as Any)]) + case .recentMeUrlChatInvite(let _data): + return ("recentMeUrlChatInvite", [("url", _data.url as Any), ("chatInvite", _data.chatInvite as Any)]) + case .recentMeUrlStickerSet(let _data): + return ("recentMeUrlStickerSet", [("url", _data.url as Any), ("set", _data.set as Any)]) + case .recentMeUrlUnknown(let _data): + return ("recentMeUrlUnknown", [("url", _data.url as Any)]) + case .recentMeUrlUser(let _data): + return ("recentMeUrlUser", [("url", _data.url as Any), ("userId", _data.userId as Any)]) + } + } + public static func parse_recentMeUrlChat(_ reader: BufferReader) -> RecentMeUrl? { var _1: String? _1 = parseString(reader) @@ -104,9 +152,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.RecentMeUrl.recentMeUrlChat(url: _1!, chatId: _2!) + if _c1 && _c2 { + return Api.RecentMeUrl.recentMeUrlChat(Cons_recentMeUrlChat(url: _1!, chatId: _2!)) + } + else { + return nil + } } public static func parse_recentMeUrlChatInvite(_ reader: BufferReader) -> RecentMeUrl? { var _1: String? @@ -117,9 +168,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.RecentMeUrl.recentMeUrlChatInvite(url: _1!, chatInvite: _2!) + if _c1 && _c2 { + return Api.RecentMeUrl.recentMeUrlChatInvite(Cons_recentMeUrlChatInvite(url: _1!, chatInvite: _2!)) + } + else { + return nil + } } public static func parse_recentMeUrlStickerSet(_ reader: BufferReader) -> RecentMeUrl? { var _1: String? @@ -130,16 +184,23 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.RecentMeUrl.recentMeUrlStickerSet(url: _1!, set: _2!) + if _c1 && _c2 { + return Api.RecentMeUrl.recentMeUrlStickerSet(Cons_recentMeUrlStickerSet(url: _1!, set: _2!)) + } + else { + return nil + } } public static func parse_recentMeUrlUnknown(_ reader: BufferReader) -> RecentMeUrl? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.RecentMeUrl.recentMeUrlUnknown(url: _1!) + if _c1 { + return Api.RecentMeUrl.recentMeUrlUnknown(Cons_recentMeUrlUnknown(url: _1!)) + } + else { + return nil + } } public static func parse_recentMeUrlUser(_ reader: BufferReader) -> RecentMeUrl? { var _1: String? @@ -148,136 +209,199 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.RecentMeUrl.recentMeUrlUser(url: _1!, userId: _2!) + if _c1 && _c2 { + return Api.RecentMeUrl.recentMeUrlUser(Cons_recentMeUrlUser(url: _1!, userId: _2!)) + } + else { + return nil + } } - } } public extension Api { enum RecentStory: TypeConstructorDescription { - case recentStory(flags: Int32, maxId: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .recentStory(let flags, let maxId): - if boxed { - buffer.appendInt32(1897752877) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(maxId!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .recentStory(let flags, let maxId): - return ("recentStory", [("flags", flags as Any), ("maxId", maxId as Any)]) - } - } - + public class Cons_recentStory { + public var flags: Int32 + public var maxId: Int32? + public init(flags: Int32, maxId: Int32?) { + self.flags = flags + self.maxId = maxId + } + } + case recentStory(Cons_recentStory) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .recentStory(let _data): + if boxed { + buffer.appendInt32(1897752877) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.maxId!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .recentStory(let _data): + return ("recentStory", [("flags", _data.flags as Any), ("maxId", _data.maxId as Any)]) + } + } + public static func parse_recentStory(_ reader: BufferReader) -> RecentStory? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_2 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _2 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.RecentStory.recentStory(flags: _1!, maxId: _2) + if _c1 && _c2 { + return Api.RecentStory.recentStory(Cons_recentStory(flags: _1!, maxId: _2)) + } + else { + return nil + } } - } } public extension Api { enum ReplyMarkup: TypeConstructorDescription { - case replyInlineMarkup(rows: [Api.KeyboardButtonRow]) - case replyKeyboardForceReply(flags: Int32, placeholder: String?) - case replyKeyboardHide(flags: Int32) - case replyKeyboardMarkup(flags: Int32, rows: [Api.KeyboardButtonRow], placeholder: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .replyInlineMarkup(let rows): - if boxed { - buffer.appendInt32(1218642516) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(rows.count)) - for item in rows { - item.serialize(buffer, true) - } - break - case .replyKeyboardForceReply(let flags, let placeholder): - if boxed { - buffer.appendInt32(-2035021048) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {serializeString(placeholder!, buffer: buffer, boxed: false)} - break - case .replyKeyboardHide(let flags): - if boxed { - buffer.appendInt32(-1606526075) - } - serializeInt32(flags, buffer: buffer, boxed: false) - break - case .replyKeyboardMarkup(let flags, let rows, let placeholder): - if boxed { - buffer.appendInt32(-2049074735) - } - serializeInt32(flags, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(rows.count)) - for item in rows { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 3) != 0 {serializeString(placeholder!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .replyInlineMarkup(let rows): - return ("replyInlineMarkup", [("rows", rows as Any)]) - case .replyKeyboardForceReply(let flags, let placeholder): - return ("replyKeyboardForceReply", [("flags", flags as Any), ("placeholder", placeholder as Any)]) - case .replyKeyboardHide(let flags): - return ("replyKeyboardHide", [("flags", flags as Any)]) - case .replyKeyboardMarkup(let flags, let rows, let placeholder): - return ("replyKeyboardMarkup", [("flags", flags as Any), ("rows", rows as Any), ("placeholder", placeholder as Any)]) - } - } - + public class Cons_replyInlineMarkup { + public var rows: [Api.KeyboardButtonRow] + public init(rows: [Api.KeyboardButtonRow]) { + self.rows = rows + } + } + public class Cons_replyKeyboardForceReply { + public var flags: Int32 + public var placeholder: String? + public init(flags: Int32, placeholder: String?) { + self.flags = flags + self.placeholder = placeholder + } + } + public class Cons_replyKeyboardHide { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } + public class Cons_replyKeyboardMarkup { + public var flags: Int32 + public var rows: [Api.KeyboardButtonRow] + public var placeholder: String? + public init(flags: Int32, rows: [Api.KeyboardButtonRow], placeholder: String?) { + self.flags = flags + self.rows = rows + self.placeholder = placeholder + } + } + case replyInlineMarkup(Cons_replyInlineMarkup) + case replyKeyboardForceReply(Cons_replyKeyboardForceReply) + case replyKeyboardHide(Cons_replyKeyboardHide) + case replyKeyboardMarkup(Cons_replyKeyboardMarkup) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .replyInlineMarkup(let _data): + if boxed { + buffer.appendInt32(1218642516) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.rows.count)) + for item in _data.rows { + item.serialize(buffer, true) + } + break + case .replyKeyboardForceReply(let _data): + if boxed { + buffer.appendInt32(-2035021048) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.placeholder!, buffer: buffer, boxed: false) + } + break + case .replyKeyboardHide(let _data): + if boxed { + buffer.appendInt32(-1606526075) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + case .replyKeyboardMarkup(let _data): + if boxed { + buffer.appendInt32(-2049074735) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.rows.count)) + for item in _data.rows { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.placeholder!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .replyInlineMarkup(let _data): + return ("replyInlineMarkup", [("rows", _data.rows as Any)]) + case .replyKeyboardForceReply(let _data): + return ("replyKeyboardForceReply", [("flags", _data.flags as Any), ("placeholder", _data.placeholder as Any)]) + case .replyKeyboardHide(let _data): + return ("replyKeyboardHide", [("flags", _data.flags as Any)]) + case .replyKeyboardMarkup(let _data): + return ("replyKeyboardMarkup", [("flags", _data.flags as Any), ("rows", _data.rows as Any), ("placeholder", _data.placeholder as Any)]) + } + } + public static func parse_replyInlineMarkup(_ reader: BufferReader) -> ReplyMarkup? { var _1: [Api.KeyboardButtonRow]? if let _ = reader.readInt32() { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.KeyboardButtonRow.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ReplyMarkup.replyInlineMarkup(rows: _1!) + if _c1 { + return Api.ReplyMarkup.replyInlineMarkup(Cons_replyInlineMarkup(rows: _1!)) + } + else { + return nil + } } public static func parse_replyKeyboardForceReply(_ reader: BufferReader) -> ReplyMarkup? { var _1: Int32? _1 = reader.readInt32() var _2: String? - if Int(_1!) & Int(1 << 3) != 0 {_2 = parseString(reader) } + if Int(_1!) & Int(1 << 3) != 0 { + _2 = parseString(reader) + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 3) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ReplyMarkup.replyKeyboardForceReply(flags: _1!, placeholder: _2) + if _c1 && _c2 { + return Api.ReplyMarkup.replyKeyboardForceReply(Cons_replyKeyboardForceReply(flags: _1!, placeholder: _2)) + } + else { + return nil + } } public static func parse_replyKeyboardHide(_ reader: BufferReader) -> ReplyMarkup? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ReplyMarkup.replyKeyboardHide(flags: _1!) + if _c1 { + return Api.ReplyMarkup.replyKeyboardHide(Cons_replyKeyboardHide(flags: _1!)) + } + else { + return nil + } } public static func parse_replyKeyboardMarkup(_ reader: BufferReader) -> ReplyMarkup? { var _1: Int32? @@ -287,16 +411,19 @@ public extension Api { _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.KeyboardButtonRow.self) } var _3: String? - if Int(_1!) & Int(1 << 3) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 3) != 0 { + _3 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 3) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.ReplyMarkup.replyKeyboardMarkup(flags: _1!, rows: _2!, placeholder: _3) + if _c1 && _c2 && _c3 { + return Api.ReplyMarkup.replyKeyboardMarkup(Cons_replyKeyboardMarkup(flags: _1!, rows: _2!, placeholder: _3)) + } + else { + return nil + } } - } } public extension Api { @@ -311,97 +438,87 @@ public extension Api { case inputReportReasonPornography case inputReportReasonSpam case inputReportReasonViolence - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputReportReasonChildAbuse: - if boxed { - buffer.appendInt32(-1376497949) - } - - break - case .inputReportReasonCopyright: - if boxed { - buffer.appendInt32(-1685456582) - } - - break - case .inputReportReasonFake: - if boxed { - buffer.appendInt32(-170010905) - } - - break - case .inputReportReasonGeoIrrelevant: - if boxed { - buffer.appendInt32(-606798099) - } - - break - case .inputReportReasonIllegalDrugs: - if boxed { - buffer.appendInt32(177124030) - } - - break - case .inputReportReasonOther: - if boxed { - buffer.appendInt32(-1041980751) - } - - break - case .inputReportReasonPersonalDetails: - if boxed { - buffer.appendInt32(-1631091139) - } - - break - case .inputReportReasonPornography: - if boxed { - buffer.appendInt32(777640226) - } - - break - case .inputReportReasonSpam: - if boxed { - buffer.appendInt32(1490799288) - } - - break - case .inputReportReasonViolence: - if boxed { - buffer.appendInt32(505595789) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputReportReasonChildAbuse: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputReportReasonChildAbuse: + if boxed { + buffer.appendInt32(-1376497949) + } + break + case .inputReportReasonCopyright: + if boxed { + buffer.appendInt32(-1685456582) + } + break + case .inputReportReasonFake: + if boxed { + buffer.appendInt32(-170010905) + } + break + case .inputReportReasonGeoIrrelevant: + if boxed { + buffer.appendInt32(-606798099) + } + break + case .inputReportReasonIllegalDrugs: + if boxed { + buffer.appendInt32(177124030) + } + break + case .inputReportReasonOther: + if boxed { + buffer.appendInt32(-1041980751) + } + break + case .inputReportReasonPersonalDetails: + if boxed { + buffer.appendInt32(-1631091139) + } + break + case .inputReportReasonPornography: + if boxed { + buffer.appendInt32(777640226) + } + break + case .inputReportReasonSpam: + if boxed { + buffer.appendInt32(1490799288) + } + break + case .inputReportReasonViolence: + if boxed { + buffer.appendInt32(505595789) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputReportReasonChildAbuse: return ("inputReportReasonChildAbuse", []) - case .inputReportReasonCopyright: + case .inputReportReasonCopyright: return ("inputReportReasonCopyright", []) - case .inputReportReasonFake: + case .inputReportReasonFake: return ("inputReportReasonFake", []) - case .inputReportReasonGeoIrrelevant: + case .inputReportReasonGeoIrrelevant: return ("inputReportReasonGeoIrrelevant", []) - case .inputReportReasonIllegalDrugs: + case .inputReportReasonIllegalDrugs: return ("inputReportReasonIllegalDrugs", []) - case .inputReportReasonOther: + case .inputReportReasonOther: return ("inputReportReasonOther", []) - case .inputReportReasonPersonalDetails: + case .inputReportReasonPersonalDetails: return ("inputReportReasonPersonalDetails", []) - case .inputReportReasonPornography: + case .inputReportReasonPornography: return ("inputReportReasonPornography", []) - case .inputReportReasonSpam: + case .inputReportReasonSpam: return ("inputReportReasonSpam", []) - case .inputReportReasonViolence: + case .inputReportReasonViolence: return ("inputReportReasonViolence", []) - } - } - + } + } + public static func parse_inputReportReasonChildAbuse(_ reader: BufferReader) -> ReportReason? { return Api.ReportReason.inputReportReasonChildAbuse } @@ -432,55 +549,69 @@ public extension Api { public static func parse_inputReportReasonViolence(_ reader: BufferReader) -> ReportReason? { return Api.ReportReason.inputReportReasonViolence } - } } public extension Api { enum ReportResult: TypeConstructorDescription { - case reportResultAddComment(flags: Int32, option: Buffer) - case reportResultChooseOption(title: String, options: [Api.MessageReportOption]) + public class Cons_reportResultAddComment { + public var flags: Int32 + public var option: Buffer + public init(flags: Int32, option: Buffer) { + self.flags = flags + self.option = option + } + } + public class Cons_reportResultChooseOption { + public var title: String + public var options: [Api.MessageReportOption] + public init(title: String, options: [Api.MessageReportOption]) { + self.title = title + self.options = options + } + } + case reportResultAddComment(Cons_reportResultAddComment) + case reportResultChooseOption(Cons_reportResultChooseOption) case reportResultReported - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .reportResultAddComment(let flags, let option): - if boxed { - buffer.appendInt32(1862904881) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeBytes(option, buffer: buffer, boxed: false) - break - case .reportResultChooseOption(let title, let options): - if boxed { - buffer.appendInt32(-253435722) - } - serializeString(title, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(options.count)) - for item in options { - item.serialize(buffer, true) - } - break - case .reportResultReported: - if boxed { - buffer.appendInt32(-1917633461) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .reportResultAddComment(let flags, let option): - return ("reportResultAddComment", [("flags", flags as Any), ("option", option as Any)]) - case .reportResultChooseOption(let title, let options): - return ("reportResultChooseOption", [("title", title as Any), ("options", options as Any)]) - case .reportResultReported: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .reportResultAddComment(let _data): + if boxed { + buffer.appendInt32(1862904881) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeBytes(_data.option, buffer: buffer, boxed: false) + break + case .reportResultChooseOption(let _data): + if boxed { + buffer.appendInt32(-253435722) + } + serializeString(_data.title, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.options.count)) + for item in _data.options { + item.serialize(buffer, true) + } + break + case .reportResultReported: + if boxed { + buffer.appendInt32(-1917633461) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .reportResultAddComment(let _data): + return ("reportResultAddComment", [("flags", _data.flags as Any), ("option", _data.option as Any)]) + case .reportResultChooseOption(let _data): + return ("reportResultChooseOption", [("title", _data.title as Any), ("options", _data.options as Any)]) + case .reportResultReported: return ("reportResultReported", []) - } - } - + } + } + public static func parse_reportResultAddComment(_ reader: BufferReader) -> ReportResult? { var _1: Int32? _1 = reader.readInt32() @@ -488,9 +619,12 @@ public extension Api { _2 = parseBytes(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ReportResult.reportResultAddComment(flags: _1!, option: _2!) + if _c1 && _c2 { + return Api.ReportResult.reportResultAddComment(Cons_reportResultAddComment(flags: _1!, option: _2!)) + } + else { + return nil + } } public static func parse_reportResultChooseOption(_ reader: BufferReader) -> ReportResult? { var _1: String? @@ -501,219 +635,361 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ReportResult.reportResultChooseOption(title: _1!, options: _2!) + if _c1 && _c2 { + return Api.ReportResult.reportResultChooseOption(Cons_reportResultChooseOption(title: _1!, options: _2!)) + } + else { + return nil + } } public static func parse_reportResultReported(_ reader: BufferReader) -> ReportResult? { return Api.ReportResult.reportResultReported } - } } public extension Api { enum RequestPeerType: TypeConstructorDescription { - case requestPeerTypeBroadcast(flags: Int32, hasUsername: Api.Bool?, userAdminRights: Api.ChatAdminRights?, botAdminRights: Api.ChatAdminRights?) - case requestPeerTypeChat(flags: Int32, hasUsername: Api.Bool?, forum: Api.Bool?, userAdminRights: Api.ChatAdminRights?, botAdminRights: Api.ChatAdminRights?) - case requestPeerTypeUser(flags: Int32, bot: Api.Bool?, premium: Api.Bool?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .requestPeerTypeBroadcast(let flags, let hasUsername, let userAdminRights, let botAdminRights): - if boxed { - buffer.appendInt32(865857388) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {hasUsername!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {userAdminRights!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {botAdminRights!.serialize(buffer, true)} - break - case .requestPeerTypeChat(let flags, let hasUsername, let forum, let userAdminRights, let botAdminRights): - if boxed { - buffer.appendInt32(-906990053) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {hasUsername!.serialize(buffer, true)} - if Int(flags) & Int(1 << 4) != 0 {forum!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {userAdminRights!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {botAdminRights!.serialize(buffer, true)} - break - case .requestPeerTypeUser(let flags, let bot, let premium): - if boxed { - buffer.appendInt32(1597737472) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {bot!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {premium!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .requestPeerTypeBroadcast(let flags, let hasUsername, let userAdminRights, let botAdminRights): - return ("requestPeerTypeBroadcast", [("flags", flags as Any), ("hasUsername", hasUsername as Any), ("userAdminRights", userAdminRights as Any), ("botAdminRights", botAdminRights as Any)]) - case .requestPeerTypeChat(let flags, let hasUsername, let forum, let userAdminRights, let botAdminRights): - return ("requestPeerTypeChat", [("flags", flags as Any), ("hasUsername", hasUsername as Any), ("forum", forum as Any), ("userAdminRights", userAdminRights as Any), ("botAdminRights", botAdminRights as Any)]) - case .requestPeerTypeUser(let flags, let bot, let premium): - return ("requestPeerTypeUser", [("flags", flags as Any), ("bot", bot as Any), ("premium", premium as Any)]) - } - } - + public class Cons_requestPeerTypeBroadcast { + public var flags: Int32 + public var hasUsername: Api.Bool? + public var userAdminRights: Api.ChatAdminRights? + public var botAdminRights: Api.ChatAdminRights? + public init(flags: Int32, hasUsername: Api.Bool?, userAdminRights: Api.ChatAdminRights?, botAdminRights: Api.ChatAdminRights?) { + self.flags = flags + self.hasUsername = hasUsername + self.userAdminRights = userAdminRights + self.botAdminRights = botAdminRights + } + } + public class Cons_requestPeerTypeChat { + public var flags: Int32 + public var hasUsername: Api.Bool? + public var forum: Api.Bool? + public var userAdminRights: Api.ChatAdminRights? + public var botAdminRights: Api.ChatAdminRights? + public init(flags: Int32, hasUsername: Api.Bool?, forum: Api.Bool?, userAdminRights: Api.ChatAdminRights?, botAdminRights: Api.ChatAdminRights?) { + self.flags = flags + self.hasUsername = hasUsername + self.forum = forum + self.userAdminRights = userAdminRights + self.botAdminRights = botAdminRights + } + } + public class Cons_requestPeerTypeUser { + public var flags: Int32 + public var bot: Api.Bool? + public var premium: Api.Bool? + public init(flags: Int32, bot: Api.Bool?, premium: Api.Bool?) { + self.flags = flags + self.bot = bot + self.premium = premium + } + } + case requestPeerTypeBroadcast(Cons_requestPeerTypeBroadcast) + case requestPeerTypeChat(Cons_requestPeerTypeChat) + case requestPeerTypeUser(Cons_requestPeerTypeUser) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .requestPeerTypeBroadcast(let _data): + if boxed { + buffer.appendInt32(865857388) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.hasUsername!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.userAdminRights!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.botAdminRights!.serialize(buffer, true) + } + break + case .requestPeerTypeChat(let _data): + if boxed { + buffer.appendInt32(-906990053) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.hasUsername!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + _data.forum!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.userAdminRights!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.botAdminRights!.serialize(buffer, true) + } + break + case .requestPeerTypeUser(let _data): + if boxed { + buffer.appendInt32(1597737472) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.bot!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.premium!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .requestPeerTypeBroadcast(let _data): + return ("requestPeerTypeBroadcast", [("flags", _data.flags as Any), ("hasUsername", _data.hasUsername as Any), ("userAdminRights", _data.userAdminRights as Any), ("botAdminRights", _data.botAdminRights as Any)]) + case .requestPeerTypeChat(let _data): + return ("requestPeerTypeChat", [("flags", _data.flags as Any), ("hasUsername", _data.hasUsername as Any), ("forum", _data.forum as Any), ("userAdminRights", _data.userAdminRights as Any), ("botAdminRights", _data.botAdminRights as Any)]) + case .requestPeerTypeUser(let _data): + return ("requestPeerTypeUser", [("flags", _data.flags as Any), ("bot", _data.bot as Any), ("premium", _data.premium as Any)]) + } + } + public static func parse_requestPeerTypeBroadcast(_ reader: BufferReader) -> RequestPeerType? { var _1: Int32? _1 = reader.readInt32() var _2: Api.Bool? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Bool + } + } var _3: Api.ChatAdminRights? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights + } + } var _4: Api.ChatAdminRights? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 3) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.RequestPeerType.requestPeerTypeBroadcast(flags: _1!, hasUsername: _2, userAdminRights: _3, botAdminRights: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.RequestPeerType.requestPeerTypeBroadcast(Cons_requestPeerTypeBroadcast(flags: _1!, hasUsername: _2, userAdminRights: _3, botAdminRights: _4)) + } + else { + return nil + } } public static func parse_requestPeerTypeChat(_ reader: BufferReader) -> RequestPeerType? { var _1: Int32? _1 = reader.readInt32() var _2: Api.Bool? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Bool + } + } var _3: Api.Bool? - if Int(_1!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Bool + } + } var _4: Api.ChatAdminRights? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights + } + } var _5: Api.ChatAdminRights? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 3) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 4) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 2) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.RequestPeerType.requestPeerTypeChat(flags: _1!, hasUsername: _2, forum: _3, userAdminRights: _4, botAdminRights: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.RequestPeerType.requestPeerTypeChat(Cons_requestPeerTypeChat(flags: _1!, hasUsername: _2, forum: _3, userAdminRights: _4, botAdminRights: _5)) + } + else { + return nil + } } public static func parse_requestPeerTypeUser(_ reader: BufferReader) -> RequestPeerType? { var _1: Int32? _1 = reader.readInt32() var _2: Api.Bool? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Bool + } + } var _3: Api.Bool? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Bool + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.RequestPeerType.requestPeerTypeUser(flags: _1!, bot: _2, premium: _3) + if _c1 && _c2 && _c3 { + return Api.RequestPeerType.requestPeerTypeUser(Cons_requestPeerTypeUser(flags: _1!, bot: _2, premium: _3)) + } + else { + return nil + } } - } } public extension Api { enum RequestedPeer: TypeConstructorDescription { - case requestedPeerChannel(flags: Int32, channelId: Int64, title: String?, username: String?, photo: Api.Photo?) - case requestedPeerChat(flags: Int32, chatId: Int64, title: String?, photo: Api.Photo?) - case requestedPeerUser(flags: Int32, userId: Int64, firstName: String?, lastName: String?, username: String?, photo: Api.Photo?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .requestedPeerChannel(let flags, let channelId, let title, let username, let photo): - if boxed { - buffer.appendInt32(-1952185372) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(channelId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(username!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {photo!.serialize(buffer, true)} - break - case .requestedPeerChat(let flags, let chatId, let title, let photo): - if boxed { - buffer.appendInt32(1929860175) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(chatId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {photo!.serialize(buffer, true)} - break - case .requestedPeerUser(let flags, let userId, let firstName, let lastName, let username, let photo): - if boxed { - buffer.appendInt32(-701500310) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(firstName!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeString(lastName!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(username!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {photo!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .requestedPeerChannel(let flags, let channelId, let title, let username, let photo): - return ("requestedPeerChannel", [("flags", flags as Any), ("channelId", channelId as Any), ("title", title as Any), ("username", username as Any), ("photo", photo as Any)]) - case .requestedPeerChat(let flags, let chatId, let title, let photo): - return ("requestedPeerChat", [("flags", flags as Any), ("chatId", chatId as Any), ("title", title as Any), ("photo", photo as Any)]) - case .requestedPeerUser(let flags, let userId, let firstName, let lastName, let username, let photo): - return ("requestedPeerUser", [("flags", flags as Any), ("userId", userId as Any), ("firstName", firstName as Any), ("lastName", lastName as Any), ("username", username as Any), ("photo", photo as Any)]) - } - } - + public class Cons_requestedPeerChannel { + public var flags: Int32 + public var channelId: Int64 + public var title: String? + public var username: String? + public var photo: Api.Photo? + public init(flags: Int32, channelId: Int64, title: String?, username: String?, photo: Api.Photo?) { + self.flags = flags + self.channelId = channelId + self.title = title + self.username = username + self.photo = photo + } + } + public class Cons_requestedPeerChat { + public var flags: Int32 + public var chatId: Int64 + public var title: String? + public var photo: Api.Photo? + public init(flags: Int32, chatId: Int64, title: String?, photo: Api.Photo?) { + self.flags = flags + self.chatId = chatId + self.title = title + self.photo = photo + } + } + public class Cons_requestedPeerUser { + public var flags: Int32 + public var userId: Int64 + public var firstName: String? + public var lastName: String? + public var username: String? + public var photo: Api.Photo? + public init(flags: Int32, userId: Int64, firstName: String?, lastName: String?, username: String?, photo: Api.Photo?) { + self.flags = flags + self.userId = userId + self.firstName = firstName + self.lastName = lastName + self.username = username + self.photo = photo + } + } + case requestedPeerChannel(Cons_requestedPeerChannel) + case requestedPeerChat(Cons_requestedPeerChat) + case requestedPeerUser(Cons_requestedPeerUser) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .requestedPeerChannel(let _data): + if boxed { + buffer.appendInt32(-1952185372) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.username!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.photo!.serialize(buffer, true) + } + break + case .requestedPeerChat(let _data): + if boxed { + buffer.appendInt32(1929860175) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.chatId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.photo!.serialize(buffer, true) + } + break + case .requestedPeerUser(let _data): + if boxed { + buffer.appendInt32(-701500310) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.firstName!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.lastName!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.username!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.photo!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .requestedPeerChannel(let _data): + return ("requestedPeerChannel", [("flags", _data.flags as Any), ("channelId", _data.channelId as Any), ("title", _data.title as Any), ("username", _data.username as Any), ("photo", _data.photo as Any)]) + case .requestedPeerChat(let _data): + return ("requestedPeerChat", [("flags", _data.flags as Any), ("chatId", _data.chatId as Any), ("title", _data.title as Any), ("photo", _data.photo as Any)]) + case .requestedPeerUser(let _data): + return ("requestedPeerUser", [("flags", _data.flags as Any), ("userId", _data.userId as Any), ("firstName", _data.firstName as Any), ("lastName", _data.lastName as Any), ("username", _data.username as Any), ("photo", _data.photo as Any)]) + } + } + public static func parse_requestedPeerChannel(_ reader: BufferReader) -> RequestedPeer? { var _1: Int32? _1 = reader.readInt32() var _2: Int64? _2 = reader.readInt64() var _3: String? - if Int(_1!) & Int(1 << 0) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = parseString(reader) + } var _4: String? - if Int(_1!) & Int(1 << 1) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = parseString(reader) + } var _5: Api.Photo? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.Photo - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.Photo + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 2) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.RequestedPeer.requestedPeerChannel(flags: _1!, channelId: _2!, title: _3, username: _4, photo: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.RequestedPeer.requestedPeerChannel(Cons_requestedPeerChannel(flags: _1!, channelId: _2!, title: _3, username: _4, photo: _5)) + } + else { + return nil + } } public static func parse_requestedPeerChat(_ reader: BufferReader) -> RequestedPeer? { var _1: Int32? @@ -721,20 +997,25 @@ public extension Api { var _2: Int64? _2 = reader.readInt64() var _3: String? - if Int(_1!) & Int(1 << 0) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = parseString(reader) + } var _4: Api.Photo? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Photo - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Photo + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.RequestedPeer.requestedPeerChat(flags: _1!, chatId: _2!, title: _3, photo: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.RequestedPeer.requestedPeerChat(Cons_requestedPeerChat(flags: _1!, chatId: _2!, title: _3, photo: _4)) + } + else { + return nil + } } public static func parse_requestedPeerUser(_ reader: BufferReader) -> RequestedPeer? { var _1: Int32? @@ -742,72 +1023,82 @@ public extension Api { var _2: Int64? _2 = reader.readInt64() var _3: String? - if Int(_1!) & Int(1 << 0) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = parseString(reader) + } var _4: String? - if Int(_1!) & Int(1 << 0) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) + } var _5: String? - if Int(_1!) & Int(1 << 1) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _5 = parseString(reader) + } var _6: Api.Photo? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.Photo - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.Photo + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.RequestedPeer.requestedPeerUser(flags: _1!, userId: _2!, firstName: _3, lastName: _4, username: _5, photo: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.RequestedPeer.requestedPeerUser(Cons_requestedPeerUser(flags: _1!, userId: _2!, firstName: _3, lastName: _4, username: _5, photo: _6)) + } + else { + return nil + } } - } } public extension Api { enum RequirementToContact: TypeConstructorDescription { + public class Cons_requirementToContactPaidMessages { + public var starsAmount: Int64 + public init(starsAmount: Int64) { + self.starsAmount = starsAmount + } + } case requirementToContactEmpty - case requirementToContactPaidMessages(starsAmount: Int64) + case requirementToContactPaidMessages(Cons_requirementToContactPaidMessages) case requirementToContactPremium - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .requirementToContactEmpty: - if boxed { - buffer.appendInt32(84580409) - } - - break - case .requirementToContactPaidMessages(let starsAmount): - if boxed { - buffer.appendInt32(-1258914157) - } - serializeInt64(starsAmount, buffer: buffer, boxed: false) - break - case .requirementToContactPremium: - if boxed { - buffer.appendInt32(-444472087) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .requirementToContactEmpty: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .requirementToContactEmpty: + if boxed { + buffer.appendInt32(84580409) + } + break + case .requirementToContactPaidMessages(let _data): + if boxed { + buffer.appendInt32(-1258914157) + } + serializeInt64(_data.starsAmount, buffer: buffer, boxed: false) + break + case .requirementToContactPremium: + if boxed { + buffer.appendInt32(-444472087) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .requirementToContactEmpty: return ("requirementToContactEmpty", []) - case .requirementToContactPaidMessages(let starsAmount): - return ("requirementToContactPaidMessages", [("starsAmount", starsAmount as Any)]) - case .requirementToContactPremium: + case .requirementToContactPaidMessages(let _data): + return ("requirementToContactPaidMessages", [("starsAmount", _data.starsAmount as Any)]) + case .requirementToContactPremium: return ("requirementToContactPremium", []) - } - } - + } + } + public static func parse_requirementToContactEmpty(_ reader: BufferReader) -> RequirementToContact? { return Api.RequirementToContact.requirementToContactEmpty } @@ -815,12 +1106,15 @@ public extension Api { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.RequirementToContact.requirementToContactPaidMessages(starsAmount: _1!) + if _c1 { + return Api.RequirementToContact.requirementToContactPaidMessages(Cons_requirementToContactPaidMessages(starsAmount: _1!)) + } + else { + return nil + } } public static func parse_requirementToContactPremium(_ reader: BufferReader) -> RequirementToContact? { return Api.RequirementToContact.requirementToContactPremium } - } } diff --git a/submodules/TelegramApi/Sources/Api23.swift b/submodules/TelegramApi/Sources/Api23.swift index 84004762..fd232331 100644 --- a/submodules/TelegramApi/Sources/Api23.swift +++ b/submodules/TelegramApi/Sources/Api23.swift @@ -1,27 +1,37 @@ public extension Api { enum RestrictionReason: TypeConstructorDescription { - case restrictionReason(platform: String, reason: String, text: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .restrictionReason(let platform, let reason, let text): - if boxed { - buffer.appendInt32(-797791052) - } - serializeString(platform, buffer: buffer, boxed: false) - serializeString(reason, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .restrictionReason(let platform, let reason, let text): - return ("restrictionReason", [("platform", platform as Any), ("reason", reason as Any), ("text", text as Any)]) - } - } - + public class Cons_restrictionReason { + public var platform: String + public var reason: String + public var text: String + public init(platform: String, reason: String, text: String) { + self.platform = platform + self.reason = reason + self.text = text + } + } + case restrictionReason(Cons_restrictionReason) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .restrictionReason(let _data): + if boxed { + buffer.appendInt32(-797791052) + } + serializeString(_data.platform, buffer: buffer, boxed: false) + serializeString(_data.reason, buffer: buffer, boxed: false) + serializeString(_data.text, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .restrictionReason(let _data): + return ("restrictionReason", [("platform", _data.platform as Any), ("reason", _data.reason as Any), ("text", _data.text as Any)]) + } + } + public static func parse_restrictionReason(_ reader: BufferReader) -> RestrictionReason? { var _1: String? _1 = parseString(reader) @@ -32,182 +42,286 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.RestrictionReason.restrictionReason(platform: _1!, reason: _2!, text: _3!) + if _c1 && _c2 && _c3 { + return Api.RestrictionReason.restrictionReason(Cons_restrictionReason(platform: _1!, reason: _2!, text: _3!)) + } + else { + return nil + } } - } } public extension Api { indirect enum RichText: TypeConstructorDescription { - case textAnchor(text: Api.RichText, name: String) - case textBold(text: Api.RichText) - case textConcat(texts: [Api.RichText]) - case textEmail(text: Api.RichText, email: String) + public class Cons_textAnchor { + public var text: Api.RichText + public var name: String + public init(text: Api.RichText, name: String) { + self.text = text + self.name = name + } + } + public class Cons_textBold { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + public class Cons_textConcat { + public var texts: [Api.RichText] + public init(texts: [Api.RichText]) { + self.texts = texts + } + } + public class Cons_textEmail { + public var text: Api.RichText + public var email: String + public init(text: Api.RichText, email: String) { + self.text = text + self.email = email + } + } + public class Cons_textFixed { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + public class Cons_textImage { + public var documentId: Int64 + public var w: Int32 + public var h: Int32 + public init(documentId: Int64, w: Int32, h: Int32) { + self.documentId = documentId + self.w = w + self.h = h + } + } + public class Cons_textItalic { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + public class Cons_textMarked { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + public class Cons_textPhone { + public var text: Api.RichText + public var phone: String + public init(text: Api.RichText, phone: String) { + self.text = text + self.phone = phone + } + } + public class Cons_textPlain { + public var text: String + public init(text: String) { + self.text = text + } + } + public class Cons_textStrike { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + public class Cons_textSubscript { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + public class Cons_textSuperscript { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + public class Cons_textUnderline { + public var text: Api.RichText + public init(text: Api.RichText) { + self.text = text + } + } + public class Cons_textUrl { + public var text: Api.RichText + public var url: String + public var webpageId: Int64 + public init(text: Api.RichText, url: String, webpageId: Int64) { + self.text = text + self.url = url + self.webpageId = webpageId + } + } + case textAnchor(Cons_textAnchor) + case textBold(Cons_textBold) + case textConcat(Cons_textConcat) + case textEmail(Cons_textEmail) case textEmpty - case textFixed(text: Api.RichText) - case textImage(documentId: Int64, w: Int32, h: Int32) - case textItalic(text: Api.RichText) - case textMarked(text: Api.RichText) - case textPhone(text: Api.RichText, phone: String) - case textPlain(text: String) - case textStrike(text: Api.RichText) - case textSubscript(text: Api.RichText) - case textSuperscript(text: Api.RichText) - case textUnderline(text: Api.RichText) - case textUrl(text: Api.RichText, url: String, webpageId: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .textAnchor(let text, let name): - if boxed { - buffer.appendInt32(894777186) - } - text.serialize(buffer, true) - serializeString(name, buffer: buffer, boxed: false) - break - case .textBold(let text): - if boxed { - buffer.appendInt32(1730456516) - } - text.serialize(buffer, true) - break - case .textConcat(let texts): - if boxed { - buffer.appendInt32(2120376535) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(texts.count)) - for item in texts { - item.serialize(buffer, true) - } - break - case .textEmail(let text, let email): - if boxed { - buffer.appendInt32(-564523562) - } - text.serialize(buffer, true) - serializeString(email, buffer: buffer, boxed: false) - break - case .textEmpty: - if boxed { - buffer.appendInt32(-599948721) - } - - break - case .textFixed(let text): - if boxed { - buffer.appendInt32(1816074681) - } - text.serialize(buffer, true) - break - case .textImage(let documentId, let w, let h): - if boxed { - buffer.appendInt32(136105807) - } - serializeInt64(documentId, buffer: buffer, boxed: false) - serializeInt32(w, buffer: buffer, boxed: false) - serializeInt32(h, buffer: buffer, boxed: false) - break - case .textItalic(let text): - if boxed { - buffer.appendInt32(-653089380) - } - text.serialize(buffer, true) - break - case .textMarked(let text): - if boxed { - buffer.appendInt32(55281185) - } - text.serialize(buffer, true) - break - case .textPhone(let text, let phone): - if boxed { - buffer.appendInt32(483104362) - } - text.serialize(buffer, true) - serializeString(phone, buffer: buffer, boxed: false) - break - case .textPlain(let text): - if boxed { - buffer.appendInt32(1950782688) - } - serializeString(text, buffer: buffer, boxed: false) - break - case .textStrike(let text): - if boxed { - buffer.appendInt32(-1678197867) - } - text.serialize(buffer, true) - break - case .textSubscript(let text): - if boxed { - buffer.appendInt32(-311786236) - } - text.serialize(buffer, true) - break - case .textSuperscript(let text): - if boxed { - buffer.appendInt32(-939827711) - } - text.serialize(buffer, true) - break - case .textUnderline(let text): - if boxed { - buffer.appendInt32(-1054465340) - } - text.serialize(buffer, true) - break - case .textUrl(let text, let url, let webpageId): - if boxed { - buffer.appendInt32(1009288385) - } - text.serialize(buffer, true) - serializeString(url, buffer: buffer, boxed: false) - serializeInt64(webpageId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .textAnchor(let text, let name): - return ("textAnchor", [("text", text as Any), ("name", name as Any)]) - case .textBold(let text): - return ("textBold", [("text", text as Any)]) - case .textConcat(let texts): - return ("textConcat", [("texts", texts as Any)]) - case .textEmail(let text, let email): - return ("textEmail", [("text", text as Any), ("email", email as Any)]) - case .textEmpty: + case textFixed(Cons_textFixed) + case textImage(Cons_textImage) + case textItalic(Cons_textItalic) + case textMarked(Cons_textMarked) + case textPhone(Cons_textPhone) + case textPlain(Cons_textPlain) + case textStrike(Cons_textStrike) + case textSubscript(Cons_textSubscript) + case textSuperscript(Cons_textSuperscript) + case textUnderline(Cons_textUnderline) + case textUrl(Cons_textUrl) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .textAnchor(let _data): + if boxed { + buffer.appendInt32(894777186) + } + _data.text.serialize(buffer, true) + serializeString(_data.name, buffer: buffer, boxed: false) + break + case .textBold(let _data): + if boxed { + buffer.appendInt32(1730456516) + } + _data.text.serialize(buffer, true) + break + case .textConcat(let _data): + if boxed { + buffer.appendInt32(2120376535) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.texts.count)) + for item in _data.texts { + item.serialize(buffer, true) + } + break + case .textEmail(let _data): + if boxed { + buffer.appendInt32(-564523562) + } + _data.text.serialize(buffer, true) + serializeString(_data.email, buffer: buffer, boxed: false) + break + case .textEmpty: + if boxed { + buffer.appendInt32(-599948721) + } + break + case .textFixed(let _data): + if boxed { + buffer.appendInt32(1816074681) + } + _data.text.serialize(buffer, true) + break + case .textImage(let _data): + if boxed { + buffer.appendInt32(136105807) + } + serializeInt64(_data.documentId, buffer: buffer, boxed: false) + serializeInt32(_data.w, buffer: buffer, boxed: false) + serializeInt32(_data.h, buffer: buffer, boxed: false) + break + case .textItalic(let _data): + if boxed { + buffer.appendInt32(-653089380) + } + _data.text.serialize(buffer, true) + break + case .textMarked(let _data): + if boxed { + buffer.appendInt32(55281185) + } + _data.text.serialize(buffer, true) + break + case .textPhone(let _data): + if boxed { + buffer.appendInt32(483104362) + } + _data.text.serialize(buffer, true) + serializeString(_data.phone, buffer: buffer, boxed: false) + break + case .textPlain(let _data): + if boxed { + buffer.appendInt32(1950782688) + } + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .textStrike(let _data): + if boxed { + buffer.appendInt32(-1678197867) + } + _data.text.serialize(buffer, true) + break + case .textSubscript(let _data): + if boxed { + buffer.appendInt32(-311786236) + } + _data.text.serialize(buffer, true) + break + case .textSuperscript(let _data): + if boxed { + buffer.appendInt32(-939827711) + } + _data.text.serialize(buffer, true) + break + case .textUnderline(let _data): + if boxed { + buffer.appendInt32(-1054465340) + } + _data.text.serialize(buffer, true) + break + case .textUrl(let _data): + if boxed { + buffer.appendInt32(1009288385) + } + _data.text.serialize(buffer, true) + serializeString(_data.url, buffer: buffer, boxed: false) + serializeInt64(_data.webpageId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .textAnchor(let _data): + return ("textAnchor", [("text", _data.text as Any), ("name", _data.name as Any)]) + case .textBold(let _data): + return ("textBold", [("text", _data.text as Any)]) + case .textConcat(let _data): + return ("textConcat", [("texts", _data.texts as Any)]) + case .textEmail(let _data): + return ("textEmail", [("text", _data.text as Any), ("email", _data.email as Any)]) + case .textEmpty: return ("textEmpty", []) - case .textFixed(let text): - return ("textFixed", [("text", text as Any)]) - case .textImage(let documentId, let w, let h): - return ("textImage", [("documentId", documentId as Any), ("w", w as Any), ("h", h as Any)]) - case .textItalic(let text): - return ("textItalic", [("text", text as Any)]) - case .textMarked(let text): - return ("textMarked", [("text", text as Any)]) - case .textPhone(let text, let phone): - return ("textPhone", [("text", text as Any), ("phone", phone as Any)]) - case .textPlain(let text): - return ("textPlain", [("text", text as Any)]) - case .textStrike(let text): - return ("textStrike", [("text", text as Any)]) - case .textSubscript(let text): - return ("textSubscript", [("text", text as Any)]) - case .textSuperscript(let text): - return ("textSuperscript", [("text", text as Any)]) - case .textUnderline(let text): - return ("textUnderline", [("text", text as Any)]) - case .textUrl(let text, let url, let webpageId): - return ("textUrl", [("text", text as Any), ("url", url as Any), ("webpageId", webpageId as Any)]) - } - } - + case .textFixed(let _data): + return ("textFixed", [("text", _data.text as Any)]) + case .textImage(let _data): + return ("textImage", [("documentId", _data.documentId as Any), ("w", _data.w as Any), ("h", _data.h as Any)]) + case .textItalic(let _data): + return ("textItalic", [("text", _data.text as Any)]) + case .textMarked(let _data): + return ("textMarked", [("text", _data.text as Any)]) + case .textPhone(let _data): + return ("textPhone", [("text", _data.text as Any), ("phone", _data.phone as Any)]) + case .textPlain(let _data): + return ("textPlain", [("text", _data.text as Any)]) + case .textStrike(let _data): + return ("textStrike", [("text", _data.text as Any)]) + case .textSubscript(let _data): + return ("textSubscript", [("text", _data.text as Any)]) + case .textSuperscript(let _data): + return ("textSuperscript", [("text", _data.text as Any)]) + case .textUnderline(let _data): + return ("textUnderline", [("text", _data.text as Any)]) + case .textUrl(let _data): + return ("textUrl", [("text", _data.text as Any), ("url", _data.url as Any), ("webpageId", _data.webpageId as Any)]) + } + } + public static func parse_textAnchor(_ reader: BufferReader) -> RichText? { var _1: Api.RichText? if let signature = reader.readInt32() { @@ -217,9 +331,12 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.RichText.textAnchor(text: _1!, name: _2!) + if _c1 && _c2 { + return Api.RichText.textAnchor(Cons_textAnchor(text: _1!, name: _2!)) + } + else { + return nil + } } public static func parse_textBold(_ reader: BufferReader) -> RichText? { var _1: Api.RichText? @@ -227,8 +344,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.RichText.textBold(text: _1!) + if _c1 { + return Api.RichText.textBold(Cons_textBold(text: _1!)) + } + else { + return nil + } } public static func parse_textConcat(_ reader: BufferReader) -> RichText? { var _1: [Api.RichText]? @@ -236,8 +357,12 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.RichText.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.RichText.textConcat(texts: _1!) + if _c1 { + return Api.RichText.textConcat(Cons_textConcat(texts: _1!)) + } + else { + return nil + } } public static func parse_textEmail(_ reader: BufferReader) -> RichText? { var _1: Api.RichText? @@ -248,9 +373,12 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.RichText.textEmail(text: _1!, email: _2!) + if _c1 && _c2 { + return Api.RichText.textEmail(Cons_textEmail(text: _1!, email: _2!)) + } + else { + return nil + } } public static func parse_textEmpty(_ reader: BufferReader) -> RichText? { return Api.RichText.textEmpty @@ -261,8 +389,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.RichText.textFixed(text: _1!) + if _c1 { + return Api.RichText.textFixed(Cons_textFixed(text: _1!)) + } + else { + return nil + } } public static func parse_textImage(_ reader: BufferReader) -> RichText? { var _1: Int64? @@ -274,10 +406,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.RichText.textImage(documentId: _1!, w: _2!, h: _3!) + if _c1 && _c2 && _c3 { + return Api.RichText.textImage(Cons_textImage(documentId: _1!, w: _2!, h: _3!)) + } + else { + return nil + } } public static func parse_textItalic(_ reader: BufferReader) -> RichText? { var _1: Api.RichText? @@ -285,8 +419,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.RichText.textItalic(text: _1!) + if _c1 { + return Api.RichText.textItalic(Cons_textItalic(text: _1!)) + } + else { + return nil + } } public static func parse_textMarked(_ reader: BufferReader) -> RichText? { var _1: Api.RichText? @@ -294,8 +432,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.RichText.textMarked(text: _1!) + if _c1 { + return Api.RichText.textMarked(Cons_textMarked(text: _1!)) + } + else { + return nil + } } public static func parse_textPhone(_ reader: BufferReader) -> RichText? { var _1: Api.RichText? @@ -306,16 +448,23 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.RichText.textPhone(text: _1!, phone: _2!) + if _c1 && _c2 { + return Api.RichText.textPhone(Cons_textPhone(text: _1!, phone: _2!)) + } + else { + return nil + } } public static func parse_textPlain(_ reader: BufferReader) -> RichText? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.RichText.textPlain(text: _1!) + if _c1 { + return Api.RichText.textPlain(Cons_textPlain(text: _1!)) + } + else { + return nil + } } public static func parse_textStrike(_ reader: BufferReader) -> RichText? { var _1: Api.RichText? @@ -323,8 +472,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.RichText.textStrike(text: _1!) + if _c1 { + return Api.RichText.textStrike(Cons_textStrike(text: _1!)) + } + else { + return nil + } } public static func parse_textSubscript(_ reader: BufferReader) -> RichText? { var _1: Api.RichText? @@ -332,8 +485,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.RichText.textSubscript(text: _1!) + if _c1 { + return Api.RichText.textSubscript(Cons_textSubscript(text: _1!)) + } + else { + return nil + } } public static func parse_textSuperscript(_ reader: BufferReader) -> RichText? { var _1: Api.RichText? @@ -341,8 +498,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.RichText.textSuperscript(text: _1!) + if _c1 { + return Api.RichText.textSuperscript(Cons_textSuperscript(text: _1!)) + } + else { + return nil + } } public static func parse_textUnderline(_ reader: BufferReader) -> RichText? { var _1: Api.RichText? @@ -350,8 +511,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.RichText } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.RichText.textUnderline(text: _1!) + if _c1 { + return Api.RichText.textUnderline(Cons_textUnderline(text: _1!)) + } + else { + return nil + } } public static func parse_textUrl(_ reader: BufferReader) -> RichText? { var _1: Api.RichText? @@ -365,39 +530,52 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.RichText.textUrl(text: _1!, url: _2!, webpageId: _3!) + if _c1 && _c2 && _c3 { + return Api.RichText.textUrl(Cons_textUrl(text: _1!, url: _2!, webpageId: _3!)) + } + else { + return nil + } } - } } public extension Api { enum SavedContact: TypeConstructorDescription { - case savedPhoneContact(phone: String, firstName: String, lastName: String, date: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .savedPhoneContact(let phone, let firstName, let lastName, let date): - if boxed { - buffer.appendInt32(289586518) - } - serializeString(phone, buffer: buffer, boxed: false) - serializeString(firstName, buffer: buffer, boxed: false) - serializeString(lastName, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .savedPhoneContact(let phone, let firstName, let lastName, let date): - return ("savedPhoneContact", [("phone", phone as Any), ("firstName", firstName as Any), ("lastName", lastName as Any), ("date", date as Any)]) - } - } - + public class Cons_savedPhoneContact { + public var phone: String + public var firstName: String + public var lastName: String + public var date: Int32 + public init(phone: String, firstName: String, lastName: String, date: Int32) { + self.phone = phone + self.firstName = firstName + self.lastName = lastName + self.date = date + } + } + case savedPhoneContact(Cons_savedPhoneContact) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .savedPhoneContact(let _data): + if boxed { + buffer.appendInt32(289586518) + } + serializeString(_data.phone, buffer: buffer, boxed: false) + serializeString(_data.firstName, buffer: buffer, boxed: false) + serializeString(_data.lastName, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .savedPhoneContact(let _data): + return ("savedPhoneContact", [("phone", _data.phone as Any), ("firstName", _data.firstName as Any), ("lastName", _data.lastName as Any), ("date", _data.date as Any)]) + } + } + public static func parse_savedPhoneContact(_ reader: BufferReader) -> SavedContact? { var _1: String? _1 = parseString(reader) @@ -411,55 +589,87 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.SavedContact.savedPhoneContact(phone: _1!, firstName: _2!, lastName: _3!, date: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.SavedContact.savedPhoneContact(Cons_savedPhoneContact(phone: _1!, firstName: _2!, lastName: _3!, date: _4!)) + } + else { + return nil + } } - } } public extension Api { indirect enum SavedDialog: TypeConstructorDescription { - case monoForumDialog(flags: Int32, peer: Api.Peer, topMessage: Int32, readInboxMaxId: Int32, readOutboxMaxId: Int32, unreadCount: Int32, unreadReactionsCount: Int32, draft: Api.DraftMessage?) - case savedDialog(flags: Int32, peer: Api.Peer, topMessage: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .monoForumDialog(let flags, let peer, let topMessage, let readInboxMaxId, let readOutboxMaxId, let unreadCount, let unreadReactionsCount, let draft): - if boxed { - buffer.appendInt32(1681948327) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(topMessage, buffer: buffer, boxed: false) - serializeInt32(readInboxMaxId, buffer: buffer, boxed: false) - serializeInt32(readOutboxMaxId, buffer: buffer, boxed: false) - serializeInt32(unreadCount, buffer: buffer, boxed: false) - serializeInt32(unreadReactionsCount, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {draft!.serialize(buffer, true)} - break - case .savedDialog(let flags, let peer, let topMessage): - if boxed { - buffer.appendInt32(-1115174036) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(topMessage, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .monoForumDialog(let flags, let peer, let topMessage, let readInboxMaxId, let readOutboxMaxId, let unreadCount, let unreadReactionsCount, let draft): - return ("monoForumDialog", [("flags", flags as Any), ("peer", peer as Any), ("topMessage", topMessage as Any), ("readInboxMaxId", readInboxMaxId as Any), ("readOutboxMaxId", readOutboxMaxId as Any), ("unreadCount", unreadCount as Any), ("unreadReactionsCount", unreadReactionsCount as Any), ("draft", draft as Any)]) - case .savedDialog(let flags, let peer, let topMessage): - return ("savedDialog", [("flags", flags as Any), ("peer", peer as Any), ("topMessage", topMessage as Any)]) - } - } - + public class Cons_monoForumDialog { + public var flags: Int32 + public var peer: Api.Peer + public var topMessage: Int32 + public var readInboxMaxId: Int32 + public var readOutboxMaxId: Int32 + public var unreadCount: Int32 + public var unreadReactionsCount: Int32 + public var draft: Api.DraftMessage? + public init(flags: Int32, peer: Api.Peer, topMessage: Int32, readInboxMaxId: Int32, readOutboxMaxId: Int32, unreadCount: Int32, unreadReactionsCount: Int32, draft: Api.DraftMessage?) { + self.flags = flags + self.peer = peer + self.topMessage = topMessage + self.readInboxMaxId = readInboxMaxId + self.readOutboxMaxId = readOutboxMaxId + self.unreadCount = unreadCount + self.unreadReactionsCount = unreadReactionsCount + self.draft = draft + } + } + public class Cons_savedDialog { + public var flags: Int32 + public var peer: Api.Peer + public var topMessage: Int32 + public init(flags: Int32, peer: Api.Peer, topMessage: Int32) { + self.flags = flags + self.peer = peer + self.topMessage = topMessage + } + } + case monoForumDialog(Cons_monoForumDialog) + case savedDialog(Cons_savedDialog) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .monoForumDialog(let _data): + if boxed { + buffer.appendInt32(1681948327) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeInt32(_data.topMessage, buffer: buffer, boxed: false) + serializeInt32(_data.readInboxMaxId, buffer: buffer, boxed: false) + serializeInt32(_data.readOutboxMaxId, buffer: buffer, boxed: false) + serializeInt32(_data.unreadCount, buffer: buffer, boxed: false) + serializeInt32(_data.unreadReactionsCount, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.draft!.serialize(buffer, true) + } + break + case .savedDialog(let _data): + if boxed { + buffer.appendInt32(-1115174036) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeInt32(_data.topMessage, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .monoForumDialog(let _data): + return ("monoForumDialog", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("topMessage", _data.topMessage as Any), ("readInboxMaxId", _data.readInboxMaxId as Any), ("readOutboxMaxId", _data.readOutboxMaxId as Any), ("unreadCount", _data.unreadCount as Any), ("unreadReactionsCount", _data.unreadReactionsCount as Any), ("draft", _data.draft as Any)]) + case .savedDialog(let _data): + return ("savedDialog", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("topMessage", _data.topMessage as Any)]) + } + } + public static func parse_monoForumDialog(_ reader: BufferReader) -> SavedDialog? { var _1: Int32? _1 = reader.readInt32() @@ -478,9 +688,11 @@ public extension Api { var _7: Int32? _7 = reader.readInt32() var _8: Api.DraftMessage? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.DraftMessage - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.DraftMessage + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -489,15 +701,12 @@ public extension Api { let _c6 = _6 != nil let _c7 = _7 != nil let _c8 = (Int(_1!) & Int(1 << 1) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.SavedDialog.monoForumDialog(flags: _1!, peer: _2!, topMessage: _3!, readInboxMaxId: _4!, readOutboxMaxId: _5!, unreadCount: _6!, unreadReactionsCount: _7!, draft: _8) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.SavedDialog.monoForumDialog(Cons_monoForumDialog(flags: _1!, peer: _2!, topMessage: _3!, readInboxMaxId: _4!, readOutboxMaxId: _5!, unreadCount: _6!, unreadReactionsCount: _7!, draft: _8)) + } + else { + return nil + } } public static func parse_savedDialog(_ reader: BufferReader) -> SavedDialog? { var _1: Int32? @@ -511,39 +720,54 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SavedDialog.savedDialog(flags: _1!, peer: _2!, topMessage: _3!) + if _c1 && _c2 && _c3 { + return Api.SavedDialog.savedDialog(Cons_savedDialog(flags: _1!, peer: _2!, topMessage: _3!)) + } + else { + return nil + } } - } } public extension Api { enum SavedReactionTag: TypeConstructorDescription { - case savedReactionTag(flags: Int32, reaction: Api.Reaction, title: String?, count: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .savedReactionTag(let flags, let reaction, let title, let count): - if boxed { - buffer.appendInt32(-881854424) - } - serializeInt32(flags, buffer: buffer, boxed: false) - reaction.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - serializeInt32(count, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .savedReactionTag(let flags, let reaction, let title, let count): - return ("savedReactionTag", [("flags", flags as Any), ("reaction", reaction as Any), ("title", title as Any), ("count", count as Any)]) - } - } - + public class Cons_savedReactionTag { + public var flags: Int32 + public var reaction: Api.Reaction + public var title: String? + public var count: Int32 + public init(flags: Int32, reaction: Api.Reaction, title: String?, count: Int32) { + self.flags = flags + self.reaction = reaction + self.title = title + self.count = count + } + } + case savedReactionTag(Cons_savedReactionTag) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .savedReactionTag(let _data): + if boxed { + buffer.appendInt32(-881854424) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.reaction.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .savedReactionTag(let _data): + return ("savedReactionTag", [("flags", _data.flags as Any), ("reaction", _data.reaction as Any), ("title", _data.title as Any), ("count", _data.count as Any)]) + } + } + public static func parse_savedReactionTag(_ reader: BufferReader) -> SavedReactionTag? { var _1: Int32? _1 = reader.readInt32() @@ -552,71 +776,146 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.Reaction } var _3: String? - if Int(_1!) & Int(1 << 0) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = parseString(reader) + } var _4: Int32? _4 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.SavedReactionTag.savedReactionTag(flags: _1!, reaction: _2!, title: _3, count: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.SavedReactionTag.savedReactionTag(Cons_savedReactionTag(flags: _1!, reaction: _2!, title: _3, count: _4!)) + } + else { + return nil + } } - } } public extension Api { enum SavedStarGift: TypeConstructorDescription { - case savedStarGift(flags: Int32, fromId: Api.Peer?, date: Int32, gift: Api.StarGift, message: Api.TextWithEntities?, msgId: Int32?, savedId: Int64?, convertStars: Int64?, upgradeStars: Int64?, canExportAt: Int32?, transferStars: Int64?, canTransferAt: Int32?, canResellAt: Int32?, collectionId: [Int32]?, prepaidUpgradeHash: String?, dropOriginalDetailsStars: Int64?, giftNum: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .savedStarGift(let flags, let fromId, let date, let gift, let message, let msgId, let savedId, let convertStars, let upgradeStars, let canExportAt, let transferStars, let canTransferAt, let canResellAt, let collectionId, let prepaidUpgradeHash, let dropOriginalDetailsStars, let giftNum): - if boxed { - buffer.appendInt32(-355041186) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {fromId!.serialize(buffer, true)} - serializeInt32(date, buffer: buffer, boxed: false) - gift.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {message!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(msgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 11) != 0 {serializeInt64(savedId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt64(convertStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 6) != 0 {serializeInt64(upgradeStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 7) != 0 {serializeInt32(canExportAt!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {serializeInt64(transferStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 13) != 0 {serializeInt32(canTransferAt!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 14) != 0 {serializeInt32(canResellAt!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 15) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(collectionId!.count)) - for item in collectionId! { + public class Cons_savedStarGift { + public var flags: Int32 + public var fromId: Api.Peer? + public var date: Int32 + public var gift: Api.StarGift + public var message: Api.TextWithEntities? + public var msgId: Int32? + public var savedId: Int64? + public var convertStars: Int64? + public var upgradeStars: Int64? + public var canExportAt: Int32? + public var transferStars: Int64? + public var canTransferAt: Int32? + public var canResellAt: Int32? + public var collectionId: [Int32]? + public var prepaidUpgradeHash: String? + public var dropOriginalDetailsStars: Int64? + public var giftNum: Int32? + public var canCraftAt: Int32? + public init(flags: Int32, fromId: Api.Peer?, date: Int32, gift: Api.StarGift, message: Api.TextWithEntities?, msgId: Int32?, savedId: Int64?, convertStars: Int64?, upgradeStars: Int64?, canExportAt: Int32?, transferStars: Int64?, canTransferAt: Int32?, canResellAt: Int32?, collectionId: [Int32]?, prepaidUpgradeHash: String?, dropOriginalDetailsStars: Int64?, giftNum: Int32?, canCraftAt: Int32?) { + self.flags = flags + self.fromId = fromId + self.date = date + self.gift = gift + self.message = message + self.msgId = msgId + self.savedId = savedId + self.convertStars = convertStars + self.upgradeStars = upgradeStars + self.canExportAt = canExportAt + self.transferStars = transferStars + self.canTransferAt = canTransferAt + self.canResellAt = canResellAt + self.collectionId = collectionId + self.prepaidUpgradeHash = prepaidUpgradeHash + self.dropOriginalDetailsStars = dropOriginalDetailsStars + self.giftNum = giftNum + self.canCraftAt = canCraftAt + } + } + case savedStarGift(Cons_savedStarGift) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .savedStarGift(let _data): + if boxed { + buffer.appendInt32(1105150972) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.fromId!.serialize(buffer, true) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + _data.gift.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.message!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.msgId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 11) != 0 { + serializeInt64(_data.savedId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt64(_data.convertStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + serializeInt64(_data.upgradeStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 7) != 0 { + serializeInt32(_data.canExportAt!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + serializeInt64(_data.transferStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 13) != 0 { + serializeInt32(_data.canTransferAt!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 14) != 0 { + serializeInt32(_data.canResellAt!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 15) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.collectionId!.count)) + for item in _data.collectionId! { serializeInt32(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 16) != 0 {serializeString(prepaidUpgradeHash!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 18) != 0 {serializeInt64(dropOriginalDetailsStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 19) != 0 {serializeInt32(giftNum!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .savedStarGift(let flags, let fromId, let date, let gift, let message, let msgId, let savedId, let convertStars, let upgradeStars, let canExportAt, let transferStars, let canTransferAt, let canResellAt, let collectionId, let prepaidUpgradeHash, let dropOriginalDetailsStars, let giftNum): - return ("savedStarGift", [("flags", flags as Any), ("fromId", fromId as Any), ("date", date as Any), ("gift", gift as Any), ("message", message as Any), ("msgId", msgId as Any), ("savedId", savedId as Any), ("convertStars", convertStars as Any), ("upgradeStars", upgradeStars as Any), ("canExportAt", canExportAt as Any), ("transferStars", transferStars as Any), ("canTransferAt", canTransferAt as Any), ("canResellAt", canResellAt as Any), ("collectionId", collectionId as Any), ("prepaidUpgradeHash", prepaidUpgradeHash as Any), ("dropOriginalDetailsStars", dropOriginalDetailsStars as Any), ("giftNum", giftNum as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 16) != 0 { + serializeString(_data.prepaidUpgradeHash!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 18) != 0 { + serializeInt64(_data.dropOriginalDetailsStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 19) != 0 { + serializeInt32(_data.giftNum!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 20) != 0 { + serializeInt32(_data.canCraftAt!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .savedStarGift(let _data): + return ("savedStarGift", [("flags", _data.flags as Any), ("fromId", _data.fromId as Any), ("date", _data.date as Any), ("gift", _data.gift as Any), ("message", _data.message as Any), ("msgId", _data.msgId as Any), ("savedId", _data.savedId as Any), ("convertStars", _data.convertStars as Any), ("upgradeStars", _data.upgradeStars as Any), ("canExportAt", _data.canExportAt as Any), ("transferStars", _data.transferStars as Any), ("canTransferAt", _data.canTransferAt as Any), ("canResellAt", _data.canResellAt as Any), ("collectionId", _data.collectionId as Any), ("prepaidUpgradeHash", _data.prepaidUpgradeHash as Any), ("dropOriginalDetailsStars", _data.dropOriginalDetailsStars as Any), ("giftNum", _data.giftNum as Any), ("canCraftAt", _data.canCraftAt as Any)]) + } + } + public static func parse_savedStarGift(_ reader: BufferReader) -> SavedStarGift? { var _1: Int32? _1 = reader.readInt32() var _2: Api.Peer? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _3: Int32? _3 = reader.readInt32() var _4: Api.StarGift? @@ -624,35 +923,65 @@ public extension Api { _4 = Api.parse(reader, signature: signature) as? Api.StarGift } var _5: Api.TextWithEntities? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.TextWithEntities - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.TextWithEntities + } + } var _6: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 3) != 0 { + _6 = reader.readInt32() + } var _7: Int64? - if Int(_1!) & Int(1 << 11) != 0 {_7 = reader.readInt64() } + if Int(_1!) & Int(1 << 11) != 0 { + _7 = reader.readInt64() + } var _8: Int64? - if Int(_1!) & Int(1 << 4) != 0 {_8 = reader.readInt64() } + if Int(_1!) & Int(1 << 4) != 0 { + _8 = reader.readInt64() + } var _9: Int64? - if Int(_1!) & Int(1 << 6) != 0 {_9 = reader.readInt64() } + if Int(_1!) & Int(1 << 6) != 0 { + _9 = reader.readInt64() + } var _10: Int32? - if Int(_1!) & Int(1 << 7) != 0 {_10 = reader.readInt32() } + if Int(_1!) & Int(1 << 7) != 0 { + _10 = reader.readInt32() + } var _11: Int64? - if Int(_1!) & Int(1 << 8) != 0 {_11 = reader.readInt64() } + if Int(_1!) & Int(1 << 8) != 0 { + _11 = reader.readInt64() + } var _12: Int32? - if Int(_1!) & Int(1 << 13) != 0 {_12 = reader.readInt32() } + if Int(_1!) & Int(1 << 13) != 0 { + _12 = reader.readInt32() + } var _13: Int32? - if Int(_1!) & Int(1 << 14) != 0 {_13 = reader.readInt32() } + if Int(_1!) & Int(1 << 14) != 0 { + _13 = reader.readInt32() + } var _14: [Int32]? - if Int(_1!) & Int(1 << 15) != 0 {if let _ = reader.readInt32() { - _14 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } } + if Int(_1!) & Int(1 << 15) != 0 { + if let _ = reader.readInt32() { + _14 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + } var _15: String? - if Int(_1!) & Int(1 << 16) != 0 {_15 = parseString(reader) } + if Int(_1!) & Int(1 << 16) != 0 { + _15 = parseString(reader) + } var _16: Int64? - if Int(_1!) & Int(1 << 18) != 0 {_16 = reader.readInt64() } + if Int(_1!) & Int(1 << 18) != 0 { + _16 = reader.readInt64() + } var _17: Int32? - if Int(_1!) & Int(1 << 19) != 0 {_17 = reader.readInt32() } + if Int(_1!) & Int(1 << 19) != 0 { + _17 = reader.readInt32() + } + var _18: Int32? + if Int(_1!) & Int(1 << 20) != 0 { + _18 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil let _c3 = _3 != nil @@ -670,54 +999,58 @@ public extension Api { let _c15 = (Int(_1!) & Int(1 << 16) == 0) || _15 != nil let _c16 = (Int(_1!) & Int(1 << 18) == 0) || _16 != nil let _c17 = (Int(_1!) & Int(1 << 19) == 0) || _17 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - if !_c16 { return nil } - if !_c17 { return nil } - return Api.SavedStarGift.savedStarGift(flags: _1!, fromId: _2, date: _3!, gift: _4!, message: _5, msgId: _6, savedId: _7, convertStars: _8, upgradeStars: _9, canExportAt: _10, transferStars: _11, canTransferAt: _12, canResellAt: _13, collectionId: _14, prepaidUpgradeHash: _15, dropOriginalDetailsStars: _16, giftNum: _17) + let _c18 = (Int(_1!) & Int(1 << 20) == 0) || _18 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 && _c18 { + return Api.SavedStarGift.savedStarGift(Cons_savedStarGift(flags: _1!, fromId: _2, date: _3!, gift: _4!, message: _5, msgId: _6, savedId: _7, convertStars: _8, upgradeStars: _9, canExportAt: _10, transferStars: _11, canTransferAt: _12, canResellAt: _13, collectionId: _14, prepaidUpgradeHash: _15, dropOriginalDetailsStars: _16, giftNum: _17, canCraftAt: _18)) + } + else { + return nil + } } - } } public extension Api { enum SearchPostsFlood: TypeConstructorDescription { - case searchPostsFlood(flags: Int32, totalDaily: Int32, remains: Int32, waitTill: Int32?, starsAmount: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .searchPostsFlood(let flags, let totalDaily, let remains, let waitTill, let starsAmount): - if boxed { - buffer.appendInt32(1040931690) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(totalDaily, buffer: buffer, boxed: false) - serializeInt32(remains, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(waitTill!, buffer: buffer, boxed: false)} - serializeInt64(starsAmount, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .searchPostsFlood(let flags, let totalDaily, let remains, let waitTill, let starsAmount): - return ("searchPostsFlood", [("flags", flags as Any), ("totalDaily", totalDaily as Any), ("remains", remains as Any), ("waitTill", waitTill as Any), ("starsAmount", starsAmount as Any)]) - } - } - + public class Cons_searchPostsFlood { + public var flags: Int32 + public var totalDaily: Int32 + public var remains: Int32 + public var waitTill: Int32? + public var starsAmount: Int64 + public init(flags: Int32, totalDaily: Int32, remains: Int32, waitTill: Int32?, starsAmount: Int64) { + self.flags = flags + self.totalDaily = totalDaily + self.remains = remains + self.waitTill = waitTill + self.starsAmount = starsAmount + } + } + case searchPostsFlood(Cons_searchPostsFlood) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .searchPostsFlood(let _data): + if boxed { + buffer.appendInt32(1040931690) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.totalDaily, buffer: buffer, boxed: false) + serializeInt32(_data.remains, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.waitTill!, buffer: buffer, boxed: false) + } + serializeInt64(_data.starsAmount, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .searchPostsFlood(let _data): + return ("searchPostsFlood", [("flags", _data.flags as Any), ("totalDaily", _data.totalDaily as Any), ("remains", _data.remains as Any), ("waitTill", _data.waitTill as Any), ("starsAmount", _data.starsAmount as Any)]) + } + } + public static func parse_searchPostsFlood(_ reader: BufferReader) -> SearchPostsFlood? { var _1: Int32? _1 = reader.readInt32() @@ -726,7 +1059,9 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = reader.readInt32() + } var _5: Int64? _5 = reader.readInt64() let _c1 = _1 != nil @@ -734,41 +1069,52 @@ public extension Api { let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.SearchPostsFlood.searchPostsFlood(flags: _1!, totalDaily: _2!, remains: _3!, waitTill: _4, starsAmount: _5!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.SearchPostsFlood.searchPostsFlood(Cons_searchPostsFlood(flags: _1!, totalDaily: _2!, remains: _3!, waitTill: _4, starsAmount: _5!)) + } + else { + return nil + } } - } } public extension Api { enum SearchResultsCalendarPeriod: TypeConstructorDescription { - case searchResultsCalendarPeriod(date: Int32, minMsgId: Int32, maxMsgId: Int32, count: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .searchResultsCalendarPeriod(let date, let minMsgId, let maxMsgId, let count): - if boxed { - buffer.appendInt32(-911191137) - } - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt32(minMsgId, buffer: buffer, boxed: false) - serializeInt32(maxMsgId, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .searchResultsCalendarPeriod(let date, let minMsgId, let maxMsgId, let count): - return ("searchResultsCalendarPeriod", [("date", date as Any), ("minMsgId", minMsgId as Any), ("maxMsgId", maxMsgId as Any), ("count", count as Any)]) - } - } - + public class Cons_searchResultsCalendarPeriod { + public var date: Int32 + public var minMsgId: Int32 + public var maxMsgId: Int32 + public var count: Int32 + public init(date: Int32, minMsgId: Int32, maxMsgId: Int32, count: Int32) { + self.date = date + self.minMsgId = minMsgId + self.maxMsgId = maxMsgId + self.count = count + } + } + case searchResultsCalendarPeriod(Cons_searchResultsCalendarPeriod) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .searchResultsCalendarPeriod(let _data): + if boxed { + buffer.appendInt32(-911191137) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt32(_data.minMsgId, buffer: buffer, boxed: false) + serializeInt32(_data.maxMsgId, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .searchResultsCalendarPeriod(let _data): + return ("searchResultsCalendarPeriod", [("date", _data.date as Any), ("minMsgId", _data.minMsgId as Any), ("maxMsgId", _data.maxMsgId as Any), ("count", _data.count as Any)]) + } + } + public static func parse_searchResultsCalendarPeriod(_ reader: BufferReader) -> SearchResultsCalendarPeriod? { var _1: Int32? _1 = reader.readInt32() @@ -782,39 +1128,49 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.SearchResultsCalendarPeriod.searchResultsCalendarPeriod(date: _1!, minMsgId: _2!, maxMsgId: _3!, count: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.SearchResultsCalendarPeriod.searchResultsCalendarPeriod(Cons_searchResultsCalendarPeriod(date: _1!, minMsgId: _2!, maxMsgId: _3!, count: _4!)) + } + else { + return nil + } } - } } public extension Api { enum SearchResultsPosition: TypeConstructorDescription { - case searchResultPosition(msgId: Int32, date: Int32, offset: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .searchResultPosition(let msgId, let date, let offset): - if boxed { - buffer.appendInt32(2137295719) - } - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt32(offset, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .searchResultPosition(let msgId, let date, let offset): - return ("searchResultPosition", [("msgId", msgId as Any), ("date", date as Any), ("offset", offset as Any)]) - } - } - + public class Cons_searchResultPosition { + public var msgId: Int32 + public var date: Int32 + public var offset: Int32 + public init(msgId: Int32, date: Int32, offset: Int32) { + self.msgId = msgId + self.date = date + self.offset = offset + } + } + case searchResultPosition(Cons_searchResultPosition) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .searchResultPosition(let _data): + if boxed { + buffer.appendInt32(2137295719) + } + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt32(_data.offset, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .searchResultPosition(let _data): + return ("searchResultPosition", [("msgId", _data.msgId as Any), ("date", _data.date as Any), ("offset", _data.offset as Any)]) + } + } + public static func parse_searchResultPosition(_ reader: BufferReader) -> SearchResultsPosition? { var _1: Int32? _1 = reader.readInt32() @@ -825,38 +1181,49 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SearchResultsPosition.searchResultPosition(msgId: _1!, date: _2!, offset: _3!) + if _c1 && _c2 && _c3 { + return Api.SearchResultsPosition.searchResultPosition(Cons_searchResultPosition(msgId: _1!, date: _2!, offset: _3!)) + } + else { + return nil + } } - } } public extension Api { enum SecureCredentialsEncrypted: TypeConstructorDescription { - case secureCredentialsEncrypted(data: Buffer, hash: Buffer, secret: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .secureCredentialsEncrypted(let data, let hash, let secret): - if boxed { - buffer.appendInt32(871426631) - } - serializeBytes(data, buffer: buffer, boxed: false) - serializeBytes(hash, buffer: buffer, boxed: false) - serializeBytes(secret, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .secureCredentialsEncrypted(let data, let hash, let secret): - return ("secureCredentialsEncrypted", [("data", data as Any), ("hash", hash as Any), ("secret", secret as Any)]) - } - } - + public class Cons_secureCredentialsEncrypted { + public var data: Buffer + public var hash: Buffer + public var secret: Buffer + public init(data: Buffer, hash: Buffer, secret: Buffer) { + self.data = data + self.hash = hash + self.secret = secret + } + } + case secureCredentialsEncrypted(Cons_secureCredentialsEncrypted) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .secureCredentialsEncrypted(let _data): + if boxed { + buffer.appendInt32(871426631) + } + serializeBytes(_data.data, buffer: buffer, boxed: false) + serializeBytes(_data.hash, buffer: buffer, boxed: false) + serializeBytes(_data.secret, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .secureCredentialsEncrypted(let _data): + return ("secureCredentialsEncrypted", [("data", _data.data as Any), ("hash", _data.hash as Any), ("secret", _data.secret as Any)]) + } + } + public static func parse_secureCredentialsEncrypted(_ reader: BufferReader) -> SecureCredentialsEncrypted? { var _1: Buffer? _1 = parseBytes(reader) @@ -867,38 +1234,49 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SecureCredentialsEncrypted.secureCredentialsEncrypted(data: _1!, hash: _2!, secret: _3!) + if _c1 && _c2 && _c3 { + return Api.SecureCredentialsEncrypted.secureCredentialsEncrypted(Cons_secureCredentialsEncrypted(data: _1!, hash: _2!, secret: _3!)) + } + else { + return nil + } } - } } public extension Api { enum SecureData: TypeConstructorDescription { - case secureData(data: Buffer, dataHash: Buffer, secret: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .secureData(let data, let dataHash, let secret): - if boxed { - buffer.appendInt32(-1964327229) - } - serializeBytes(data, buffer: buffer, boxed: false) - serializeBytes(dataHash, buffer: buffer, boxed: false) - serializeBytes(secret, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .secureData(let data, let dataHash, let secret): - return ("secureData", [("data", data as Any), ("dataHash", dataHash as Any), ("secret", secret as Any)]) - } - } - + public class Cons_secureData { + public var data: Buffer + public var dataHash: Buffer + public var secret: Buffer + public init(data: Buffer, dataHash: Buffer, secret: Buffer) { + self.data = data + self.dataHash = dataHash + self.secret = secret + } + } + case secureData(Cons_secureData) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .secureData(let _data): + if boxed { + buffer.appendInt32(-1964327229) + } + serializeBytes(_data.data, buffer: buffer, boxed: false) + serializeBytes(_data.dataHash, buffer: buffer, boxed: false) + serializeBytes(_data.secret, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .secureData(let _data): + return ("secureData", [("data", _data.data as Any), ("dataHash", _data.dataHash as Any), ("secret", _data.secret as Any)]) + } + } + public static func parse_secureData(_ reader: BufferReader) -> SecureData? { var _1: Buffer? _1 = parseBytes(reader) @@ -909,51 +1287,69 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SecureData.secureData(data: _1!, dataHash: _2!, secret: _3!) + if _c1 && _c2 && _c3 { + return Api.SecureData.secureData(Cons_secureData(data: _1!, dataHash: _2!, secret: _3!)) + } + else { + return nil + } } - } } public extension Api { enum SecureFile: TypeConstructorDescription { - case secureFile(id: Int64, accessHash: Int64, size: Int64, dcId: Int32, date: Int32, fileHash: Buffer, secret: Buffer) + public class Cons_secureFile { + public var id: Int64 + public var accessHash: Int64 + public var size: Int64 + public var dcId: Int32 + public var date: Int32 + public var fileHash: Buffer + public var secret: Buffer + public init(id: Int64, accessHash: Int64, size: Int64, dcId: Int32, date: Int32, fileHash: Buffer, secret: Buffer) { + self.id = id + self.accessHash = accessHash + self.size = size + self.dcId = dcId + self.date = date + self.fileHash = fileHash + self.secret = secret + } + } + case secureFile(Cons_secureFile) case secureFileEmpty - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .secureFile(let id, let accessHash, let size, let dcId, let date, let fileHash, let secret): - if boxed { - buffer.appendInt32(2097791614) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeInt64(size, buffer: buffer, boxed: false) - serializeInt32(dcId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeBytes(fileHash, buffer: buffer, boxed: false) - serializeBytes(secret, buffer: buffer, boxed: false) - break - case .secureFileEmpty: - if boxed { - buffer.appendInt32(1679398724) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .secureFile(let id, let accessHash, let size, let dcId, let date, let fileHash, let secret): - return ("secureFile", [("id", id as Any), ("accessHash", accessHash as Any), ("size", size as Any), ("dcId", dcId as Any), ("date", date as Any), ("fileHash", fileHash as Any), ("secret", secret as Any)]) - case .secureFileEmpty: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .secureFile(let _data): + if boxed { + buffer.appendInt32(2097791614) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeInt64(_data.size, buffer: buffer, boxed: false) + serializeInt32(_data.dcId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeBytes(_data.fileHash, buffer: buffer, boxed: false) + serializeBytes(_data.secret, buffer: buffer, boxed: false) + break + case .secureFileEmpty: + if boxed { + buffer.appendInt32(1679398724) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .secureFile(let _data): + return ("secureFile", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("size", _data.size as Any), ("dcId", _data.dcId as Any), ("date", _data.date as Any), ("fileHash", _data.fileHash as Any), ("secret", _data.secret as Any)]) + case .secureFileEmpty: return ("secureFileEmpty", []) - } - } - + } + } + public static func parse_secureFile(_ reader: BufferReader) -> SecureFile? { var _1: Int64? _1 = reader.readInt64() @@ -976,78 +1372,93 @@ public extension Api { let _c5 = _5 != nil let _c6 = _6 != nil let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.SecureFile.secureFile(id: _1!, accessHash: _2!, size: _3!, dcId: _4!, date: _5!, fileHash: _6!, secret: _7!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.SecureFile.secureFile(Cons_secureFile(id: _1!, accessHash: _2!, size: _3!, dcId: _4!, date: _5!, fileHash: _6!, secret: _7!)) + } + else { + return nil + } } public static func parse_secureFileEmpty(_ reader: BufferReader) -> SecureFile? { return Api.SecureFile.secureFileEmpty } - } } public extension Api { enum SecurePasswordKdfAlgo: TypeConstructorDescription { - case securePasswordKdfAlgoPBKDF2HMACSHA512iter100000(salt: Buffer) - case securePasswordKdfAlgoSHA512(salt: Buffer) + public class Cons_securePasswordKdfAlgoPBKDF2HMACSHA512iter100000 { + public var salt: Buffer + public init(salt: Buffer) { + self.salt = salt + } + } + public class Cons_securePasswordKdfAlgoSHA512 { + public var salt: Buffer + public init(salt: Buffer) { + self.salt = salt + } + } + case securePasswordKdfAlgoPBKDF2HMACSHA512iter100000(Cons_securePasswordKdfAlgoPBKDF2HMACSHA512iter100000) + case securePasswordKdfAlgoSHA512(Cons_securePasswordKdfAlgoSHA512) case securePasswordKdfAlgoUnknown - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .securePasswordKdfAlgoPBKDF2HMACSHA512iter100000(let salt): - if boxed { - buffer.appendInt32(-1141711456) - } - serializeBytes(salt, buffer: buffer, boxed: false) - break - case .securePasswordKdfAlgoSHA512(let salt): - if boxed { - buffer.appendInt32(-2042159726) - } - serializeBytes(salt, buffer: buffer, boxed: false) - break - case .securePasswordKdfAlgoUnknown: - if boxed { - buffer.appendInt32(4883767) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .securePasswordKdfAlgoPBKDF2HMACSHA512iter100000(let salt): - return ("securePasswordKdfAlgoPBKDF2HMACSHA512iter100000", [("salt", salt as Any)]) - case .securePasswordKdfAlgoSHA512(let salt): - return ("securePasswordKdfAlgoSHA512", [("salt", salt as Any)]) - case .securePasswordKdfAlgoUnknown: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .securePasswordKdfAlgoPBKDF2HMACSHA512iter100000(let _data): + if boxed { + buffer.appendInt32(-1141711456) + } + serializeBytes(_data.salt, buffer: buffer, boxed: false) + break + case .securePasswordKdfAlgoSHA512(let _data): + if boxed { + buffer.appendInt32(-2042159726) + } + serializeBytes(_data.salt, buffer: buffer, boxed: false) + break + case .securePasswordKdfAlgoUnknown: + if boxed { + buffer.appendInt32(4883767) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .securePasswordKdfAlgoPBKDF2HMACSHA512iter100000(let _data): + return ("securePasswordKdfAlgoPBKDF2HMACSHA512iter100000", [("salt", _data.salt as Any)]) + case .securePasswordKdfAlgoSHA512(let _data): + return ("securePasswordKdfAlgoSHA512", [("salt", _data.salt as Any)]) + case .securePasswordKdfAlgoUnknown: return ("securePasswordKdfAlgoUnknown", []) - } - } - + } + } + public static func parse_securePasswordKdfAlgoPBKDF2HMACSHA512iter100000(_ reader: BufferReader) -> SecurePasswordKdfAlgo? { var _1: Buffer? _1 = parseBytes(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.SecurePasswordKdfAlgo.securePasswordKdfAlgoPBKDF2HMACSHA512iter100000(salt: _1!) + if _c1 { + return Api.SecurePasswordKdfAlgo.securePasswordKdfAlgoPBKDF2HMACSHA512iter100000(Cons_securePasswordKdfAlgoPBKDF2HMACSHA512iter100000(salt: _1!)) + } + else { + return nil + } } public static func parse_securePasswordKdfAlgoSHA512(_ reader: BufferReader) -> SecurePasswordKdfAlgo? { var _1: Buffer? _1 = parseBytes(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.SecurePasswordKdfAlgo.securePasswordKdfAlgoSHA512(salt: _1!) + if _c1 { + return Api.SecurePasswordKdfAlgo.securePasswordKdfAlgoSHA512(Cons_securePasswordKdfAlgoSHA512(salt: _1!)) + } + else { + return nil + } } public static func parse_securePasswordKdfAlgoUnknown(_ reader: BufferReader) -> SecurePasswordKdfAlgo? { return Api.SecurePasswordKdfAlgo.securePasswordKdfAlgoUnknown } - } } diff --git a/submodules/TelegramApi/Sources/Api24.swift b/submodules/TelegramApi/Sources/Api24.swift index 77fe9cc5..ca98335e 100644 --- a/submodules/TelegramApi/Sources/Api24.swift +++ b/submodules/TelegramApi/Sources/Api24.swift @@ -1,87 +1,120 @@ public extension Api { enum SecurePlainData: TypeConstructorDescription { - case securePlainEmail(email: String) - case securePlainPhone(phone: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .securePlainEmail(let email): - if boxed { - buffer.appendInt32(569137759) - } - serializeString(email, buffer: buffer, boxed: false) - break - case .securePlainPhone(let phone): - if boxed { - buffer.appendInt32(2103482845) - } - serializeString(phone, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .securePlainEmail(let email): - return ("securePlainEmail", [("email", email as Any)]) - case .securePlainPhone(let phone): - return ("securePlainPhone", [("phone", phone as Any)]) - } - } - + public class Cons_securePlainEmail { + public var email: String + public init(email: String) { + self.email = email + } + } + public class Cons_securePlainPhone { + public var phone: String + public init(phone: String) { + self.phone = phone + } + } + case securePlainEmail(Cons_securePlainEmail) + case securePlainPhone(Cons_securePlainPhone) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .securePlainEmail(let _data): + if boxed { + buffer.appendInt32(569137759) + } + serializeString(_data.email, buffer: buffer, boxed: false) + break + case .securePlainPhone(let _data): + if boxed { + buffer.appendInt32(2103482845) + } + serializeString(_data.phone, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .securePlainEmail(let _data): + return ("securePlainEmail", [("email", _data.email as Any)]) + case .securePlainPhone(let _data): + return ("securePlainPhone", [("phone", _data.phone as Any)]) + } + } + public static func parse_securePlainEmail(_ reader: BufferReader) -> SecurePlainData? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.SecurePlainData.securePlainEmail(email: _1!) + if _c1 { + return Api.SecurePlainData.securePlainEmail(Cons_securePlainEmail(email: _1!)) + } + else { + return nil + } } public static func parse_securePlainPhone(_ reader: BufferReader) -> SecurePlainData? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.SecurePlainData.securePlainPhone(phone: _1!) + if _c1 { + return Api.SecurePlainData.securePlainPhone(Cons_securePlainPhone(phone: _1!)) + } + else { + return nil + } } - } } public extension Api { enum SecureRequiredType: TypeConstructorDescription { - case secureRequiredType(flags: Int32, type: Api.SecureValueType) - case secureRequiredTypeOneOf(types: [Api.SecureRequiredType]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .secureRequiredType(let flags, let type): - if boxed { - buffer.appendInt32(-2103600678) - } - serializeInt32(flags, buffer: buffer, boxed: false) - type.serialize(buffer, true) - break - case .secureRequiredTypeOneOf(let types): - if boxed { - buffer.appendInt32(41187252) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(types.count)) - for item in types { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .secureRequiredType(let flags, let type): - return ("secureRequiredType", [("flags", flags as Any), ("type", type as Any)]) - case .secureRequiredTypeOneOf(let types): - return ("secureRequiredTypeOneOf", [("types", types as Any)]) - } - } - + public class Cons_secureRequiredType { + public var flags: Int32 + public var type: Api.SecureValueType + public init(flags: Int32, type: Api.SecureValueType) { + self.flags = flags + self.type = type + } + } + public class Cons_secureRequiredTypeOneOf { + public var types: [Api.SecureRequiredType] + public init(types: [Api.SecureRequiredType]) { + self.types = types + } + } + case secureRequiredType(Cons_secureRequiredType) + case secureRequiredTypeOneOf(Cons_secureRequiredTypeOneOf) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .secureRequiredType(let _data): + if boxed { + buffer.appendInt32(-2103600678) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.type.serialize(buffer, true) + break + case .secureRequiredTypeOneOf(let _data): + if boxed { + buffer.appendInt32(41187252) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.types.count)) + for item in _data.types { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .secureRequiredType(let _data): + return ("secureRequiredType", [("flags", _data.flags as Any), ("type", _data.type as Any)]) + case .secureRequiredTypeOneOf(let _data): + return ("secureRequiredTypeOneOf", [("types", _data.types as Any)]) + } + } + public static func parse_secureRequiredType(_ reader: BufferReader) -> SecureRequiredType? { var _1: Int32? _1 = reader.readInt32() @@ -91,9 +124,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.SecureRequiredType.secureRequiredType(flags: _1!, type: _2!) + if _c1 && _c2 { + return Api.SecureRequiredType.secureRequiredType(Cons_secureRequiredType(flags: _1!, type: _2!)) + } + else { + return nil + } } public static func parse_secureRequiredTypeOneOf(_ reader: BufferReader) -> SecureRequiredType? { var _1: [Api.SecureRequiredType]? @@ -101,36 +137,49 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureRequiredType.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.SecureRequiredType.secureRequiredTypeOneOf(types: _1!) + if _c1 { + return Api.SecureRequiredType.secureRequiredTypeOneOf(Cons_secureRequiredTypeOneOf(types: _1!)) + } + else { + return nil + } } - } } public extension Api { enum SecureSecretSettings: TypeConstructorDescription { - case secureSecretSettings(secureAlgo: Api.SecurePasswordKdfAlgo, secureSecret: Buffer, secureSecretId: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .secureSecretSettings(let secureAlgo, let secureSecret, let secureSecretId): - if boxed { - buffer.appendInt32(354925740) - } - secureAlgo.serialize(buffer, true) - serializeBytes(secureSecret, buffer: buffer, boxed: false) - serializeInt64(secureSecretId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .secureSecretSettings(let secureAlgo, let secureSecret, let secureSecretId): - return ("secureSecretSettings", [("secureAlgo", secureAlgo as Any), ("secureSecret", secureSecret as Any), ("secureSecretId", secureSecretId as Any)]) - } - } - + public class Cons_secureSecretSettings { + public var secureAlgo: Api.SecurePasswordKdfAlgo + public var secureSecret: Buffer + public var secureSecretId: Int64 + public init(secureAlgo: Api.SecurePasswordKdfAlgo, secureSecret: Buffer, secureSecretId: Int64) { + self.secureAlgo = secureAlgo + self.secureSecret = secureSecret + self.secureSecretId = secureSecretId + } + } + case secureSecretSettings(Cons_secureSecretSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .secureSecretSettings(let _data): + if boxed { + buffer.appendInt32(354925740) + } + _data.secureAlgo.serialize(buffer, true) + serializeBytes(_data.secureSecret, buffer: buffer, boxed: false) + serializeInt64(_data.secureSecretId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .secureSecretSettings(let _data): + return ("secureSecretSettings", [("secureAlgo", _data.secureAlgo as Any), ("secureSecret", _data.secureSecret as Any), ("secureSecretId", _data.secureSecretId as Any)]) + } + } + public static func parse_secureSecretSettings(_ reader: BufferReader) -> SecureSecretSettings? { var _1: Api.SecurePasswordKdfAlgo? if let signature = reader.readInt32() { @@ -143,53 +192,92 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SecureSecretSettings.secureSecretSettings(secureAlgo: _1!, secureSecret: _2!, secureSecretId: _3!) + if _c1 && _c2 && _c3 { + return Api.SecureSecretSettings.secureSecretSettings(Cons_secureSecretSettings(secureAlgo: _1!, secureSecret: _2!, secureSecretId: _3!)) + } + else { + return nil + } } - } } public extension Api { enum SecureValue: TypeConstructorDescription { - case secureValue(flags: Int32, type: Api.SecureValueType, data: Api.SecureData?, frontSide: Api.SecureFile?, reverseSide: Api.SecureFile?, selfie: Api.SecureFile?, translation: [Api.SecureFile]?, files: [Api.SecureFile]?, plainData: Api.SecurePlainData?, hash: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .secureValue(let flags, let type, let data, let frontSide, let reverseSide, let selfie, let translation, let files, let plainData, let hash): - if boxed { - buffer.appendInt32(411017418) + public class Cons_secureValue { + public var flags: Int32 + public var type: Api.SecureValueType + public var data: Api.SecureData? + public var frontSide: Api.SecureFile? + public var reverseSide: Api.SecureFile? + public var selfie: Api.SecureFile? + public var translation: [Api.SecureFile]? + public var files: [Api.SecureFile]? + public var plainData: Api.SecurePlainData? + public var hash: Buffer + public init(flags: Int32, type: Api.SecureValueType, data: Api.SecureData?, frontSide: Api.SecureFile?, reverseSide: Api.SecureFile?, selfie: Api.SecureFile?, translation: [Api.SecureFile]?, files: [Api.SecureFile]?, plainData: Api.SecurePlainData?, hash: Buffer) { + self.flags = flags + self.type = type + self.data = data + self.frontSide = frontSide + self.reverseSide = reverseSide + self.selfie = selfie + self.translation = translation + self.files = files + self.plainData = plainData + self.hash = hash + } + } + case secureValue(Cons_secureValue) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .secureValue(let _data): + if boxed { + buffer.appendInt32(411017418) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.type.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.data!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.frontSide!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.reverseSide!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.selfie!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.translation!.count)) + for item in _data.translation! { + item.serialize(buffer, true) } - serializeInt32(flags, buffer: buffer, boxed: false) - type.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {data!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {frontSide!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {reverseSide!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {selfie!.serialize(buffer, true)} - if Int(flags) & Int(1 << 6) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(translation!.count)) - for item in translation! { + } + if Int(_data.flags) & Int(1 << 4) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.files!.count)) + for item in _data.files! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 4) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(files!.count)) - for item in files! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 5) != 0 {plainData!.serialize(buffer, true)} - serializeBytes(hash, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .secureValue(let flags, let type, let data, let frontSide, let reverseSide, let selfie, let translation, let files, let plainData, let hash): - return ("secureValue", [("flags", flags as Any), ("type", type as Any), ("data", data as Any), ("frontSide", frontSide as Any), ("reverseSide", reverseSide as Any), ("selfie", selfie as Any), ("translation", translation as Any), ("files", files as Any), ("plainData", plainData as Any), ("hash", hash as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 5) != 0 { + _data.plainData!.serialize(buffer, true) + } + serializeBytes(_data.hash, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .secureValue(let _data): + return ("secureValue", [("flags", _data.flags as Any), ("type", _data.type as Any), ("data", _data.data as Any), ("frontSide", _data.frontSide as Any), ("reverseSide", _data.reverseSide as Any), ("selfie", _data.selfie as Any), ("translation", _data.translation as Any), ("files", _data.files as Any), ("plainData", _data.plainData as Any), ("hash", _data.hash as Any)]) + } + } + public static func parse_secureValue(_ reader: BufferReader) -> SecureValue? { var _1: Int32? _1 = reader.readInt32() @@ -198,33 +286,47 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.SecureValueType } var _3: Api.SecureData? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.SecureData - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.SecureData + } + } var _4: Api.SecureFile? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.SecureFile - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.SecureFile + } + } var _5: Api.SecureFile? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.SecureFile - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.SecureFile + } + } var _6: Api.SecureFile? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.SecureFile - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.SecureFile + } + } var _7: [Api.SecureFile]? - if Int(_1!) & Int(1 << 6) != 0 {if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureFile.self) - } } + if Int(_1!) & Int(1 << 6) != 0 { + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureFile.self) + } + } var _8: [Api.SecureFile]? - if Int(_1!) & Int(1 << 4) != 0 {if let _ = reader.readInt32() { - _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureFile.self) - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let _ = reader.readInt32() { + _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureFile.self) + } + } var _9: Api.SecurePlainData? - if Int(_1!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.SecurePlainData - } } + if Int(_1!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.SecurePlainData + } + } var _10: Buffer? _10 = parseBytes(reader) let _c1 = _1 != nil @@ -237,142 +339,228 @@ public extension Api { let _c8 = (Int(_1!) & Int(1 << 4) == 0) || _8 != nil let _c9 = (Int(_1!) & Int(1 << 5) == 0) || _9 != nil let _c10 = _10 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - return Api.SecureValue.secureValue(flags: _1!, type: _2!, data: _3, frontSide: _4, reverseSide: _5, selfie: _6, translation: _7, files: _8, plainData: _9, hash: _10!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 { + return Api.SecureValue.secureValue(Cons_secureValue(flags: _1!, type: _2!, data: _3, frontSide: _4, reverseSide: _5, selfie: _6, translation: _7, files: _8, plainData: _9, hash: _10!)) + } + else { + return nil + } } - } } public extension Api { enum SecureValueError: TypeConstructorDescription { - case secureValueError(type: Api.SecureValueType, hash: Buffer, text: String) - case secureValueErrorData(type: Api.SecureValueType, dataHash: Buffer, field: String, text: String) - case secureValueErrorFile(type: Api.SecureValueType, fileHash: Buffer, text: String) - case secureValueErrorFiles(type: Api.SecureValueType, fileHash: [Buffer], text: String) - case secureValueErrorFrontSide(type: Api.SecureValueType, fileHash: Buffer, text: String) - case secureValueErrorReverseSide(type: Api.SecureValueType, fileHash: Buffer, text: String) - case secureValueErrorSelfie(type: Api.SecureValueType, fileHash: Buffer, text: String) - case secureValueErrorTranslationFile(type: Api.SecureValueType, fileHash: Buffer, text: String) - case secureValueErrorTranslationFiles(type: Api.SecureValueType, fileHash: [Buffer], text: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .secureValueError(let type, let hash, let text): - if boxed { - buffer.appendInt32(-2036501105) - } - type.serialize(buffer, true) - serializeBytes(hash, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - break - case .secureValueErrorData(let type, let dataHash, let field, let text): - if boxed { - buffer.appendInt32(-391902247) - } - type.serialize(buffer, true) - serializeBytes(dataHash, buffer: buffer, boxed: false) - serializeString(field, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - break - case .secureValueErrorFile(let type, let fileHash, let text): - if boxed { - buffer.appendInt32(2054162547) - } - type.serialize(buffer, true) - serializeBytes(fileHash, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - break - case .secureValueErrorFiles(let type, let fileHash, let text): - if boxed { - buffer.appendInt32(1717706985) - } - type.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(fileHash.count)) - for item in fileHash { - serializeBytes(item, buffer: buffer, boxed: false) - } - serializeString(text, buffer: buffer, boxed: false) - break - case .secureValueErrorFrontSide(let type, let fileHash, let text): - if boxed { - buffer.appendInt32(12467706) - } - type.serialize(buffer, true) - serializeBytes(fileHash, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - break - case .secureValueErrorReverseSide(let type, let fileHash, let text): - if boxed { - buffer.appendInt32(-2037765467) - } - type.serialize(buffer, true) - serializeBytes(fileHash, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - break - case .secureValueErrorSelfie(let type, let fileHash, let text): - if boxed { - buffer.appendInt32(-449327402) - } - type.serialize(buffer, true) - serializeBytes(fileHash, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - break - case .secureValueErrorTranslationFile(let type, let fileHash, let text): - if boxed { - buffer.appendInt32(-1592506512) - } - type.serialize(buffer, true) - serializeBytes(fileHash, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - break - case .secureValueErrorTranslationFiles(let type, let fileHash, let text): - if boxed { - buffer.appendInt32(878931416) - } - type.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(fileHash.count)) - for item in fileHash { - serializeBytes(item, buffer: buffer, boxed: false) - } - serializeString(text, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .secureValueError(let type, let hash, let text): - return ("secureValueError", [("type", type as Any), ("hash", hash as Any), ("text", text as Any)]) - case .secureValueErrorData(let type, let dataHash, let field, let text): - return ("secureValueErrorData", [("type", type as Any), ("dataHash", dataHash as Any), ("field", field as Any), ("text", text as Any)]) - case .secureValueErrorFile(let type, let fileHash, let text): - return ("secureValueErrorFile", [("type", type as Any), ("fileHash", fileHash as Any), ("text", text as Any)]) - case .secureValueErrorFiles(let type, let fileHash, let text): - return ("secureValueErrorFiles", [("type", type as Any), ("fileHash", fileHash as Any), ("text", text as Any)]) - case .secureValueErrorFrontSide(let type, let fileHash, let text): - return ("secureValueErrorFrontSide", [("type", type as Any), ("fileHash", fileHash as Any), ("text", text as Any)]) - case .secureValueErrorReverseSide(let type, let fileHash, let text): - return ("secureValueErrorReverseSide", [("type", type as Any), ("fileHash", fileHash as Any), ("text", text as Any)]) - case .secureValueErrorSelfie(let type, let fileHash, let text): - return ("secureValueErrorSelfie", [("type", type as Any), ("fileHash", fileHash as Any), ("text", text as Any)]) - case .secureValueErrorTranslationFile(let type, let fileHash, let text): - return ("secureValueErrorTranslationFile", [("type", type as Any), ("fileHash", fileHash as Any), ("text", text as Any)]) - case .secureValueErrorTranslationFiles(let type, let fileHash, let text): - return ("secureValueErrorTranslationFiles", [("type", type as Any), ("fileHash", fileHash as Any), ("text", text as Any)]) - } - } - + public class Cons_secureValueError { + public var type: Api.SecureValueType + public var hash: Buffer + public var text: String + public init(type: Api.SecureValueType, hash: Buffer, text: String) { + self.type = type + self.hash = hash + self.text = text + } + } + public class Cons_secureValueErrorData { + public var type: Api.SecureValueType + public var dataHash: Buffer + public var field: String + public var text: String + public init(type: Api.SecureValueType, dataHash: Buffer, field: String, text: String) { + self.type = type + self.dataHash = dataHash + self.field = field + self.text = text + } + } + public class Cons_secureValueErrorFile { + public var type: Api.SecureValueType + public var fileHash: Buffer + public var text: String + public init(type: Api.SecureValueType, fileHash: Buffer, text: String) { + self.type = type + self.fileHash = fileHash + self.text = text + } + } + public class Cons_secureValueErrorFiles { + public var type: Api.SecureValueType + public var fileHash: [Buffer] + public var text: String + public init(type: Api.SecureValueType, fileHash: [Buffer], text: String) { + self.type = type + self.fileHash = fileHash + self.text = text + } + } + public class Cons_secureValueErrorFrontSide { + public var type: Api.SecureValueType + public var fileHash: Buffer + public var text: String + public init(type: Api.SecureValueType, fileHash: Buffer, text: String) { + self.type = type + self.fileHash = fileHash + self.text = text + } + } + public class Cons_secureValueErrorReverseSide { + public var type: Api.SecureValueType + public var fileHash: Buffer + public var text: String + public init(type: Api.SecureValueType, fileHash: Buffer, text: String) { + self.type = type + self.fileHash = fileHash + self.text = text + } + } + public class Cons_secureValueErrorSelfie { + public var type: Api.SecureValueType + public var fileHash: Buffer + public var text: String + public init(type: Api.SecureValueType, fileHash: Buffer, text: String) { + self.type = type + self.fileHash = fileHash + self.text = text + } + } + public class Cons_secureValueErrorTranslationFile { + public var type: Api.SecureValueType + public var fileHash: Buffer + public var text: String + public init(type: Api.SecureValueType, fileHash: Buffer, text: String) { + self.type = type + self.fileHash = fileHash + self.text = text + } + } + public class Cons_secureValueErrorTranslationFiles { + public var type: Api.SecureValueType + public var fileHash: [Buffer] + public var text: String + public init(type: Api.SecureValueType, fileHash: [Buffer], text: String) { + self.type = type + self.fileHash = fileHash + self.text = text + } + } + case secureValueError(Cons_secureValueError) + case secureValueErrorData(Cons_secureValueErrorData) + case secureValueErrorFile(Cons_secureValueErrorFile) + case secureValueErrorFiles(Cons_secureValueErrorFiles) + case secureValueErrorFrontSide(Cons_secureValueErrorFrontSide) + case secureValueErrorReverseSide(Cons_secureValueErrorReverseSide) + case secureValueErrorSelfie(Cons_secureValueErrorSelfie) + case secureValueErrorTranslationFile(Cons_secureValueErrorTranslationFile) + case secureValueErrorTranslationFiles(Cons_secureValueErrorTranslationFiles) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .secureValueError(let _data): + if boxed { + buffer.appendInt32(-2036501105) + } + _data.type.serialize(buffer, true) + serializeBytes(_data.hash, buffer: buffer, boxed: false) + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .secureValueErrorData(let _data): + if boxed { + buffer.appendInt32(-391902247) + } + _data.type.serialize(buffer, true) + serializeBytes(_data.dataHash, buffer: buffer, boxed: false) + serializeString(_data.field, buffer: buffer, boxed: false) + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .secureValueErrorFile(let _data): + if boxed { + buffer.appendInt32(2054162547) + } + _data.type.serialize(buffer, true) + serializeBytes(_data.fileHash, buffer: buffer, boxed: false) + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .secureValueErrorFiles(let _data): + if boxed { + buffer.appendInt32(1717706985) + } + _data.type.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.fileHash.count)) + for item in _data.fileHash { + serializeBytes(item, buffer: buffer, boxed: false) + } + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .secureValueErrorFrontSide(let _data): + if boxed { + buffer.appendInt32(12467706) + } + _data.type.serialize(buffer, true) + serializeBytes(_data.fileHash, buffer: buffer, boxed: false) + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .secureValueErrorReverseSide(let _data): + if boxed { + buffer.appendInt32(-2037765467) + } + _data.type.serialize(buffer, true) + serializeBytes(_data.fileHash, buffer: buffer, boxed: false) + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .secureValueErrorSelfie(let _data): + if boxed { + buffer.appendInt32(-449327402) + } + _data.type.serialize(buffer, true) + serializeBytes(_data.fileHash, buffer: buffer, boxed: false) + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .secureValueErrorTranslationFile(let _data): + if boxed { + buffer.appendInt32(-1592506512) + } + _data.type.serialize(buffer, true) + serializeBytes(_data.fileHash, buffer: buffer, boxed: false) + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .secureValueErrorTranslationFiles(let _data): + if boxed { + buffer.appendInt32(878931416) + } + _data.type.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.fileHash.count)) + for item in _data.fileHash { + serializeBytes(item, buffer: buffer, boxed: false) + } + serializeString(_data.text, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .secureValueError(let _data): + return ("secureValueError", [("type", _data.type as Any), ("hash", _data.hash as Any), ("text", _data.text as Any)]) + case .secureValueErrorData(let _data): + return ("secureValueErrorData", [("type", _data.type as Any), ("dataHash", _data.dataHash as Any), ("field", _data.field as Any), ("text", _data.text as Any)]) + case .secureValueErrorFile(let _data): + return ("secureValueErrorFile", [("type", _data.type as Any), ("fileHash", _data.fileHash as Any), ("text", _data.text as Any)]) + case .secureValueErrorFiles(let _data): + return ("secureValueErrorFiles", [("type", _data.type as Any), ("fileHash", _data.fileHash as Any), ("text", _data.text as Any)]) + case .secureValueErrorFrontSide(let _data): + return ("secureValueErrorFrontSide", [("type", _data.type as Any), ("fileHash", _data.fileHash as Any), ("text", _data.text as Any)]) + case .secureValueErrorReverseSide(let _data): + return ("secureValueErrorReverseSide", [("type", _data.type as Any), ("fileHash", _data.fileHash as Any), ("text", _data.text as Any)]) + case .secureValueErrorSelfie(let _data): + return ("secureValueErrorSelfie", [("type", _data.type as Any), ("fileHash", _data.fileHash as Any), ("text", _data.text as Any)]) + case .secureValueErrorTranslationFile(let _data): + return ("secureValueErrorTranslationFile", [("type", _data.type as Any), ("fileHash", _data.fileHash as Any), ("text", _data.text as Any)]) + case .secureValueErrorTranslationFiles(let _data): + return ("secureValueErrorTranslationFiles", [("type", _data.type as Any), ("fileHash", _data.fileHash as Any), ("text", _data.text as Any)]) + } + } + public static func parse_secureValueError(_ reader: BufferReader) -> SecureValueError? { var _1: Api.SecureValueType? if let signature = reader.readInt32() { @@ -385,10 +573,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SecureValueError.secureValueError(type: _1!, hash: _2!, text: _3!) + if _c1 && _c2 && _c3 { + return Api.SecureValueError.secureValueError(Cons_secureValueError(type: _1!, hash: _2!, text: _3!)) + } + else { + return nil + } } public static func parse_secureValueErrorData(_ reader: BufferReader) -> SecureValueError? { var _1: Api.SecureValueType? @@ -405,11 +595,12 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.SecureValueError.secureValueErrorData(type: _1!, dataHash: _2!, field: _3!, text: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.SecureValueError.secureValueErrorData(Cons_secureValueErrorData(type: _1!, dataHash: _2!, field: _3!, text: _4!)) + } + else { + return nil + } } public static func parse_secureValueErrorFile(_ reader: BufferReader) -> SecureValueError? { var _1: Api.SecureValueType? @@ -423,10 +614,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SecureValueError.secureValueErrorFile(type: _1!, fileHash: _2!, text: _3!) + if _c1 && _c2 && _c3 { + return Api.SecureValueError.secureValueErrorFile(Cons_secureValueErrorFile(type: _1!, fileHash: _2!, text: _3!)) + } + else { + return nil + } } public static func parse_secureValueErrorFiles(_ reader: BufferReader) -> SecureValueError? { var _1: Api.SecureValueType? @@ -442,10 +635,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SecureValueError.secureValueErrorFiles(type: _1!, fileHash: _2!, text: _3!) + if _c1 && _c2 && _c3 { + return Api.SecureValueError.secureValueErrorFiles(Cons_secureValueErrorFiles(type: _1!, fileHash: _2!, text: _3!)) + } + else { + return nil + } } public static func parse_secureValueErrorFrontSide(_ reader: BufferReader) -> SecureValueError? { var _1: Api.SecureValueType? @@ -459,10 +654,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SecureValueError.secureValueErrorFrontSide(type: _1!, fileHash: _2!, text: _3!) + if _c1 && _c2 && _c3 { + return Api.SecureValueError.secureValueErrorFrontSide(Cons_secureValueErrorFrontSide(type: _1!, fileHash: _2!, text: _3!)) + } + else { + return nil + } } public static func parse_secureValueErrorReverseSide(_ reader: BufferReader) -> SecureValueError? { var _1: Api.SecureValueType? @@ -476,10 +673,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SecureValueError.secureValueErrorReverseSide(type: _1!, fileHash: _2!, text: _3!) + if _c1 && _c2 && _c3 { + return Api.SecureValueError.secureValueErrorReverseSide(Cons_secureValueErrorReverseSide(type: _1!, fileHash: _2!, text: _3!)) + } + else { + return nil + } } public static func parse_secureValueErrorSelfie(_ reader: BufferReader) -> SecureValueError? { var _1: Api.SecureValueType? @@ -493,10 +692,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SecureValueError.secureValueErrorSelfie(type: _1!, fileHash: _2!, text: _3!) + if _c1 && _c2 && _c3 { + return Api.SecureValueError.secureValueErrorSelfie(Cons_secureValueErrorSelfie(type: _1!, fileHash: _2!, text: _3!)) + } + else { + return nil + } } public static func parse_secureValueErrorTranslationFile(_ reader: BufferReader) -> SecureValueError? { var _1: Api.SecureValueType? @@ -510,10 +711,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SecureValueError.secureValueErrorTranslationFile(type: _1!, fileHash: _2!, text: _3!) + if _c1 && _c2 && _c3 { + return Api.SecureValueError.secureValueErrorTranslationFile(Cons_secureValueErrorTranslationFile(type: _1!, fileHash: _2!, text: _3!)) + } + else { + return nil + } } public static func parse_secureValueErrorTranslationFiles(_ reader: BufferReader) -> SecureValueError? { var _1: Api.SecureValueType? @@ -529,37 +732,46 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SecureValueError.secureValueErrorTranslationFiles(type: _1!, fileHash: _2!, text: _3!) + if _c1 && _c2 && _c3 { + return Api.SecureValueError.secureValueErrorTranslationFiles(Cons_secureValueErrorTranslationFiles(type: _1!, fileHash: _2!, text: _3!)) + } + else { + return nil + } } - } } public extension Api { enum SecureValueHash: TypeConstructorDescription { - case secureValueHash(type: Api.SecureValueType, hash: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .secureValueHash(let type, let hash): - if boxed { - buffer.appendInt32(-316748368) - } - type.serialize(buffer, true) - serializeBytes(hash, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .secureValueHash(let type, let hash): - return ("secureValueHash", [("type", type as Any), ("hash", hash as Any)]) - } - } - + public class Cons_secureValueHash { + public var type: Api.SecureValueType + public var hash: Buffer + public init(type: Api.SecureValueType, hash: Buffer) { + self.type = type + self.hash = hash + } + } + case secureValueHash(Cons_secureValueHash) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .secureValueHash(let _data): + if boxed { + buffer.appendInt32(-316748368) + } + _data.type.serialize(buffer, true) + serializeBytes(_data.hash, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .secureValueHash(let _data): + return ("secureValueHash", [("type", _data.type as Any), ("hash", _data.hash as Any)]) + } + } + public static func parse_secureValueHash(_ reader: BufferReader) -> SecureValueHash? { var _1: Api.SecureValueType? if let signature = reader.readInt32() { @@ -569,11 +781,13 @@ public extension Api { _2 = parseBytes(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.SecureValueHash.secureValueHash(type: _1!, hash: _2!) + if _c1 && _c2 { + return Api.SecureValueHash.secureValueHash(Cons_secureValueHash(type: _1!, hash: _2!)) + } + else { + return nil + } } - } } public extension Api { @@ -591,121 +805,108 @@ public extension Api { case secureValueTypeRentalAgreement case secureValueTypeTemporaryRegistration case secureValueTypeUtilityBill - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .secureValueTypeAddress: - if boxed { - buffer.appendInt32(-874308058) - } - - break - case .secureValueTypeBankStatement: - if boxed { - buffer.appendInt32(-1995211763) - } - - break - case .secureValueTypeDriverLicense: - if boxed { - buffer.appendInt32(115615172) - } - - break - case .secureValueTypeEmail: - if boxed { - buffer.appendInt32(-1908627474) - } - - break - case .secureValueTypeIdentityCard: - if boxed { - buffer.appendInt32(-1596951477) - } - - break - case .secureValueTypeInternalPassport: - if boxed { - buffer.appendInt32(-1717268701) - } - - break - case .secureValueTypePassport: - if boxed { - buffer.appendInt32(1034709504) - } - - break - case .secureValueTypePassportRegistration: - if boxed { - buffer.appendInt32(-1713143702) - } - - break - case .secureValueTypePersonalDetails: - if boxed { - buffer.appendInt32(-1658158621) - } - - break - case .secureValueTypePhone: - if boxed { - buffer.appendInt32(-1289704741) - } - - break - case .secureValueTypeRentalAgreement: - if boxed { - buffer.appendInt32(-1954007928) - } - - break - case .secureValueTypeTemporaryRegistration: - if boxed { - buffer.appendInt32(-368907213) - } - - break - case .secureValueTypeUtilityBill: - if boxed { - buffer.appendInt32(-63531698) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .secureValueTypeAddress: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .secureValueTypeAddress: + if boxed { + buffer.appendInt32(-874308058) + } + break + case .secureValueTypeBankStatement: + if boxed { + buffer.appendInt32(-1995211763) + } + break + case .secureValueTypeDriverLicense: + if boxed { + buffer.appendInt32(115615172) + } + break + case .secureValueTypeEmail: + if boxed { + buffer.appendInt32(-1908627474) + } + break + case .secureValueTypeIdentityCard: + if boxed { + buffer.appendInt32(-1596951477) + } + break + case .secureValueTypeInternalPassport: + if boxed { + buffer.appendInt32(-1717268701) + } + break + case .secureValueTypePassport: + if boxed { + buffer.appendInt32(1034709504) + } + break + case .secureValueTypePassportRegistration: + if boxed { + buffer.appendInt32(-1713143702) + } + break + case .secureValueTypePersonalDetails: + if boxed { + buffer.appendInt32(-1658158621) + } + break + case .secureValueTypePhone: + if boxed { + buffer.appendInt32(-1289704741) + } + break + case .secureValueTypeRentalAgreement: + if boxed { + buffer.appendInt32(-1954007928) + } + break + case .secureValueTypeTemporaryRegistration: + if boxed { + buffer.appendInt32(-368907213) + } + break + case .secureValueTypeUtilityBill: + if boxed { + buffer.appendInt32(-63531698) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .secureValueTypeAddress: return ("secureValueTypeAddress", []) - case .secureValueTypeBankStatement: + case .secureValueTypeBankStatement: return ("secureValueTypeBankStatement", []) - case .secureValueTypeDriverLicense: + case .secureValueTypeDriverLicense: return ("secureValueTypeDriverLicense", []) - case .secureValueTypeEmail: + case .secureValueTypeEmail: return ("secureValueTypeEmail", []) - case .secureValueTypeIdentityCard: + case .secureValueTypeIdentityCard: return ("secureValueTypeIdentityCard", []) - case .secureValueTypeInternalPassport: + case .secureValueTypeInternalPassport: return ("secureValueTypeInternalPassport", []) - case .secureValueTypePassport: + case .secureValueTypePassport: return ("secureValueTypePassport", []) - case .secureValueTypePassportRegistration: + case .secureValueTypePassportRegistration: return ("secureValueTypePassportRegistration", []) - case .secureValueTypePersonalDetails: + case .secureValueTypePersonalDetails: return ("secureValueTypePersonalDetails", []) - case .secureValueTypePhone: + case .secureValueTypePhone: return ("secureValueTypePhone", []) - case .secureValueTypeRentalAgreement: + case .secureValueTypeRentalAgreement: return ("secureValueTypeRentalAgreement", []) - case .secureValueTypeTemporaryRegistration: + case .secureValueTypeTemporaryRegistration: return ("secureValueTypeTemporaryRegistration", []) - case .secureValueTypeUtilityBill: + case .secureValueTypeUtilityBill: return ("secureValueTypeUtilityBill", []) - } - } - + } + } + public static func parse_secureValueTypeAddress(_ reader: BufferReader) -> SecureValueType? { return Api.SecureValueType.secureValueTypeAddress } @@ -745,32 +946,39 @@ public extension Api { public static func parse_secureValueTypeUtilityBill(_ reader: BufferReader) -> SecureValueType? { return Api.SecureValueType.secureValueTypeUtilityBill } - } } public extension Api { enum SendAsPeer: TypeConstructorDescription { - case sendAsPeer(flags: Int32, peer: Api.Peer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .sendAsPeer(let flags, let peer): - if boxed { - buffer.appendInt32(-1206095820) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .sendAsPeer(let flags, let peer): - return ("sendAsPeer", [("flags", flags as Any), ("peer", peer as Any)]) - } - } - + public class Cons_sendAsPeer { + public var flags: Int32 + public var peer: Api.Peer + public init(flags: Int32, peer: Api.Peer) { + self.flags = flags + self.peer = peer + } + } + case sendAsPeer(Cons_sendAsPeer) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .sendAsPeer(let _data): + if boxed { + buffer.appendInt32(-1206095820) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .sendAsPeer(let _data): + return ("sendAsPeer", [("flags", _data.flags as Any), ("peer", _data.peer as Any)]) + } + } + public static func parse_sendAsPeer(_ reader: BufferReader) -> SendAsPeer? { var _1: Int32? _1 = reader.readInt32() @@ -780,200 +988,252 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.SendAsPeer.sendAsPeer(flags: _1!, peer: _2!) + if _c1 && _c2 { + return Api.SendAsPeer.sendAsPeer(Cons_sendAsPeer(flags: _1!, peer: _2!)) + } + else { + return nil + } } - } } public extension Api { enum SendMessageAction: TypeConstructorDescription { + public class Cons_sendMessageEmojiInteraction { + public var emoticon: String + public var msgId: Int32 + public var interaction: Api.DataJSON + public init(emoticon: String, msgId: Int32, interaction: Api.DataJSON) { + self.emoticon = emoticon + self.msgId = msgId + self.interaction = interaction + } + } + public class Cons_sendMessageEmojiInteractionSeen { + public var emoticon: String + public init(emoticon: String) { + self.emoticon = emoticon + } + } + public class Cons_sendMessageHistoryImportAction { + public var progress: Int32 + public init(progress: Int32) { + self.progress = progress + } + } + public class Cons_sendMessageTextDraftAction { + public var randomId: Int64 + public var text: Api.TextWithEntities + public init(randomId: Int64, text: Api.TextWithEntities) { + self.randomId = randomId + self.text = text + } + } + public class Cons_sendMessageUploadAudioAction { + public var progress: Int32 + public init(progress: Int32) { + self.progress = progress + } + } + public class Cons_sendMessageUploadDocumentAction { + public var progress: Int32 + public init(progress: Int32) { + self.progress = progress + } + } + public class Cons_sendMessageUploadPhotoAction { + public var progress: Int32 + public init(progress: Int32) { + self.progress = progress + } + } + public class Cons_sendMessageUploadRoundAction { + public var progress: Int32 + public init(progress: Int32) { + self.progress = progress + } + } + public class Cons_sendMessageUploadVideoAction { + public var progress: Int32 + public init(progress: Int32) { + self.progress = progress + } + } case sendMessageCancelAction case sendMessageChooseContactAction case sendMessageChooseStickerAction - case sendMessageEmojiInteraction(emoticon: String, msgId: Int32, interaction: Api.DataJSON) - case sendMessageEmojiInteractionSeen(emoticon: String) + case sendMessageEmojiInteraction(Cons_sendMessageEmojiInteraction) + case sendMessageEmojiInteractionSeen(Cons_sendMessageEmojiInteractionSeen) case sendMessageGamePlayAction case sendMessageGeoLocationAction - case sendMessageHistoryImportAction(progress: Int32) + case sendMessageHistoryImportAction(Cons_sendMessageHistoryImportAction) case sendMessageRecordAudioAction case sendMessageRecordRoundAction case sendMessageRecordVideoAction - case sendMessageTextDraftAction(randomId: Int64, text: Api.TextWithEntities) + case sendMessageTextDraftAction(Cons_sendMessageTextDraftAction) case sendMessageTypingAction - case sendMessageUploadAudioAction(progress: Int32) - case sendMessageUploadDocumentAction(progress: Int32) - case sendMessageUploadPhotoAction(progress: Int32) - case sendMessageUploadRoundAction(progress: Int32) - case sendMessageUploadVideoAction(progress: Int32) + case sendMessageUploadAudioAction(Cons_sendMessageUploadAudioAction) + case sendMessageUploadDocumentAction(Cons_sendMessageUploadDocumentAction) + case sendMessageUploadPhotoAction(Cons_sendMessageUploadPhotoAction) + case sendMessageUploadRoundAction(Cons_sendMessageUploadRoundAction) + case sendMessageUploadVideoAction(Cons_sendMessageUploadVideoAction) case speakingInGroupCallAction - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .sendMessageCancelAction: - if boxed { - buffer.appendInt32(-44119819) - } - - break - case .sendMessageChooseContactAction: - if boxed { - buffer.appendInt32(1653390447) - } - - break - case .sendMessageChooseStickerAction: - if boxed { - buffer.appendInt32(-1336228175) - } - - break - case .sendMessageEmojiInteraction(let emoticon, let msgId, let interaction): - if boxed { - buffer.appendInt32(630664139) - } - serializeString(emoticon, buffer: buffer, boxed: false) - serializeInt32(msgId, buffer: buffer, boxed: false) - interaction.serialize(buffer, true) - break - case .sendMessageEmojiInteractionSeen(let emoticon): - if boxed { - buffer.appendInt32(-1234857938) - } - serializeString(emoticon, buffer: buffer, boxed: false) - break - case .sendMessageGamePlayAction: - if boxed { - buffer.appendInt32(-580219064) - } - - break - case .sendMessageGeoLocationAction: - if boxed { - buffer.appendInt32(393186209) - } - - break - case .sendMessageHistoryImportAction(let progress): - if boxed { - buffer.appendInt32(-606432698) - } - serializeInt32(progress, buffer: buffer, boxed: false) - break - case .sendMessageRecordAudioAction: - if boxed { - buffer.appendInt32(-718310409) - } - - break - case .sendMessageRecordRoundAction: - if boxed { - buffer.appendInt32(-1997373508) - } - - break - case .sendMessageRecordVideoAction: - if boxed { - buffer.appendInt32(-1584933265) - } - - break - case .sendMessageTextDraftAction(let randomId, let text): - if boxed { - buffer.appendInt32(929929052) - } - serializeInt64(randomId, buffer: buffer, boxed: false) - text.serialize(buffer, true) - break - case .sendMessageTypingAction: - if boxed { - buffer.appendInt32(381645902) - } - - break - case .sendMessageUploadAudioAction(let progress): - if boxed { - buffer.appendInt32(-212740181) - } - serializeInt32(progress, buffer: buffer, boxed: false) - break - case .sendMessageUploadDocumentAction(let progress): - if boxed { - buffer.appendInt32(-1441998364) - } - serializeInt32(progress, buffer: buffer, boxed: false) - break - case .sendMessageUploadPhotoAction(let progress): - if boxed { - buffer.appendInt32(-774682074) - } - serializeInt32(progress, buffer: buffer, boxed: false) - break - case .sendMessageUploadRoundAction(let progress): - if boxed { - buffer.appendInt32(608050278) - } - serializeInt32(progress, buffer: buffer, boxed: false) - break - case .sendMessageUploadVideoAction(let progress): - if boxed { - buffer.appendInt32(-378127636) - } - serializeInt32(progress, buffer: buffer, boxed: false) - break - case .speakingInGroupCallAction: - if boxed { - buffer.appendInt32(-651419003) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .sendMessageCancelAction: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .sendMessageCancelAction: + if boxed { + buffer.appendInt32(-44119819) + } + break + case .sendMessageChooseContactAction: + if boxed { + buffer.appendInt32(1653390447) + } + break + case .sendMessageChooseStickerAction: + if boxed { + buffer.appendInt32(-1336228175) + } + break + case .sendMessageEmojiInteraction(let _data): + if boxed { + buffer.appendInt32(630664139) + } + serializeString(_data.emoticon, buffer: buffer, boxed: false) + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + _data.interaction.serialize(buffer, true) + break + case .sendMessageEmojiInteractionSeen(let _data): + if boxed { + buffer.appendInt32(-1234857938) + } + serializeString(_data.emoticon, buffer: buffer, boxed: false) + break + case .sendMessageGamePlayAction: + if boxed { + buffer.appendInt32(-580219064) + } + break + case .sendMessageGeoLocationAction: + if boxed { + buffer.appendInt32(393186209) + } + break + case .sendMessageHistoryImportAction(let _data): + if boxed { + buffer.appendInt32(-606432698) + } + serializeInt32(_data.progress, buffer: buffer, boxed: false) + break + case .sendMessageRecordAudioAction: + if boxed { + buffer.appendInt32(-718310409) + } + break + case .sendMessageRecordRoundAction: + if boxed { + buffer.appendInt32(-1997373508) + } + break + case .sendMessageRecordVideoAction: + if boxed { + buffer.appendInt32(-1584933265) + } + break + case .sendMessageTextDraftAction(let _data): + if boxed { + buffer.appendInt32(929929052) + } + serializeInt64(_data.randomId, buffer: buffer, boxed: false) + _data.text.serialize(buffer, true) + break + case .sendMessageTypingAction: + if boxed { + buffer.appendInt32(381645902) + } + break + case .sendMessageUploadAudioAction(let _data): + if boxed { + buffer.appendInt32(-212740181) + } + serializeInt32(_data.progress, buffer: buffer, boxed: false) + break + case .sendMessageUploadDocumentAction(let _data): + if boxed { + buffer.appendInt32(-1441998364) + } + serializeInt32(_data.progress, buffer: buffer, boxed: false) + break + case .sendMessageUploadPhotoAction(let _data): + if boxed { + buffer.appendInt32(-774682074) + } + serializeInt32(_data.progress, buffer: buffer, boxed: false) + break + case .sendMessageUploadRoundAction(let _data): + if boxed { + buffer.appendInt32(608050278) + } + serializeInt32(_data.progress, buffer: buffer, boxed: false) + break + case .sendMessageUploadVideoAction(let _data): + if boxed { + buffer.appendInt32(-378127636) + } + serializeInt32(_data.progress, buffer: buffer, boxed: false) + break + case .speakingInGroupCallAction: + if boxed { + buffer.appendInt32(-651419003) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .sendMessageCancelAction: return ("sendMessageCancelAction", []) - case .sendMessageChooseContactAction: + case .sendMessageChooseContactAction: return ("sendMessageChooseContactAction", []) - case .sendMessageChooseStickerAction: + case .sendMessageChooseStickerAction: return ("sendMessageChooseStickerAction", []) - case .sendMessageEmojiInteraction(let emoticon, let msgId, let interaction): - return ("sendMessageEmojiInteraction", [("emoticon", emoticon as Any), ("msgId", msgId as Any), ("interaction", interaction as Any)]) - case .sendMessageEmojiInteractionSeen(let emoticon): - return ("sendMessageEmojiInteractionSeen", [("emoticon", emoticon as Any)]) - case .sendMessageGamePlayAction: + case .sendMessageEmojiInteraction(let _data): + return ("sendMessageEmojiInteraction", [("emoticon", _data.emoticon as Any), ("msgId", _data.msgId as Any), ("interaction", _data.interaction as Any)]) + case .sendMessageEmojiInteractionSeen(let _data): + return ("sendMessageEmojiInteractionSeen", [("emoticon", _data.emoticon as Any)]) + case .sendMessageGamePlayAction: return ("sendMessageGamePlayAction", []) - case .sendMessageGeoLocationAction: + case .sendMessageGeoLocationAction: return ("sendMessageGeoLocationAction", []) - case .sendMessageHistoryImportAction(let progress): - return ("sendMessageHistoryImportAction", [("progress", progress as Any)]) - case .sendMessageRecordAudioAction: + case .sendMessageHistoryImportAction(let _data): + return ("sendMessageHistoryImportAction", [("progress", _data.progress as Any)]) + case .sendMessageRecordAudioAction: return ("sendMessageRecordAudioAction", []) - case .sendMessageRecordRoundAction: + case .sendMessageRecordRoundAction: return ("sendMessageRecordRoundAction", []) - case .sendMessageRecordVideoAction: + case .sendMessageRecordVideoAction: return ("sendMessageRecordVideoAction", []) - case .sendMessageTextDraftAction(let randomId, let text): - return ("sendMessageTextDraftAction", [("randomId", randomId as Any), ("text", text as Any)]) - case .sendMessageTypingAction: + case .sendMessageTextDraftAction(let _data): + return ("sendMessageTextDraftAction", [("randomId", _data.randomId as Any), ("text", _data.text as Any)]) + case .sendMessageTypingAction: return ("sendMessageTypingAction", []) - case .sendMessageUploadAudioAction(let progress): - return ("sendMessageUploadAudioAction", [("progress", progress as Any)]) - case .sendMessageUploadDocumentAction(let progress): - return ("sendMessageUploadDocumentAction", [("progress", progress as Any)]) - case .sendMessageUploadPhotoAction(let progress): - return ("sendMessageUploadPhotoAction", [("progress", progress as Any)]) - case .sendMessageUploadRoundAction(let progress): - return ("sendMessageUploadRoundAction", [("progress", progress as Any)]) - case .sendMessageUploadVideoAction(let progress): - return ("sendMessageUploadVideoAction", [("progress", progress as Any)]) - case .speakingInGroupCallAction: + case .sendMessageUploadAudioAction(let _data): + return ("sendMessageUploadAudioAction", [("progress", _data.progress as Any)]) + case .sendMessageUploadDocumentAction(let _data): + return ("sendMessageUploadDocumentAction", [("progress", _data.progress as Any)]) + case .sendMessageUploadPhotoAction(let _data): + return ("sendMessageUploadPhotoAction", [("progress", _data.progress as Any)]) + case .sendMessageUploadRoundAction(let _data): + return ("sendMessageUploadRoundAction", [("progress", _data.progress as Any)]) + case .sendMessageUploadVideoAction(let _data): + return ("sendMessageUploadVideoAction", [("progress", _data.progress as Any)]) + case .speakingInGroupCallAction: return ("speakingInGroupCallAction", []) - } - } - + } + } + public static func parse_sendMessageCancelAction(_ reader: BufferReader) -> SendMessageAction? { return Api.SendMessageAction.sendMessageCancelAction } @@ -995,17 +1255,23 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SendMessageAction.sendMessageEmojiInteraction(emoticon: _1!, msgId: _2!, interaction: _3!) + if _c1 && _c2 && _c3 { + return Api.SendMessageAction.sendMessageEmojiInteraction(Cons_sendMessageEmojiInteraction(emoticon: _1!, msgId: _2!, interaction: _3!)) + } + else { + return nil + } } public static func parse_sendMessageEmojiInteractionSeen(_ reader: BufferReader) -> SendMessageAction? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.SendMessageAction.sendMessageEmojiInteractionSeen(emoticon: _1!) + if _c1 { + return Api.SendMessageAction.sendMessageEmojiInteractionSeen(Cons_sendMessageEmojiInteractionSeen(emoticon: _1!)) + } + else { + return nil + } } public static func parse_sendMessageGamePlayAction(_ reader: BufferReader) -> SendMessageAction? { return Api.SendMessageAction.sendMessageGamePlayAction @@ -1017,8 +1283,12 @@ public extension Api { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.SendMessageAction.sendMessageHistoryImportAction(progress: _1!) + if _c1 { + return Api.SendMessageAction.sendMessageHistoryImportAction(Cons_sendMessageHistoryImportAction(progress: _1!)) + } + else { + return nil + } } public static func parse_sendMessageRecordAudioAction(_ reader: BufferReader) -> SendMessageAction? { return Api.SendMessageAction.sendMessageRecordAudioAction @@ -1038,9 +1308,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.SendMessageAction.sendMessageTextDraftAction(randomId: _1!, text: _2!) + if _c1 && _c2 { + return Api.SendMessageAction.sendMessageTextDraftAction(Cons_sendMessageTextDraftAction(randomId: _1!, text: _2!)) + } + else { + return nil + } } public static func parse_sendMessageTypingAction(_ reader: BufferReader) -> SendMessageAction? { return Api.SendMessageAction.sendMessageTypingAction @@ -1049,40 +1322,59 @@ public extension Api { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.SendMessageAction.sendMessageUploadAudioAction(progress: _1!) + if _c1 { + return Api.SendMessageAction.sendMessageUploadAudioAction(Cons_sendMessageUploadAudioAction(progress: _1!)) + } + else { + return nil + } } public static func parse_sendMessageUploadDocumentAction(_ reader: BufferReader) -> SendMessageAction? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.SendMessageAction.sendMessageUploadDocumentAction(progress: _1!) + if _c1 { + return Api.SendMessageAction.sendMessageUploadDocumentAction(Cons_sendMessageUploadDocumentAction(progress: _1!)) + } + else { + return nil + } } public static func parse_sendMessageUploadPhotoAction(_ reader: BufferReader) -> SendMessageAction? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.SendMessageAction.sendMessageUploadPhotoAction(progress: _1!) + if _c1 { + return Api.SendMessageAction.sendMessageUploadPhotoAction(Cons_sendMessageUploadPhotoAction(progress: _1!)) + } + else { + return nil + } } public static func parse_sendMessageUploadRoundAction(_ reader: BufferReader) -> SendMessageAction? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.SendMessageAction.sendMessageUploadRoundAction(progress: _1!) + if _c1 { + return Api.SendMessageAction.sendMessageUploadRoundAction(Cons_sendMessageUploadRoundAction(progress: _1!)) + } + else { + return nil + } } public static func parse_sendMessageUploadVideoAction(_ reader: BufferReader) -> SendMessageAction? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.SendMessageAction.sendMessageUploadVideoAction(progress: _1!) + if _c1 { + return Api.SendMessageAction.sendMessageUploadVideoAction(Cons_sendMessageUploadVideoAction(progress: _1!)) + } + else { + return nil + } } public static func parse_speakingInGroupCallAction(_ reader: BufferReader) -> SendMessageAction? { return Api.SendMessageAction.speakingInGroupCallAction } - } } diff --git a/submodules/TelegramApi/Sources/Api25.swift b/submodules/TelegramApi/Sources/Api25.swift index 08d8aafe..6193057a 100644 --- a/submodules/TelegramApi/Sources/Api25.swift +++ b/submodules/TelegramApi/Sources/Api25.swift @@ -1,31 +1,41 @@ public extension Api { enum ShippingOption: TypeConstructorDescription { - case shippingOption(id: String, title: String, prices: [Api.LabeledPrice]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .shippingOption(let id, let title, let prices): - if boxed { - buffer.appendInt32(-1239335713) - } - serializeString(id, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(prices.count)) - for item in prices { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .shippingOption(let id, let title, let prices): - return ("shippingOption", [("id", id as Any), ("title", title as Any), ("prices", prices as Any)]) - } - } - + public class Cons_shippingOption { + public var id: String + public var title: String + public var prices: [Api.LabeledPrice] + public init(id: String, title: String, prices: [Api.LabeledPrice]) { + self.id = id + self.title = title + self.prices = prices + } + } + case shippingOption(Cons_shippingOption) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .shippingOption(let _data): + if boxed { + buffer.appendInt32(-1239335713) + } + serializeString(_data.id, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.prices.count)) + for item in _data.prices { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .shippingOption(let _data): + return ("shippingOption", [("id", _data.id as Any), ("title", _data.title as Any), ("prices", _data.prices as Any)]) + } + } + public static func parse_shippingOption(_ reader: BufferReader) -> ShippingOption? { var _1: String? _1 = parseString(reader) @@ -38,38 +48,49 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.ShippingOption.shippingOption(id: _1!, title: _2!, prices: _3!) + if _c1 && _c2 && _c3 { + return Api.ShippingOption.shippingOption(Cons_shippingOption(id: _1!, title: _2!, prices: _3!)) + } + else { + return nil + } } - } } public extension Api { enum SmsJob: TypeConstructorDescription { - case smsJob(jobId: String, phoneNumber: String, text: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .smsJob(let jobId, let phoneNumber, let text): - if boxed { - buffer.appendInt32(-425595208) - } - serializeString(jobId, buffer: buffer, boxed: false) - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .smsJob(let jobId, let phoneNumber, let text): - return ("smsJob", [("jobId", jobId as Any), ("phoneNumber", phoneNumber as Any), ("text", text as Any)]) - } - } - + public class Cons_smsJob { + public var jobId: String + public var phoneNumber: String + public var text: String + public init(jobId: String, phoneNumber: String, text: String) { + self.jobId = jobId + self.phoneNumber = phoneNumber + self.text = text + } + } + case smsJob(Cons_smsJob) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .smsJob(let _data): + if boxed { + buffer.appendInt32(-425595208) + } + serializeString(_data.jobId, buffer: buffer, boxed: false) + serializeString(_data.phoneNumber, buffer: buffer, boxed: false) + serializeString(_data.text, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .smsJob(let _data): + return ("smsJob", [("jobId", _data.jobId as Any), ("phoneNumber", _data.phoneNumber as Any), ("text", _data.text as Any)]) + } + } + public static func parse_smsJob(_ reader: BufferReader) -> SmsJob? { var _1: String? _1 = parseString(reader) @@ -80,53 +101,102 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SmsJob.smsJob(jobId: _1!, phoneNumber: _2!, text: _3!) + if _c1 && _c2 && _c3 { + return Api.SmsJob.smsJob(Cons_smsJob(jobId: _1!, phoneNumber: _2!, text: _3!)) + } + else { + return nil + } } - } } public extension Api { indirect enum SponsoredMessage: TypeConstructorDescription { - case sponsoredMessage(flags: Int32, randomId: Buffer, url: String, title: String, message: String, entities: [Api.MessageEntity]?, photo: Api.Photo?, media: Api.MessageMedia?, color: Api.PeerColor?, buttonText: String, sponsorInfo: String?, additionalInfo: String?, minDisplayDuration: Int32?, maxDisplayDuration: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .sponsoredMessage(let flags, let randomId, let url, let title, let message, let entities, let photo, let media, let color, let buttonText, let sponsorInfo, let additionalInfo, let minDisplayDuration, let maxDisplayDuration): - if boxed { - buffer.appendInt32(2109703795) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeBytes(randomId, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { + public class Cons_sponsoredMessage { + public var flags: Int32 + public var randomId: Buffer + public var url: String + public var title: String + public var message: String + public var entities: [Api.MessageEntity]? + public var photo: Api.Photo? + public var media: Api.MessageMedia? + public var color: Api.PeerColor? + public var buttonText: String + public var sponsorInfo: String? + public var additionalInfo: String? + public var minDisplayDuration: Int32? + public var maxDisplayDuration: Int32? + public init(flags: Int32, randomId: Buffer, url: String, title: String, message: String, entities: [Api.MessageEntity]?, photo: Api.Photo?, media: Api.MessageMedia?, color: Api.PeerColor?, buttonText: String, sponsorInfo: String?, additionalInfo: String?, minDisplayDuration: Int32?, maxDisplayDuration: Int32?) { + self.flags = flags + self.randomId = randomId + self.url = url + self.title = title + self.message = message + self.entities = entities + self.photo = photo + self.media = media + self.color = color + self.buttonText = buttonText + self.sponsorInfo = sponsorInfo + self.additionalInfo = additionalInfo + self.minDisplayDuration = minDisplayDuration + self.maxDisplayDuration = maxDisplayDuration + } + } + case sponsoredMessage(Cons_sponsoredMessage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .sponsoredMessage(let _data): + if boxed { + buffer.appendInt32(2109703795) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeBytes(_data.randomId, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.message, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 6) != 0 {photo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 14) != 0 {media!.serialize(buffer, true)} - if Int(flags) & Int(1 << 13) != 0 {color!.serialize(buffer, true)} - serializeString(buttonText, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 7) != 0 {serializeString(sponsorInfo!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {serializeString(additionalInfo!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 15) != 0 {serializeInt32(minDisplayDuration!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 15) != 0 {serializeInt32(maxDisplayDuration!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .sponsoredMessage(let flags, let randomId, let url, let title, let message, let entities, let photo, let media, let color, let buttonText, let sponsorInfo, let additionalInfo, let minDisplayDuration, let maxDisplayDuration): - return ("sponsoredMessage", [("flags", flags as Any), ("randomId", randomId as Any), ("url", url as Any), ("title", title as Any), ("message", message as Any), ("entities", entities as Any), ("photo", photo as Any), ("media", media as Any), ("color", color as Any), ("buttonText", buttonText as Any), ("sponsorInfo", sponsorInfo as Any), ("additionalInfo", additionalInfo as Any), ("minDisplayDuration", minDisplayDuration as Any), ("maxDisplayDuration", maxDisplayDuration as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 6) != 0 { + _data.photo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 14) != 0 { + _data.media!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 13) != 0 { + _data.color!.serialize(buffer, true) + } + serializeString(_data.buttonText, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 7) != 0 { + serializeString(_data.sponsorInfo!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + serializeString(_data.additionalInfo!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 15) != 0 { + serializeInt32(_data.minDisplayDuration!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 15) != 0 { + serializeInt32(_data.maxDisplayDuration!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .sponsoredMessage(let _data): + return ("sponsoredMessage", [("flags", _data.flags as Any), ("randomId", _data.randomId as Any), ("url", _data.url as Any), ("title", _data.title as Any), ("message", _data.message as Any), ("entities", _data.entities as Any), ("photo", _data.photo as Any), ("media", _data.media as Any), ("color", _data.color as Any), ("buttonText", _data.buttonText as Any), ("sponsorInfo", _data.sponsorInfo as Any), ("additionalInfo", _data.additionalInfo as Any), ("minDisplayDuration", _data.minDisplayDuration as Any), ("maxDisplayDuration", _data.maxDisplayDuration as Any)]) + } + } + public static func parse_sponsoredMessage(_ reader: BufferReader) -> SponsoredMessage? { var _1: Int32? _1 = reader.readInt32() @@ -139,31 +209,47 @@ public extension Api { var _5: String? _5 = parseString(reader) var _6: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } var _7: Api.Photo? - if Int(_1!) & Int(1 << 6) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.Photo - } } + if Int(_1!) & Int(1 << 6) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.Photo + } + } var _8: Api.MessageMedia? - if Int(_1!) & Int(1 << 14) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.MessageMedia - } } + if Int(_1!) & Int(1 << 14) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.MessageMedia + } + } var _9: Api.PeerColor? - if Int(_1!) & Int(1 << 13) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.PeerColor - } } + if Int(_1!) & Int(1 << 13) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.PeerColor + } + } var _10: String? _10 = parseString(reader) var _11: String? - if Int(_1!) & Int(1 << 7) != 0 {_11 = parseString(reader) } + if Int(_1!) & Int(1 << 7) != 0 { + _11 = parseString(reader) + } var _12: String? - if Int(_1!) & Int(1 << 8) != 0 {_12 = parseString(reader) } + if Int(_1!) & Int(1 << 8) != 0 { + _12 = parseString(reader) + } var _13: Int32? - if Int(_1!) & Int(1 << 15) != 0 {_13 = reader.readInt32() } + if Int(_1!) & Int(1 << 15) != 0 { + _13 = reader.readInt32() + } var _14: Int32? - if Int(_1!) & Int(1 << 15) != 0 {_14 = reader.readInt32() } + if Int(_1!) & Int(1 << 15) != 0 { + _14 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -178,48 +264,46 @@ public extension Api { let _c12 = (Int(_1!) & Int(1 << 8) == 0) || _12 != nil let _c13 = (Int(_1!) & Int(1 << 15) == 0) || _13 != nil let _c14 = (Int(_1!) & Int(1 << 15) == 0) || _14 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - return Api.SponsoredMessage.sponsoredMessage(flags: _1!, randomId: _2!, url: _3!, title: _4!, message: _5!, entities: _6, photo: _7, media: _8, color: _9, buttonText: _10!, sponsorInfo: _11, additionalInfo: _12, minDisplayDuration: _13, maxDisplayDuration: _14) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 { + return Api.SponsoredMessage.sponsoredMessage(Cons_sponsoredMessage(flags: _1!, randomId: _2!, url: _3!, title: _4!, message: _5!, entities: _6, photo: _7, media: _8, color: _9, buttonText: _10!, sponsorInfo: _11, additionalInfo: _12, minDisplayDuration: _13, maxDisplayDuration: _14)) + } + else { + return nil + } } - } } public extension Api { enum SponsoredMessageReportOption: TypeConstructorDescription { - case sponsoredMessageReportOption(text: String, option: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .sponsoredMessageReportOption(let text, let option): - if boxed { - buffer.appendInt32(1124938064) - } - serializeString(text, buffer: buffer, boxed: false) - serializeBytes(option, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .sponsoredMessageReportOption(let text, let option): - return ("sponsoredMessageReportOption", [("text", text as Any), ("option", option as Any)]) - } - } - + public class Cons_sponsoredMessageReportOption { + public var text: String + public var option: Buffer + public init(text: String, option: Buffer) { + self.text = text + self.option = option + } + } + case sponsoredMessageReportOption(Cons_sponsoredMessageReportOption) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .sponsoredMessageReportOption(let _data): + if boxed { + buffer.appendInt32(1124938064) + } + serializeString(_data.text, buffer: buffer, boxed: false) + serializeBytes(_data.option, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .sponsoredMessageReportOption(let _data): + return ("sponsoredMessageReportOption", [("text", _data.text as Any), ("option", _data.option as Any)]) + } + } + public static func parse_sponsoredMessageReportOption(_ reader: BufferReader) -> SponsoredMessageReportOption? { var _1: String? _1 = parseString(reader) @@ -227,39 +311,59 @@ public extension Api { _2 = parseBytes(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.SponsoredMessageReportOption.sponsoredMessageReportOption(text: _1!, option: _2!) + if _c1 && _c2 { + return Api.SponsoredMessageReportOption.sponsoredMessageReportOption(Cons_sponsoredMessageReportOption(text: _1!, option: _2!)) + } + else { + return nil + } } - } } public extension Api { enum SponsoredPeer: TypeConstructorDescription { - case sponsoredPeer(flags: Int32, randomId: Buffer, peer: Api.Peer, sponsorInfo: String?, additionalInfo: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .sponsoredPeer(let flags, let randomId, let peer, let sponsorInfo, let additionalInfo): - if boxed { - buffer.appendInt32(-963180333) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeBytes(randomId, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeString(sponsorInfo!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(additionalInfo!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .sponsoredPeer(let flags, let randomId, let peer, let sponsorInfo, let additionalInfo): - return ("sponsoredPeer", [("flags", flags as Any), ("randomId", randomId as Any), ("peer", peer as Any), ("sponsorInfo", sponsorInfo as Any), ("additionalInfo", additionalInfo as Any)]) - } - } - + public class Cons_sponsoredPeer { + public var flags: Int32 + public var randomId: Buffer + public var peer: Api.Peer + public var sponsorInfo: String? + public var additionalInfo: String? + public init(flags: Int32, randomId: Buffer, peer: Api.Peer, sponsorInfo: String?, additionalInfo: String?) { + self.flags = flags + self.randomId = randomId + self.peer = peer + self.sponsorInfo = sponsorInfo + self.additionalInfo = additionalInfo + } + } + case sponsoredPeer(Cons_sponsoredPeer) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .sponsoredPeer(let _data): + if boxed { + buffer.appendInt32(-963180333) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeBytes(_data.randomId, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.sponsorInfo!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.additionalInfo!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .sponsoredPeer(let _data): + return ("sponsoredPeer", [("flags", _data.flags as Any), ("randomId", _data.randomId as Any), ("peer", _data.peer as Any), ("sponsorInfo", _data.sponsorInfo as Any), ("additionalInfo", _data.additionalInfo as Any)]) + } + } + public static func parse_sponsoredPeer(_ reader: BufferReader) -> SponsoredPeer? { var _1: Int32? _1 = reader.readInt32() @@ -270,105 +374,269 @@ public extension Api { _3 = Api.parse(reader, signature: signature) as? Api.Peer } var _4: String? - if Int(_1!) & Int(1 << 0) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) + } var _5: String? - if Int(_1!) & Int(1 << 1) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _5 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.SponsoredPeer.sponsoredPeer(flags: _1!, randomId: _2!, peer: _3!, sponsorInfo: _4, additionalInfo: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.SponsoredPeer.sponsoredPeer(Cons_sponsoredPeer(flags: _1!, randomId: _2!, peer: _3!, sponsorInfo: _4, additionalInfo: _5)) + } + else { + return nil + } } - } } public extension Api { enum StarGift: TypeConstructorDescription { - case starGift(flags: Int32, id: Int64, sticker: Api.Document, stars: Int64, availabilityRemains: Int32?, availabilityTotal: Int32?, availabilityResale: Int64?, convertStars: Int64, firstSaleDate: Int32?, lastSaleDate: Int32?, upgradeStars: Int64?, resellMinStars: Int64?, title: String?, releasedBy: Api.Peer?, perUserTotal: Int32?, perUserRemains: Int32?, lockedUntilDate: Int32?, auctionSlug: String?, giftsPerRound: Int32?, auctionStartDate: Int32?, upgradeVariants: Int32?, background: Api.StarGiftBackground?) - case starGiftUnique(flags: Int32, id: Int64, giftId: Int64, title: String, slug: String, num: Int32, ownerId: Api.Peer?, ownerName: String?, ownerAddress: String?, attributes: [Api.StarGiftAttribute], availabilityIssued: Int32, availabilityTotal: Int32, giftAddress: String?, resellAmount: [Api.StarsAmount]?, releasedBy: Api.Peer?, valueAmount: Int64?, valueCurrency: String?, valueUsdAmount: Int64?, themePeer: Api.Peer?, peerColor: Api.PeerColor?, hostId: Api.Peer?, offerMinStars: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGift(let flags, let id, let sticker, let stars, let availabilityRemains, let availabilityTotal, let availabilityResale, let convertStars, let firstSaleDate, let lastSaleDate, let upgradeStars, let resellMinStars, let title, let releasedBy, let perUserTotal, let perUserRemains, let lockedUntilDate, let auctionSlug, let giftsPerRound, let auctionStartDate, let upgradeVariants, let background): - if boxed { - buffer.appendInt32(825922887) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - sticker.serialize(buffer, true) - serializeInt64(stars, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(availabilityRemains!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(availabilityTotal!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt64(availabilityResale!, buffer: buffer, boxed: false)} - serializeInt64(convertStars, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(firstSaleDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(lastSaleDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt64(upgradeStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt64(resellMinStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 6) != 0 {releasedBy!.serialize(buffer, true)} - if Int(flags) & Int(1 << 8) != 0 {serializeInt32(perUserTotal!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {serializeInt32(perUserRemains!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 9) != 0 {serializeInt32(lockedUntilDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 11) != 0 {serializeString(auctionSlug!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 11) != 0 {serializeInt32(giftsPerRound!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 11) != 0 {serializeInt32(auctionStartDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 12) != 0 {serializeInt32(upgradeVariants!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 13) != 0 {background!.serialize(buffer, true)} - break - case .starGiftUnique(let flags, let id, let giftId, let title, let slug, let num, let ownerId, let ownerName, let ownerAddress, let attributes, let availabilityIssued, let availabilityTotal, let giftAddress, let resellAmount, let releasedBy, let valueAmount, let valueCurrency, let valueUsdAmount, let themePeer, let peerColor, let hostId, let offerMinStars): - if boxed { - buffer.appendInt32(1453155529) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(giftId, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(slug, buffer: buffer, boxed: false) - serializeInt32(num, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {ownerId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(ownerName!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(ownerAddress!, buffer: buffer, boxed: false)} + public class Cons_starGift { + public var flags: Int32 + public var id: Int64 + public var sticker: Api.Document + public var stars: Int64 + public var availabilityRemains: Int32? + public var availabilityTotal: Int32? + public var availabilityResale: Int64? + public var convertStars: Int64 + public var firstSaleDate: Int32? + public var lastSaleDate: Int32? + public var upgradeStars: Int64? + public var resellMinStars: Int64? + public var title: String? + public var releasedBy: Api.Peer? + public var perUserTotal: Int32? + public var perUserRemains: Int32? + public var lockedUntilDate: Int32? + public var auctionSlug: String? + public var giftsPerRound: Int32? + public var auctionStartDate: Int32? + public var upgradeVariants: Int32? + public var background: Api.StarGiftBackground? + public init(flags: Int32, id: Int64, sticker: Api.Document, stars: Int64, availabilityRemains: Int32?, availabilityTotal: Int32?, availabilityResale: Int64?, convertStars: Int64, firstSaleDate: Int32?, lastSaleDate: Int32?, upgradeStars: Int64?, resellMinStars: Int64?, title: String?, releasedBy: Api.Peer?, perUserTotal: Int32?, perUserRemains: Int32?, lockedUntilDate: Int32?, auctionSlug: String?, giftsPerRound: Int32?, auctionStartDate: Int32?, upgradeVariants: Int32?, background: Api.StarGiftBackground?) { + self.flags = flags + self.id = id + self.sticker = sticker + self.stars = stars + self.availabilityRemains = availabilityRemains + self.availabilityTotal = availabilityTotal + self.availabilityResale = availabilityResale + self.convertStars = convertStars + self.firstSaleDate = firstSaleDate + self.lastSaleDate = lastSaleDate + self.upgradeStars = upgradeStars + self.resellMinStars = resellMinStars + self.title = title + self.releasedBy = releasedBy + self.perUserTotal = perUserTotal + self.perUserRemains = perUserRemains + self.lockedUntilDate = lockedUntilDate + self.auctionSlug = auctionSlug + self.giftsPerRound = giftsPerRound + self.auctionStartDate = auctionStartDate + self.upgradeVariants = upgradeVariants + self.background = background + } + } + public class Cons_starGiftUnique { + public var flags: Int32 + public var id: Int64 + public var giftId: Int64 + public var title: String + public var slug: String + public var num: Int32 + public var ownerId: Api.Peer? + public var ownerName: String? + public var ownerAddress: String? + public var attributes: [Api.StarGiftAttribute] + public var availabilityIssued: Int32 + public var availabilityTotal: Int32 + public var giftAddress: String? + public var resellAmount: [Api.StarsAmount]? + public var releasedBy: Api.Peer? + public var valueAmount: Int64? + public var valueCurrency: String? + public var valueUsdAmount: Int64? + public var themePeer: Api.Peer? + public var peerColor: Api.PeerColor? + public var hostId: Api.Peer? + public var offerMinStars: Int32? + public var craftChancePermille: Int32? + public init(flags: Int32, id: Int64, giftId: Int64, title: String, slug: String, num: Int32, ownerId: Api.Peer?, ownerName: String?, ownerAddress: String?, attributes: [Api.StarGiftAttribute], availabilityIssued: Int32, availabilityTotal: Int32, giftAddress: String?, resellAmount: [Api.StarsAmount]?, releasedBy: Api.Peer?, valueAmount: Int64?, valueCurrency: String?, valueUsdAmount: Int64?, themePeer: Api.Peer?, peerColor: Api.PeerColor?, hostId: Api.Peer?, offerMinStars: Int32?, craftChancePermille: Int32?) { + self.flags = flags + self.id = id + self.giftId = giftId + self.title = title + self.slug = slug + self.num = num + self.ownerId = ownerId + self.ownerName = ownerName + self.ownerAddress = ownerAddress + self.attributes = attributes + self.availabilityIssued = availabilityIssued + self.availabilityTotal = availabilityTotal + self.giftAddress = giftAddress + self.resellAmount = resellAmount + self.releasedBy = releasedBy + self.valueAmount = valueAmount + self.valueCurrency = valueCurrency + self.valueUsdAmount = valueUsdAmount + self.themePeer = themePeer + self.peerColor = peerColor + self.hostId = hostId + self.offerMinStars = offerMinStars + self.craftChancePermille = craftChancePermille + } + } + case starGift(Cons_starGift) + case starGiftUnique(Cons_starGiftUnique) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGift(let _data): + if boxed { + buffer.appendInt32(825922887) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + _data.sticker.serialize(buffer, true) + serializeInt64(_data.stars, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.availabilityRemains!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.availabilityTotal!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt64(_data.availabilityResale!, buffer: buffer, boxed: false) + } + serializeInt64(_data.convertStars, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.firstSaleDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.lastSaleDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt64(_data.upgradeStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt64(_data.resellMinStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + _data.releasedBy!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + serializeInt32(_data.perUserTotal!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + serializeInt32(_data.perUserRemains!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 9) != 0 { + serializeInt32(_data.lockedUntilDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 11) != 0 { + serializeString(_data.auctionSlug!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 11) != 0 { + serializeInt32(_data.giftsPerRound!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 11) != 0 { + serializeInt32(_data.auctionStartDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 12) != 0 { + serializeInt32(_data.upgradeVariants!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 13) != 0 { + _data.background!.serialize(buffer, true) + } + break + case .starGiftUnique(let _data): + if boxed { + buffer.appendInt32(-2047825459) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.giftId, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.slug, buffer: buffer, boxed: false) + serializeInt32(_data.num, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.ownerId!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.ownerName!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.ownerAddress!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.attributes.count)) + for item in _data.attributes { + item.serialize(buffer, true) + } + serializeInt32(_data.availabilityIssued, buffer: buffer, boxed: false) + serializeInt32(_data.availabilityTotal, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.giftAddress!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(attributes.count)) - for item in attributes { + buffer.appendInt32(Int32(_data.resellAmount!.count)) + for item in _data.resellAmount! { item.serialize(buffer, true) } - serializeInt32(availabilityIssued, buffer: buffer, boxed: false) - serializeInt32(availabilityTotal, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {serializeString(giftAddress!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(resellAmount!.count)) - for item in resellAmount! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 5) != 0 {releasedBy!.serialize(buffer, true)} - if Int(flags) & Int(1 << 8) != 0 {serializeInt64(valueAmount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {serializeString(valueCurrency!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {serializeInt64(valueUsdAmount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 10) != 0 {themePeer!.serialize(buffer, true)} - if Int(flags) & Int(1 << 11) != 0 {peerColor!.serialize(buffer, true)} - if Int(flags) & Int(1 << 12) != 0 {hostId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 13) != 0 {serializeInt32(offerMinStars!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGift(let flags, let id, let sticker, let stars, let availabilityRemains, let availabilityTotal, let availabilityResale, let convertStars, let firstSaleDate, let lastSaleDate, let upgradeStars, let resellMinStars, let title, let releasedBy, let perUserTotal, let perUserRemains, let lockedUntilDate, let auctionSlug, let giftsPerRound, let auctionStartDate, let upgradeVariants, let background): - return ("starGift", [("flags", flags as Any), ("id", id as Any), ("sticker", sticker as Any), ("stars", stars as Any), ("availabilityRemains", availabilityRemains as Any), ("availabilityTotal", availabilityTotal as Any), ("availabilityResale", availabilityResale as Any), ("convertStars", convertStars as Any), ("firstSaleDate", firstSaleDate as Any), ("lastSaleDate", lastSaleDate as Any), ("upgradeStars", upgradeStars as Any), ("resellMinStars", resellMinStars as Any), ("title", title as Any), ("releasedBy", releasedBy as Any), ("perUserTotal", perUserTotal as Any), ("perUserRemains", perUserRemains as Any), ("lockedUntilDate", lockedUntilDate as Any), ("auctionSlug", auctionSlug as Any), ("giftsPerRound", giftsPerRound as Any), ("auctionStartDate", auctionStartDate as Any), ("upgradeVariants", upgradeVariants as Any), ("background", background as Any)]) - case .starGiftUnique(let flags, let id, let giftId, let title, let slug, let num, let ownerId, let ownerName, let ownerAddress, let attributes, let availabilityIssued, let availabilityTotal, let giftAddress, let resellAmount, let releasedBy, let valueAmount, let valueCurrency, let valueUsdAmount, let themePeer, let peerColor, let hostId, let offerMinStars): - return ("starGiftUnique", [("flags", flags as Any), ("id", id as Any), ("giftId", giftId as Any), ("title", title as Any), ("slug", slug as Any), ("num", num as Any), ("ownerId", ownerId as Any), ("ownerName", ownerName as Any), ("ownerAddress", ownerAddress as Any), ("attributes", attributes as Any), ("availabilityIssued", availabilityIssued as Any), ("availabilityTotal", availabilityTotal as Any), ("giftAddress", giftAddress as Any), ("resellAmount", resellAmount as Any), ("releasedBy", releasedBy as Any), ("valueAmount", valueAmount as Any), ("valueCurrency", valueCurrency as Any), ("valueUsdAmount", valueUsdAmount as Any), ("themePeer", themePeer as Any), ("peerColor", peerColor as Any), ("hostId", hostId as Any), ("offerMinStars", offerMinStars as Any)]) - } - } - + } + if Int(_data.flags) & Int(1 << 5) != 0 { + _data.releasedBy!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + serializeInt64(_data.valueAmount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + serializeString(_data.valueCurrency!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + serializeInt64(_data.valueUsdAmount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.themePeer!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 11) != 0 { + _data.peerColor!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 12) != 0 { + _data.hostId!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 13) != 0 { + serializeInt32(_data.offerMinStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 16) != 0 { + serializeInt32(_data.craftChancePermille!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGift(let _data): + return ("starGift", [("flags", _data.flags as Any), ("id", _data.id as Any), ("sticker", _data.sticker as Any), ("stars", _data.stars as Any), ("availabilityRemains", _data.availabilityRemains as Any), ("availabilityTotal", _data.availabilityTotal as Any), ("availabilityResale", _data.availabilityResale as Any), ("convertStars", _data.convertStars as Any), ("firstSaleDate", _data.firstSaleDate as Any), ("lastSaleDate", _data.lastSaleDate as Any), ("upgradeStars", _data.upgradeStars as Any), ("resellMinStars", _data.resellMinStars as Any), ("title", _data.title as Any), ("releasedBy", _data.releasedBy as Any), ("perUserTotal", _data.perUserTotal as Any), ("perUserRemains", _data.perUserRemains as Any), ("lockedUntilDate", _data.lockedUntilDate as Any), ("auctionSlug", _data.auctionSlug as Any), ("giftsPerRound", _data.giftsPerRound as Any), ("auctionStartDate", _data.auctionStartDate as Any), ("upgradeVariants", _data.upgradeVariants as Any), ("background", _data.background as Any)]) + case .starGiftUnique(let _data): + return ("starGiftUnique", [("flags", _data.flags as Any), ("id", _data.id as Any), ("giftId", _data.giftId as Any), ("title", _data.title as Any), ("slug", _data.slug as Any), ("num", _data.num as Any), ("ownerId", _data.ownerId as Any), ("ownerName", _data.ownerName as Any), ("ownerAddress", _data.ownerAddress as Any), ("attributes", _data.attributes as Any), ("availabilityIssued", _data.availabilityIssued as Any), ("availabilityTotal", _data.availabilityTotal as Any), ("giftAddress", _data.giftAddress as Any), ("resellAmount", _data.resellAmount as Any), ("releasedBy", _data.releasedBy as Any), ("valueAmount", _data.valueAmount as Any), ("valueCurrency", _data.valueCurrency as Any), ("valueUsdAmount", _data.valueUsdAmount as Any), ("themePeer", _data.themePeer as Any), ("peerColor", _data.peerColor as Any), ("hostId", _data.hostId as Any), ("offerMinStars", _data.offerMinStars as Any), ("craftChancePermille", _data.craftChancePermille as Any)]) + } + } + public static func parse_starGift(_ reader: BufferReader) -> StarGift? { var _1: Int32? _1 = reader.readInt32() @@ -381,45 +649,79 @@ public extension Api { var _4: Int64? _4 = reader.readInt64() var _5: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _5 = reader.readInt32() + } var _6: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _6 = reader.readInt32() + } var _7: Int64? - if Int(_1!) & Int(1 << 4) != 0 {_7 = reader.readInt64() } + if Int(_1!) & Int(1 << 4) != 0 { + _7 = reader.readInt64() + } var _8: Int64? _8 = reader.readInt64() var _9: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_9 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _9 = reader.readInt32() + } var _10: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_10 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _10 = reader.readInt32() + } var _11: Int64? - if Int(_1!) & Int(1 << 3) != 0 {_11 = reader.readInt64() } + if Int(_1!) & Int(1 << 3) != 0 { + _11 = reader.readInt64() + } var _12: Int64? - if Int(_1!) & Int(1 << 4) != 0 {_12 = reader.readInt64() } + if Int(_1!) & Int(1 << 4) != 0 { + _12 = reader.readInt64() + } var _13: String? - if Int(_1!) & Int(1 << 5) != 0 {_13 = parseString(reader) } + if Int(_1!) & Int(1 << 5) != 0 { + _13 = parseString(reader) + } var _14: Api.Peer? - if Int(_1!) & Int(1 << 6) != 0 {if let signature = reader.readInt32() { - _14 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 6) != 0 { + if let signature = reader.readInt32() { + _14 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _15: Int32? - if Int(_1!) & Int(1 << 8) != 0 {_15 = reader.readInt32() } + if Int(_1!) & Int(1 << 8) != 0 { + _15 = reader.readInt32() + } var _16: Int32? - if Int(_1!) & Int(1 << 8) != 0 {_16 = reader.readInt32() } + if Int(_1!) & Int(1 << 8) != 0 { + _16 = reader.readInt32() + } var _17: Int32? - if Int(_1!) & Int(1 << 9) != 0 {_17 = reader.readInt32() } + if Int(_1!) & Int(1 << 9) != 0 { + _17 = reader.readInt32() + } var _18: String? - if Int(_1!) & Int(1 << 11) != 0 {_18 = parseString(reader) } + if Int(_1!) & Int(1 << 11) != 0 { + _18 = parseString(reader) + } var _19: Int32? - if Int(_1!) & Int(1 << 11) != 0 {_19 = reader.readInt32() } + if Int(_1!) & Int(1 << 11) != 0 { + _19 = reader.readInt32() + } var _20: Int32? - if Int(_1!) & Int(1 << 11) != 0 {_20 = reader.readInt32() } + if Int(_1!) & Int(1 << 11) != 0 { + _20 = reader.readInt32() + } var _21: Int32? - if Int(_1!) & Int(1 << 12) != 0 {_21 = reader.readInt32() } + if Int(_1!) & Int(1 << 12) != 0 { + _21 = reader.readInt32() + } var _22: Api.StarGiftBackground? - if Int(_1!) & Int(1 << 13) != 0 {if let signature = reader.readInt32() { - _22 = Api.parse(reader, signature: signature) as? Api.StarGiftBackground - } } + if Int(_1!) & Int(1 << 13) != 0 { + if let signature = reader.readInt32() { + _22 = Api.parse(reader, signature: signature) as? Api.StarGiftBackground + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -442,29 +744,12 @@ public extension Api { let _c20 = (Int(_1!) & Int(1 << 11) == 0) || _20 != nil let _c21 = (Int(_1!) & Int(1 << 12) == 0) || _21 != nil let _c22 = (Int(_1!) & Int(1 << 13) == 0) || _22 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - if !_c16 { return nil } - if !_c17 { return nil } - if !_c18 { return nil } - if !_c19 { return nil } - if !_c20 { return nil } - if !_c21 { return nil } - if !_c22 { return nil } - return Api.StarGift.starGift(flags: _1!, id: _2!, sticker: _3!, stars: _4!, availabilityRemains: _5, availabilityTotal: _6, availabilityResale: _7, convertStars: _8!, firstSaleDate: _9, lastSaleDate: _10, upgradeStars: _11, resellMinStars: _12, title: _13, releasedBy: _14, perUserTotal: _15, perUserRemains: _16, lockedUntilDate: _17, auctionSlug: _18, giftsPerRound: _19, auctionStartDate: _20, upgradeVariants: _21, background: _22) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 && _c18 && _c19 && _c20 && _c21 && _c22 { + return Api.StarGift.starGift(Cons_starGift(flags: _1!, id: _2!, sticker: _3!, stars: _4!, availabilityRemains: _5, availabilityTotal: _6, availabilityResale: _7, convertStars: _8!, firstSaleDate: _9, lastSaleDate: _10, upgradeStars: _11, resellMinStars: _12, title: _13, releasedBy: _14, perUserTotal: _15, perUserRemains: _16, lockedUntilDate: _17, auctionSlug: _18, giftsPerRound: _19, auctionStartDate: _20, upgradeVariants: _21, background: _22)) + } + else { + return nil + } } public static func parse_starGiftUnique(_ reader: BufferReader) -> StarGift? { var _1: Int32? @@ -480,13 +765,19 @@ public extension Api { var _6: Int32? _6 = reader.readInt32() var _7: Api.Peer? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _8: String? - if Int(_1!) & Int(1 << 1) != 0 {_8 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _8 = parseString(reader) + } var _9: String? - if Int(_1!) & Int(1 << 2) != 0 {_9 = parseString(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _9 = parseString(reader) + } var _10: [Api.StarGiftAttribute]? if let _ = reader.readInt32() { _10 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftAttribute.self) @@ -496,35 +787,59 @@ public extension Api { var _12: Int32? _12 = reader.readInt32() var _13: String? - if Int(_1!) & Int(1 << 3) != 0 {_13 = parseString(reader) } + if Int(_1!) & Int(1 << 3) != 0 { + _13 = parseString(reader) + } var _14: [Api.StarsAmount]? - if Int(_1!) & Int(1 << 4) != 0 {if let _ = reader.readInt32() { - _14 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarsAmount.self) - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let _ = reader.readInt32() { + _14 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarsAmount.self) + } + } var _15: Api.Peer? - if Int(_1!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _15 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _15 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _16: Int64? - if Int(_1!) & Int(1 << 8) != 0 {_16 = reader.readInt64() } + if Int(_1!) & Int(1 << 8) != 0 { + _16 = reader.readInt64() + } var _17: String? - if Int(_1!) & Int(1 << 8) != 0 {_17 = parseString(reader) } + if Int(_1!) & Int(1 << 8) != 0 { + _17 = parseString(reader) + } var _18: Int64? - if Int(_1!) & Int(1 << 8) != 0 {_18 = reader.readInt64() } + if Int(_1!) & Int(1 << 8) != 0 { + _18 = reader.readInt64() + } var _19: Api.Peer? - if Int(_1!) & Int(1 << 10) != 0 {if let signature = reader.readInt32() { - _19 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _19 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _20: Api.PeerColor? - if Int(_1!) & Int(1 << 11) != 0 {if let signature = reader.readInt32() { - _20 = Api.parse(reader, signature: signature) as? Api.PeerColor - } } + if Int(_1!) & Int(1 << 11) != 0 { + if let signature = reader.readInt32() { + _20 = Api.parse(reader, signature: signature) as? Api.PeerColor + } + } var _21: Api.Peer? - if Int(_1!) & Int(1 << 12) != 0 {if let signature = reader.readInt32() { - _21 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 12) != 0 { + if let signature = reader.readInt32() { + _21 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _22: Int32? - if Int(_1!) & Int(1 << 13) != 0 {_22 = reader.readInt32() } + if Int(_1!) & Int(1 << 13) != 0 { + _22 = reader.readInt32() + } + var _23: Int32? + if Int(_1!) & Int(1 << 16) != 0 { + _23 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -547,57 +862,50 @@ public extension Api { let _c20 = (Int(_1!) & Int(1 << 11) == 0) || _20 != nil let _c21 = (Int(_1!) & Int(1 << 12) == 0) || _21 != nil let _c22 = (Int(_1!) & Int(1 << 13) == 0) || _22 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - if !_c16 { return nil } - if !_c17 { return nil } - if !_c18 { return nil } - if !_c19 { return nil } - if !_c20 { return nil } - if !_c21 { return nil } - if !_c22 { return nil } - return Api.StarGift.starGiftUnique(flags: _1!, id: _2!, giftId: _3!, title: _4!, slug: _5!, num: _6!, ownerId: _7, ownerName: _8, ownerAddress: _9, attributes: _10!, availabilityIssued: _11!, availabilityTotal: _12!, giftAddress: _13, resellAmount: _14, releasedBy: _15, valueAmount: _16, valueCurrency: _17, valueUsdAmount: _18, themePeer: _19, peerColor: _20, hostId: _21, offerMinStars: _22) + let _c23 = (Int(_1!) & Int(1 << 16) == 0) || _23 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 && _c18 && _c19 && _c20 && _c21 && _c22 && _c23 { + return Api.StarGift.starGiftUnique(Cons_starGiftUnique(flags: _1!, id: _2!, giftId: _3!, title: _4!, slug: _5!, num: _6!, ownerId: _7, ownerName: _8, ownerAddress: _9, attributes: _10!, availabilityIssued: _11!, availabilityTotal: _12!, giftAddress: _13, resellAmount: _14, releasedBy: _15, valueAmount: _16, valueCurrency: _17, valueUsdAmount: _18, themePeer: _19, peerColor: _20, hostId: _21, offerMinStars: _22, craftChancePermille: _23)) + } + else { + return nil + } } - } } public extension Api { enum StarGiftActiveAuctionState: TypeConstructorDescription { - case starGiftActiveAuctionState(gift: Api.StarGift, state: Api.StarGiftAuctionState, userState: Api.StarGiftAuctionUserState) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftActiveAuctionState(let gift, let state, let userState): - if boxed { - buffer.appendInt32(-753154979) - } - gift.serialize(buffer, true) - state.serialize(buffer, true) - userState.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftActiveAuctionState(let gift, let state, let userState): - return ("starGiftActiveAuctionState", [("gift", gift as Any), ("state", state as Any), ("userState", userState as Any)]) - } - } - + public class Cons_starGiftActiveAuctionState { + public var gift: Api.StarGift + public var state: Api.StarGiftAuctionState + public var userState: Api.StarGiftAuctionUserState + public init(gift: Api.StarGift, state: Api.StarGiftAuctionState, userState: Api.StarGiftAuctionUserState) { + self.gift = gift + self.state = state + self.userState = userState + } + } + case starGiftActiveAuctionState(Cons_starGiftActiveAuctionState) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftActiveAuctionState(let _data): + if boxed { + buffer.appendInt32(-753154979) + } + _data.gift.serialize(buffer, true) + _data.state.serialize(buffer, true) + _data.userState.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftActiveAuctionState(let _data): + return ("starGiftActiveAuctionState", [("gift", _data.gift as Any), ("state", _data.state as Any), ("userState", _data.userState as Any)]) + } + } + public static func parse_starGiftActiveAuctionState(_ reader: BufferReader) -> StarGiftActiveAuctionState? { var _1: Api.StarGift? if let signature = reader.readInt32() { @@ -614,77 +922,137 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.StarGiftActiveAuctionState.starGiftActiveAuctionState(gift: _1!, state: _2!, userState: _3!) + if _c1 && _c2 && _c3 { + return Api.StarGiftActiveAuctionState.starGiftActiveAuctionState(Cons_starGiftActiveAuctionState(gift: _1!, state: _2!, userState: _3!)) + } + else { + return nil + } } - } } public extension Api { enum StarGiftAttribute: TypeConstructorDescription { - case starGiftAttributeBackdrop(name: String, backdropId: Int32, centerColor: Int32, edgeColor: Int32, patternColor: Int32, textColor: Int32, rarityPermille: Int32) - case starGiftAttributeModel(name: String, document: Api.Document, rarityPermille: Int32) - case starGiftAttributeOriginalDetails(flags: Int32, senderId: Api.Peer?, recipientId: Api.Peer, date: Int32, message: Api.TextWithEntities?) - case starGiftAttributePattern(name: String, document: Api.Document, rarityPermille: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftAttributeBackdrop(let name, let backdropId, let centerColor, let edgeColor, let patternColor, let textColor, let rarityPermille): - if boxed { - buffer.appendInt32(-650279524) - } - serializeString(name, buffer: buffer, boxed: false) - serializeInt32(backdropId, buffer: buffer, boxed: false) - serializeInt32(centerColor, buffer: buffer, boxed: false) - serializeInt32(edgeColor, buffer: buffer, boxed: false) - serializeInt32(patternColor, buffer: buffer, boxed: false) - serializeInt32(textColor, buffer: buffer, boxed: false) - serializeInt32(rarityPermille, buffer: buffer, boxed: false) - break - case .starGiftAttributeModel(let name, let document, let rarityPermille): - if boxed { - buffer.appendInt32(970559507) - } - serializeString(name, buffer: buffer, boxed: false) - document.serialize(buffer, true) - serializeInt32(rarityPermille, buffer: buffer, boxed: false) - break - case .starGiftAttributeOriginalDetails(let flags, let senderId, let recipientId, let date, let message): - if boxed { - buffer.appendInt32(-524291476) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {senderId!.serialize(buffer, true)} - recipientId.serialize(buffer, true) - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {message!.serialize(buffer, true)} - break - case .starGiftAttributePattern(let name, let document, let rarityPermille): - if boxed { - buffer.appendInt32(330104601) - } - serializeString(name, buffer: buffer, boxed: false) - document.serialize(buffer, true) - serializeInt32(rarityPermille, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftAttributeBackdrop(let name, let backdropId, let centerColor, let edgeColor, let patternColor, let textColor, let rarityPermille): - return ("starGiftAttributeBackdrop", [("name", name as Any), ("backdropId", backdropId as Any), ("centerColor", centerColor as Any), ("edgeColor", edgeColor as Any), ("patternColor", patternColor as Any), ("textColor", textColor as Any), ("rarityPermille", rarityPermille as Any)]) - case .starGiftAttributeModel(let name, let document, let rarityPermille): - return ("starGiftAttributeModel", [("name", name as Any), ("document", document as Any), ("rarityPermille", rarityPermille as Any)]) - case .starGiftAttributeOriginalDetails(let flags, let senderId, let recipientId, let date, let message): - return ("starGiftAttributeOriginalDetails", [("flags", flags as Any), ("senderId", senderId as Any), ("recipientId", recipientId as Any), ("date", date as Any), ("message", message as Any)]) - case .starGiftAttributePattern(let name, let document, let rarityPermille): - return ("starGiftAttributePattern", [("name", name as Any), ("document", document as Any), ("rarityPermille", rarityPermille as Any)]) - } - } - + public class Cons_starGiftAttributeBackdrop { + public var name: String + public var backdropId: Int32 + public var centerColor: Int32 + public var edgeColor: Int32 + public var patternColor: Int32 + public var textColor: Int32 + public var rarity: Api.StarGiftAttributeRarity + public init(name: String, backdropId: Int32, centerColor: Int32, edgeColor: Int32, patternColor: Int32, textColor: Int32, rarity: Api.StarGiftAttributeRarity) { + self.name = name + self.backdropId = backdropId + self.centerColor = centerColor + self.edgeColor = edgeColor + self.patternColor = patternColor + self.textColor = textColor + self.rarity = rarity + } + } + public class Cons_starGiftAttributeModel { + public var flags: Int32 + public var name: String + public var document: Api.Document + public var rarity: Api.StarGiftAttributeRarity + public init(flags: Int32, name: String, document: Api.Document, rarity: Api.StarGiftAttributeRarity) { + self.flags = flags + self.name = name + self.document = document + self.rarity = rarity + } + } + public class Cons_starGiftAttributeOriginalDetails { + public var flags: Int32 + public var senderId: Api.Peer? + public var recipientId: Api.Peer + public var date: Int32 + public var message: Api.TextWithEntities? + public init(flags: Int32, senderId: Api.Peer?, recipientId: Api.Peer, date: Int32, message: Api.TextWithEntities?) { + self.flags = flags + self.senderId = senderId + self.recipientId = recipientId + self.date = date + self.message = message + } + } + public class Cons_starGiftAttributePattern { + public var name: String + public var document: Api.Document + public var rarity: Api.StarGiftAttributeRarity + public init(name: String, document: Api.Document, rarity: Api.StarGiftAttributeRarity) { + self.name = name + self.document = document + self.rarity = rarity + } + } + case starGiftAttributeBackdrop(Cons_starGiftAttributeBackdrop) + case starGiftAttributeModel(Cons_starGiftAttributeModel) + case starGiftAttributeOriginalDetails(Cons_starGiftAttributeOriginalDetails) + case starGiftAttributePattern(Cons_starGiftAttributePattern) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftAttributeBackdrop(let _data): + if boxed { + buffer.appendInt32(-1624963868) + } + serializeString(_data.name, buffer: buffer, boxed: false) + serializeInt32(_data.backdropId, buffer: buffer, boxed: false) + serializeInt32(_data.centerColor, buffer: buffer, boxed: false) + serializeInt32(_data.edgeColor, buffer: buffer, boxed: false) + serializeInt32(_data.patternColor, buffer: buffer, boxed: false) + serializeInt32(_data.textColor, buffer: buffer, boxed: false) + _data.rarity.serialize(buffer, true) + break + case .starGiftAttributeModel(let _data): + if boxed { + buffer.appendInt32(1448235490) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.name, buffer: buffer, boxed: false) + _data.document.serialize(buffer, true) + _data.rarity.serialize(buffer, true) + break + case .starGiftAttributeOriginalDetails(let _data): + if boxed { + buffer.appendInt32(-524291476) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.senderId!.serialize(buffer, true) + } + _data.recipientId.serialize(buffer, true) + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.message!.serialize(buffer, true) + } + break + case .starGiftAttributePattern(let _data): + if boxed { + buffer.appendInt32(1315997162) + } + serializeString(_data.name, buffer: buffer, boxed: false) + _data.document.serialize(buffer, true) + _data.rarity.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftAttributeBackdrop(let _data): + return ("starGiftAttributeBackdrop", [("name", _data.name as Any), ("backdropId", _data.backdropId as Any), ("centerColor", _data.centerColor as Any), ("edgeColor", _data.edgeColor as Any), ("patternColor", _data.patternColor as Any), ("textColor", _data.textColor as Any), ("rarity", _data.rarity as Any)]) + case .starGiftAttributeModel(let _data): + return ("starGiftAttributeModel", [("flags", _data.flags as Any), ("name", _data.name as Any), ("document", _data.document as Any), ("rarity", _data.rarity as Any)]) + case .starGiftAttributeOriginalDetails(let _data): + return ("starGiftAttributeOriginalDetails", [("flags", _data.flags as Any), ("senderId", _data.senderId as Any), ("recipientId", _data.recipientId as Any), ("date", _data.date as Any), ("message", _data.message as Any)]) + case .starGiftAttributePattern(let _data): + return ("starGiftAttributePattern", [("name", _data.name as Any), ("document", _data.document as Any), ("rarity", _data.rarity as Any)]) + } + } + public static func parse_starGiftAttributeBackdrop(_ reader: BufferReader) -> StarGiftAttribute? { var _1: String? _1 = parseString(reader) @@ -698,8 +1066,10 @@ public extension Api { _5 = reader.readInt32() var _6: Int32? _6 = reader.readInt32() - var _7: Int32? - _7 = reader.readInt32() + var _7: Api.StarGiftAttributeRarity? + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.StarGiftAttributeRarity + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -707,39 +1077,46 @@ public extension Api { let _c5 = _5 != nil let _c6 = _6 != nil let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.StarGiftAttribute.starGiftAttributeBackdrop(name: _1!, backdropId: _2!, centerColor: _3!, edgeColor: _4!, patternColor: _5!, textColor: _6!, rarityPermille: _7!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.StarGiftAttribute.starGiftAttributeBackdrop(Cons_starGiftAttributeBackdrop(name: _1!, backdropId: _2!, centerColor: _3!, edgeColor: _4!, patternColor: _5!, textColor: _6!, rarity: _7!)) + } + else { + return nil + } } public static func parse_starGiftAttributeModel(_ reader: BufferReader) -> StarGiftAttribute? { - var _1: String? - _1 = parseString(reader) - var _2: Api.Document? + var _1: Int32? + _1 = reader.readInt32() + var _2: String? + _2 = parseString(reader) + var _3: Api.Document? if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Document + _3 = Api.parse(reader, signature: signature) as? Api.Document + } + var _4: Api.StarGiftAttributeRarity? + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.StarGiftAttributeRarity } - var _3: Int32? - _3 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.StarGiftAttribute.starGiftAttributeModel(name: _1!, document: _2!, rarityPermille: _3!) + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.StarGiftAttribute.starGiftAttributeModel(Cons_starGiftAttributeModel(flags: _1!, name: _2!, document: _3!, rarity: _4!)) + } + else { + return nil + } } public static func parse_starGiftAttributeOriginalDetails(_ reader: BufferReader) -> StarGiftAttribute? { var _1: Int32? _1 = reader.readInt32() var _2: Api.Peer? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _3: Api.Peer? if let signature = reader.readInt32() { _3 = Api.parse(reader, signature: signature) as? Api.Peer @@ -747,20 +1124,22 @@ public extension Api { var _4: Int32? _4 = reader.readInt32() var _5: Api.TextWithEntities? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.TextWithEntities - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.TextWithEntities + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.StarGiftAttribute.starGiftAttributeOriginalDetails(flags: _1!, senderId: _2, recipientId: _3!, date: _4!, message: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.StarGiftAttribute.starGiftAttributeOriginalDetails(Cons_starGiftAttributeOriginalDetails(flags: _1!, senderId: _2, recipientId: _3!, date: _4!, message: _5)) + } + else { + return nil + } } public static func parse_starGiftAttributePattern(_ reader: BufferReader) -> StarGiftAttribute? { var _1: String? @@ -769,42 +1148,53 @@ public extension Api { if let signature = reader.readInt32() { _2 = Api.parse(reader, signature: signature) as? Api.Document } - var _3: Int32? - _3 = reader.readInt32() + var _3: Api.StarGiftAttributeRarity? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.StarGiftAttributeRarity + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.StarGiftAttribute.starGiftAttributePattern(name: _1!, document: _2!, rarityPermille: _3!) + if _c1 && _c2 && _c3 { + return Api.StarGiftAttribute.starGiftAttributePattern(Cons_starGiftAttributePattern(name: _1!, document: _2!, rarity: _3!)) + } + else { + return nil + } } - } } public extension Api { enum StarGiftAttributeCounter: TypeConstructorDescription { - case starGiftAttributeCounter(attribute: Api.StarGiftAttributeId, count: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftAttributeCounter(let attribute, let count): - if boxed { - buffer.appendInt32(783398488) - } - attribute.serialize(buffer, true) - serializeInt32(count, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftAttributeCounter(let attribute, let count): - return ("starGiftAttributeCounter", [("attribute", attribute as Any), ("count", count as Any)]) - } - } - + public class Cons_starGiftAttributeCounter { + public var attribute: Api.StarGiftAttributeId + public var count: Int32 + public init(attribute: Api.StarGiftAttributeId, count: Int32) { + self.attribute = attribute + self.count = count + } + } + case starGiftAttributeCounter(Cons_starGiftAttributeCounter) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftAttributeCounter(let _data): + if boxed { + buffer.appendInt32(783398488) + } + _data.attribute.serialize(buffer, true) + serializeInt32(_data.count, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftAttributeCounter(let _data): + return ("starGiftAttributeCounter", [("attribute", _data.attribute as Any), ("count", _data.count as Any)]) + } + } + public static func parse_starGiftAttributeCounter(_ reader: BufferReader) -> StarGiftAttributeCounter? { var _1: Api.StarGiftAttributeId? if let signature = reader.readInt32() { @@ -814,106 +1204,246 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.StarGiftAttributeCounter.starGiftAttributeCounter(attribute: _1!, count: _2!) + if _c1 && _c2 { + return Api.StarGiftAttributeCounter.starGiftAttributeCounter(Cons_starGiftAttributeCounter(attribute: _1!, count: _2!)) + } + else { + return nil + } } - } } public extension Api { enum StarGiftAttributeId: TypeConstructorDescription { - case starGiftAttributeIdBackdrop(backdropId: Int32) - case starGiftAttributeIdModel(documentId: Int64) - case starGiftAttributeIdPattern(documentId: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftAttributeIdBackdrop(let backdropId): - if boxed { - buffer.appendInt32(520210263) - } - serializeInt32(backdropId, buffer: buffer, boxed: false) - break - case .starGiftAttributeIdModel(let documentId): - if boxed { - buffer.appendInt32(1219145276) - } - serializeInt64(documentId, buffer: buffer, boxed: false) - break - case .starGiftAttributeIdPattern(let documentId): - if boxed { - buffer.appendInt32(1242965043) - } - serializeInt64(documentId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftAttributeIdBackdrop(let backdropId): - return ("starGiftAttributeIdBackdrop", [("backdropId", backdropId as Any)]) - case .starGiftAttributeIdModel(let documentId): - return ("starGiftAttributeIdModel", [("documentId", documentId as Any)]) - case .starGiftAttributeIdPattern(let documentId): - return ("starGiftAttributeIdPattern", [("documentId", documentId as Any)]) - } - } - + public class Cons_starGiftAttributeIdBackdrop { + public var backdropId: Int32 + public init(backdropId: Int32) { + self.backdropId = backdropId + } + } + public class Cons_starGiftAttributeIdModel { + public var documentId: Int64 + public init(documentId: Int64) { + self.documentId = documentId + } + } + public class Cons_starGiftAttributeIdPattern { + public var documentId: Int64 + public init(documentId: Int64) { + self.documentId = documentId + } + } + case starGiftAttributeIdBackdrop(Cons_starGiftAttributeIdBackdrop) + case starGiftAttributeIdModel(Cons_starGiftAttributeIdModel) + case starGiftAttributeIdPattern(Cons_starGiftAttributeIdPattern) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftAttributeIdBackdrop(let _data): + if boxed { + buffer.appendInt32(520210263) + } + serializeInt32(_data.backdropId, buffer: buffer, boxed: false) + break + case .starGiftAttributeIdModel(let _data): + if boxed { + buffer.appendInt32(1219145276) + } + serializeInt64(_data.documentId, buffer: buffer, boxed: false) + break + case .starGiftAttributeIdPattern(let _data): + if boxed { + buffer.appendInt32(1242965043) + } + serializeInt64(_data.documentId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftAttributeIdBackdrop(let _data): + return ("starGiftAttributeIdBackdrop", [("backdropId", _data.backdropId as Any)]) + case .starGiftAttributeIdModel(let _data): + return ("starGiftAttributeIdModel", [("documentId", _data.documentId as Any)]) + case .starGiftAttributeIdPattern(let _data): + return ("starGiftAttributeIdPattern", [("documentId", _data.documentId as Any)]) + } + } + public static func parse_starGiftAttributeIdBackdrop(_ reader: BufferReader) -> StarGiftAttributeId? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.StarGiftAttributeId.starGiftAttributeIdBackdrop(backdropId: _1!) + if _c1 { + return Api.StarGiftAttributeId.starGiftAttributeIdBackdrop(Cons_starGiftAttributeIdBackdrop(backdropId: _1!)) + } + else { + return nil + } } public static func parse_starGiftAttributeIdModel(_ reader: BufferReader) -> StarGiftAttributeId? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.StarGiftAttributeId.starGiftAttributeIdModel(documentId: _1!) + if _c1 { + return Api.StarGiftAttributeId.starGiftAttributeIdModel(Cons_starGiftAttributeIdModel(documentId: _1!)) + } + else { + return nil + } } public static func parse_starGiftAttributeIdPattern(_ reader: BufferReader) -> StarGiftAttributeId? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.StarGiftAttributeId.starGiftAttributeIdPattern(documentId: _1!) + if _c1 { + return Api.StarGiftAttributeId.starGiftAttributeIdPattern(Cons_starGiftAttributeIdPattern(documentId: _1!)) + } + else { + return nil + } + } + } +} +public extension Api { + enum StarGiftAttributeRarity: TypeConstructorDescription { + public class Cons_starGiftAttributeRarity { + public var permille: Int32 + public init(permille: Int32) { + self.permille = permille + } + } + case starGiftAttributeRarity(Cons_starGiftAttributeRarity) + case starGiftAttributeRarityEpic + case starGiftAttributeRarityLegendary + case starGiftAttributeRarityRare + case starGiftAttributeRarityUncommon + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftAttributeRarity(let _data): + if boxed { + buffer.appendInt32(910391095) + } + serializeInt32(_data.permille, buffer: buffer, boxed: false) + break + case .starGiftAttributeRarityEpic: + if boxed { + buffer.appendInt32(2029777832) + } + break + case .starGiftAttributeRarityLegendary: + if boxed { + buffer.appendInt32(-822614104) + } + break + case .starGiftAttributeRarityRare: + if boxed { + buffer.appendInt32(-259174037) + } + break + case .starGiftAttributeRarityUncommon: + if boxed { + buffer.appendInt32(-607231095) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftAttributeRarity(let _data): + return ("starGiftAttributeRarity", [("permille", _data.permille as Any)]) + case .starGiftAttributeRarityEpic: + return ("starGiftAttributeRarityEpic", []) + case .starGiftAttributeRarityLegendary: + return ("starGiftAttributeRarityLegendary", []) + case .starGiftAttributeRarityRare: + return ("starGiftAttributeRarityRare", []) + case .starGiftAttributeRarityUncommon: + return ("starGiftAttributeRarityUncommon", []) + } + } + + public static func parse_starGiftAttributeRarity(_ reader: BufferReader) -> StarGiftAttributeRarity? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.StarGiftAttributeRarity.starGiftAttributeRarity(Cons_starGiftAttributeRarity(permille: _1!)) + } + else { + return nil + } + } + public static func parse_starGiftAttributeRarityEpic(_ reader: BufferReader) -> StarGiftAttributeRarity? { + return Api.StarGiftAttributeRarity.starGiftAttributeRarityEpic + } + public static func parse_starGiftAttributeRarityLegendary(_ reader: BufferReader) -> StarGiftAttributeRarity? { + return Api.StarGiftAttributeRarity.starGiftAttributeRarityLegendary + } + public static func parse_starGiftAttributeRarityRare(_ reader: BufferReader) -> StarGiftAttributeRarity? { + return Api.StarGiftAttributeRarity.starGiftAttributeRarityRare + } + public static func parse_starGiftAttributeRarityUncommon(_ reader: BufferReader) -> StarGiftAttributeRarity? { + return Api.StarGiftAttributeRarity.starGiftAttributeRarityUncommon } - } } public extension Api { enum StarGiftAuctionAcquiredGift: TypeConstructorDescription { - case starGiftAuctionAcquiredGift(flags: Int32, peer: Api.Peer, date: Int32, bidAmount: Int64, round: Int32, pos: Int32, message: Api.TextWithEntities?, giftNum: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftAuctionAcquiredGift(let flags, let peer, let date, let bidAmount, let round, let pos, let message, let giftNum): - if boxed { - buffer.appendInt32(1118831432) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(bidAmount, buffer: buffer, boxed: false) - serializeInt32(round, buffer: buffer, boxed: false) - serializeInt32(pos, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {message!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(giftNum!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftAuctionAcquiredGift(let flags, let peer, let date, let bidAmount, let round, let pos, let message, let giftNum): - return ("starGiftAuctionAcquiredGift", [("flags", flags as Any), ("peer", peer as Any), ("date", date as Any), ("bidAmount", bidAmount as Any), ("round", round as Any), ("pos", pos as Any), ("message", message as Any), ("giftNum", giftNum as Any)]) - } - } - + public class Cons_starGiftAuctionAcquiredGift { + public var flags: Int32 + public var peer: Api.Peer + public var date: Int32 + public var bidAmount: Int64 + public var round: Int32 + public var pos: Int32 + public var message: Api.TextWithEntities? + public var giftNum: Int32? + public init(flags: Int32, peer: Api.Peer, date: Int32, bidAmount: Int64, round: Int32, pos: Int32, message: Api.TextWithEntities?, giftNum: Int32?) { + self.flags = flags + self.peer = peer + self.date = date + self.bidAmount = bidAmount + self.round = round + self.pos = pos + self.message = message + self.giftNum = giftNum + } + } + case starGiftAuctionAcquiredGift(Cons_starGiftAuctionAcquiredGift) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftAuctionAcquiredGift(let _data): + if boxed { + buffer.appendInt32(1118831432) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.bidAmount, buffer: buffer, boxed: false) + serializeInt32(_data.round, buffer: buffer, boxed: false) + serializeInt32(_data.pos, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.message!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.giftNum!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftAuctionAcquiredGift(let _data): + return ("starGiftAuctionAcquiredGift", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("date", _data.date as Any), ("bidAmount", _data.bidAmount as Any), ("round", _data.round as Any), ("pos", _data.pos as Any), ("message", _data.message as Any), ("giftNum", _data.giftNum as Any)]) + } + } + public static func parse_starGiftAuctionAcquiredGift(_ reader: BufferReader) -> StarGiftAuctionAcquiredGift? { var _1: Int32? _1 = reader.readInt32() @@ -930,11 +1460,15 @@ public extension Api { var _6: Int32? _6 = reader.readInt32() var _7: Api.TextWithEntities? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.TextWithEntities - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.TextWithEntities + } + } var _8: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_8 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _8 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -943,54 +1477,70 @@ public extension Api { let _c6 = _6 != nil let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil let _c8 = (Int(_1!) & Int(1 << 2) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.StarGiftAuctionAcquiredGift.starGiftAuctionAcquiredGift(flags: _1!, peer: _2!, date: _3!, bidAmount: _4!, round: _5!, pos: _6!, message: _7, giftNum: _8) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.StarGiftAuctionAcquiredGift.starGiftAuctionAcquiredGift(Cons_starGiftAuctionAcquiredGift(flags: _1!, peer: _2!, date: _3!, bidAmount: _4!, round: _5!, pos: _6!, message: _7, giftNum: _8)) + } + else { + return nil + } } - } } public extension Api { enum StarGiftAuctionRound: TypeConstructorDescription { - case starGiftAuctionRound(num: Int32, duration: Int32) - case starGiftAuctionRoundExtendable(num: Int32, duration: Int32, extendTop: Int32, extendWindow: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftAuctionRound(let num, let duration): - if boxed { - buffer.appendInt32(984483112) - } - serializeInt32(num, buffer: buffer, boxed: false) - serializeInt32(duration, buffer: buffer, boxed: false) - break - case .starGiftAuctionRoundExtendable(let num, let duration, let extendTop, let extendWindow): - if boxed { - buffer.appendInt32(178266597) - } - serializeInt32(num, buffer: buffer, boxed: false) - serializeInt32(duration, buffer: buffer, boxed: false) - serializeInt32(extendTop, buffer: buffer, boxed: false) - serializeInt32(extendWindow, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftAuctionRound(let num, let duration): - return ("starGiftAuctionRound", [("num", num as Any), ("duration", duration as Any)]) - case .starGiftAuctionRoundExtendable(let num, let duration, let extendTop, let extendWindow): - return ("starGiftAuctionRoundExtendable", [("num", num as Any), ("duration", duration as Any), ("extendTop", extendTop as Any), ("extendWindow", extendWindow as Any)]) - } - } - + public class Cons_starGiftAuctionRound { + public var num: Int32 + public var duration: Int32 + public init(num: Int32, duration: Int32) { + self.num = num + self.duration = duration + } + } + public class Cons_starGiftAuctionRoundExtendable { + public var num: Int32 + public var duration: Int32 + public var extendTop: Int32 + public var extendWindow: Int32 + public init(num: Int32, duration: Int32, extendTop: Int32, extendWindow: Int32) { + self.num = num + self.duration = duration + self.extendTop = extendTop + self.extendWindow = extendWindow + } + } + case starGiftAuctionRound(Cons_starGiftAuctionRound) + case starGiftAuctionRoundExtendable(Cons_starGiftAuctionRoundExtendable) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftAuctionRound(let _data): + if boxed { + buffer.appendInt32(984483112) + } + serializeInt32(_data.num, buffer: buffer, boxed: false) + serializeInt32(_data.duration, buffer: buffer, boxed: false) + break + case .starGiftAuctionRoundExtendable(let _data): + if boxed { + buffer.appendInt32(178266597) + } + serializeInt32(_data.num, buffer: buffer, boxed: false) + serializeInt32(_data.duration, buffer: buffer, boxed: false) + serializeInt32(_data.extendTop, buffer: buffer, boxed: false) + serializeInt32(_data.extendWindow, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftAuctionRound(let _data): + return ("starGiftAuctionRound", [("num", _data.num as Any), ("duration", _data.duration as Any)]) + case .starGiftAuctionRoundExtendable(let _data): + return ("starGiftAuctionRoundExtendable", [("num", _data.num as Any), ("duration", _data.duration as Any), ("extendTop", _data.extendTop as Any), ("extendWindow", _data.extendWindow as Any)]) + } + } + public static func parse_starGiftAuctionRound(_ reader: BufferReader) -> StarGiftAuctionRound? { var _1: Int32? _1 = reader.readInt32() @@ -998,9 +1548,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.StarGiftAuctionRound.starGiftAuctionRound(num: _1!, duration: _2!) + if _c1 && _c2 { + return Api.StarGiftAuctionRound.starGiftAuctionRound(Cons_starGiftAuctionRound(num: _1!, duration: _2!)) + } + else { + return nil + } } public static func parse_starGiftAuctionRoundExtendable(_ reader: BufferReader) -> StarGiftAuctionRound? { var _1: Int32? @@ -1015,84 +1568,135 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.StarGiftAuctionRound.starGiftAuctionRoundExtendable(num: _1!, duration: _2!, extendTop: _3!, extendWindow: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.StarGiftAuctionRound.starGiftAuctionRoundExtendable(Cons_starGiftAuctionRoundExtendable(num: _1!, duration: _2!, extendTop: _3!, extendWindow: _4!)) + } + else { + return nil + } } - } } public extension Api { enum StarGiftAuctionState: TypeConstructorDescription { - case starGiftAuctionState(version: Int32, startDate: Int32, endDate: Int32, minBidAmount: Int64, bidLevels: [Api.AuctionBidLevel], topBidders: [Int64], nextRoundAt: Int32, lastGiftNum: Int32, giftsLeft: Int32, currentRound: Int32, totalRounds: Int32, rounds: [Api.StarGiftAuctionRound]) - case starGiftAuctionStateFinished(flags: Int32, startDate: Int32, endDate: Int32, averagePrice: Int64, listedCount: Int32?, fragmentListedCount: Int32?, fragmentListedUrl: String?) + public class Cons_starGiftAuctionState { + public var version: Int32 + public var startDate: Int32 + public var endDate: Int32 + public var minBidAmount: Int64 + public var bidLevels: [Api.AuctionBidLevel] + public var topBidders: [Int64] + public var nextRoundAt: Int32 + public var lastGiftNum: Int32 + public var giftsLeft: Int32 + public var currentRound: Int32 + public var totalRounds: Int32 + public var rounds: [Api.StarGiftAuctionRound] + public init(version: Int32, startDate: Int32, endDate: Int32, minBidAmount: Int64, bidLevels: [Api.AuctionBidLevel], topBidders: [Int64], nextRoundAt: Int32, lastGiftNum: Int32, giftsLeft: Int32, currentRound: Int32, totalRounds: Int32, rounds: [Api.StarGiftAuctionRound]) { + self.version = version + self.startDate = startDate + self.endDate = endDate + self.minBidAmount = minBidAmount + self.bidLevels = bidLevels + self.topBidders = topBidders + self.nextRoundAt = nextRoundAt + self.lastGiftNum = lastGiftNum + self.giftsLeft = giftsLeft + self.currentRound = currentRound + self.totalRounds = totalRounds + self.rounds = rounds + } + } + public class Cons_starGiftAuctionStateFinished { + public var flags: Int32 + public var startDate: Int32 + public var endDate: Int32 + public var averagePrice: Int64 + public var listedCount: Int32? + public var fragmentListedCount: Int32? + public var fragmentListedUrl: String? + public init(flags: Int32, startDate: Int32, endDate: Int32, averagePrice: Int64, listedCount: Int32?, fragmentListedCount: Int32?, fragmentListedUrl: String?) { + self.flags = flags + self.startDate = startDate + self.endDate = endDate + self.averagePrice = averagePrice + self.listedCount = listedCount + self.fragmentListedCount = fragmentListedCount + self.fragmentListedUrl = fragmentListedUrl + } + } + case starGiftAuctionState(Cons_starGiftAuctionState) + case starGiftAuctionStateFinished(Cons_starGiftAuctionStateFinished) case starGiftAuctionStateNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftAuctionState(let version, let startDate, let endDate, let minBidAmount, let bidLevels, let topBidders, let nextRoundAt, let lastGiftNum, let giftsLeft, let currentRound, let totalRounds, let rounds): - if boxed { - buffer.appendInt32(1998212710) - } - serializeInt32(version, buffer: buffer, boxed: false) - serializeInt32(startDate, buffer: buffer, boxed: false) - serializeInt32(endDate, buffer: buffer, boxed: false) - serializeInt64(minBidAmount, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(bidLevels.count)) - for item in bidLevels { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(topBidders.count)) - for item in topBidders { - serializeInt64(item, buffer: buffer, boxed: false) - } - serializeInt32(nextRoundAt, buffer: buffer, boxed: false) - serializeInt32(lastGiftNum, buffer: buffer, boxed: false) - serializeInt32(giftsLeft, buffer: buffer, boxed: false) - serializeInt32(currentRound, buffer: buffer, boxed: false) - serializeInt32(totalRounds, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(rounds.count)) - for item in rounds { - item.serialize(buffer, true) - } - break - case .starGiftAuctionStateFinished(let flags, let startDate, let endDate, let averagePrice, let listedCount, let fragmentListedCount, let fragmentListedUrl): - if boxed { - buffer.appendInt32(-1758614593) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(startDate, buffer: buffer, boxed: false) - serializeInt32(endDate, buffer: buffer, boxed: false) - serializeInt64(averagePrice, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(listedCount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(fragmentListedCount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(fragmentListedUrl!, buffer: buffer, boxed: false)} - break - case .starGiftAuctionStateNotModified: - if boxed { - buffer.appendInt32(-30197422) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftAuctionState(let version, let startDate, let endDate, let minBidAmount, let bidLevels, let topBidders, let nextRoundAt, let lastGiftNum, let giftsLeft, let currentRound, let totalRounds, let rounds): - return ("starGiftAuctionState", [("version", version as Any), ("startDate", startDate as Any), ("endDate", endDate as Any), ("minBidAmount", minBidAmount as Any), ("bidLevels", bidLevels as Any), ("topBidders", topBidders as Any), ("nextRoundAt", nextRoundAt as Any), ("lastGiftNum", lastGiftNum as Any), ("giftsLeft", giftsLeft as Any), ("currentRound", currentRound as Any), ("totalRounds", totalRounds as Any), ("rounds", rounds as Any)]) - case .starGiftAuctionStateFinished(let flags, let startDate, let endDate, let averagePrice, let listedCount, let fragmentListedCount, let fragmentListedUrl): - return ("starGiftAuctionStateFinished", [("flags", flags as Any), ("startDate", startDate as Any), ("endDate", endDate as Any), ("averagePrice", averagePrice as Any), ("listedCount", listedCount as Any), ("fragmentListedCount", fragmentListedCount as Any), ("fragmentListedUrl", fragmentListedUrl as Any)]) - case .starGiftAuctionStateNotModified: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftAuctionState(let _data): + if boxed { + buffer.appendInt32(1998212710) + } + serializeInt32(_data.version, buffer: buffer, boxed: false) + serializeInt32(_data.startDate, buffer: buffer, boxed: false) + serializeInt32(_data.endDate, buffer: buffer, boxed: false) + serializeInt64(_data.minBidAmount, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.bidLevels.count)) + for item in _data.bidLevels { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.topBidders.count)) + for item in _data.topBidders { + serializeInt64(item, buffer: buffer, boxed: false) + } + serializeInt32(_data.nextRoundAt, buffer: buffer, boxed: false) + serializeInt32(_data.lastGiftNum, buffer: buffer, boxed: false) + serializeInt32(_data.giftsLeft, buffer: buffer, boxed: false) + serializeInt32(_data.currentRound, buffer: buffer, boxed: false) + serializeInt32(_data.totalRounds, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.rounds.count)) + for item in _data.rounds { + item.serialize(buffer, true) + } + break + case .starGiftAuctionStateFinished(let _data): + if boxed { + buffer.appendInt32(-1758614593) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.startDate, buffer: buffer, boxed: false) + serializeInt32(_data.endDate, buffer: buffer, boxed: false) + serializeInt64(_data.averagePrice, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.listedCount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.fragmentListedCount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.fragmentListedUrl!, buffer: buffer, boxed: false) + } + break + case .starGiftAuctionStateNotModified: + if boxed { + buffer.appendInt32(-30197422) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftAuctionState(let _data): + return ("starGiftAuctionState", [("version", _data.version as Any), ("startDate", _data.startDate as Any), ("endDate", _data.endDate as Any), ("minBidAmount", _data.minBidAmount as Any), ("bidLevels", _data.bidLevels as Any), ("topBidders", _data.topBidders as Any), ("nextRoundAt", _data.nextRoundAt as Any), ("lastGiftNum", _data.lastGiftNum as Any), ("giftsLeft", _data.giftsLeft as Any), ("currentRound", _data.currentRound as Any), ("totalRounds", _data.totalRounds as Any), ("rounds", _data.rounds as Any)]) + case .starGiftAuctionStateFinished(let _data): + return ("starGiftAuctionStateFinished", [("flags", _data.flags as Any), ("startDate", _data.startDate as Any), ("endDate", _data.endDate as Any), ("averagePrice", _data.averagePrice as Any), ("listedCount", _data.listedCount as Any), ("fragmentListedCount", _data.fragmentListedCount as Any), ("fragmentListedUrl", _data.fragmentListedUrl as Any)]) + case .starGiftAuctionStateNotModified: return ("starGiftAuctionStateNotModified", []) - } - } - + } + } + public static func parse_starGiftAuctionState(_ reader: BufferReader) -> StarGiftAuctionState? { var _1: Int32? _1 = reader.readInt32() @@ -1136,19 +1740,12 @@ public extension Api { let _c10 = _10 != nil let _c11 = _11 != nil let _c12 = _12 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - return Api.StarGiftAuctionState.starGiftAuctionState(version: _1!, startDate: _2!, endDate: _3!, minBidAmount: _4!, bidLevels: _5!, topBidders: _6!, nextRoundAt: _7!, lastGiftNum: _8!, giftsLeft: _9!, currentRound: _10!, totalRounds: _11!, rounds: _12!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 { + return Api.StarGiftAuctionState.starGiftAuctionState(Cons_starGiftAuctionState(version: _1!, startDate: _2!, endDate: _3!, minBidAmount: _4!, bidLevels: _5!, topBidders: _6!, nextRoundAt: _7!, lastGiftNum: _8!, giftsLeft: _9!, currentRound: _10!, totalRounds: _11!, rounds: _12!)) + } + else { + return nil + } } public static func parse_starGiftAuctionStateFinished(_ reader: BufferReader) -> StarGiftAuctionState? { var _1: Int32? @@ -1160,11 +1757,17 @@ public extension Api { var _4: Int64? _4 = reader.readInt64() var _5: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _5 = reader.readInt32() + } var _6: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _6 = reader.readInt32() + } var _7: String? - if Int(_1!) & Int(1 << 1) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _7 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -1172,61 +1775,90 @@ public extension Api { let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.StarGiftAuctionState.starGiftAuctionStateFinished(flags: _1!, startDate: _2!, endDate: _3!, averagePrice: _4!, listedCount: _5, fragmentListedCount: _6, fragmentListedUrl: _7) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.StarGiftAuctionState.starGiftAuctionStateFinished(Cons_starGiftAuctionStateFinished(flags: _1!, startDate: _2!, endDate: _3!, averagePrice: _4!, listedCount: _5, fragmentListedCount: _6, fragmentListedUrl: _7)) + } + else { + return nil + } } public static func parse_starGiftAuctionStateNotModified(_ reader: BufferReader) -> StarGiftAuctionState? { return Api.StarGiftAuctionState.starGiftAuctionStateNotModified } - } } public extension Api { enum StarGiftAuctionUserState: TypeConstructorDescription { - case starGiftAuctionUserState(flags: Int32, bidAmount: Int64?, bidDate: Int32?, minBidAmount: Int64?, bidPeer: Api.Peer?, acquiredCount: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftAuctionUserState(let flags, let bidAmount, let bidDate, let minBidAmount, let bidPeer, let acquiredCount): - if boxed { - buffer.appendInt32(787403204) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(bidAmount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(bidDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(minBidAmount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {bidPeer!.serialize(buffer, true)} - serializeInt32(acquiredCount, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftAuctionUserState(let flags, let bidAmount, let bidDate, let minBidAmount, let bidPeer, let acquiredCount): - return ("starGiftAuctionUserState", [("flags", flags as Any), ("bidAmount", bidAmount as Any), ("bidDate", bidDate as Any), ("minBidAmount", minBidAmount as Any), ("bidPeer", bidPeer as Any), ("acquiredCount", acquiredCount as Any)]) - } - } - + public class Cons_starGiftAuctionUserState { + public var flags: Int32 + public var bidAmount: Int64? + public var bidDate: Int32? + public var minBidAmount: Int64? + public var bidPeer: Api.Peer? + public var acquiredCount: Int32 + public init(flags: Int32, bidAmount: Int64?, bidDate: Int32?, minBidAmount: Int64?, bidPeer: Api.Peer?, acquiredCount: Int32) { + self.flags = flags + self.bidAmount = bidAmount + self.bidDate = bidDate + self.minBidAmount = minBidAmount + self.bidPeer = bidPeer + self.acquiredCount = acquiredCount + } + } + case starGiftAuctionUserState(Cons_starGiftAuctionUserState) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftAuctionUserState(let _data): + if boxed { + buffer.appendInt32(787403204) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.bidAmount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.bidDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.minBidAmount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.bidPeer!.serialize(buffer, true) + } + serializeInt32(_data.acquiredCount, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftAuctionUserState(let _data): + return ("starGiftAuctionUserState", [("flags", _data.flags as Any), ("bidAmount", _data.bidAmount as Any), ("bidDate", _data.bidDate as Any), ("minBidAmount", _data.minBidAmount as Any), ("bidPeer", _data.bidPeer as Any), ("acquiredCount", _data.acquiredCount as Any)]) + } + } + public static func parse_starGiftAuctionUserState(_ reader: BufferReader) -> StarGiftAuctionUserState? { var _1: Int32? _1 = reader.readInt32() var _2: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt64() + } var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } var _4: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_4 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = reader.readInt64() + } var _5: Api.Peer? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _6: Int32? _6 = reader.readInt32() let _c1 = _1 != nil @@ -1235,41 +1867,49 @@ public extension Api { let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.StarGiftAuctionUserState.starGiftAuctionUserState(flags: _1!, bidAmount: _2, bidDate: _3, minBidAmount: _4, bidPeer: _5, acquiredCount: _6!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.StarGiftAuctionUserState.starGiftAuctionUserState(Cons_starGiftAuctionUserState(flags: _1!, bidAmount: _2, bidDate: _3, minBidAmount: _4, bidPeer: _5, acquiredCount: _6!)) + } + else { + return nil + } } - } } public extension Api { enum StarGiftBackground: TypeConstructorDescription { - case starGiftBackground(centerColor: Int32, edgeColor: Int32, textColor: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftBackground(let centerColor, let edgeColor, let textColor): - if boxed { - buffer.appendInt32(-1342872680) - } - serializeInt32(centerColor, buffer: buffer, boxed: false) - serializeInt32(edgeColor, buffer: buffer, boxed: false) - serializeInt32(textColor, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftBackground(let centerColor, let edgeColor, let textColor): - return ("starGiftBackground", [("centerColor", centerColor as Any), ("edgeColor", edgeColor as Any), ("textColor", textColor as Any)]) - } - } - + public class Cons_starGiftBackground { + public var centerColor: Int32 + public var edgeColor: Int32 + public var textColor: Int32 + public init(centerColor: Int32, edgeColor: Int32, textColor: Int32) { + self.centerColor = centerColor + self.edgeColor = edgeColor + self.textColor = textColor + } + } + case starGiftBackground(Cons_starGiftBackground) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftBackground(let _data): + if boxed { + buffer.appendInt32(-1342872680) + } + serializeInt32(_data.centerColor, buffer: buffer, boxed: false) + serializeInt32(_data.edgeColor, buffer: buffer, boxed: false) + serializeInt32(_data.textColor, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftBackground(let _data): + return ("starGiftBackground", [("centerColor", _data.centerColor as Any), ("edgeColor", _data.edgeColor as Any), ("textColor", _data.textColor as Any)]) + } + } + public static func parse_starGiftBackground(_ reader: BufferReader) -> StarGiftBackground? { var _1: Int32? _1 = reader.readInt32() @@ -1280,41 +1920,60 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.StarGiftBackground.starGiftBackground(centerColor: _1!, edgeColor: _2!, textColor: _3!) + if _c1 && _c2 && _c3 { + return Api.StarGiftBackground.starGiftBackground(Cons_starGiftBackground(centerColor: _1!, edgeColor: _2!, textColor: _3!)) + } + else { + return nil + } } - } } public extension Api { enum StarGiftCollection: TypeConstructorDescription { - case starGiftCollection(flags: Int32, collectionId: Int32, title: String, icon: Api.Document?, giftsCount: Int32, hash: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftCollection(let flags, let collectionId, let title, let icon, let giftsCount, let hash): - if boxed { - buffer.appendInt32(-1653926992) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(collectionId, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {icon!.serialize(buffer, true)} - serializeInt32(giftsCount, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftCollection(let flags, let collectionId, let title, let icon, let giftsCount, let hash): - return ("starGiftCollection", [("flags", flags as Any), ("collectionId", collectionId as Any), ("title", title as Any), ("icon", icon as Any), ("giftsCount", giftsCount as Any), ("hash", hash as Any)]) - } - } - + public class Cons_starGiftCollection { + public var flags: Int32 + public var collectionId: Int32 + public var title: String + public var icon: Api.Document? + public var giftsCount: Int32 + public var hash: Int64 + public init(flags: Int32, collectionId: Int32, title: String, icon: Api.Document?, giftsCount: Int32, hash: Int64) { + self.flags = flags + self.collectionId = collectionId + self.title = title + self.icon = icon + self.giftsCount = giftsCount + self.hash = hash + } + } + case starGiftCollection(Cons_starGiftCollection) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftCollection(let _data): + if boxed { + buffer.appendInt32(-1653926992) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.collectionId, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.icon!.serialize(buffer, true) + } + serializeInt32(_data.giftsCount, buffer: buffer, boxed: false) + serializeInt64(_data.hash, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftCollection(let _data): + return ("starGiftCollection", [("flags", _data.flags as Any), ("collectionId", _data.collectionId as Any), ("title", _data.title as Any), ("icon", _data.icon as Any), ("giftsCount", _data.giftsCount as Any), ("hash", _data.hash as Any)]) + } + } + public static func parse_starGiftCollection(_ reader: BufferReader) -> StarGiftCollection? { var _1: Int32? _1 = reader.readInt32() @@ -1323,9 +1982,11 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: Api.Document? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Document - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Document + } + } var _5: Int32? _5 = reader.readInt32() var _6: Int64? @@ -1336,40 +1997,46 @@ public extension Api { let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil let _c5 = _5 != nil let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.StarGiftCollection.starGiftCollection(flags: _1!, collectionId: _2!, title: _3!, icon: _4, giftsCount: _5!, hash: _6!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.StarGiftCollection.starGiftCollection(Cons_starGiftCollection(flags: _1!, collectionId: _2!, title: _3!, icon: _4, giftsCount: _5!, hash: _6!)) + } + else { + return nil + } } - } } public extension Api { enum StarGiftUpgradePrice: TypeConstructorDescription { - case starGiftUpgradePrice(date: Int32, upgradeStars: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftUpgradePrice(let date, let upgradeStars): - if boxed { - buffer.appendInt32(-1712704739) - } - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(upgradeStars, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftUpgradePrice(let date, let upgradeStars): - return ("starGiftUpgradePrice", [("date", date as Any), ("upgradeStars", upgradeStars as Any)]) - } - } - + public class Cons_starGiftUpgradePrice { + public var date: Int32 + public var upgradeStars: Int64 + public init(date: Int32, upgradeStars: Int64) { + self.date = date + self.upgradeStars = upgradeStars + } + } + case starGiftUpgradePrice(Cons_starGiftUpgradePrice) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftUpgradePrice(let _data): + if boxed { + buffer.appendInt32(-1712704739) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.upgradeStars, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftUpgradePrice(let _data): + return ("starGiftUpgradePrice", [("date", _data.date as Any), ("upgradeStars", _data.upgradeStars as Any)]) + } + } + public static func parse_starGiftUpgradePrice(_ reader: BufferReader) -> StarGiftUpgradePrice? { var _1: Int32? _1 = reader.readInt32() @@ -1377,40 +2044,64 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.StarGiftUpgradePrice.starGiftUpgradePrice(date: _1!, upgradeStars: _2!) + if _c1 && _c2 { + return Api.StarGiftUpgradePrice.starGiftUpgradePrice(Cons_starGiftUpgradePrice(date: _1!, upgradeStars: _2!)) + } + else { + return nil + } } - } } public extension Api { enum StarRefProgram: TypeConstructorDescription { - case starRefProgram(flags: Int32, botId: Int64, commissionPermille: Int32, durationMonths: Int32?, endDate: Int32?, dailyRevenuePerUser: Api.StarsAmount?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starRefProgram(let flags, let botId, let commissionPermille, let durationMonths, let endDate, let dailyRevenuePerUser): - if boxed { - buffer.appendInt32(-586389774) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(botId, buffer: buffer, boxed: false) - serializeInt32(commissionPermille, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(durationMonths!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(endDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {dailyRevenuePerUser!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starRefProgram(let flags, let botId, let commissionPermille, let durationMonths, let endDate, let dailyRevenuePerUser): - return ("starRefProgram", [("flags", flags as Any), ("botId", botId as Any), ("commissionPermille", commissionPermille as Any), ("durationMonths", durationMonths as Any), ("endDate", endDate as Any), ("dailyRevenuePerUser", dailyRevenuePerUser as Any)]) - } - } - + public class Cons_starRefProgram { + public var flags: Int32 + public var botId: Int64 + public var commissionPermille: Int32 + public var durationMonths: Int32? + public var endDate: Int32? + public var dailyRevenuePerUser: Api.StarsAmount? + public init(flags: Int32, botId: Int64, commissionPermille: Int32, durationMonths: Int32?, endDate: Int32?, dailyRevenuePerUser: Api.StarsAmount?) { + self.flags = flags + self.botId = botId + self.commissionPermille = commissionPermille + self.durationMonths = durationMonths + self.endDate = endDate + self.dailyRevenuePerUser = dailyRevenuePerUser + } + } + case starRefProgram(Cons_starRefProgram) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starRefProgram(let _data): + if boxed { + buffer.appendInt32(-586389774) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.botId, buffer: buffer, boxed: false) + serializeInt32(_data.commissionPermille, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.durationMonths!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.endDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.dailyRevenuePerUser!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starRefProgram(let _data): + return ("starRefProgram", [("flags", _data.flags as Any), ("botId", _data.botId as Any), ("commissionPermille", _data.commissionPermille as Any), ("durationMonths", _data.durationMonths as Any), ("endDate", _data.endDate as Any), ("dailyRevenuePerUser", _data.dailyRevenuePerUser as Any)]) + } + } + public static func parse_starRefProgram(_ reader: BufferReader) -> StarRefProgram? { var _1: Int32? _1 = reader.readInt32() @@ -1419,242 +2110,31 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = reader.readInt32() + } var _5: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _5 = reader.readInt32() + } var _6: Api.StarsAmount? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.StarsAmount - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.StarsAmount + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.StarRefProgram.starRefProgram(flags: _1!, botId: _2!, commissionPermille: _3!, durationMonths: _4, endDate: _5, dailyRevenuePerUser: _6) - } - - } -} -public extension Api { - enum StarsAmount: TypeConstructorDescription { - case starsAmount(amount: Int64, nanos: Int32) - case starsTonAmount(amount: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starsAmount(let amount, let nanos): - if boxed { - buffer.appendInt32(-1145654109) - } - serializeInt64(amount, buffer: buffer, boxed: false) - serializeInt32(nanos, buffer: buffer, boxed: false) - break - case .starsTonAmount(let amount): - if boxed { - buffer.appendInt32(1957618656) - } - serializeInt64(amount, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starsAmount(let amount, let nanos): - return ("starsAmount", [("amount", amount as Any), ("nanos", nanos as Any)]) - case .starsTonAmount(let amount): - return ("starsTonAmount", [("amount", amount as Any)]) - } - } - - public static func parse_starsAmount(_ reader: BufferReader) -> StarsAmount? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Int32? - _2 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.StarsAmount.starsAmount(amount: _1!, nanos: _2!) - } - public static func parse_starsTonAmount(_ reader: BufferReader) -> StarsAmount? { - var _1: Int64? - _1 = reader.readInt64() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.StarsAmount.starsTonAmount(amount: _1!) - } - - } -} -public extension Api { - enum StarsGiftOption: TypeConstructorDescription { - case starsGiftOption(flags: Int32, stars: Int64, storeProduct: String?, currency: String, amount: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starsGiftOption(let flags, let stars, let storeProduct, let currency, let amount): - if boxed { - buffer.appendInt32(1577421297) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(stars, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(storeProduct!, buffer: buffer, boxed: false)} - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starsGiftOption(let flags, let stars, let storeProduct, let currency, let amount): - return ("starsGiftOption", [("flags", flags as Any), ("stars", stars as Any), ("storeProduct", storeProduct as Any), ("currency", currency as Any), ("amount", amount as Any)]) - } - } - - public static func parse_starsGiftOption(_ reader: BufferReader) -> StarsGiftOption? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: String? - if Int(_1!) & Int(1 << 0) != 0 {_3 = parseString(reader) } - var _4: String? - _4 = parseString(reader) - var _5: Int64? - _5 = reader.readInt64() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.StarsGiftOption.starsGiftOption(flags: _1!, stars: _2!, storeProduct: _3, currency: _4!, amount: _5!) - } - - } -} -public extension Api { - enum StarsGiveawayOption: TypeConstructorDescription { - case starsGiveawayOption(flags: Int32, stars: Int64, yearlyBoosts: Int32, storeProduct: String?, currency: String, amount: Int64, winners: [Api.StarsGiveawayWinnersOption]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starsGiveawayOption(let flags, let stars, let yearlyBoosts, let storeProduct, let currency, let amount, let winners): - if boxed { - buffer.appendInt32(-1798404822) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(stars, buffer: buffer, boxed: false) - serializeInt32(yearlyBoosts, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeString(storeProduct!, buffer: buffer, boxed: false)} - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(winners.count)) - for item in winners { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starsGiveawayOption(let flags, let stars, let yearlyBoosts, let storeProduct, let currency, let amount, let winners): - return ("starsGiveawayOption", [("flags", flags as Any), ("stars", stars as Any), ("yearlyBoosts", yearlyBoosts as Any), ("storeProduct", storeProduct as Any), ("currency", currency as Any), ("amount", amount as Any), ("winners", winners as Any)]) - } - } - - public static func parse_starsGiveawayOption(_ reader: BufferReader) -> StarsGiveawayOption? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int32? - _3 = reader.readInt32() - var _4: String? - if Int(_1!) & Int(1 << 2) != 0 {_4 = parseString(reader) } - var _5: String? - _5 = parseString(reader) - var _6: Int64? - _6 = reader.readInt64() - var _7: [Api.StarsGiveawayWinnersOption]? - if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarsGiveawayWinnersOption.self) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.StarRefProgram.starRefProgram(Cons_starRefProgram(flags: _1!, botId: _2!, commissionPermille: _3!, durationMonths: _4, endDate: _5, dailyRevenuePerUser: _6)) + } + else { + return nil } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.StarsGiveawayOption.starsGiveawayOption(flags: _1!, stars: _2!, yearlyBoosts: _3!, storeProduct: _4, currency: _5!, amount: _6!, winners: _7!) } - - } -} -public extension Api { - enum StarsGiveawayWinnersOption: TypeConstructorDescription { - case starsGiveawayWinnersOption(flags: Int32, users: Int32, perUserStars: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starsGiveawayWinnersOption(let flags, let users, let perUserStars): - if boxed { - buffer.appendInt32(1411605001) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(users, buffer: buffer, boxed: false) - serializeInt64(perUserStars, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starsGiveawayWinnersOption(let flags, let users, let perUserStars): - return ("starsGiveawayWinnersOption", [("flags", flags as Any), ("users", users as Any), ("perUserStars", perUserStars as Any)]) - } - } - - public static func parse_starsGiveawayWinnersOption(_ reader: BufferReader) -> StarsGiveawayWinnersOption? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int64? - _3 = reader.readInt64() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.StarsGiveawayWinnersOption.starsGiveawayWinnersOption(flags: _1!, users: _2!, perUserStars: _3!) - } - } } diff --git a/submodules/TelegramApi/Sources/Api26.swift b/submodules/TelegramApi/Sources/Api26.swift index 4a5c08c4..a5dbafa1 100644 --- a/submodules/TelegramApi/Sources/Api26.swift +++ b/submodules/TelegramApi/Sources/Api26.swift @@ -1,29 +1,327 @@ +public extension Api { + enum StarsAmount: TypeConstructorDescription { + public class Cons_starsAmount { + public var amount: Int64 + public var nanos: Int32 + public init(amount: Int64, nanos: Int32) { + self.amount = amount + self.nanos = nanos + } + } + public class Cons_starsTonAmount { + public var amount: Int64 + public init(amount: Int64) { + self.amount = amount + } + } + case starsAmount(Cons_starsAmount) + case starsTonAmount(Cons_starsTonAmount) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starsAmount(let _data): + if boxed { + buffer.appendInt32(-1145654109) + } + serializeInt64(_data.amount, buffer: buffer, boxed: false) + serializeInt32(_data.nanos, buffer: buffer, boxed: false) + break + case .starsTonAmount(let _data): + if boxed { + buffer.appendInt32(1957618656) + } + serializeInt64(_data.amount, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starsAmount(let _data): + return ("starsAmount", [("amount", _data.amount as Any), ("nanos", _data.nanos as Any)]) + case .starsTonAmount(let _data): + return ("starsTonAmount", [("amount", _data.amount as Any)]) + } + } + + public static func parse_starsAmount(_ reader: BufferReader) -> StarsAmount? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Int32? + _2 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.StarsAmount.starsAmount(Cons_starsAmount(amount: _1!, nanos: _2!)) + } + else { + return nil + } + } + public static func parse_starsTonAmount(_ reader: BufferReader) -> StarsAmount? { + var _1: Int64? + _1 = reader.readInt64() + let _c1 = _1 != nil + if _c1 { + return Api.StarsAmount.starsTonAmount(Cons_starsTonAmount(amount: _1!)) + } + else { + return nil + } + } + } +} +public extension Api { + enum StarsGiftOption: TypeConstructorDescription { + public class Cons_starsGiftOption { + public var flags: Int32 + public var stars: Int64 + public var storeProduct: String? + public var currency: String + public var amount: Int64 + public init(flags: Int32, stars: Int64, storeProduct: String?, currency: String, amount: Int64) { + self.flags = flags + self.stars = stars + self.storeProduct = storeProduct + self.currency = currency + self.amount = amount + } + } + case starsGiftOption(Cons_starsGiftOption) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starsGiftOption(let _data): + if boxed { + buffer.appendInt32(1577421297) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.stars, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.storeProduct!, buffer: buffer, boxed: false) + } + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starsGiftOption(let _data): + return ("starsGiftOption", [("flags", _data.flags as Any), ("stars", _data.stars as Any), ("storeProduct", _data.storeProduct as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any)]) + } + } + + public static func parse_starsGiftOption(_ reader: BufferReader) -> StarsGiftOption? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: String? + if Int(_1!) & Int(1 << 0) != 0 { + _3 = parseString(reader) + } + var _4: String? + _4 = parseString(reader) + var _5: Int64? + _5 = reader.readInt64() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.StarsGiftOption.starsGiftOption(Cons_starsGiftOption(flags: _1!, stars: _2!, storeProduct: _3, currency: _4!, amount: _5!)) + } + else { + return nil + } + } + } +} +public extension Api { + enum StarsGiveawayOption: TypeConstructorDescription { + public class Cons_starsGiveawayOption { + public var flags: Int32 + public var stars: Int64 + public var yearlyBoosts: Int32 + public var storeProduct: String? + public var currency: String + public var amount: Int64 + public var winners: [Api.StarsGiveawayWinnersOption] + public init(flags: Int32, stars: Int64, yearlyBoosts: Int32, storeProduct: String?, currency: String, amount: Int64, winners: [Api.StarsGiveawayWinnersOption]) { + self.flags = flags + self.stars = stars + self.yearlyBoosts = yearlyBoosts + self.storeProduct = storeProduct + self.currency = currency + self.amount = amount + self.winners = winners + } + } + case starsGiveawayOption(Cons_starsGiveawayOption) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starsGiveawayOption(let _data): + if boxed { + buffer.appendInt32(-1798404822) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.stars, buffer: buffer, boxed: false) + serializeInt32(_data.yearlyBoosts, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.storeProduct!, buffer: buffer, boxed: false) + } + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.winners.count)) + for item in _data.winners { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starsGiveawayOption(let _data): + return ("starsGiveawayOption", [("flags", _data.flags as Any), ("stars", _data.stars as Any), ("yearlyBoosts", _data.yearlyBoosts as Any), ("storeProduct", _data.storeProduct as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any), ("winners", _data.winners as Any)]) + } + } + + public static func parse_starsGiveawayOption(_ reader: BufferReader) -> StarsGiveawayOption? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: Int32? + _3 = reader.readInt32() + var _4: String? + if Int(_1!) & Int(1 << 2) != 0 { + _4 = parseString(reader) + } + var _5: String? + _5 = parseString(reader) + var _6: Int64? + _6 = reader.readInt64() + var _7: [Api.StarsGiveawayWinnersOption]? + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarsGiveawayWinnersOption.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + let _c7 = _7 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.StarsGiveawayOption.starsGiveawayOption(Cons_starsGiveawayOption(flags: _1!, stars: _2!, yearlyBoosts: _3!, storeProduct: _4, currency: _5!, amount: _6!, winners: _7!)) + } + else { + return nil + } + } + } +} +public extension Api { + enum StarsGiveawayWinnersOption: TypeConstructorDescription { + public class Cons_starsGiveawayWinnersOption { + public var flags: Int32 + public var users: Int32 + public var perUserStars: Int64 + public init(flags: Int32, users: Int32, perUserStars: Int64) { + self.flags = flags + self.users = users + self.perUserStars = perUserStars + } + } + case starsGiveawayWinnersOption(Cons_starsGiveawayWinnersOption) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starsGiveawayWinnersOption(let _data): + if boxed { + buffer.appendInt32(1411605001) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.users, buffer: buffer, boxed: false) + serializeInt64(_data.perUserStars, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starsGiveawayWinnersOption(let _data): + return ("starsGiveawayWinnersOption", [("flags", _data.flags as Any), ("users", _data.users as Any), ("perUserStars", _data.perUserStars as Any)]) + } + } + + public static func parse_starsGiveawayWinnersOption(_ reader: BufferReader) -> StarsGiveawayWinnersOption? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int64? + _3 = reader.readInt64() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.StarsGiveawayWinnersOption.starsGiveawayWinnersOption(Cons_starsGiveawayWinnersOption(flags: _1!, users: _2!, perUserStars: _3!)) + } + else { + return nil + } + } + } +} public extension Api { enum StarsRating: TypeConstructorDescription { - case starsRating(flags: Int32, level: Int32, currentLevelStars: Int64, stars: Int64, nextLevelStars: Int64?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starsRating(let flags, let level, let currentLevelStars, let stars, let nextLevelStars): - if boxed { - buffer.appendInt32(453922567) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(level, buffer: buffer, boxed: false) - serializeInt64(currentLevelStars, buffer: buffer, boxed: false) - serializeInt64(stars, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(nextLevelStars!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starsRating(let flags, let level, let currentLevelStars, let stars, let nextLevelStars): - return ("starsRating", [("flags", flags as Any), ("level", level as Any), ("currentLevelStars", currentLevelStars as Any), ("stars", stars as Any), ("nextLevelStars", nextLevelStars as Any)]) - } - } - + public class Cons_starsRating { + public var flags: Int32 + public var level: Int32 + public var currentLevelStars: Int64 + public var stars: Int64 + public var nextLevelStars: Int64? + public init(flags: Int32, level: Int32, currentLevelStars: Int64, stars: Int64, nextLevelStars: Int64?) { + self.flags = flags + self.level = level + self.currentLevelStars = currentLevelStars + self.stars = stars + self.nextLevelStars = nextLevelStars + } + } + case starsRating(Cons_starsRating) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starsRating(let _data): + if boxed { + buffer.appendInt32(453922567) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.level, buffer: buffer, boxed: false) + serializeInt64(_data.currentLevelStars, buffer: buffer, boxed: false) + serializeInt64(_data.stars, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.nextLevelStars!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starsRating(let _data): + return ("starsRating", [("flags", _data.flags as Any), ("level", _data.level as Any), ("currentLevelStars", _data.currentLevelStars as Any), ("stars", _data.stars as Any), ("nextLevelStars", _data.nextLevelStars as Any)]) + } + } + public static func parse_starsRating(_ reader: BufferReader) -> StarsRating? { var _1: Int32? _1 = reader.readInt32() @@ -34,48 +332,65 @@ public extension Api { var _4: Int64? _4 = reader.readInt64() var _5: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_5 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _5 = reader.readInt64() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.StarsRating.starsRating(flags: _1!, level: _2!, currentLevelStars: _3!, stars: _4!, nextLevelStars: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.StarsRating.starsRating(Cons_starsRating(flags: _1!, level: _2!, currentLevelStars: _3!, stars: _4!, nextLevelStars: _5)) + } + else { + return nil + } } - } } public extension Api { enum StarsRevenueStatus: TypeConstructorDescription { - case starsRevenueStatus(flags: Int32, currentBalance: Api.StarsAmount, availableBalance: Api.StarsAmount, overallRevenue: Api.StarsAmount, nextWithdrawalAt: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starsRevenueStatus(let flags, let currentBalance, let availableBalance, let overallRevenue, let nextWithdrawalAt): - if boxed { - buffer.appendInt32(-21080943) - } - serializeInt32(flags, buffer: buffer, boxed: false) - currentBalance.serialize(buffer, true) - availableBalance.serialize(buffer, true) - overallRevenue.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(nextWithdrawalAt!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starsRevenueStatus(let flags, let currentBalance, let availableBalance, let overallRevenue, let nextWithdrawalAt): - return ("starsRevenueStatus", [("flags", flags as Any), ("currentBalance", currentBalance as Any), ("availableBalance", availableBalance as Any), ("overallRevenue", overallRevenue as Any), ("nextWithdrawalAt", nextWithdrawalAt as Any)]) - } - } - + public class Cons_starsRevenueStatus { + public var flags: Int32 + public var currentBalance: Api.StarsAmount + public var availableBalance: Api.StarsAmount + public var overallRevenue: Api.StarsAmount + public var nextWithdrawalAt: Int32? + public init(flags: Int32, currentBalance: Api.StarsAmount, availableBalance: Api.StarsAmount, overallRevenue: Api.StarsAmount, nextWithdrawalAt: Int32?) { + self.flags = flags + self.currentBalance = currentBalance + self.availableBalance = availableBalance + self.overallRevenue = overallRevenue + self.nextWithdrawalAt = nextWithdrawalAt + } + } + case starsRevenueStatus(Cons_starsRevenueStatus) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starsRevenueStatus(let _data): + if boxed { + buffer.appendInt32(-21080943) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.currentBalance.serialize(buffer, true) + _data.availableBalance.serialize(buffer, true) + _data.overallRevenue.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.nextWithdrawalAt!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starsRevenueStatus(let _data): + return ("starsRevenueStatus", [("flags", _data.flags as Any), ("currentBalance", _data.currentBalance as Any), ("availableBalance", _data.availableBalance as Any), ("overallRevenue", _data.overallRevenue as Any), ("nextWithdrawalAt", _data.nextWithdrawalAt as Any)]) + } + } + public static func parse_starsRevenueStatus(_ reader: BufferReader) -> StarsRevenueStatus? { var _1: Int32? _1 = reader.readInt32() @@ -92,52 +407,83 @@ public extension Api { _4 = Api.parse(reader, signature: signature) as? Api.StarsAmount } var _5: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _5 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.StarsRevenueStatus.starsRevenueStatus(flags: _1!, currentBalance: _2!, availableBalance: _3!, overallRevenue: _4!, nextWithdrawalAt: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.StarsRevenueStatus.starsRevenueStatus(Cons_starsRevenueStatus(flags: _1!, currentBalance: _2!, availableBalance: _3!, overallRevenue: _4!, nextWithdrawalAt: _5)) + } + else { + return nil + } } - } } public extension Api { enum StarsSubscription: TypeConstructorDescription { - case starsSubscription(flags: Int32, id: String, peer: Api.Peer, untilDate: Int32, pricing: Api.StarsSubscriptionPricing, chatInviteHash: String?, title: String?, photo: Api.WebDocument?, invoiceSlug: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starsSubscription(let flags, let id, let peer, let untilDate, let pricing, let chatInviteHash, let title, let photo, let invoiceSlug): - if boxed { - buffer.appendInt32(779004698) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(id, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(untilDate, buffer: buffer, boxed: false) - pricing.serialize(buffer, true) - if Int(flags) & Int(1 << 3) != 0 {serializeString(chatInviteHash!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {photo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 6) != 0 {serializeString(invoiceSlug!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starsSubscription(let flags, let id, let peer, let untilDate, let pricing, let chatInviteHash, let title, let photo, let invoiceSlug): - return ("starsSubscription", [("flags", flags as Any), ("id", id as Any), ("peer", peer as Any), ("untilDate", untilDate as Any), ("pricing", pricing as Any), ("chatInviteHash", chatInviteHash as Any), ("title", title as Any), ("photo", photo as Any), ("invoiceSlug", invoiceSlug as Any)]) - } - } - + public class Cons_starsSubscription { + public var flags: Int32 + public var id: String + public var peer: Api.Peer + public var untilDate: Int32 + public var pricing: Api.StarsSubscriptionPricing + public var chatInviteHash: String? + public var title: String? + public var photo: Api.WebDocument? + public var invoiceSlug: String? + public init(flags: Int32, id: String, peer: Api.Peer, untilDate: Int32, pricing: Api.StarsSubscriptionPricing, chatInviteHash: String?, title: String?, photo: Api.WebDocument?, invoiceSlug: String?) { + self.flags = flags + self.id = id + self.peer = peer + self.untilDate = untilDate + self.pricing = pricing + self.chatInviteHash = chatInviteHash + self.title = title + self.photo = photo + self.invoiceSlug = invoiceSlug + } + } + case starsSubscription(Cons_starsSubscription) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starsSubscription(let _data): + if boxed { + buffer.appendInt32(779004698) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.id, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeInt32(_data.untilDate, buffer: buffer, boxed: false) + _data.pricing.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.chatInviteHash!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + _data.photo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + serializeString(_data.invoiceSlug!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starsSubscription(let _data): + return ("starsSubscription", [("flags", _data.flags as Any), ("id", _data.id as Any), ("peer", _data.peer as Any), ("untilDate", _data.untilDate as Any), ("pricing", _data.pricing as Any), ("chatInviteHash", _data.chatInviteHash as Any), ("title", _data.title as Any), ("photo", _data.photo as Any), ("invoiceSlug", _data.invoiceSlug as Any)]) + } + } + public static func parse_starsSubscription(_ reader: BufferReader) -> StarsSubscription? { var _1: Int32? _1 = reader.readInt32() @@ -154,15 +500,23 @@ public extension Api { _5 = Api.parse(reader, signature: signature) as? Api.StarsSubscriptionPricing } var _6: String? - if Int(_1!) & Int(1 << 3) != 0 {_6 = parseString(reader) } + if Int(_1!) & Int(1 << 3) != 0 { + _6 = parseString(reader) + } var _7: String? - if Int(_1!) & Int(1 << 4) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 4) != 0 { + _7 = parseString(reader) + } var _8: Api.WebDocument? - if Int(_1!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.WebDocument - } } + if Int(_1!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.WebDocument + } + } var _9: String? - if Int(_1!) & Int(1 << 6) != 0 {_9 = parseString(reader) } + if Int(_1!) & Int(1 << 6) != 0 { + _9 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -172,43 +526,46 @@ public extension Api { let _c7 = (Int(_1!) & Int(1 << 4) == 0) || _7 != nil let _c8 = (Int(_1!) & Int(1 << 5) == 0) || _8 != nil let _c9 = (Int(_1!) & Int(1 << 6) == 0) || _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.StarsSubscription.starsSubscription(flags: _1!, id: _2!, peer: _3!, untilDate: _4!, pricing: _5!, chatInviteHash: _6, title: _7, photo: _8, invoiceSlug: _9) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.StarsSubscription.starsSubscription(Cons_starsSubscription(flags: _1!, id: _2!, peer: _3!, untilDate: _4!, pricing: _5!, chatInviteHash: _6, title: _7, photo: _8, invoiceSlug: _9)) + } + else { + return nil + } } - } } public extension Api { enum StarsSubscriptionPricing: TypeConstructorDescription { - case starsSubscriptionPricing(period: Int32, amount: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starsSubscriptionPricing(let period, let amount): - if boxed { - buffer.appendInt32(88173912) - } - serializeInt32(period, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starsSubscriptionPricing(let period, let amount): - return ("starsSubscriptionPricing", [("period", period as Any), ("amount", amount as Any)]) - } - } - + public class Cons_starsSubscriptionPricing { + public var period: Int32 + public var amount: Int64 + public init(period: Int32, amount: Int64) { + self.period = period + self.amount = amount + } + } + case starsSubscriptionPricing(Cons_starsSubscriptionPricing) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starsSubscriptionPricing(let _data): + if boxed { + buffer.appendInt32(88173912) + } + serializeInt32(_data.period, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starsSubscriptionPricing(let _data): + return ("starsSubscriptionPricing", [("period", _data.period as Any), ("amount", _data.amount as Any)]) + } + } + public static func parse_starsSubscriptionPricing(_ reader: BufferReader) -> StarsSubscriptionPricing? { var _1: Int32? _1 = reader.readInt32() @@ -216,46 +573,66 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.StarsSubscriptionPricing.starsSubscriptionPricing(period: _1!, amount: _2!) + if _c1 && _c2 { + return Api.StarsSubscriptionPricing.starsSubscriptionPricing(Cons_starsSubscriptionPricing(period: _1!, amount: _2!)) + } + else { + return nil + } } - } } public extension Api { enum StarsTopupOption: TypeConstructorDescription { - case starsTopupOption(flags: Int32, stars: Int64, storeProduct: String?, currency: String, amount: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starsTopupOption(let flags, let stars, let storeProduct, let currency, let amount): - if boxed { - buffer.appendInt32(198776256) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(stars, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(storeProduct!, buffer: buffer, boxed: false)} - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starsTopupOption(let flags, let stars, let storeProduct, let currency, let amount): - return ("starsTopupOption", [("flags", flags as Any), ("stars", stars as Any), ("storeProduct", storeProduct as Any), ("currency", currency as Any), ("amount", amount as Any)]) - } - } - + public class Cons_starsTopupOption { + public var flags: Int32 + public var stars: Int64 + public var storeProduct: String? + public var currency: String + public var amount: Int64 + public init(flags: Int32, stars: Int64, storeProduct: String?, currency: String, amount: Int64) { + self.flags = flags + self.stars = stars + self.storeProduct = storeProduct + self.currency = currency + self.amount = amount + } + } + case starsTopupOption(Cons_starsTopupOption) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starsTopupOption(let _data): + if boxed { + buffer.appendInt32(198776256) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.stars, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.storeProduct!, buffer: buffer, boxed: false) + } + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starsTopupOption(let _data): + return ("starsTopupOption", [("flags", _data.flags as Any), ("stars", _data.stars as Any), ("storeProduct", _data.storeProduct as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any)]) + } + } + public static func parse_starsTopupOption(_ reader: BufferReader) -> StarsTopupOption? { var _1: Int32? _1 = reader.readInt32() var _2: Int64? _2 = reader.readInt64() var _3: String? - if Int(_1!) & Int(1 << 0) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = parseString(reader) + } var _4: String? _4 = parseString(reader) var _5: Int64? @@ -265,65 +642,154 @@ public extension Api { let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.StarsTopupOption.starsTopupOption(flags: _1!, stars: _2!, storeProduct: _3, currency: _4!, amount: _5!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.StarsTopupOption.starsTopupOption(Cons_starsTopupOption(flags: _1!, stars: _2!, storeProduct: _3, currency: _4!, amount: _5!)) + } + else { + return nil + } } - } } public extension Api { enum StarsTransaction: TypeConstructorDescription { - case starsTransaction(flags: Int32, id: String, amount: Api.StarsAmount, date: Int32, peer: Api.StarsTransactionPeer, title: String?, description: String?, photo: Api.WebDocument?, transactionDate: Int32?, transactionUrl: String?, botPayload: Buffer?, msgId: Int32?, extendedMedia: [Api.MessageMedia]?, subscriptionPeriod: Int32?, giveawayPostId: Int32?, stargift: Api.StarGift?, floodskipNumber: Int32?, starrefCommissionPermille: Int32?, starrefPeer: Api.Peer?, starrefAmount: Api.StarsAmount?, paidMessages: Int32?, premiumGiftMonths: Int32?, adsProceedsFromDate: Int32?, adsProceedsToDate: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starsTransaction(let flags, let id, let amount, let date, let peer, let title, let description, let photo, let transactionDate, let transactionUrl, let botPayload, let msgId, let extendedMedia, let subscriptionPeriod, let giveawayPostId, let stargift, let floodskipNumber, let starrefCommissionPermille, let starrefPeer, let starrefAmount, let paidMessages, let premiumGiftMonths, let adsProceedsFromDate, let adsProceedsToDate): - if boxed { - buffer.appendInt32(325426864) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(id, buffer: buffer, boxed: false) - amount.serialize(buffer, true) - serializeInt32(date, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(description!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {photo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 5) != 0 {serializeInt32(transactionDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeString(transactionUrl!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 7) != 0 {serializeBytes(botPayload!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {serializeInt32(msgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 9) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(extendedMedia!.count)) - for item in extendedMedia! { + public class Cons_starsTransaction { + public var flags: Int32 + public var id: String + public var amount: Api.StarsAmount + public var date: Int32 + public var peer: Api.StarsTransactionPeer + public var title: String? + public var description: String? + public var photo: Api.WebDocument? + public var transactionDate: Int32? + public var transactionUrl: String? + public var botPayload: Buffer? + public var msgId: Int32? + public var extendedMedia: [Api.MessageMedia]? + public var subscriptionPeriod: Int32? + public var giveawayPostId: Int32? + public var stargift: Api.StarGift? + public var floodskipNumber: Int32? + public var starrefCommissionPermille: Int32? + public var starrefPeer: Api.Peer? + public var starrefAmount: Api.StarsAmount? + public var paidMessages: Int32? + public var premiumGiftMonths: Int32? + public var adsProceedsFromDate: Int32? + public var adsProceedsToDate: Int32? + public init(flags: Int32, id: String, amount: Api.StarsAmount, date: Int32, peer: Api.StarsTransactionPeer, title: String?, description: String?, photo: Api.WebDocument?, transactionDate: Int32?, transactionUrl: String?, botPayload: Buffer?, msgId: Int32?, extendedMedia: [Api.MessageMedia]?, subscriptionPeriod: Int32?, giveawayPostId: Int32?, stargift: Api.StarGift?, floodskipNumber: Int32?, starrefCommissionPermille: Int32?, starrefPeer: Api.Peer?, starrefAmount: Api.StarsAmount?, paidMessages: Int32?, premiumGiftMonths: Int32?, adsProceedsFromDate: Int32?, adsProceedsToDate: Int32?) { + self.flags = flags + self.id = id + self.amount = amount + self.date = date + self.peer = peer + self.title = title + self.description = description + self.photo = photo + self.transactionDate = transactionDate + self.transactionUrl = transactionUrl + self.botPayload = botPayload + self.msgId = msgId + self.extendedMedia = extendedMedia + self.subscriptionPeriod = subscriptionPeriod + self.giveawayPostId = giveawayPostId + self.stargift = stargift + self.floodskipNumber = floodskipNumber + self.starrefCommissionPermille = starrefCommissionPermille + self.starrefPeer = starrefPeer + self.starrefAmount = starrefAmount + self.paidMessages = paidMessages + self.premiumGiftMonths = premiumGiftMonths + self.adsProceedsFromDate = adsProceedsFromDate + self.adsProceedsToDate = adsProceedsToDate + } + } + case starsTransaction(Cons_starsTransaction) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starsTransaction(let _data): + if boxed { + buffer.appendInt32(325426864) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.id, buffer: buffer, boxed: false) + _data.amount.serialize(buffer, true) + serializeInt32(_data.date, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.description!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.photo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeInt32(_data.transactionDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeString(_data.transactionUrl!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 7) != 0 { + serializeBytes(_data.botPayload!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + serializeInt32(_data.msgId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 9) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.extendedMedia!.count)) + for item in _data.extendedMedia! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 12) != 0 {serializeInt32(subscriptionPeriod!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 13) != 0 {serializeInt32(giveawayPostId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 14) != 0 {stargift!.serialize(buffer, true)} - if Int(flags) & Int(1 << 15) != 0 {serializeInt32(floodskipNumber!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 16) != 0 {serializeInt32(starrefCommissionPermille!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 17) != 0 {starrefPeer!.serialize(buffer, true)} - if Int(flags) & Int(1 << 17) != 0 {starrefAmount!.serialize(buffer, true)} - if Int(flags) & Int(1 << 19) != 0 {serializeInt32(paidMessages!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 20) != 0 {serializeInt32(premiumGiftMonths!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 23) != 0 {serializeInt32(adsProceedsFromDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 23) != 0 {serializeInt32(adsProceedsToDate!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starsTransaction(let flags, let id, let amount, let date, let peer, let title, let description, let photo, let transactionDate, let transactionUrl, let botPayload, let msgId, let extendedMedia, let subscriptionPeriod, let giveawayPostId, let stargift, let floodskipNumber, let starrefCommissionPermille, let starrefPeer, let starrefAmount, let paidMessages, let premiumGiftMonths, let adsProceedsFromDate, let adsProceedsToDate): - return ("starsTransaction", [("flags", flags as Any), ("id", id as Any), ("amount", amount as Any), ("date", date as Any), ("peer", peer as Any), ("title", title as Any), ("description", description as Any), ("photo", photo as Any), ("transactionDate", transactionDate as Any), ("transactionUrl", transactionUrl as Any), ("botPayload", botPayload as Any), ("msgId", msgId as Any), ("extendedMedia", extendedMedia as Any), ("subscriptionPeriod", subscriptionPeriod as Any), ("giveawayPostId", giveawayPostId as Any), ("stargift", stargift as Any), ("floodskipNumber", floodskipNumber as Any), ("starrefCommissionPermille", starrefCommissionPermille as Any), ("starrefPeer", starrefPeer as Any), ("starrefAmount", starrefAmount as Any), ("paidMessages", paidMessages as Any), ("premiumGiftMonths", premiumGiftMonths as Any), ("adsProceedsFromDate", adsProceedsFromDate as Any), ("adsProceedsToDate", adsProceedsToDate as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 12) != 0 { + serializeInt32(_data.subscriptionPeriod!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 13) != 0 { + serializeInt32(_data.giveawayPostId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 14) != 0 { + _data.stargift!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 15) != 0 { + serializeInt32(_data.floodskipNumber!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 16) != 0 { + serializeInt32(_data.starrefCommissionPermille!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 17) != 0 { + _data.starrefPeer!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 17) != 0 { + _data.starrefAmount!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 19) != 0 { + serializeInt32(_data.paidMessages!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 20) != 0 { + serializeInt32(_data.premiumGiftMonths!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 23) != 0 { + serializeInt32(_data.adsProceedsFromDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 23) != 0 { + serializeInt32(_data.adsProceedsToDate!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starsTransaction(let _data): + return ("starsTransaction", [("flags", _data.flags as Any), ("id", _data.id as Any), ("amount", _data.amount as Any), ("date", _data.date as Any), ("peer", _data.peer as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("photo", _data.photo as Any), ("transactionDate", _data.transactionDate as Any), ("transactionUrl", _data.transactionUrl as Any), ("botPayload", _data.botPayload as Any), ("msgId", _data.msgId as Any), ("extendedMedia", _data.extendedMedia as Any), ("subscriptionPeriod", _data.subscriptionPeriod as Any), ("giveawayPostId", _data.giveawayPostId as Any), ("stargift", _data.stargift as Any), ("floodskipNumber", _data.floodskipNumber as Any), ("starrefCommissionPermille", _data.starrefCommissionPermille as Any), ("starrefPeer", _data.starrefPeer as Any), ("starrefAmount", _data.starrefAmount as Any), ("paidMessages", _data.paidMessages as Any), ("premiumGiftMonths", _data.premiumGiftMonths as Any), ("adsProceedsFromDate", _data.adsProceedsFromDate as Any), ("adsProceedsToDate", _data.adsProceedsToDate as Any)]) + } + } + public static func parse_starsTransaction(_ reader: BufferReader) -> StarsTransaction? { var _1: Int32? _1 = reader.readInt32() @@ -340,53 +806,91 @@ public extension Api { _5 = Api.parse(reader, signature: signature) as? Api.StarsTransactionPeer } var _6: String? - if Int(_1!) & Int(1 << 0) != 0 {_6 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _6 = parseString(reader) + } var _7: String? - if Int(_1!) & Int(1 << 1) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _7 = parseString(reader) + } var _8: Api.WebDocument? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.WebDocument - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.WebDocument + } + } var _9: Int32? - if Int(_1!) & Int(1 << 5) != 0 {_9 = reader.readInt32() } + if Int(_1!) & Int(1 << 5) != 0 { + _9 = reader.readInt32() + } var _10: String? - if Int(_1!) & Int(1 << 5) != 0 {_10 = parseString(reader) } + if Int(_1!) & Int(1 << 5) != 0 { + _10 = parseString(reader) + } var _11: Buffer? - if Int(_1!) & Int(1 << 7) != 0 {_11 = parseBytes(reader) } + if Int(_1!) & Int(1 << 7) != 0 { + _11 = parseBytes(reader) + } var _12: Int32? - if Int(_1!) & Int(1 << 8) != 0 {_12 = reader.readInt32() } + if Int(_1!) & Int(1 << 8) != 0 { + _12 = reader.readInt32() + } var _13: [Api.MessageMedia]? - if Int(_1!) & Int(1 << 9) != 0 {if let _ = reader.readInt32() { - _13 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageMedia.self) - } } + if Int(_1!) & Int(1 << 9) != 0 { + if let _ = reader.readInt32() { + _13 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageMedia.self) + } + } var _14: Int32? - if Int(_1!) & Int(1 << 12) != 0 {_14 = reader.readInt32() } + if Int(_1!) & Int(1 << 12) != 0 { + _14 = reader.readInt32() + } var _15: Int32? - if Int(_1!) & Int(1 << 13) != 0 {_15 = reader.readInt32() } + if Int(_1!) & Int(1 << 13) != 0 { + _15 = reader.readInt32() + } var _16: Api.StarGift? - if Int(_1!) & Int(1 << 14) != 0 {if let signature = reader.readInt32() { - _16 = Api.parse(reader, signature: signature) as? Api.StarGift - } } + if Int(_1!) & Int(1 << 14) != 0 { + if let signature = reader.readInt32() { + _16 = Api.parse(reader, signature: signature) as? Api.StarGift + } + } var _17: Int32? - if Int(_1!) & Int(1 << 15) != 0 {_17 = reader.readInt32() } + if Int(_1!) & Int(1 << 15) != 0 { + _17 = reader.readInt32() + } var _18: Int32? - if Int(_1!) & Int(1 << 16) != 0 {_18 = reader.readInt32() } + if Int(_1!) & Int(1 << 16) != 0 { + _18 = reader.readInt32() + } var _19: Api.Peer? - if Int(_1!) & Int(1 << 17) != 0 {if let signature = reader.readInt32() { - _19 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 17) != 0 { + if let signature = reader.readInt32() { + _19 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _20: Api.StarsAmount? - if Int(_1!) & Int(1 << 17) != 0 {if let signature = reader.readInt32() { - _20 = Api.parse(reader, signature: signature) as? Api.StarsAmount - } } + if Int(_1!) & Int(1 << 17) != 0 { + if let signature = reader.readInt32() { + _20 = Api.parse(reader, signature: signature) as? Api.StarsAmount + } + } var _21: Int32? - if Int(_1!) & Int(1 << 19) != 0 {_21 = reader.readInt32() } + if Int(_1!) & Int(1 << 19) != 0 { + _21 = reader.readInt32() + } var _22: Int32? - if Int(_1!) & Int(1 << 20) != 0 {_22 = reader.readInt32() } + if Int(_1!) & Int(1 << 20) != 0 { + _22 = reader.readInt32() + } var _23: Int32? - if Int(_1!) & Int(1 << 23) != 0 {_23 = reader.readInt32() } + if Int(_1!) & Int(1 << 23) != 0 { + _23 = reader.readInt32() + } var _24: Int32? - if Int(_1!) & Int(1 << 23) != 0 {_24 = reader.readInt32() } + if Int(_1!) & Int(1 << 23) != 0 { + _24 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -411,38 +915,24 @@ public extension Api { let _c22 = (Int(_1!) & Int(1 << 20) == 0) || _22 != nil let _c23 = (Int(_1!) & Int(1 << 23) == 0) || _23 != nil let _c24 = (Int(_1!) & Int(1 << 23) == 0) || _24 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - if !_c16 { return nil } - if !_c17 { return nil } - if !_c18 { return nil } - if !_c19 { return nil } - if !_c20 { return nil } - if !_c21 { return nil } - if !_c22 { return nil } - if !_c23 { return nil } - if !_c24 { return nil } - return Api.StarsTransaction.starsTransaction(flags: _1!, id: _2!, amount: _3!, date: _4!, peer: _5!, title: _6, description: _7, photo: _8, transactionDate: _9, transactionUrl: _10, botPayload: _11, msgId: _12, extendedMedia: _13, subscriptionPeriod: _14, giveawayPostId: _15, stargift: _16, floodskipNumber: _17, starrefCommissionPermille: _18, starrefPeer: _19, starrefAmount: _20, paidMessages: _21, premiumGiftMonths: _22, adsProceedsFromDate: _23, adsProceedsToDate: _24) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 && _c18 && _c19 && _c20 && _c21 && _c22 && _c23 && _c24 { + return Api.StarsTransaction.starsTransaction(Cons_starsTransaction(flags: _1!, id: _2!, amount: _3!, date: _4!, peer: _5!, title: _6, description: _7, photo: _8, transactionDate: _9, transactionUrl: _10, botPayload: _11, msgId: _12, extendedMedia: _13, subscriptionPeriod: _14, giveawayPostId: _15, stargift: _16, floodskipNumber: _17, starrefCommissionPermille: _18, starrefPeer: _19, starrefAmount: _20, paidMessages: _21, premiumGiftMonths: _22, adsProceedsFromDate: _23, adsProceedsToDate: _24)) + } + else { + return nil + } } - } } public extension Api { enum StarsTransactionPeer: TypeConstructorDescription { - case starsTransactionPeer(peer: Api.Peer) + public class Cons_starsTransactionPeer { + public var peer: Api.Peer + public init(peer: Api.Peer) { + self.peer = peer + } + } + case starsTransactionPeer(Cons_starsTransactionPeer) case starsTransactionPeerAPI case starsTransactionPeerAds case starsTransactionPeerAppStore @@ -450,89 +940,86 @@ public extension Api { case starsTransactionPeerPlayMarket case starsTransactionPeerPremiumBot case starsTransactionPeerUnsupported - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starsTransactionPeer(let peer): - if boxed { - buffer.appendInt32(-670195363) - } - peer.serialize(buffer, true) - break - case .starsTransactionPeerAPI: - if boxed { - buffer.appendInt32(-110658899) - } - - break - case .starsTransactionPeerAds: - if boxed { - buffer.appendInt32(1617438738) - } - - break - case .starsTransactionPeerAppStore: - if boxed { - buffer.appendInt32(-1269320843) - } - - break - case .starsTransactionPeerFragment: - if boxed { - buffer.appendInt32(-382740222) - } - - break - case .starsTransactionPeerPlayMarket: - if boxed { - buffer.appendInt32(2069236235) - } - - break - case .starsTransactionPeerPremiumBot: - if boxed { - buffer.appendInt32(621656824) - } - - break - case .starsTransactionPeerUnsupported: - if boxed { - buffer.appendInt32(-1779253276) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starsTransactionPeer(let peer): - return ("starsTransactionPeer", [("peer", peer as Any)]) - case .starsTransactionPeerAPI: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starsTransactionPeer(let _data): + if boxed { + buffer.appendInt32(-670195363) + } + _data.peer.serialize(buffer, true) + break + case .starsTransactionPeerAPI: + if boxed { + buffer.appendInt32(-110658899) + } + break + case .starsTransactionPeerAds: + if boxed { + buffer.appendInt32(1617438738) + } + break + case .starsTransactionPeerAppStore: + if boxed { + buffer.appendInt32(-1269320843) + } + break + case .starsTransactionPeerFragment: + if boxed { + buffer.appendInt32(-382740222) + } + break + case .starsTransactionPeerPlayMarket: + if boxed { + buffer.appendInt32(2069236235) + } + break + case .starsTransactionPeerPremiumBot: + if boxed { + buffer.appendInt32(621656824) + } + break + case .starsTransactionPeerUnsupported: + if boxed { + buffer.appendInt32(-1779253276) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starsTransactionPeer(let _data): + return ("starsTransactionPeer", [("peer", _data.peer as Any)]) + case .starsTransactionPeerAPI: return ("starsTransactionPeerAPI", []) - case .starsTransactionPeerAds: + case .starsTransactionPeerAds: return ("starsTransactionPeerAds", []) - case .starsTransactionPeerAppStore: + case .starsTransactionPeerAppStore: return ("starsTransactionPeerAppStore", []) - case .starsTransactionPeerFragment: + case .starsTransactionPeerFragment: return ("starsTransactionPeerFragment", []) - case .starsTransactionPeerPlayMarket: + case .starsTransactionPeerPlayMarket: return ("starsTransactionPeerPlayMarket", []) - case .starsTransactionPeerPremiumBot: + case .starsTransactionPeerPremiumBot: return ("starsTransactionPeerPremiumBot", []) - case .starsTransactionPeerUnsupported: + case .starsTransactionPeerUnsupported: return ("starsTransactionPeerUnsupported", []) - } - } - + } + } + public static func parse_starsTransactionPeer(_ reader: BufferReader) -> StarsTransactionPeer? { var _1: Api.Peer? if let signature = reader.readInt32() { _1 = Api.parse(reader, signature: signature) as? Api.Peer } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.StarsTransactionPeer.starsTransactionPeer(peer: _1!) + if _c1 { + return Api.StarsTransactionPeer.starsTransactionPeer(Cons_starsTransactionPeer(peer: _1!)) + } + else { + return nil + } } public static func parse_starsTransactionPeerAPI(_ reader: BufferReader) -> StarsTransactionPeer? { return Api.StarsTransactionPeer.starsTransactionPeerAPI @@ -555,32 +1042,39 @@ public extension Api { public static func parse_starsTransactionPeerUnsupported(_ reader: BufferReader) -> StarsTransactionPeer? { return Api.StarsTransactionPeer.starsTransactionPeerUnsupported } - } } public extension Api { enum StatsAbsValueAndPrev: TypeConstructorDescription { - case statsAbsValueAndPrev(current: Double, previous: Double) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .statsAbsValueAndPrev(let current, let previous): - if boxed { - buffer.appendInt32(-884757282) - } - serializeDouble(current, buffer: buffer, boxed: false) - serializeDouble(previous, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .statsAbsValueAndPrev(let current, let previous): - return ("statsAbsValueAndPrev", [("current", current as Any), ("previous", previous as Any)]) - } - } - + public class Cons_statsAbsValueAndPrev { + public var current: Double + public var previous: Double + public init(current: Double, previous: Double) { + self.current = current + self.previous = previous + } + } + case statsAbsValueAndPrev(Cons_statsAbsValueAndPrev) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .statsAbsValueAndPrev(let _data): + if boxed { + buffer.appendInt32(-884757282) + } + serializeDouble(_data.current, buffer: buffer, boxed: false) + serializeDouble(_data.previous, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .statsAbsValueAndPrev(let _data): + return ("statsAbsValueAndPrev", [("current", _data.current as Any), ("previous", _data.previous as Any)]) + } + } + public static func parse_statsAbsValueAndPrev(_ reader: BufferReader) -> StatsAbsValueAndPrev? { var _1: Double? _1 = reader.readDouble() @@ -588,36 +1082,46 @@ public extension Api { _2 = reader.readDouble() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.StatsAbsValueAndPrev.statsAbsValueAndPrev(current: _1!, previous: _2!) + if _c1 && _c2 { + return Api.StatsAbsValueAndPrev.statsAbsValueAndPrev(Cons_statsAbsValueAndPrev(current: _1!, previous: _2!)) + } + else { + return nil + } } - } } public extension Api { enum StatsDateRangeDays: TypeConstructorDescription { - case statsDateRangeDays(minDate: Int32, maxDate: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .statsDateRangeDays(let minDate, let maxDate): - if boxed { - buffer.appendInt32(-1237848657) - } - serializeInt32(minDate, buffer: buffer, boxed: false) - serializeInt32(maxDate, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .statsDateRangeDays(let minDate, let maxDate): - return ("statsDateRangeDays", [("minDate", minDate as Any), ("maxDate", maxDate as Any)]) - } - } - + public class Cons_statsDateRangeDays { + public var minDate: Int32 + public var maxDate: Int32 + public init(minDate: Int32, maxDate: Int32) { + self.minDate = minDate + self.maxDate = maxDate + } + } + case statsDateRangeDays(Cons_statsDateRangeDays) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .statsDateRangeDays(let _data): + if boxed { + buffer.appendInt32(-1237848657) + } + serializeInt32(_data.minDate, buffer: buffer, boxed: false) + serializeInt32(_data.maxDate, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .statsDateRangeDays(let _data): + return ("statsDateRangeDays", [("minDate", _data.minDate as Any), ("maxDate", _data.maxDate as Any)]) + } + } + public static func parse_statsDateRangeDays(_ reader: BufferReader) -> StatsDateRangeDays? { var _1: Int32? _1 = reader.readInt32() @@ -625,55 +1129,81 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.StatsDateRangeDays.statsDateRangeDays(minDate: _1!, maxDate: _2!) + if _c1 && _c2 { + return Api.StatsDateRangeDays.statsDateRangeDays(Cons_statsDateRangeDays(minDate: _1!, maxDate: _2!)) + } + else { + return nil + } } - } } public extension Api { enum StatsGraph: TypeConstructorDescription { - case statsGraph(flags: Int32, json: Api.DataJSON, zoomToken: String?) - case statsGraphAsync(token: String) - case statsGraphError(error: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .statsGraph(let flags, let json, let zoomToken): - if boxed { - buffer.appendInt32(-1901828938) - } - serializeInt32(flags, buffer: buffer, boxed: false) - json.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeString(zoomToken!, buffer: buffer, boxed: false)} - break - case .statsGraphAsync(let token): - if boxed { - buffer.appendInt32(1244130093) - } - serializeString(token, buffer: buffer, boxed: false) - break - case .statsGraphError(let error): - if boxed { - buffer.appendInt32(-1092839390) - } - serializeString(error, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .statsGraph(let flags, let json, let zoomToken): - return ("statsGraph", [("flags", flags as Any), ("json", json as Any), ("zoomToken", zoomToken as Any)]) - case .statsGraphAsync(let token): - return ("statsGraphAsync", [("token", token as Any)]) - case .statsGraphError(let error): - return ("statsGraphError", [("error", error as Any)]) - } - } - + public class Cons_statsGraph { + public var flags: Int32 + public var json: Api.DataJSON + public var zoomToken: String? + public init(flags: Int32, json: Api.DataJSON, zoomToken: String?) { + self.flags = flags + self.json = json + self.zoomToken = zoomToken + } + } + public class Cons_statsGraphAsync { + public var token: String + public init(token: String) { + self.token = token + } + } + public class Cons_statsGraphError { + public var error: String + public init(error: String) { + self.error = error + } + } + case statsGraph(Cons_statsGraph) + case statsGraphAsync(Cons_statsGraphAsync) + case statsGraphError(Cons_statsGraphError) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .statsGraph(let _data): + if boxed { + buffer.appendInt32(-1901828938) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.json.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.zoomToken!, buffer: buffer, boxed: false) + } + break + case .statsGraphAsync(let _data): + if boxed { + buffer.appendInt32(1244130093) + } + serializeString(_data.token, buffer: buffer, boxed: false) + break + case .statsGraphError(let _data): + if boxed { + buffer.appendInt32(-1092839390) + } + serializeString(_data.error, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .statsGraph(let _data): + return ("statsGraph", [("flags", _data.flags as Any), ("json", _data.json as Any), ("zoomToken", _data.zoomToken as Any)]) + case .statsGraphAsync(let _data): + return ("statsGraphAsync", [("token", _data.token as Any)]) + case .statsGraphError(let _data): + return ("statsGraphError", [("error", _data.error as Any)]) + } + } + public static func parse_statsGraph(_ reader: BufferReader) -> StatsGraph? { var _1: Int32? _1 = reader.readInt32() @@ -682,57 +1212,80 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.DataJSON } var _3: String? - if Int(_1!) & Int(1 << 0) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.StatsGraph.statsGraph(flags: _1!, json: _2!, zoomToken: _3) + if _c1 && _c2 && _c3 { + return Api.StatsGraph.statsGraph(Cons_statsGraph(flags: _1!, json: _2!, zoomToken: _3)) + } + else { + return nil + } } public static func parse_statsGraphAsync(_ reader: BufferReader) -> StatsGraph? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.StatsGraph.statsGraphAsync(token: _1!) + if _c1 { + return Api.StatsGraph.statsGraphAsync(Cons_statsGraphAsync(token: _1!)) + } + else { + return nil + } } public static func parse_statsGraphError(_ reader: BufferReader) -> StatsGraph? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.StatsGraph.statsGraphError(error: _1!) + if _c1 { + return Api.StatsGraph.statsGraphError(Cons_statsGraphError(error: _1!)) + } + else { + return nil + } } - } } public extension Api { enum StatsGroupTopAdmin: TypeConstructorDescription { - case statsGroupTopAdmin(userId: Int64, deleted: Int32, kicked: Int32, banned: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .statsGroupTopAdmin(let userId, let deleted, let kicked, let banned): - if boxed { - buffer.appendInt32(-682079097) - } - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt32(deleted, buffer: buffer, boxed: false) - serializeInt32(kicked, buffer: buffer, boxed: false) - serializeInt32(banned, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .statsGroupTopAdmin(let userId, let deleted, let kicked, let banned): - return ("statsGroupTopAdmin", [("userId", userId as Any), ("deleted", deleted as Any), ("kicked", kicked as Any), ("banned", banned as Any)]) - } - } - + public class Cons_statsGroupTopAdmin { + public var userId: Int64 + public var deleted: Int32 + public var kicked: Int32 + public var banned: Int32 + public init(userId: Int64, deleted: Int32, kicked: Int32, banned: Int32) { + self.userId = userId + self.deleted = deleted + self.kicked = kicked + self.banned = banned + } + } + case statsGroupTopAdmin(Cons_statsGroupTopAdmin) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .statsGroupTopAdmin(let _data): + if boxed { + buffer.appendInt32(-682079097) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt32(_data.deleted, buffer: buffer, boxed: false) + serializeInt32(_data.kicked, buffer: buffer, boxed: false) + serializeInt32(_data.banned, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .statsGroupTopAdmin(let _data): + return ("statsGroupTopAdmin", [("userId", _data.userId as Any), ("deleted", _data.deleted as Any), ("kicked", _data.kicked as Any), ("banned", _data.banned as Any)]) + } + } + public static func parse_statsGroupTopAdmin(_ reader: BufferReader) -> StatsGroupTopAdmin? { var _1: Int64? _1 = reader.readInt64() @@ -746,38 +1299,46 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.StatsGroupTopAdmin.statsGroupTopAdmin(userId: _1!, deleted: _2!, kicked: _3!, banned: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.StatsGroupTopAdmin.statsGroupTopAdmin(Cons_statsGroupTopAdmin(userId: _1!, deleted: _2!, kicked: _3!, banned: _4!)) + } + else { + return nil + } } - } } public extension Api { enum StatsGroupTopInviter: TypeConstructorDescription { - case statsGroupTopInviter(userId: Int64, invitations: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .statsGroupTopInviter(let userId, let invitations): - if boxed { - buffer.appendInt32(1398765469) - } - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt32(invitations, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .statsGroupTopInviter(let userId, let invitations): - return ("statsGroupTopInviter", [("userId", userId as Any), ("invitations", invitations as Any)]) - } - } - + public class Cons_statsGroupTopInviter { + public var userId: Int64 + public var invitations: Int32 + public init(userId: Int64, invitations: Int32) { + self.userId = userId + self.invitations = invitations + } + } + case statsGroupTopInviter(Cons_statsGroupTopInviter) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .statsGroupTopInviter(let _data): + if boxed { + buffer.appendInt32(1398765469) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt32(_data.invitations, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .statsGroupTopInviter(let _data): + return ("statsGroupTopInviter", [("userId", _data.userId as Any), ("invitations", _data.invitations as Any)]) + } + } + public static func parse_statsGroupTopInviter(_ reader: BufferReader) -> StatsGroupTopInviter? { var _1: Int64? _1 = reader.readInt64() @@ -785,37 +1346,49 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.StatsGroupTopInviter.statsGroupTopInviter(userId: _1!, invitations: _2!) + if _c1 && _c2 { + return Api.StatsGroupTopInviter.statsGroupTopInviter(Cons_statsGroupTopInviter(userId: _1!, invitations: _2!)) + } + else { + return nil + } } - } } public extension Api { enum StatsGroupTopPoster: TypeConstructorDescription { - case statsGroupTopPoster(userId: Int64, messages: Int32, avgChars: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .statsGroupTopPoster(let userId, let messages, let avgChars): - if boxed { - buffer.appendInt32(-1660637285) - } - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt32(messages, buffer: buffer, boxed: false) - serializeInt32(avgChars, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .statsGroupTopPoster(let userId, let messages, let avgChars): - return ("statsGroupTopPoster", [("userId", userId as Any), ("messages", messages as Any), ("avgChars", avgChars as Any)]) - } - } - + public class Cons_statsGroupTopPoster { + public var userId: Int64 + public var messages: Int32 + public var avgChars: Int32 + public init(userId: Int64, messages: Int32, avgChars: Int32) { + self.userId = userId + self.messages = messages + self.avgChars = avgChars + } + } + case statsGroupTopPoster(Cons_statsGroupTopPoster) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .statsGroupTopPoster(let _data): + if boxed { + buffer.appendInt32(-1660637285) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt32(_data.messages, buffer: buffer, boxed: false) + serializeInt32(_data.avgChars, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .statsGroupTopPoster(let _data): + return ("statsGroupTopPoster", [("userId", _data.userId as Any), ("messages", _data.messages as Any), ("avgChars", _data.avgChars as Any)]) + } + } + public static func parse_statsGroupTopPoster(_ reader: BufferReader) -> StatsGroupTopPoster? { var _1: Int64? _1 = reader.readInt64() @@ -826,37 +1399,46 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.StatsGroupTopPoster.statsGroupTopPoster(userId: _1!, messages: _2!, avgChars: _3!) + if _c1 && _c2 && _c3 { + return Api.StatsGroupTopPoster.statsGroupTopPoster(Cons_statsGroupTopPoster(userId: _1!, messages: _2!, avgChars: _3!)) + } + else { + return nil + } } - } } public extension Api { enum StatsPercentValue: TypeConstructorDescription { - case statsPercentValue(part: Double, total: Double) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .statsPercentValue(let part, let total): - if boxed { - buffer.appendInt32(-875679776) - } - serializeDouble(part, buffer: buffer, boxed: false) - serializeDouble(total, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .statsPercentValue(let part, let total): - return ("statsPercentValue", [("part", part as Any), ("total", total as Any)]) - } - } - + public class Cons_statsPercentValue { + public var part: Double + public var total: Double + public init(part: Double, total: Double) { + self.part = part + self.total = total + } + } + case statsPercentValue(Cons_statsPercentValue) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .statsPercentValue(let _data): + if boxed { + buffer.appendInt32(-875679776) + } + serializeDouble(_data.part, buffer: buffer, boxed: false) + serializeDouble(_data.total, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .statsPercentValue(let _data): + return ("statsPercentValue", [("part", _data.part as Any), ("total", _data.total as Any)]) + } + } + public static func parse_statsPercentValue(_ reader: BufferReader) -> StatsPercentValue? { var _1: Double? _1 = reader.readDouble() @@ -864,72 +1446,91 @@ public extension Api { _2 = reader.readDouble() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.StatsPercentValue.statsPercentValue(part: _1!, total: _2!) + if _c1 && _c2 { + return Api.StatsPercentValue.statsPercentValue(Cons_statsPercentValue(part: _1!, total: _2!)) + } + else { + return nil + } } - } } public extension Api { enum StatsURL: TypeConstructorDescription { - case statsURL(url: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .statsURL(let url): - if boxed { - buffer.appendInt32(1202287072) - } - serializeString(url, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .statsURL(let url): - return ("statsURL", [("url", url as Any)]) - } - } - + public class Cons_statsURL { + public var url: String + public init(url: String) { + self.url = url + } + } + case statsURL(Cons_statsURL) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .statsURL(let _data): + if boxed { + buffer.appendInt32(1202287072) + } + serializeString(_data.url, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .statsURL(let _data): + return ("statsURL", [("url", _data.url as Any)]) + } + } + public static func parse_statsURL(_ reader: BufferReader) -> StatsURL? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.StatsURL.statsURL(url: _1!) + if _c1 { + return Api.StatsURL.statsURL(Cons_statsURL(url: _1!)) + } + else { + return nil + } } - } } public extension Api { enum StickerKeyword: TypeConstructorDescription { - case stickerKeyword(documentId: Int64, keyword: [String]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .stickerKeyword(let documentId, let keyword): - if boxed { - buffer.appendInt32(-50416996) - } - serializeInt64(documentId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(keyword.count)) - for item in keyword { - serializeString(item, buffer: buffer, boxed: false) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .stickerKeyword(let documentId, let keyword): - return ("stickerKeyword", [("documentId", documentId as Any), ("keyword", keyword as Any)]) - } - } - + public class Cons_stickerKeyword { + public var documentId: Int64 + public var keyword: [String] + public init(documentId: Int64, keyword: [String]) { + self.documentId = documentId + self.keyword = keyword + } + } + case stickerKeyword(Cons_stickerKeyword) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .stickerKeyword(let _data): + if boxed { + buffer.appendInt32(-50416996) + } + serializeInt64(_data.documentId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.keyword.count)) + for item in _data.keyword { + serializeString(item, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .stickerKeyword(let _data): + return ("stickerKeyword", [("documentId", _data.documentId as Any), ("keyword", _data.keyword as Any)]) + } + } + public static func parse_stickerKeyword(_ reader: BufferReader) -> StickerKeyword? { var _1: Int64? _1 = reader.readInt64() @@ -939,40 +1540,50 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.StickerKeyword.stickerKeyword(documentId: _1!, keyword: _2!) + if _c1 && _c2 { + return Api.StickerKeyword.stickerKeyword(Cons_stickerKeyword(documentId: _1!, keyword: _2!)) + } + else { + return nil + } } - } } public extension Api { enum StickerPack: TypeConstructorDescription { - case stickerPack(emoticon: String, documents: [Int64]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .stickerPack(let emoticon, let documents): - if boxed { - buffer.appendInt32(313694676) - } - serializeString(emoticon, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(documents.count)) - for item in documents { - serializeInt64(item, buffer: buffer, boxed: false) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .stickerPack(let emoticon, let documents): - return ("stickerPack", [("emoticon", emoticon as Any), ("documents", documents as Any)]) - } - } - + public class Cons_stickerPack { + public var emoticon: String + public var documents: [Int64] + public init(emoticon: String, documents: [Int64]) { + self.emoticon = emoticon + self.documents = documents + } + } + case stickerPack(Cons_stickerPack) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .stickerPack(let _data): + if boxed { + buffer.appendInt32(313694676) + } + serializeString(_data.emoticon, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.documents.count)) + for item in _data.documents { + serializeInt64(item, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .stickerPack(let _data): + return ("stickerPack", [("emoticon", _data.emoticon as Any), ("documents", _data.documents as Any)]) + } + } + public static func parse_stickerPack(_ reader: BufferReader) -> StickerPack? { var _1: String? _1 = parseString(reader) @@ -982,55 +1593,97 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.StickerPack.stickerPack(emoticon: _1!, documents: _2!) + if _c1 && _c2 { + return Api.StickerPack.stickerPack(Cons_stickerPack(emoticon: _1!, documents: _2!)) + } + else { + return nil + } } - } } public extension Api { enum StickerSet: TypeConstructorDescription { - case stickerSet(flags: Int32, installedDate: Int32?, id: Int64, accessHash: Int64, title: String, shortName: String, thumbs: [Api.PhotoSize]?, thumbDcId: Int32?, thumbVersion: Int32?, thumbDocumentId: Int64?, count: Int32, hash: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .stickerSet(let flags, let installedDate, let id, let accessHash, let title, let shortName, let thumbs, let thumbDcId, let thumbVersion, let thumbDocumentId, let count, let hash): - if boxed { - buffer.appendInt32(768691932) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(installedDate!, buffer: buffer, boxed: false)} - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(shortName, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(thumbs!.count)) - for item in thumbs! { + public class Cons_stickerSet { + public var flags: Int32 + public var installedDate: Int32? + public var id: Int64 + public var accessHash: Int64 + public var title: String + public var shortName: String + public var thumbs: [Api.PhotoSize]? + public var thumbDcId: Int32? + public var thumbVersion: Int32? + public var thumbDocumentId: Int64? + public var count: Int32 + public var hash: Int32 + public init(flags: Int32, installedDate: Int32?, id: Int64, accessHash: Int64, title: String, shortName: String, thumbs: [Api.PhotoSize]?, thumbDcId: Int32?, thumbVersion: Int32?, thumbDocumentId: Int64?, count: Int32, hash: Int32) { + self.flags = flags + self.installedDate = installedDate + self.id = id + self.accessHash = accessHash + self.title = title + self.shortName = shortName + self.thumbs = thumbs + self.thumbDcId = thumbDcId + self.thumbVersion = thumbVersion + self.thumbDocumentId = thumbDocumentId + self.count = count + self.hash = hash + } + } + case stickerSet(Cons_stickerSet) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .stickerSet(let _data): + if boxed { + buffer.appendInt32(768691932) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.installedDate!, buffer: buffer, boxed: false) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.shortName, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 4) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.thumbs!.count)) + for item in _data.thumbs! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(thumbDcId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(thumbVersion!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {serializeInt64(thumbDocumentId!, buffer: buffer, boxed: false)} - serializeInt32(count, buffer: buffer, boxed: false) - serializeInt32(hash, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .stickerSet(let flags, let installedDate, let id, let accessHash, let title, let shortName, let thumbs, let thumbDcId, let thumbVersion, let thumbDocumentId, let count, let hash): - return ("stickerSet", [("flags", flags as Any), ("installedDate", installedDate as Any), ("id", id as Any), ("accessHash", accessHash as Any), ("title", title as Any), ("shortName", shortName as Any), ("thumbs", thumbs as Any), ("thumbDcId", thumbDcId as Any), ("thumbVersion", thumbVersion as Any), ("thumbDocumentId", thumbDocumentId as Any), ("count", count as Any), ("hash", hash as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.thumbDcId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.thumbVersion!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + serializeInt64(_data.thumbDocumentId!, buffer: buffer, boxed: false) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + serializeInt32(_data.hash, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .stickerSet(let _data): + return ("stickerSet", [("flags", _data.flags as Any), ("installedDate", _data.installedDate as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("title", _data.title as Any), ("shortName", _data.shortName as Any), ("thumbs", _data.thumbs as Any), ("thumbDcId", _data.thumbDcId as Any), ("thumbVersion", _data.thumbVersion as Any), ("thumbDocumentId", _data.thumbDocumentId as Any), ("count", _data.count as Any), ("hash", _data.hash as Any)]) + } + } + public static func parse_stickerSet(_ reader: BufferReader) -> StickerSet? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt32() + } var _3: Int64? _3 = reader.readInt64() var _4: Int64? @@ -1040,15 +1693,23 @@ public extension Api { var _6: String? _6 = parseString(reader) var _7: [Api.PhotoSize]? - if Int(_1!) & Int(1 << 4) != 0 {if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PhotoSize.self) - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PhotoSize.self) + } + } var _8: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_8 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _8 = reader.readInt32() + } var _9: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_9 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _9 = reader.readInt32() + } var _10: Int64? - if Int(_1!) & Int(1 << 8) != 0 {_10 = reader.readInt64() } + if Int(_1!) & Int(1 << 8) != 0 { + _10 = reader.readInt64() + } var _11: Int32? _11 = reader.readInt32() var _12: Int32? @@ -1065,201 +1726,12 @@ public extension Api { let _c10 = (Int(_1!) & Int(1 << 8) == 0) || _10 != nil let _c11 = _11 != nil let _c12 = _12 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - return Api.StickerSet.stickerSet(flags: _1!, installedDate: _2, id: _3!, accessHash: _4!, title: _5!, shortName: _6!, thumbs: _7, thumbDcId: _8, thumbVersion: _9, thumbDocumentId: _10, count: _11!, hash: _12!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 { + return Api.StickerSet.stickerSet(Cons_stickerSet(flags: _1!, installedDate: _2, id: _3!, accessHash: _4!, title: _5!, shortName: _6!, thumbs: _7, thumbDcId: _8, thumbVersion: _9, thumbDocumentId: _10, count: _11!, hash: _12!)) + } + else { + return nil + } } - - } -} -public extension Api { - enum StickerSetCovered: TypeConstructorDescription { - case stickerSetCovered(set: Api.StickerSet, cover: Api.Document) - case stickerSetFullCovered(set: Api.StickerSet, packs: [Api.StickerPack], keywords: [Api.StickerKeyword], documents: [Api.Document]) - case stickerSetMultiCovered(set: Api.StickerSet, covers: [Api.Document]) - case stickerSetNoCovered(set: Api.StickerSet) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .stickerSetCovered(let set, let cover): - if boxed { - buffer.appendInt32(1678812626) - } - set.serialize(buffer, true) - cover.serialize(buffer, true) - break - case .stickerSetFullCovered(let set, let packs, let keywords, let documents): - if boxed { - buffer.appendInt32(1087454222) - } - set.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(packs.count)) - for item in packs { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(keywords.count)) - for item in keywords { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(documents.count)) - for item in documents { - item.serialize(buffer, true) - } - break - case .stickerSetMultiCovered(let set, let covers): - if boxed { - buffer.appendInt32(872932635) - } - set.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(covers.count)) - for item in covers { - item.serialize(buffer, true) - } - break - case .stickerSetNoCovered(let set): - if boxed { - buffer.appendInt32(2008112412) - } - set.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .stickerSetCovered(let set, let cover): - return ("stickerSetCovered", [("set", set as Any), ("cover", cover as Any)]) - case .stickerSetFullCovered(let set, let packs, let keywords, let documents): - return ("stickerSetFullCovered", [("set", set as Any), ("packs", packs as Any), ("keywords", keywords as Any), ("documents", documents as Any)]) - case .stickerSetMultiCovered(let set, let covers): - return ("stickerSetMultiCovered", [("set", set as Any), ("covers", covers as Any)]) - case .stickerSetNoCovered(let set): - return ("stickerSetNoCovered", [("set", set as Any)]) - } - } - - public static func parse_stickerSetCovered(_ reader: BufferReader) -> StickerSetCovered? { - var _1: Api.StickerSet? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.StickerSet - } - var _2: Api.Document? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Document - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.StickerSetCovered.stickerSetCovered(set: _1!, cover: _2!) - } - public static func parse_stickerSetFullCovered(_ reader: BufferReader) -> StickerSetCovered? { - var _1: Api.StickerSet? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.StickerSet - } - var _2: [Api.StickerPack]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerPack.self) - } - var _3: [Api.StickerKeyword]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerKeyword.self) - } - var _4: [Api.Document]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.StickerSetCovered.stickerSetFullCovered(set: _1!, packs: _2!, keywords: _3!, documents: _4!) - } - public static func parse_stickerSetMultiCovered(_ reader: BufferReader) -> StickerSetCovered? { - var _1: Api.StickerSet? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.StickerSet - } - var _2: [Api.Document]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.StickerSetCovered.stickerSetMultiCovered(set: _1!, covers: _2!) - } - public static func parse_stickerSetNoCovered(_ reader: BufferReader) -> StickerSetCovered? { - var _1: Api.StickerSet? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.StickerSet - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.StickerSetCovered.stickerSetNoCovered(set: _1!) - } - - } -} -public extension Api { - enum StoriesStealthMode: TypeConstructorDescription { - case storiesStealthMode(flags: Int32, activeUntilDate: Int32?, cooldownUntilDate: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .storiesStealthMode(let flags, let activeUntilDate, let cooldownUntilDate): - if boxed { - buffer.appendInt32(1898850301) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(activeUntilDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(cooldownUntilDate!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .storiesStealthMode(let flags, let activeUntilDate, let cooldownUntilDate): - return ("storiesStealthMode", [("flags", flags as Any), ("activeUntilDate", activeUntilDate as Any), ("cooldownUntilDate", cooldownUntilDate as Any)]) - } - } - - public static func parse_storiesStealthMode(_ reader: BufferReader) -> StoriesStealthMode? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt32() } - var _3: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_3 = reader.readInt32() } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.StoriesStealthMode.storiesStealthMode(flags: _1!, activeUntilDate: _2, cooldownUntilDate: _3) - } - } } diff --git a/submodules/TelegramApi/Sources/Api27.swift b/submodules/TelegramApi/Sources/Api27.swift index 12cbc688..395ba65b 100644 --- a/submodules/TelegramApi/Sources/Api27.swift +++ b/submodules/TelegramApi/Sources/Api27.swift @@ -1,29 +1,291 @@ +public extension Api { + enum StickerSetCovered: TypeConstructorDescription { + public class Cons_stickerSetCovered { + public var set: Api.StickerSet + public var cover: Api.Document + public init(set: Api.StickerSet, cover: Api.Document) { + self.set = set + self.cover = cover + } + } + public class Cons_stickerSetFullCovered { + public var set: Api.StickerSet + public var packs: [Api.StickerPack] + public var keywords: [Api.StickerKeyword] + public var documents: [Api.Document] + public init(set: Api.StickerSet, packs: [Api.StickerPack], keywords: [Api.StickerKeyword], documents: [Api.Document]) { + self.set = set + self.packs = packs + self.keywords = keywords + self.documents = documents + } + } + public class Cons_stickerSetMultiCovered { + public var set: Api.StickerSet + public var covers: [Api.Document] + public init(set: Api.StickerSet, covers: [Api.Document]) { + self.set = set + self.covers = covers + } + } + public class Cons_stickerSetNoCovered { + public var set: Api.StickerSet + public init(set: Api.StickerSet) { + self.set = set + } + } + case stickerSetCovered(Cons_stickerSetCovered) + case stickerSetFullCovered(Cons_stickerSetFullCovered) + case stickerSetMultiCovered(Cons_stickerSetMultiCovered) + case stickerSetNoCovered(Cons_stickerSetNoCovered) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .stickerSetCovered(let _data): + if boxed { + buffer.appendInt32(1678812626) + } + _data.set.serialize(buffer, true) + _data.cover.serialize(buffer, true) + break + case .stickerSetFullCovered(let _data): + if boxed { + buffer.appendInt32(1087454222) + } + _data.set.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.packs.count)) + for item in _data.packs { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.keywords.count)) + for item in _data.keywords { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.documents.count)) + for item in _data.documents { + item.serialize(buffer, true) + } + break + case .stickerSetMultiCovered(let _data): + if boxed { + buffer.appendInt32(872932635) + } + _data.set.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.covers.count)) + for item in _data.covers { + item.serialize(buffer, true) + } + break + case .stickerSetNoCovered(let _data): + if boxed { + buffer.appendInt32(2008112412) + } + _data.set.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .stickerSetCovered(let _data): + return ("stickerSetCovered", [("set", _data.set as Any), ("cover", _data.cover as Any)]) + case .stickerSetFullCovered(let _data): + return ("stickerSetFullCovered", [("set", _data.set as Any), ("packs", _data.packs as Any), ("keywords", _data.keywords as Any), ("documents", _data.documents as Any)]) + case .stickerSetMultiCovered(let _data): + return ("stickerSetMultiCovered", [("set", _data.set as Any), ("covers", _data.covers as Any)]) + case .stickerSetNoCovered(let _data): + return ("stickerSetNoCovered", [("set", _data.set as Any)]) + } + } + + public static func parse_stickerSetCovered(_ reader: BufferReader) -> StickerSetCovered? { + var _1: Api.StickerSet? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.StickerSet + } + var _2: Api.Document? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Document + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.StickerSetCovered.stickerSetCovered(Cons_stickerSetCovered(set: _1!, cover: _2!)) + } + else { + return nil + } + } + public static func parse_stickerSetFullCovered(_ reader: BufferReader) -> StickerSetCovered? { + var _1: Api.StickerSet? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.StickerSet + } + var _2: [Api.StickerPack]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerPack.self) + } + var _3: [Api.StickerKeyword]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerKeyword.self) + } + var _4: [Api.Document]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.StickerSetCovered.stickerSetFullCovered(Cons_stickerSetFullCovered(set: _1!, packs: _2!, keywords: _3!, documents: _4!)) + } + else { + return nil + } + } + public static func parse_stickerSetMultiCovered(_ reader: BufferReader) -> StickerSetCovered? { + var _1: Api.StickerSet? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.StickerSet + } + var _2: [Api.Document]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.StickerSetCovered.stickerSetMultiCovered(Cons_stickerSetMultiCovered(set: _1!, covers: _2!)) + } + else { + return nil + } + } + public static func parse_stickerSetNoCovered(_ reader: BufferReader) -> StickerSetCovered? { + var _1: Api.StickerSet? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.StickerSet + } + let _c1 = _1 != nil + if _c1 { + return Api.StickerSetCovered.stickerSetNoCovered(Cons_stickerSetNoCovered(set: _1!)) + } + else { + return nil + } + } + } +} +public extension Api { + enum StoriesStealthMode: TypeConstructorDescription { + public class Cons_storiesStealthMode { + public var flags: Int32 + public var activeUntilDate: Int32? + public var cooldownUntilDate: Int32? + public init(flags: Int32, activeUntilDate: Int32?, cooldownUntilDate: Int32?) { + self.flags = flags + self.activeUntilDate = activeUntilDate + self.cooldownUntilDate = cooldownUntilDate + } + } + case storiesStealthMode(Cons_storiesStealthMode) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .storiesStealthMode(let _data): + if boxed { + buffer.appendInt32(1898850301) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.activeUntilDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.cooldownUntilDate!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .storiesStealthMode(let _data): + return ("storiesStealthMode", [("flags", _data.flags as Any), ("activeUntilDate", _data.activeUntilDate as Any), ("cooldownUntilDate", _data.cooldownUntilDate as Any)]) + } + } + + public static func parse_storiesStealthMode(_ reader: BufferReader) -> StoriesStealthMode? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt32() + } + var _3: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _3 = reader.readInt32() + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil + if _c1 && _c2 && _c3 { + return Api.StoriesStealthMode.storiesStealthMode(Cons_storiesStealthMode(flags: _1!, activeUntilDate: _2, cooldownUntilDate: _3)) + } + else { + return nil + } + } + } +} public extension Api { enum StoryAlbum: TypeConstructorDescription { - case storyAlbum(flags: Int32, albumId: Int32, title: String, iconPhoto: Api.Photo?, iconVideo: Api.Document?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .storyAlbum(let flags, let albumId, let title, let iconPhoto, let iconVideo): - if boxed { - buffer.appendInt32(-1826262950) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(albumId, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {iconPhoto!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {iconVideo!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .storyAlbum(let flags, let albumId, let title, let iconPhoto, let iconVideo): - return ("storyAlbum", [("flags", flags as Any), ("albumId", albumId as Any), ("title", title as Any), ("iconPhoto", iconPhoto as Any), ("iconVideo", iconVideo as Any)]) - } - } - + public class Cons_storyAlbum { + public var flags: Int32 + public var albumId: Int32 + public var title: String + public var iconPhoto: Api.Photo? + public var iconVideo: Api.Document? + public init(flags: Int32, albumId: Int32, title: String, iconPhoto: Api.Photo?, iconVideo: Api.Document?) { + self.flags = flags + self.albumId = albumId + self.title = title + self.iconPhoto = iconPhoto + self.iconVideo = iconVideo + } + } + case storyAlbum(Cons_storyAlbum) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .storyAlbum(let _data): + if boxed { + buffer.appendInt32(-1826262950) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.albumId, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.iconPhoto!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.iconVideo!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .storyAlbum(let _data): + return ("storyAlbum", [("flags", _data.flags as Any), ("albumId", _data.albumId as Any), ("title", _data.title as Any), ("iconPhoto", _data.iconPhoto as Any), ("iconVideo", _data.iconVideo as Any)]) + } + } + public static func parse_storyAlbum(_ reader: BufferReader) -> StoryAlbum? { var _1: Int32? _1 = reader.readInt32() @@ -32,149 +294,244 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: Api.Photo? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Photo - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Photo + } + } var _5: Api.Document? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.Document - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.Document + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.StoryAlbum.storyAlbum(flags: _1!, albumId: _2!, title: _3!, iconPhoto: _4, iconVideo: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.StoryAlbum.storyAlbum(Cons_storyAlbum(flags: _1!, albumId: _2!, title: _3!, iconPhoto: _4, iconVideo: _5)) + } + else { + return nil + } } - } } public extension Api { enum StoryFwdHeader: TypeConstructorDescription { - case storyFwdHeader(flags: Int32, from: Api.Peer?, fromName: String?, storyId: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .storyFwdHeader(let flags, let from, let fromName, let storyId): - if boxed { - buffer.appendInt32(-1205411504) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {from!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(fromName!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(storyId!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .storyFwdHeader(let flags, let from, let fromName, let storyId): - return ("storyFwdHeader", [("flags", flags as Any), ("from", from as Any), ("fromName", fromName as Any), ("storyId", storyId as Any)]) - } - } - + public class Cons_storyFwdHeader { + public var flags: Int32 + public var from: Api.Peer? + public var fromName: String? + public var storyId: Int32? + public init(flags: Int32, from: Api.Peer?, fromName: String?, storyId: Int32?) { + self.flags = flags + self.from = from + self.fromName = fromName + self.storyId = storyId + } + } + case storyFwdHeader(Cons_storyFwdHeader) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .storyFwdHeader(let _data): + if boxed { + buffer.appendInt32(-1205411504) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.from!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.fromName!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.storyId!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .storyFwdHeader(let _data): + return ("storyFwdHeader", [("flags", _data.flags as Any), ("from", _data.from as Any), ("fromName", _data.fromName as Any), ("storyId", _data.storyId as Any)]) + } + } + public static func parse_storyFwdHeader(_ reader: BufferReader) -> StoryFwdHeader? { var _1: Int32? _1 = reader.readInt32() var _2: Api.Peer? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _3: String? - if Int(_1!) & Int(1 << 1) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _3 = parseString(reader) + } var _4: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _4 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.StoryFwdHeader.storyFwdHeader(flags: _1!, from: _2, fromName: _3, storyId: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.StoryFwdHeader.storyFwdHeader(Cons_storyFwdHeader(flags: _1!, from: _2, fromName: _3, storyId: _4)) + } + else { + return nil + } } - } } public extension Api { indirect enum StoryItem: TypeConstructorDescription { - case storyItem(flags: Int32, id: Int32, date: Int32, fromId: Api.Peer?, fwdFrom: Api.StoryFwdHeader?, expireDate: Int32, caption: String?, entities: [Api.MessageEntity]?, media: Api.MessageMedia, mediaAreas: [Api.MediaArea]?, privacy: [Api.PrivacyRule]?, views: Api.StoryViews?, sentReaction: Api.Reaction?, albums: [Int32]?) - case storyItemDeleted(id: Int32) - case storyItemSkipped(flags: Int32, id: Int32, date: Int32, expireDate: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .storyItem(let flags, let id, let date, let fromId, let fwdFrom, let expireDate, let caption, let entities, let media, let mediaAreas, let privacy, let views, let sentReaction, let albums): - if boxed { - buffer.appendInt32(-302947087) + public class Cons_storyItem { + public var flags: Int32 + public var id: Int32 + public var date: Int32 + public var fromId: Api.Peer? + public var fwdFrom: Api.StoryFwdHeader? + public var expireDate: Int32 + public var caption: String? + public var entities: [Api.MessageEntity]? + public var media: Api.MessageMedia + public var mediaAreas: [Api.MediaArea]? + public var privacy: [Api.PrivacyRule]? + public var views: Api.StoryViews? + public var sentReaction: Api.Reaction? + public var albums: [Int32]? + public init(flags: Int32, id: Int32, date: Int32, fromId: Api.Peer?, fwdFrom: Api.StoryFwdHeader?, expireDate: Int32, caption: String?, entities: [Api.MessageEntity]?, media: Api.MessageMedia, mediaAreas: [Api.MediaArea]?, privacy: [Api.PrivacyRule]?, views: Api.StoryViews?, sentReaction: Api.Reaction?, albums: [Int32]?) { + self.flags = flags + self.id = id + self.date = date + self.fromId = fromId + self.fwdFrom = fwdFrom + self.expireDate = expireDate + self.caption = caption + self.entities = entities + self.media = media + self.mediaAreas = mediaAreas + self.privacy = privacy + self.views = views + self.sentReaction = sentReaction + self.albums = albums + } + } + public class Cons_storyItemDeleted { + public var id: Int32 + public init(id: Int32) { + self.id = id + } + } + public class Cons_storyItemSkipped { + public var flags: Int32 + public var id: Int32 + public var date: Int32 + public var expireDate: Int32 + public init(flags: Int32, id: Int32, date: Int32, expireDate: Int32) { + self.flags = flags + self.id = id + self.date = date + self.expireDate = expireDate + } + } + case storyItem(Cons_storyItem) + case storyItemDeleted(Cons_storyItemDeleted) + case storyItemSkipped(Cons_storyItemSkipped) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .storyItem(let _data): + if boxed { + buffer.appendInt32(-302947087) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 18) != 0 { + _data.fromId!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 17) != 0 { + _data.fwdFrom!.serialize(buffer, true) + } + serializeInt32(_data.expireDate, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.caption!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { + item.serialize(buffer, true) } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 18) != 0 {fromId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 17) != 0 {fwdFrom!.serialize(buffer, true)} - serializeInt32(expireDate, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(caption!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { + } + _data.media.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 14) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.mediaAreas!.count)) + for item in _data.mediaAreas! { item.serialize(buffer, true) - }} - media.serialize(buffer, true) - if Int(flags) & Int(1 << 14) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(mediaAreas!.count)) - for item in mediaAreas! { + } + } + if Int(_data.flags) & Int(1 << 2) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.privacy!.count)) + for item in _data.privacy! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 2) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(privacy!.count)) - for item in privacy! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 3) != 0 {views!.serialize(buffer, true)} - if Int(flags) & Int(1 << 15) != 0 {sentReaction!.serialize(buffer, true)} - if Int(flags) & Int(1 << 19) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(albums!.count)) - for item in albums! { + } + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.views!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 15) != 0 { + _data.sentReaction!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 19) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.albums!.count)) + for item in _data.albums! { serializeInt32(item, buffer: buffer, boxed: false) - }} - break - case .storyItemDeleted(let id): - if boxed { - buffer.appendInt32(1374088783) } - serializeInt32(id, buffer: buffer, boxed: false) - break - case .storyItemSkipped(let flags, let id, let date, let expireDate): - if boxed { - buffer.appendInt32(-5388013) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt32(expireDate, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .storyItem(let flags, let id, let date, let fromId, let fwdFrom, let expireDate, let caption, let entities, let media, let mediaAreas, let privacy, let views, let sentReaction, let albums): - return ("storyItem", [("flags", flags as Any), ("id", id as Any), ("date", date as Any), ("fromId", fromId as Any), ("fwdFrom", fwdFrom as Any), ("expireDate", expireDate as Any), ("caption", caption as Any), ("entities", entities as Any), ("media", media as Any), ("mediaAreas", mediaAreas as Any), ("privacy", privacy as Any), ("views", views as Any), ("sentReaction", sentReaction as Any), ("albums", albums as Any)]) - case .storyItemDeleted(let id): - return ("storyItemDeleted", [("id", id as Any)]) - case .storyItemSkipped(let flags, let id, let date, let expireDate): - return ("storyItemSkipped", [("flags", flags as Any), ("id", id as Any), ("date", date as Any), ("expireDate", expireDate as Any)]) - } - } - + } + break + case .storyItemDeleted(let _data): + if boxed { + buffer.appendInt32(1374088783) + } + serializeInt32(_data.id, buffer: buffer, boxed: false) + break + case .storyItemSkipped(let _data): + if boxed { + buffer.appendInt32(-5388013) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt32(_data.expireDate, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .storyItem(let _data): + return ("storyItem", [("flags", _data.flags as Any), ("id", _data.id as Any), ("date", _data.date as Any), ("fromId", _data.fromId as Any), ("fwdFrom", _data.fwdFrom as Any), ("expireDate", _data.expireDate as Any), ("caption", _data.caption as Any), ("entities", _data.entities as Any), ("media", _data.media as Any), ("mediaAreas", _data.mediaAreas as Any), ("privacy", _data.privacy as Any), ("views", _data.views as Any), ("sentReaction", _data.sentReaction as Any), ("albums", _data.albums as Any)]) + case .storyItemDeleted(let _data): + return ("storyItemDeleted", [("id", _data.id as Any)]) + case .storyItemSkipped(let _data): + return ("storyItemSkipped", [("flags", _data.flags as Any), ("id", _data.id as Any), ("date", _data.date as Any), ("expireDate", _data.expireDate as Any)]) + } + } + public static func parse_storyItem(_ reader: BufferReader) -> StoryItem? { var _1: Int32? _1 = reader.readInt32() @@ -183,45 +540,63 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: Api.Peer? - if Int(_1!) & Int(1 << 18) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 18) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _5: Api.StoryFwdHeader? - if Int(_1!) & Int(1 << 17) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.StoryFwdHeader - } } + if Int(_1!) & Int(1 << 17) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.StoryFwdHeader + } + } var _6: Int32? _6 = reader.readInt32() var _7: String? - if Int(_1!) & Int(1 << 0) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _7 = parseString(reader) + } var _8: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } var _9: Api.MessageMedia? if let signature = reader.readInt32() { _9 = Api.parse(reader, signature: signature) as? Api.MessageMedia } var _10: [Api.MediaArea]? - if Int(_1!) & Int(1 << 14) != 0 {if let _ = reader.readInt32() { - _10 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MediaArea.self) - } } + if Int(_1!) & Int(1 << 14) != 0 { + if let _ = reader.readInt32() { + _10 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MediaArea.self) + } + } var _11: [Api.PrivacyRule]? - if Int(_1!) & Int(1 << 2) != 0 {if let _ = reader.readInt32() { - _11 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PrivacyRule.self) - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let _ = reader.readInt32() { + _11 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PrivacyRule.self) + } + } var _12: Api.StoryViews? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _12 = Api.parse(reader, signature: signature) as? Api.StoryViews - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _12 = Api.parse(reader, signature: signature) as? Api.StoryViews + } + } var _13: Api.Reaction? - if Int(_1!) & Int(1 << 15) != 0 {if let signature = reader.readInt32() { - _13 = Api.parse(reader, signature: signature) as? Api.Reaction - } } + if Int(_1!) & Int(1 << 15) != 0 { + if let signature = reader.readInt32() { + _13 = Api.parse(reader, signature: signature) as? Api.Reaction + } + } var _14: [Int32]? - if Int(_1!) & Int(1 << 19) != 0 {if let _ = reader.readInt32() { - _14 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } } + if Int(_1!) & Int(1 << 19) != 0 { + if let _ = reader.readInt32() { + _14 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -236,28 +611,23 @@ public extension Api { let _c12 = (Int(_1!) & Int(1 << 3) == 0) || _12 != nil let _c13 = (Int(_1!) & Int(1 << 15) == 0) || _13 != nil let _c14 = (Int(_1!) & Int(1 << 19) == 0) || _14 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - return Api.StoryItem.storyItem(flags: _1!, id: _2!, date: _3!, fromId: _4, fwdFrom: _5, expireDate: _6!, caption: _7, entities: _8, media: _9!, mediaAreas: _10, privacy: _11, views: _12, sentReaction: _13, albums: _14) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 { + return Api.StoryItem.storyItem(Cons_storyItem(flags: _1!, id: _2!, date: _3!, fromId: _4, fwdFrom: _5, expireDate: _6!, caption: _7, entities: _8, media: _9!, mediaAreas: _10, privacy: _11, views: _12, sentReaction: _13, albums: _14)) + } + else { + return nil + } } public static func parse_storyItemDeleted(_ reader: BufferReader) -> StoryItem? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.StoryItem.storyItemDeleted(id: _1!) + if _c1 { + return Api.StoryItem.storyItemDeleted(Cons_storyItemDeleted(id: _1!)) + } + else { + return nil + } } public static func parse_storyItemSkipped(_ reader: BufferReader) -> StoryItem? { var _1: Int32? @@ -272,58 +642,82 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.StoryItem.storyItemSkipped(flags: _1!, id: _2!, date: _3!, expireDate: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.StoryItem.storyItemSkipped(Cons_storyItemSkipped(flags: _1!, id: _2!, date: _3!, expireDate: _4!)) + } + else { + return nil + } } - } } public extension Api { indirect enum StoryReaction: TypeConstructorDescription { - case storyReaction(peerId: Api.Peer, date: Int32, reaction: Api.Reaction) - case storyReactionPublicForward(message: Api.Message) - case storyReactionPublicRepost(peerId: Api.Peer, story: Api.StoryItem) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .storyReaction(let peerId, let date, let reaction): - if boxed { - buffer.appendInt32(1620104917) - } - peerId.serialize(buffer, true) - serializeInt32(date, buffer: buffer, boxed: false) - reaction.serialize(buffer, true) - break - case .storyReactionPublicForward(let message): - if boxed { - buffer.appendInt32(-1146411453) - } - message.serialize(buffer, true) - break - case .storyReactionPublicRepost(let peerId, let story): - if boxed { - buffer.appendInt32(-808644845) - } - peerId.serialize(buffer, true) - story.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .storyReaction(let peerId, let date, let reaction): - return ("storyReaction", [("peerId", peerId as Any), ("date", date as Any), ("reaction", reaction as Any)]) - case .storyReactionPublicForward(let message): - return ("storyReactionPublicForward", [("message", message as Any)]) - case .storyReactionPublicRepost(let peerId, let story): - return ("storyReactionPublicRepost", [("peerId", peerId as Any), ("story", story as Any)]) - } - } - + public class Cons_storyReaction { + public var peerId: Api.Peer + public var date: Int32 + public var reaction: Api.Reaction + public init(peerId: Api.Peer, date: Int32, reaction: Api.Reaction) { + self.peerId = peerId + self.date = date + self.reaction = reaction + } + } + public class Cons_storyReactionPublicForward { + public var message: Api.Message + public init(message: Api.Message) { + self.message = message + } + } + public class Cons_storyReactionPublicRepost { + public var peerId: Api.Peer + public var story: Api.StoryItem + public init(peerId: Api.Peer, story: Api.StoryItem) { + self.peerId = peerId + self.story = story + } + } + case storyReaction(Cons_storyReaction) + case storyReactionPublicForward(Cons_storyReactionPublicForward) + case storyReactionPublicRepost(Cons_storyReactionPublicRepost) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .storyReaction(let _data): + if boxed { + buffer.appendInt32(1620104917) + } + _data.peerId.serialize(buffer, true) + serializeInt32(_data.date, buffer: buffer, boxed: false) + _data.reaction.serialize(buffer, true) + break + case .storyReactionPublicForward(let _data): + if boxed { + buffer.appendInt32(-1146411453) + } + _data.message.serialize(buffer, true) + break + case .storyReactionPublicRepost(let _data): + if boxed { + buffer.appendInt32(-808644845) + } + _data.peerId.serialize(buffer, true) + _data.story.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .storyReaction(let _data): + return ("storyReaction", [("peerId", _data.peerId as Any), ("date", _data.date as Any), ("reaction", _data.reaction as Any)]) + case .storyReactionPublicForward(let _data): + return ("storyReactionPublicForward", [("message", _data.message as Any)]) + case .storyReactionPublicRepost(let _data): + return ("storyReactionPublicRepost", [("peerId", _data.peerId as Any), ("story", _data.story as Any)]) + } + } + public static func parse_storyReaction(_ reader: BufferReader) -> StoryReaction? { var _1: Api.Peer? if let signature = reader.readInt32() { @@ -338,10 +732,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.StoryReaction.storyReaction(peerId: _1!, date: _2!, reaction: _3!) + if _c1 && _c2 && _c3 { + return Api.StoryReaction.storyReaction(Cons_storyReaction(peerId: _1!, date: _2!, reaction: _3!)) + } + else { + return nil + } } public static func parse_storyReactionPublicForward(_ reader: BufferReader) -> StoryReaction? { var _1: Api.Message? @@ -349,8 +745,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Message } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.StoryReaction.storyReactionPublicForward(message: _1!) + if _c1 { + return Api.StoryReaction.storyReactionPublicForward(Cons_storyReactionPublicForward(message: _1!)) + } + else { + return nil + } } public static func parse_storyReactionPublicRepost(_ reader: BufferReader) -> StoryReaction? { var _1: Api.Peer? @@ -363,59 +763,93 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.StoryReaction.storyReactionPublicRepost(peerId: _1!, story: _2!) + if _c1 && _c2 { + return Api.StoryReaction.storyReactionPublicRepost(Cons_storyReactionPublicRepost(peerId: _1!, story: _2!)) + } + else { + return nil + } } - } } public extension Api { indirect enum StoryView: TypeConstructorDescription { - case storyView(flags: Int32, userId: Int64, date: Int32, reaction: Api.Reaction?) - case storyViewPublicForward(flags: Int32, message: Api.Message) - case storyViewPublicRepost(flags: Int32, peerId: Api.Peer, story: Api.StoryItem) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .storyView(let flags, let userId, let date, let reaction): - if boxed { - buffer.appendInt32(-1329730875) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {reaction!.serialize(buffer, true)} - break - case .storyViewPublicForward(let flags, let message): - if boxed { - buffer.appendInt32(-1870436597) - } - serializeInt32(flags, buffer: buffer, boxed: false) - message.serialize(buffer, true) - break - case .storyViewPublicRepost(let flags, let peerId, let story): - if boxed { - buffer.appendInt32(-1116418231) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peerId.serialize(buffer, true) - story.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .storyView(let flags, let userId, let date, let reaction): - return ("storyView", [("flags", flags as Any), ("userId", userId as Any), ("date", date as Any), ("reaction", reaction as Any)]) - case .storyViewPublicForward(let flags, let message): - return ("storyViewPublicForward", [("flags", flags as Any), ("message", message as Any)]) - case .storyViewPublicRepost(let flags, let peerId, let story): - return ("storyViewPublicRepost", [("flags", flags as Any), ("peerId", peerId as Any), ("story", story as Any)]) - } - } - + public class Cons_storyView { + public var flags: Int32 + public var userId: Int64 + public var date: Int32 + public var reaction: Api.Reaction? + public init(flags: Int32, userId: Int64, date: Int32, reaction: Api.Reaction?) { + self.flags = flags + self.userId = userId + self.date = date + self.reaction = reaction + } + } + public class Cons_storyViewPublicForward { + public var flags: Int32 + public var message: Api.Message + public init(flags: Int32, message: Api.Message) { + self.flags = flags + self.message = message + } + } + public class Cons_storyViewPublicRepost { + public var flags: Int32 + public var peerId: Api.Peer + public var story: Api.StoryItem + public init(flags: Int32, peerId: Api.Peer, story: Api.StoryItem) { + self.flags = flags + self.peerId = peerId + self.story = story + } + } + case storyView(Cons_storyView) + case storyViewPublicForward(Cons_storyViewPublicForward) + case storyViewPublicRepost(Cons_storyViewPublicRepost) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .storyView(let _data): + if boxed { + buffer.appendInt32(-1329730875) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.reaction!.serialize(buffer, true) + } + break + case .storyViewPublicForward(let _data): + if boxed { + buffer.appendInt32(-1870436597) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.message.serialize(buffer, true) + break + case .storyViewPublicRepost(let _data): + if boxed { + buffer.appendInt32(-1116418231) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peerId.serialize(buffer, true) + _data.story.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .storyView(let _data): + return ("storyView", [("flags", _data.flags as Any), ("userId", _data.userId as Any), ("date", _data.date as Any), ("reaction", _data.reaction as Any)]) + case .storyViewPublicForward(let _data): + return ("storyViewPublicForward", [("flags", _data.flags as Any), ("message", _data.message as Any)]) + case .storyViewPublicRepost(let _data): + return ("storyViewPublicRepost", [("flags", _data.flags as Any), ("peerId", _data.peerId as Any), ("story", _data.story as Any)]) + } + } + public static func parse_storyView(_ reader: BufferReader) -> StoryView? { var _1: Int32? _1 = reader.readInt32() @@ -424,18 +858,21 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: Api.Reaction? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Reaction - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Reaction + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.StoryView.storyView(flags: _1!, userId: _2!, date: _3!, reaction: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.StoryView.storyView(Cons_storyView(flags: _1!, userId: _2!, date: _3!, reaction: _4)) + } + else { + return nil + } } public static func parse_storyViewPublicForward(_ reader: BufferReader) -> StoryView? { var _1: Int32? @@ -446,9 +883,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.StoryView.storyViewPublicForward(flags: _1!, message: _2!) + if _c1 && _c2 { + return Api.StoryView.storyViewPublicForward(Cons_storyViewPublicForward(flags: _1!, message: _2!)) + } + else { + return nil + } } public static func parse_storyViewPublicRepost(_ reader: BufferReader) -> StoryView? { var _1: Int32? @@ -464,154 +904,212 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.StoryView.storyViewPublicRepost(flags: _1!, peerId: _2!, story: _3!) + if _c1 && _c2 && _c3 { + return Api.StoryView.storyViewPublicRepost(Cons_storyViewPublicRepost(flags: _1!, peerId: _2!, story: _3!)) + } + else { + return nil + } } - } } public extension Api { enum StoryViews: TypeConstructorDescription { - case storyViews(flags: Int32, viewsCount: Int32, forwardsCount: Int32?, reactions: [Api.ReactionCount]?, reactionsCount: Int32?, recentViewers: [Int64]?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .storyViews(let flags, let viewsCount, let forwardsCount, let reactions, let reactionsCount, let recentViewers): - if boxed { - buffer.appendInt32(-1923523370) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(viewsCount, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(forwardsCount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(reactions!.count)) - for item in reactions! { + public class Cons_storyViews { + public var flags: Int32 + public var viewsCount: Int32 + public var forwardsCount: Int32? + public var reactions: [Api.ReactionCount]? + public var reactionsCount: Int32? + public var recentViewers: [Int64]? + public init(flags: Int32, viewsCount: Int32, forwardsCount: Int32?, reactions: [Api.ReactionCount]?, reactionsCount: Int32?, recentViewers: [Int64]?) { + self.flags = flags + self.viewsCount = viewsCount + self.forwardsCount = forwardsCount + self.reactions = reactions + self.reactionsCount = reactionsCount + self.recentViewers = recentViewers + } + } + case storyViews(Cons_storyViews) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .storyViews(let _data): + if boxed { + buffer.appendInt32(-1923523370) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.viewsCount, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.forwardsCount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.reactions!.count)) + for item in _data.reactions! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(reactionsCount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(recentViewers!.count)) - for item in recentViewers! { + } + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.reactionsCount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.recentViewers!.count)) + for item in _data.recentViewers! { serializeInt64(item, buffer: buffer, boxed: false) - }} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .storyViews(let flags, let viewsCount, let forwardsCount, let reactions, let reactionsCount, let recentViewers): - return ("storyViews", [("flags", flags as Any), ("viewsCount", viewsCount as Any), ("forwardsCount", forwardsCount as Any), ("reactions", reactions as Any), ("reactionsCount", reactionsCount as Any), ("recentViewers", recentViewers as Any)]) - } - } - + } + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .storyViews(let _data): + return ("storyViews", [("flags", _data.flags as Any), ("viewsCount", _data.viewsCount as Any), ("forwardsCount", _data.forwardsCount as Any), ("reactions", _data.reactions as Any), ("reactionsCount", _data.reactionsCount as Any), ("recentViewers", _data.recentViewers as Any)]) + } + } + public static func parse_storyViews(_ reader: BufferReader) -> StoryViews? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? _2 = reader.readInt32() var _3: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _3 = reader.readInt32() + } var _4: [Api.ReactionCount]? - if Int(_1!) & Int(1 << 3) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ReactionCount.self) - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ReactionCount.self) + } + } var _5: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _5 = reader.readInt32() + } var _6: [Int64]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 2) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 3) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 4) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.StoryViews.storyViews(flags: _1!, viewsCount: _2!, forwardsCount: _3, reactions: _4, reactionsCount: _5, recentViewers: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.StoryViews.storyViews(Cons_storyViews(flags: _1!, viewsCount: _2!, forwardsCount: _3, reactions: _4, reactionsCount: _5, recentViewers: _6)) + } + else { + return nil + } } - } } public extension Api { enum SuggestedPost: TypeConstructorDescription { - case suggestedPost(flags: Int32, price: Api.StarsAmount?, scheduleDate: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .suggestedPost(let flags, let price, let scheduleDate): - if boxed { - buffer.appendInt32(244201445) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {price!.serialize(buffer, true)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(scheduleDate!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .suggestedPost(let flags, let price, let scheduleDate): - return ("suggestedPost", [("flags", flags as Any), ("price", price as Any), ("scheduleDate", scheduleDate as Any)]) - } - } - + public class Cons_suggestedPost { + public var flags: Int32 + public var price: Api.StarsAmount? + public var scheduleDate: Int32? + public init(flags: Int32, price: Api.StarsAmount?, scheduleDate: Int32?) { + self.flags = flags + self.price = price + self.scheduleDate = scheduleDate + } + } + case suggestedPost(Cons_suggestedPost) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .suggestedPost(let _data): + if boxed { + buffer.appendInt32(244201445) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.price!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.scheduleDate!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .suggestedPost(let _data): + return ("suggestedPost", [("flags", _data.flags as Any), ("price", _data.price as Any), ("scheduleDate", _data.scheduleDate as Any)]) + } + } + public static func parse_suggestedPost(_ reader: BufferReader) -> SuggestedPost? { var _1: Int32? _1 = reader.readInt32() var _2: Api.StarsAmount? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.StarsAmount - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.StarsAmount + } + } var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 3) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.SuggestedPost.suggestedPost(flags: _1!, price: _2, scheduleDate: _3) + if _c1 && _c2 && _c3 { + return Api.SuggestedPost.suggestedPost(Cons_suggestedPost(flags: _1!, price: _2, scheduleDate: _3)) + } + else { + return nil + } } - } } public extension Api { enum TextWithEntities: TypeConstructorDescription { - case textWithEntities(text: String, entities: [Api.MessageEntity]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .textWithEntities(let text, let entities): - if boxed { - buffer.appendInt32(1964978502) - } - serializeString(text, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities.count)) - for item in entities { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .textWithEntities(let text, let entities): - return ("textWithEntities", [("text", text as Any), ("entities", entities as Any)]) - } - } - + public class Cons_textWithEntities { + public var text: String + public var entities: [Api.MessageEntity] + public init(text: String, entities: [Api.MessageEntity]) { + self.text = text + self.entities = entities + } + } + case textWithEntities(Cons_textWithEntities) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .textWithEntities(let _data): + if boxed { + buffer.appendInt32(1964978502) + } + serializeString(_data.text, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities.count)) + for item in _data.entities { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .textWithEntities(let _data): + return ("textWithEntities", [("text", _data.text as Any), ("entities", _data.entities as Any)]) + } + } + public static func parse_textWithEntities(_ reader: BufferReader) -> TextWithEntities? { var _1: String? _1 = parseString(reader) @@ -621,47 +1119,79 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.TextWithEntities.textWithEntities(text: _1!, entities: _2!) + if _c1 && _c2 { + return Api.TextWithEntities.textWithEntities(Cons_textWithEntities(text: _1!, entities: _2!)) + } + else { + return nil + } } - } } public extension Api { enum Theme: TypeConstructorDescription { - case theme(flags: Int32, id: Int64, accessHash: Int64, slug: String, title: String, document: Api.Document?, settings: [Api.ThemeSettings]?, emoticon: String?, installsCount: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .theme(let flags, let id, let accessHash, let slug, let title, let document, let settings, let emoticon, let installsCount): - if boxed { - buffer.appendInt32(-1609668650) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeString(slug, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {document!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(settings!.count)) - for item in settings! { + public class Cons_theme { + public var flags: Int32 + public var id: Int64 + public var accessHash: Int64 + public var slug: String + public var title: String + public var document: Api.Document? + public var settings: [Api.ThemeSettings]? + public var emoticon: String? + public var installsCount: Int32? + public init(flags: Int32, id: Int64, accessHash: Int64, slug: String, title: String, document: Api.Document?, settings: [Api.ThemeSettings]?, emoticon: String?, installsCount: Int32?) { + self.flags = flags + self.id = id + self.accessHash = accessHash + self.slug = slug + self.title = title + self.document = document + self.settings = settings + self.emoticon = emoticon + self.installsCount = installsCount + } + } + case theme(Cons_theme) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .theme(let _data): + if boxed { + buffer.appendInt32(-1609668650) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeString(_data.slug, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.document!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.settings!.count)) + for item in _data.settings! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 6) != 0 {serializeString(emoticon!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(installsCount!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .theme(let flags, let id, let accessHash, let slug, let title, let document, let settings, let emoticon, let installsCount): - return ("theme", [("flags", flags as Any), ("id", id as Any), ("accessHash", accessHash as Any), ("slug", slug as Any), ("title", title as Any), ("document", document as Any), ("settings", settings as Any), ("emoticon", emoticon as Any), ("installsCount", installsCount as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 6) != 0 { + serializeString(_data.emoticon!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.installsCount!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .theme(let _data): + return ("theme", [("flags", _data.flags as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("slug", _data.slug as Any), ("title", _data.title as Any), ("document", _data.document as Any), ("settings", _data.settings as Any), ("emoticon", _data.emoticon as Any), ("installsCount", _data.installsCount as Any)]) + } + } + public static func parse_theme(_ reader: BufferReader) -> Theme? { var _1: Int32? _1 = reader.readInt32() @@ -674,17 +1204,25 @@ public extension Api { var _5: String? _5 = parseString(reader) var _6: Api.Document? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.Document - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.Document + } + } var _7: [Api.ThemeSettings]? - if Int(_1!) & Int(1 << 3) != 0 {if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ThemeSettings.self) - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ThemeSettings.self) + } + } var _8: String? - if Int(_1!) & Int(1 << 6) != 0 {_8 = parseString(reader) } + if Int(_1!) & Int(1 << 6) != 0 { + _8 = parseString(reader) + } var _9: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_9 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _9 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -694,51 +1232,68 @@ public extension Api { let _c7 = (Int(_1!) & Int(1 << 3) == 0) || _7 != nil let _c8 = (Int(_1!) & Int(1 << 6) == 0) || _8 != nil let _c9 = (Int(_1!) & Int(1 << 4) == 0) || _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.Theme.theme(flags: _1!, id: _2!, accessHash: _3!, slug: _4!, title: _5!, document: _6, settings: _7, emoticon: _8, installsCount: _9) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.Theme.theme(Cons_theme(flags: _1!, id: _2!, accessHash: _3!, slug: _4!, title: _5!, document: _6, settings: _7, emoticon: _8, installsCount: _9)) + } + else { + return nil + } } - } } public extension Api { enum ThemeSettings: TypeConstructorDescription { - case themeSettings(flags: Int32, baseTheme: Api.BaseTheme, accentColor: Int32, outboxAccentColor: Int32?, messageColors: [Int32]?, wallpaper: Api.WallPaper?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .themeSettings(let flags, let baseTheme, let accentColor, let outboxAccentColor, let messageColors, let wallpaper): - if boxed { - buffer.appendInt32(-94849324) - } - serializeInt32(flags, buffer: buffer, boxed: false) - baseTheme.serialize(buffer, true) - serializeInt32(accentColor, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(outboxAccentColor!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messageColors!.count)) - for item in messageColors! { + public class Cons_themeSettings { + public var flags: Int32 + public var baseTheme: Api.BaseTheme + public var accentColor: Int32 + public var outboxAccentColor: Int32? + public var messageColors: [Int32]? + public var wallpaper: Api.WallPaper? + public init(flags: Int32, baseTheme: Api.BaseTheme, accentColor: Int32, outboxAccentColor: Int32?, messageColors: [Int32]?, wallpaper: Api.WallPaper?) { + self.flags = flags + self.baseTheme = baseTheme + self.accentColor = accentColor + self.outboxAccentColor = outboxAccentColor + self.messageColors = messageColors + self.wallpaper = wallpaper + } + } + case themeSettings(Cons_themeSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .themeSettings(let _data): + if boxed { + buffer.appendInt32(-94849324) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.baseTheme.serialize(buffer, true) + serializeInt32(_data.accentColor, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.outboxAccentColor!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messageColors!.count)) + for item in _data.messageColors! { serializeInt32(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 1) != 0 {wallpaper!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .themeSettings(let flags, let baseTheme, let accentColor, let outboxAccentColor, let messageColors, let wallpaper): - return ("themeSettings", [("flags", flags as Any), ("baseTheme", baseTheme as Any), ("accentColor", accentColor as Any), ("outboxAccentColor", outboxAccentColor as Any), ("messageColors", messageColors as Any), ("wallpaper", wallpaper as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.wallpaper!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .themeSettings(let _data): + return ("themeSettings", [("flags", _data.flags as Any), ("baseTheme", _data.baseTheme as Any), ("accentColor", _data.accentColor as Any), ("outboxAccentColor", _data.outboxAccentColor as Any), ("messageColors", _data.messageColors as Any), ("wallpaper", _data.wallpaper as Any)]) + } + } + public static func parse_themeSettings(_ reader: BufferReader) -> ThemeSettings? { var _1: Int32? _1 = reader.readInt32() @@ -749,56 +1304,70 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 3) != 0 { + _4 = reader.readInt32() + } var _5: [Int32]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + } var _6: Api.WallPaper? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.WallPaper - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.WallPaper + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 3) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.ThemeSettings.themeSettings(flags: _1!, baseTheme: _2!, accentColor: _3!, outboxAccentColor: _4, messageColors: _5, wallpaper: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.ThemeSettings.themeSettings(Cons_themeSettings(flags: _1!, baseTheme: _2!, accentColor: _3!, outboxAccentColor: _4, messageColors: _5, wallpaper: _6)) + } + else { + return nil + } } - } } public extension Api { enum Timezone: TypeConstructorDescription { - case timezone(id: String, name: String, utcOffset: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .timezone(let id, let name, let utcOffset): - if boxed { - buffer.appendInt32(-7173643) - } - serializeString(id, buffer: buffer, boxed: false) - serializeString(name, buffer: buffer, boxed: false) - serializeInt32(utcOffset, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .timezone(let id, let name, let utcOffset): - return ("timezone", [("id", id as Any), ("name", name as Any), ("utcOffset", utcOffset as Any)]) - } - } - + public class Cons_timezone { + public var id: String + public var name: String + public var utcOffset: Int32 + public init(id: String, name: String, utcOffset: Int32) { + self.id = id + self.name = name + self.utcOffset = utcOffset + } + } + case timezone(Cons_timezone) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .timezone(let _data): + if boxed { + buffer.appendInt32(-7173643) + } + serializeString(_data.id, buffer: buffer, boxed: false) + serializeString(_data.name, buffer: buffer, boxed: false) + serializeInt32(_data.utcOffset, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .timezone(let _data): + return ("timezone", [("id", _data.id as Any), ("name", _data.name as Any), ("utcOffset", _data.utcOffset as Any)]) + } + } + public static func parse_timezone(_ reader: BufferReader) -> Timezone? { var _1: String? _1 = parseString(reader) @@ -809,38 +1378,49 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Timezone.timezone(id: _1!, name: _2!, utcOffset: _3!) + if _c1 && _c2 && _c3 { + return Api.Timezone.timezone(Cons_timezone(id: _1!, name: _2!, utcOffset: _3!)) + } + else { + return nil + } } - } } public extension Api { enum TodoCompletion: TypeConstructorDescription { - case todoCompletion(id: Int32, completedBy: Api.Peer, date: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .todoCompletion(let id, let completedBy, let date): - if boxed { - buffer.appendInt32(572241380) - } - serializeInt32(id, buffer: buffer, boxed: false) - completedBy.serialize(buffer, true) - serializeInt32(date, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .todoCompletion(let id, let completedBy, let date): - return ("todoCompletion", [("id", id as Any), ("completedBy", completedBy as Any), ("date", date as Any)]) - } - } - + public class Cons_todoCompletion { + public var id: Int32 + public var completedBy: Api.Peer + public var date: Int32 + public init(id: Int32, completedBy: Api.Peer, date: Int32) { + self.id = id + self.completedBy = completedBy + self.date = date + } + } + case todoCompletion(Cons_todoCompletion) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .todoCompletion(let _data): + if boxed { + buffer.appendInt32(572241380) + } + serializeInt32(_data.id, buffer: buffer, boxed: false) + _data.completedBy.serialize(buffer, true) + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .todoCompletion(let _data): + return ("todoCompletion", [("id", _data.id as Any), ("completedBy", _data.completedBy as Any), ("date", _data.date as Any)]) + } + } + public static func parse_todoCompletion(_ reader: BufferReader) -> TodoCompletion? { var _1: Int32? _1 = reader.readInt32() @@ -853,37 +1433,46 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.TodoCompletion.todoCompletion(id: _1!, completedBy: _2!, date: _3!) + if _c1 && _c2 && _c3 { + return Api.TodoCompletion.todoCompletion(Cons_todoCompletion(id: _1!, completedBy: _2!, date: _3!)) + } + else { + return nil + } } - } } public extension Api { enum TodoItem: TypeConstructorDescription { - case todoItem(id: Int32, title: Api.TextWithEntities) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .todoItem(let id, let title): - if boxed { - buffer.appendInt32(-878074577) - } - serializeInt32(id, buffer: buffer, boxed: false) - title.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .todoItem(let id, let title): - return ("todoItem", [("id", id as Any), ("title", title as Any)]) - } - } - + public class Cons_todoItem { + public var id: Int32 + public var title: Api.TextWithEntities + public init(id: Int32, title: Api.TextWithEntities) { + self.id = id + self.title = title + } + } + case todoItem(Cons_todoItem) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .todoItem(let _data): + if boxed { + buffer.appendInt32(-878074577) + } + serializeInt32(_data.id, buffer: buffer, boxed: false) + _data.title.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .todoItem(let _data): + return ("todoItem", [("id", _data.id as Any), ("title", _data.title as Any)]) + } + } + public static func parse_todoItem(_ reader: BufferReader) -> TodoItem? { var _1: Int32? _1 = reader.readInt32() @@ -893,41 +1482,53 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.TodoItem.todoItem(id: _1!, title: _2!) + if _c1 && _c2 { + return Api.TodoItem.todoItem(Cons_todoItem(id: _1!, title: _2!)) + } + else { + return nil + } } - } } public extension Api { enum TodoList: TypeConstructorDescription { - case todoList(flags: Int32, title: Api.TextWithEntities, list: [Api.TodoItem]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .todoList(let flags, let title, let list): - if boxed { - buffer.appendInt32(1236871718) - } - serializeInt32(flags, buffer: buffer, boxed: false) - title.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(list.count)) - for item in list { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .todoList(let flags, let title, let list): - return ("todoList", [("flags", flags as Any), ("title", title as Any), ("list", list as Any)]) - } - } - + public class Cons_todoList { + public var flags: Int32 + public var title: Api.TextWithEntities + public var list: [Api.TodoItem] + public init(flags: Int32, title: Api.TextWithEntities, list: [Api.TodoItem]) { + self.flags = flags + self.title = title + self.list = list + } + } + case todoList(Cons_todoList) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .todoList(let _data): + if boxed { + buffer.appendInt32(1236871718) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.title.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.list.count)) + for item in _data.list { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .todoList(let _data): + return ("todoList", [("flags", _data.flags as Any), ("title", _data.title as Any), ("list", _data.list as Any)]) + } + } + public static func parse_todoList(_ reader: BufferReader) -> TodoList? { var _1: Int32? _1 = reader.readInt32() @@ -942,37 +1543,46 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.TodoList.todoList(flags: _1!, title: _2!, list: _3!) + if _c1 && _c2 && _c3 { + return Api.TodoList.todoList(Cons_todoList(flags: _1!, title: _2!, list: _3!)) + } + else { + return nil + } } - } } public extension Api { enum TopPeer: TypeConstructorDescription { - case topPeer(peer: Api.Peer, rating: Double) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .topPeer(let peer, let rating): - if boxed { - buffer.appendInt32(-305282981) - } - peer.serialize(buffer, true) - serializeDouble(rating, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .topPeer(let peer, let rating): - return ("topPeer", [("peer", peer as Any), ("rating", rating as Any)]) - } - } - + public class Cons_topPeer { + public var peer: Api.Peer + public var rating: Double + public init(peer: Api.Peer, rating: Double) { + self.peer = peer + self.rating = rating + } + } + case topPeer(Cons_topPeer) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .topPeer(let _data): + if boxed { + buffer.appendInt32(-305282981) + } + _data.peer.serialize(buffer, true) + serializeDouble(_data.rating, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .topPeer(let _data): + return ("topPeer", [("peer", _data.peer as Any), ("rating", _data.rating as Any)]) + } + } + public static func parse_topPeer(_ reader: BufferReader) -> TopPeer? { var _1: Api.Peer? if let signature = reader.readInt32() { @@ -982,11 +1592,13 @@ public extension Api { _2 = reader.readDouble() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.TopPeer.topPeer(peer: _1!, rating: _2!) + if _c1 && _c2 { + return Api.TopPeer.topPeer(Cons_topPeer(peer: _1!, rating: _2!)) + } + else { + return nil + } } - } } public extension Api { @@ -1000,89 +1612,80 @@ public extension Api { case topPeerCategoryForwardUsers case topPeerCategoryGroups case topPeerCategoryPhoneCalls - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .topPeerCategoryBotsApp: - if boxed { - buffer.appendInt32(-39945236) - } - - break - case .topPeerCategoryBotsInline: - if boxed { - buffer.appendInt32(344356834) - } - - break - case .topPeerCategoryBotsPM: - if boxed { - buffer.appendInt32(-1419371685) - } - - break - case .topPeerCategoryChannels: - if boxed { - buffer.appendInt32(371037736) - } - - break - case .topPeerCategoryCorrespondents: - if boxed { - buffer.appendInt32(104314861) - } - - break - case .topPeerCategoryForwardChats: - if boxed { - buffer.appendInt32(-68239120) - } - - break - case .topPeerCategoryForwardUsers: - if boxed { - buffer.appendInt32(-1472172887) - } - - break - case .topPeerCategoryGroups: - if boxed { - buffer.appendInt32(-1122524854) - } - - break - case .topPeerCategoryPhoneCalls: - if boxed { - buffer.appendInt32(511092620) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .topPeerCategoryBotsApp: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .topPeerCategoryBotsApp: + if boxed { + buffer.appendInt32(-39945236) + } + break + case .topPeerCategoryBotsInline: + if boxed { + buffer.appendInt32(344356834) + } + break + case .topPeerCategoryBotsPM: + if boxed { + buffer.appendInt32(-1419371685) + } + break + case .topPeerCategoryChannels: + if boxed { + buffer.appendInt32(371037736) + } + break + case .topPeerCategoryCorrespondents: + if boxed { + buffer.appendInt32(104314861) + } + break + case .topPeerCategoryForwardChats: + if boxed { + buffer.appendInt32(-68239120) + } + break + case .topPeerCategoryForwardUsers: + if boxed { + buffer.appendInt32(-1472172887) + } + break + case .topPeerCategoryGroups: + if boxed { + buffer.appendInt32(-1122524854) + } + break + case .topPeerCategoryPhoneCalls: + if boxed { + buffer.appendInt32(511092620) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .topPeerCategoryBotsApp: return ("topPeerCategoryBotsApp", []) - case .topPeerCategoryBotsInline: + case .topPeerCategoryBotsInline: return ("topPeerCategoryBotsInline", []) - case .topPeerCategoryBotsPM: + case .topPeerCategoryBotsPM: return ("topPeerCategoryBotsPM", []) - case .topPeerCategoryChannels: + case .topPeerCategoryChannels: return ("topPeerCategoryChannels", []) - case .topPeerCategoryCorrespondents: + case .topPeerCategoryCorrespondents: return ("topPeerCategoryCorrespondents", []) - case .topPeerCategoryForwardChats: + case .topPeerCategoryForwardChats: return ("topPeerCategoryForwardChats", []) - case .topPeerCategoryForwardUsers: + case .topPeerCategoryForwardUsers: return ("topPeerCategoryForwardUsers", []) - case .topPeerCategoryGroups: + case .topPeerCategoryGroups: return ("topPeerCategoryGroups", []) - case .topPeerCategoryPhoneCalls: + case .topPeerCategoryPhoneCalls: return ("topPeerCategoryPhoneCalls", []) - } - } - + } + } + public static func parse_topPeerCategoryBotsApp(_ reader: BufferReader) -> TopPeerCategory? { return Api.TopPeerCategory.topPeerCategoryBotsApp } @@ -1110,4286 +1713,5 @@ public extension Api { public static func parse_topPeerCategoryPhoneCalls(_ reader: BufferReader) -> TopPeerCategory? { return Api.TopPeerCategory.topPeerCategoryPhoneCalls } - - } -} -public extension Api { - enum TopPeerCategoryPeers: TypeConstructorDescription { - case topPeerCategoryPeers(category: Api.TopPeerCategory, count: Int32, peers: [Api.TopPeer]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .topPeerCategoryPeers(let category, let count, let peers): - if boxed { - buffer.appendInt32(-75283823) - } - category.serialize(buffer, true) - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peers.count)) - for item in peers { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .topPeerCategoryPeers(let category, let count, let peers): - return ("topPeerCategoryPeers", [("category", category as Any), ("count", count as Any), ("peers", peers as Any)]) - } - } - - public static func parse_topPeerCategoryPeers(_ reader: BufferReader) -> TopPeerCategoryPeers? { - var _1: Api.TopPeerCategory? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.TopPeerCategory - } - var _2: Int32? - _2 = reader.readInt32() - var _3: [Api.TopPeer]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.TopPeer.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.TopPeerCategoryPeers.topPeerCategoryPeers(category: _1!, count: _2!, peers: _3!) - } - - } -} -public extension Api { - indirect enum Update: TypeConstructorDescription { - case updateAttachMenuBots - case updateAutoSaveSettings - case updateBotBusinessConnect(connection: Api.BotBusinessConnection, qts: Int32) - case updateBotCallbackQuery(flags: Int32, queryId: Int64, userId: Int64, peer: Api.Peer, msgId: Int32, chatInstance: Int64, data: Buffer?, gameShortName: String?) - case updateBotChatBoost(peer: Api.Peer, boost: Api.Boost, qts: Int32) - case updateBotChatInviteRequester(peer: Api.Peer, date: Int32, userId: Int64, about: String, invite: Api.ExportedChatInvite, qts: Int32) - case updateBotCommands(peer: Api.Peer, botId: Int64, commands: [Api.BotCommand]) - case updateBotDeleteBusinessMessage(connectionId: String, peer: Api.Peer, messages: [Int32], qts: Int32) - case updateBotEditBusinessMessage(flags: Int32, connectionId: String, message: Api.Message, replyToMessage: Api.Message?, qts: Int32) - case updateBotInlineQuery(flags: Int32, queryId: Int64, userId: Int64, query: String, geo: Api.GeoPoint?, peerType: Api.InlineQueryPeerType?, offset: String) - case updateBotInlineSend(flags: Int32, userId: Int64, query: String, geo: Api.GeoPoint?, id: String, msgId: Api.InputBotInlineMessageID?) - case updateBotMenuButton(botId: Int64, button: Api.BotMenuButton) - case updateBotMessageReaction(peer: Api.Peer, msgId: Int32, date: Int32, actor: Api.Peer, oldReactions: [Api.Reaction], newReactions: [Api.Reaction], qts: Int32) - case updateBotMessageReactions(peer: Api.Peer, msgId: Int32, date: Int32, reactions: [Api.ReactionCount], qts: Int32) - case updateBotNewBusinessMessage(flags: Int32, connectionId: String, message: Api.Message, replyToMessage: Api.Message?, qts: Int32) - case updateBotPrecheckoutQuery(flags: Int32, queryId: Int64, userId: Int64, payload: Buffer, info: Api.PaymentRequestedInfo?, shippingOptionId: String?, currency: String, totalAmount: Int64) - case updateBotPurchasedPaidMedia(userId: Int64, payload: String, qts: Int32) - case updateBotShippingQuery(queryId: Int64, userId: Int64, payload: Buffer, shippingAddress: Api.PostAddress) - case updateBotStopped(userId: Int64, date: Int32, stopped: Api.Bool, qts: Int32) - case updateBotWebhookJSON(data: Api.DataJSON) - case updateBotWebhookJSONQuery(queryId: Int64, data: Api.DataJSON, timeout: Int32) - case updateBusinessBotCallbackQuery(flags: Int32, queryId: Int64, userId: Int64, connectionId: String, message: Api.Message, replyToMessage: Api.Message?, chatInstance: Int64, data: Buffer?) - case updateChannel(channelId: Int64) - case updateChannelAvailableMessages(channelId: Int64, availableMinId: Int32) - case updateChannelMessageForwards(channelId: Int64, id: Int32, forwards: Int32) - case updateChannelMessageViews(channelId: Int64, id: Int32, views: Int32) - case updateChannelParticipant(flags: Int32, channelId: Int64, date: Int32, actorId: Int64, userId: Int64, prevParticipant: Api.ChannelParticipant?, newParticipant: Api.ChannelParticipant?, invite: Api.ExportedChatInvite?, qts: Int32) - case updateChannelReadMessagesContents(flags: Int32, channelId: Int64, topMsgId: Int32?, savedPeerId: Api.Peer?, messages: [Int32]) - case updateChannelTooLong(flags: Int32, channelId: Int64, pts: Int32?) - case updateChannelUserTyping(flags: Int32, channelId: Int64, topMsgId: Int32?, fromId: Api.Peer, action: Api.SendMessageAction) - case updateChannelViewForumAsMessages(channelId: Int64, enabled: Api.Bool) - case updateChannelWebPage(channelId: Int64, webpage: Api.WebPage, pts: Int32, ptsCount: Int32) - case updateChat(chatId: Int64) - case updateChatDefaultBannedRights(peer: Api.Peer, defaultBannedRights: Api.ChatBannedRights, version: Int32) - case updateChatParticipant(flags: Int32, chatId: Int64, date: Int32, actorId: Int64, userId: Int64, prevParticipant: Api.ChatParticipant?, newParticipant: Api.ChatParticipant?, invite: Api.ExportedChatInvite?, qts: Int32) - case updateChatParticipantAdd(chatId: Int64, userId: Int64, inviterId: Int64, date: Int32, version: Int32) - case updateChatParticipantAdmin(chatId: Int64, userId: Int64, isAdmin: Api.Bool, version: Int32) - case updateChatParticipantDelete(chatId: Int64, userId: Int64, version: Int32) - case updateChatParticipants(participants: Api.ChatParticipants) - case updateChatUserTyping(chatId: Int64, fromId: Api.Peer, action: Api.SendMessageAction) - case updateConfig - case updateContactsReset - case updateDcOptions(dcOptions: [Api.DcOption]) - case updateDeleteChannelMessages(channelId: Int64, messages: [Int32], pts: Int32, ptsCount: Int32) - case updateDeleteGroupCallMessages(call: Api.InputGroupCall, messages: [Int32]) - case updateDeleteMessages(messages: [Int32], pts: Int32, ptsCount: Int32) - case updateDeleteQuickReply(shortcutId: Int32) - case updateDeleteQuickReplyMessages(shortcutId: Int32, messages: [Int32]) - case updateDeleteScheduledMessages(flags: Int32, peer: Api.Peer, messages: [Int32], sentMessages: [Int32]?) - case updateDialogFilter(flags: Int32, id: Int32, filter: Api.DialogFilter?) - case updateDialogFilterOrder(order: [Int32]) - case updateDialogFilters - case updateDialogPinned(flags: Int32, folderId: Int32?, peer: Api.DialogPeer) - case updateDialogUnreadMark(flags: Int32, peer: Api.DialogPeer, savedPeerId: Api.Peer?) - case updateDraftMessage(flags: Int32, peer: Api.Peer, topMsgId: Int32?, savedPeerId: Api.Peer?, draft: Api.DraftMessage) - case updateEditChannelMessage(message: Api.Message, pts: Int32, ptsCount: Int32) - case updateEditMessage(message: Api.Message, pts: Int32, ptsCount: Int32) - case updateEmojiGameInfo(info: Api.messages.EmojiGameInfo) - case updateEncryptedChatTyping(chatId: Int32) - case updateEncryptedMessagesRead(chatId: Int32, maxDate: Int32, date: Int32) - case updateEncryption(chat: Api.EncryptedChat, date: Int32) - case updateFavedStickers - case updateFolderPeers(folderPeers: [Api.FolderPeer], pts: Int32, ptsCount: Int32) - case updateGeoLiveViewed(peer: Api.Peer, msgId: Int32) - case updateGroupCall(flags: Int32, peer: Api.Peer?, call: Api.GroupCall) - case updateGroupCallChainBlocks(call: Api.InputGroupCall, subChainId: Int32, blocks: [Buffer], nextOffset: Int32) - case updateGroupCallConnection(flags: Int32, params: Api.DataJSON) - case updateGroupCallEncryptedMessage(call: Api.InputGroupCall, fromId: Api.Peer, encryptedMessage: Buffer) - case updateGroupCallMessage(call: Api.InputGroupCall, message: Api.GroupCallMessage) - case updateGroupCallParticipants(call: Api.InputGroupCall, participants: [Api.GroupCallParticipant], version: Int32) - case updateInlineBotCallbackQuery(flags: Int32, queryId: Int64, userId: Int64, msgId: Api.InputBotInlineMessageID, chatInstance: Int64, data: Buffer?, gameShortName: String?) - case updateLangPack(difference: Api.LangPackDifference) - case updateLangPackTooLong(langCode: String) - case updateLoginToken - case updateMessageExtendedMedia(peer: Api.Peer, msgId: Int32, extendedMedia: [Api.MessageExtendedMedia]) - case updateMessageID(id: Int32, randomId: Int64) - case updateMessagePoll(flags: Int32, pollId: Int64, poll: Api.Poll?, results: Api.PollResults) - case updateMessagePollVote(pollId: Int64, peer: Api.Peer, options: [Buffer], qts: Int32) - case updateMessageReactions(flags: Int32, peer: Api.Peer, msgId: Int32, topMsgId: Int32?, savedPeerId: Api.Peer?, reactions: Api.MessageReactions) - case updateMonoForumNoPaidException(flags: Int32, channelId: Int64, savedPeerId: Api.Peer) - case updateMoveStickerSetToTop(flags: Int32, stickerset: Int64) - case updateNewAuthorization(flags: Int32, hash: Int64, date: Int32?, device: String?, location: String?) - case updateNewChannelMessage(message: Api.Message, pts: Int32, ptsCount: Int32) - case updateNewEncryptedMessage(message: Api.EncryptedMessage, qts: Int32) - case updateNewMessage(message: Api.Message, pts: Int32, ptsCount: Int32) - case updateNewQuickReply(quickReply: Api.QuickReply) - case updateNewScheduledMessage(message: Api.Message) - case updateNewStickerSet(stickerset: Api.messages.StickerSet) - case updateNewStoryReaction(storyId: Int32, peer: Api.Peer, reaction: Api.Reaction) - case updateNotifySettings(peer: Api.NotifyPeer, notifySettings: Api.PeerNotifySettings) - case updatePaidReactionPrivacy(private: Api.PaidReactionPrivacy) - case updatePeerBlocked(flags: Int32, peerId: Api.Peer) - case updatePeerHistoryTTL(flags: Int32, peer: Api.Peer, ttlPeriod: Int32?) - case updatePeerLocated(peers: [Api.PeerLocated]) - case updatePeerSettings(peer: Api.Peer, settings: Api.PeerSettings) - case updatePeerWallpaper(flags: Int32, peer: Api.Peer, wallpaper: Api.WallPaper?) - case updatePendingJoinRequests(peer: Api.Peer, requestsPending: Int32, recentRequesters: [Int64]) - case updatePhoneCall(phoneCall: Api.PhoneCall) - case updatePhoneCallSignalingData(phoneCallId: Int64, data: Buffer) - case updatePinnedChannelMessages(flags: Int32, channelId: Int64, messages: [Int32], pts: Int32, ptsCount: Int32) - case updatePinnedDialogs(flags: Int32, folderId: Int32?, order: [Api.DialogPeer]?) - case updatePinnedForumTopic(flags: Int32, peer: Api.Peer, topicId: Int32) - case updatePinnedForumTopics(flags: Int32, peer: Api.Peer, order: [Int32]?) - case updatePinnedMessages(flags: Int32, peer: Api.Peer, messages: [Int32], pts: Int32, ptsCount: Int32) - case updatePinnedSavedDialogs(flags: Int32, order: [Api.DialogPeer]?) - case updatePrivacy(key: Api.PrivacyKey, rules: [Api.PrivacyRule]) - case updatePtsChanged - case updateQuickReplies(quickReplies: [Api.QuickReply]) - case updateQuickReplyMessage(message: Api.Message) - case updateReadChannelDiscussionInbox(flags: Int32, channelId: Int64, topMsgId: Int32, readMaxId: Int32, broadcastId: Int64?, broadcastPost: Int32?) - case updateReadChannelDiscussionOutbox(channelId: Int64, topMsgId: Int32, readMaxId: Int32) - case updateReadChannelInbox(flags: Int32, folderId: Int32?, channelId: Int64, maxId: Int32, stillUnreadCount: Int32, pts: Int32) - case updateReadChannelOutbox(channelId: Int64, maxId: Int32) - case updateReadFeaturedEmojiStickers - case updateReadFeaturedStickers - case updateReadHistoryInbox(flags: Int32, folderId: Int32?, peer: Api.Peer, topMsgId: Int32?, maxId: Int32, stillUnreadCount: Int32, pts: Int32, ptsCount: Int32) - case updateReadHistoryOutbox(peer: Api.Peer, maxId: Int32, pts: Int32, ptsCount: Int32) - case updateReadMessagesContents(flags: Int32, messages: [Int32], pts: Int32, ptsCount: Int32, date: Int32?) - case updateReadMonoForumInbox(channelId: Int64, savedPeerId: Api.Peer, readMaxId: Int32) - case updateReadMonoForumOutbox(channelId: Int64, savedPeerId: Api.Peer, readMaxId: Int32) - case updateReadStories(peer: Api.Peer, maxId: Int32) - case updateRecentEmojiStatuses - case updateRecentReactions - case updateRecentStickers - case updateSavedDialogPinned(flags: Int32, peer: Api.DialogPeer) - case updateSavedGifs - case updateSavedReactionTags - case updateSavedRingtones - case updateSentPhoneCode(sentCode: Api.auth.SentCode) - case updateSentStoryReaction(peer: Api.Peer, storyId: Int32, reaction: Api.Reaction) - case updateServiceNotification(flags: Int32, inboxDate: Int32?, type: String, message: String, media: Api.MessageMedia, entities: [Api.MessageEntity]) - case updateSmsJob(jobId: String) - case updateStarGiftAuctionState(giftId: Int64, state: Api.StarGiftAuctionState) - case updateStarGiftAuctionUserState(giftId: Int64, userState: Api.StarGiftAuctionUserState) - case updateStarsBalance(balance: Api.StarsAmount) - case updateStarsRevenueStatus(peer: Api.Peer, status: Api.StarsRevenueStatus) - case updateStickerSets(flags: Int32) - case updateStickerSetsOrder(flags: Int32, order: [Int64]) - case updateStoriesStealthMode(stealthMode: Api.StoriesStealthMode) - case updateStory(peer: Api.Peer, story: Api.StoryItem) - case updateStoryID(id: Int32, randomId: Int64) - case updateTheme(theme: Api.Theme) - case updateTranscribedAudio(flags: Int32, peer: Api.Peer, msgId: Int32, transcriptionId: Int64, text: String) - case updateUser(userId: Int64) - case updateUserEmojiStatus(userId: Int64, emojiStatus: Api.EmojiStatus) - case updateUserName(userId: Int64, firstName: String, lastName: String, usernames: [Api.Username]) - case updateUserPhone(userId: Int64, phone: String) - case updateUserStatus(userId: Int64, status: Api.UserStatus) - case updateUserTyping(flags: Int32, userId: Int64, topMsgId: Int32?, action: Api.SendMessageAction) - case updateWebPage(webpage: Api.WebPage, pts: Int32, ptsCount: Int32) - case updateWebViewResultSent(queryId: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .updateAttachMenuBots: - if boxed { - buffer.appendInt32(397910539) - } - - break - case .updateAutoSaveSettings: - if boxed { - buffer.appendInt32(-335171433) - } - - break - case .updateBotBusinessConnect(let connection, let qts): - if boxed { - buffer.appendInt32(-1964652166) - } - connection.serialize(buffer, true) - serializeInt32(qts, buffer: buffer, boxed: false) - break - case .updateBotCallbackQuery(let flags, let queryId, let userId, let peer, let msgId, let chatInstance, let data, let gameShortName): - if boxed { - buffer.appendInt32(-1177566067) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(queryId, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeInt64(chatInstance, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeBytes(data!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(gameShortName!, buffer: buffer, boxed: false)} - break - case .updateBotChatBoost(let peer, let boost, let qts): - if boxed { - buffer.appendInt32(-1873947492) - } - peer.serialize(buffer, true) - boost.serialize(buffer, true) - serializeInt32(qts, buffer: buffer, boxed: false) - break - case .updateBotChatInviteRequester(let peer, let date, let userId, let about, let invite, let qts): - if boxed { - buffer.appendInt32(299870598) - } - peer.serialize(buffer, true) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - serializeString(about, buffer: buffer, boxed: false) - invite.serialize(buffer, true) - serializeInt32(qts, buffer: buffer, boxed: false) - break - case .updateBotCommands(let peer, let botId, let commands): - if boxed { - buffer.appendInt32(1299263278) - } - peer.serialize(buffer, true) - serializeInt64(botId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(commands.count)) - for item in commands { - item.serialize(buffer, true) - } - break - case .updateBotDeleteBusinessMessage(let connectionId, let peer, let messages, let qts): - if boxed { - buffer.appendInt32(-1607821266) - } - serializeString(connectionId, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - serializeInt32(item, buffer: buffer, boxed: false) - } - serializeInt32(qts, buffer: buffer, boxed: false) - break - case .updateBotEditBusinessMessage(let flags, let connectionId, let message, let replyToMessage, let qts): - if boxed { - buffer.appendInt32(132077692) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(connectionId, buffer: buffer, boxed: false) - message.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {replyToMessage!.serialize(buffer, true)} - serializeInt32(qts, buffer: buffer, boxed: false) - break - case .updateBotInlineQuery(let flags, let queryId, let userId, let query, let geo, let peerType, let offset): - if boxed { - buffer.appendInt32(1232025500) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(queryId, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - serializeString(query, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {geo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {peerType!.serialize(buffer, true)} - serializeString(offset, buffer: buffer, boxed: false) - break - case .updateBotInlineSend(let flags, let userId, let query, let geo, let id, let msgId): - if boxed { - buffer.appendInt32(317794823) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - serializeString(query, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {geo!.serialize(buffer, true)} - serializeString(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {msgId!.serialize(buffer, true)} - break - case .updateBotMenuButton(let botId, let button): - if boxed { - buffer.appendInt32(347625491) - } - serializeInt64(botId, buffer: buffer, boxed: false) - button.serialize(buffer, true) - break - case .updateBotMessageReaction(let peer, let msgId, let date, let actor, let oldReactions, let newReactions, let qts): - if boxed { - buffer.appendInt32(-1407069234) - } - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - actor.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(oldReactions.count)) - for item in oldReactions { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(newReactions.count)) - for item in newReactions { - item.serialize(buffer, true) - } - serializeInt32(qts, buffer: buffer, boxed: false) - break - case .updateBotMessageReactions(let peer, let msgId, let date, let reactions, let qts): - if boxed { - buffer.appendInt32(164329305) - } - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(reactions.count)) - for item in reactions { - item.serialize(buffer, true) - } - serializeInt32(qts, buffer: buffer, boxed: false) - break - case .updateBotNewBusinessMessage(let flags, let connectionId, let message, let replyToMessage, let qts): - if boxed { - buffer.appendInt32(-1646578564) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(connectionId, buffer: buffer, boxed: false) - message.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {replyToMessage!.serialize(buffer, true)} - serializeInt32(qts, buffer: buffer, boxed: false) - break - case .updateBotPrecheckoutQuery(let flags, let queryId, let userId, let payload, let info, let shippingOptionId, let currency, let totalAmount): - if boxed { - buffer.appendInt32(-1934976362) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(queryId, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - serializeBytes(payload, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {info!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(shippingOptionId!, buffer: buffer, boxed: false)} - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(totalAmount, buffer: buffer, boxed: false) - break - case .updateBotPurchasedPaidMedia(let userId, let payload, let qts): - if boxed { - buffer.appendInt32(675009298) - } - serializeInt64(userId, buffer: buffer, boxed: false) - serializeString(payload, buffer: buffer, boxed: false) - serializeInt32(qts, buffer: buffer, boxed: false) - break - case .updateBotShippingQuery(let queryId, let userId, let payload, let shippingAddress): - if boxed { - buffer.appendInt32(-1246823043) - } - serializeInt64(queryId, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - serializeBytes(payload, buffer: buffer, boxed: false) - shippingAddress.serialize(buffer, true) - break - case .updateBotStopped(let userId, let date, let stopped, let qts): - if boxed { - buffer.appendInt32(-997782967) - } - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - stopped.serialize(buffer, true) - serializeInt32(qts, buffer: buffer, boxed: false) - break - case .updateBotWebhookJSON(let data): - if boxed { - buffer.appendInt32(-2095595325) - } - data.serialize(buffer, true) - break - case .updateBotWebhookJSONQuery(let queryId, let data, let timeout): - if boxed { - buffer.appendInt32(-1684914010) - } - serializeInt64(queryId, buffer: buffer, boxed: false) - data.serialize(buffer, true) - serializeInt32(timeout, buffer: buffer, boxed: false) - break - case .updateBusinessBotCallbackQuery(let flags, let queryId, let userId, let connectionId, let message, let replyToMessage, let chatInstance, let data): - if boxed { - buffer.appendInt32(513998247) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(queryId, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - serializeString(connectionId, buffer: buffer, boxed: false) - message.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {replyToMessage!.serialize(buffer, true)} - serializeInt64(chatInstance, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeBytes(data!, buffer: buffer, boxed: false)} - break - case .updateChannel(let channelId): - if boxed { - buffer.appendInt32(1666927625) - } - serializeInt64(channelId, buffer: buffer, boxed: false) - break - case .updateChannelAvailableMessages(let channelId, let availableMinId): - if boxed { - buffer.appendInt32(-1304443240) - } - serializeInt64(channelId, buffer: buffer, boxed: false) - serializeInt32(availableMinId, buffer: buffer, boxed: false) - break - case .updateChannelMessageForwards(let channelId, let id, let forwards): - if boxed { - buffer.appendInt32(-761649164) - } - serializeInt64(channelId, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt32(forwards, buffer: buffer, boxed: false) - break - case .updateChannelMessageViews(let channelId, let id, let views): - if boxed { - buffer.appendInt32(-232346616) - } - serializeInt64(channelId, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt32(views, buffer: buffer, boxed: false) - break - case .updateChannelParticipant(let flags, let channelId, let date, let actorId, let userId, let prevParticipant, let newParticipant, let invite, let qts): - if boxed { - buffer.appendInt32(-1738720581) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(channelId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(actorId, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {prevParticipant!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {newParticipant!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {invite!.serialize(buffer, true)} - serializeInt32(qts, buffer: buffer, boxed: false) - break - case .updateChannelReadMessagesContents(let flags, let channelId, let topMsgId, let savedPeerId, let messages): - if boxed { - buffer.appendInt32(636691703) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(channelId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {savedPeerId!.serialize(buffer, true)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - serializeInt32(item, buffer: buffer, boxed: false) - } - break - case .updateChannelTooLong(let flags, let channelId, let pts): - if boxed { - buffer.appendInt32(277713951) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(channelId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(pts!, buffer: buffer, boxed: false)} - break - case .updateChannelUserTyping(let flags, let channelId, let topMsgId, let fromId, let action): - if boxed { - buffer.appendInt32(-1937192669) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(channelId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - fromId.serialize(buffer, true) - action.serialize(buffer, true) - break - case .updateChannelViewForumAsMessages(let channelId, let enabled): - if boxed { - buffer.appendInt32(129403168) - } - serializeInt64(channelId, buffer: buffer, boxed: false) - enabled.serialize(buffer, true) - break - case .updateChannelWebPage(let channelId, let webpage, let pts, let ptsCount): - if boxed { - buffer.appendInt32(791390623) - } - serializeInt64(channelId, buffer: buffer, boxed: false) - webpage.serialize(buffer, true) - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - break - case .updateChat(let chatId): - if boxed { - buffer.appendInt32(-124097970) - } - serializeInt64(chatId, buffer: buffer, boxed: false) - break - case .updateChatDefaultBannedRights(let peer, let defaultBannedRights, let version): - if boxed { - buffer.appendInt32(1421875280) - } - peer.serialize(buffer, true) - defaultBannedRights.serialize(buffer, true) - serializeInt32(version, buffer: buffer, boxed: false) - break - case .updateChatParticipant(let flags, let chatId, let date, let actorId, let userId, let prevParticipant, let newParticipant, let invite, let qts): - if boxed { - buffer.appendInt32(-796432838) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(chatId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(actorId, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {prevParticipant!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {newParticipant!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {invite!.serialize(buffer, true)} - serializeInt32(qts, buffer: buffer, boxed: false) - break - case .updateChatParticipantAdd(let chatId, let userId, let inviterId, let date, let version): - if boxed { - buffer.appendInt32(1037718609) - } - serializeInt64(chatId, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt64(inviterId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt32(version, buffer: buffer, boxed: false) - break - case .updateChatParticipantAdmin(let chatId, let userId, let isAdmin, let version): - if boxed { - buffer.appendInt32(-674602590) - } - serializeInt64(chatId, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - isAdmin.serialize(buffer, true) - serializeInt32(version, buffer: buffer, boxed: false) - break - case .updateChatParticipantDelete(let chatId, let userId, let version): - if boxed { - buffer.appendInt32(-483443337) - } - serializeInt64(chatId, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt32(version, buffer: buffer, boxed: false) - break - case .updateChatParticipants(let participants): - if boxed { - buffer.appendInt32(125178264) - } - participants.serialize(buffer, true) - break - case .updateChatUserTyping(let chatId, let fromId, let action): - if boxed { - buffer.appendInt32(-2092401936) - } - serializeInt64(chatId, buffer: buffer, boxed: false) - fromId.serialize(buffer, true) - action.serialize(buffer, true) - break - case .updateConfig: - if boxed { - buffer.appendInt32(-1574314746) - } - - break - case .updateContactsReset: - if boxed { - buffer.appendInt32(1887741886) - } - - break - case .updateDcOptions(let dcOptions): - if boxed { - buffer.appendInt32(-1906403213) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(dcOptions.count)) - for item in dcOptions { - item.serialize(buffer, true) - } - break - case .updateDeleteChannelMessages(let channelId, let messages, let pts, let ptsCount): - if boxed { - buffer.appendInt32(-1020437742) - } - serializeInt64(channelId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - serializeInt32(item, buffer: buffer, boxed: false) - } - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - break - case .updateDeleteGroupCallMessages(let call, let messages): - if boxed { - buffer.appendInt32(1048963372) - } - call.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - serializeInt32(item, buffer: buffer, boxed: false) - } - break - case .updateDeleteMessages(let messages, let pts, let ptsCount): - if boxed { - buffer.appendInt32(-1576161051) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - serializeInt32(item, buffer: buffer, boxed: false) - } - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - break - case .updateDeleteQuickReply(let shortcutId): - if boxed { - buffer.appendInt32(1407644140) - } - serializeInt32(shortcutId, buffer: buffer, boxed: false) - break - case .updateDeleteQuickReplyMessages(let shortcutId, let messages): - if boxed { - buffer.appendInt32(1450174413) - } - serializeInt32(shortcutId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - serializeInt32(item, buffer: buffer, boxed: false) - } - break - case .updateDeleteScheduledMessages(let flags, let peer, let messages, let sentMessages): - if boxed { - buffer.appendInt32(-223929981) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - serializeInt32(item, buffer: buffer, boxed: false) - } - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(sentMessages!.count)) - for item in sentMessages! { - serializeInt32(item, buffer: buffer, boxed: false) - }} - break - case .updateDialogFilter(let flags, let id, let filter): - if boxed { - buffer.appendInt32(654302845) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {filter!.serialize(buffer, true)} - break - case .updateDialogFilterOrder(let order): - if boxed { - buffer.appendInt32(-1512627963) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order.count)) - for item in order { - serializeInt32(item, buffer: buffer, boxed: false) - } - break - case .updateDialogFilters: - if boxed { - buffer.appendInt32(889491791) - } - - break - case .updateDialogPinned(let flags, let folderId, let peer): - if boxed { - buffer.appendInt32(1852826908) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(folderId!, buffer: buffer, boxed: false)} - peer.serialize(buffer, true) - break - case .updateDialogUnreadMark(let flags, let peer, let savedPeerId): - if boxed { - buffer.appendInt32(-1235684802) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {savedPeerId!.serialize(buffer, true)} - break - case .updateDraftMessage(let flags, let peer, let topMsgId, let savedPeerId, let draft): - if boxed { - buffer.appendInt32(-302247650) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {savedPeerId!.serialize(buffer, true)} - draft.serialize(buffer, true) - break - case .updateEditChannelMessage(let message, let pts, let ptsCount): - if boxed { - buffer.appendInt32(457133559) - } - message.serialize(buffer, true) - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - break - case .updateEditMessage(let message, let pts, let ptsCount): - if boxed { - buffer.appendInt32(-469536605) - } - message.serialize(buffer, true) - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - break - case .updateEmojiGameInfo(let info): - if boxed { - buffer.appendInt32(-73640838) - } - info.serialize(buffer, true) - break - case .updateEncryptedChatTyping(let chatId): - if boxed { - buffer.appendInt32(386986326) - } - serializeInt32(chatId, buffer: buffer, boxed: false) - break - case .updateEncryptedMessagesRead(let chatId, let maxDate, let date): - if boxed { - buffer.appendInt32(956179895) - } - serializeInt32(chatId, buffer: buffer, boxed: false) - serializeInt32(maxDate, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - break - case .updateEncryption(let chat, let date): - if boxed { - buffer.appendInt32(-1264392051) - } - chat.serialize(buffer, true) - serializeInt32(date, buffer: buffer, boxed: false) - break - case .updateFavedStickers: - if boxed { - buffer.appendInt32(-451831443) - } - - break - case .updateFolderPeers(let folderPeers, let pts, let ptsCount): - if boxed { - buffer.appendInt32(422972864) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(folderPeers.count)) - for item in folderPeers { - item.serialize(buffer, true) - } - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - break - case .updateGeoLiveViewed(let peer, let msgId): - if boxed { - buffer.appendInt32(-2027964103) - } - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - break - case .updateGroupCall(let flags, let peer, let call): - if boxed { - buffer.appendInt32(-1658710304) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {peer!.serialize(buffer, true)} - call.serialize(buffer, true) - break - case .updateGroupCallChainBlocks(let call, let subChainId, let blocks, let nextOffset): - if boxed { - buffer.appendInt32(-1535694705) - } - call.serialize(buffer, true) - serializeInt32(subChainId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(blocks.count)) - for item in blocks { - serializeBytes(item, buffer: buffer, boxed: false) - } - serializeInt32(nextOffset, buffer: buffer, boxed: false) - break - case .updateGroupCallConnection(let flags, let params): - if boxed { - buffer.appendInt32(192428418) - } - serializeInt32(flags, buffer: buffer, boxed: false) - params.serialize(buffer, true) - break - case .updateGroupCallEncryptedMessage(let call, let fromId, let encryptedMessage): - if boxed { - buffer.appendInt32(-917002394) - } - call.serialize(buffer, true) - fromId.serialize(buffer, true) - serializeBytes(encryptedMessage, buffer: buffer, boxed: false) - break - case .updateGroupCallMessage(let call, let message): - if boxed { - buffer.appendInt32(-667783411) - } - call.serialize(buffer, true) - message.serialize(buffer, true) - break - case .updateGroupCallParticipants(let call, let participants, let version): - if boxed { - buffer.appendInt32(-219423922) - } - call.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(participants.count)) - for item in participants { - item.serialize(buffer, true) - } - serializeInt32(version, buffer: buffer, boxed: false) - break - case .updateInlineBotCallbackQuery(let flags, let queryId, let userId, let msgId, let chatInstance, let data, let gameShortName): - if boxed { - buffer.appendInt32(1763610706) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(queryId, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - msgId.serialize(buffer, true) - serializeInt64(chatInstance, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeBytes(data!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(gameShortName!, buffer: buffer, boxed: false)} - break - case .updateLangPack(let difference): - if boxed { - buffer.appendInt32(1442983757) - } - difference.serialize(buffer, true) - break - case .updateLangPackTooLong(let langCode): - if boxed { - buffer.appendInt32(1180041828) - } - serializeString(langCode, buffer: buffer, boxed: false) - break - case .updateLoginToken: - if boxed { - buffer.appendInt32(1448076945) - } - - break - case .updateMessageExtendedMedia(let peer, let msgId, let extendedMedia): - if boxed { - buffer.appendInt32(-710666460) - } - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(extendedMedia.count)) - for item in extendedMedia { - item.serialize(buffer, true) - } - break - case .updateMessageID(let id, let randomId): - if boxed { - buffer.appendInt32(1318109142) - } - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt64(randomId, buffer: buffer, boxed: false) - break - case .updateMessagePoll(let flags, let pollId, let poll, let results): - if boxed { - buffer.appendInt32(-1398708869) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(pollId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {poll!.serialize(buffer, true)} - results.serialize(buffer, true) - break - case .updateMessagePollVote(let pollId, let peer, let options, let qts): - if boxed { - buffer.appendInt32(619974263) - } - serializeInt64(pollId, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(options.count)) - for item in options { - serializeBytes(item, buffer: buffer, boxed: false) - } - serializeInt32(qts, buffer: buffer, boxed: false) - break - case .updateMessageReactions(let flags, let peer, let msgId, let topMsgId, let savedPeerId, let reactions): - if boxed { - buffer.appendInt32(506035194) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {savedPeerId!.serialize(buffer, true)} - reactions.serialize(buffer, true) - break - case .updateMonoForumNoPaidException(let flags, let channelId, let savedPeerId): - if boxed { - buffer.appendInt32(-1618924792) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(channelId, buffer: buffer, boxed: false) - savedPeerId.serialize(buffer, true) - break - case .updateMoveStickerSetToTop(let flags, let stickerset): - if boxed { - buffer.appendInt32(-2030252155) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(stickerset, buffer: buffer, boxed: false) - break - case .updateNewAuthorization(let flags, let hash, let date, let device, let location): - if boxed { - buffer.appendInt32(-1991136273) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(date!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeString(device!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeString(location!, buffer: buffer, boxed: false)} - break - case .updateNewChannelMessage(let message, let pts, let ptsCount): - if boxed { - buffer.appendInt32(1656358105) - } - message.serialize(buffer, true) - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - break - case .updateNewEncryptedMessage(let message, let qts): - if boxed { - buffer.appendInt32(314359194) - } - message.serialize(buffer, true) - serializeInt32(qts, buffer: buffer, boxed: false) - break - case .updateNewMessage(let message, let pts, let ptsCount): - if boxed { - buffer.appendInt32(522914557) - } - message.serialize(buffer, true) - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - break - case .updateNewQuickReply(let quickReply): - if boxed { - buffer.appendInt32(-180508905) - } - quickReply.serialize(buffer, true) - break - case .updateNewScheduledMessage(let message): - if boxed { - buffer.appendInt32(967122427) - } - message.serialize(buffer, true) - break - case .updateNewStickerSet(let stickerset): - if boxed { - buffer.appendInt32(1753886890) - } - stickerset.serialize(buffer, true) - break - case .updateNewStoryReaction(let storyId, let peer, let reaction): - if boxed { - buffer.appendInt32(405070859) - } - serializeInt32(storyId, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - reaction.serialize(buffer, true) - break - case .updateNotifySettings(let peer, let notifySettings): - if boxed { - buffer.appendInt32(-1094555409) - } - peer.serialize(buffer, true) - notifySettings.serialize(buffer, true) - break - case .updatePaidReactionPrivacy(let `private`): - if boxed { - buffer.appendInt32(-1955438642) - } - `private`.serialize(buffer, true) - break - case .updatePeerBlocked(let flags, let peerId): - if boxed { - buffer.appendInt32(-337610926) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peerId.serialize(buffer, true) - break - case .updatePeerHistoryTTL(let flags, let peer, let ttlPeriod): - if boxed { - buffer.appendInt32(-1147422299) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(ttlPeriod!, buffer: buffer, boxed: false)} - break - case .updatePeerLocated(let peers): - if boxed { - buffer.appendInt32(-1263546448) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peers.count)) - for item in peers { - item.serialize(buffer, true) - } - break - case .updatePeerSettings(let peer, let settings): - if boxed { - buffer.appendInt32(1786671974) - } - peer.serialize(buffer, true) - settings.serialize(buffer, true) - break - case .updatePeerWallpaper(let flags, let peer, let wallpaper): - if boxed { - buffer.appendInt32(-1371598819) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {wallpaper!.serialize(buffer, true)} - break - case .updatePendingJoinRequests(let peer, let requestsPending, let recentRequesters): - if boxed { - buffer.appendInt32(1885586395) - } - peer.serialize(buffer, true) - serializeInt32(requestsPending, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(recentRequesters.count)) - for item in recentRequesters { - serializeInt64(item, buffer: buffer, boxed: false) - } - break - case .updatePhoneCall(let phoneCall): - if boxed { - buffer.appendInt32(-1425052898) - } - phoneCall.serialize(buffer, true) - break - case .updatePhoneCallSignalingData(let phoneCallId, let data): - if boxed { - buffer.appendInt32(643940105) - } - serializeInt64(phoneCallId, buffer: buffer, boxed: false) - serializeBytes(data, buffer: buffer, boxed: false) - break - case .updatePinnedChannelMessages(let flags, let channelId, let messages, let pts, let ptsCount): - if boxed { - buffer.appendInt32(1538885128) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(channelId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - serializeInt32(item, buffer: buffer, boxed: false) - } - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - break - case .updatePinnedDialogs(let flags, let folderId, let order): - if boxed { - buffer.appendInt32(-99664734) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(folderId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order!.count)) - for item in order! { - item.serialize(buffer, true) - }} - break - case .updatePinnedForumTopic(let flags, let peer, let topicId): - if boxed { - buffer.appendInt32(1748708434) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(topicId, buffer: buffer, boxed: false) - break - case .updatePinnedForumTopics(let flags, let peer, let order): - if boxed { - buffer.appendInt32(-554613808) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order!.count)) - for item in order! { - serializeInt32(item, buffer: buffer, boxed: false) - }} - break - case .updatePinnedMessages(let flags, let peer, let messages, let pts, let ptsCount): - if boxed { - buffer.appendInt32(-309990731) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - serializeInt32(item, buffer: buffer, boxed: false) - } - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - break - case .updatePinnedSavedDialogs(let flags, let order): - if boxed { - buffer.appendInt32(1751942566) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order!.count)) - for item in order! { - item.serialize(buffer, true) - }} - break - case .updatePrivacy(let key, let rules): - if boxed { - buffer.appendInt32(-298113238) - } - key.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(rules.count)) - for item in rules { - item.serialize(buffer, true) - } - break - case .updatePtsChanged: - if boxed { - buffer.appendInt32(861169551) - } - - break - case .updateQuickReplies(let quickReplies): - if boxed { - buffer.appendInt32(-112784718) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(quickReplies.count)) - for item in quickReplies { - item.serialize(buffer, true) - } - break - case .updateQuickReplyMessage(let message): - if boxed { - buffer.appendInt32(1040518415) - } - message.serialize(buffer, true) - break - case .updateReadChannelDiscussionInbox(let flags, let channelId, let topMsgId, let readMaxId, let broadcastId, let broadcastPost): - if boxed { - buffer.appendInt32(-693004986) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(channelId, buffer: buffer, boxed: false) - serializeInt32(topMsgId, buffer: buffer, boxed: false) - serializeInt32(readMaxId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(broadcastId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(broadcastPost!, buffer: buffer, boxed: false)} - break - case .updateReadChannelDiscussionOutbox(let channelId, let topMsgId, let readMaxId): - if boxed { - buffer.appendInt32(1767677564) - } - serializeInt64(channelId, buffer: buffer, boxed: false) - serializeInt32(topMsgId, buffer: buffer, boxed: false) - serializeInt32(readMaxId, buffer: buffer, boxed: false) - break - case .updateReadChannelInbox(let flags, let folderId, let channelId, let maxId, let stillUnreadCount, let pts): - if boxed { - buffer.appendInt32(-1842450928) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(folderId!, buffer: buffer, boxed: false)} - serializeInt64(channelId, buffer: buffer, boxed: false) - serializeInt32(maxId, buffer: buffer, boxed: false) - serializeInt32(stillUnreadCount, buffer: buffer, boxed: false) - serializeInt32(pts, buffer: buffer, boxed: false) - break - case .updateReadChannelOutbox(let channelId, let maxId): - if boxed { - buffer.appendInt32(-1218471511) - } - serializeInt64(channelId, buffer: buffer, boxed: false) - serializeInt32(maxId, buffer: buffer, boxed: false) - break - case .updateReadFeaturedEmojiStickers: - if boxed { - buffer.appendInt32(-78886548) - } - - break - case .updateReadFeaturedStickers: - if boxed { - buffer.appendInt32(1461528386) - } - - break - case .updateReadHistoryInbox(let flags, let folderId, let peer, let topMsgId, let maxId, let stillUnreadCount, let pts, let ptsCount): - if boxed { - buffer.appendInt32(-1635468135) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(folderId!, buffer: buffer, boxed: false)} - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - serializeInt32(maxId, buffer: buffer, boxed: false) - serializeInt32(stillUnreadCount, buffer: buffer, boxed: false) - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - break - case .updateReadHistoryOutbox(let peer, let maxId, let pts, let ptsCount): - if boxed { - buffer.appendInt32(791617983) - } - peer.serialize(buffer, true) - serializeInt32(maxId, buffer: buffer, boxed: false) - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - break - case .updateReadMessagesContents(let flags, let messages, let pts, let ptsCount, let date): - if boxed { - buffer.appendInt32(-131960447) - } - serializeInt32(flags, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - serializeInt32(item, buffer: buffer, boxed: false) - } - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(date!, buffer: buffer, boxed: false)} - break - case .updateReadMonoForumInbox(let channelId, let savedPeerId, let readMaxId): - if boxed { - buffer.appendInt32(2008081266) - } - serializeInt64(channelId, buffer: buffer, boxed: false) - savedPeerId.serialize(buffer, true) - serializeInt32(readMaxId, buffer: buffer, boxed: false) - break - case .updateReadMonoForumOutbox(let channelId, let savedPeerId, let readMaxId): - if boxed { - buffer.appendInt32(-1532521610) - } - serializeInt64(channelId, buffer: buffer, boxed: false) - savedPeerId.serialize(buffer, true) - serializeInt32(readMaxId, buffer: buffer, boxed: false) - break - case .updateReadStories(let peer, let maxId): - if boxed { - buffer.appendInt32(-145845461) - } - peer.serialize(buffer, true) - serializeInt32(maxId, buffer: buffer, boxed: false) - break - case .updateRecentEmojiStatuses: - if boxed { - buffer.appendInt32(821314523) - } - - break - case .updateRecentReactions: - if boxed { - buffer.appendInt32(1870160884) - } - - break - case .updateRecentStickers: - if boxed { - buffer.appendInt32(-1706939360) - } - - break - case .updateSavedDialogPinned(let flags, let peer): - if boxed { - buffer.appendInt32(-1364222348) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - break - case .updateSavedGifs: - if boxed { - buffer.appendInt32(-1821035490) - } - - break - case .updateSavedReactionTags: - if boxed { - buffer.appendInt32(969307186) - } - - break - case .updateSavedRingtones: - if boxed { - buffer.appendInt32(1960361625) - } - - break - case .updateSentPhoneCode(let sentCode): - if boxed { - buffer.appendInt32(1347068303) - } - sentCode.serialize(buffer, true) - break - case .updateSentStoryReaction(let peer, let storyId, let reaction): - if boxed { - buffer.appendInt32(2103604867) - } - peer.serialize(buffer, true) - serializeInt32(storyId, buffer: buffer, boxed: false) - reaction.serialize(buffer, true) - break - case .updateServiceNotification(let flags, let inboxDate, let type, let message, let media, let entities): - if boxed { - buffer.appendInt32(-337352679) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(inboxDate!, buffer: buffer, boxed: false)} - serializeString(type, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - media.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities.count)) - for item in entities { - item.serialize(buffer, true) - } - break - case .updateSmsJob(let jobId): - if boxed { - buffer.appendInt32(-245208620) - } - serializeString(jobId, buffer: buffer, boxed: false) - break - case .updateStarGiftAuctionState(let giftId, let state): - if boxed { - buffer.appendInt32(1222788802) - } - serializeInt64(giftId, buffer: buffer, boxed: false) - state.serialize(buffer, true) - break - case .updateStarGiftAuctionUserState(let giftId, let userState): - if boxed { - buffer.appendInt32(-598150370) - } - serializeInt64(giftId, buffer: buffer, boxed: false) - userState.serialize(buffer, true) - break - case .updateStarsBalance(let balance): - if boxed { - buffer.appendInt32(1317053305) - } - balance.serialize(buffer, true) - break - case .updateStarsRevenueStatus(let peer, let status): - if boxed { - buffer.appendInt32(-1518030823) - } - peer.serialize(buffer, true) - status.serialize(buffer, true) - break - case .updateStickerSets(let flags): - if boxed { - buffer.appendInt32(834816008) - } - serializeInt32(flags, buffer: buffer, boxed: false) - break - case .updateStickerSetsOrder(let flags, let order): - if boxed { - buffer.appendInt32(196268545) - } - serializeInt32(flags, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order.count)) - for item in order { - serializeInt64(item, buffer: buffer, boxed: false) - } - break - case .updateStoriesStealthMode(let stealthMode): - if boxed { - buffer.appendInt32(738741697) - } - stealthMode.serialize(buffer, true) - break - case .updateStory(let peer, let story): - if boxed { - buffer.appendInt32(1974712216) - } - peer.serialize(buffer, true) - story.serialize(buffer, true) - break - case .updateStoryID(let id, let randomId): - if boxed { - buffer.appendInt32(468923833) - } - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt64(randomId, buffer: buffer, boxed: false) - break - case .updateTheme(let theme): - if boxed { - buffer.appendInt32(-2112423005) - } - theme.serialize(buffer, true) - break - case .updateTranscribedAudio(let flags, let peer, let msgId, let transcriptionId, let text): - if boxed { - buffer.appendInt32(8703322) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeInt64(transcriptionId, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - break - case .updateUser(let userId): - if boxed { - buffer.appendInt32(542282808) - } - serializeInt64(userId, buffer: buffer, boxed: false) - break - case .updateUserEmojiStatus(let userId, let emojiStatus): - if boxed { - buffer.appendInt32(674706841) - } - serializeInt64(userId, buffer: buffer, boxed: false) - emojiStatus.serialize(buffer, true) - break - case .updateUserName(let userId, let firstName, let lastName, let usernames): - if boxed { - buffer.appendInt32(-1484486364) - } - serializeInt64(userId, buffer: buffer, boxed: false) - serializeString(firstName, buffer: buffer, boxed: false) - serializeString(lastName, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(usernames.count)) - for item in usernames { - item.serialize(buffer, true) - } - break - case .updateUserPhone(let userId, let phone): - if boxed { - buffer.appendInt32(88680979) - } - serializeInt64(userId, buffer: buffer, boxed: false) - serializeString(phone, buffer: buffer, boxed: false) - break - case .updateUserStatus(let userId, let status): - if boxed { - buffer.appendInt32(-440534818) - } - serializeInt64(userId, buffer: buffer, boxed: false) - status.serialize(buffer, true) - break - case .updateUserTyping(let flags, let userId, let topMsgId, let action): - if boxed { - buffer.appendInt32(706199388) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - action.serialize(buffer, true) - break - case .updateWebPage(let webpage, let pts, let ptsCount): - if boxed { - buffer.appendInt32(2139689491) - } - webpage.serialize(buffer, true) - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - break - case .updateWebViewResultSent(let queryId): - if boxed { - buffer.appendInt32(361936797) - } - serializeInt64(queryId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .updateAttachMenuBots: - return ("updateAttachMenuBots", []) - case .updateAutoSaveSettings: - return ("updateAutoSaveSettings", []) - case .updateBotBusinessConnect(let connection, let qts): - return ("updateBotBusinessConnect", [("connection", connection as Any), ("qts", qts as Any)]) - case .updateBotCallbackQuery(let flags, let queryId, let userId, let peer, let msgId, let chatInstance, let data, let gameShortName): - return ("updateBotCallbackQuery", [("flags", flags as Any), ("queryId", queryId as Any), ("userId", userId as Any), ("peer", peer as Any), ("msgId", msgId as Any), ("chatInstance", chatInstance as Any), ("data", data as Any), ("gameShortName", gameShortName as Any)]) - case .updateBotChatBoost(let peer, let boost, let qts): - return ("updateBotChatBoost", [("peer", peer as Any), ("boost", boost as Any), ("qts", qts as Any)]) - case .updateBotChatInviteRequester(let peer, let date, let userId, let about, let invite, let qts): - return ("updateBotChatInviteRequester", [("peer", peer as Any), ("date", date as Any), ("userId", userId as Any), ("about", about as Any), ("invite", invite as Any), ("qts", qts as Any)]) - case .updateBotCommands(let peer, let botId, let commands): - return ("updateBotCommands", [("peer", peer as Any), ("botId", botId as Any), ("commands", commands as Any)]) - case .updateBotDeleteBusinessMessage(let connectionId, let peer, let messages, let qts): - return ("updateBotDeleteBusinessMessage", [("connectionId", connectionId as Any), ("peer", peer as Any), ("messages", messages as Any), ("qts", qts as Any)]) - case .updateBotEditBusinessMessage(let flags, let connectionId, let message, let replyToMessage, let qts): - return ("updateBotEditBusinessMessage", [("flags", flags as Any), ("connectionId", connectionId as Any), ("message", message as Any), ("replyToMessage", replyToMessage as Any), ("qts", qts as Any)]) - case .updateBotInlineQuery(let flags, let queryId, let userId, let query, let geo, let peerType, let offset): - return ("updateBotInlineQuery", [("flags", flags as Any), ("queryId", queryId as Any), ("userId", userId as Any), ("query", query as Any), ("geo", geo as Any), ("peerType", peerType as Any), ("offset", offset as Any)]) - case .updateBotInlineSend(let flags, let userId, let query, let geo, let id, let msgId): - return ("updateBotInlineSend", [("flags", flags as Any), ("userId", userId as Any), ("query", query as Any), ("geo", geo as Any), ("id", id as Any), ("msgId", msgId as Any)]) - case .updateBotMenuButton(let botId, let button): - return ("updateBotMenuButton", [("botId", botId as Any), ("button", button as Any)]) - case .updateBotMessageReaction(let peer, let msgId, let date, let actor, let oldReactions, let newReactions, let qts): - return ("updateBotMessageReaction", [("peer", peer as Any), ("msgId", msgId as Any), ("date", date as Any), ("actor", actor as Any), ("oldReactions", oldReactions as Any), ("newReactions", newReactions as Any), ("qts", qts as Any)]) - case .updateBotMessageReactions(let peer, let msgId, let date, let reactions, let qts): - return ("updateBotMessageReactions", [("peer", peer as Any), ("msgId", msgId as Any), ("date", date as Any), ("reactions", reactions as Any), ("qts", qts as Any)]) - case .updateBotNewBusinessMessage(let flags, let connectionId, let message, let replyToMessage, let qts): - return ("updateBotNewBusinessMessage", [("flags", flags as Any), ("connectionId", connectionId as Any), ("message", message as Any), ("replyToMessage", replyToMessage as Any), ("qts", qts as Any)]) - case .updateBotPrecheckoutQuery(let flags, let queryId, let userId, let payload, let info, let shippingOptionId, let currency, let totalAmount): - return ("updateBotPrecheckoutQuery", [("flags", flags as Any), ("queryId", queryId as Any), ("userId", userId as Any), ("payload", payload as Any), ("info", info as Any), ("shippingOptionId", shippingOptionId as Any), ("currency", currency as Any), ("totalAmount", totalAmount as Any)]) - case .updateBotPurchasedPaidMedia(let userId, let payload, let qts): - return ("updateBotPurchasedPaidMedia", [("userId", userId as Any), ("payload", payload as Any), ("qts", qts as Any)]) - case .updateBotShippingQuery(let queryId, let userId, let payload, let shippingAddress): - return ("updateBotShippingQuery", [("queryId", queryId as Any), ("userId", userId as Any), ("payload", payload as Any), ("shippingAddress", shippingAddress as Any)]) - case .updateBotStopped(let userId, let date, let stopped, let qts): - return ("updateBotStopped", [("userId", userId as Any), ("date", date as Any), ("stopped", stopped as Any), ("qts", qts as Any)]) - case .updateBotWebhookJSON(let data): - return ("updateBotWebhookJSON", [("data", data as Any)]) - case .updateBotWebhookJSONQuery(let queryId, let data, let timeout): - return ("updateBotWebhookJSONQuery", [("queryId", queryId as Any), ("data", data as Any), ("timeout", timeout as Any)]) - case .updateBusinessBotCallbackQuery(let flags, let queryId, let userId, let connectionId, let message, let replyToMessage, let chatInstance, let data): - return ("updateBusinessBotCallbackQuery", [("flags", flags as Any), ("queryId", queryId as Any), ("userId", userId as Any), ("connectionId", connectionId as Any), ("message", message as Any), ("replyToMessage", replyToMessage as Any), ("chatInstance", chatInstance as Any), ("data", data as Any)]) - case .updateChannel(let channelId): - return ("updateChannel", [("channelId", channelId as Any)]) - case .updateChannelAvailableMessages(let channelId, let availableMinId): - return ("updateChannelAvailableMessages", [("channelId", channelId as Any), ("availableMinId", availableMinId as Any)]) - case .updateChannelMessageForwards(let channelId, let id, let forwards): - return ("updateChannelMessageForwards", [("channelId", channelId as Any), ("id", id as Any), ("forwards", forwards as Any)]) - case .updateChannelMessageViews(let channelId, let id, let views): - return ("updateChannelMessageViews", [("channelId", channelId as Any), ("id", id as Any), ("views", views as Any)]) - case .updateChannelParticipant(let flags, let channelId, let date, let actorId, let userId, let prevParticipant, let newParticipant, let invite, let qts): - return ("updateChannelParticipant", [("flags", flags as Any), ("channelId", channelId as Any), ("date", date as Any), ("actorId", actorId as Any), ("userId", userId as Any), ("prevParticipant", prevParticipant as Any), ("newParticipant", newParticipant as Any), ("invite", invite as Any), ("qts", qts as Any)]) - case .updateChannelReadMessagesContents(let flags, let channelId, let topMsgId, let savedPeerId, let messages): - return ("updateChannelReadMessagesContents", [("flags", flags as Any), ("channelId", channelId as Any), ("topMsgId", topMsgId as Any), ("savedPeerId", savedPeerId as Any), ("messages", messages as Any)]) - case .updateChannelTooLong(let flags, let channelId, let pts): - return ("updateChannelTooLong", [("flags", flags as Any), ("channelId", channelId as Any), ("pts", pts as Any)]) - case .updateChannelUserTyping(let flags, let channelId, let topMsgId, let fromId, let action): - return ("updateChannelUserTyping", [("flags", flags as Any), ("channelId", channelId as Any), ("topMsgId", topMsgId as Any), ("fromId", fromId as Any), ("action", action as Any)]) - case .updateChannelViewForumAsMessages(let channelId, let enabled): - return ("updateChannelViewForumAsMessages", [("channelId", channelId as Any), ("enabled", enabled as Any)]) - case .updateChannelWebPage(let channelId, let webpage, let pts, let ptsCount): - return ("updateChannelWebPage", [("channelId", channelId as Any), ("webpage", webpage as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any)]) - case .updateChat(let chatId): - return ("updateChat", [("chatId", chatId as Any)]) - case .updateChatDefaultBannedRights(let peer, let defaultBannedRights, let version): - return ("updateChatDefaultBannedRights", [("peer", peer as Any), ("defaultBannedRights", defaultBannedRights as Any), ("version", version as Any)]) - case .updateChatParticipant(let flags, let chatId, let date, let actorId, let userId, let prevParticipant, let newParticipant, let invite, let qts): - return ("updateChatParticipant", [("flags", flags as Any), ("chatId", chatId as Any), ("date", date as Any), ("actorId", actorId as Any), ("userId", userId as Any), ("prevParticipant", prevParticipant as Any), ("newParticipant", newParticipant as Any), ("invite", invite as Any), ("qts", qts as Any)]) - case .updateChatParticipantAdd(let chatId, let userId, let inviterId, let date, let version): - return ("updateChatParticipantAdd", [("chatId", chatId as Any), ("userId", userId as Any), ("inviterId", inviterId as Any), ("date", date as Any), ("version", version as Any)]) - case .updateChatParticipantAdmin(let chatId, let userId, let isAdmin, let version): - return ("updateChatParticipantAdmin", [("chatId", chatId as Any), ("userId", userId as Any), ("isAdmin", isAdmin as Any), ("version", version as Any)]) - case .updateChatParticipantDelete(let chatId, let userId, let version): - return ("updateChatParticipantDelete", [("chatId", chatId as Any), ("userId", userId as Any), ("version", version as Any)]) - case .updateChatParticipants(let participants): - return ("updateChatParticipants", [("participants", participants as Any)]) - case .updateChatUserTyping(let chatId, let fromId, let action): - return ("updateChatUserTyping", [("chatId", chatId as Any), ("fromId", fromId as Any), ("action", action as Any)]) - case .updateConfig: - return ("updateConfig", []) - case .updateContactsReset: - return ("updateContactsReset", []) - case .updateDcOptions(let dcOptions): - return ("updateDcOptions", [("dcOptions", dcOptions as Any)]) - case .updateDeleteChannelMessages(let channelId, let messages, let pts, let ptsCount): - return ("updateDeleteChannelMessages", [("channelId", channelId as Any), ("messages", messages as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any)]) - case .updateDeleteGroupCallMessages(let call, let messages): - return ("updateDeleteGroupCallMessages", [("call", call as Any), ("messages", messages as Any)]) - case .updateDeleteMessages(let messages, let pts, let ptsCount): - return ("updateDeleteMessages", [("messages", messages as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any)]) - case .updateDeleteQuickReply(let shortcutId): - return ("updateDeleteQuickReply", [("shortcutId", shortcutId as Any)]) - case .updateDeleteQuickReplyMessages(let shortcutId, let messages): - return ("updateDeleteQuickReplyMessages", [("shortcutId", shortcutId as Any), ("messages", messages as Any)]) - case .updateDeleteScheduledMessages(let flags, let peer, let messages, let sentMessages): - return ("updateDeleteScheduledMessages", [("flags", flags as Any), ("peer", peer as Any), ("messages", messages as Any), ("sentMessages", sentMessages as Any)]) - case .updateDialogFilter(let flags, let id, let filter): - return ("updateDialogFilter", [("flags", flags as Any), ("id", id as Any), ("filter", filter as Any)]) - case .updateDialogFilterOrder(let order): - return ("updateDialogFilterOrder", [("order", order as Any)]) - case .updateDialogFilters: - return ("updateDialogFilters", []) - case .updateDialogPinned(let flags, let folderId, let peer): - return ("updateDialogPinned", [("flags", flags as Any), ("folderId", folderId as Any), ("peer", peer as Any)]) - case .updateDialogUnreadMark(let flags, let peer, let savedPeerId): - return ("updateDialogUnreadMark", [("flags", flags as Any), ("peer", peer as Any), ("savedPeerId", savedPeerId as Any)]) - case .updateDraftMessage(let flags, let peer, let topMsgId, let savedPeerId, let draft): - return ("updateDraftMessage", [("flags", flags as Any), ("peer", peer as Any), ("topMsgId", topMsgId as Any), ("savedPeerId", savedPeerId as Any), ("draft", draft as Any)]) - case .updateEditChannelMessage(let message, let pts, let ptsCount): - return ("updateEditChannelMessage", [("message", message as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any)]) - case .updateEditMessage(let message, let pts, let ptsCount): - return ("updateEditMessage", [("message", message as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any)]) - case .updateEmojiGameInfo(let info): - return ("updateEmojiGameInfo", [("info", info as Any)]) - case .updateEncryptedChatTyping(let chatId): - return ("updateEncryptedChatTyping", [("chatId", chatId as Any)]) - case .updateEncryptedMessagesRead(let chatId, let maxDate, let date): - return ("updateEncryptedMessagesRead", [("chatId", chatId as Any), ("maxDate", maxDate as Any), ("date", date as Any)]) - case .updateEncryption(let chat, let date): - return ("updateEncryption", [("chat", chat as Any), ("date", date as Any)]) - case .updateFavedStickers: - return ("updateFavedStickers", []) - case .updateFolderPeers(let folderPeers, let pts, let ptsCount): - return ("updateFolderPeers", [("folderPeers", folderPeers as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any)]) - case .updateGeoLiveViewed(let peer, let msgId): - return ("updateGeoLiveViewed", [("peer", peer as Any), ("msgId", msgId as Any)]) - case .updateGroupCall(let flags, let peer, let call): - return ("updateGroupCall", [("flags", flags as Any), ("peer", peer as Any), ("call", call as Any)]) - case .updateGroupCallChainBlocks(let call, let subChainId, let blocks, let nextOffset): - return ("updateGroupCallChainBlocks", [("call", call as Any), ("subChainId", subChainId as Any), ("blocks", blocks as Any), ("nextOffset", nextOffset as Any)]) - case .updateGroupCallConnection(let flags, let params): - return ("updateGroupCallConnection", [("flags", flags as Any), ("params", params as Any)]) - case .updateGroupCallEncryptedMessage(let call, let fromId, let encryptedMessage): - return ("updateGroupCallEncryptedMessage", [("call", call as Any), ("fromId", fromId as Any), ("encryptedMessage", encryptedMessage as Any)]) - case .updateGroupCallMessage(let call, let message): - return ("updateGroupCallMessage", [("call", call as Any), ("message", message as Any)]) - case .updateGroupCallParticipants(let call, let participants, let version): - return ("updateGroupCallParticipants", [("call", call as Any), ("participants", participants as Any), ("version", version as Any)]) - case .updateInlineBotCallbackQuery(let flags, let queryId, let userId, let msgId, let chatInstance, let data, let gameShortName): - return ("updateInlineBotCallbackQuery", [("flags", flags as Any), ("queryId", queryId as Any), ("userId", userId as Any), ("msgId", msgId as Any), ("chatInstance", chatInstance as Any), ("data", data as Any), ("gameShortName", gameShortName as Any)]) - case .updateLangPack(let difference): - return ("updateLangPack", [("difference", difference as Any)]) - case .updateLangPackTooLong(let langCode): - return ("updateLangPackTooLong", [("langCode", langCode as Any)]) - case .updateLoginToken: - return ("updateLoginToken", []) - case .updateMessageExtendedMedia(let peer, let msgId, let extendedMedia): - return ("updateMessageExtendedMedia", [("peer", peer as Any), ("msgId", msgId as Any), ("extendedMedia", extendedMedia as Any)]) - case .updateMessageID(let id, let randomId): - return ("updateMessageID", [("id", id as Any), ("randomId", randomId as Any)]) - case .updateMessagePoll(let flags, let pollId, let poll, let results): - return ("updateMessagePoll", [("flags", flags as Any), ("pollId", pollId as Any), ("poll", poll as Any), ("results", results as Any)]) - case .updateMessagePollVote(let pollId, let peer, let options, let qts): - return ("updateMessagePollVote", [("pollId", pollId as Any), ("peer", peer as Any), ("options", options as Any), ("qts", qts as Any)]) - case .updateMessageReactions(let flags, let peer, let msgId, let topMsgId, let savedPeerId, let reactions): - return ("updateMessageReactions", [("flags", flags as Any), ("peer", peer as Any), ("msgId", msgId as Any), ("topMsgId", topMsgId as Any), ("savedPeerId", savedPeerId as Any), ("reactions", reactions as Any)]) - case .updateMonoForumNoPaidException(let flags, let channelId, let savedPeerId): - return ("updateMonoForumNoPaidException", [("flags", flags as Any), ("channelId", channelId as Any), ("savedPeerId", savedPeerId as Any)]) - case .updateMoveStickerSetToTop(let flags, let stickerset): - return ("updateMoveStickerSetToTop", [("flags", flags as Any), ("stickerset", stickerset as Any)]) - case .updateNewAuthorization(let flags, let hash, let date, let device, let location): - return ("updateNewAuthorization", [("flags", flags as Any), ("hash", hash as Any), ("date", date as Any), ("device", device as Any), ("location", location as Any)]) - case .updateNewChannelMessage(let message, let pts, let ptsCount): - return ("updateNewChannelMessage", [("message", message as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any)]) - case .updateNewEncryptedMessage(let message, let qts): - return ("updateNewEncryptedMessage", [("message", message as Any), ("qts", qts as Any)]) - case .updateNewMessage(let message, let pts, let ptsCount): - return ("updateNewMessage", [("message", message as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any)]) - case .updateNewQuickReply(let quickReply): - return ("updateNewQuickReply", [("quickReply", quickReply as Any)]) - case .updateNewScheduledMessage(let message): - return ("updateNewScheduledMessage", [("message", message as Any)]) - case .updateNewStickerSet(let stickerset): - return ("updateNewStickerSet", [("stickerset", stickerset as Any)]) - case .updateNewStoryReaction(let storyId, let peer, let reaction): - return ("updateNewStoryReaction", [("storyId", storyId as Any), ("peer", peer as Any), ("reaction", reaction as Any)]) - case .updateNotifySettings(let peer, let notifySettings): - return ("updateNotifySettings", [("peer", peer as Any), ("notifySettings", notifySettings as Any)]) - case .updatePaidReactionPrivacy(let `private`): - return ("updatePaidReactionPrivacy", [("`private`", `private` as Any)]) - case .updatePeerBlocked(let flags, let peerId): - return ("updatePeerBlocked", [("flags", flags as Any), ("peerId", peerId as Any)]) - case .updatePeerHistoryTTL(let flags, let peer, let ttlPeriod): - return ("updatePeerHistoryTTL", [("flags", flags as Any), ("peer", peer as Any), ("ttlPeriod", ttlPeriod as Any)]) - case .updatePeerLocated(let peers): - return ("updatePeerLocated", [("peers", peers as Any)]) - case .updatePeerSettings(let peer, let settings): - return ("updatePeerSettings", [("peer", peer as Any), ("settings", settings as Any)]) - case .updatePeerWallpaper(let flags, let peer, let wallpaper): - return ("updatePeerWallpaper", [("flags", flags as Any), ("peer", peer as Any), ("wallpaper", wallpaper as Any)]) - case .updatePendingJoinRequests(let peer, let requestsPending, let recentRequesters): - return ("updatePendingJoinRequests", [("peer", peer as Any), ("requestsPending", requestsPending as Any), ("recentRequesters", recentRequesters as Any)]) - case .updatePhoneCall(let phoneCall): - return ("updatePhoneCall", [("phoneCall", phoneCall as Any)]) - case .updatePhoneCallSignalingData(let phoneCallId, let data): - return ("updatePhoneCallSignalingData", [("phoneCallId", phoneCallId as Any), ("data", data as Any)]) - case .updatePinnedChannelMessages(let flags, let channelId, let messages, let pts, let ptsCount): - return ("updatePinnedChannelMessages", [("flags", flags as Any), ("channelId", channelId as Any), ("messages", messages as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any)]) - case .updatePinnedDialogs(let flags, let folderId, let order): - return ("updatePinnedDialogs", [("flags", flags as Any), ("folderId", folderId as Any), ("order", order as Any)]) - case .updatePinnedForumTopic(let flags, let peer, let topicId): - return ("updatePinnedForumTopic", [("flags", flags as Any), ("peer", peer as Any), ("topicId", topicId as Any)]) - case .updatePinnedForumTopics(let flags, let peer, let order): - return ("updatePinnedForumTopics", [("flags", flags as Any), ("peer", peer as Any), ("order", order as Any)]) - case .updatePinnedMessages(let flags, let peer, let messages, let pts, let ptsCount): - return ("updatePinnedMessages", [("flags", flags as Any), ("peer", peer as Any), ("messages", messages as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any)]) - case .updatePinnedSavedDialogs(let flags, let order): - return ("updatePinnedSavedDialogs", [("flags", flags as Any), ("order", order as Any)]) - case .updatePrivacy(let key, let rules): - return ("updatePrivacy", [("key", key as Any), ("rules", rules as Any)]) - case .updatePtsChanged: - return ("updatePtsChanged", []) - case .updateQuickReplies(let quickReplies): - return ("updateQuickReplies", [("quickReplies", quickReplies as Any)]) - case .updateQuickReplyMessage(let message): - return ("updateQuickReplyMessage", [("message", message as Any)]) - case .updateReadChannelDiscussionInbox(let flags, let channelId, let topMsgId, let readMaxId, let broadcastId, let broadcastPost): - return ("updateReadChannelDiscussionInbox", [("flags", flags as Any), ("channelId", channelId as Any), ("topMsgId", topMsgId as Any), ("readMaxId", readMaxId as Any), ("broadcastId", broadcastId as Any), ("broadcastPost", broadcastPost as Any)]) - case .updateReadChannelDiscussionOutbox(let channelId, let topMsgId, let readMaxId): - return ("updateReadChannelDiscussionOutbox", [("channelId", channelId as Any), ("topMsgId", topMsgId as Any), ("readMaxId", readMaxId as Any)]) - case .updateReadChannelInbox(let flags, let folderId, let channelId, let maxId, let stillUnreadCount, let pts): - return ("updateReadChannelInbox", [("flags", flags as Any), ("folderId", folderId as Any), ("channelId", channelId as Any), ("maxId", maxId as Any), ("stillUnreadCount", stillUnreadCount as Any), ("pts", pts as Any)]) - case .updateReadChannelOutbox(let channelId, let maxId): - return ("updateReadChannelOutbox", [("channelId", channelId as Any), ("maxId", maxId as Any)]) - case .updateReadFeaturedEmojiStickers: - return ("updateReadFeaturedEmojiStickers", []) - case .updateReadFeaturedStickers: - return ("updateReadFeaturedStickers", []) - case .updateReadHistoryInbox(let flags, let folderId, let peer, let topMsgId, let maxId, let stillUnreadCount, let pts, let ptsCount): - return ("updateReadHistoryInbox", [("flags", flags as Any), ("folderId", folderId as Any), ("peer", peer as Any), ("topMsgId", topMsgId as Any), ("maxId", maxId as Any), ("stillUnreadCount", stillUnreadCount as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any)]) - case .updateReadHistoryOutbox(let peer, let maxId, let pts, let ptsCount): - return ("updateReadHistoryOutbox", [("peer", peer as Any), ("maxId", maxId as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any)]) - case .updateReadMessagesContents(let flags, let messages, let pts, let ptsCount, let date): - return ("updateReadMessagesContents", [("flags", flags as Any), ("messages", messages as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any), ("date", date as Any)]) - case .updateReadMonoForumInbox(let channelId, let savedPeerId, let readMaxId): - return ("updateReadMonoForumInbox", [("channelId", channelId as Any), ("savedPeerId", savedPeerId as Any), ("readMaxId", readMaxId as Any)]) - case .updateReadMonoForumOutbox(let channelId, let savedPeerId, let readMaxId): - return ("updateReadMonoForumOutbox", [("channelId", channelId as Any), ("savedPeerId", savedPeerId as Any), ("readMaxId", readMaxId as Any)]) - case .updateReadStories(let peer, let maxId): - return ("updateReadStories", [("peer", peer as Any), ("maxId", maxId as Any)]) - case .updateRecentEmojiStatuses: - return ("updateRecentEmojiStatuses", []) - case .updateRecentReactions: - return ("updateRecentReactions", []) - case .updateRecentStickers: - return ("updateRecentStickers", []) - case .updateSavedDialogPinned(let flags, let peer): - return ("updateSavedDialogPinned", [("flags", flags as Any), ("peer", peer as Any)]) - case .updateSavedGifs: - return ("updateSavedGifs", []) - case .updateSavedReactionTags: - return ("updateSavedReactionTags", []) - case .updateSavedRingtones: - return ("updateSavedRingtones", []) - case .updateSentPhoneCode(let sentCode): - return ("updateSentPhoneCode", [("sentCode", sentCode as Any)]) - case .updateSentStoryReaction(let peer, let storyId, let reaction): - return ("updateSentStoryReaction", [("peer", peer as Any), ("storyId", storyId as Any), ("reaction", reaction as Any)]) - case .updateServiceNotification(let flags, let inboxDate, let type, let message, let media, let entities): - return ("updateServiceNotification", [("flags", flags as Any), ("inboxDate", inboxDate as Any), ("type", type as Any), ("message", message as Any), ("media", media as Any), ("entities", entities as Any)]) - case .updateSmsJob(let jobId): - return ("updateSmsJob", [("jobId", jobId as Any)]) - case .updateStarGiftAuctionState(let giftId, let state): - return ("updateStarGiftAuctionState", [("giftId", giftId as Any), ("state", state as Any)]) - case .updateStarGiftAuctionUserState(let giftId, let userState): - return ("updateStarGiftAuctionUserState", [("giftId", giftId as Any), ("userState", userState as Any)]) - case .updateStarsBalance(let balance): - return ("updateStarsBalance", [("balance", balance as Any)]) - case .updateStarsRevenueStatus(let peer, let status): - return ("updateStarsRevenueStatus", [("peer", peer as Any), ("status", status as Any)]) - case .updateStickerSets(let flags): - return ("updateStickerSets", [("flags", flags as Any)]) - case .updateStickerSetsOrder(let flags, let order): - return ("updateStickerSetsOrder", [("flags", flags as Any), ("order", order as Any)]) - case .updateStoriesStealthMode(let stealthMode): - return ("updateStoriesStealthMode", [("stealthMode", stealthMode as Any)]) - case .updateStory(let peer, let story): - return ("updateStory", [("peer", peer as Any), ("story", story as Any)]) - case .updateStoryID(let id, let randomId): - return ("updateStoryID", [("id", id as Any), ("randomId", randomId as Any)]) - case .updateTheme(let theme): - return ("updateTheme", [("theme", theme as Any)]) - case .updateTranscribedAudio(let flags, let peer, let msgId, let transcriptionId, let text): - return ("updateTranscribedAudio", [("flags", flags as Any), ("peer", peer as Any), ("msgId", msgId as Any), ("transcriptionId", transcriptionId as Any), ("text", text as Any)]) - case .updateUser(let userId): - return ("updateUser", [("userId", userId as Any)]) - case .updateUserEmojiStatus(let userId, let emojiStatus): - return ("updateUserEmojiStatus", [("userId", userId as Any), ("emojiStatus", emojiStatus as Any)]) - case .updateUserName(let userId, let firstName, let lastName, let usernames): - return ("updateUserName", [("userId", userId as Any), ("firstName", firstName as Any), ("lastName", lastName as Any), ("usernames", usernames as Any)]) - case .updateUserPhone(let userId, let phone): - return ("updateUserPhone", [("userId", userId as Any), ("phone", phone as Any)]) - case .updateUserStatus(let userId, let status): - return ("updateUserStatus", [("userId", userId as Any), ("status", status as Any)]) - case .updateUserTyping(let flags, let userId, let topMsgId, let action): - return ("updateUserTyping", [("flags", flags as Any), ("userId", userId as Any), ("topMsgId", topMsgId as Any), ("action", action as Any)]) - case .updateWebPage(let webpage, let pts, let ptsCount): - return ("updateWebPage", [("webpage", webpage as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any)]) - case .updateWebViewResultSent(let queryId): - return ("updateWebViewResultSent", [("queryId", queryId as Any)]) - } - } - - public static func parse_updateAttachMenuBots(_ reader: BufferReader) -> Update? { - return Api.Update.updateAttachMenuBots - } - public static func parse_updateAutoSaveSettings(_ reader: BufferReader) -> Update? { - return Api.Update.updateAutoSaveSettings - } - public static func parse_updateBotBusinessConnect(_ reader: BufferReader) -> Update? { - var _1: Api.BotBusinessConnection? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.BotBusinessConnection - } - var _2: Int32? - _2 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateBotBusinessConnect(connection: _1!, qts: _2!) - } - public static func parse_updateBotCallbackQuery(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int64? - _3 = reader.readInt64() - var _4: Api.Peer? - if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _5: Int32? - _5 = reader.readInt32() - var _6: Int64? - _6 = reader.readInt64() - var _7: Buffer? - if Int(_1!) & Int(1 << 0) != 0 {_7 = parseBytes(reader) } - var _8: String? - if Int(_1!) & Int(1 << 1) != 0 {_8 = parseString(reader) } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - let _c7 = (Int(_1!) & Int(1 << 0) == 0) || _7 != nil - let _c8 = (Int(_1!) & Int(1 << 1) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.Update.updateBotCallbackQuery(flags: _1!, queryId: _2!, userId: _3!, peer: _4!, msgId: _5!, chatInstance: _6!, data: _7, gameShortName: _8) - } - public static func parse_updateBotChatBoost(_ reader: BufferReader) -> Update? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: Api.Boost? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Boost - } - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateBotChatBoost(peer: _1!, boost: _2!, qts: _3!) - } - public static func parse_updateBotChatInviteRequester(_ reader: BufferReader) -> Update? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: Int32? - _2 = reader.readInt32() - var _3: Int64? - _3 = reader.readInt64() - var _4: String? - _4 = parseString(reader) - var _5: Api.ExportedChatInvite? - if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite - } - var _6: Int32? - _6 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.Update.updateBotChatInviteRequester(peer: _1!, date: _2!, userId: _3!, about: _4!, invite: _5!, qts: _6!) - } - public static func parse_updateBotCommands(_ reader: BufferReader) -> Update? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: Int64? - _2 = reader.readInt64() - var _3: [Api.BotCommand]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.BotCommand.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateBotCommands(peer: _1!, botId: _2!, commands: _3!) - } - public static func parse_updateBotDeleteBusinessMessage(_ reader: BufferReader) -> Update? { - var _1: String? - _1 = parseString(reader) - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: [Int32]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - var _4: Int32? - _4 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.Update.updateBotDeleteBusinessMessage(connectionId: _1!, peer: _2!, messages: _3!, qts: _4!) - } - public static func parse_updateBotEditBusinessMessage(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: String? - _2 = parseString(reader) - var _3: Api.Message? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Message - } - var _4: Api.Message? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Message - } } - var _5: Int32? - _5 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.Update.updateBotEditBusinessMessage(flags: _1!, connectionId: _2!, message: _3!, replyToMessage: _4, qts: _5!) - } - public static func parse_updateBotInlineQuery(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int64? - _3 = reader.readInt64() - var _4: String? - _4 = parseString(reader) - var _5: Api.GeoPoint? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.GeoPoint - } } - var _6: Api.InlineQueryPeerType? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.InlineQueryPeerType - } } - var _7: String? - _7 = parseString(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil - let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil - let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.Update.updateBotInlineQuery(flags: _1!, queryId: _2!, userId: _3!, query: _4!, geo: _5, peerType: _6, offset: _7!) - } - public static func parse_updateBotInlineSend(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: String? - _3 = parseString(reader) - var _4: Api.GeoPoint? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.GeoPoint - } } - var _5: String? - _5 = parseString(reader) - var _6: Api.InputBotInlineMessageID? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.InputBotInlineMessageID - } } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.Update.updateBotInlineSend(flags: _1!, userId: _2!, query: _3!, geo: _4, id: _5!, msgId: _6) - } - public static func parse_updateBotMenuButton(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Api.BotMenuButton? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.BotMenuButton - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateBotMenuButton(botId: _1!, button: _2!) - } - public static func parse_updateBotMessageReaction(_ reader: BufferReader) -> Update? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - var _4: Api.Peer? - if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _5: [Api.Reaction]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Reaction.self) - } - var _6: [Api.Reaction]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Reaction.self) - } - var _7: Int32? - _7 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.Update.updateBotMessageReaction(peer: _1!, msgId: _2!, date: _3!, actor: _4!, oldReactions: _5!, newReactions: _6!, qts: _7!) - } - public static func parse_updateBotMessageReactions(_ reader: BufferReader) -> Update? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - var _4: [Api.ReactionCount]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ReactionCount.self) - } - var _5: Int32? - _5 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.Update.updateBotMessageReactions(peer: _1!, msgId: _2!, date: _3!, reactions: _4!, qts: _5!) - } - public static func parse_updateBotNewBusinessMessage(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: String? - _2 = parseString(reader) - var _3: Api.Message? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Message - } - var _4: Api.Message? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Message - } } - var _5: Int32? - _5 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.Update.updateBotNewBusinessMessage(flags: _1!, connectionId: _2!, message: _3!, replyToMessage: _4, qts: _5!) - } - public static func parse_updateBotPrecheckoutQuery(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int64? - _3 = reader.readInt64() - var _4: Buffer? - _4 = parseBytes(reader) - var _5: Api.PaymentRequestedInfo? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.PaymentRequestedInfo - } } - var _6: String? - if Int(_1!) & Int(1 << 1) != 0 {_6 = parseString(reader) } - var _7: String? - _7 = parseString(reader) - var _8: Int64? - _8 = reader.readInt64() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil - let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil - let _c7 = _7 != nil - let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.Update.updateBotPrecheckoutQuery(flags: _1!, queryId: _2!, userId: _3!, payload: _4!, info: _5, shippingOptionId: _6, currency: _7!, totalAmount: _8!) - } - public static func parse_updateBotPurchasedPaidMedia(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: String? - _2 = parseString(reader) - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateBotPurchasedPaidMedia(userId: _1!, payload: _2!, qts: _3!) - } - public static func parse_updateBotShippingQuery(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Int64? - _2 = reader.readInt64() - var _3: Buffer? - _3 = parseBytes(reader) - var _4: Api.PostAddress? - if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.PostAddress - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.Update.updateBotShippingQuery(queryId: _1!, userId: _2!, payload: _3!, shippingAddress: _4!) - } - public static func parse_updateBotStopped(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Int32? - _2 = reader.readInt32() - var _3: Api.Bool? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Bool - } - var _4: Int32? - _4 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.Update.updateBotStopped(userId: _1!, date: _2!, stopped: _3!, qts: _4!) - } - public static func parse_updateBotWebhookJSON(_ reader: BufferReader) -> Update? { - var _1: Api.DataJSON? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.DataJSON - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateBotWebhookJSON(data: _1!) - } - public static func parse_updateBotWebhookJSONQuery(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Api.DataJSON? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.DataJSON - } - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateBotWebhookJSONQuery(queryId: _1!, data: _2!, timeout: _3!) - } - public static func parse_updateBusinessBotCallbackQuery(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int64? - _3 = reader.readInt64() - var _4: String? - _4 = parseString(reader) - var _5: Api.Message? - if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.Message - } - var _6: Api.Message? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.Message - } } - var _7: Int64? - _7 = reader.readInt64() - var _8: Buffer? - if Int(_1!) & Int(1 << 0) != 0 {_8 = parseBytes(reader) } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil - let _c7 = _7 != nil - let _c8 = (Int(_1!) & Int(1 << 0) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.Update.updateBusinessBotCallbackQuery(flags: _1!, queryId: _2!, userId: _3!, connectionId: _4!, message: _5!, replyToMessage: _6, chatInstance: _7!, data: _8) - } - public static func parse_updateChannel(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateChannel(channelId: _1!) - } - public static func parse_updateChannelAvailableMessages(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Int32? - _2 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateChannelAvailableMessages(channelId: _1!, availableMinId: _2!) - } - public static func parse_updateChannelMessageForwards(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateChannelMessageForwards(channelId: _1!, id: _2!, forwards: _3!) - } - public static func parse_updateChannelMessageViews(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateChannelMessageViews(channelId: _1!, id: _2!, views: _3!) - } - public static func parse_updateChannelParticipant(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int32? - _3 = reader.readInt32() - var _4: Int64? - _4 = reader.readInt64() - var _5: Int64? - _5 = reader.readInt64() - var _6: Api.ChannelParticipant? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.ChannelParticipant - } } - var _7: Api.ChannelParticipant? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.ChannelParticipant - } } - var _8: Api.ExportedChatInvite? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite - } } - var _9: Int32? - _9 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil - let _c8 = (Int(_1!) & Int(1 << 2) == 0) || _8 != nil - let _c9 = _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.Update.updateChannelParticipant(flags: _1!, channelId: _2!, date: _3!, actorId: _4!, userId: _5!, prevParticipant: _6, newParticipant: _7, invite: _8, qts: _9!) - } - public static func parse_updateChannelReadMessagesContents(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } - var _4: Api.Peer? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Peer - } } - var _5: [Int32]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.Update.updateChannelReadMessagesContents(flags: _1!, channelId: _2!, topMsgId: _3, savedPeerId: _4, messages: _5!) - } - public static func parse_updateChannelTooLong(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateChannelTooLong(flags: _1!, channelId: _2!, pts: _3) - } - public static func parse_updateChannelUserTyping(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } - var _4: Api.Peer? - if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _5: Api.SendMessageAction? - if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.SendMessageAction - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.Update.updateChannelUserTyping(flags: _1!, channelId: _2!, topMsgId: _3, fromId: _4!, action: _5!) - } - public static func parse_updateChannelViewForumAsMessages(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Api.Bool? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Bool - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateChannelViewForumAsMessages(channelId: _1!, enabled: _2!) - } - public static func parse_updateChannelWebPage(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Api.WebPage? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.WebPage - } - var _3: Int32? - _3 = reader.readInt32() - var _4: Int32? - _4 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.Update.updateChannelWebPage(channelId: _1!, webpage: _2!, pts: _3!, ptsCount: _4!) - } - public static func parse_updateChat(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateChat(chatId: _1!) - } - public static func parse_updateChatDefaultBannedRights(_ reader: BufferReader) -> Update? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: Api.ChatBannedRights? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.ChatBannedRights - } - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateChatDefaultBannedRights(peer: _1!, defaultBannedRights: _2!, version: _3!) - } - public static func parse_updateChatParticipant(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int32? - _3 = reader.readInt32() - var _4: Int64? - _4 = reader.readInt64() - var _5: Int64? - _5 = reader.readInt64() - var _6: Api.ChatParticipant? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.ChatParticipant - } } - var _7: Api.ChatParticipant? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.ChatParticipant - } } - var _8: Api.ExportedChatInvite? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite - } } - var _9: Int32? - _9 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil - let _c8 = (Int(_1!) & Int(1 << 2) == 0) || _8 != nil - let _c9 = _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.Update.updateChatParticipant(flags: _1!, chatId: _2!, date: _3!, actorId: _4!, userId: _5!, prevParticipant: _6, newParticipant: _7, invite: _8, qts: _9!) - } - public static func parse_updateChatParticipantAdd(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int64? - _3 = reader.readInt64() - var _4: Int32? - _4 = reader.readInt32() - var _5: Int32? - _5 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.Update.updateChatParticipantAdd(chatId: _1!, userId: _2!, inviterId: _3!, date: _4!, version: _5!) - } - public static func parse_updateChatParticipantAdmin(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Int64? - _2 = reader.readInt64() - var _3: Api.Bool? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Bool - } - var _4: Int32? - _4 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.Update.updateChatParticipantAdmin(chatId: _1!, userId: _2!, isAdmin: _3!, version: _4!) - } - public static func parse_updateChatParticipantDelete(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateChatParticipantDelete(chatId: _1!, userId: _2!, version: _3!) - } - public static func parse_updateChatParticipants(_ reader: BufferReader) -> Update? { - var _1: Api.ChatParticipants? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.ChatParticipants - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateChatParticipants(participants: _1!) - } - public static func parse_updateChatUserTyping(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: Api.SendMessageAction? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.SendMessageAction - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateChatUserTyping(chatId: _1!, fromId: _2!, action: _3!) - } - public static func parse_updateConfig(_ reader: BufferReader) -> Update? { - return Api.Update.updateConfig - } - public static func parse_updateContactsReset(_ reader: BufferReader) -> Update? { - return Api.Update.updateContactsReset - } - public static func parse_updateDcOptions(_ reader: BufferReader) -> Update? { - var _1: [Api.DcOption]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.DcOption.self) - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateDcOptions(dcOptions: _1!) - } - public static func parse_updateDeleteChannelMessages(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: [Int32]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - var _3: Int32? - _3 = reader.readInt32() - var _4: Int32? - _4 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.Update.updateDeleteChannelMessages(channelId: _1!, messages: _2!, pts: _3!, ptsCount: _4!) - } - public static func parse_updateDeleteGroupCallMessages(_ reader: BufferReader) -> Update? { - var _1: Api.InputGroupCall? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.InputGroupCall - } - var _2: [Int32]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateDeleteGroupCallMessages(call: _1!, messages: _2!) - } - public static func parse_updateDeleteMessages(_ reader: BufferReader) -> Update? { - var _1: [Int32]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateDeleteMessages(messages: _1!, pts: _2!, ptsCount: _3!) - } - public static func parse_updateDeleteQuickReply(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateDeleteQuickReply(shortcutId: _1!) - } - public static func parse_updateDeleteQuickReplyMessages(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Int32]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateDeleteQuickReplyMessages(shortcutId: _1!, messages: _2!) - } - public static func parse_updateDeleteScheduledMessages(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: [Int32]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - var _4: [Int32]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.Update.updateDeleteScheduledMessages(flags: _1!, peer: _2!, messages: _3!, sentMessages: _4) - } - public static func parse_updateDialogFilter(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Api.DialogFilter? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.DialogFilter - } } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateDialogFilter(flags: _1!, id: _2!, filter: _3) - } - public static func parse_updateDialogFilterOrder(_ reader: BufferReader) -> Update? { - var _1: [Int32]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateDialogFilterOrder(order: _1!) - } - public static func parse_updateDialogFilters(_ reader: BufferReader) -> Update? { - return Api.Update.updateDialogFilters - } - public static func parse_updateDialogPinned(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_2 = reader.readInt32() } - var _3: Api.DialogPeer? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.DialogPeer - } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateDialogPinned(flags: _1!, folderId: _2, peer: _3!) - } - public static func parse_updateDialogUnreadMark(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.DialogPeer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.DialogPeer - } - var _3: Api.Peer? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Peer - } } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateDialogUnreadMark(flags: _1!, peer: _2!, savedPeerId: _3) - } - public static func parse_updateDraftMessage(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } - var _4: Api.Peer? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Peer - } } - var _5: Api.DraftMessage? - if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.DraftMessage - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.Update.updateDraftMessage(flags: _1!, peer: _2!, topMsgId: _3, savedPeerId: _4, draft: _5!) - } - public static func parse_updateEditChannelMessage(_ reader: BufferReader) -> Update? { - var _1: Api.Message? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Message - } - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateEditChannelMessage(message: _1!, pts: _2!, ptsCount: _3!) - } - public static func parse_updateEditMessage(_ reader: BufferReader) -> Update? { - var _1: Api.Message? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Message - } - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateEditMessage(message: _1!, pts: _2!, ptsCount: _3!) - } - public static func parse_updateEmojiGameInfo(_ reader: BufferReader) -> Update? { - var _1: Api.messages.EmojiGameInfo? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.messages.EmojiGameInfo - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateEmojiGameInfo(info: _1!) - } - public static func parse_updateEncryptedChatTyping(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateEncryptedChatTyping(chatId: _1!) - } - public static func parse_updateEncryptedMessagesRead(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateEncryptedMessagesRead(chatId: _1!, maxDate: _2!, date: _3!) - } - public static func parse_updateEncryption(_ reader: BufferReader) -> Update? { - var _1: Api.EncryptedChat? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.EncryptedChat - } - var _2: Int32? - _2 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateEncryption(chat: _1!, date: _2!) - } - public static func parse_updateFavedStickers(_ reader: BufferReader) -> Update? { - return Api.Update.updateFavedStickers - } - public static func parse_updateFolderPeers(_ reader: BufferReader) -> Update? { - var _1: [Api.FolderPeer]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.FolderPeer.self) - } - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateFolderPeers(folderPeers: _1!, pts: _2!, ptsCount: _3!) - } - public static func parse_updateGeoLiveViewed(_ reader: BufferReader) -> Update? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: Int32? - _2 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateGeoLiveViewed(peer: _1!, msgId: _2!) - } - public static func parse_updateGroupCall(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.Peer? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } } - var _3: Api.GroupCall? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.GroupCall - } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateGroupCall(flags: _1!, peer: _2, call: _3!) - } - public static func parse_updateGroupCallChainBlocks(_ reader: BufferReader) -> Update? { - var _1: Api.InputGroupCall? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.InputGroupCall - } - var _2: Int32? - _2 = reader.readInt32() - var _3: [Buffer]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: -1255641564, elementType: Buffer.self) - } - var _4: Int32? - _4 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.Update.updateGroupCallChainBlocks(call: _1!, subChainId: _2!, blocks: _3!, nextOffset: _4!) - } - public static func parse_updateGroupCallConnection(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.DataJSON? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.DataJSON - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateGroupCallConnection(flags: _1!, params: _2!) - } - public static func parse_updateGroupCallEncryptedMessage(_ reader: BufferReader) -> Update? { - var _1: Api.InputGroupCall? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.InputGroupCall - } - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: Buffer? - _3 = parseBytes(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateGroupCallEncryptedMessage(call: _1!, fromId: _2!, encryptedMessage: _3!) - } - public static func parse_updateGroupCallMessage(_ reader: BufferReader) -> Update? { - var _1: Api.InputGroupCall? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.InputGroupCall - } - var _2: Api.GroupCallMessage? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.GroupCallMessage - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateGroupCallMessage(call: _1!, message: _2!) - } - public static func parse_updateGroupCallParticipants(_ reader: BufferReader) -> Update? { - var _1: Api.InputGroupCall? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.InputGroupCall - } - var _2: [Api.GroupCallParticipant]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.GroupCallParticipant.self) - } - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateGroupCallParticipants(call: _1!, participants: _2!, version: _3!) - } - public static func parse_updateInlineBotCallbackQuery(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int64? - _3 = reader.readInt64() - var _4: Api.InputBotInlineMessageID? - if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.InputBotInlineMessageID - } - var _5: Int64? - _5 = reader.readInt64() - var _6: Buffer? - if Int(_1!) & Int(1 << 0) != 0 {_6 = parseBytes(reader) } - var _7: String? - if Int(_1!) & Int(1 << 1) != 0 {_7 = parseString(reader) } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.Update.updateInlineBotCallbackQuery(flags: _1!, queryId: _2!, userId: _3!, msgId: _4!, chatInstance: _5!, data: _6, gameShortName: _7) - } - public static func parse_updateLangPack(_ reader: BufferReader) -> Update? { - var _1: Api.LangPackDifference? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.LangPackDifference - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateLangPack(difference: _1!) - } - public static func parse_updateLangPackTooLong(_ reader: BufferReader) -> Update? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateLangPackTooLong(langCode: _1!) - } - public static func parse_updateLoginToken(_ reader: BufferReader) -> Update? { - return Api.Update.updateLoginToken - } - public static func parse_updateMessageExtendedMedia(_ reader: BufferReader) -> Update? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: Int32? - _2 = reader.readInt32() - var _3: [Api.MessageExtendedMedia]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageExtendedMedia.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateMessageExtendedMedia(peer: _1!, msgId: _2!, extendedMedia: _3!) - } - public static func parse_updateMessageID(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateMessageID(id: _1!, randomId: _2!) - } - public static func parse_updateMessagePoll(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Api.Poll? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Poll - } } - var _4: Api.PollResults? - if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.PollResults - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.Update.updateMessagePoll(flags: _1!, pollId: _2!, poll: _3, results: _4!) - } - public static func parse_updateMessagePollVote(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: [Buffer]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: -1255641564, elementType: Buffer.self) - } - var _4: Int32? - _4 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.Update.updateMessagePollVote(pollId: _1!, peer: _2!, options: _3!, qts: _4!) - } - public static func parse_updateMessageReactions(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: Int32? - _3 = reader.readInt32() - var _4: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_4 = reader.readInt32() } - var _5: Api.Peer? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.Peer - } } - var _6: Api.MessageReactions? - if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.MessageReactions - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.Update.updateMessageReactions(flags: _1!, peer: _2!, msgId: _3!, topMsgId: _4, savedPeerId: _5, reactions: _6!) - } - public static func parse_updateMonoForumNoPaidException(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Api.Peer? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Peer - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateMonoForumNoPaidException(flags: _1!, channelId: _2!, savedPeerId: _3!) - } - public static func parse_updateMoveStickerSetToTop(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateMoveStickerSetToTop(flags: _1!, stickerset: _2!) - } - public static func parse_updateNewAuthorization(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } - var _4: String? - if Int(_1!) & Int(1 << 0) != 0 {_4 = parseString(reader) } - var _5: String? - if Int(_1!) & Int(1 << 0) != 0 {_5 = parseString(reader) } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.Update.updateNewAuthorization(flags: _1!, hash: _2!, date: _3, device: _4, location: _5) - } - public static func parse_updateNewChannelMessage(_ reader: BufferReader) -> Update? { - var _1: Api.Message? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Message - } - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateNewChannelMessage(message: _1!, pts: _2!, ptsCount: _3!) - } - public static func parse_updateNewEncryptedMessage(_ reader: BufferReader) -> Update? { - var _1: Api.EncryptedMessage? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.EncryptedMessage - } - var _2: Int32? - _2 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateNewEncryptedMessage(message: _1!, qts: _2!) - } - public static func parse_updateNewMessage(_ reader: BufferReader) -> Update? { - var _1: Api.Message? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Message - } - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateNewMessage(message: _1!, pts: _2!, ptsCount: _3!) - } - public static func parse_updateNewQuickReply(_ reader: BufferReader) -> Update? { - var _1: Api.QuickReply? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.QuickReply - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateNewQuickReply(quickReply: _1!) - } - public static func parse_updateNewScheduledMessage(_ reader: BufferReader) -> Update? { - var _1: Api.Message? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Message - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateNewScheduledMessage(message: _1!) - } - public static func parse_updateNewStickerSet(_ reader: BufferReader) -> Update? { - var _1: Api.messages.StickerSet? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.messages.StickerSet - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateNewStickerSet(stickerset: _1!) - } - public static func parse_updateNewStoryReaction(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: Api.Reaction? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Reaction - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateNewStoryReaction(storyId: _1!, peer: _2!, reaction: _3!) - } - public static func parse_updateNotifySettings(_ reader: BufferReader) -> Update? { - var _1: Api.NotifyPeer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.NotifyPeer - } - var _2: Api.PeerNotifySettings? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.PeerNotifySettings - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateNotifySettings(peer: _1!, notifySettings: _2!) - } - public static func parse_updatePaidReactionPrivacy(_ reader: BufferReader) -> Update? { - var _1: Api.PaidReactionPrivacy? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.PaidReactionPrivacy - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updatePaidReactionPrivacy(private: _1!) - } - public static func parse_updatePeerBlocked(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updatePeerBlocked(flags: _1!, peerId: _2!) - } - public static func parse_updatePeerHistoryTTL(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updatePeerHistoryTTL(flags: _1!, peer: _2!, ttlPeriod: _3) - } - public static func parse_updatePeerLocated(_ reader: BufferReader) -> Update? { - var _1: [Api.PeerLocated]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PeerLocated.self) - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updatePeerLocated(peers: _1!) - } - public static func parse_updatePeerSettings(_ reader: BufferReader) -> Update? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: Api.PeerSettings? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.PeerSettings - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updatePeerSettings(peer: _1!, settings: _2!) - } - public static func parse_updatePeerWallpaper(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: Api.WallPaper? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.WallPaper - } } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updatePeerWallpaper(flags: _1!, peer: _2!, wallpaper: _3) - } - public static func parse_updatePendingJoinRequests(_ reader: BufferReader) -> Update? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: Int32? - _2 = reader.readInt32() - var _3: [Int64]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updatePendingJoinRequests(peer: _1!, requestsPending: _2!, recentRequesters: _3!) - } - public static func parse_updatePhoneCall(_ reader: BufferReader) -> Update? { - var _1: Api.PhoneCall? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.PhoneCall - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updatePhoneCall(phoneCall: _1!) - } - public static func parse_updatePhoneCallSignalingData(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Buffer? - _2 = parseBytes(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updatePhoneCallSignalingData(phoneCallId: _1!, data: _2!) - } - public static func parse_updatePinnedChannelMessages(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: [Int32]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - var _4: Int32? - _4 = reader.readInt32() - var _5: Int32? - _5 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.Update.updatePinnedChannelMessages(flags: _1!, channelId: _2!, messages: _3!, pts: _4!, ptsCount: _5!) - } - public static func parse_updatePinnedDialogs(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_2 = reader.readInt32() } - var _3: [Api.DialogPeer]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.DialogPeer.self) - } } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updatePinnedDialogs(flags: _1!, folderId: _2, order: _3) - } - public static func parse_updatePinnedForumTopic(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updatePinnedForumTopic(flags: _1!, peer: _2!, topicId: _3!) - } - public static func parse_updatePinnedForumTopics(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: [Int32]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updatePinnedForumTopics(flags: _1!, peer: _2!, order: _3) - } - public static func parse_updatePinnedMessages(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: [Int32]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - var _4: Int32? - _4 = reader.readInt32() - var _5: Int32? - _5 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.Update.updatePinnedMessages(flags: _1!, peer: _2!, messages: _3!, pts: _4!, ptsCount: _5!) - } - public static func parse_updatePinnedSavedDialogs(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.DialogPeer]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.DialogPeer.self) - } } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updatePinnedSavedDialogs(flags: _1!, order: _2) - } - public static func parse_updatePrivacy(_ reader: BufferReader) -> Update? { - var _1: Api.PrivacyKey? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.PrivacyKey - } - var _2: [Api.PrivacyRule]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PrivacyRule.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updatePrivacy(key: _1!, rules: _2!) - } - public static func parse_updatePtsChanged(_ reader: BufferReader) -> Update? { - return Api.Update.updatePtsChanged - } - public static func parse_updateQuickReplies(_ reader: BufferReader) -> Update? { - var _1: [Api.QuickReply]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.QuickReply.self) - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateQuickReplies(quickReplies: _1!) - } - public static func parse_updateQuickReplyMessage(_ reader: BufferReader) -> Update? { - var _1: Api.Message? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Message - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateQuickReplyMessage(message: _1!) - } - public static func parse_updateReadChannelDiscussionInbox(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int32? - _3 = reader.readInt32() - var _4: Int32? - _4 = reader.readInt32() - var _5: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_5 = reader.readInt64() } - var _6: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_6 = reader.readInt32() } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil - let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.Update.updateReadChannelDiscussionInbox(flags: _1!, channelId: _2!, topMsgId: _3!, readMaxId: _4!, broadcastId: _5, broadcastPost: _6) - } - public static func parse_updateReadChannelDiscussionOutbox(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateReadChannelDiscussionOutbox(channelId: _1!, topMsgId: _2!, readMaxId: _3!) - } - public static func parse_updateReadChannelInbox(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt32() } - var _3: Int64? - _3 = reader.readInt64() - var _4: Int32? - _4 = reader.readInt32() - var _5: Int32? - _5 = reader.readInt32() - var _6: Int32? - _6 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.Update.updateReadChannelInbox(flags: _1!, folderId: _2, channelId: _3!, maxId: _4!, stillUnreadCount: _5!, pts: _6!) - } - public static func parse_updateReadChannelOutbox(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Int32? - _2 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateReadChannelOutbox(channelId: _1!, maxId: _2!) - } - public static func parse_updateReadFeaturedEmojiStickers(_ reader: BufferReader) -> Update? { - return Api.Update.updateReadFeaturedEmojiStickers - } - public static func parse_updateReadFeaturedStickers(_ reader: BufferReader) -> Update? { - return Api.Update.updateReadFeaturedStickers - } - public static func parse_updateReadHistoryInbox(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt32() } - var _3: Api.Peer? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _4: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_4 = reader.readInt32() } - var _5: Int32? - _5 = reader.readInt32() - var _6: Int32? - _6 = reader.readInt32() - var _7: Int32? - _7 = reader.readInt32() - var _8: Int32? - _8 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - let _c7 = _7 != nil - let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.Update.updateReadHistoryInbox(flags: _1!, folderId: _2, peer: _3!, topMsgId: _4, maxId: _5!, stillUnreadCount: _6!, pts: _7!, ptsCount: _8!) - } - public static func parse_updateReadHistoryOutbox(_ reader: BufferReader) -> Update? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - var _4: Int32? - _4 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.Update.updateReadHistoryOutbox(peer: _1!, maxId: _2!, pts: _3!, ptsCount: _4!) - } - public static func parse_updateReadMessagesContents(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Int32]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - var _3: Int32? - _3 = reader.readInt32() - var _4: Int32? - _4 = reader.readInt32() - var _5: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_5 = reader.readInt32() } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.Update.updateReadMessagesContents(flags: _1!, messages: _2!, pts: _3!, ptsCount: _4!, date: _5) - } - public static func parse_updateReadMonoForumInbox(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateReadMonoForumInbox(channelId: _1!, savedPeerId: _2!, readMaxId: _3!) - } - public static func parse_updateReadMonoForumOutbox(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateReadMonoForumOutbox(channelId: _1!, savedPeerId: _2!, readMaxId: _3!) - } - public static func parse_updateReadStories(_ reader: BufferReader) -> Update? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: Int32? - _2 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateReadStories(peer: _1!, maxId: _2!) - } - public static func parse_updateRecentEmojiStatuses(_ reader: BufferReader) -> Update? { - return Api.Update.updateRecentEmojiStatuses - } - public static func parse_updateRecentReactions(_ reader: BufferReader) -> Update? { - return Api.Update.updateRecentReactions - } - public static func parse_updateRecentStickers(_ reader: BufferReader) -> Update? { - return Api.Update.updateRecentStickers - } - public static func parse_updateSavedDialogPinned(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.DialogPeer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.DialogPeer - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateSavedDialogPinned(flags: _1!, peer: _2!) - } - public static func parse_updateSavedGifs(_ reader: BufferReader) -> Update? { - return Api.Update.updateSavedGifs - } - public static func parse_updateSavedReactionTags(_ reader: BufferReader) -> Update? { - return Api.Update.updateSavedReactionTags - } - public static func parse_updateSavedRingtones(_ reader: BufferReader) -> Update? { - return Api.Update.updateSavedRingtones - } - public static func parse_updateSentPhoneCode(_ reader: BufferReader) -> Update? { - var _1: Api.auth.SentCode? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.auth.SentCode - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateSentPhoneCode(sentCode: _1!) - } - public static func parse_updateSentStoryReaction(_ reader: BufferReader) -> Update? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: Int32? - _2 = reader.readInt32() - var _3: Api.Reaction? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Reaction - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateSentStoryReaction(peer: _1!, storyId: _2!, reaction: _3!) - } - public static func parse_updateServiceNotification(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_2 = reader.readInt32() } - var _3: String? - _3 = parseString(reader) - var _4: String? - _4 = parseString(reader) - var _5: Api.MessageMedia? - if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.MessageMedia - } - var _6: [Api.MessageEntity]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.Update.updateServiceNotification(flags: _1!, inboxDate: _2, type: _3!, message: _4!, media: _5!, entities: _6!) - } - public static func parse_updateSmsJob(_ reader: BufferReader) -> Update? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateSmsJob(jobId: _1!) - } - public static func parse_updateStarGiftAuctionState(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Api.StarGiftAuctionState? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.StarGiftAuctionState - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateStarGiftAuctionState(giftId: _1!, state: _2!) - } - public static func parse_updateStarGiftAuctionUserState(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Api.StarGiftAuctionUserState? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.StarGiftAuctionUserState - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateStarGiftAuctionUserState(giftId: _1!, userState: _2!) - } - public static func parse_updateStarsBalance(_ reader: BufferReader) -> Update? { - var _1: Api.StarsAmount? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.StarsAmount - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateStarsBalance(balance: _1!) - } - public static func parse_updateStarsRevenueStatus(_ reader: BufferReader) -> Update? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: Api.StarsRevenueStatus? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.StarsRevenueStatus - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateStarsRevenueStatus(peer: _1!, status: _2!) - } - public static func parse_updateStickerSets(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateStickerSets(flags: _1!) - } - public static func parse_updateStickerSetsOrder(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Int64]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateStickerSetsOrder(flags: _1!, order: _2!) - } - public static func parse_updateStoriesStealthMode(_ reader: BufferReader) -> Update? { - var _1: Api.StoriesStealthMode? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.StoriesStealthMode - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateStoriesStealthMode(stealthMode: _1!) - } - public static func parse_updateStory(_ reader: BufferReader) -> Update? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: Api.StoryItem? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.StoryItem - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateStory(peer: _1!, story: _2!) - } - public static func parse_updateStoryID(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateStoryID(id: _1!, randomId: _2!) - } - public static func parse_updateTheme(_ reader: BufferReader) -> Update? { - var _1: Api.Theme? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Theme - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateTheme(theme: _1!) - } - public static func parse_updateTranscribedAudio(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _3: Int32? - _3 = reader.readInt32() - var _4: Int64? - _4 = reader.readInt64() - var _5: String? - _5 = parseString(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.Update.updateTranscribedAudio(flags: _1!, peer: _2!, msgId: _3!, transcriptionId: _4!, text: _5!) - } - public static func parse_updateUser(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateUser(userId: _1!) - } - public static func parse_updateUserEmojiStatus(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Api.EmojiStatus? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.EmojiStatus - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateUserEmojiStatus(userId: _1!, emojiStatus: _2!) - } - public static func parse_updateUserName(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: String? - _2 = parseString(reader) - var _3: String? - _3 = parseString(reader) - var _4: [Api.Username]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Username.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.Update.updateUserName(userId: _1!, firstName: _2!, lastName: _3!, usernames: _4!) - } - public static func parse_updateUserPhone(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: String? - _2 = parseString(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateUserPhone(userId: _1!, phone: _2!) - } - public static func parse_updateUserStatus(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Api.UserStatus? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.UserStatus - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Update.updateUserStatus(userId: _1!, status: _2!) - } - public static func parse_updateUserTyping(_ reader: BufferReader) -> Update? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } - var _4: Api.SendMessageAction? - if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.SendMessageAction - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.Update.updateUserTyping(flags: _1!, userId: _2!, topMsgId: _3, action: _4!) - } - public static func parse_updateWebPage(_ reader: BufferReader) -> Update? { - var _1: Api.WebPage? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.WebPage - } - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.Update.updateWebPage(webpage: _1!, pts: _2!, ptsCount: _3!) - } - public static func parse_updateWebViewResultSent(_ reader: BufferReader) -> Update? { - var _1: Int64? - _1 = reader.readInt64() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Update.updateWebViewResultSent(queryId: _1!) - } - } } diff --git a/submodules/TelegramApi/Sources/Api28.swift b/submodules/TelegramApi/Sources/Api28.swift index 247694f3..9cd5aa8c 100644 --- a/submodules/TelegramApi/Sources/Api28.swift +++ b/submodules/TelegramApi/Sources/Api28.swift @@ -1,371 +1,3416 @@ public extension Api { - indirect enum Updates: TypeConstructorDescription { - case updateShort(update: Api.Update, date: Int32) - case updateShortChatMessage(flags: Int32, id: Int32, fromId: Int64, chatId: Int64, message: String, pts: Int32, ptsCount: Int32, date: Int32, fwdFrom: Api.MessageFwdHeader?, viaBotId: Int64?, replyTo: Api.MessageReplyHeader?, entities: [Api.MessageEntity]?, ttlPeriod: Int32?) - case updateShortMessage(flags: Int32, id: Int32, userId: Int64, message: String, pts: Int32, ptsCount: Int32, date: Int32, fwdFrom: Api.MessageFwdHeader?, viaBotId: Int64?, replyTo: Api.MessageReplyHeader?, entities: [Api.MessageEntity]?, ttlPeriod: Int32?) - case updateShortSentMessage(flags: Int32, id: Int32, pts: Int32, ptsCount: Int32, date: Int32, media: Api.MessageMedia?, entities: [Api.MessageEntity]?, ttlPeriod: Int32?) - case updates(updates: [Api.Update], users: [Api.User], chats: [Api.Chat], date: Int32, seq: Int32) - case updatesCombined(updates: [Api.Update], users: [Api.User], chats: [Api.Chat], date: Int32, seqStart: Int32, seq: Int32) - case updatesTooLong - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .updateShort(let update, let date): - if boxed { - buffer.appendInt32(2027216577) - } - update.serialize(buffer, true) - serializeInt32(date, buffer: buffer, boxed: false) - break - case .updateShortChatMessage(let flags, let id, let fromId, let chatId, let message, let pts, let ptsCount, let date, let fwdFrom, let viaBotId, let replyTo, let entities, let ttlPeriod): - if boxed { - buffer.appendInt32(1299050149) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt64(fromId, buffer: buffer, boxed: false) - serializeInt64(chatId, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {fwdFrom!.serialize(buffer, true)} - if Int(flags) & Int(1 << 11) != 0 {serializeInt64(viaBotId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {replyTo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 7) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 25) != 0 {serializeInt32(ttlPeriod!, buffer: buffer, boxed: false)} - break - case .updateShortMessage(let flags, let id, let userId, let message, let pts, let ptsCount, let date, let fwdFrom, let viaBotId, let replyTo, let entities, let ttlPeriod): - if boxed { - buffer.appendInt32(826001400) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {fwdFrom!.serialize(buffer, true)} - if Int(flags) & Int(1 << 11) != 0 {serializeInt64(viaBotId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {replyTo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 7) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 25) != 0 {serializeInt32(ttlPeriod!, buffer: buffer, boxed: false)} - break - case .updateShortSentMessage(let flags, let id, let pts, let ptsCount, let date, let media, let entities, let ttlPeriod): - if boxed { - buffer.appendInt32(-1877614335) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 9) != 0 {media!.serialize(buffer, true)} - if Int(flags) & Int(1 << 7) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 25) != 0 {serializeInt32(ttlPeriod!, buffer: buffer, boxed: false)} - break - case .updates(let updates, let users, let chats, let date, let seq): - if boxed { - buffer.appendInt32(1957577280) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(updates.count)) - for item in updates { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt32(seq, buffer: buffer, boxed: false) - break - case .updatesCombined(let updates, let users, let chats, let date, let seqStart, let seq): - if boxed { - buffer.appendInt32(1918567619) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(updates.count)) - for item in updates { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt32(seqStart, buffer: buffer, boxed: false) - serializeInt32(seq, buffer: buffer, boxed: false) - break - case .updatesTooLong: - if boxed { - buffer.appendInt32(-484987010) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .updateShort(let update, let date): - return ("updateShort", [("update", update as Any), ("date", date as Any)]) - case .updateShortChatMessage(let flags, let id, let fromId, let chatId, let message, let pts, let ptsCount, let date, let fwdFrom, let viaBotId, let replyTo, let entities, let ttlPeriod): - return ("updateShortChatMessage", [("flags", flags as Any), ("id", id as Any), ("fromId", fromId as Any), ("chatId", chatId as Any), ("message", message as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any), ("date", date as Any), ("fwdFrom", fwdFrom as Any), ("viaBotId", viaBotId as Any), ("replyTo", replyTo as Any), ("entities", entities as Any), ("ttlPeriod", ttlPeriod as Any)]) - case .updateShortMessage(let flags, let id, let userId, let message, let pts, let ptsCount, let date, let fwdFrom, let viaBotId, let replyTo, let entities, let ttlPeriod): - return ("updateShortMessage", [("flags", flags as Any), ("id", id as Any), ("userId", userId as Any), ("message", message as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any), ("date", date as Any), ("fwdFrom", fwdFrom as Any), ("viaBotId", viaBotId as Any), ("replyTo", replyTo as Any), ("entities", entities as Any), ("ttlPeriod", ttlPeriod as Any)]) - case .updateShortSentMessage(let flags, let id, let pts, let ptsCount, let date, let media, let entities, let ttlPeriod): - return ("updateShortSentMessage", [("flags", flags as Any), ("id", id as Any), ("pts", pts as Any), ("ptsCount", ptsCount as Any), ("date", date as Any), ("media", media as Any), ("entities", entities as Any), ("ttlPeriod", ttlPeriod as Any)]) - case .updates(let updates, let users, let chats, let date, let seq): - return ("updates", [("updates", updates as Any), ("users", users as Any), ("chats", chats as Any), ("date", date as Any), ("seq", seq as Any)]) - case .updatesCombined(let updates, let users, let chats, let date, let seqStart, let seq): - return ("updatesCombined", [("updates", updates as Any), ("users", users as Any), ("chats", chats as Any), ("date", date as Any), ("seqStart", seqStart as Any), ("seq", seq as Any)]) - case .updatesTooLong: - return ("updatesTooLong", []) - } - } - - public static func parse_updateShort(_ reader: BufferReader) -> Updates? { - var _1: Api.Update? + enum TopPeerCategoryPeers: TypeConstructorDescription { + public class Cons_topPeerCategoryPeers { + public var category: Api.TopPeerCategory + public var count: Int32 + public var peers: [Api.TopPeer] + public init(category: Api.TopPeerCategory, count: Int32, peers: [Api.TopPeer]) { + self.category = category + self.count = count + self.peers = peers + } + } + case topPeerCategoryPeers(Cons_topPeerCategoryPeers) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .topPeerCategoryPeers(let _data): + if boxed { + buffer.appendInt32(-75283823) + } + _data.category.serialize(buffer, true) + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.peers.count)) + for item in _data.peers { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .topPeerCategoryPeers(let _data): + return ("topPeerCategoryPeers", [("category", _data.category as Any), ("count", _data.count as Any), ("peers", _data.peers as Any)]) + } + } + + public static func parse_topPeerCategoryPeers(_ reader: BufferReader) -> TopPeerCategoryPeers? { + var _1: Api.TopPeerCategory? if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Update + _1 = Api.parse(reader, signature: signature) as? Api.TopPeerCategory + } + var _2: Int32? + _2 = reader.readInt32() + var _3: [Api.TopPeer]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.TopPeer.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.TopPeerCategoryPeers.topPeerCategoryPeers(Cons_topPeerCategoryPeers(category: _1!, count: _2!, peers: _3!)) + } + else { + return nil + } + } + } +} +public extension Api { + indirect enum Update: TypeConstructorDescription { + public class Cons_updateBotBusinessConnect { + public var connection: Api.BotBusinessConnection + public var qts: Int32 + public init(connection: Api.BotBusinessConnection, qts: Int32) { + self.connection = connection + self.qts = qts + } + } + public class Cons_updateBotCallbackQuery { + public var flags: Int32 + public var queryId: Int64 + public var userId: Int64 + public var peer: Api.Peer + public var msgId: Int32 + public var chatInstance: Int64 + public var data: Buffer? + public var gameShortName: String? + public init(flags: Int32, queryId: Int64, userId: Int64, peer: Api.Peer, msgId: Int32, chatInstance: Int64, data: Buffer?, gameShortName: String?) { + self.flags = flags + self.queryId = queryId + self.userId = userId + self.peer = peer + self.msgId = msgId + self.chatInstance = chatInstance + self.data = data + self.gameShortName = gameShortName + } + } + public class Cons_updateBotChatBoost { + public var peer: Api.Peer + public var boost: Api.Boost + public var qts: Int32 + public init(peer: Api.Peer, boost: Api.Boost, qts: Int32) { + self.peer = peer + self.boost = boost + self.qts = qts + } + } + public class Cons_updateBotChatInviteRequester { + public var peer: Api.Peer + public var date: Int32 + public var userId: Int64 + public var about: String + public var invite: Api.ExportedChatInvite + public var qts: Int32 + public init(peer: Api.Peer, date: Int32, userId: Int64, about: String, invite: Api.ExportedChatInvite, qts: Int32) { + self.peer = peer + self.date = date + self.userId = userId + self.about = about + self.invite = invite + self.qts = qts + } + } + public class Cons_updateBotCommands { + public var peer: Api.Peer + public var botId: Int64 + public var commands: [Api.BotCommand] + public init(peer: Api.Peer, botId: Int64, commands: [Api.BotCommand]) { + self.peer = peer + self.botId = botId + self.commands = commands + } + } + public class Cons_updateBotDeleteBusinessMessage { + public var connectionId: String + public var peer: Api.Peer + public var messages: [Int32] + public var qts: Int32 + public init(connectionId: String, peer: Api.Peer, messages: [Int32], qts: Int32) { + self.connectionId = connectionId + self.peer = peer + self.messages = messages + self.qts = qts + } + } + public class Cons_updateBotEditBusinessMessage { + public var flags: Int32 + public var connectionId: String + public var message: Api.Message + public var replyToMessage: Api.Message? + public var qts: Int32 + public init(flags: Int32, connectionId: String, message: Api.Message, replyToMessage: Api.Message?, qts: Int32) { + self.flags = flags + self.connectionId = connectionId + self.message = message + self.replyToMessage = replyToMessage + self.qts = qts + } + } + public class Cons_updateBotInlineQuery { + public var flags: Int32 + public var queryId: Int64 + public var userId: Int64 + public var query: String + public var geo: Api.GeoPoint? + public var peerType: Api.InlineQueryPeerType? + public var offset: String + public init(flags: Int32, queryId: Int64, userId: Int64, query: String, geo: Api.GeoPoint?, peerType: Api.InlineQueryPeerType?, offset: String) { + self.flags = flags + self.queryId = queryId + self.userId = userId + self.query = query + self.geo = geo + self.peerType = peerType + self.offset = offset + } + } + public class Cons_updateBotInlineSend { + public var flags: Int32 + public var userId: Int64 + public var query: String + public var geo: Api.GeoPoint? + public var id: String + public var msgId: Api.InputBotInlineMessageID? + public init(flags: Int32, userId: Int64, query: String, geo: Api.GeoPoint?, id: String, msgId: Api.InputBotInlineMessageID?) { + self.flags = flags + self.userId = userId + self.query = query + self.geo = geo + self.id = id + self.msgId = msgId + } + } + public class Cons_updateBotMenuButton { + public var botId: Int64 + public var button: Api.BotMenuButton + public init(botId: Int64, button: Api.BotMenuButton) { + self.botId = botId + self.button = button + } + } + public class Cons_updateBotMessageReaction { + public var peer: Api.Peer + public var msgId: Int32 + public var date: Int32 + public var actor: Api.Peer + public var oldReactions: [Api.Reaction] + public var newReactions: [Api.Reaction] + public var qts: Int32 + public init(peer: Api.Peer, msgId: Int32, date: Int32, actor: Api.Peer, oldReactions: [Api.Reaction], newReactions: [Api.Reaction], qts: Int32) { + self.peer = peer + self.msgId = msgId + self.date = date + self.actor = actor + self.oldReactions = oldReactions + self.newReactions = newReactions + self.qts = qts + } + } + public class Cons_updateBotMessageReactions { + public var peer: Api.Peer + public var msgId: Int32 + public var date: Int32 + public var reactions: [Api.ReactionCount] + public var qts: Int32 + public init(peer: Api.Peer, msgId: Int32, date: Int32, reactions: [Api.ReactionCount], qts: Int32) { + self.peer = peer + self.msgId = msgId + self.date = date + self.reactions = reactions + self.qts = qts + } + } + public class Cons_updateBotNewBusinessMessage { + public var flags: Int32 + public var connectionId: String + public var message: Api.Message + public var replyToMessage: Api.Message? + public var qts: Int32 + public init(flags: Int32, connectionId: String, message: Api.Message, replyToMessage: Api.Message?, qts: Int32) { + self.flags = flags + self.connectionId = connectionId + self.message = message + self.replyToMessage = replyToMessage + self.qts = qts + } + } + public class Cons_updateBotPrecheckoutQuery { + public var flags: Int32 + public var queryId: Int64 + public var userId: Int64 + public var payload: Buffer + public var info: Api.PaymentRequestedInfo? + public var shippingOptionId: String? + public var currency: String + public var totalAmount: Int64 + public init(flags: Int32, queryId: Int64, userId: Int64, payload: Buffer, info: Api.PaymentRequestedInfo?, shippingOptionId: String?, currency: String, totalAmount: Int64) { + self.flags = flags + self.queryId = queryId + self.userId = userId + self.payload = payload + self.info = info + self.shippingOptionId = shippingOptionId + self.currency = currency + self.totalAmount = totalAmount + } + } + public class Cons_updateBotPurchasedPaidMedia { + public var userId: Int64 + public var payload: String + public var qts: Int32 + public init(userId: Int64, payload: String, qts: Int32) { + self.userId = userId + self.payload = payload + self.qts = qts + } + } + public class Cons_updateBotShippingQuery { + public var queryId: Int64 + public var userId: Int64 + public var payload: Buffer + public var shippingAddress: Api.PostAddress + public init(queryId: Int64, userId: Int64, payload: Buffer, shippingAddress: Api.PostAddress) { + self.queryId = queryId + self.userId = userId + self.payload = payload + self.shippingAddress = shippingAddress + } + } + public class Cons_updateBotStopped { + public var userId: Int64 + public var date: Int32 + public var stopped: Api.Bool + public var qts: Int32 + public init(userId: Int64, date: Int32, stopped: Api.Bool, qts: Int32) { + self.userId = userId + self.date = date + self.stopped = stopped + self.qts = qts + } + } + public class Cons_updateBotWebhookJSON { + public var data: Api.DataJSON + public init(data: Api.DataJSON) { + self.data = data + } + } + public class Cons_updateBotWebhookJSONQuery { + public var queryId: Int64 + public var data: Api.DataJSON + public var timeout: Int32 + public init(queryId: Int64, data: Api.DataJSON, timeout: Int32) { + self.queryId = queryId + self.data = data + self.timeout = timeout + } + } + public class Cons_updateBusinessBotCallbackQuery { + public var flags: Int32 + public var queryId: Int64 + public var userId: Int64 + public var connectionId: String + public var message: Api.Message + public var replyToMessage: Api.Message? + public var chatInstance: Int64 + public var data: Buffer? + public init(flags: Int32, queryId: Int64, userId: Int64, connectionId: String, message: Api.Message, replyToMessage: Api.Message?, chatInstance: Int64, data: Buffer?) { + self.flags = flags + self.queryId = queryId + self.userId = userId + self.connectionId = connectionId + self.message = message + self.replyToMessage = replyToMessage + self.chatInstance = chatInstance + self.data = data + } + } + public class Cons_updateChannel { + public var channelId: Int64 + public init(channelId: Int64) { + self.channelId = channelId + } + } + public class Cons_updateChannelAvailableMessages { + public var channelId: Int64 + public var availableMinId: Int32 + public init(channelId: Int64, availableMinId: Int32) { + self.channelId = channelId + self.availableMinId = availableMinId + } + } + public class Cons_updateChannelMessageForwards { + public var channelId: Int64 + public var id: Int32 + public var forwards: Int32 + public init(channelId: Int64, id: Int32, forwards: Int32) { + self.channelId = channelId + self.id = id + self.forwards = forwards + } + } + public class Cons_updateChannelMessageViews { + public var channelId: Int64 + public var id: Int32 + public var views: Int32 + public init(channelId: Int64, id: Int32, views: Int32) { + self.channelId = channelId + self.id = id + self.views = views + } + } + public class Cons_updateChannelParticipant { + public var flags: Int32 + public var channelId: Int64 + public var date: Int32 + public var actorId: Int64 + public var userId: Int64 + public var prevParticipant: Api.ChannelParticipant? + public var newParticipant: Api.ChannelParticipant? + public var invite: Api.ExportedChatInvite? + public var qts: Int32 + public init(flags: Int32, channelId: Int64, date: Int32, actorId: Int64, userId: Int64, prevParticipant: Api.ChannelParticipant?, newParticipant: Api.ChannelParticipant?, invite: Api.ExportedChatInvite?, qts: Int32) { + self.flags = flags + self.channelId = channelId + self.date = date + self.actorId = actorId + self.userId = userId + self.prevParticipant = prevParticipant + self.newParticipant = newParticipant + self.invite = invite + self.qts = qts + } + } + public class Cons_updateChannelReadMessagesContents { + public var flags: Int32 + public var channelId: Int64 + public var topMsgId: Int32? + public var savedPeerId: Api.Peer? + public var messages: [Int32] + public init(flags: Int32, channelId: Int64, topMsgId: Int32?, savedPeerId: Api.Peer?, messages: [Int32]) { + self.flags = flags + self.channelId = channelId + self.topMsgId = topMsgId + self.savedPeerId = savedPeerId + self.messages = messages + } + } + public class Cons_updateChannelTooLong { + public var flags: Int32 + public var channelId: Int64 + public var pts: Int32? + public init(flags: Int32, channelId: Int64, pts: Int32?) { + self.flags = flags + self.channelId = channelId + self.pts = pts + } + } + public class Cons_updateChannelUserTyping { + public var flags: Int32 + public var channelId: Int64 + public var topMsgId: Int32? + public var fromId: Api.Peer + public var action: Api.SendMessageAction + public init(flags: Int32, channelId: Int64, topMsgId: Int32?, fromId: Api.Peer, action: Api.SendMessageAction) { + self.flags = flags + self.channelId = channelId + self.topMsgId = topMsgId + self.fromId = fromId + self.action = action + } + } + public class Cons_updateChannelViewForumAsMessages { + public var channelId: Int64 + public var enabled: Api.Bool + public init(channelId: Int64, enabled: Api.Bool) { + self.channelId = channelId + self.enabled = enabled + } + } + public class Cons_updateChannelWebPage { + public var channelId: Int64 + public var webpage: Api.WebPage + public var pts: Int32 + public var ptsCount: Int32 + public init(channelId: Int64, webpage: Api.WebPage, pts: Int32, ptsCount: Int32) { + self.channelId = channelId + self.webpage = webpage + self.pts = pts + self.ptsCount = ptsCount + } + } + public class Cons_updateChat { + public var chatId: Int64 + public init(chatId: Int64) { + self.chatId = chatId + } + } + public class Cons_updateChatDefaultBannedRights { + public var peer: Api.Peer + public var defaultBannedRights: Api.ChatBannedRights + public var version: Int32 + public init(peer: Api.Peer, defaultBannedRights: Api.ChatBannedRights, version: Int32) { + self.peer = peer + self.defaultBannedRights = defaultBannedRights + self.version = version + } + } + public class Cons_updateChatParticipant { + public var flags: Int32 + public var chatId: Int64 + public var date: Int32 + public var actorId: Int64 + public var userId: Int64 + public var prevParticipant: Api.ChatParticipant? + public var newParticipant: Api.ChatParticipant? + public var invite: Api.ExportedChatInvite? + public var qts: Int32 + public init(flags: Int32, chatId: Int64, date: Int32, actorId: Int64, userId: Int64, prevParticipant: Api.ChatParticipant?, newParticipant: Api.ChatParticipant?, invite: Api.ExportedChatInvite?, qts: Int32) { + self.flags = flags + self.chatId = chatId + self.date = date + self.actorId = actorId + self.userId = userId + self.prevParticipant = prevParticipant + self.newParticipant = newParticipant + self.invite = invite + self.qts = qts + } + } + public class Cons_updateChatParticipantAdd { + public var chatId: Int64 + public var userId: Int64 + public var inviterId: Int64 + public var date: Int32 + public var version: Int32 + public init(chatId: Int64, userId: Int64, inviterId: Int64, date: Int32, version: Int32) { + self.chatId = chatId + self.userId = userId + self.inviterId = inviterId + self.date = date + self.version = version + } + } + public class Cons_updateChatParticipantAdmin { + public var chatId: Int64 + public var userId: Int64 + public var isAdmin: Api.Bool + public var version: Int32 + public init(chatId: Int64, userId: Int64, isAdmin: Api.Bool, version: Int32) { + self.chatId = chatId + self.userId = userId + self.isAdmin = isAdmin + self.version = version + } + } + public class Cons_updateChatParticipantDelete { + public var chatId: Int64 + public var userId: Int64 + public var version: Int32 + public init(chatId: Int64, userId: Int64, version: Int32) { + self.chatId = chatId + self.userId = userId + self.version = version + } + } + public class Cons_updateChatParticipants { + public var participants: Api.ChatParticipants + public init(participants: Api.ChatParticipants) { + self.participants = participants + } + } + public class Cons_updateChatUserTyping { + public var chatId: Int64 + public var fromId: Api.Peer + public var action: Api.SendMessageAction + public init(chatId: Int64, fromId: Api.Peer, action: Api.SendMessageAction) { + self.chatId = chatId + self.fromId = fromId + self.action = action + } + } + public class Cons_updateDcOptions { + public var dcOptions: [Api.DcOption] + public init(dcOptions: [Api.DcOption]) { + self.dcOptions = dcOptions + } + } + public class Cons_updateDeleteChannelMessages { + public var channelId: Int64 + public var messages: [Int32] + public var pts: Int32 + public var ptsCount: Int32 + public init(channelId: Int64, messages: [Int32], pts: Int32, ptsCount: Int32) { + self.channelId = channelId + self.messages = messages + self.pts = pts + self.ptsCount = ptsCount + } + } + public class Cons_updateDeleteGroupCallMessages { + public var call: Api.InputGroupCall + public var messages: [Int32] + public init(call: Api.InputGroupCall, messages: [Int32]) { + self.call = call + self.messages = messages + } + } + public class Cons_updateDeleteMessages { + public var messages: [Int32] + public var pts: Int32 + public var ptsCount: Int32 + public init(messages: [Int32], pts: Int32, ptsCount: Int32) { + self.messages = messages + self.pts = pts + self.ptsCount = ptsCount + } + } + public class Cons_updateDeleteQuickReply { + public var shortcutId: Int32 + public init(shortcutId: Int32) { + self.shortcutId = shortcutId + } + } + public class Cons_updateDeleteQuickReplyMessages { + public var shortcutId: Int32 + public var messages: [Int32] + public init(shortcutId: Int32, messages: [Int32]) { + self.shortcutId = shortcutId + self.messages = messages + } + } + public class Cons_updateDeleteScheduledMessages { + public var flags: Int32 + public var peer: Api.Peer + public var messages: [Int32] + public var sentMessages: [Int32]? + public init(flags: Int32, peer: Api.Peer, messages: [Int32], sentMessages: [Int32]?) { + self.flags = flags + self.peer = peer + self.messages = messages + self.sentMessages = sentMessages + } + } + public class Cons_updateDialogFilter { + public var flags: Int32 + public var id: Int32 + public var filter: Api.DialogFilter? + public init(flags: Int32, id: Int32, filter: Api.DialogFilter?) { + self.flags = flags + self.id = id + self.filter = filter + } + } + public class Cons_updateDialogFilterOrder { + public var order: [Int32] + public init(order: [Int32]) { + self.order = order + } + } + public class Cons_updateDialogPinned { + public var flags: Int32 + public var folderId: Int32? + public var peer: Api.DialogPeer + public init(flags: Int32, folderId: Int32?, peer: Api.DialogPeer) { + self.flags = flags + self.folderId = folderId + self.peer = peer + } + } + public class Cons_updateDialogUnreadMark { + public var flags: Int32 + public var peer: Api.DialogPeer + public var savedPeerId: Api.Peer? + public init(flags: Int32, peer: Api.DialogPeer, savedPeerId: Api.Peer?) { + self.flags = flags + self.peer = peer + self.savedPeerId = savedPeerId + } + } + public class Cons_updateDraftMessage { + public var flags: Int32 + public var peer: Api.Peer + public var topMsgId: Int32? + public var savedPeerId: Api.Peer? + public var draft: Api.DraftMessage + public init(flags: Int32, peer: Api.Peer, topMsgId: Int32?, savedPeerId: Api.Peer?, draft: Api.DraftMessage) { + self.flags = flags + self.peer = peer + self.topMsgId = topMsgId + self.savedPeerId = savedPeerId + self.draft = draft + } + } + public class Cons_updateEditChannelMessage { + public var message: Api.Message + public var pts: Int32 + public var ptsCount: Int32 + public init(message: Api.Message, pts: Int32, ptsCount: Int32) { + self.message = message + self.pts = pts + self.ptsCount = ptsCount + } + } + public class Cons_updateEditMessage { + public var message: Api.Message + public var pts: Int32 + public var ptsCount: Int32 + public init(message: Api.Message, pts: Int32, ptsCount: Int32) { + self.message = message + self.pts = pts + self.ptsCount = ptsCount + } + } + public class Cons_updateEmojiGameInfo { + public var info: Api.messages.EmojiGameInfo + public init(info: Api.messages.EmojiGameInfo) { + self.info = info + } + } + public class Cons_updateEncryptedChatTyping { + public var chatId: Int32 + public init(chatId: Int32) { + self.chatId = chatId + } + } + public class Cons_updateEncryptedMessagesRead { + public var chatId: Int32 + public var maxDate: Int32 + public var date: Int32 + public init(chatId: Int32, maxDate: Int32, date: Int32) { + self.chatId = chatId + self.maxDate = maxDate + self.date = date + } + } + public class Cons_updateEncryption { + public var chat: Api.EncryptedChat + public var date: Int32 + public init(chat: Api.EncryptedChat, date: Int32) { + self.chat = chat + self.date = date + } + } + public class Cons_updateFolderPeers { + public var folderPeers: [Api.FolderPeer] + public var pts: Int32 + public var ptsCount: Int32 + public init(folderPeers: [Api.FolderPeer], pts: Int32, ptsCount: Int32) { + self.folderPeers = folderPeers + self.pts = pts + self.ptsCount = ptsCount + } + } + public class Cons_updateGeoLiveViewed { + public var peer: Api.Peer + public var msgId: Int32 + public init(peer: Api.Peer, msgId: Int32) { + self.peer = peer + self.msgId = msgId + } + } + public class Cons_updateGroupCall { + public var flags: Int32 + public var peer: Api.Peer? + public var call: Api.GroupCall + public init(flags: Int32, peer: Api.Peer?, call: Api.GroupCall) { + self.flags = flags + self.peer = peer + self.call = call + } + } + public class Cons_updateGroupCallChainBlocks { + public var call: Api.InputGroupCall + public var subChainId: Int32 + public var blocks: [Buffer] + public var nextOffset: Int32 + public init(call: Api.InputGroupCall, subChainId: Int32, blocks: [Buffer], nextOffset: Int32) { + self.call = call + self.subChainId = subChainId + self.blocks = blocks + self.nextOffset = nextOffset + } + } + public class Cons_updateGroupCallConnection { + public var flags: Int32 + public var params: Api.DataJSON + public init(flags: Int32, params: Api.DataJSON) { + self.flags = flags + self.params = params + } + } + public class Cons_updateGroupCallEncryptedMessage { + public var call: Api.InputGroupCall + public var fromId: Api.Peer + public var encryptedMessage: Buffer + public init(call: Api.InputGroupCall, fromId: Api.Peer, encryptedMessage: Buffer) { + self.call = call + self.fromId = fromId + self.encryptedMessage = encryptedMessage + } + } + public class Cons_updateGroupCallMessage { + public var call: Api.InputGroupCall + public var message: Api.GroupCallMessage + public init(call: Api.InputGroupCall, message: Api.GroupCallMessage) { + self.call = call + self.message = message + } + } + public class Cons_updateGroupCallParticipants { + public var call: Api.InputGroupCall + public var participants: [Api.GroupCallParticipant] + public var version: Int32 + public init(call: Api.InputGroupCall, participants: [Api.GroupCallParticipant], version: Int32) { + self.call = call + self.participants = participants + self.version = version + } + } + public class Cons_updateInlineBotCallbackQuery { + public var flags: Int32 + public var queryId: Int64 + public var userId: Int64 + public var msgId: Api.InputBotInlineMessageID + public var chatInstance: Int64 + public var data: Buffer? + public var gameShortName: String? + public init(flags: Int32, queryId: Int64, userId: Int64, msgId: Api.InputBotInlineMessageID, chatInstance: Int64, data: Buffer?, gameShortName: String?) { + self.flags = flags + self.queryId = queryId + self.userId = userId + self.msgId = msgId + self.chatInstance = chatInstance + self.data = data + self.gameShortName = gameShortName + } + } + public class Cons_updateLangPack { + public var difference: Api.LangPackDifference + public init(difference: Api.LangPackDifference) { + self.difference = difference + } + } + public class Cons_updateLangPackTooLong { + public var langCode: String + public init(langCode: String) { + self.langCode = langCode + } + } + public class Cons_updateMessageExtendedMedia { + public var peer: Api.Peer + public var msgId: Int32 + public var extendedMedia: [Api.MessageExtendedMedia] + public init(peer: Api.Peer, msgId: Int32, extendedMedia: [Api.MessageExtendedMedia]) { + self.peer = peer + self.msgId = msgId + self.extendedMedia = extendedMedia + } + } + public class Cons_updateMessageID { + public var id: Int32 + public var randomId: Int64 + public init(id: Int32, randomId: Int64) { + self.id = id + self.randomId = randomId + } + } + public class Cons_updateMessagePoll { + public var flags: Int32 + public var pollId: Int64 + public var poll: Api.Poll? + public var results: Api.PollResults + public init(flags: Int32, pollId: Int64, poll: Api.Poll?, results: Api.PollResults) { + self.flags = flags + self.pollId = pollId + self.poll = poll + self.results = results + } + } + public class Cons_updateMessagePollVote { + public var pollId: Int64 + public var peer: Api.Peer + public var options: [Buffer] + public var qts: Int32 + public init(pollId: Int64, peer: Api.Peer, options: [Buffer], qts: Int32) { + self.pollId = pollId + self.peer = peer + self.options = options + self.qts = qts + } + } + public class Cons_updateMessageReactions { + public var flags: Int32 + public var peer: Api.Peer + public var msgId: Int32 + public var topMsgId: Int32? + public var savedPeerId: Api.Peer? + public var reactions: Api.MessageReactions + public init(flags: Int32, peer: Api.Peer, msgId: Int32, topMsgId: Int32?, savedPeerId: Api.Peer?, reactions: Api.MessageReactions) { + self.flags = flags + self.peer = peer + self.msgId = msgId + self.topMsgId = topMsgId + self.savedPeerId = savedPeerId + self.reactions = reactions + } + } + public class Cons_updateMonoForumNoPaidException { + public var flags: Int32 + public var channelId: Int64 + public var savedPeerId: Api.Peer + public init(flags: Int32, channelId: Int64, savedPeerId: Api.Peer) { + self.flags = flags + self.channelId = channelId + self.savedPeerId = savedPeerId + } + } + public class Cons_updateMoveStickerSetToTop { + public var flags: Int32 + public var stickerset: Int64 + public init(flags: Int32, stickerset: Int64) { + self.flags = flags + self.stickerset = stickerset + } + } + public class Cons_updateNewAuthorization { + public var flags: Int32 + public var hash: Int64 + public var date: Int32? + public var device: String? + public var location: String? + public init(flags: Int32, hash: Int64, date: Int32?, device: String?, location: String?) { + self.flags = flags + self.hash = hash + self.date = date + self.device = device + self.location = location + } + } + public class Cons_updateNewChannelMessage { + public var message: Api.Message + public var pts: Int32 + public var ptsCount: Int32 + public init(message: Api.Message, pts: Int32, ptsCount: Int32) { + self.message = message + self.pts = pts + self.ptsCount = ptsCount + } + } + public class Cons_updateNewEncryptedMessage { + public var message: Api.EncryptedMessage + public var qts: Int32 + public init(message: Api.EncryptedMessage, qts: Int32) { + self.message = message + self.qts = qts + } + } + public class Cons_updateNewMessage { + public var message: Api.Message + public var pts: Int32 + public var ptsCount: Int32 + public init(message: Api.Message, pts: Int32, ptsCount: Int32) { + self.message = message + self.pts = pts + self.ptsCount = ptsCount + } + } + public class Cons_updateNewQuickReply { + public var quickReply: Api.QuickReply + public init(quickReply: Api.QuickReply) { + self.quickReply = quickReply + } + } + public class Cons_updateNewScheduledMessage { + public var message: Api.Message + public init(message: Api.Message) { + self.message = message + } + } + public class Cons_updateNewStickerSet { + public var stickerset: Api.messages.StickerSet + public init(stickerset: Api.messages.StickerSet) { + self.stickerset = stickerset + } + } + public class Cons_updateNewStoryReaction { + public var storyId: Int32 + public var peer: Api.Peer + public var reaction: Api.Reaction + public init(storyId: Int32, peer: Api.Peer, reaction: Api.Reaction) { + self.storyId = storyId + self.peer = peer + self.reaction = reaction + } + } + public class Cons_updateNotifySettings { + public var peer: Api.NotifyPeer + public var notifySettings: Api.PeerNotifySettings + public init(peer: Api.NotifyPeer, notifySettings: Api.PeerNotifySettings) { + self.peer = peer + self.notifySettings = notifySettings + } + } + public class Cons_updatePaidReactionPrivacy { + public var `private`: Api.PaidReactionPrivacy + public init(`private`: Api.PaidReactionPrivacy) { + self.`private` = `private` + } + } + public class Cons_updatePeerBlocked { + public var flags: Int32 + public var peerId: Api.Peer + public init(flags: Int32, peerId: Api.Peer) { + self.flags = flags + self.peerId = peerId + } + } + public class Cons_updatePeerHistoryTTL { + public var flags: Int32 + public var peer: Api.Peer + public var ttlPeriod: Int32? + public init(flags: Int32, peer: Api.Peer, ttlPeriod: Int32?) { + self.flags = flags + self.peer = peer + self.ttlPeriod = ttlPeriod + } + } + public class Cons_updatePeerLocated { + public var peers: [Api.PeerLocated] + public init(peers: [Api.PeerLocated]) { + self.peers = peers + } + } + public class Cons_updatePeerSettings { + public var peer: Api.Peer + public var settings: Api.PeerSettings + public init(peer: Api.Peer, settings: Api.PeerSettings) { + self.peer = peer + self.settings = settings + } + } + public class Cons_updatePeerWallpaper { + public var flags: Int32 + public var peer: Api.Peer + public var wallpaper: Api.WallPaper? + public init(flags: Int32, peer: Api.Peer, wallpaper: Api.WallPaper?) { + self.flags = flags + self.peer = peer + self.wallpaper = wallpaper + } + } + public class Cons_updatePendingJoinRequests { + public var peer: Api.Peer + public var requestsPending: Int32 + public var recentRequesters: [Int64] + public init(peer: Api.Peer, requestsPending: Int32, recentRequesters: [Int64]) { + self.peer = peer + self.requestsPending = requestsPending + self.recentRequesters = recentRequesters + } + } + public class Cons_updatePhoneCall { + public var phoneCall: Api.PhoneCall + public init(phoneCall: Api.PhoneCall) { + self.phoneCall = phoneCall + } + } + public class Cons_updatePhoneCallSignalingData { + public var phoneCallId: Int64 + public var data: Buffer + public init(phoneCallId: Int64, data: Buffer) { + self.phoneCallId = phoneCallId + self.data = data + } + } + public class Cons_updatePinnedChannelMessages { + public var flags: Int32 + public var channelId: Int64 + public var messages: [Int32] + public var pts: Int32 + public var ptsCount: Int32 + public init(flags: Int32, channelId: Int64, messages: [Int32], pts: Int32, ptsCount: Int32) { + self.flags = flags + self.channelId = channelId + self.messages = messages + self.pts = pts + self.ptsCount = ptsCount + } + } + public class Cons_updatePinnedDialogs { + public var flags: Int32 + public var folderId: Int32? + public var order: [Api.DialogPeer]? + public init(flags: Int32, folderId: Int32?, order: [Api.DialogPeer]?) { + self.flags = flags + self.folderId = folderId + self.order = order + } + } + public class Cons_updatePinnedForumTopic { + public var flags: Int32 + public var peer: Api.Peer + public var topicId: Int32 + public init(flags: Int32, peer: Api.Peer, topicId: Int32) { + self.flags = flags + self.peer = peer + self.topicId = topicId + } + } + public class Cons_updatePinnedForumTopics { + public var flags: Int32 + public var peer: Api.Peer + public var order: [Int32]? + public init(flags: Int32, peer: Api.Peer, order: [Int32]?) { + self.flags = flags + self.peer = peer + self.order = order + } + } + public class Cons_updatePinnedMessages { + public var flags: Int32 + public var peer: Api.Peer + public var messages: [Int32] + public var pts: Int32 + public var ptsCount: Int32 + public init(flags: Int32, peer: Api.Peer, messages: [Int32], pts: Int32, ptsCount: Int32) { + self.flags = flags + self.peer = peer + self.messages = messages + self.pts = pts + self.ptsCount = ptsCount + } + } + public class Cons_updatePinnedSavedDialogs { + public var flags: Int32 + public var order: [Api.DialogPeer]? + public init(flags: Int32, order: [Api.DialogPeer]?) { + self.flags = flags + self.order = order + } + } + public class Cons_updatePrivacy { + public var key: Api.PrivacyKey + public var rules: [Api.PrivacyRule] + public init(key: Api.PrivacyKey, rules: [Api.PrivacyRule]) { + self.key = key + self.rules = rules + } + } + public class Cons_updateQuickReplies { + public var quickReplies: [Api.QuickReply] + public init(quickReplies: [Api.QuickReply]) { + self.quickReplies = quickReplies + } + } + public class Cons_updateQuickReplyMessage { + public var message: Api.Message + public init(message: Api.Message) { + self.message = message + } + } + public class Cons_updateReadChannelDiscussionInbox { + public var flags: Int32 + public var channelId: Int64 + public var topMsgId: Int32 + public var readMaxId: Int32 + public var broadcastId: Int64? + public var broadcastPost: Int32? + public init(flags: Int32, channelId: Int64, topMsgId: Int32, readMaxId: Int32, broadcastId: Int64?, broadcastPost: Int32?) { + self.flags = flags + self.channelId = channelId + self.topMsgId = topMsgId + self.readMaxId = readMaxId + self.broadcastId = broadcastId + self.broadcastPost = broadcastPost + } + } + public class Cons_updateReadChannelDiscussionOutbox { + public var channelId: Int64 + public var topMsgId: Int32 + public var readMaxId: Int32 + public init(channelId: Int64, topMsgId: Int32, readMaxId: Int32) { + self.channelId = channelId + self.topMsgId = topMsgId + self.readMaxId = readMaxId + } + } + public class Cons_updateReadChannelInbox { + public var flags: Int32 + public var folderId: Int32? + public var channelId: Int64 + public var maxId: Int32 + public var stillUnreadCount: Int32 + public var pts: Int32 + public init(flags: Int32, folderId: Int32?, channelId: Int64, maxId: Int32, stillUnreadCount: Int32, pts: Int32) { + self.flags = flags + self.folderId = folderId + self.channelId = channelId + self.maxId = maxId + self.stillUnreadCount = stillUnreadCount + self.pts = pts + } + } + public class Cons_updateReadChannelOutbox { + public var channelId: Int64 + public var maxId: Int32 + public init(channelId: Int64, maxId: Int32) { + self.channelId = channelId + self.maxId = maxId + } + } + public class Cons_updateReadHistoryInbox { + public var flags: Int32 + public var folderId: Int32? + public var peer: Api.Peer + public var topMsgId: Int32? + public var maxId: Int32 + public var stillUnreadCount: Int32 + public var pts: Int32 + public var ptsCount: Int32 + public init(flags: Int32, folderId: Int32?, peer: Api.Peer, topMsgId: Int32?, maxId: Int32, stillUnreadCount: Int32, pts: Int32, ptsCount: Int32) { + self.flags = flags + self.folderId = folderId + self.peer = peer + self.topMsgId = topMsgId + self.maxId = maxId + self.stillUnreadCount = stillUnreadCount + self.pts = pts + self.ptsCount = ptsCount + } + } + public class Cons_updateReadHistoryOutbox { + public var peer: Api.Peer + public var maxId: Int32 + public var pts: Int32 + public var ptsCount: Int32 + public init(peer: Api.Peer, maxId: Int32, pts: Int32, ptsCount: Int32) { + self.peer = peer + self.maxId = maxId + self.pts = pts + self.ptsCount = ptsCount + } + } + public class Cons_updateReadMessagesContents { + public var flags: Int32 + public var messages: [Int32] + public var pts: Int32 + public var ptsCount: Int32 + public var date: Int32? + public init(flags: Int32, messages: [Int32], pts: Int32, ptsCount: Int32, date: Int32?) { + self.flags = flags + self.messages = messages + self.pts = pts + self.ptsCount = ptsCount + self.date = date + } + } + public class Cons_updateReadMonoForumInbox { + public var channelId: Int64 + public var savedPeerId: Api.Peer + public var readMaxId: Int32 + public init(channelId: Int64, savedPeerId: Api.Peer, readMaxId: Int32) { + self.channelId = channelId + self.savedPeerId = savedPeerId + self.readMaxId = readMaxId + } + } + public class Cons_updateReadMonoForumOutbox { + public var channelId: Int64 + public var savedPeerId: Api.Peer + public var readMaxId: Int32 + public init(channelId: Int64, savedPeerId: Api.Peer, readMaxId: Int32) { + self.channelId = channelId + self.savedPeerId = savedPeerId + self.readMaxId = readMaxId + } + } + public class Cons_updateReadStories { + public var peer: Api.Peer + public var maxId: Int32 + public init(peer: Api.Peer, maxId: Int32) { + self.peer = peer + self.maxId = maxId + } + } + public class Cons_updateSavedDialogPinned { + public var flags: Int32 + public var peer: Api.DialogPeer + public init(flags: Int32, peer: Api.DialogPeer) { + self.flags = flags + self.peer = peer + } + } + public class Cons_updateSentPhoneCode { + public var sentCode: Api.auth.SentCode + public init(sentCode: Api.auth.SentCode) { + self.sentCode = sentCode + } + } + public class Cons_updateSentStoryReaction { + public var peer: Api.Peer + public var storyId: Int32 + public var reaction: Api.Reaction + public init(peer: Api.Peer, storyId: Int32, reaction: Api.Reaction) { + self.peer = peer + self.storyId = storyId + self.reaction = reaction + } + } + public class Cons_updateServiceNotification { + public var flags: Int32 + public var inboxDate: Int32? + public var type: String + public var message: String + public var media: Api.MessageMedia + public var entities: [Api.MessageEntity] + public init(flags: Int32, inboxDate: Int32?, type: String, message: String, media: Api.MessageMedia, entities: [Api.MessageEntity]) { + self.flags = flags + self.inboxDate = inboxDate + self.type = type + self.message = message + self.media = media + self.entities = entities + } + } + public class Cons_updateSmsJob { + public var jobId: String + public init(jobId: String) { + self.jobId = jobId + } + } + public class Cons_updateStarGiftAuctionState { + public var giftId: Int64 + public var state: Api.StarGiftAuctionState + public init(giftId: Int64, state: Api.StarGiftAuctionState) { + self.giftId = giftId + self.state = state + } + } + public class Cons_updateStarGiftAuctionUserState { + public var giftId: Int64 + public var userState: Api.StarGiftAuctionUserState + public init(giftId: Int64, userState: Api.StarGiftAuctionUserState) { + self.giftId = giftId + self.userState = userState + } + } + public class Cons_updateStarsBalance { + public var balance: Api.StarsAmount + public init(balance: Api.StarsAmount) { + self.balance = balance + } + } + public class Cons_updateStarsRevenueStatus { + public var peer: Api.Peer + public var status: Api.StarsRevenueStatus + public init(peer: Api.Peer, status: Api.StarsRevenueStatus) { + self.peer = peer + self.status = status + } + } + public class Cons_updateStickerSets { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } + public class Cons_updateStickerSetsOrder { + public var flags: Int32 + public var order: [Int64] + public init(flags: Int32, order: [Int64]) { + self.flags = flags + self.order = order + } + } + public class Cons_updateStoriesStealthMode { + public var stealthMode: Api.StoriesStealthMode + public init(stealthMode: Api.StoriesStealthMode) { + self.stealthMode = stealthMode + } + } + public class Cons_updateStory { + public var peer: Api.Peer + public var story: Api.StoryItem + public init(peer: Api.Peer, story: Api.StoryItem) { + self.peer = peer + self.story = story + } + } + public class Cons_updateStoryID { + public var id: Int32 + public var randomId: Int64 + public init(id: Int32, randomId: Int64) { + self.id = id + self.randomId = randomId + } + } + public class Cons_updateTheme { + public var theme: Api.Theme + public init(theme: Api.Theme) { + self.theme = theme + } + } + public class Cons_updateTranscribedAudio { + public var flags: Int32 + public var peer: Api.Peer + public var msgId: Int32 + public var transcriptionId: Int64 + public var text: String + public init(flags: Int32, peer: Api.Peer, msgId: Int32, transcriptionId: Int64, text: String) { + self.flags = flags + self.peer = peer + self.msgId = msgId + self.transcriptionId = transcriptionId + self.text = text + } + } + public class Cons_updateUser { + public var userId: Int64 + public init(userId: Int64) { + self.userId = userId + } + } + public class Cons_updateUserEmojiStatus { + public var userId: Int64 + public var emojiStatus: Api.EmojiStatus + public init(userId: Int64, emojiStatus: Api.EmojiStatus) { + self.userId = userId + self.emojiStatus = emojiStatus + } + } + public class Cons_updateUserName { + public var userId: Int64 + public var firstName: String + public var lastName: String + public var usernames: [Api.Username] + public init(userId: Int64, firstName: String, lastName: String, usernames: [Api.Username]) { + self.userId = userId + self.firstName = firstName + self.lastName = lastName + self.usernames = usernames + } + } + public class Cons_updateUserPhone { + public var userId: Int64 + public var phone: String + public init(userId: Int64, phone: String) { + self.userId = userId + self.phone = phone + } + } + public class Cons_updateUserStatus { + public var userId: Int64 + public var status: Api.UserStatus + public init(userId: Int64, status: Api.UserStatus) { + self.userId = userId + self.status = status + } + } + public class Cons_updateUserTyping { + public var flags: Int32 + public var userId: Int64 + public var topMsgId: Int32? + public var action: Api.SendMessageAction + public init(flags: Int32, userId: Int64, topMsgId: Int32?, action: Api.SendMessageAction) { + self.flags = flags + self.userId = userId + self.topMsgId = topMsgId + self.action = action + } + } + public class Cons_updateWebPage { + public var webpage: Api.WebPage + public var pts: Int32 + public var ptsCount: Int32 + public init(webpage: Api.WebPage, pts: Int32, ptsCount: Int32) { + self.webpage = webpage + self.pts = pts + self.ptsCount = ptsCount + } + } + public class Cons_updateWebViewResultSent { + public var queryId: Int64 + public init(queryId: Int64) { + self.queryId = queryId + } + } + case updateAttachMenuBots + case updateAutoSaveSettings + case updateBotBusinessConnect(Cons_updateBotBusinessConnect) + case updateBotCallbackQuery(Cons_updateBotCallbackQuery) + case updateBotChatBoost(Cons_updateBotChatBoost) + case updateBotChatInviteRequester(Cons_updateBotChatInviteRequester) + case updateBotCommands(Cons_updateBotCommands) + case updateBotDeleteBusinessMessage(Cons_updateBotDeleteBusinessMessage) + case updateBotEditBusinessMessage(Cons_updateBotEditBusinessMessage) + case updateBotInlineQuery(Cons_updateBotInlineQuery) + case updateBotInlineSend(Cons_updateBotInlineSend) + case updateBotMenuButton(Cons_updateBotMenuButton) + case updateBotMessageReaction(Cons_updateBotMessageReaction) + case updateBotMessageReactions(Cons_updateBotMessageReactions) + case updateBotNewBusinessMessage(Cons_updateBotNewBusinessMessage) + case updateBotPrecheckoutQuery(Cons_updateBotPrecheckoutQuery) + case updateBotPurchasedPaidMedia(Cons_updateBotPurchasedPaidMedia) + case updateBotShippingQuery(Cons_updateBotShippingQuery) + case updateBotStopped(Cons_updateBotStopped) + case updateBotWebhookJSON(Cons_updateBotWebhookJSON) + case updateBotWebhookJSONQuery(Cons_updateBotWebhookJSONQuery) + case updateBusinessBotCallbackQuery(Cons_updateBusinessBotCallbackQuery) + case updateChannel(Cons_updateChannel) + case updateChannelAvailableMessages(Cons_updateChannelAvailableMessages) + case updateChannelMessageForwards(Cons_updateChannelMessageForwards) + case updateChannelMessageViews(Cons_updateChannelMessageViews) + case updateChannelParticipant(Cons_updateChannelParticipant) + case updateChannelReadMessagesContents(Cons_updateChannelReadMessagesContents) + case updateChannelTooLong(Cons_updateChannelTooLong) + case updateChannelUserTyping(Cons_updateChannelUserTyping) + case updateChannelViewForumAsMessages(Cons_updateChannelViewForumAsMessages) + case updateChannelWebPage(Cons_updateChannelWebPage) + case updateChat(Cons_updateChat) + case updateChatDefaultBannedRights(Cons_updateChatDefaultBannedRights) + case updateChatParticipant(Cons_updateChatParticipant) + case updateChatParticipantAdd(Cons_updateChatParticipantAdd) + case updateChatParticipantAdmin(Cons_updateChatParticipantAdmin) + case updateChatParticipantDelete(Cons_updateChatParticipantDelete) + case updateChatParticipants(Cons_updateChatParticipants) + case updateChatUserTyping(Cons_updateChatUserTyping) + case updateConfig + case updateContactsReset + case updateDcOptions(Cons_updateDcOptions) + case updateDeleteChannelMessages(Cons_updateDeleteChannelMessages) + case updateDeleteGroupCallMessages(Cons_updateDeleteGroupCallMessages) + case updateDeleteMessages(Cons_updateDeleteMessages) + case updateDeleteQuickReply(Cons_updateDeleteQuickReply) + case updateDeleteQuickReplyMessages(Cons_updateDeleteQuickReplyMessages) + case updateDeleteScheduledMessages(Cons_updateDeleteScheduledMessages) + case updateDialogFilter(Cons_updateDialogFilter) + case updateDialogFilterOrder(Cons_updateDialogFilterOrder) + case updateDialogFilters + case updateDialogPinned(Cons_updateDialogPinned) + case updateDialogUnreadMark(Cons_updateDialogUnreadMark) + case updateDraftMessage(Cons_updateDraftMessage) + case updateEditChannelMessage(Cons_updateEditChannelMessage) + case updateEditMessage(Cons_updateEditMessage) + case updateEmojiGameInfo(Cons_updateEmojiGameInfo) + case updateEncryptedChatTyping(Cons_updateEncryptedChatTyping) + case updateEncryptedMessagesRead(Cons_updateEncryptedMessagesRead) + case updateEncryption(Cons_updateEncryption) + case updateFavedStickers + case updateFolderPeers(Cons_updateFolderPeers) + case updateGeoLiveViewed(Cons_updateGeoLiveViewed) + case updateGroupCall(Cons_updateGroupCall) + case updateGroupCallChainBlocks(Cons_updateGroupCallChainBlocks) + case updateGroupCallConnection(Cons_updateGroupCallConnection) + case updateGroupCallEncryptedMessage(Cons_updateGroupCallEncryptedMessage) + case updateGroupCallMessage(Cons_updateGroupCallMessage) + case updateGroupCallParticipants(Cons_updateGroupCallParticipants) + case updateInlineBotCallbackQuery(Cons_updateInlineBotCallbackQuery) + case updateLangPack(Cons_updateLangPack) + case updateLangPackTooLong(Cons_updateLangPackTooLong) + case updateLoginToken + case updateMessageExtendedMedia(Cons_updateMessageExtendedMedia) + case updateMessageID(Cons_updateMessageID) + case updateMessagePoll(Cons_updateMessagePoll) + case updateMessagePollVote(Cons_updateMessagePollVote) + case updateMessageReactions(Cons_updateMessageReactions) + case updateMonoForumNoPaidException(Cons_updateMonoForumNoPaidException) + case updateMoveStickerSetToTop(Cons_updateMoveStickerSetToTop) + case updateNewAuthorization(Cons_updateNewAuthorization) + case updateNewChannelMessage(Cons_updateNewChannelMessage) + case updateNewEncryptedMessage(Cons_updateNewEncryptedMessage) + case updateNewMessage(Cons_updateNewMessage) + case updateNewQuickReply(Cons_updateNewQuickReply) + case updateNewScheduledMessage(Cons_updateNewScheduledMessage) + case updateNewStickerSet(Cons_updateNewStickerSet) + case updateNewStoryReaction(Cons_updateNewStoryReaction) + case updateNotifySettings(Cons_updateNotifySettings) + case updatePaidReactionPrivacy(Cons_updatePaidReactionPrivacy) + case updatePeerBlocked(Cons_updatePeerBlocked) + case updatePeerHistoryTTL(Cons_updatePeerHistoryTTL) + case updatePeerLocated(Cons_updatePeerLocated) + case updatePeerSettings(Cons_updatePeerSettings) + case updatePeerWallpaper(Cons_updatePeerWallpaper) + case updatePendingJoinRequests(Cons_updatePendingJoinRequests) + case updatePhoneCall(Cons_updatePhoneCall) + case updatePhoneCallSignalingData(Cons_updatePhoneCallSignalingData) + case updatePinnedChannelMessages(Cons_updatePinnedChannelMessages) + case updatePinnedDialogs(Cons_updatePinnedDialogs) + case updatePinnedForumTopic(Cons_updatePinnedForumTopic) + case updatePinnedForumTopics(Cons_updatePinnedForumTopics) + case updatePinnedMessages(Cons_updatePinnedMessages) + case updatePinnedSavedDialogs(Cons_updatePinnedSavedDialogs) + case updatePrivacy(Cons_updatePrivacy) + case updatePtsChanged + case updateQuickReplies(Cons_updateQuickReplies) + case updateQuickReplyMessage(Cons_updateQuickReplyMessage) + case updateReadChannelDiscussionInbox(Cons_updateReadChannelDiscussionInbox) + case updateReadChannelDiscussionOutbox(Cons_updateReadChannelDiscussionOutbox) + case updateReadChannelInbox(Cons_updateReadChannelInbox) + case updateReadChannelOutbox(Cons_updateReadChannelOutbox) + case updateReadFeaturedEmojiStickers + case updateReadFeaturedStickers + case updateReadHistoryInbox(Cons_updateReadHistoryInbox) + case updateReadHistoryOutbox(Cons_updateReadHistoryOutbox) + case updateReadMessagesContents(Cons_updateReadMessagesContents) + case updateReadMonoForumInbox(Cons_updateReadMonoForumInbox) + case updateReadMonoForumOutbox(Cons_updateReadMonoForumOutbox) + case updateReadStories(Cons_updateReadStories) + case updateRecentEmojiStatuses + case updateRecentReactions + case updateRecentStickers + case updateSavedDialogPinned(Cons_updateSavedDialogPinned) + case updateSavedGifs + case updateSavedReactionTags + case updateSavedRingtones + case updateSentPhoneCode(Cons_updateSentPhoneCode) + case updateSentStoryReaction(Cons_updateSentStoryReaction) + case updateServiceNotification(Cons_updateServiceNotification) + case updateSmsJob(Cons_updateSmsJob) + case updateStarGiftAuctionState(Cons_updateStarGiftAuctionState) + case updateStarGiftAuctionUserState(Cons_updateStarGiftAuctionUserState) + case updateStarGiftCraftFail + case updateStarsBalance(Cons_updateStarsBalance) + case updateStarsRevenueStatus(Cons_updateStarsRevenueStatus) + case updateStickerSets(Cons_updateStickerSets) + case updateStickerSetsOrder(Cons_updateStickerSetsOrder) + case updateStoriesStealthMode(Cons_updateStoriesStealthMode) + case updateStory(Cons_updateStory) + case updateStoryID(Cons_updateStoryID) + case updateTheme(Cons_updateTheme) + case updateTranscribedAudio(Cons_updateTranscribedAudio) + case updateUser(Cons_updateUser) + case updateUserEmojiStatus(Cons_updateUserEmojiStatus) + case updateUserName(Cons_updateUserName) + case updateUserPhone(Cons_updateUserPhone) + case updateUserStatus(Cons_updateUserStatus) + case updateUserTyping(Cons_updateUserTyping) + case updateWebPage(Cons_updateWebPage) + case updateWebViewResultSent(Cons_updateWebViewResultSent) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .updateAttachMenuBots: + if boxed { + buffer.appendInt32(397910539) + } + break + case .updateAutoSaveSettings: + if boxed { + buffer.appendInt32(-335171433) + } + break + case .updateBotBusinessConnect(let _data): + if boxed { + buffer.appendInt32(-1964652166) + } + _data.connection.serialize(buffer, true) + serializeInt32(_data.qts, buffer: buffer, boxed: false) + break + case .updateBotCallbackQuery(let _data): + if boxed { + buffer.appendInt32(-1177566067) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.queryId, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + serializeInt64(_data.chatInstance, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeBytes(_data.data!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.gameShortName!, buffer: buffer, boxed: false) + } + break + case .updateBotChatBoost(let _data): + if boxed { + buffer.appendInt32(-1873947492) + } + _data.peer.serialize(buffer, true) + _data.boost.serialize(buffer, true) + serializeInt32(_data.qts, buffer: buffer, boxed: false) + break + case .updateBotChatInviteRequester(let _data): + if boxed { + buffer.appendInt32(299870598) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeString(_data.about, buffer: buffer, boxed: false) + _data.invite.serialize(buffer, true) + serializeInt32(_data.qts, buffer: buffer, boxed: false) + break + case .updateBotCommands(let _data): + if boxed { + buffer.appendInt32(1299263278) + } + _data.peer.serialize(buffer, true) + serializeInt64(_data.botId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.commands.count)) + for item in _data.commands { + item.serialize(buffer, true) + } + break + case .updateBotDeleteBusinessMessage(let _data): + if boxed { + buffer.appendInt32(-1607821266) + } + serializeString(_data.connectionId, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + serializeInt32(item, buffer: buffer, boxed: false) + } + serializeInt32(_data.qts, buffer: buffer, boxed: false) + break + case .updateBotEditBusinessMessage(let _data): + if boxed { + buffer.appendInt32(132077692) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.connectionId, buffer: buffer, boxed: false) + _data.message.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.replyToMessage!.serialize(buffer, true) + } + serializeInt32(_data.qts, buffer: buffer, boxed: false) + break + case .updateBotInlineQuery(let _data): + if boxed { + buffer.appendInt32(1232025500) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.queryId, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeString(_data.query, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.geo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.peerType!.serialize(buffer, true) + } + serializeString(_data.offset, buffer: buffer, boxed: false) + break + case .updateBotInlineSend(let _data): + if boxed { + buffer.appendInt32(317794823) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeString(_data.query, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.geo!.serialize(buffer, true) + } + serializeString(_data.id, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.msgId!.serialize(buffer, true) + } + break + case .updateBotMenuButton(let _data): + if boxed { + buffer.appendInt32(347625491) + } + serializeInt64(_data.botId, buffer: buffer, boxed: false) + _data.button.serialize(buffer, true) + break + case .updateBotMessageReaction(let _data): + if boxed { + buffer.appendInt32(-1407069234) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + _data.actor.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.oldReactions.count)) + for item in _data.oldReactions { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.newReactions.count)) + for item in _data.newReactions { + item.serialize(buffer, true) + } + serializeInt32(_data.qts, buffer: buffer, boxed: false) + break + case .updateBotMessageReactions(let _data): + if boxed { + buffer.appendInt32(164329305) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.reactions.count)) + for item in _data.reactions { + item.serialize(buffer, true) + } + serializeInt32(_data.qts, buffer: buffer, boxed: false) + break + case .updateBotNewBusinessMessage(let _data): + if boxed { + buffer.appendInt32(-1646578564) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.connectionId, buffer: buffer, boxed: false) + _data.message.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.replyToMessage!.serialize(buffer, true) + } + serializeInt32(_data.qts, buffer: buffer, boxed: false) + break + case .updateBotPrecheckoutQuery(let _data): + if boxed { + buffer.appendInt32(-1934976362) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.queryId, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeBytes(_data.payload, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.info!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.shippingOptionId!, buffer: buffer, boxed: false) + } + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.totalAmount, buffer: buffer, boxed: false) + break + case .updateBotPurchasedPaidMedia(let _data): + if boxed { + buffer.appendInt32(675009298) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeString(_data.payload, buffer: buffer, boxed: false) + serializeInt32(_data.qts, buffer: buffer, boxed: false) + break + case .updateBotShippingQuery(let _data): + if boxed { + buffer.appendInt32(-1246823043) + } + serializeInt64(_data.queryId, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeBytes(_data.payload, buffer: buffer, boxed: false) + _data.shippingAddress.serialize(buffer, true) + break + case .updateBotStopped(let _data): + if boxed { + buffer.appendInt32(-997782967) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + _data.stopped.serialize(buffer, true) + serializeInt32(_data.qts, buffer: buffer, boxed: false) + break + case .updateBotWebhookJSON(let _data): + if boxed { + buffer.appendInt32(-2095595325) + } + _data.data.serialize(buffer, true) + break + case .updateBotWebhookJSONQuery(let _data): + if boxed { + buffer.appendInt32(-1684914010) + } + serializeInt64(_data.queryId, buffer: buffer, boxed: false) + _data.data.serialize(buffer, true) + serializeInt32(_data.timeout, buffer: buffer, boxed: false) + break + case .updateBusinessBotCallbackQuery(let _data): + if boxed { + buffer.appendInt32(513998247) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.queryId, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeString(_data.connectionId, buffer: buffer, boxed: false) + _data.message.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyToMessage!.serialize(buffer, true) + } + serializeInt64(_data.chatInstance, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeBytes(_data.data!, buffer: buffer, boxed: false) + } + break + case .updateChannel(let _data): + if boxed { + buffer.appendInt32(1666927625) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + break + case .updateChannelAvailableMessages(let _data): + if boxed { + buffer.appendInt32(-1304443240) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + serializeInt32(_data.availableMinId, buffer: buffer, boxed: false) + break + case .updateChannelMessageForwards(let _data): + if boxed { + buffer.appendInt32(-761649164) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.forwards, buffer: buffer, boxed: false) + break + case .updateChannelMessageViews(let _data): + if boxed { + buffer.appendInt32(-232346616) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.views, buffer: buffer, boxed: false) + break + case .updateChannelParticipant(let _data): + if boxed { + buffer.appendInt32(-1738720581) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.actorId, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.prevParticipant!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.newParticipant!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.invite!.serialize(buffer, true) + } + serializeInt32(_data.qts, buffer: buffer, boxed: false) + break + case .updateChannelReadMessagesContents(let _data): + if boxed { + buffer.appendInt32(636691703) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.topMsgId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.savedPeerId!.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + serializeInt32(item, buffer: buffer, boxed: false) + } + break + case .updateChannelTooLong(let _data): + if boxed { + buffer.appendInt32(277713951) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.pts!, buffer: buffer, boxed: false) + } + break + case .updateChannelUserTyping(let _data): + if boxed { + buffer.appendInt32(-1937192669) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.topMsgId!, buffer: buffer, boxed: false) + } + _data.fromId.serialize(buffer, true) + _data.action.serialize(buffer, true) + break + case .updateChannelViewForumAsMessages(let _data): + if boxed { + buffer.appendInt32(129403168) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + _data.enabled.serialize(buffer, true) + break + case .updateChannelWebPage(let _data): + if boxed { + buffer.appendInt32(791390623) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + _data.webpage.serialize(buffer, true) + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + break + case .updateChat(let _data): + if boxed { + buffer.appendInt32(-124097970) + } + serializeInt64(_data.chatId, buffer: buffer, boxed: false) + break + case .updateChatDefaultBannedRights(let _data): + if boxed { + buffer.appendInt32(1421875280) + } + _data.peer.serialize(buffer, true) + _data.defaultBannedRights.serialize(buffer, true) + serializeInt32(_data.version, buffer: buffer, boxed: false) + break + case .updateChatParticipant(let _data): + if boxed { + buffer.appendInt32(-796432838) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.chatId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.actorId, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.prevParticipant!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.newParticipant!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.invite!.serialize(buffer, true) + } + serializeInt32(_data.qts, buffer: buffer, boxed: false) + break + case .updateChatParticipantAdd(let _data): + if boxed { + buffer.appendInt32(1037718609) + } + serializeInt64(_data.chatId, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt64(_data.inviterId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt32(_data.version, buffer: buffer, boxed: false) + break + case .updateChatParticipantAdmin(let _data): + if boxed { + buffer.appendInt32(-674602590) + } + serializeInt64(_data.chatId, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + _data.isAdmin.serialize(buffer, true) + serializeInt32(_data.version, buffer: buffer, boxed: false) + break + case .updateChatParticipantDelete(let _data): + if boxed { + buffer.appendInt32(-483443337) + } + serializeInt64(_data.chatId, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt32(_data.version, buffer: buffer, boxed: false) + break + case .updateChatParticipants(let _data): + if boxed { + buffer.appendInt32(125178264) + } + _data.participants.serialize(buffer, true) + break + case .updateChatUserTyping(let _data): + if boxed { + buffer.appendInt32(-2092401936) + } + serializeInt64(_data.chatId, buffer: buffer, boxed: false) + _data.fromId.serialize(buffer, true) + _data.action.serialize(buffer, true) + break + case .updateConfig: + if boxed { + buffer.appendInt32(-1574314746) + } + break + case .updateContactsReset: + if boxed { + buffer.appendInt32(1887741886) + } + break + case .updateDcOptions(let _data): + if boxed { + buffer.appendInt32(-1906403213) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.dcOptions.count)) + for item in _data.dcOptions { + item.serialize(buffer, true) + } + break + case .updateDeleteChannelMessages(let _data): + if boxed { + buffer.appendInt32(-1020437742) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + serializeInt32(item, buffer: buffer, boxed: false) + } + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + break + case .updateDeleteGroupCallMessages(let _data): + if boxed { + buffer.appendInt32(1048963372) + } + _data.call.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + serializeInt32(item, buffer: buffer, boxed: false) + } + break + case .updateDeleteMessages(let _data): + if boxed { + buffer.appendInt32(-1576161051) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + serializeInt32(item, buffer: buffer, boxed: false) + } + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + break + case .updateDeleteQuickReply(let _data): + if boxed { + buffer.appendInt32(1407644140) + } + serializeInt32(_data.shortcutId, buffer: buffer, boxed: false) + break + case .updateDeleteQuickReplyMessages(let _data): + if boxed { + buffer.appendInt32(1450174413) + } + serializeInt32(_data.shortcutId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + serializeInt32(item, buffer: buffer, boxed: false) + } + break + case .updateDeleteScheduledMessages(let _data): + if boxed { + buffer.appendInt32(-223929981) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + serializeInt32(item, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.sentMessages!.count)) + for item in _data.sentMessages! { + serializeInt32(item, buffer: buffer, boxed: false) + } + } + break + case .updateDialogFilter(let _data): + if boxed { + buffer.appendInt32(654302845) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.filter!.serialize(buffer, true) + } + break + case .updateDialogFilterOrder(let _data): + if boxed { + buffer.appendInt32(-1512627963) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.order.count)) + for item in _data.order { + serializeInt32(item, buffer: buffer, boxed: false) + } + break + case .updateDialogFilters: + if boxed { + buffer.appendInt32(889491791) + } + break + case .updateDialogPinned(let _data): + if boxed { + buffer.appendInt32(1852826908) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.folderId!, buffer: buffer, boxed: false) + } + _data.peer.serialize(buffer, true) + break + case .updateDialogUnreadMark(let _data): + if boxed { + buffer.appendInt32(-1235684802) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.savedPeerId!.serialize(buffer, true) + } + break + case .updateDraftMessage(let _data): + if boxed { + buffer.appendInt32(-302247650) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.topMsgId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.savedPeerId!.serialize(buffer, true) + } + _data.draft.serialize(buffer, true) + break + case .updateEditChannelMessage(let _data): + if boxed { + buffer.appendInt32(457133559) + } + _data.message.serialize(buffer, true) + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + break + case .updateEditMessage(let _data): + if boxed { + buffer.appendInt32(-469536605) + } + _data.message.serialize(buffer, true) + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + break + case .updateEmojiGameInfo(let _data): + if boxed { + buffer.appendInt32(-73640838) + } + _data.info.serialize(buffer, true) + break + case .updateEncryptedChatTyping(let _data): + if boxed { + buffer.appendInt32(386986326) + } + serializeInt32(_data.chatId, buffer: buffer, boxed: false) + break + case .updateEncryptedMessagesRead(let _data): + if boxed { + buffer.appendInt32(956179895) + } + serializeInt32(_data.chatId, buffer: buffer, boxed: false) + serializeInt32(_data.maxDate, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + case .updateEncryption(let _data): + if boxed { + buffer.appendInt32(-1264392051) + } + _data.chat.serialize(buffer, true) + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + case .updateFavedStickers: + if boxed { + buffer.appendInt32(-451831443) + } + break + case .updateFolderPeers(let _data): + if boxed { + buffer.appendInt32(422972864) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.folderPeers.count)) + for item in _data.folderPeers { + item.serialize(buffer, true) + } + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + break + case .updateGeoLiveViewed(let _data): + if boxed { + buffer.appendInt32(-2027964103) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + break + case .updateGroupCall(let _data): + if boxed { + buffer.appendInt32(-1658710304) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.peer!.serialize(buffer, true) + } + _data.call.serialize(buffer, true) + break + case .updateGroupCallChainBlocks(let _data): + if boxed { + buffer.appendInt32(-1535694705) + } + _data.call.serialize(buffer, true) + serializeInt32(_data.subChainId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.blocks.count)) + for item in _data.blocks { + serializeBytes(item, buffer: buffer, boxed: false) + } + serializeInt32(_data.nextOffset, buffer: buffer, boxed: false) + break + case .updateGroupCallConnection(let _data): + if boxed { + buffer.appendInt32(192428418) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.params.serialize(buffer, true) + break + case .updateGroupCallEncryptedMessage(let _data): + if boxed { + buffer.appendInt32(-917002394) + } + _data.call.serialize(buffer, true) + _data.fromId.serialize(buffer, true) + serializeBytes(_data.encryptedMessage, buffer: buffer, boxed: false) + break + case .updateGroupCallMessage(let _data): + if boxed { + buffer.appendInt32(-667783411) + } + _data.call.serialize(buffer, true) + _data.message.serialize(buffer, true) + break + case .updateGroupCallParticipants(let _data): + if boxed { + buffer.appendInt32(-219423922) + } + _data.call.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.participants.count)) + for item in _data.participants { + item.serialize(buffer, true) + } + serializeInt32(_data.version, buffer: buffer, boxed: false) + break + case .updateInlineBotCallbackQuery(let _data): + if boxed { + buffer.appendInt32(1763610706) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.queryId, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + _data.msgId.serialize(buffer, true) + serializeInt64(_data.chatInstance, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeBytes(_data.data!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.gameShortName!, buffer: buffer, boxed: false) + } + break + case .updateLangPack(let _data): + if boxed { + buffer.appendInt32(1442983757) + } + _data.difference.serialize(buffer, true) + break + case .updateLangPackTooLong(let _data): + if boxed { + buffer.appendInt32(1180041828) + } + serializeString(_data.langCode, buffer: buffer, boxed: false) + break + case .updateLoginToken: + if boxed { + buffer.appendInt32(1448076945) + } + break + case .updateMessageExtendedMedia(let _data): + if boxed { + buffer.appendInt32(-710666460) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.extendedMedia.count)) + for item in _data.extendedMedia { + item.serialize(buffer, true) + } + break + case .updateMessageID(let _data): + if boxed { + buffer.appendInt32(1318109142) + } + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.randomId, buffer: buffer, boxed: false) + break + case .updateMessagePoll(let _data): + if boxed { + buffer.appendInt32(-1398708869) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.pollId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.poll!.serialize(buffer, true) + } + _data.results.serialize(buffer, true) + break + case .updateMessagePollVote(let _data): + if boxed { + buffer.appendInt32(619974263) + } + serializeInt64(_data.pollId, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.options.count)) + for item in _data.options { + serializeBytes(item, buffer: buffer, boxed: false) + } + serializeInt32(_data.qts, buffer: buffer, boxed: false) + break + case .updateMessageReactions(let _data): + if boxed { + buffer.appendInt32(506035194) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.topMsgId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.savedPeerId!.serialize(buffer, true) + } + _data.reactions.serialize(buffer, true) + break + case .updateMonoForumNoPaidException(let _data): + if boxed { + buffer.appendInt32(-1618924792) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + _data.savedPeerId.serialize(buffer, true) + break + case .updateMoveStickerSetToTop(let _data): + if boxed { + buffer.appendInt32(-2030252155) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.stickerset, buffer: buffer, boxed: false) + break + case .updateNewAuthorization(let _data): + if boxed { + buffer.appendInt32(-1991136273) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.hash, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.date!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.device!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.location!, buffer: buffer, boxed: false) + } + break + case .updateNewChannelMessage(let _data): + if boxed { + buffer.appendInt32(1656358105) + } + _data.message.serialize(buffer, true) + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + break + case .updateNewEncryptedMessage(let _data): + if boxed { + buffer.appendInt32(314359194) + } + _data.message.serialize(buffer, true) + serializeInt32(_data.qts, buffer: buffer, boxed: false) + break + case .updateNewMessage(let _data): + if boxed { + buffer.appendInt32(522914557) + } + _data.message.serialize(buffer, true) + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + break + case .updateNewQuickReply(let _data): + if boxed { + buffer.appendInt32(-180508905) + } + _data.quickReply.serialize(buffer, true) + break + case .updateNewScheduledMessage(let _data): + if boxed { + buffer.appendInt32(967122427) + } + _data.message.serialize(buffer, true) + break + case .updateNewStickerSet(let _data): + if boxed { + buffer.appendInt32(1753886890) + } + _data.stickerset.serialize(buffer, true) + break + case .updateNewStoryReaction(let _data): + if boxed { + buffer.appendInt32(405070859) + } + serializeInt32(_data.storyId, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + _data.reaction.serialize(buffer, true) + break + case .updateNotifySettings(let _data): + if boxed { + buffer.appendInt32(-1094555409) + } + _data.peer.serialize(buffer, true) + _data.notifySettings.serialize(buffer, true) + break + case .updatePaidReactionPrivacy(let _data): + if boxed { + buffer.appendInt32(-1955438642) + } + _data.`private`.serialize(buffer, true) + break + case .updatePeerBlocked(let _data): + if boxed { + buffer.appendInt32(-337610926) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peerId.serialize(buffer, true) + break + case .updatePeerHistoryTTL(let _data): + if boxed { + buffer.appendInt32(-1147422299) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.ttlPeriod!, buffer: buffer, boxed: false) + } + break + case .updatePeerLocated(let _data): + if boxed { + buffer.appendInt32(-1263546448) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.peers.count)) + for item in _data.peers { + item.serialize(buffer, true) + } + break + case .updatePeerSettings(let _data): + if boxed { + buffer.appendInt32(1786671974) + } + _data.peer.serialize(buffer, true) + _data.settings.serialize(buffer, true) + break + case .updatePeerWallpaper(let _data): + if boxed { + buffer.appendInt32(-1371598819) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.wallpaper!.serialize(buffer, true) + } + break + case .updatePendingJoinRequests(let _data): + if boxed { + buffer.appendInt32(1885586395) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.requestsPending, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.recentRequesters.count)) + for item in _data.recentRequesters { + serializeInt64(item, buffer: buffer, boxed: false) + } + break + case .updatePhoneCall(let _data): + if boxed { + buffer.appendInt32(-1425052898) + } + _data.phoneCall.serialize(buffer, true) + break + case .updatePhoneCallSignalingData(let _data): + if boxed { + buffer.appendInt32(643940105) + } + serializeInt64(_data.phoneCallId, buffer: buffer, boxed: false) + serializeBytes(_data.data, buffer: buffer, boxed: false) + break + case .updatePinnedChannelMessages(let _data): + if boxed { + buffer.appendInt32(1538885128) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + serializeInt32(item, buffer: buffer, boxed: false) + } + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + break + case .updatePinnedDialogs(let _data): + if boxed { + buffer.appendInt32(-99664734) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.folderId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.order!.count)) + for item in _data.order! { + item.serialize(buffer, true) + } + } + break + case .updatePinnedForumTopic(let _data): + if boxed { + buffer.appendInt32(1748708434) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeInt32(_data.topicId, buffer: buffer, boxed: false) + break + case .updatePinnedForumTopics(let _data): + if boxed { + buffer.appendInt32(-554613808) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.order!.count)) + for item in _data.order! { + serializeInt32(item, buffer: buffer, boxed: false) + } + } + break + case .updatePinnedMessages(let _data): + if boxed { + buffer.appendInt32(-309990731) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + serializeInt32(item, buffer: buffer, boxed: false) + } + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + break + case .updatePinnedSavedDialogs(let _data): + if boxed { + buffer.appendInt32(1751942566) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.order!.count)) + for item in _data.order! { + item.serialize(buffer, true) + } + } + break + case .updatePrivacy(let _data): + if boxed { + buffer.appendInt32(-298113238) + } + _data.key.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.rules.count)) + for item in _data.rules { + item.serialize(buffer, true) + } + break + case .updatePtsChanged: + if boxed { + buffer.appendInt32(861169551) + } + break + case .updateQuickReplies(let _data): + if boxed { + buffer.appendInt32(-112784718) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.quickReplies.count)) + for item in _data.quickReplies { + item.serialize(buffer, true) + } + break + case .updateQuickReplyMessage(let _data): + if boxed { + buffer.appendInt32(1040518415) + } + _data.message.serialize(buffer, true) + break + case .updateReadChannelDiscussionInbox(let _data): + if boxed { + buffer.appendInt32(-693004986) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + serializeInt32(_data.topMsgId, buffer: buffer, boxed: false) + serializeInt32(_data.readMaxId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.broadcastId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.broadcastPost!, buffer: buffer, boxed: false) + } + break + case .updateReadChannelDiscussionOutbox(let _data): + if boxed { + buffer.appendInt32(1767677564) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + serializeInt32(_data.topMsgId, buffer: buffer, boxed: false) + serializeInt32(_data.readMaxId, buffer: buffer, boxed: false) + break + case .updateReadChannelInbox(let _data): + if boxed { + buffer.appendInt32(-1842450928) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.folderId!, buffer: buffer, boxed: false) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + serializeInt32(_data.maxId, buffer: buffer, boxed: false) + serializeInt32(_data.stillUnreadCount, buffer: buffer, boxed: false) + serializeInt32(_data.pts, buffer: buffer, boxed: false) + break + case .updateReadChannelOutbox(let _data): + if boxed { + buffer.appendInt32(-1218471511) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + serializeInt32(_data.maxId, buffer: buffer, boxed: false) + break + case .updateReadFeaturedEmojiStickers: + if boxed { + buffer.appendInt32(-78886548) + } + break + case .updateReadFeaturedStickers: + if boxed { + buffer.appendInt32(1461528386) + } + break + case .updateReadHistoryInbox(let _data): + if boxed { + buffer.appendInt32(-1635468135) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.folderId!, buffer: buffer, boxed: false) + } + _data.peer.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.topMsgId!, buffer: buffer, boxed: false) + } + serializeInt32(_data.maxId, buffer: buffer, boxed: false) + serializeInt32(_data.stillUnreadCount, buffer: buffer, boxed: false) + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + break + case .updateReadHistoryOutbox(let _data): + if boxed { + buffer.appendInt32(791617983) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.maxId, buffer: buffer, boxed: false) + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + break + case .updateReadMessagesContents(let _data): + if boxed { + buffer.appendInt32(-131960447) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + serializeInt32(item, buffer: buffer, boxed: false) + } + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.date!, buffer: buffer, boxed: false) + } + break + case .updateReadMonoForumInbox(let _data): + if boxed { + buffer.appendInt32(2008081266) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + _data.savedPeerId.serialize(buffer, true) + serializeInt32(_data.readMaxId, buffer: buffer, boxed: false) + break + case .updateReadMonoForumOutbox(let _data): + if boxed { + buffer.appendInt32(-1532521610) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + _data.savedPeerId.serialize(buffer, true) + serializeInt32(_data.readMaxId, buffer: buffer, boxed: false) + break + case .updateReadStories(let _data): + if boxed { + buffer.appendInt32(-145845461) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.maxId, buffer: buffer, boxed: false) + break + case .updateRecentEmojiStatuses: + if boxed { + buffer.appendInt32(821314523) + } + break + case .updateRecentReactions: + if boxed { + buffer.appendInt32(1870160884) + } + break + case .updateRecentStickers: + if boxed { + buffer.appendInt32(-1706939360) + } + break + case .updateSavedDialogPinned(let _data): + if boxed { + buffer.appendInt32(-1364222348) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + break + case .updateSavedGifs: + if boxed { + buffer.appendInt32(-1821035490) + } + break + case .updateSavedReactionTags: + if boxed { + buffer.appendInt32(969307186) + } + break + case .updateSavedRingtones: + if boxed { + buffer.appendInt32(1960361625) + } + break + case .updateSentPhoneCode(let _data): + if boxed { + buffer.appendInt32(1347068303) + } + _data.sentCode.serialize(buffer, true) + break + case .updateSentStoryReaction(let _data): + if boxed { + buffer.appendInt32(2103604867) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.storyId, buffer: buffer, boxed: false) + _data.reaction.serialize(buffer, true) + break + case .updateServiceNotification(let _data): + if boxed { + buffer.appendInt32(-337352679) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.inboxDate!, buffer: buffer, boxed: false) + } + serializeString(_data.type, buffer: buffer, boxed: false) + serializeString(_data.message, buffer: buffer, boxed: false) + _data.media.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities.count)) + for item in _data.entities { + item.serialize(buffer, true) + } + break + case .updateSmsJob(let _data): + if boxed { + buffer.appendInt32(-245208620) + } + serializeString(_data.jobId, buffer: buffer, boxed: false) + break + case .updateStarGiftAuctionState(let _data): + if boxed { + buffer.appendInt32(1222788802) + } + serializeInt64(_data.giftId, buffer: buffer, boxed: false) + _data.state.serialize(buffer, true) + break + case .updateStarGiftAuctionUserState(let _data): + if boxed { + buffer.appendInt32(-598150370) + } + serializeInt64(_data.giftId, buffer: buffer, boxed: false) + _data.userState.serialize(buffer, true) + break + case .updateStarGiftCraftFail: + if boxed { + buffer.appendInt32(-1408818108) + } + break + case .updateStarsBalance(let _data): + if boxed { + buffer.appendInt32(1317053305) + } + _data.balance.serialize(buffer, true) + break + case .updateStarsRevenueStatus(let _data): + if boxed { + buffer.appendInt32(-1518030823) + } + _data.peer.serialize(buffer, true) + _data.status.serialize(buffer, true) + break + case .updateStickerSets(let _data): + if boxed { + buffer.appendInt32(834816008) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + case .updateStickerSetsOrder(let _data): + if boxed { + buffer.appendInt32(196268545) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.order.count)) + for item in _data.order { + serializeInt64(item, buffer: buffer, boxed: false) + } + break + case .updateStoriesStealthMode(let _data): + if boxed { + buffer.appendInt32(738741697) + } + _data.stealthMode.serialize(buffer, true) + break + case .updateStory(let _data): + if boxed { + buffer.appendInt32(1974712216) + } + _data.peer.serialize(buffer, true) + _data.story.serialize(buffer, true) + break + case .updateStoryID(let _data): + if boxed { + buffer.appendInt32(468923833) + } + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.randomId, buffer: buffer, boxed: false) + break + case .updateTheme(let _data): + if boxed { + buffer.appendInt32(-2112423005) + } + _data.theme.serialize(buffer, true) + break + case .updateTranscribedAudio(let _data): + if boxed { + buffer.appendInt32(8703322) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + serializeInt64(_data.transcriptionId, buffer: buffer, boxed: false) + serializeString(_data.text, buffer: buffer, boxed: false) + break + case .updateUser(let _data): + if boxed { + buffer.appendInt32(542282808) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + break + case .updateUserEmojiStatus(let _data): + if boxed { + buffer.appendInt32(674706841) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + _data.emojiStatus.serialize(buffer, true) + break + case .updateUserName(let _data): + if boxed { + buffer.appendInt32(-1484486364) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeString(_data.firstName, buffer: buffer, boxed: false) + serializeString(_data.lastName, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.usernames.count)) + for item in _data.usernames { + item.serialize(buffer, true) + } + break + case .updateUserPhone(let _data): + if boxed { + buffer.appendInt32(88680979) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeString(_data.phone, buffer: buffer, boxed: false) + break + case .updateUserStatus(let _data): + if boxed { + buffer.appendInt32(-440534818) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + _data.status.serialize(buffer, true) + break + case .updateUserTyping(let _data): + if boxed { + buffer.appendInt32(706199388) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.topMsgId!, buffer: buffer, boxed: false) + } + _data.action.serialize(buffer, true) + break + case .updateWebPage(let _data): + if boxed { + buffer.appendInt32(2139689491) + } + _data.webpage.serialize(buffer, true) + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + break + case .updateWebViewResultSent(let _data): + if boxed { + buffer.appendInt32(361936797) + } + serializeInt64(_data.queryId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .updateAttachMenuBots: + return ("updateAttachMenuBots", []) + case .updateAutoSaveSettings: + return ("updateAutoSaveSettings", []) + case .updateBotBusinessConnect(let _data): + return ("updateBotBusinessConnect", [("connection", _data.connection as Any), ("qts", _data.qts as Any)]) + case .updateBotCallbackQuery(let _data): + return ("updateBotCallbackQuery", [("flags", _data.flags as Any), ("queryId", _data.queryId as Any), ("userId", _data.userId as Any), ("peer", _data.peer as Any), ("msgId", _data.msgId as Any), ("chatInstance", _data.chatInstance as Any), ("data", _data.data as Any), ("gameShortName", _data.gameShortName as Any)]) + case .updateBotChatBoost(let _data): + return ("updateBotChatBoost", [("peer", _data.peer as Any), ("boost", _data.boost as Any), ("qts", _data.qts as Any)]) + case .updateBotChatInviteRequester(let _data): + return ("updateBotChatInviteRequester", [("peer", _data.peer as Any), ("date", _data.date as Any), ("userId", _data.userId as Any), ("about", _data.about as Any), ("invite", _data.invite as Any), ("qts", _data.qts as Any)]) + case .updateBotCommands(let _data): + return ("updateBotCommands", [("peer", _data.peer as Any), ("botId", _data.botId as Any), ("commands", _data.commands as Any)]) + case .updateBotDeleteBusinessMessage(let _data): + return ("updateBotDeleteBusinessMessage", [("connectionId", _data.connectionId as Any), ("peer", _data.peer as Any), ("messages", _data.messages as Any), ("qts", _data.qts as Any)]) + case .updateBotEditBusinessMessage(let _data): + return ("updateBotEditBusinessMessage", [("flags", _data.flags as Any), ("connectionId", _data.connectionId as Any), ("message", _data.message as Any), ("replyToMessage", _data.replyToMessage as Any), ("qts", _data.qts as Any)]) + case .updateBotInlineQuery(let _data): + return ("updateBotInlineQuery", [("flags", _data.flags as Any), ("queryId", _data.queryId as Any), ("userId", _data.userId as Any), ("query", _data.query as Any), ("geo", _data.geo as Any), ("peerType", _data.peerType as Any), ("offset", _data.offset as Any)]) + case .updateBotInlineSend(let _data): + return ("updateBotInlineSend", [("flags", _data.flags as Any), ("userId", _data.userId as Any), ("query", _data.query as Any), ("geo", _data.geo as Any), ("id", _data.id as Any), ("msgId", _data.msgId as Any)]) + case .updateBotMenuButton(let _data): + return ("updateBotMenuButton", [("botId", _data.botId as Any), ("button", _data.button as Any)]) + case .updateBotMessageReaction(let _data): + return ("updateBotMessageReaction", [("peer", _data.peer as Any), ("msgId", _data.msgId as Any), ("date", _data.date as Any), ("actor", _data.actor as Any), ("oldReactions", _data.oldReactions as Any), ("newReactions", _data.newReactions as Any), ("qts", _data.qts as Any)]) + case .updateBotMessageReactions(let _data): + return ("updateBotMessageReactions", [("peer", _data.peer as Any), ("msgId", _data.msgId as Any), ("date", _data.date as Any), ("reactions", _data.reactions as Any), ("qts", _data.qts as Any)]) + case .updateBotNewBusinessMessage(let _data): + return ("updateBotNewBusinessMessage", [("flags", _data.flags as Any), ("connectionId", _data.connectionId as Any), ("message", _data.message as Any), ("replyToMessage", _data.replyToMessage as Any), ("qts", _data.qts as Any)]) + case .updateBotPrecheckoutQuery(let _data): + return ("updateBotPrecheckoutQuery", [("flags", _data.flags as Any), ("queryId", _data.queryId as Any), ("userId", _data.userId as Any), ("payload", _data.payload as Any), ("info", _data.info as Any), ("shippingOptionId", _data.shippingOptionId as Any), ("currency", _data.currency as Any), ("totalAmount", _data.totalAmount as Any)]) + case .updateBotPurchasedPaidMedia(let _data): + return ("updateBotPurchasedPaidMedia", [("userId", _data.userId as Any), ("payload", _data.payload as Any), ("qts", _data.qts as Any)]) + case .updateBotShippingQuery(let _data): + return ("updateBotShippingQuery", [("queryId", _data.queryId as Any), ("userId", _data.userId as Any), ("payload", _data.payload as Any), ("shippingAddress", _data.shippingAddress as Any)]) + case .updateBotStopped(let _data): + return ("updateBotStopped", [("userId", _data.userId as Any), ("date", _data.date as Any), ("stopped", _data.stopped as Any), ("qts", _data.qts as Any)]) + case .updateBotWebhookJSON(let _data): + return ("updateBotWebhookJSON", [("data", _data.data as Any)]) + case .updateBotWebhookJSONQuery(let _data): + return ("updateBotWebhookJSONQuery", [("queryId", _data.queryId as Any), ("data", _data.data as Any), ("timeout", _data.timeout as Any)]) + case .updateBusinessBotCallbackQuery(let _data): + return ("updateBusinessBotCallbackQuery", [("flags", _data.flags as Any), ("queryId", _data.queryId as Any), ("userId", _data.userId as Any), ("connectionId", _data.connectionId as Any), ("message", _data.message as Any), ("replyToMessage", _data.replyToMessage as Any), ("chatInstance", _data.chatInstance as Any), ("data", _data.data as Any)]) + case .updateChannel(let _data): + return ("updateChannel", [("channelId", _data.channelId as Any)]) + case .updateChannelAvailableMessages(let _data): + return ("updateChannelAvailableMessages", [("channelId", _data.channelId as Any), ("availableMinId", _data.availableMinId as Any)]) + case .updateChannelMessageForwards(let _data): + return ("updateChannelMessageForwards", [("channelId", _data.channelId as Any), ("id", _data.id as Any), ("forwards", _data.forwards as Any)]) + case .updateChannelMessageViews(let _data): + return ("updateChannelMessageViews", [("channelId", _data.channelId as Any), ("id", _data.id as Any), ("views", _data.views as Any)]) + case .updateChannelParticipant(let _data): + return ("updateChannelParticipant", [("flags", _data.flags as Any), ("channelId", _data.channelId as Any), ("date", _data.date as Any), ("actorId", _data.actorId as Any), ("userId", _data.userId as Any), ("prevParticipant", _data.prevParticipant as Any), ("newParticipant", _data.newParticipant as Any), ("invite", _data.invite as Any), ("qts", _data.qts as Any)]) + case .updateChannelReadMessagesContents(let _data): + return ("updateChannelReadMessagesContents", [("flags", _data.flags as Any), ("channelId", _data.channelId as Any), ("topMsgId", _data.topMsgId as Any), ("savedPeerId", _data.savedPeerId as Any), ("messages", _data.messages as Any)]) + case .updateChannelTooLong(let _data): + return ("updateChannelTooLong", [("flags", _data.flags as Any), ("channelId", _data.channelId as Any), ("pts", _data.pts as Any)]) + case .updateChannelUserTyping(let _data): + return ("updateChannelUserTyping", [("flags", _data.flags as Any), ("channelId", _data.channelId as Any), ("topMsgId", _data.topMsgId as Any), ("fromId", _data.fromId as Any), ("action", _data.action as Any)]) + case .updateChannelViewForumAsMessages(let _data): + return ("updateChannelViewForumAsMessages", [("channelId", _data.channelId as Any), ("enabled", _data.enabled as Any)]) + case .updateChannelWebPage(let _data): + return ("updateChannelWebPage", [("channelId", _data.channelId as Any), ("webpage", _data.webpage as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any)]) + case .updateChat(let _data): + return ("updateChat", [("chatId", _data.chatId as Any)]) + case .updateChatDefaultBannedRights(let _data): + return ("updateChatDefaultBannedRights", [("peer", _data.peer as Any), ("defaultBannedRights", _data.defaultBannedRights as Any), ("version", _data.version as Any)]) + case .updateChatParticipant(let _data): + return ("updateChatParticipant", [("flags", _data.flags as Any), ("chatId", _data.chatId as Any), ("date", _data.date as Any), ("actorId", _data.actorId as Any), ("userId", _data.userId as Any), ("prevParticipant", _data.prevParticipant as Any), ("newParticipant", _data.newParticipant as Any), ("invite", _data.invite as Any), ("qts", _data.qts as Any)]) + case .updateChatParticipantAdd(let _data): + return ("updateChatParticipantAdd", [("chatId", _data.chatId as Any), ("userId", _data.userId as Any), ("inviterId", _data.inviterId as Any), ("date", _data.date as Any), ("version", _data.version as Any)]) + case .updateChatParticipantAdmin(let _data): + return ("updateChatParticipantAdmin", [("chatId", _data.chatId as Any), ("userId", _data.userId as Any), ("isAdmin", _data.isAdmin as Any), ("version", _data.version as Any)]) + case .updateChatParticipantDelete(let _data): + return ("updateChatParticipantDelete", [("chatId", _data.chatId as Any), ("userId", _data.userId as Any), ("version", _data.version as Any)]) + case .updateChatParticipants(let _data): + return ("updateChatParticipants", [("participants", _data.participants as Any)]) + case .updateChatUserTyping(let _data): + return ("updateChatUserTyping", [("chatId", _data.chatId as Any), ("fromId", _data.fromId as Any), ("action", _data.action as Any)]) + case .updateConfig: + return ("updateConfig", []) + case .updateContactsReset: + return ("updateContactsReset", []) + case .updateDcOptions(let _data): + return ("updateDcOptions", [("dcOptions", _data.dcOptions as Any)]) + case .updateDeleteChannelMessages(let _data): + return ("updateDeleteChannelMessages", [("channelId", _data.channelId as Any), ("messages", _data.messages as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any)]) + case .updateDeleteGroupCallMessages(let _data): + return ("updateDeleteGroupCallMessages", [("call", _data.call as Any), ("messages", _data.messages as Any)]) + case .updateDeleteMessages(let _data): + return ("updateDeleteMessages", [("messages", _data.messages as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any)]) + case .updateDeleteQuickReply(let _data): + return ("updateDeleteQuickReply", [("shortcutId", _data.shortcutId as Any)]) + case .updateDeleteQuickReplyMessages(let _data): + return ("updateDeleteQuickReplyMessages", [("shortcutId", _data.shortcutId as Any), ("messages", _data.messages as Any)]) + case .updateDeleteScheduledMessages(let _data): + return ("updateDeleteScheduledMessages", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("messages", _data.messages as Any), ("sentMessages", _data.sentMessages as Any)]) + case .updateDialogFilter(let _data): + return ("updateDialogFilter", [("flags", _data.flags as Any), ("id", _data.id as Any), ("filter", _data.filter as Any)]) + case .updateDialogFilterOrder(let _data): + return ("updateDialogFilterOrder", [("order", _data.order as Any)]) + case .updateDialogFilters: + return ("updateDialogFilters", []) + case .updateDialogPinned(let _data): + return ("updateDialogPinned", [("flags", _data.flags as Any), ("folderId", _data.folderId as Any), ("peer", _data.peer as Any)]) + case .updateDialogUnreadMark(let _data): + return ("updateDialogUnreadMark", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("savedPeerId", _data.savedPeerId as Any)]) + case .updateDraftMessage(let _data): + return ("updateDraftMessage", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("topMsgId", _data.topMsgId as Any), ("savedPeerId", _data.savedPeerId as Any), ("draft", _data.draft as Any)]) + case .updateEditChannelMessage(let _data): + return ("updateEditChannelMessage", [("message", _data.message as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any)]) + case .updateEditMessage(let _data): + return ("updateEditMessage", [("message", _data.message as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any)]) + case .updateEmojiGameInfo(let _data): + return ("updateEmojiGameInfo", [("info", _data.info as Any)]) + case .updateEncryptedChatTyping(let _data): + return ("updateEncryptedChatTyping", [("chatId", _data.chatId as Any)]) + case .updateEncryptedMessagesRead(let _data): + return ("updateEncryptedMessagesRead", [("chatId", _data.chatId as Any), ("maxDate", _data.maxDate as Any), ("date", _data.date as Any)]) + case .updateEncryption(let _data): + return ("updateEncryption", [("chat", _data.chat as Any), ("date", _data.date as Any)]) + case .updateFavedStickers: + return ("updateFavedStickers", []) + case .updateFolderPeers(let _data): + return ("updateFolderPeers", [("folderPeers", _data.folderPeers as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any)]) + case .updateGeoLiveViewed(let _data): + return ("updateGeoLiveViewed", [("peer", _data.peer as Any), ("msgId", _data.msgId as Any)]) + case .updateGroupCall(let _data): + return ("updateGroupCall", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("call", _data.call as Any)]) + case .updateGroupCallChainBlocks(let _data): + return ("updateGroupCallChainBlocks", [("call", _data.call as Any), ("subChainId", _data.subChainId as Any), ("blocks", _data.blocks as Any), ("nextOffset", _data.nextOffset as Any)]) + case .updateGroupCallConnection(let _data): + return ("updateGroupCallConnection", [("flags", _data.flags as Any), ("params", _data.params as Any)]) + case .updateGroupCallEncryptedMessage(let _data): + return ("updateGroupCallEncryptedMessage", [("call", _data.call as Any), ("fromId", _data.fromId as Any), ("encryptedMessage", _data.encryptedMessage as Any)]) + case .updateGroupCallMessage(let _data): + return ("updateGroupCallMessage", [("call", _data.call as Any), ("message", _data.message as Any)]) + case .updateGroupCallParticipants(let _data): + return ("updateGroupCallParticipants", [("call", _data.call as Any), ("participants", _data.participants as Any), ("version", _data.version as Any)]) + case .updateInlineBotCallbackQuery(let _data): + return ("updateInlineBotCallbackQuery", [("flags", _data.flags as Any), ("queryId", _data.queryId as Any), ("userId", _data.userId as Any), ("msgId", _data.msgId as Any), ("chatInstance", _data.chatInstance as Any), ("data", _data.data as Any), ("gameShortName", _data.gameShortName as Any)]) + case .updateLangPack(let _data): + return ("updateLangPack", [("difference", _data.difference as Any)]) + case .updateLangPackTooLong(let _data): + return ("updateLangPackTooLong", [("langCode", _data.langCode as Any)]) + case .updateLoginToken: + return ("updateLoginToken", []) + case .updateMessageExtendedMedia(let _data): + return ("updateMessageExtendedMedia", [("peer", _data.peer as Any), ("msgId", _data.msgId as Any), ("extendedMedia", _data.extendedMedia as Any)]) + case .updateMessageID(let _data): + return ("updateMessageID", [("id", _data.id as Any), ("randomId", _data.randomId as Any)]) + case .updateMessagePoll(let _data): + return ("updateMessagePoll", [("flags", _data.flags as Any), ("pollId", _data.pollId as Any), ("poll", _data.poll as Any), ("results", _data.results as Any)]) + case .updateMessagePollVote(let _data): + return ("updateMessagePollVote", [("pollId", _data.pollId as Any), ("peer", _data.peer as Any), ("options", _data.options as Any), ("qts", _data.qts as Any)]) + case .updateMessageReactions(let _data): + return ("updateMessageReactions", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("msgId", _data.msgId as Any), ("topMsgId", _data.topMsgId as Any), ("savedPeerId", _data.savedPeerId as Any), ("reactions", _data.reactions as Any)]) + case .updateMonoForumNoPaidException(let _data): + return ("updateMonoForumNoPaidException", [("flags", _data.flags as Any), ("channelId", _data.channelId as Any), ("savedPeerId", _data.savedPeerId as Any)]) + case .updateMoveStickerSetToTop(let _data): + return ("updateMoveStickerSetToTop", [("flags", _data.flags as Any), ("stickerset", _data.stickerset as Any)]) + case .updateNewAuthorization(let _data): + return ("updateNewAuthorization", [("flags", _data.flags as Any), ("hash", _data.hash as Any), ("date", _data.date as Any), ("device", _data.device as Any), ("location", _data.location as Any)]) + case .updateNewChannelMessage(let _data): + return ("updateNewChannelMessage", [("message", _data.message as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any)]) + case .updateNewEncryptedMessage(let _data): + return ("updateNewEncryptedMessage", [("message", _data.message as Any), ("qts", _data.qts as Any)]) + case .updateNewMessage(let _data): + return ("updateNewMessage", [("message", _data.message as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any)]) + case .updateNewQuickReply(let _data): + return ("updateNewQuickReply", [("quickReply", _data.quickReply as Any)]) + case .updateNewScheduledMessage(let _data): + return ("updateNewScheduledMessage", [("message", _data.message as Any)]) + case .updateNewStickerSet(let _data): + return ("updateNewStickerSet", [("stickerset", _data.stickerset as Any)]) + case .updateNewStoryReaction(let _data): + return ("updateNewStoryReaction", [("storyId", _data.storyId as Any), ("peer", _data.peer as Any), ("reaction", _data.reaction as Any)]) + case .updateNotifySettings(let _data): + return ("updateNotifySettings", [("peer", _data.peer as Any), ("notifySettings", _data.notifySettings as Any)]) + case .updatePaidReactionPrivacy(let _data): + return ("updatePaidReactionPrivacy", [("`private`", _data.`private` as Any)]) + case .updatePeerBlocked(let _data): + return ("updatePeerBlocked", [("flags", _data.flags as Any), ("peerId", _data.peerId as Any)]) + case .updatePeerHistoryTTL(let _data): + return ("updatePeerHistoryTTL", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("ttlPeriod", _data.ttlPeriod as Any)]) + case .updatePeerLocated(let _data): + return ("updatePeerLocated", [("peers", _data.peers as Any)]) + case .updatePeerSettings(let _data): + return ("updatePeerSettings", [("peer", _data.peer as Any), ("settings", _data.settings as Any)]) + case .updatePeerWallpaper(let _data): + return ("updatePeerWallpaper", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("wallpaper", _data.wallpaper as Any)]) + case .updatePendingJoinRequests(let _data): + return ("updatePendingJoinRequests", [("peer", _data.peer as Any), ("requestsPending", _data.requestsPending as Any), ("recentRequesters", _data.recentRequesters as Any)]) + case .updatePhoneCall(let _data): + return ("updatePhoneCall", [("phoneCall", _data.phoneCall as Any)]) + case .updatePhoneCallSignalingData(let _data): + return ("updatePhoneCallSignalingData", [("phoneCallId", _data.phoneCallId as Any), ("data", _data.data as Any)]) + case .updatePinnedChannelMessages(let _data): + return ("updatePinnedChannelMessages", [("flags", _data.flags as Any), ("channelId", _data.channelId as Any), ("messages", _data.messages as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any)]) + case .updatePinnedDialogs(let _data): + return ("updatePinnedDialogs", [("flags", _data.flags as Any), ("folderId", _data.folderId as Any), ("order", _data.order as Any)]) + case .updatePinnedForumTopic(let _data): + return ("updatePinnedForumTopic", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("topicId", _data.topicId as Any)]) + case .updatePinnedForumTopics(let _data): + return ("updatePinnedForumTopics", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("order", _data.order as Any)]) + case .updatePinnedMessages(let _data): + return ("updatePinnedMessages", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("messages", _data.messages as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any)]) + case .updatePinnedSavedDialogs(let _data): + return ("updatePinnedSavedDialogs", [("flags", _data.flags as Any), ("order", _data.order as Any)]) + case .updatePrivacy(let _data): + return ("updatePrivacy", [("key", _data.key as Any), ("rules", _data.rules as Any)]) + case .updatePtsChanged: + return ("updatePtsChanged", []) + case .updateQuickReplies(let _data): + return ("updateQuickReplies", [("quickReplies", _data.quickReplies as Any)]) + case .updateQuickReplyMessage(let _data): + return ("updateQuickReplyMessage", [("message", _data.message as Any)]) + case .updateReadChannelDiscussionInbox(let _data): + return ("updateReadChannelDiscussionInbox", [("flags", _data.flags as Any), ("channelId", _data.channelId as Any), ("topMsgId", _data.topMsgId as Any), ("readMaxId", _data.readMaxId as Any), ("broadcastId", _data.broadcastId as Any), ("broadcastPost", _data.broadcastPost as Any)]) + case .updateReadChannelDiscussionOutbox(let _data): + return ("updateReadChannelDiscussionOutbox", [("channelId", _data.channelId as Any), ("topMsgId", _data.topMsgId as Any), ("readMaxId", _data.readMaxId as Any)]) + case .updateReadChannelInbox(let _data): + return ("updateReadChannelInbox", [("flags", _data.flags as Any), ("folderId", _data.folderId as Any), ("channelId", _data.channelId as Any), ("maxId", _data.maxId as Any), ("stillUnreadCount", _data.stillUnreadCount as Any), ("pts", _data.pts as Any)]) + case .updateReadChannelOutbox(let _data): + return ("updateReadChannelOutbox", [("channelId", _data.channelId as Any), ("maxId", _data.maxId as Any)]) + case .updateReadFeaturedEmojiStickers: + return ("updateReadFeaturedEmojiStickers", []) + case .updateReadFeaturedStickers: + return ("updateReadFeaturedStickers", []) + case .updateReadHistoryInbox(let _data): + return ("updateReadHistoryInbox", [("flags", _data.flags as Any), ("folderId", _data.folderId as Any), ("peer", _data.peer as Any), ("topMsgId", _data.topMsgId as Any), ("maxId", _data.maxId as Any), ("stillUnreadCount", _data.stillUnreadCount as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any)]) + case .updateReadHistoryOutbox(let _data): + return ("updateReadHistoryOutbox", [("peer", _data.peer as Any), ("maxId", _data.maxId as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any)]) + case .updateReadMessagesContents(let _data): + return ("updateReadMessagesContents", [("flags", _data.flags as Any), ("messages", _data.messages as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any), ("date", _data.date as Any)]) + case .updateReadMonoForumInbox(let _data): + return ("updateReadMonoForumInbox", [("channelId", _data.channelId as Any), ("savedPeerId", _data.savedPeerId as Any), ("readMaxId", _data.readMaxId as Any)]) + case .updateReadMonoForumOutbox(let _data): + return ("updateReadMonoForumOutbox", [("channelId", _data.channelId as Any), ("savedPeerId", _data.savedPeerId as Any), ("readMaxId", _data.readMaxId as Any)]) + case .updateReadStories(let _data): + return ("updateReadStories", [("peer", _data.peer as Any), ("maxId", _data.maxId as Any)]) + case .updateRecentEmojiStatuses: + return ("updateRecentEmojiStatuses", []) + case .updateRecentReactions: + return ("updateRecentReactions", []) + case .updateRecentStickers: + return ("updateRecentStickers", []) + case .updateSavedDialogPinned(let _data): + return ("updateSavedDialogPinned", [("flags", _data.flags as Any), ("peer", _data.peer as Any)]) + case .updateSavedGifs: + return ("updateSavedGifs", []) + case .updateSavedReactionTags: + return ("updateSavedReactionTags", []) + case .updateSavedRingtones: + return ("updateSavedRingtones", []) + case .updateSentPhoneCode(let _data): + return ("updateSentPhoneCode", [("sentCode", _data.sentCode as Any)]) + case .updateSentStoryReaction(let _data): + return ("updateSentStoryReaction", [("peer", _data.peer as Any), ("storyId", _data.storyId as Any), ("reaction", _data.reaction as Any)]) + case .updateServiceNotification(let _data): + return ("updateServiceNotification", [("flags", _data.flags as Any), ("inboxDate", _data.inboxDate as Any), ("type", _data.type as Any), ("message", _data.message as Any), ("media", _data.media as Any), ("entities", _data.entities as Any)]) + case .updateSmsJob(let _data): + return ("updateSmsJob", [("jobId", _data.jobId as Any)]) + case .updateStarGiftAuctionState(let _data): + return ("updateStarGiftAuctionState", [("giftId", _data.giftId as Any), ("state", _data.state as Any)]) + case .updateStarGiftAuctionUserState(let _data): + return ("updateStarGiftAuctionUserState", [("giftId", _data.giftId as Any), ("userState", _data.userState as Any)]) + case .updateStarGiftCraftFail: + return ("updateStarGiftCraftFail", []) + case .updateStarsBalance(let _data): + return ("updateStarsBalance", [("balance", _data.balance as Any)]) + case .updateStarsRevenueStatus(let _data): + return ("updateStarsRevenueStatus", [("peer", _data.peer as Any), ("status", _data.status as Any)]) + case .updateStickerSets(let _data): + return ("updateStickerSets", [("flags", _data.flags as Any)]) + case .updateStickerSetsOrder(let _data): + return ("updateStickerSetsOrder", [("flags", _data.flags as Any), ("order", _data.order as Any)]) + case .updateStoriesStealthMode(let _data): + return ("updateStoriesStealthMode", [("stealthMode", _data.stealthMode as Any)]) + case .updateStory(let _data): + return ("updateStory", [("peer", _data.peer as Any), ("story", _data.story as Any)]) + case .updateStoryID(let _data): + return ("updateStoryID", [("id", _data.id as Any), ("randomId", _data.randomId as Any)]) + case .updateTheme(let _data): + return ("updateTheme", [("theme", _data.theme as Any)]) + case .updateTranscribedAudio(let _data): + return ("updateTranscribedAudio", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("msgId", _data.msgId as Any), ("transcriptionId", _data.transcriptionId as Any), ("text", _data.text as Any)]) + case .updateUser(let _data): + return ("updateUser", [("userId", _data.userId as Any)]) + case .updateUserEmojiStatus(let _data): + return ("updateUserEmojiStatus", [("userId", _data.userId as Any), ("emojiStatus", _data.emojiStatus as Any)]) + case .updateUserName(let _data): + return ("updateUserName", [("userId", _data.userId as Any), ("firstName", _data.firstName as Any), ("lastName", _data.lastName as Any), ("usernames", _data.usernames as Any)]) + case .updateUserPhone(let _data): + return ("updateUserPhone", [("userId", _data.userId as Any), ("phone", _data.phone as Any)]) + case .updateUserStatus(let _data): + return ("updateUserStatus", [("userId", _data.userId as Any), ("status", _data.status as Any)]) + case .updateUserTyping(let _data): + return ("updateUserTyping", [("flags", _data.flags as Any), ("userId", _data.userId as Any), ("topMsgId", _data.topMsgId as Any), ("action", _data.action as Any)]) + case .updateWebPage(let _data): + return ("updateWebPage", [("webpage", _data.webpage as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any)]) + case .updateWebViewResultSent(let _data): + return ("updateWebViewResultSent", [("queryId", _data.queryId as Any)]) + } + } + + public static func parse_updateAttachMenuBots(_ reader: BufferReader) -> Update? { + return Api.Update.updateAttachMenuBots + } + public static func parse_updateAutoSaveSettings(_ reader: BufferReader) -> Update? { + return Api.Update.updateAutoSaveSettings + } + public static func parse_updateBotBusinessConnect(_ reader: BufferReader) -> Update? { + var _1: Api.BotBusinessConnection? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.BotBusinessConnection } var _2: Int32? _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Updates.updateShort(update: _1!, date: _2!) + if _c1 && _c2 { + return Api.Update.updateBotBusinessConnect(Cons_updateBotBusinessConnect(connection: _1!, qts: _2!)) + } + else { + return nil + } } - public static func parse_updateShortChatMessage(_ reader: BufferReader) -> Updates? { + public static func parse_updateBotCallbackQuery(_ reader: BufferReader) -> Update? { var _1: Int32? _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() var _3: Int64? _3 = reader.readInt64() - var _4: Int64? - _4 = reader.readInt64() - var _5: String? - _5 = parseString(reader) - var _6: Int32? - _6 = reader.readInt32() - var _7: Int32? - _7 = reader.readInt32() - var _8: Int32? - _8 = reader.readInt32() - var _9: Api.MessageFwdHeader? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.MessageFwdHeader - } } - var _10: Int64? - if Int(_1!) & Int(1 << 11) != 0 {_10 = reader.readInt64() } - var _11: Api.MessageReplyHeader? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _11 = Api.parse(reader, signature: signature) as? Api.MessageReplyHeader - } } - var _12: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 7) != 0 {if let _ = reader.readInt32() { - _12 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } - var _13: Int32? - if Int(_1!) & Int(1 << 25) != 0 {_13 = reader.readInt32() } + var _4: Api.Peer? + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _5: Int32? + _5 = reader.readInt32() + var _6: Int64? + _6 = reader.readInt64() + var _7: Buffer? + if Int(_1!) & Int(1 << 0) != 0 { + _7 = parseBytes(reader) + } + var _8: String? + if Int(_1!) & Int(1 << 1) != 0 { + _8 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = _6 != nil - let _c7 = _7 != nil - let _c8 = _8 != nil - let _c9 = (Int(_1!) & Int(1 << 2) == 0) || _9 != nil - let _c10 = (Int(_1!) & Int(1 << 11) == 0) || _10 != nil - let _c11 = (Int(_1!) & Int(1 << 3) == 0) || _11 != nil - let _c12 = (Int(_1!) & Int(1 << 7) == 0) || _12 != nil - let _c13 = (Int(_1!) & Int(1 << 25) == 0) || _13 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - return Api.Updates.updateShortChatMessage(flags: _1!, id: _2!, fromId: _3!, chatId: _4!, message: _5!, pts: _6!, ptsCount: _7!, date: _8!, fwdFrom: _9, viaBotId: _10, replyTo: _11, entities: _12, ttlPeriod: _13) + let _c7 = (Int(_1!) & Int(1 << 0) == 0) || _7 != nil + let _c8 = (Int(_1!) & Int(1 << 1) == 0) || _8 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.Update.updateBotCallbackQuery(Cons_updateBotCallbackQuery(flags: _1!, queryId: _2!, userId: _3!, peer: _4!, msgId: _5!, chatInstance: _6!, data: _7, gameShortName: _8)) + } + else { + return nil + } } - public static func parse_updateShortMessage(_ reader: BufferReader) -> Updates? { - var _1: Int32? - _1 = reader.readInt32() + public static func parse_updateBotChatBoost(_ reader: BufferReader) -> Update? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _2: Api.Boost? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Boost + } + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateBotChatBoost(Cons_updateBotChatBoost(peer: _1!, boost: _2!, qts: _3!)) + } + else { + return nil + } + } + public static func parse_updateBotChatInviteRequester(_ reader: BufferReader) -> Update? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } var _2: Int32? _2 = reader.readInt32() var _3: Int64? _3 = reader.readInt64() var _4: String? _4 = parseString(reader) - var _5: Int32? - _5 = reader.readInt32() - var _6: Int32? - _6 = reader.readInt32() - var _7: Int32? - _7 = reader.readInt32() - var _8: Api.MessageFwdHeader? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.MessageFwdHeader - } } - var _9: Int64? - if Int(_1!) & Int(1 << 11) != 0 {_9 = reader.readInt64() } - var _10: Api.MessageReplyHeader? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _10 = Api.parse(reader, signature: signature) as? Api.MessageReplyHeader - } } - var _11: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 7) != 0 {if let _ = reader.readInt32() { - _11 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } - var _12: Int32? - if Int(_1!) & Int(1 << 25) != 0 {_12 = reader.readInt32() } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - let _c7 = _7 != nil - let _c8 = (Int(_1!) & Int(1 << 2) == 0) || _8 != nil - let _c9 = (Int(_1!) & Int(1 << 11) == 0) || _9 != nil - let _c10 = (Int(_1!) & Int(1 << 3) == 0) || _10 != nil - let _c11 = (Int(_1!) & Int(1 << 7) == 0) || _11 != nil - let _c12 = (Int(_1!) & Int(1 << 25) == 0) || _12 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - return Api.Updates.updateShortMessage(flags: _1!, id: _2!, userId: _3!, message: _4!, pts: _5!, ptsCount: _6!, date: _7!, fwdFrom: _8, viaBotId: _9, replyTo: _10, entities: _11, ttlPeriod: _12) - } - public static func parse_updateShortSentMessage(_ reader: BufferReader) -> Updates? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - var _4: Int32? - _4 = reader.readInt32() - var _5: Int32? - _5 = reader.readInt32() - var _6: Api.MessageMedia? - if Int(_1!) & Int(1 << 9) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.MessageMedia - } } - var _7: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 7) != 0 {if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } - var _8: Int32? - if Int(_1!) & Int(1 << 25) != 0 {_8 = reader.readInt32() } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 9) == 0) || _6 != nil - let _c7 = (Int(_1!) & Int(1 << 7) == 0) || _7 != nil - let _c8 = (Int(_1!) & Int(1 << 25) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.Updates.updateShortSentMessage(flags: _1!, id: _2!, pts: _3!, ptsCount: _4!, date: _5!, media: _6, entities: _7, ttlPeriod: _8) - } - public static func parse_updates(_ reader: BufferReader) -> Updates? { - var _1: [Api.Update]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Update.self) + var _5: Api.ExportedChatInvite? + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite } - var _2: [Api.User]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - var _3: [Api.Chat]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _4: Int32? - _4 = reader.readInt32() - var _5: Int32? - _5 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.Updates.updates(updates: _1!, users: _2!, chats: _3!, date: _4!, seq: _5!) - } - public static func parse_updatesCombined(_ reader: BufferReader) -> Updates? { - var _1: [Api.Update]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Update.self) - } - var _2: [Api.User]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - var _3: [Api.Chat]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _4: Int32? - _4 = reader.readInt32() - var _5: Int32? - _5 = reader.readInt32() var _6: Int32? _6 = reader.readInt32() let _c1 = _1 != nil @@ -374,1068 +3419,197 @@ public extension Api { let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.Updates.updatesCombined(updates: _1!, users: _2!, chats: _3!, date: _4!, seqStart: _5!, seq: _6!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.Update.updateBotChatInviteRequester(Cons_updateBotChatInviteRequester(peer: _1!, date: _2!, userId: _3!, about: _4!, invite: _5!, qts: _6!)) + } + else { + return nil + } } - public static func parse_updatesTooLong(_ reader: BufferReader) -> Updates? { - return Api.Updates.updatesTooLong + public static func parse_updateBotCommands(_ reader: BufferReader) -> Update? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _2: Int64? + _2 = reader.readInt64() + var _3: [Api.BotCommand]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.BotCommand.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateBotCommands(Cons_updateBotCommands(peer: _1!, botId: _2!, commands: _3!)) + } + else { + return nil + } } - - } -} -public extension Api { - enum UrlAuthResult: TypeConstructorDescription { - case urlAuthResultAccepted(url: String) - case urlAuthResultDefault - case urlAuthResultRequest(flags: Int32, bot: Api.User, domain: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .urlAuthResultAccepted(let url): - if boxed { - buffer.appendInt32(-1886646706) - } - serializeString(url, buffer: buffer, boxed: false) - break - case .urlAuthResultDefault: - if boxed { - buffer.appendInt32(-1445536993) - } - - break - case .urlAuthResultRequest(let flags, let bot, let domain): - if boxed { - buffer.appendInt32(-1831650802) - } - serializeInt32(flags, buffer: buffer, boxed: false) - bot.serialize(buffer, true) - serializeString(domain, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .urlAuthResultAccepted(let url): - return ("urlAuthResultAccepted", [("url", url as Any)]) - case .urlAuthResultDefault: - return ("urlAuthResultDefault", []) - case .urlAuthResultRequest(let flags, let bot, let domain): - return ("urlAuthResultRequest", [("flags", flags as Any), ("bot", bot as Any), ("domain", domain as Any)]) - } - } - - public static func parse_urlAuthResultAccepted(_ reader: BufferReader) -> UrlAuthResult? { + public static func parse_updateBotDeleteBusinessMessage(_ reader: BufferReader) -> Update? { var _1: String? _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.UrlAuthResult.urlAuthResultAccepted(url: _1!) - } - public static func parse_urlAuthResultDefault(_ reader: BufferReader) -> UrlAuthResult? { - return Api.UrlAuthResult.urlAuthResultDefault - } - public static func parse_urlAuthResultRequest(_ reader: BufferReader) -> UrlAuthResult? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.User? + var _2: Api.Peer? if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.User + _2 = Api.parse(reader, signature: signature) as? Api.Peer } - var _3: String? - _3 = parseString(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.UrlAuthResult.urlAuthResultRequest(flags: _1!, bot: _2!, domain: _3!) - } - - } -} -public extension Api { - enum User: TypeConstructorDescription { - case user(flags: Int32, flags2: Int32, id: Int64, accessHash: Int64?, firstName: String?, lastName: String?, username: String?, phone: String?, photo: Api.UserProfilePhoto?, status: Api.UserStatus?, botInfoVersion: Int32?, restrictionReason: [Api.RestrictionReason]?, botInlinePlaceholder: String?, langCode: String?, emojiStatus: Api.EmojiStatus?, usernames: [Api.Username]?, storiesMaxId: Api.RecentStory?, color: Api.PeerColor?, profileColor: Api.PeerColor?, botActiveUsers: Int32?, botVerificationIcon: Int64?, sendPaidMessagesStars: Int64?) - case userEmpty(id: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .user(let flags, let flags2, let id, let accessHash, let firstName, let lastName, let username, let phone, let photo, let status, let botInfoVersion, let restrictionReason, let botInlinePlaceholder, let langCode, let emojiStatus, let usernames, let storiesMaxId, let color, let profileColor, let botActiveUsers, let botVerificationIcon, let sendPaidMessagesStars): - if boxed { - buffer.appendInt32(829899656) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(flags2, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(accessHash!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(firstName!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(lastName!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeString(username!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeString(phone!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {photo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 6) != 0 {status!.serialize(buffer, true)} - if Int(flags) & Int(1 << 14) != 0 {serializeInt32(botInfoVersion!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 18) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(restrictionReason!.count)) - for item in restrictionReason! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 19) != 0 {serializeString(botInlinePlaceholder!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 22) != 0 {serializeString(langCode!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 30) != 0 {emojiStatus!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(usernames!.count)) - for item in usernames! { - item.serialize(buffer, true) - }} - if Int(flags2) & Int(1 << 5) != 0 {storiesMaxId!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 8) != 0 {color!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 9) != 0 {profileColor!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 12) != 0 {serializeInt32(botActiveUsers!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 14) != 0 {serializeInt64(botVerificationIcon!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 15) != 0 {serializeInt64(sendPaidMessagesStars!, buffer: buffer, boxed: false)} - break - case .userEmpty(let id): - if boxed { - buffer.appendInt32(-742634630) - } - serializeInt64(id, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .user(let flags, let flags2, let id, let accessHash, let firstName, let lastName, let username, let phone, let photo, let status, let botInfoVersion, let restrictionReason, let botInlinePlaceholder, let langCode, let emojiStatus, let usernames, let storiesMaxId, let color, let profileColor, let botActiveUsers, let botVerificationIcon, let sendPaidMessagesStars): - return ("user", [("flags", flags as Any), ("flags2", flags2 as Any), ("id", id as Any), ("accessHash", accessHash as Any), ("firstName", firstName as Any), ("lastName", lastName as Any), ("username", username as Any), ("phone", phone as Any), ("photo", photo as Any), ("status", status as Any), ("botInfoVersion", botInfoVersion as Any), ("restrictionReason", restrictionReason as Any), ("botInlinePlaceholder", botInlinePlaceholder as Any), ("langCode", langCode as Any), ("emojiStatus", emojiStatus as Any), ("usernames", usernames as Any), ("storiesMaxId", storiesMaxId as Any), ("color", color as Any), ("profileColor", profileColor as Any), ("botActiveUsers", botActiveUsers as Any), ("botVerificationIcon", botVerificationIcon as Any), ("sendPaidMessagesStars", sendPaidMessagesStars as Any)]) - case .userEmpty(let id): - return ("userEmpty", [("id", id as Any)]) - } - } - - public static func parse_user(_ reader: BufferReader) -> User? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int64? - _3 = reader.readInt64() - var _4: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_4 = reader.readInt64() } - var _5: String? - if Int(_1!) & Int(1 << 1) != 0 {_5 = parseString(reader) } - var _6: String? - if Int(_1!) & Int(1 << 2) != 0 {_6 = parseString(reader) } - var _7: String? - if Int(_1!) & Int(1 << 3) != 0 {_7 = parseString(reader) } - var _8: String? - if Int(_1!) & Int(1 << 4) != 0 {_8 = parseString(reader) } - var _9: Api.UserProfilePhoto? - if Int(_1!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.UserProfilePhoto - } } - var _10: Api.UserStatus? - if Int(_1!) & Int(1 << 6) != 0 {if let signature = reader.readInt32() { - _10 = Api.parse(reader, signature: signature) as? Api.UserStatus - } } - var _11: Int32? - if Int(_1!) & Int(1 << 14) != 0 {_11 = reader.readInt32() } - var _12: [Api.RestrictionReason]? - if Int(_1!) & Int(1 << 18) != 0 {if let _ = reader.readInt32() { - _12 = Api.parseVector(reader, elementSignature: 0, elementType: Api.RestrictionReason.self) - } } - var _13: String? - if Int(_1!) & Int(1 << 19) != 0 {_13 = parseString(reader) } - var _14: String? - if Int(_1!) & Int(1 << 22) != 0 {_14 = parseString(reader) } - var _15: Api.EmojiStatus? - if Int(_1!) & Int(1 << 30) != 0 {if let signature = reader.readInt32() { - _15 = Api.parse(reader, signature: signature) as? Api.EmojiStatus - } } - var _16: [Api.Username]? - if Int(_2!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _16 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Username.self) - } } - var _17: Api.RecentStory? - if Int(_2!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _17 = Api.parse(reader, signature: signature) as? Api.RecentStory - } } - var _18: Api.PeerColor? - if Int(_2!) & Int(1 << 8) != 0 {if let signature = reader.readInt32() { - _18 = Api.parse(reader, signature: signature) as? Api.PeerColor - } } - var _19: Api.PeerColor? - if Int(_2!) & Int(1 << 9) != 0 {if let signature = reader.readInt32() { - _19 = Api.parse(reader, signature: signature) as? Api.PeerColor - } } - var _20: Int32? - if Int(_2!) & Int(1 << 12) != 0 {_20 = reader.readInt32() } - var _21: Int64? - if Int(_2!) & Int(1 << 14) != 0 {_21 = reader.readInt64() } - var _22: Int64? - if Int(_2!) & Int(1 << 15) != 0 {_22 = reader.readInt64() } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil - let _c7 = (Int(_1!) & Int(1 << 3) == 0) || _7 != nil - let _c8 = (Int(_1!) & Int(1 << 4) == 0) || _8 != nil - let _c9 = (Int(_1!) & Int(1 << 5) == 0) || _9 != nil - let _c10 = (Int(_1!) & Int(1 << 6) == 0) || _10 != nil - let _c11 = (Int(_1!) & Int(1 << 14) == 0) || _11 != nil - let _c12 = (Int(_1!) & Int(1 << 18) == 0) || _12 != nil - let _c13 = (Int(_1!) & Int(1 << 19) == 0) || _13 != nil - let _c14 = (Int(_1!) & Int(1 << 22) == 0) || _14 != nil - let _c15 = (Int(_1!) & Int(1 << 30) == 0) || _15 != nil - let _c16 = (Int(_2!) & Int(1 << 0) == 0) || _16 != nil - let _c17 = (Int(_2!) & Int(1 << 5) == 0) || _17 != nil - let _c18 = (Int(_2!) & Int(1 << 8) == 0) || _18 != nil - let _c19 = (Int(_2!) & Int(1 << 9) == 0) || _19 != nil - let _c20 = (Int(_2!) & Int(1 << 12) == 0) || _20 != nil - let _c21 = (Int(_2!) & Int(1 << 14) == 0) || _21 != nil - let _c22 = (Int(_2!) & Int(1 << 15) == 0) || _22 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - if !_c16 { return nil } - if !_c17 { return nil } - if !_c18 { return nil } - if !_c19 { return nil } - if !_c20 { return nil } - if !_c21 { return nil } - if !_c22 { return nil } - return Api.User.user(flags: _1!, flags2: _2!, id: _3!, accessHash: _4, firstName: _5, lastName: _6, username: _7, phone: _8, photo: _9, status: _10, botInfoVersion: _11, restrictionReason: _12, botInlinePlaceholder: _13, langCode: _14, emojiStatus: _15, usernames: _16, storiesMaxId: _17, color: _18, profileColor: _19, botActiveUsers: _20, botVerificationIcon: _21, sendPaidMessagesStars: _22) - } - public static func parse_userEmpty(_ reader: BufferReader) -> User? { - var _1: Int64? - _1 = reader.readInt64() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.User.userEmpty(id: _1!) - } - - } -} -public extension Api { - enum UserFull: TypeConstructorDescription { - case userFull(flags: Int32, flags2: Int32, id: Int64, about: String?, settings: Api.PeerSettings, personalPhoto: Api.Photo?, profilePhoto: Api.Photo?, fallbackPhoto: Api.Photo?, notifySettings: Api.PeerNotifySettings, botInfo: Api.BotInfo?, pinnedMsgId: Int32?, commonChatsCount: Int32, folderId: Int32?, ttlPeriod: Int32?, theme: Api.ChatTheme?, privateForwardName: String?, botGroupAdminRights: Api.ChatAdminRights?, botBroadcastAdminRights: Api.ChatAdminRights?, wallpaper: Api.WallPaper?, stories: Api.PeerStories?, businessWorkHours: Api.BusinessWorkHours?, businessLocation: Api.BusinessLocation?, businessGreetingMessage: Api.BusinessGreetingMessage?, businessAwayMessage: Api.BusinessAwayMessage?, businessIntro: Api.BusinessIntro?, birthday: Api.Birthday?, personalChannelId: Int64?, personalChannelMessage: Int32?, stargiftsCount: Int32?, starrefProgram: Api.StarRefProgram?, botVerification: Api.BotVerification?, sendPaidMessagesStars: Int64?, disallowedGifts: Api.DisallowedGiftsSettings?, starsRating: Api.StarsRating?, starsMyPendingRating: Api.StarsRating?, starsMyPendingRatingDate: Int32?, mainTab: Api.ProfileTab?, savedMusic: Api.Document?, note: Api.TextWithEntities?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .userFull(let flags, let flags2, let id, let about, let settings, let personalPhoto, let profilePhoto, let fallbackPhoto, let notifySettings, let botInfo, let pinnedMsgId, let commonChatsCount, let folderId, let ttlPeriod, let theme, let privateForwardName, let botGroupAdminRights, let botBroadcastAdminRights, let wallpaper, let stories, let businessWorkHours, let businessLocation, let businessGreetingMessage, let businessAwayMessage, let businessIntro, let birthday, let personalChannelId, let personalChannelMessage, let stargiftsCount, let starrefProgram, let botVerification, let sendPaidMessagesStars, let disallowedGifts, let starsRating, let starsMyPendingRating, let starsMyPendingRatingDate, let mainTab, let savedMusic, let note): - if boxed { - buffer.appendInt32(-1607745218) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(flags2, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeString(about!, buffer: buffer, boxed: false)} - settings.serialize(buffer, true) - if Int(flags) & Int(1 << 21) != 0 {personalPhoto!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {profilePhoto!.serialize(buffer, true)} - if Int(flags) & Int(1 << 22) != 0 {fallbackPhoto!.serialize(buffer, true)} - notifySettings.serialize(buffer, true) - if Int(flags) & Int(1 << 3) != 0 {botInfo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 6) != 0 {serializeInt32(pinnedMsgId!, buffer: buffer, boxed: false)} - serializeInt32(commonChatsCount, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 11) != 0 {serializeInt32(folderId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 14) != 0 {serializeInt32(ttlPeriod!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 15) != 0 {theme!.serialize(buffer, true)} - if Int(flags) & Int(1 << 16) != 0 {serializeString(privateForwardName!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 17) != 0 {botGroupAdminRights!.serialize(buffer, true)} - if Int(flags) & Int(1 << 18) != 0 {botBroadcastAdminRights!.serialize(buffer, true)} - if Int(flags) & Int(1 << 24) != 0 {wallpaper!.serialize(buffer, true)} - if Int(flags) & Int(1 << 25) != 0 {stories!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 0) != 0 {businessWorkHours!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 1) != 0 {businessLocation!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 2) != 0 {businessGreetingMessage!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 3) != 0 {businessAwayMessage!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 4) != 0 {businessIntro!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 5) != 0 {birthday!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 6) != 0 {serializeInt64(personalChannelId!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 6) != 0 {serializeInt32(personalChannelMessage!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 8) != 0 {serializeInt32(stargiftsCount!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 11) != 0 {starrefProgram!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 12) != 0 {botVerification!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 14) != 0 {serializeInt64(sendPaidMessagesStars!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 15) != 0 {disallowedGifts!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 17) != 0 {starsRating!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 18) != 0 {starsMyPendingRating!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 18) != 0 {serializeInt32(starsMyPendingRatingDate!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 20) != 0 {mainTab!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 21) != 0 {savedMusic!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 22) != 0 {note!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .userFull(let flags, let flags2, let id, let about, let settings, let personalPhoto, let profilePhoto, let fallbackPhoto, let notifySettings, let botInfo, let pinnedMsgId, let commonChatsCount, let folderId, let ttlPeriod, let theme, let privateForwardName, let botGroupAdminRights, let botBroadcastAdminRights, let wallpaper, let stories, let businessWorkHours, let businessLocation, let businessGreetingMessage, let businessAwayMessage, let businessIntro, let birthday, let personalChannelId, let personalChannelMessage, let stargiftsCount, let starrefProgram, let botVerification, let sendPaidMessagesStars, let disallowedGifts, let starsRating, let starsMyPendingRating, let starsMyPendingRatingDate, let mainTab, let savedMusic, let note): - return ("userFull", [("flags", flags as Any), ("flags2", flags2 as Any), ("id", id as Any), ("about", about as Any), ("settings", settings as Any), ("personalPhoto", personalPhoto as Any), ("profilePhoto", profilePhoto as Any), ("fallbackPhoto", fallbackPhoto as Any), ("notifySettings", notifySettings as Any), ("botInfo", botInfo as Any), ("pinnedMsgId", pinnedMsgId as Any), ("commonChatsCount", commonChatsCount as Any), ("folderId", folderId as Any), ("ttlPeriod", ttlPeriod as Any), ("theme", theme as Any), ("privateForwardName", privateForwardName as Any), ("botGroupAdminRights", botGroupAdminRights as Any), ("botBroadcastAdminRights", botBroadcastAdminRights as Any), ("wallpaper", wallpaper as Any), ("stories", stories as Any), ("businessWorkHours", businessWorkHours as Any), ("businessLocation", businessLocation as Any), ("businessGreetingMessage", businessGreetingMessage as Any), ("businessAwayMessage", businessAwayMessage as Any), ("businessIntro", businessIntro as Any), ("birthday", birthday as Any), ("personalChannelId", personalChannelId as Any), ("personalChannelMessage", personalChannelMessage as Any), ("stargiftsCount", stargiftsCount as Any), ("starrefProgram", starrefProgram as Any), ("botVerification", botVerification as Any), ("sendPaidMessagesStars", sendPaidMessagesStars as Any), ("disallowedGifts", disallowedGifts as Any), ("starsRating", starsRating as Any), ("starsMyPendingRating", starsMyPendingRating as Any), ("starsMyPendingRatingDate", starsMyPendingRatingDate as Any), ("mainTab", mainTab as Any), ("savedMusic", savedMusic as Any), ("note", note as Any)]) - } - } - - public static func parse_userFull(_ reader: BufferReader) -> UserFull? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int64? - _3 = reader.readInt64() - var _4: String? - if Int(_1!) & Int(1 << 1) != 0 {_4 = parseString(reader) } - var _5: Api.PeerSettings? - if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.PeerSettings - } - var _6: Api.Photo? - if Int(_1!) & Int(1 << 21) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.Photo - } } - var _7: Api.Photo? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.Photo - } } - var _8: Api.Photo? - if Int(_1!) & Int(1 << 22) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.Photo - } } - var _9: Api.PeerNotifySettings? - if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.PeerNotifySettings - } - var _10: Api.BotInfo? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _10 = Api.parse(reader, signature: signature) as? Api.BotInfo - } } - var _11: Int32? - if Int(_1!) & Int(1 << 6) != 0 {_11 = reader.readInt32() } - var _12: Int32? - _12 = reader.readInt32() - var _13: Int32? - if Int(_1!) & Int(1 << 11) != 0 {_13 = reader.readInt32() } - var _14: Int32? - if Int(_1!) & Int(1 << 14) != 0 {_14 = reader.readInt32() } - var _15: Api.ChatTheme? - if Int(_1!) & Int(1 << 15) != 0 {if let signature = reader.readInt32() { - _15 = Api.parse(reader, signature: signature) as? Api.ChatTheme - } } - var _16: String? - if Int(_1!) & Int(1 << 16) != 0 {_16 = parseString(reader) } - var _17: Api.ChatAdminRights? - if Int(_1!) & Int(1 << 17) != 0 {if let signature = reader.readInt32() { - _17 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights - } } - var _18: Api.ChatAdminRights? - if Int(_1!) & Int(1 << 18) != 0 {if let signature = reader.readInt32() { - _18 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights - } } - var _19: Api.WallPaper? - if Int(_1!) & Int(1 << 24) != 0 {if let signature = reader.readInt32() { - _19 = Api.parse(reader, signature: signature) as? Api.WallPaper - } } - var _20: Api.PeerStories? - if Int(_1!) & Int(1 << 25) != 0 {if let signature = reader.readInt32() { - _20 = Api.parse(reader, signature: signature) as? Api.PeerStories - } } - var _21: Api.BusinessWorkHours? - if Int(_2!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _21 = Api.parse(reader, signature: signature) as? Api.BusinessWorkHours - } } - var _22: Api.BusinessLocation? - if Int(_2!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _22 = Api.parse(reader, signature: signature) as? Api.BusinessLocation - } } - var _23: Api.BusinessGreetingMessage? - if Int(_2!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _23 = Api.parse(reader, signature: signature) as? Api.BusinessGreetingMessage - } } - var _24: Api.BusinessAwayMessage? - if Int(_2!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _24 = Api.parse(reader, signature: signature) as? Api.BusinessAwayMessage - } } - var _25: Api.BusinessIntro? - if Int(_2!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _25 = Api.parse(reader, signature: signature) as? Api.BusinessIntro - } } - var _26: Api.Birthday? - if Int(_2!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _26 = Api.parse(reader, signature: signature) as? Api.Birthday - } } - var _27: Int64? - if Int(_2!) & Int(1 << 6) != 0 {_27 = reader.readInt64() } - var _28: Int32? - if Int(_2!) & Int(1 << 6) != 0 {_28 = reader.readInt32() } - var _29: Int32? - if Int(_2!) & Int(1 << 8) != 0 {_29 = reader.readInt32() } - var _30: Api.StarRefProgram? - if Int(_2!) & Int(1 << 11) != 0 {if let signature = reader.readInt32() { - _30 = Api.parse(reader, signature: signature) as? Api.StarRefProgram - } } - var _31: Api.BotVerification? - if Int(_2!) & Int(1 << 12) != 0 {if let signature = reader.readInt32() { - _31 = Api.parse(reader, signature: signature) as? Api.BotVerification - } } - var _32: Int64? - if Int(_2!) & Int(1 << 14) != 0 {_32 = reader.readInt64() } - var _33: Api.DisallowedGiftsSettings? - if Int(_2!) & Int(1 << 15) != 0 {if let signature = reader.readInt32() { - _33 = Api.parse(reader, signature: signature) as? Api.DisallowedGiftsSettings - } } - var _34: Api.StarsRating? - if Int(_2!) & Int(1 << 17) != 0 {if let signature = reader.readInt32() { - _34 = Api.parse(reader, signature: signature) as? Api.StarsRating - } } - var _35: Api.StarsRating? - if Int(_2!) & Int(1 << 18) != 0 {if let signature = reader.readInt32() { - _35 = Api.parse(reader, signature: signature) as? Api.StarsRating - } } - var _36: Int32? - if Int(_2!) & Int(1 << 18) != 0 {_36 = reader.readInt32() } - var _37: Api.ProfileTab? - if Int(_2!) & Int(1 << 20) != 0 {if let signature = reader.readInt32() { - _37 = Api.parse(reader, signature: signature) as? Api.ProfileTab - } } - var _38: Api.Document? - if Int(_2!) & Int(1 << 21) != 0 {if let signature = reader.readInt32() { - _38 = Api.parse(reader, signature: signature) as? Api.Document - } } - var _39: Api.TextWithEntities? - if Int(_2!) & Int(1 << 22) != 0 {if let signature = reader.readInt32() { - _39 = Api.parse(reader, signature: signature) as? Api.TextWithEntities - } } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 21) == 0) || _6 != nil - let _c7 = (Int(_1!) & Int(1 << 2) == 0) || _7 != nil - let _c8 = (Int(_1!) & Int(1 << 22) == 0) || _8 != nil - let _c9 = _9 != nil - let _c10 = (Int(_1!) & Int(1 << 3) == 0) || _10 != nil - let _c11 = (Int(_1!) & Int(1 << 6) == 0) || _11 != nil - let _c12 = _12 != nil - let _c13 = (Int(_1!) & Int(1 << 11) == 0) || _13 != nil - let _c14 = (Int(_1!) & Int(1 << 14) == 0) || _14 != nil - let _c15 = (Int(_1!) & Int(1 << 15) == 0) || _15 != nil - let _c16 = (Int(_1!) & Int(1 << 16) == 0) || _16 != nil - let _c17 = (Int(_1!) & Int(1 << 17) == 0) || _17 != nil - let _c18 = (Int(_1!) & Int(1 << 18) == 0) || _18 != nil - let _c19 = (Int(_1!) & Int(1 << 24) == 0) || _19 != nil - let _c20 = (Int(_1!) & Int(1 << 25) == 0) || _20 != nil - let _c21 = (Int(_2!) & Int(1 << 0) == 0) || _21 != nil - let _c22 = (Int(_2!) & Int(1 << 1) == 0) || _22 != nil - let _c23 = (Int(_2!) & Int(1 << 2) == 0) || _23 != nil - let _c24 = (Int(_2!) & Int(1 << 3) == 0) || _24 != nil - let _c25 = (Int(_2!) & Int(1 << 4) == 0) || _25 != nil - let _c26 = (Int(_2!) & Int(1 << 5) == 0) || _26 != nil - let _c27 = (Int(_2!) & Int(1 << 6) == 0) || _27 != nil - let _c28 = (Int(_2!) & Int(1 << 6) == 0) || _28 != nil - let _c29 = (Int(_2!) & Int(1 << 8) == 0) || _29 != nil - let _c30 = (Int(_2!) & Int(1 << 11) == 0) || _30 != nil - let _c31 = (Int(_2!) & Int(1 << 12) == 0) || _31 != nil - let _c32 = (Int(_2!) & Int(1 << 14) == 0) || _32 != nil - let _c33 = (Int(_2!) & Int(1 << 15) == 0) || _33 != nil - let _c34 = (Int(_2!) & Int(1 << 17) == 0) || _34 != nil - let _c35 = (Int(_2!) & Int(1 << 18) == 0) || _35 != nil - let _c36 = (Int(_2!) & Int(1 << 18) == 0) || _36 != nil - let _c37 = (Int(_2!) & Int(1 << 20) == 0) || _37 != nil - let _c38 = (Int(_2!) & Int(1 << 21) == 0) || _38 != nil - let _c39 = (Int(_2!) & Int(1 << 22) == 0) || _39 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - if !_c16 { return nil } - if !_c17 { return nil } - if !_c18 { return nil } - if !_c19 { return nil } - if !_c20 { return nil } - if !_c21 { return nil } - if !_c22 { return nil } - if !_c23 { return nil } - if !_c24 { return nil } - if !_c25 { return nil } - if !_c26 { return nil } - if !_c27 { return nil } - if !_c28 { return nil } - if !_c29 { return nil } - if !_c30 { return nil } - if !_c31 { return nil } - if !_c32 { return nil } - if !_c33 { return nil } - if !_c34 { return nil } - if !_c35 { return nil } - if !_c36 { return nil } - if !_c37 { return nil } - if !_c38 { return nil } - if !_c39 { return nil } - return Api.UserFull.userFull(flags: _1!, flags2: _2!, id: _3!, about: _4, settings: _5!, personalPhoto: _6, profilePhoto: _7, fallbackPhoto: _8, notifySettings: _9!, botInfo: _10, pinnedMsgId: _11, commonChatsCount: _12!, folderId: _13, ttlPeriod: _14, theme: _15, privateForwardName: _16, botGroupAdminRights: _17, botBroadcastAdminRights: _18, wallpaper: _19, stories: _20, businessWorkHours: _21, businessLocation: _22, businessGreetingMessage: _23, businessAwayMessage: _24, businessIntro: _25, birthday: _26, personalChannelId: _27, personalChannelMessage: _28, stargiftsCount: _29, starrefProgram: _30, botVerification: _31, sendPaidMessagesStars: _32, disallowedGifts: _33, starsRating: _34, starsMyPendingRating: _35, starsMyPendingRatingDate: _36, mainTab: _37, savedMusic: _38, note: _39) - } - - } -} -public extension Api { - enum UserProfilePhoto: TypeConstructorDescription { - case userProfilePhoto(flags: Int32, photoId: Int64, strippedThumb: Buffer?, dcId: Int32) - case userProfilePhotoEmpty - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .userProfilePhoto(let flags, let photoId, let strippedThumb, let dcId): - if boxed { - buffer.appendInt32(-2100168954) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(photoId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeBytes(strippedThumb!, buffer: buffer, boxed: false)} - serializeInt32(dcId, buffer: buffer, boxed: false) - break - case .userProfilePhotoEmpty: - if boxed { - buffer.appendInt32(1326562017) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .userProfilePhoto(let flags, let photoId, let strippedThumb, let dcId): - return ("userProfilePhoto", [("flags", flags as Any), ("photoId", photoId as Any), ("strippedThumb", strippedThumb as Any), ("dcId", dcId as Any)]) - case .userProfilePhotoEmpty: - return ("userProfilePhotoEmpty", []) - } - } - - public static func parse_userProfilePhoto(_ reader: BufferReader) -> UserProfilePhoto? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Buffer? - if Int(_1!) & Int(1 << 1) != 0 {_3 = parseBytes(reader) } - var _4: Int32? - _4 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.UserProfilePhoto.userProfilePhoto(flags: _1!, photoId: _2!, strippedThumb: _3, dcId: _4!) - } - public static func parse_userProfilePhotoEmpty(_ reader: BufferReader) -> UserProfilePhoto? { - return Api.UserProfilePhoto.userProfilePhotoEmpty - } - - } -} -public extension Api { - enum UserStatus: TypeConstructorDescription { - case userStatusEmpty - case userStatusLastMonth(flags: Int32) - case userStatusLastWeek(flags: Int32) - case userStatusOffline(wasOnline: Int32) - case userStatusOnline(expires: Int32) - case userStatusRecently(flags: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .userStatusEmpty: - if boxed { - buffer.appendInt32(164646985) - } - - break - case .userStatusLastMonth(let flags): - if boxed { - buffer.appendInt32(1703516023) - } - serializeInt32(flags, buffer: buffer, boxed: false) - break - case .userStatusLastWeek(let flags): - if boxed { - buffer.appendInt32(1410997530) - } - serializeInt32(flags, buffer: buffer, boxed: false) - break - case .userStatusOffline(let wasOnline): - if boxed { - buffer.appendInt32(9203775) - } - serializeInt32(wasOnline, buffer: buffer, boxed: false) - break - case .userStatusOnline(let expires): - if boxed { - buffer.appendInt32(-306628279) - } - serializeInt32(expires, buffer: buffer, boxed: false) - break - case .userStatusRecently(let flags): - if boxed { - buffer.appendInt32(2065268168) - } - serializeInt32(flags, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .userStatusEmpty: - return ("userStatusEmpty", []) - case .userStatusLastMonth(let flags): - return ("userStatusLastMonth", [("flags", flags as Any)]) - case .userStatusLastWeek(let flags): - return ("userStatusLastWeek", [("flags", flags as Any)]) - case .userStatusOffline(let wasOnline): - return ("userStatusOffline", [("wasOnline", wasOnline as Any)]) - case .userStatusOnline(let expires): - return ("userStatusOnline", [("expires", expires as Any)]) - case .userStatusRecently(let flags): - return ("userStatusRecently", [("flags", flags as Any)]) - } - } - - public static func parse_userStatusEmpty(_ reader: BufferReader) -> UserStatus? { - return Api.UserStatus.userStatusEmpty - } - public static func parse_userStatusLastMonth(_ reader: BufferReader) -> UserStatus? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.UserStatus.userStatusLastMonth(flags: _1!) - } - public static func parse_userStatusLastWeek(_ reader: BufferReader) -> UserStatus? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.UserStatus.userStatusLastWeek(flags: _1!) - } - public static func parse_userStatusOffline(_ reader: BufferReader) -> UserStatus? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.UserStatus.userStatusOffline(wasOnline: _1!) - } - public static func parse_userStatusOnline(_ reader: BufferReader) -> UserStatus? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.UserStatus.userStatusOnline(expires: _1!) - } - public static func parse_userStatusRecently(_ reader: BufferReader) -> UserStatus? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.UserStatus.userStatusRecently(flags: _1!) - } - - } -} -public extension Api { - enum Username: TypeConstructorDescription { - case username(flags: Int32, username: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .username(let flags, let username): - if boxed { - buffer.appendInt32(-1274595769) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(username, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .username(let flags, let username): - return ("username", [("flags", flags as Any), ("username", username as Any)]) - } - } - - public static func parse_username(_ reader: BufferReader) -> Username? { - var _1: Int32? - _1 = reader.readInt32() - var _2: String? - _2 = parseString(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Username.username(flags: _1!, username: _2!) - } - - } -} -public extension Api { - enum VideoSize: TypeConstructorDescription { - case videoSize(flags: Int32, type: String, w: Int32, h: Int32, size: Int32, videoStartTs: Double?) - case videoSizeEmojiMarkup(emojiId: Int64, backgroundColors: [Int32]) - case videoSizeStickerMarkup(stickerset: Api.InputStickerSet, stickerId: Int64, backgroundColors: [Int32]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .videoSize(let flags, let type, let w, let h, let size, let videoStartTs): - if boxed { - buffer.appendInt32(-567037804) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(type, buffer: buffer, boxed: false) - serializeInt32(w, buffer: buffer, boxed: false) - serializeInt32(h, buffer: buffer, boxed: false) - serializeInt32(size, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeDouble(videoStartTs!, buffer: buffer, boxed: false)} - break - case .videoSizeEmojiMarkup(let emojiId, let backgroundColors): - if boxed { - buffer.appendInt32(-128171716) - } - serializeInt64(emojiId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(backgroundColors.count)) - for item in backgroundColors { - serializeInt32(item, buffer: buffer, boxed: false) - } - break - case .videoSizeStickerMarkup(let stickerset, let stickerId, let backgroundColors): - if boxed { - buffer.appendInt32(228623102) - } - stickerset.serialize(buffer, true) - serializeInt64(stickerId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(backgroundColors.count)) - for item in backgroundColors { - serializeInt32(item, buffer: buffer, boxed: false) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .videoSize(let flags, let type, let w, let h, let size, let videoStartTs): - return ("videoSize", [("flags", flags as Any), ("type", type as Any), ("w", w as Any), ("h", h as Any), ("size", size as Any), ("videoStartTs", videoStartTs as Any)]) - case .videoSizeEmojiMarkup(let emojiId, let backgroundColors): - return ("videoSizeEmojiMarkup", [("emojiId", emojiId as Any), ("backgroundColors", backgroundColors as Any)]) - case .videoSizeStickerMarkup(let stickerset, let stickerId, let backgroundColors): - return ("videoSizeStickerMarkup", [("stickerset", stickerset as Any), ("stickerId", stickerId as Any), ("backgroundColors", backgroundColors as Any)]) - } - } - - public static func parse_videoSize(_ reader: BufferReader) -> VideoSize? { - var _1: Int32? - _1 = reader.readInt32() - var _2: String? - _2 = parseString(reader) - var _3: Int32? - _3 = reader.readInt32() - var _4: Int32? - _4 = reader.readInt32() - var _5: Int32? - _5 = reader.readInt32() - var _6: Double? - if Int(_1!) & Int(1 << 0) != 0 {_6 = reader.readDouble() } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.VideoSize.videoSize(flags: _1!, type: _2!, w: _3!, h: _4!, size: _5!, videoStartTs: _6) - } - public static func parse_videoSizeEmojiMarkup(_ reader: BufferReader) -> VideoSize? { - var _1: Int64? - _1 = reader.readInt64() - var _2: [Int32]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.VideoSize.videoSizeEmojiMarkup(emojiId: _1!, backgroundColors: _2!) - } - public static func parse_videoSizeStickerMarkup(_ reader: BufferReader) -> VideoSize? { - var _1: Api.InputStickerSet? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.InputStickerSet - } - var _2: Int64? - _2 = reader.readInt64() var _3: [Int32]? if let _ = reader.readInt32() { _3 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.VideoSize.videoSizeStickerMarkup(stickerset: _1!, stickerId: _2!, backgroundColors: _3!) - } - - } -} -public extension Api { - enum WallPaper: TypeConstructorDescription { - case wallPaper(id: Int64, flags: Int32, accessHash: Int64, slug: String, document: Api.Document, settings: Api.WallPaperSettings?) - case wallPaperNoFile(id: Int64, flags: Int32, settings: Api.WallPaperSettings?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .wallPaper(let id, let flags, let accessHash, let slug, let document, let settings): - if boxed { - buffer.appendInt32(-1539849235) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeString(slug, buffer: buffer, boxed: false) - document.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {settings!.serialize(buffer, true)} - break - case .wallPaperNoFile(let id, let flags, let settings): - if boxed { - buffer.appendInt32(-528465642) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {settings!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .wallPaper(let id, let flags, let accessHash, let slug, let document, let settings): - return ("wallPaper", [("id", id as Any), ("flags", flags as Any), ("accessHash", accessHash as Any), ("slug", slug as Any), ("document", document as Any), ("settings", settings as Any)]) - case .wallPaperNoFile(let id, let flags, let settings): - return ("wallPaperNoFile", [("id", id as Any), ("flags", flags as Any), ("settings", settings as Any)]) - } - } - - public static func parse_wallPaper(_ reader: BufferReader) -> WallPaper? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int64? - _3 = reader.readInt64() - var _4: String? - _4 = parseString(reader) - var _5: Api.Document? - if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.Document - } - var _6: Api.WallPaperSettings? - if Int(_2!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.WallPaperSettings - } } + var _4: Int32? + _4 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_2!) & Int(1 << 2) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.WallPaper.wallPaper(id: _1!, flags: _2!, accessHash: _3!, slug: _4!, document: _5!, settings: _6) + if _c1 && _c2 && _c3 && _c4 { + return Api.Update.updateBotDeleteBusinessMessage(Cons_updateBotDeleteBusinessMessage(connectionId: _1!, peer: _2!, messages: _3!, qts: _4!)) + } + else { + return nil + } } - public static func parse_wallPaperNoFile(_ reader: BufferReader) -> WallPaper? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Int32? - _2 = reader.readInt32() - var _3: Api.WallPaperSettings? - if Int(_2!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.WallPaperSettings - } } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_2!) & Int(1 << 2) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.WallPaper.wallPaperNoFile(id: _1!, flags: _2!, settings: _3) - } - - } -} -public extension Api { - enum WallPaperSettings: TypeConstructorDescription { - case wallPaperSettings(flags: Int32, backgroundColor: Int32?, secondBackgroundColor: Int32?, thirdBackgroundColor: Int32?, fourthBackgroundColor: Int32?, intensity: Int32?, rotation: Int32?, emoticon: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .wallPaperSettings(let flags, let backgroundColor, let secondBackgroundColor, let thirdBackgroundColor, let fourthBackgroundColor, let intensity, let rotation, let emoticon): - if boxed { - buffer.appendInt32(925826256) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(backgroundColor!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(secondBackgroundColor!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeInt32(thirdBackgroundColor!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 6) != 0 {serializeInt32(fourthBackgroundColor!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(intensity!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(rotation!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 7) != 0 {serializeString(emoticon!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .wallPaperSettings(let flags, let backgroundColor, let secondBackgroundColor, let thirdBackgroundColor, let fourthBackgroundColor, let intensity, let rotation, let emoticon): - return ("wallPaperSettings", [("flags", flags as Any), ("backgroundColor", backgroundColor as Any), ("secondBackgroundColor", secondBackgroundColor as Any), ("thirdBackgroundColor", thirdBackgroundColor as Any), ("fourthBackgroundColor", fourthBackgroundColor as Any), ("intensity", intensity as Any), ("rotation", rotation as Any), ("emoticon", emoticon as Any)]) - } - } - - public static func parse_wallPaperSettings(_ reader: BufferReader) -> WallPaperSettings? { + public static func parse_updateBotEditBusinessMessage(_ reader: BufferReader) -> Update? { var _1: Int32? _1 = reader.readInt32() - var _2: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt32() } - var _3: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_3 = reader.readInt32() } - var _4: Int32? - if Int(_1!) & Int(1 << 5) != 0 {_4 = reader.readInt32() } + var _2: String? + _2 = parseString(reader) + var _3: Api.Message? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Message + } + var _4: Api.Message? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Message + } + } var _5: Int32? - if Int(_1!) & Int(1 << 6) != 0 {_5 = reader.readInt32() } - var _6: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_6 = reader.readInt32() } - var _7: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_7 = reader.readInt32() } - var _8: String? - if Int(_1!) & Int(1 << 7) != 0 {_8 = parseString(reader) } + _5 = reader.readInt32() let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - let _c3 = (Int(_1!) & Int(1 << 4) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 5) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 6) == 0) || _5 != nil - let _c6 = (Int(_1!) & Int(1 << 3) == 0) || _6 != nil - let _c7 = (Int(_1!) & Int(1 << 4) == 0) || _7 != nil - let _c8 = (Int(_1!) & Int(1 << 7) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.WallPaperSettings.wallPaperSettings(flags: _1!, backgroundColor: _2, secondBackgroundColor: _3, thirdBackgroundColor: _4, fourthBackgroundColor: _5, intensity: _6, rotation: _7, emoticon: _8) + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.Update.updateBotEditBusinessMessage(Cons_updateBotEditBusinessMessage(flags: _1!, connectionId: _2!, message: _3!, replyToMessage: _4, qts: _5!)) + } + else { + return nil + } } - - } -} -public extension Api { - enum WebAuthorization: TypeConstructorDescription { - case webAuthorization(hash: Int64, botId: Int64, domain: String, browser: String, platform: String, dateCreated: Int32, dateActive: Int32, ip: String, region: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .webAuthorization(let hash, let botId, let domain, let browser, let platform, let dateCreated, let dateActive, let ip, let region): - if boxed { - buffer.appendInt32(-1493633966) - } - serializeInt64(hash, buffer: buffer, boxed: false) - serializeInt64(botId, buffer: buffer, boxed: false) - serializeString(domain, buffer: buffer, boxed: false) - serializeString(browser, buffer: buffer, boxed: false) - serializeString(platform, buffer: buffer, boxed: false) - serializeInt32(dateCreated, buffer: buffer, boxed: false) - serializeInt32(dateActive, buffer: buffer, boxed: false) - serializeString(ip, buffer: buffer, boxed: false) - serializeString(region, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .webAuthorization(let hash, let botId, let domain, let browser, let platform, let dateCreated, let dateActive, let ip, let region): - return ("webAuthorization", [("hash", hash as Any), ("botId", botId as Any), ("domain", domain as Any), ("browser", browser as Any), ("platform", platform as Any), ("dateCreated", dateCreated as Any), ("dateActive", dateActive as Any), ("ip", ip as Any), ("region", region as Any)]) - } - } - - public static func parse_webAuthorization(_ reader: BufferReader) -> WebAuthorization? { - var _1: Int64? - _1 = reader.readInt64() + public static func parse_updateBotInlineQuery(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: Int64? + _3 = reader.readInt64() + var _4: String? + _4 = parseString(reader) + var _5: Api.GeoPoint? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.GeoPoint + } + } + var _6: Api.InlineQueryPeerType? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.InlineQueryPeerType + } + } + var _7: String? + _7 = parseString(reader) + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil + let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil + let _c7 = _7 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.Update.updateBotInlineQuery(Cons_updateBotInlineQuery(flags: _1!, queryId: _2!, userId: _3!, query: _4!, geo: _5, peerType: _6, offset: _7!)) + } + else { + return nil + } + } + public static func parse_updateBotInlineSend(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() var _2: Int64? _2 = reader.readInt64() var _3: String? _3 = parseString(reader) - var _4: String? - _4 = parseString(reader) + var _4: Api.GeoPoint? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.GeoPoint + } + } var _5: String? _5 = parseString(reader) - var _6: Int32? - _6 = reader.readInt32() + var _6: Api.InputBotInlineMessageID? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.InputBotInlineMessageID + } + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil + let _c5 = _5 != nil + let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.Update.updateBotInlineSend(Cons_updateBotInlineSend(flags: _1!, userId: _2!, query: _3!, geo: _4, id: _5!, msgId: _6)) + } + else { + return nil + } + } + public static func parse_updateBotMenuButton(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Api.BotMenuButton? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.BotMenuButton + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateBotMenuButton(Cons_updateBotMenuButton(botId: _1!, button: _2!)) + } + else { + return nil + } + } + public static func parse_updateBotMessageReaction(_ reader: BufferReader) -> Update? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + var _4: Api.Peer? + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _5: [Api.Reaction]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Reaction.self) + } + var _6: [Api.Reaction]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Reaction.self) + } var _7: Int32? _7 = reader.readInt32() - var _8: String? - _8 = parseString(reader) - var _9: String? - _9 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -1443,241 +3617,330 @@ public extension Api { let _c5 = _5 != nil let _c6 = _6 != nil let _c7 = _7 != nil - let _c8 = _8 != nil - let _c9 = _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.WebAuthorization.webAuthorization(hash: _1!, botId: _2!, domain: _3!, browser: _4!, platform: _5!, dateCreated: _6!, dateActive: _7!, ip: _8!, region: _9!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.Update.updateBotMessageReaction(Cons_updateBotMessageReaction(peer: _1!, msgId: _2!, date: _3!, actor: _4!, oldReactions: _5!, newReactions: _6!, qts: _7!)) + } + else { + return nil + } } - - } -} -public extension Api { - enum WebDocument: TypeConstructorDescription { - case webDocument(url: String, accessHash: Int64, size: Int32, mimeType: String, attributes: [Api.DocumentAttribute]) - case webDocumentNoProxy(url: String, size: Int32, mimeType: String, attributes: [Api.DocumentAttribute]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .webDocument(let url, let accessHash, let size, let mimeType, let attributes): - if boxed { - buffer.appendInt32(475467473) - } - serializeString(url, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeInt32(size, buffer: buffer, boxed: false) - serializeString(mimeType, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(attributes.count)) - for item in attributes { - item.serialize(buffer, true) - } - break - case .webDocumentNoProxy(let url, let size, let mimeType, let attributes): - if boxed { - buffer.appendInt32(-104284986) - } - serializeString(url, buffer: buffer, boxed: false) - serializeInt32(size, buffer: buffer, boxed: false) - serializeString(mimeType, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(attributes.count)) - for item in attributes { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .webDocument(let url, let accessHash, let size, let mimeType, let attributes): - return ("webDocument", [("url", url as Any), ("accessHash", accessHash as Any), ("size", size as Any), ("mimeType", mimeType as Any), ("attributes", attributes as Any)]) - case .webDocumentNoProxy(let url, let size, let mimeType, let attributes): - return ("webDocumentNoProxy", [("url", url as Any), ("size", size as Any), ("mimeType", mimeType as Any), ("attributes", attributes as Any)]) - } - } - - public static func parse_webDocument(_ reader: BufferReader) -> WebDocument? { - var _1: String? - _1 = parseString(reader) - var _2: Int64? - _2 = reader.readInt64() + public static func parse_updateBotMessageReactions(_ reader: BufferReader) -> Update? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _2: Int32? + _2 = reader.readInt32() var _3: Int32? _3 = reader.readInt32() + var _4: [Api.ReactionCount]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ReactionCount.self) + } + var _5: Int32? + _5 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.Update.updateBotMessageReactions(Cons_updateBotMessageReactions(peer: _1!, msgId: _2!, date: _3!, reactions: _4!, qts: _5!)) + } + else { + return nil + } + } + public static func parse_updateBotNewBusinessMessage(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: String? + _2 = parseString(reader) + var _3: Api.Message? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Message + } + var _4: Api.Message? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Message + } + } + var _5: Int32? + _5 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.Update.updateBotNewBusinessMessage(Cons_updateBotNewBusinessMessage(flags: _1!, connectionId: _2!, message: _3!, replyToMessage: _4, qts: _5!)) + } + else { + return nil + } + } + public static func parse_updateBotPrecheckoutQuery(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: Int64? + _3 = reader.readInt64() + var _4: Buffer? + _4 = parseBytes(reader) + var _5: Api.PaymentRequestedInfo? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.PaymentRequestedInfo + } + } + var _6: String? + if Int(_1!) & Int(1 << 1) != 0 { + _6 = parseString(reader) + } + var _7: String? + _7 = parseString(reader) + var _8: Int64? + _8 = reader.readInt64() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil + let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil + let _c7 = _7 != nil + let _c8 = _8 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.Update.updateBotPrecheckoutQuery(Cons_updateBotPrecheckoutQuery(flags: _1!, queryId: _2!, userId: _3!, payload: _4!, info: _5, shippingOptionId: _6, currency: _7!, totalAmount: _8!)) + } + else { + return nil + } + } + public static func parse_updateBotPurchasedPaidMedia(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: String? + _2 = parseString(reader) + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateBotPurchasedPaidMedia(Cons_updateBotPurchasedPaidMedia(userId: _1!, payload: _2!, qts: _3!)) + } + else { + return nil + } + } + public static func parse_updateBotShippingQuery(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Int64? + _2 = reader.readInt64() + var _3: Buffer? + _3 = parseBytes(reader) + var _4: Api.PostAddress? + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.PostAddress + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.Update.updateBotShippingQuery(Cons_updateBotShippingQuery(queryId: _1!, userId: _2!, payload: _3!, shippingAddress: _4!)) + } + else { + return nil + } + } + public static func parse_updateBotStopped(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Int32? + _2 = reader.readInt32() + var _3: Api.Bool? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Bool + } + var _4: Int32? + _4 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.Update.updateBotStopped(Cons_updateBotStopped(userId: _1!, date: _2!, stopped: _3!, qts: _4!)) + } + else { + return nil + } + } + public static func parse_updateBotWebhookJSON(_ reader: BufferReader) -> Update? { + var _1: Api.DataJSON? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.DataJSON + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateBotWebhookJSON(Cons_updateBotWebhookJSON(data: _1!)) + } + else { + return nil + } + } + public static func parse_updateBotWebhookJSONQuery(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Api.DataJSON? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.DataJSON + } + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateBotWebhookJSONQuery(Cons_updateBotWebhookJSONQuery(queryId: _1!, data: _2!, timeout: _3!)) + } + else { + return nil + } + } + public static func parse_updateBusinessBotCallbackQuery(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: Int64? + _3 = reader.readInt64() var _4: String? _4 = parseString(reader) - var _5: [Api.DocumentAttribute]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.DocumentAttribute.self) + var _5: Api.Message? + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.Message + } + var _6: Api.Message? + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.Message + } + } + var _7: Int64? + _7 = reader.readInt64() + var _8: Buffer? + if Int(_1!) & Int(1 << 0) != 0 { + _8 = parseBytes(reader) } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.WebDocument.webDocument(url: _1!, accessHash: _2!, size: _3!, mimeType: _4!, attributes: _5!) + let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil + let _c7 = _7 != nil + let _c8 = (Int(_1!) & Int(1 << 0) == 0) || _8 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.Update.updateBusinessBotCallbackQuery(Cons_updateBusinessBotCallbackQuery(flags: _1!, queryId: _2!, userId: _3!, connectionId: _4!, message: _5!, replyToMessage: _6, chatInstance: _7!, data: _8)) + } + else { + return nil + } } - public static func parse_webDocumentNoProxy(_ reader: BufferReader) -> WebDocument? { - var _1: String? - _1 = parseString(reader) + public static func parse_updateChannel(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateChannel(Cons_updateChannel(channelId: _1!)) + } + else { + return nil + } + } + public static func parse_updateChannelAvailableMessages(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() var _2: Int32? _2 = reader.readInt32() - var _3: String? - _3 = parseString(reader) - var _4: [Api.DocumentAttribute]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.DocumentAttribute.self) + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateChannelAvailableMessages(Cons_updateChannelAvailableMessages(channelId: _1!, availableMinId: _2!)) } + else { + return nil + } + } + public static func parse_updateChannelMessageForwards(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.WebDocument.webDocumentNoProxy(url: _1!, size: _2!, mimeType: _3!, attributes: _4!) + if _c1 && _c2 && _c3 { + return Api.Update.updateChannelMessageForwards(Cons_updateChannelMessageForwards(channelId: _1!, id: _2!, forwards: _3!)) + } + else { + return nil + } } - - } -} -public extension Api { - enum WebPage: TypeConstructorDescription { - case webPage(flags: Int32, id: Int64, url: String, displayUrl: String, hash: Int32, type: String?, siteName: String?, title: String?, description: String?, photo: Api.Photo?, embedUrl: String?, embedType: String?, embedWidth: Int32?, embedHeight: Int32?, duration: Int32?, author: String?, document: Api.Document?, cachedPage: Api.Page?, attributes: [Api.WebPageAttribute]?) - case webPageEmpty(flags: Int32, id: Int64, url: String?) - case webPageNotModified(flags: Int32, cachedPageViews: Int32?) - case webPagePending(flags: Int32, id: Int64, url: String?, date: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .webPage(let flags, let id, let url, let displayUrl, let hash, let type, let siteName, let title, let description, let photo, let embedUrl, let embedType, let embedWidth, let embedHeight, let duration, let author, let document, let cachedPage, let attributes): - if boxed { - buffer.appendInt32(-392411726) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - serializeString(displayUrl, buffer: buffer, boxed: false) - serializeInt32(hash, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(type!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(siteName!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeString(description!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {photo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 5) != 0 {serializeString(embedUrl!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeString(embedType!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 6) != 0 {serializeInt32(embedWidth!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 6) != 0 {serializeInt32(embedHeight!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 7) != 0 {serializeInt32(duration!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {serializeString(author!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 9) != 0 {document!.serialize(buffer, true)} - if Int(flags) & Int(1 << 10) != 0 {cachedPage!.serialize(buffer, true)} - if Int(flags) & Int(1 << 12) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(attributes!.count)) - for item in attributes! { - item.serialize(buffer, true) - }} - break - case .webPageEmpty(let flags, let id, let url): - if boxed { - buffer.appendInt32(555358088) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(url!, buffer: buffer, boxed: false)} - break - case .webPageNotModified(let flags, let cachedPageViews): - if boxed { - buffer.appendInt32(1930545681) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(cachedPageViews!, buffer: buffer, boxed: false)} - break - case .webPagePending(let flags, let id, let url, let date): - if boxed { - buffer.appendInt32(-1328464313) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(url!, buffer: buffer, boxed: false)} - serializeInt32(date, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .webPage(let flags, let id, let url, let displayUrl, let hash, let type, let siteName, let title, let description, let photo, let embedUrl, let embedType, let embedWidth, let embedHeight, let duration, let author, let document, let cachedPage, let attributes): - return ("webPage", [("flags", flags as Any), ("id", id as Any), ("url", url as Any), ("displayUrl", displayUrl as Any), ("hash", hash as Any), ("type", type as Any), ("siteName", siteName as Any), ("title", title as Any), ("description", description as Any), ("photo", photo as Any), ("embedUrl", embedUrl as Any), ("embedType", embedType as Any), ("embedWidth", embedWidth as Any), ("embedHeight", embedHeight as Any), ("duration", duration as Any), ("author", author as Any), ("document", document as Any), ("cachedPage", cachedPage as Any), ("attributes", attributes as Any)]) - case .webPageEmpty(let flags, let id, let url): - return ("webPageEmpty", [("flags", flags as Any), ("id", id as Any), ("url", url as Any)]) - case .webPageNotModified(let flags, let cachedPageViews): - return ("webPageNotModified", [("flags", flags as Any), ("cachedPageViews", cachedPageViews as Any)]) - case .webPagePending(let flags, let id, let url, let date): - return ("webPagePending", [("flags", flags as Any), ("id", id as Any), ("url", url as Any), ("date", date as Any)]) - } - } - - public static func parse_webPage(_ reader: BufferReader) -> WebPage? { + public static func parse_updateChannelMessageViews(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateChannelMessageViews(Cons_updateChannelMessageViews(channelId: _1!, id: _2!, views: _3!)) + } + else { + return nil + } + } + public static func parse_updateChannelParticipant(_ reader: BufferReader) -> Update? { var _1: Int32? _1 = reader.readInt32() var _2: Int64? _2 = reader.readInt64() - var _3: String? - _3 = parseString(reader) - var _4: String? - _4 = parseString(reader) - var _5: Int32? - _5 = reader.readInt32() - var _6: String? - if Int(_1!) & Int(1 << 0) != 0 {_6 = parseString(reader) } - var _7: String? - if Int(_1!) & Int(1 << 1) != 0 {_7 = parseString(reader) } - var _8: String? - if Int(_1!) & Int(1 << 2) != 0 {_8 = parseString(reader) } - var _9: String? - if Int(_1!) & Int(1 << 3) != 0 {_9 = parseString(reader) } - var _10: Api.Photo? - if Int(_1!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _10 = Api.parse(reader, signature: signature) as? Api.Photo - } } - var _11: String? - if Int(_1!) & Int(1 << 5) != 0 {_11 = parseString(reader) } - var _12: String? - if Int(_1!) & Int(1 << 5) != 0 {_12 = parseString(reader) } - var _13: Int32? - if Int(_1!) & Int(1 << 6) != 0 {_13 = reader.readInt32() } - var _14: Int32? - if Int(_1!) & Int(1 << 6) != 0 {_14 = reader.readInt32() } - var _15: Int32? - if Int(_1!) & Int(1 << 7) != 0 {_15 = reader.readInt32() } - var _16: String? - if Int(_1!) & Int(1 << 8) != 0 {_16 = parseString(reader) } - var _17: Api.Document? - if Int(_1!) & Int(1 << 9) != 0 {if let signature = reader.readInt32() { - _17 = Api.parse(reader, signature: signature) as? Api.Document - } } - var _18: Api.Page? - if Int(_1!) & Int(1 << 10) != 0 {if let signature = reader.readInt32() { - _18 = Api.parse(reader, signature: signature) as? Api.Page - } } - var _19: [Api.WebPageAttribute]? - if Int(_1!) & Int(1 << 12) != 0 {if let _ = reader.readInt32() { - _19 = Api.parseVector(reader, elementSignature: 0, elementType: Api.WebPageAttribute.self) - } } + var _3: Int32? + _3 = reader.readInt32() + var _4: Int64? + _4 = reader.readInt64() + var _5: Int64? + _5 = reader.readInt64() + var _6: Api.ChannelParticipant? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.ChannelParticipant + } + } + var _7: Api.ChannelParticipant? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.ChannelParticipant + } + } + var _8: Api.ExportedChatInvite? + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite + } + } + var _9: Int32? + _9 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -1686,83 +3949,2175 @@ public extension Api { let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil let _c8 = (Int(_1!) & Int(1 << 2) == 0) || _8 != nil - let _c9 = (Int(_1!) & Int(1 << 3) == 0) || _9 != nil - let _c10 = (Int(_1!) & Int(1 << 4) == 0) || _10 != nil - let _c11 = (Int(_1!) & Int(1 << 5) == 0) || _11 != nil - let _c12 = (Int(_1!) & Int(1 << 5) == 0) || _12 != nil - let _c13 = (Int(_1!) & Int(1 << 6) == 0) || _13 != nil - let _c14 = (Int(_1!) & Int(1 << 6) == 0) || _14 != nil - let _c15 = (Int(_1!) & Int(1 << 7) == 0) || _15 != nil - let _c16 = (Int(_1!) & Int(1 << 8) == 0) || _16 != nil - let _c17 = (Int(_1!) & Int(1 << 9) == 0) || _17 != nil - let _c18 = (Int(_1!) & Int(1 << 10) == 0) || _18 != nil - let _c19 = (Int(_1!) & Int(1 << 12) == 0) || _19 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - if !_c16 { return nil } - if !_c17 { return nil } - if !_c18 { return nil } - if !_c19 { return nil } - return Api.WebPage.webPage(flags: _1!, id: _2!, url: _3!, displayUrl: _4!, hash: _5!, type: _6, siteName: _7, title: _8, description: _9, photo: _10, embedUrl: _11, embedType: _12, embedWidth: _13, embedHeight: _14, duration: _15, author: _16, document: _17, cachedPage: _18, attributes: _19) + let _c9 = _9 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.Update.updateChannelParticipant(Cons_updateChannelParticipant(flags: _1!, channelId: _2!, date: _3!, actorId: _4!, userId: _5!, prevParticipant: _6, newParticipant: _7, invite: _8, qts: _9!)) + } + else { + return nil + } } - public static func parse_webPageEmpty(_ reader: BufferReader) -> WebPage? { + public static func parse_updateChannelReadMessagesContents(_ reader: BufferReader) -> Update? { var _1: Int32? _1 = reader.readInt32() var _2: Int64? _2 = reader.readInt64() - var _3: String? - if Int(_1!) & Int(1 << 0) != 0 {_3 = parseString(reader) } + var _3: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } + var _4: Api.Peer? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Peer + } + } + var _5: [Int32]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.WebPage.webPageEmpty(flags: _1!, id: _2!, url: _3) + let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.Update.updateChannelReadMessagesContents(Cons_updateChannelReadMessagesContents(flags: _1!, channelId: _2!, topMsgId: _3, savedPeerId: _4, messages: _5!)) + } + else { + return nil + } } - public static func parse_webPageNotModified(_ reader: BufferReader) -> WebPage? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt32() } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.WebPage.webPageNotModified(flags: _1!, cachedPageViews: _2) - } - public static func parse_webPagePending(_ reader: BufferReader) -> WebPage? { + public static func parse_updateChannelTooLong(_ reader: BufferReader) -> Update? { var _1: Int32? _1 = reader.readInt32() var _2: Int64? _2 = reader.readInt64() - var _3: String? - if Int(_1!) & Int(1 << 0) != 0 {_3 = parseString(reader) } - var _4: Int32? - _4 = reader.readInt32() + var _3: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateChannelTooLong(Cons_updateChannelTooLong(flags: _1!, channelId: _2!, pts: _3)) + } + else { + return nil + } + } + public static func parse_updateChannelUserTyping(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } + var _4: Api.Peer? + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _5: Api.SendMessageAction? + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.SendMessageAction + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.WebPage.webPagePending(flags: _1!, id: _2!, url: _3, date: _4!) + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.Update.updateChannelUserTyping(Cons_updateChannelUserTyping(flags: _1!, channelId: _2!, topMsgId: _3, fromId: _4!, action: _5!)) + } + else { + return nil + } + } + public static func parse_updateChannelViewForumAsMessages(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Api.Bool? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Bool + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateChannelViewForumAsMessages(Cons_updateChannelViewForumAsMessages(channelId: _1!, enabled: _2!)) + } + else { + return nil + } + } + public static func parse_updateChannelWebPage(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Api.WebPage? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.WebPage + } + var _3: Int32? + _3 = reader.readInt32() + var _4: Int32? + _4 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.Update.updateChannelWebPage(Cons_updateChannelWebPage(channelId: _1!, webpage: _2!, pts: _3!, ptsCount: _4!)) + } + else { + return nil + } + } + public static func parse_updateChat(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateChat(Cons_updateChat(chatId: _1!)) + } + else { + return nil + } + } + public static func parse_updateChatDefaultBannedRights(_ reader: BufferReader) -> Update? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _2: Api.ChatBannedRights? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.ChatBannedRights + } + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateChatDefaultBannedRights(Cons_updateChatDefaultBannedRights(peer: _1!, defaultBannedRights: _2!, version: _3!)) + } + else { + return nil + } + } + public static func parse_updateChatParticipant(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: Int32? + _3 = reader.readInt32() + var _4: Int64? + _4 = reader.readInt64() + var _5: Int64? + _5 = reader.readInt64() + var _6: Api.ChatParticipant? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.ChatParticipant + } + } + var _7: Api.ChatParticipant? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.ChatParticipant + } + } + var _8: Api.ExportedChatInvite? + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite + } + } + var _9: Int32? + _9 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil + let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil + let _c8 = (Int(_1!) & Int(1 << 2) == 0) || _8 != nil + let _c9 = _9 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.Update.updateChatParticipant(Cons_updateChatParticipant(flags: _1!, chatId: _2!, date: _3!, actorId: _4!, userId: _5!, prevParticipant: _6, newParticipant: _7, invite: _8, qts: _9!)) + } + else { + return nil + } + } + public static func parse_updateChatParticipantAdd(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Int64? + _2 = reader.readInt64() + var _3: Int64? + _3 = reader.readInt64() + var _4: Int32? + _4 = reader.readInt32() + var _5: Int32? + _5 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.Update.updateChatParticipantAdd(Cons_updateChatParticipantAdd(chatId: _1!, userId: _2!, inviterId: _3!, date: _4!, version: _5!)) + } + else { + return nil + } + } + public static func parse_updateChatParticipantAdmin(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Int64? + _2 = reader.readInt64() + var _3: Api.Bool? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Bool + } + var _4: Int32? + _4 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.Update.updateChatParticipantAdmin(Cons_updateChatParticipantAdmin(chatId: _1!, userId: _2!, isAdmin: _3!, version: _4!)) + } + else { + return nil + } + } + public static func parse_updateChatParticipantDelete(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Int64? + _2 = reader.readInt64() + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateChatParticipantDelete(Cons_updateChatParticipantDelete(chatId: _1!, userId: _2!, version: _3!)) + } + else { + return nil + } + } + public static func parse_updateChatParticipants(_ reader: BufferReader) -> Update? { + var _1: Api.ChatParticipants? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.ChatParticipants + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateChatParticipants(Cons_updateChatParticipants(participants: _1!)) + } + else { + return nil + } + } + public static func parse_updateChatUserTyping(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: Api.SendMessageAction? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.SendMessageAction + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateChatUserTyping(Cons_updateChatUserTyping(chatId: _1!, fromId: _2!, action: _3!)) + } + else { + return nil + } + } + public static func parse_updateConfig(_ reader: BufferReader) -> Update? { + return Api.Update.updateConfig + } + public static func parse_updateContactsReset(_ reader: BufferReader) -> Update? { + return Api.Update.updateContactsReset + } + public static func parse_updateDcOptions(_ reader: BufferReader) -> Update? { + var _1: [Api.DcOption]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.DcOption.self) + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateDcOptions(Cons_updateDcOptions(dcOptions: _1!)) + } + else { + return nil + } + } + public static func parse_updateDeleteChannelMessages(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: [Int32]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + var _3: Int32? + _3 = reader.readInt32() + var _4: Int32? + _4 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.Update.updateDeleteChannelMessages(Cons_updateDeleteChannelMessages(channelId: _1!, messages: _2!, pts: _3!, ptsCount: _4!)) + } + else { + return nil + } + } + public static func parse_updateDeleteGroupCallMessages(_ reader: BufferReader) -> Update? { + var _1: Api.InputGroupCall? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.InputGroupCall + } + var _2: [Int32]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateDeleteGroupCallMessages(Cons_updateDeleteGroupCallMessages(call: _1!, messages: _2!)) + } + else { + return nil + } + } + public static func parse_updateDeleteMessages(_ reader: BufferReader) -> Update? { + var _1: [Int32]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateDeleteMessages(Cons_updateDeleteMessages(messages: _1!, pts: _2!, ptsCount: _3!)) + } + else { + return nil + } + } + public static func parse_updateDeleteQuickReply(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateDeleteQuickReply(Cons_updateDeleteQuickReply(shortcutId: _1!)) + } + else { + return nil + } + } + public static func parse_updateDeleteQuickReplyMessages(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Int32]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateDeleteQuickReplyMessages(Cons_updateDeleteQuickReplyMessages(shortcutId: _1!, messages: _2!)) + } + else { + return nil + } + } + public static func parse_updateDeleteScheduledMessages(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: [Int32]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + var _4: [Int32]? + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.Update.updateDeleteScheduledMessages(Cons_updateDeleteScheduledMessages(flags: _1!, peer: _2!, messages: _3!, sentMessages: _4)) + } + else { + return nil + } + } + public static func parse_updateDialogFilter(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Api.DialogFilter? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.DialogFilter + } + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateDialogFilter(Cons_updateDialogFilter(flags: _1!, id: _2!, filter: _3)) + } + else { + return nil + } + } + public static func parse_updateDialogFilterOrder(_ reader: BufferReader) -> Update? { + var _1: [Int32]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateDialogFilterOrder(Cons_updateDialogFilterOrder(order: _1!)) + } + else { + return nil + } + } + public static func parse_updateDialogFilters(_ reader: BufferReader) -> Update? { + return Api.Update.updateDialogFilters + } + public static func parse_updateDialogPinned(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _2 = reader.readInt32() + } + var _3: Api.DialogPeer? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.DialogPeer + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateDialogPinned(Cons_updateDialogPinned(flags: _1!, folderId: _2, peer: _3!)) + } + else { + return nil + } + } + public static func parse_updateDialogUnreadMark(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.DialogPeer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.DialogPeer + } + var _3: Api.Peer? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Peer + } + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateDialogUnreadMark(Cons_updateDialogUnreadMark(flags: _1!, peer: _2!, savedPeerId: _3)) + } + else { + return nil + } + } + public static func parse_updateDraftMessage(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } + var _4: Api.Peer? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Peer + } + } + var _5: Api.DraftMessage? + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.DraftMessage + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.Update.updateDraftMessage(Cons_updateDraftMessage(flags: _1!, peer: _2!, topMsgId: _3, savedPeerId: _4, draft: _5!)) + } + else { + return nil + } + } + public static func parse_updateEditChannelMessage(_ reader: BufferReader) -> Update? { + var _1: Api.Message? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Message + } + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateEditChannelMessage(Cons_updateEditChannelMessage(message: _1!, pts: _2!, ptsCount: _3!)) + } + else { + return nil + } + } + public static func parse_updateEditMessage(_ reader: BufferReader) -> Update? { + var _1: Api.Message? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Message + } + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateEditMessage(Cons_updateEditMessage(message: _1!, pts: _2!, ptsCount: _3!)) + } + else { + return nil + } + } + public static func parse_updateEmojiGameInfo(_ reader: BufferReader) -> Update? { + var _1: Api.messages.EmojiGameInfo? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.messages.EmojiGameInfo + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateEmojiGameInfo(Cons_updateEmojiGameInfo(info: _1!)) + } + else { + return nil + } + } + public static func parse_updateEncryptedChatTyping(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateEncryptedChatTyping(Cons_updateEncryptedChatTyping(chatId: _1!)) + } + else { + return nil + } + } + public static func parse_updateEncryptedMessagesRead(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateEncryptedMessagesRead(Cons_updateEncryptedMessagesRead(chatId: _1!, maxDate: _2!, date: _3!)) + } + else { + return nil + } + } + public static func parse_updateEncryption(_ reader: BufferReader) -> Update? { + var _1: Api.EncryptedChat? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.EncryptedChat + } + var _2: Int32? + _2 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateEncryption(Cons_updateEncryption(chat: _1!, date: _2!)) + } + else { + return nil + } + } + public static func parse_updateFavedStickers(_ reader: BufferReader) -> Update? { + return Api.Update.updateFavedStickers + } + public static func parse_updateFolderPeers(_ reader: BufferReader) -> Update? { + var _1: [Api.FolderPeer]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.FolderPeer.self) + } + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateFolderPeers(Cons_updateFolderPeers(folderPeers: _1!, pts: _2!, ptsCount: _3!)) + } + else { + return nil + } + } + public static func parse_updateGeoLiveViewed(_ reader: BufferReader) -> Update? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _2: Int32? + _2 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateGeoLiveViewed(Cons_updateGeoLiveViewed(peer: _1!, msgId: _2!)) + } + else { + return nil + } + } + public static func parse_updateGroupCall(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.Peer? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + } + var _3: Api.GroupCall? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.GroupCall + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateGroupCall(Cons_updateGroupCall(flags: _1!, peer: _2, call: _3!)) + } + else { + return nil + } + } + public static func parse_updateGroupCallChainBlocks(_ reader: BufferReader) -> Update? { + var _1: Api.InputGroupCall? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.InputGroupCall + } + var _2: Int32? + _2 = reader.readInt32() + var _3: [Buffer]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: -1255641564, elementType: Buffer.self) + } + var _4: Int32? + _4 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.Update.updateGroupCallChainBlocks(Cons_updateGroupCallChainBlocks(call: _1!, subChainId: _2!, blocks: _3!, nextOffset: _4!)) + } + else { + return nil + } + } + public static func parse_updateGroupCallConnection(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.DataJSON? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.DataJSON + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateGroupCallConnection(Cons_updateGroupCallConnection(flags: _1!, params: _2!)) + } + else { + return nil + } + } + public static func parse_updateGroupCallEncryptedMessage(_ reader: BufferReader) -> Update? { + var _1: Api.InputGroupCall? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.InputGroupCall + } + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: Buffer? + _3 = parseBytes(reader) + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateGroupCallEncryptedMessage(Cons_updateGroupCallEncryptedMessage(call: _1!, fromId: _2!, encryptedMessage: _3!)) + } + else { + return nil + } + } + public static func parse_updateGroupCallMessage(_ reader: BufferReader) -> Update? { + var _1: Api.InputGroupCall? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.InputGroupCall + } + var _2: Api.GroupCallMessage? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.GroupCallMessage + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateGroupCallMessage(Cons_updateGroupCallMessage(call: _1!, message: _2!)) + } + else { + return nil + } + } + public static func parse_updateGroupCallParticipants(_ reader: BufferReader) -> Update? { + var _1: Api.InputGroupCall? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.InputGroupCall + } + var _2: [Api.GroupCallParticipant]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.GroupCallParticipant.self) + } + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateGroupCallParticipants(Cons_updateGroupCallParticipants(call: _1!, participants: _2!, version: _3!)) + } + else { + return nil + } + } + public static func parse_updateInlineBotCallbackQuery(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: Int64? + _3 = reader.readInt64() + var _4: Api.InputBotInlineMessageID? + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.InputBotInlineMessageID + } + var _5: Int64? + _5 = reader.readInt64() + var _6: Buffer? + if Int(_1!) & Int(1 << 0) != 0 { + _6 = parseBytes(reader) + } + var _7: String? + if Int(_1!) & Int(1 << 1) != 0 { + _7 = parseString(reader) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil + let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.Update.updateInlineBotCallbackQuery(Cons_updateInlineBotCallbackQuery(flags: _1!, queryId: _2!, userId: _3!, msgId: _4!, chatInstance: _5!, data: _6, gameShortName: _7)) + } + else { + return nil + } + } + public static func parse_updateLangPack(_ reader: BufferReader) -> Update? { + var _1: Api.LangPackDifference? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.LangPackDifference + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateLangPack(Cons_updateLangPack(difference: _1!)) + } + else { + return nil + } + } + public static func parse_updateLangPackTooLong(_ reader: BufferReader) -> Update? { + var _1: String? + _1 = parseString(reader) + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateLangPackTooLong(Cons_updateLangPackTooLong(langCode: _1!)) + } + else { + return nil + } + } + public static func parse_updateLoginToken(_ reader: BufferReader) -> Update? { + return Api.Update.updateLoginToken + } + public static func parse_updateMessageExtendedMedia(_ reader: BufferReader) -> Update? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _2: Int32? + _2 = reader.readInt32() + var _3: [Api.MessageExtendedMedia]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageExtendedMedia.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateMessageExtendedMedia(Cons_updateMessageExtendedMedia(peer: _1!, msgId: _2!, extendedMedia: _3!)) + } + else { + return nil + } + } + public static func parse_updateMessageID(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateMessageID(Cons_updateMessageID(id: _1!, randomId: _2!)) + } + else { + return nil + } + } + public static func parse_updateMessagePoll(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: Api.Poll? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Poll + } + } + var _4: Api.PollResults? + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.PollResults + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.Update.updateMessagePoll(Cons_updateMessagePoll(flags: _1!, pollId: _2!, poll: _3, results: _4!)) + } + else { + return nil + } + } + public static func parse_updateMessagePollVote(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: [Buffer]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: -1255641564, elementType: Buffer.self) + } + var _4: Int32? + _4 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.Update.updateMessagePollVote(Cons_updateMessagePollVote(pollId: _1!, peer: _2!, options: _3!, qts: _4!)) + } + else { + return nil + } + } + public static func parse_updateMessageReactions(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: Int32? + _3 = reader.readInt32() + var _4: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _4 = reader.readInt32() + } + var _5: Api.Peer? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.Peer + } + } + var _6: Api.MessageReactions? + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.MessageReactions + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil + let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.Update.updateMessageReactions(Cons_updateMessageReactions(flags: _1!, peer: _2!, msgId: _3!, topMsgId: _4, savedPeerId: _5, reactions: _6!)) + } + else { + return nil + } + } + public static func parse_updateMonoForumNoPaidException(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: Api.Peer? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Peer + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateMonoForumNoPaidException(Cons_updateMonoForumNoPaidException(flags: _1!, channelId: _2!, savedPeerId: _3!)) + } + else { + return nil + } + } + public static func parse_updateMoveStickerSetToTop(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateMoveStickerSetToTop(Cons_updateMoveStickerSetToTop(flags: _1!, stickerset: _2!)) + } + else { + return nil + } + } + public static func parse_updateNewAuthorization(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } + var _4: String? + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) + } + var _5: String? + if Int(_1!) & Int(1 << 0) != 0 { + _5 = parseString(reader) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil + let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.Update.updateNewAuthorization(Cons_updateNewAuthorization(flags: _1!, hash: _2!, date: _3, device: _4, location: _5)) + } + else { + return nil + } + } + public static func parse_updateNewChannelMessage(_ reader: BufferReader) -> Update? { + var _1: Api.Message? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Message + } + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateNewChannelMessage(Cons_updateNewChannelMessage(message: _1!, pts: _2!, ptsCount: _3!)) + } + else { + return nil + } + } + public static func parse_updateNewEncryptedMessage(_ reader: BufferReader) -> Update? { + var _1: Api.EncryptedMessage? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.EncryptedMessage + } + var _2: Int32? + _2 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateNewEncryptedMessage(Cons_updateNewEncryptedMessage(message: _1!, qts: _2!)) + } + else { + return nil + } + } + public static func parse_updateNewMessage(_ reader: BufferReader) -> Update? { + var _1: Api.Message? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Message + } + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateNewMessage(Cons_updateNewMessage(message: _1!, pts: _2!, ptsCount: _3!)) + } + else { + return nil + } + } + public static func parse_updateNewQuickReply(_ reader: BufferReader) -> Update? { + var _1: Api.QuickReply? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.QuickReply + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateNewQuickReply(Cons_updateNewQuickReply(quickReply: _1!)) + } + else { + return nil + } + } + public static func parse_updateNewScheduledMessage(_ reader: BufferReader) -> Update? { + var _1: Api.Message? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Message + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateNewScheduledMessage(Cons_updateNewScheduledMessage(message: _1!)) + } + else { + return nil + } + } + public static func parse_updateNewStickerSet(_ reader: BufferReader) -> Update? { + var _1: Api.messages.StickerSet? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.messages.StickerSet + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateNewStickerSet(Cons_updateNewStickerSet(stickerset: _1!)) + } + else { + return nil + } + } + public static func parse_updateNewStoryReaction(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: Api.Reaction? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Reaction + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateNewStoryReaction(Cons_updateNewStoryReaction(storyId: _1!, peer: _2!, reaction: _3!)) + } + else { + return nil + } + } + public static func parse_updateNotifySettings(_ reader: BufferReader) -> Update? { + var _1: Api.NotifyPeer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.NotifyPeer + } + var _2: Api.PeerNotifySettings? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.PeerNotifySettings + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateNotifySettings(Cons_updateNotifySettings(peer: _1!, notifySettings: _2!)) + } + else { + return nil + } + } + public static func parse_updatePaidReactionPrivacy(_ reader: BufferReader) -> Update? { + var _1: Api.PaidReactionPrivacy? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.PaidReactionPrivacy + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updatePaidReactionPrivacy(Cons_updatePaidReactionPrivacy(private: _1!)) + } + else { + return nil + } + } + public static func parse_updatePeerBlocked(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updatePeerBlocked(Cons_updatePeerBlocked(flags: _1!, peerId: _2!)) + } + else { + return nil + } + } + public static func parse_updatePeerHistoryTTL(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updatePeerHistoryTTL(Cons_updatePeerHistoryTTL(flags: _1!, peer: _2!, ttlPeriod: _3)) + } + else { + return nil + } + } + public static func parse_updatePeerLocated(_ reader: BufferReader) -> Update? { + var _1: [Api.PeerLocated]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PeerLocated.self) + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updatePeerLocated(Cons_updatePeerLocated(peers: _1!)) + } + else { + return nil + } + } + public static func parse_updatePeerSettings(_ reader: BufferReader) -> Update? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _2: Api.PeerSettings? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.PeerSettings + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updatePeerSettings(Cons_updatePeerSettings(peer: _1!, settings: _2!)) + } + else { + return nil + } + } + public static func parse_updatePeerWallpaper(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: Api.WallPaper? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.WallPaper + } + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updatePeerWallpaper(Cons_updatePeerWallpaper(flags: _1!, peer: _2!, wallpaper: _3)) + } + else { + return nil + } + } + public static func parse_updatePendingJoinRequests(_ reader: BufferReader) -> Update? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _2: Int32? + _2 = reader.readInt32() + var _3: [Int64]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updatePendingJoinRequests(Cons_updatePendingJoinRequests(peer: _1!, requestsPending: _2!, recentRequesters: _3!)) + } + else { + return nil + } + } + public static func parse_updatePhoneCall(_ reader: BufferReader) -> Update? { + var _1: Api.PhoneCall? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.PhoneCall + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updatePhoneCall(Cons_updatePhoneCall(phoneCall: _1!)) + } + else { + return nil + } + } + public static func parse_updatePhoneCallSignalingData(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Buffer? + _2 = parseBytes(reader) + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updatePhoneCallSignalingData(Cons_updatePhoneCallSignalingData(phoneCallId: _1!, data: _2!)) + } + else { + return nil + } + } + public static func parse_updatePinnedChannelMessages(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: [Int32]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + var _4: Int32? + _4 = reader.readInt32() + var _5: Int32? + _5 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.Update.updatePinnedChannelMessages(Cons_updatePinnedChannelMessages(flags: _1!, channelId: _2!, messages: _3!, pts: _4!, ptsCount: _5!)) + } + else { + return nil + } + } + public static func parse_updatePinnedDialogs(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _2 = reader.readInt32() + } + var _3: [Api.DialogPeer]? + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.DialogPeer.self) + } + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updatePinnedDialogs(Cons_updatePinnedDialogs(flags: _1!, folderId: _2, order: _3)) + } + else { + return nil + } + } + public static func parse_updatePinnedForumTopic(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updatePinnedForumTopic(Cons_updatePinnedForumTopic(flags: _1!, peer: _2!, topicId: _3!)) + } + else { + return nil + } + } + public static func parse_updatePinnedForumTopics(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: [Int32]? + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updatePinnedForumTopics(Cons_updatePinnedForumTopics(flags: _1!, peer: _2!, order: _3)) + } + else { + return nil + } + } + public static func parse_updatePinnedMessages(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: [Int32]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + var _4: Int32? + _4 = reader.readInt32() + var _5: Int32? + _5 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.Update.updatePinnedMessages(Cons_updatePinnedMessages(flags: _1!, peer: _2!, messages: _3!, pts: _4!, ptsCount: _5!)) + } + else { + return nil + } + } + public static func parse_updatePinnedSavedDialogs(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.DialogPeer]? + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.DialogPeer.self) + } + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + if _c1 && _c2 { + return Api.Update.updatePinnedSavedDialogs(Cons_updatePinnedSavedDialogs(flags: _1!, order: _2)) + } + else { + return nil + } + } + public static func parse_updatePrivacy(_ reader: BufferReader) -> Update? { + var _1: Api.PrivacyKey? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.PrivacyKey + } + var _2: [Api.PrivacyRule]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PrivacyRule.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updatePrivacy(Cons_updatePrivacy(key: _1!, rules: _2!)) + } + else { + return nil + } + } + public static func parse_updatePtsChanged(_ reader: BufferReader) -> Update? { + return Api.Update.updatePtsChanged + } + public static func parse_updateQuickReplies(_ reader: BufferReader) -> Update? { + var _1: [Api.QuickReply]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.QuickReply.self) + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateQuickReplies(Cons_updateQuickReplies(quickReplies: _1!)) + } + else { + return nil + } + } + public static func parse_updateQuickReplyMessage(_ reader: BufferReader) -> Update? { + var _1: Api.Message? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Message + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateQuickReplyMessage(Cons_updateQuickReplyMessage(message: _1!)) + } + else { + return nil + } + } + public static func parse_updateReadChannelDiscussionInbox(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: Int32? + _3 = reader.readInt32() + var _4: Int32? + _4 = reader.readInt32() + var _5: Int64? + if Int(_1!) & Int(1 << 0) != 0 { + _5 = reader.readInt64() + } + var _6: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _6 = reader.readInt32() + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil + let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.Update.updateReadChannelDiscussionInbox(Cons_updateReadChannelDiscussionInbox(flags: _1!, channelId: _2!, topMsgId: _3!, readMaxId: _4!, broadcastId: _5, broadcastPost: _6)) + } + else { + return nil + } + } + public static func parse_updateReadChannelDiscussionOutbox(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateReadChannelDiscussionOutbox(Cons_updateReadChannelDiscussionOutbox(channelId: _1!, topMsgId: _2!, readMaxId: _3!)) + } + else { + return nil + } + } + public static func parse_updateReadChannelInbox(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt32() + } + var _3: Int64? + _3 = reader.readInt64() + var _4: Int32? + _4 = reader.readInt32() + var _5: Int32? + _5 = reader.readInt32() + var _6: Int32? + _6 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.Update.updateReadChannelInbox(Cons_updateReadChannelInbox(flags: _1!, folderId: _2, channelId: _3!, maxId: _4!, stillUnreadCount: _5!, pts: _6!)) + } + else { + return nil + } + } + public static func parse_updateReadChannelOutbox(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Int32? + _2 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateReadChannelOutbox(Cons_updateReadChannelOutbox(channelId: _1!, maxId: _2!)) + } + else { + return nil + } + } + public static func parse_updateReadFeaturedEmojiStickers(_ reader: BufferReader) -> Update? { + return Api.Update.updateReadFeaturedEmojiStickers + } + public static func parse_updateReadFeaturedStickers(_ reader: BufferReader) -> Update? { + return Api.Update.updateReadFeaturedStickers + } + public static func parse_updateReadHistoryInbox(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt32() + } + var _3: Api.Peer? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _4: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _4 = reader.readInt32() + } + var _5: Int32? + _5 = reader.readInt32() + var _6: Int32? + _6 = reader.readInt32() + var _7: Int32? + _7 = reader.readInt32() + var _8: Int32? + _8 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + let _c7 = _7 != nil + let _c8 = _8 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.Update.updateReadHistoryInbox(Cons_updateReadHistoryInbox(flags: _1!, folderId: _2, peer: _3!, topMsgId: _4, maxId: _5!, stillUnreadCount: _6!, pts: _7!, ptsCount: _8!)) + } + else { + return nil + } + } + public static func parse_updateReadHistoryOutbox(_ reader: BufferReader) -> Update? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + var _4: Int32? + _4 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.Update.updateReadHistoryOutbox(Cons_updateReadHistoryOutbox(peer: _1!, maxId: _2!, pts: _3!, ptsCount: _4!)) + } + else { + return nil + } + } + public static func parse_updateReadMessagesContents(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Int32]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + var _3: Int32? + _3 = reader.readInt32() + var _4: Int32? + _4 = reader.readInt32() + var _5: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _5 = reader.readInt32() + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.Update.updateReadMessagesContents(Cons_updateReadMessagesContents(flags: _1!, messages: _2!, pts: _3!, ptsCount: _4!, date: _5)) + } + else { + return nil + } + } + public static func parse_updateReadMonoForumInbox(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateReadMonoForumInbox(Cons_updateReadMonoForumInbox(channelId: _1!, savedPeerId: _2!, readMaxId: _3!)) + } + else { + return nil + } + } + public static func parse_updateReadMonoForumOutbox(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateReadMonoForumOutbox(Cons_updateReadMonoForumOutbox(channelId: _1!, savedPeerId: _2!, readMaxId: _3!)) + } + else { + return nil + } + } + public static func parse_updateReadStories(_ reader: BufferReader) -> Update? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _2: Int32? + _2 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateReadStories(Cons_updateReadStories(peer: _1!, maxId: _2!)) + } + else { + return nil + } + } + public static func parse_updateRecentEmojiStatuses(_ reader: BufferReader) -> Update? { + return Api.Update.updateRecentEmojiStatuses + } + public static func parse_updateRecentReactions(_ reader: BufferReader) -> Update? { + return Api.Update.updateRecentReactions + } + public static func parse_updateRecentStickers(_ reader: BufferReader) -> Update? { + return Api.Update.updateRecentStickers + } + public static func parse_updateSavedDialogPinned(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.DialogPeer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.DialogPeer + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateSavedDialogPinned(Cons_updateSavedDialogPinned(flags: _1!, peer: _2!)) + } + else { + return nil + } + } + public static func parse_updateSavedGifs(_ reader: BufferReader) -> Update? { + return Api.Update.updateSavedGifs + } + public static func parse_updateSavedReactionTags(_ reader: BufferReader) -> Update? { + return Api.Update.updateSavedReactionTags + } + public static func parse_updateSavedRingtones(_ reader: BufferReader) -> Update? { + return Api.Update.updateSavedRingtones + } + public static func parse_updateSentPhoneCode(_ reader: BufferReader) -> Update? { + var _1: Api.auth.SentCode? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.auth.SentCode + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateSentPhoneCode(Cons_updateSentPhoneCode(sentCode: _1!)) + } + else { + return nil + } + } + public static func parse_updateSentStoryReaction(_ reader: BufferReader) -> Update? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _2: Int32? + _2 = reader.readInt32() + var _3: Api.Reaction? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Reaction + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateSentStoryReaction(Cons_updateSentStoryReaction(peer: _1!, storyId: _2!, reaction: _3!)) + } + else { + return nil + } + } + public static func parse_updateServiceNotification(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _2 = reader.readInt32() + } + var _3: String? + _3 = parseString(reader) + var _4: String? + _4 = parseString(reader) + var _5: Api.MessageMedia? + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.MessageMedia + } + var _6: [Api.MessageEntity]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.Update.updateServiceNotification(Cons_updateServiceNotification(flags: _1!, inboxDate: _2, type: _3!, message: _4!, media: _5!, entities: _6!)) + } + else { + return nil + } + } + public static func parse_updateSmsJob(_ reader: BufferReader) -> Update? { + var _1: String? + _1 = parseString(reader) + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateSmsJob(Cons_updateSmsJob(jobId: _1!)) + } + else { + return nil + } + } + public static func parse_updateStarGiftAuctionState(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Api.StarGiftAuctionState? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.StarGiftAuctionState + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateStarGiftAuctionState(Cons_updateStarGiftAuctionState(giftId: _1!, state: _2!)) + } + else { + return nil + } + } + public static func parse_updateStarGiftAuctionUserState(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Api.StarGiftAuctionUserState? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.StarGiftAuctionUserState + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateStarGiftAuctionUserState(Cons_updateStarGiftAuctionUserState(giftId: _1!, userState: _2!)) + } + else { + return nil + } + } + public static func parse_updateStarGiftCraftFail(_ reader: BufferReader) -> Update? { + return Api.Update.updateStarGiftCraftFail + } + public static func parse_updateStarsBalance(_ reader: BufferReader) -> Update? { + var _1: Api.StarsAmount? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.StarsAmount + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateStarsBalance(Cons_updateStarsBalance(balance: _1!)) + } + else { + return nil + } + } + public static func parse_updateStarsRevenueStatus(_ reader: BufferReader) -> Update? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _2: Api.StarsRevenueStatus? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.StarsRevenueStatus + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateStarsRevenueStatus(Cons_updateStarsRevenueStatus(peer: _1!, status: _2!)) + } + else { + return nil + } + } + public static func parse_updateStickerSets(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateStickerSets(Cons_updateStickerSets(flags: _1!)) + } + else { + return nil + } + } + public static func parse_updateStickerSetsOrder(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Int64]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateStickerSetsOrder(Cons_updateStickerSetsOrder(flags: _1!, order: _2!)) + } + else { + return nil + } + } + public static func parse_updateStoriesStealthMode(_ reader: BufferReader) -> Update? { + var _1: Api.StoriesStealthMode? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.StoriesStealthMode + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateStoriesStealthMode(Cons_updateStoriesStealthMode(stealthMode: _1!)) + } + else { + return nil + } + } + public static func parse_updateStory(_ reader: BufferReader) -> Update? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _2: Api.StoryItem? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.StoryItem + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateStory(Cons_updateStory(peer: _1!, story: _2!)) + } + else { + return nil + } + } + public static func parse_updateStoryID(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateStoryID(Cons_updateStoryID(id: _1!, randomId: _2!)) + } + else { + return nil + } + } + public static func parse_updateTheme(_ reader: BufferReader) -> Update? { + var _1: Api.Theme? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Theme + } + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateTheme(Cons_updateTheme(theme: _1!)) + } + else { + return nil + } + } + public static func parse_updateTranscribedAudio(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: Int32? + _3 = reader.readInt32() + var _4: Int64? + _4 = reader.readInt64() + var _5: String? + _5 = parseString(reader) + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.Update.updateTranscribedAudio(Cons_updateTranscribedAudio(flags: _1!, peer: _2!, msgId: _3!, transcriptionId: _4!, text: _5!)) + } + else { + return nil + } + } + public static func parse_updateUser(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateUser(Cons_updateUser(userId: _1!)) + } + else { + return nil + } + } + public static func parse_updateUserEmojiStatus(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Api.EmojiStatus? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.EmojiStatus + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateUserEmojiStatus(Cons_updateUserEmojiStatus(userId: _1!, emojiStatus: _2!)) + } + else { + return nil + } + } + public static func parse_updateUserName(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: String? + _2 = parseString(reader) + var _3: String? + _3 = parseString(reader) + var _4: [Api.Username]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Username.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.Update.updateUserName(Cons_updateUserName(userId: _1!, firstName: _2!, lastName: _3!, usernames: _4!)) + } + else { + return nil + } + } + public static func parse_updateUserPhone(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: String? + _2 = parseString(reader) + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateUserPhone(Cons_updateUserPhone(userId: _1!, phone: _2!)) + } + else { + return nil + } + } + public static func parse_updateUserStatus(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Api.UserStatus? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.UserStatus + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Update.updateUserStatus(Cons_updateUserStatus(userId: _1!, status: _2!)) + } + else { + return nil + } + } + public static func parse_updateUserTyping(_ reader: BufferReader) -> Update? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } + var _4: Api.SendMessageAction? + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.SendMessageAction + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.Update.updateUserTyping(Cons_updateUserTyping(flags: _1!, userId: _2!, topMsgId: _3, action: _4!)) + } + else { + return nil + } + } + public static func parse_updateWebPage(_ reader: BufferReader) -> Update? { + var _1: Api.WebPage? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.WebPage + } + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.Update.updateWebPage(Cons_updateWebPage(webpage: _1!, pts: _2!, ptsCount: _3!)) + } + else { + return nil + } + } + public static func parse_updateWebViewResultSent(_ reader: BufferReader) -> Update? { + var _1: Int64? + _1 = reader.readInt64() + let _c1 = _1 != nil + if _c1 { + return Api.Update.updateWebViewResultSent(Cons_updateWebViewResultSent(queryId: _1!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api29.swift b/submodules/TelegramApi/Sources/Api29.swift index 7814d89e..9afe0f8f 100644 --- a/submodules/TelegramApi/Sources/Api29.swift +++ b/submodules/TelegramApi/Sources/Api29.swift @@ -1,494 +1,354 @@ public extension Api { - indirect enum WebPageAttribute: TypeConstructorDescription { - case webPageAttributeStarGiftAuction(gift: Api.StarGift, endDate: Int32) - case webPageAttributeStarGiftCollection(icons: [Api.Document]) - case webPageAttributeStickerSet(flags: Int32, stickers: [Api.Document]) - case webPageAttributeStory(flags: Int32, peer: Api.Peer, id: Int32, story: Api.StoryItem?) - case webPageAttributeTheme(flags: Int32, documents: [Api.Document]?, settings: Api.ThemeSettings?) - case webPageAttributeUniqueStarGift(gift: Api.StarGift) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .webPageAttributeStarGiftAuction(let gift, let endDate): - if boxed { - buffer.appendInt32(29770178) - } - gift.serialize(buffer, true) - serializeInt32(endDate, buffer: buffer, boxed: false) - break - case .webPageAttributeStarGiftCollection(let icons): - if boxed { - buffer.appendInt32(835375875) - } + indirect enum Updates: TypeConstructorDescription { + public class Cons_updateShort { + public var update: Api.Update + public var date: Int32 + public init(update: Api.Update, date: Int32) { + self.update = update + self.date = date + } + } + public class Cons_updateShortChatMessage { + public var flags: Int32 + public var id: Int32 + public var fromId: Int64 + public var chatId: Int64 + public var message: String + public var pts: Int32 + public var ptsCount: Int32 + public var date: Int32 + public var fwdFrom: Api.MessageFwdHeader? + public var viaBotId: Int64? + public var replyTo: Api.MessageReplyHeader? + public var entities: [Api.MessageEntity]? + public var ttlPeriod: Int32? + public init(flags: Int32, id: Int32, fromId: Int64, chatId: Int64, message: String, pts: Int32, ptsCount: Int32, date: Int32, fwdFrom: Api.MessageFwdHeader?, viaBotId: Int64?, replyTo: Api.MessageReplyHeader?, entities: [Api.MessageEntity]?, ttlPeriod: Int32?) { + self.flags = flags + self.id = id + self.fromId = fromId + self.chatId = chatId + self.message = message + self.pts = pts + self.ptsCount = ptsCount + self.date = date + self.fwdFrom = fwdFrom + self.viaBotId = viaBotId + self.replyTo = replyTo + self.entities = entities + self.ttlPeriod = ttlPeriod + } + } + public class Cons_updateShortMessage { + public var flags: Int32 + public var id: Int32 + public var userId: Int64 + public var message: String + public var pts: Int32 + public var ptsCount: Int32 + public var date: Int32 + public var fwdFrom: Api.MessageFwdHeader? + public var viaBotId: Int64? + public var replyTo: Api.MessageReplyHeader? + public var entities: [Api.MessageEntity]? + public var ttlPeriod: Int32? + public init(flags: Int32, id: Int32, userId: Int64, message: String, pts: Int32, ptsCount: Int32, date: Int32, fwdFrom: Api.MessageFwdHeader?, viaBotId: Int64?, replyTo: Api.MessageReplyHeader?, entities: [Api.MessageEntity]?, ttlPeriod: Int32?) { + self.flags = flags + self.id = id + self.userId = userId + self.message = message + self.pts = pts + self.ptsCount = ptsCount + self.date = date + self.fwdFrom = fwdFrom + self.viaBotId = viaBotId + self.replyTo = replyTo + self.entities = entities + self.ttlPeriod = ttlPeriod + } + } + public class Cons_updateShortSentMessage { + public var flags: Int32 + public var id: Int32 + public var pts: Int32 + public var ptsCount: Int32 + public var date: Int32 + public var media: Api.MessageMedia? + public var entities: [Api.MessageEntity]? + public var ttlPeriod: Int32? + public init(flags: Int32, id: Int32, pts: Int32, ptsCount: Int32, date: Int32, media: Api.MessageMedia?, entities: [Api.MessageEntity]?, ttlPeriod: Int32?) { + self.flags = flags + self.id = id + self.pts = pts + self.ptsCount = ptsCount + self.date = date + self.media = media + self.entities = entities + self.ttlPeriod = ttlPeriod + } + } + public class Cons_updates { + public var updates: [Api.Update] + public var users: [Api.User] + public var chats: [Api.Chat] + public var date: Int32 + public var seq: Int32 + public init(updates: [Api.Update], users: [Api.User], chats: [Api.Chat], date: Int32, seq: Int32) { + self.updates = updates + self.users = users + self.chats = chats + self.date = date + self.seq = seq + } + } + public class Cons_updatesCombined { + public var updates: [Api.Update] + public var users: [Api.User] + public var chats: [Api.Chat] + public var date: Int32 + public var seqStart: Int32 + public var seq: Int32 + public init(updates: [Api.Update], users: [Api.User], chats: [Api.Chat], date: Int32, seqStart: Int32, seq: Int32) { + self.updates = updates + self.users = users + self.chats = chats + self.date = date + self.seqStart = seqStart + self.seq = seq + } + } + case updateShort(Cons_updateShort) + case updateShortChatMessage(Cons_updateShortChatMessage) + case updateShortMessage(Cons_updateShortMessage) + case updateShortSentMessage(Cons_updateShortSentMessage) + case updates(Cons_updates) + case updatesCombined(Cons_updatesCombined) + case updatesTooLong + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .updateShort(let _data): + if boxed { + buffer.appendInt32(2027216577) + } + _data.update.serialize(buffer, true) + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + case .updateShortChatMessage(let _data): + if boxed { + buffer.appendInt32(1299050149) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.fromId, buffer: buffer, boxed: false) + serializeInt64(_data.chatId, buffer: buffer, boxed: false) + serializeString(_data.message, buffer: buffer, boxed: false) + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.fwdFrom!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 11) != 0 { + serializeInt64(_data.viaBotId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.replyTo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 7) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(icons.count)) - for item in icons { + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { item.serialize(buffer, true) } - break - case .webPageAttributeStickerSet(let flags, let stickers): - if boxed { - buffer.appendInt32(1355547603) - } - serializeInt32(flags, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 25) != 0 { + serializeInt32(_data.ttlPeriod!, buffer: buffer, boxed: false) + } + break + case .updateShortMessage(let _data): + if boxed { + buffer.appendInt32(826001400) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeString(_data.message, buffer: buffer, boxed: false) + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.fwdFrom!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 11) != 0 { + serializeInt64(_data.viaBotId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.replyTo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 7) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stickers.count)) - for item in stickers { + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { item.serialize(buffer, true) } - break - case .webPageAttributeStory(let flags, let peer, let id, let story): - if boxed { - buffer.appendInt32(781501415) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {story!.serialize(buffer, true)} - break - case .webPageAttributeTheme(let flags, let documents, let settings): - if boxed { - buffer.appendInt32(1421174295) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(documents!.count)) - for item in documents! { + } + if Int(_data.flags) & Int(1 << 25) != 0 { + serializeInt32(_data.ttlPeriod!, buffer: buffer, boxed: false) + } + break + case .updateShortSentMessage(let _data): + if boxed { + buffer.appendInt32(-1877614335) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 9) != 0 { + _data.media!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 7) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 1) != 0 {settings!.serialize(buffer, true)} - break - case .webPageAttributeUniqueStarGift(let gift): - if boxed { - buffer.appendInt32(-814781000) } - gift.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .webPageAttributeStarGiftAuction(let gift, let endDate): - return ("webPageAttributeStarGiftAuction", [("gift", gift as Any), ("endDate", endDate as Any)]) - case .webPageAttributeStarGiftCollection(let icons): - return ("webPageAttributeStarGiftCollection", [("icons", icons as Any)]) - case .webPageAttributeStickerSet(let flags, let stickers): - return ("webPageAttributeStickerSet", [("flags", flags as Any), ("stickers", stickers as Any)]) - case .webPageAttributeStory(let flags, let peer, let id, let story): - return ("webPageAttributeStory", [("flags", flags as Any), ("peer", peer as Any), ("id", id as Any), ("story", story as Any)]) - case .webPageAttributeTheme(let flags, let documents, let settings): - return ("webPageAttributeTheme", [("flags", flags as Any), ("documents", documents as Any), ("settings", settings as Any)]) - case .webPageAttributeUniqueStarGift(let gift): - return ("webPageAttributeUniqueStarGift", [("gift", gift as Any)]) - } - } - - public static func parse_webPageAttributeStarGiftAuction(_ reader: BufferReader) -> WebPageAttribute? { - var _1: Api.StarGift? + } + if Int(_data.flags) & Int(1 << 25) != 0 { + serializeInt32(_data.ttlPeriod!, buffer: buffer, boxed: false) + } + break + case .updates(let _data): + if boxed { + buffer.appendInt32(1957577280) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.updates.count)) + for item in _data.updates { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt32(_data.seq, buffer: buffer, boxed: false) + break + case .updatesCombined(let _data): + if boxed { + buffer.appendInt32(1918567619) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.updates.count)) + for item in _data.updates { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt32(_data.seqStart, buffer: buffer, boxed: false) + serializeInt32(_data.seq, buffer: buffer, boxed: false) + break + case .updatesTooLong: + if boxed { + buffer.appendInt32(-484987010) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .updateShort(let _data): + return ("updateShort", [("update", _data.update as Any), ("date", _data.date as Any)]) + case .updateShortChatMessage(let _data): + return ("updateShortChatMessage", [("flags", _data.flags as Any), ("id", _data.id as Any), ("fromId", _data.fromId as Any), ("chatId", _data.chatId as Any), ("message", _data.message as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any), ("date", _data.date as Any), ("fwdFrom", _data.fwdFrom as Any), ("viaBotId", _data.viaBotId as Any), ("replyTo", _data.replyTo as Any), ("entities", _data.entities as Any), ("ttlPeriod", _data.ttlPeriod as Any)]) + case .updateShortMessage(let _data): + return ("updateShortMessage", [("flags", _data.flags as Any), ("id", _data.id as Any), ("userId", _data.userId as Any), ("message", _data.message as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any), ("date", _data.date as Any), ("fwdFrom", _data.fwdFrom as Any), ("viaBotId", _data.viaBotId as Any), ("replyTo", _data.replyTo as Any), ("entities", _data.entities as Any), ("ttlPeriod", _data.ttlPeriod as Any)]) + case .updateShortSentMessage(let _data): + return ("updateShortSentMessage", [("flags", _data.flags as Any), ("id", _data.id as Any), ("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any), ("date", _data.date as Any), ("media", _data.media as Any), ("entities", _data.entities as Any), ("ttlPeriod", _data.ttlPeriod as Any)]) + case .updates(let _data): + return ("updates", [("updates", _data.updates as Any), ("users", _data.users as Any), ("chats", _data.chats as Any), ("date", _data.date as Any), ("seq", _data.seq as Any)]) + case .updatesCombined(let _data): + return ("updatesCombined", [("updates", _data.updates as Any), ("users", _data.users as Any), ("chats", _data.chats as Any), ("date", _data.date as Any), ("seqStart", _data.seqStart as Any), ("seq", _data.seq as Any)]) + case .updatesTooLong: + return ("updatesTooLong", []) + } + } + + public static func parse_updateShort(_ reader: BufferReader) -> Updates? { + var _1: Api.Update? if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.StarGift + _1 = Api.parse(reader, signature: signature) as? Api.Update } var _2: Int32? _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.WebPageAttribute.webPageAttributeStarGiftAuction(gift: _1!, endDate: _2!) - } - public static func parse_webPageAttributeStarGiftCollection(_ reader: BufferReader) -> WebPageAttribute? { - var _1: [Api.Document]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + if _c1 && _c2 { + return Api.Updates.updateShort(Cons_updateShort(update: _1!, date: _2!)) + } + else { + return nil } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.WebPageAttribute.webPageAttributeStarGiftCollection(icons: _1!) } - public static func parse_webPageAttributeStickerSet(_ reader: BufferReader) -> WebPageAttribute? { + public static func parse_updateShortChatMessage(_ reader: BufferReader) -> Updates? { var _1: Int32? _1 = reader.readInt32() - var _2: [Api.Document]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + var _2: Int32? + _2 = reader.readInt32() + var _3: Int64? + _3 = reader.readInt64() + var _4: Int64? + _4 = reader.readInt64() + var _5: String? + _5 = parseString(reader) + var _6: Int32? + _6 = reader.readInt32() + var _7: Int32? + _7 = reader.readInt32() + var _8: Int32? + _8 = reader.readInt32() + var _9: Api.MessageFwdHeader? + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.MessageFwdHeader + } } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.WebPageAttribute.webPageAttributeStickerSet(flags: _1!, stickers: _2!) - } - public static func parse_webPageAttributeStory(_ reader: BufferReader) -> WebPageAttribute? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer + var _10: Int64? + if Int(_1!) & Int(1 << 11) != 0 { + _10 = reader.readInt64() } - var _3: Int32? - _3 = reader.readInt32() - var _4: Api.StoryItem? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.StoryItem - } } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.WebPageAttribute.webPageAttributeStory(flags: _1!, peer: _2!, id: _3!, story: _4) - } - public static func parse_webPageAttributeTheme(_ reader: BufferReader) -> WebPageAttribute? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.Document]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) - } } - var _3: Api.ThemeSettings? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.ThemeSettings - } } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.WebPageAttribute.webPageAttributeTheme(flags: _1!, documents: _2, settings: _3) - } - public static func parse_webPageAttributeUniqueStarGift(_ reader: BufferReader) -> WebPageAttribute? { - var _1: Api.StarGift? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.StarGift + var _11: Api.MessageReplyHeader? + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _11 = Api.parse(reader, signature: signature) as? Api.MessageReplyHeader + } } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.WebPageAttribute.webPageAttributeUniqueStarGift(gift: _1!) - } - - } -} -public extension Api { - enum WebViewMessageSent: TypeConstructorDescription { - case webViewMessageSent(flags: Int32, msgId: Api.InputBotInlineMessageID?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .webViewMessageSent(let flags, let msgId): - if boxed { - buffer.appendInt32(211046684) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {msgId!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .webViewMessageSent(let flags, let msgId): - return ("webViewMessageSent", [("flags", flags as Any), ("msgId", msgId as Any)]) - } - } - - public static func parse_webViewMessageSent(_ reader: BufferReader) -> WebViewMessageSent? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.InputBotInlineMessageID? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.InputBotInlineMessageID - } } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.WebViewMessageSent.webViewMessageSent(flags: _1!, msgId: _2) - } - - } -} -public extension Api { - enum WebViewResult: TypeConstructorDescription { - case webViewResultUrl(flags: Int32, queryId: Int64?, url: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .webViewResultUrl(let flags, let queryId, let url): - if boxed { - buffer.appendInt32(1294139288) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(queryId!, buffer: buffer, boxed: false)} - serializeString(url, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .webViewResultUrl(let flags, let queryId, let url): - return ("webViewResultUrl", [("flags", flags as Any), ("queryId", queryId as Any), ("url", url as Any)]) - } - } - - public static func parse_webViewResultUrl(_ reader: BufferReader) -> WebViewResult? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt64() } - var _3: String? - _3 = parseString(reader) - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.WebViewResult.webViewResultUrl(flags: _1!, queryId: _2, url: _3!) - } - - } -} -public extension Api.account { - enum AuthorizationForm: TypeConstructorDescription { - case authorizationForm(flags: Int32, requiredTypes: [Api.SecureRequiredType], values: [Api.SecureValue], errors: [Api.SecureValueError], users: [Api.User], privacyPolicyUrl: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .authorizationForm(let flags, let requiredTypes, let values, let errors, let users, let privacyPolicyUrl): - if boxed { - buffer.appendInt32(-1389486888) - } - serializeInt32(flags, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(requiredTypes.count)) - for item in requiredTypes { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(values.count)) - for item in values { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(errors.count)) - for item in errors { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 0) != 0 {serializeString(privacyPolicyUrl!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .authorizationForm(let flags, let requiredTypes, let values, let errors, let users, let privacyPolicyUrl): - return ("authorizationForm", [("flags", flags as Any), ("requiredTypes", requiredTypes as Any), ("values", values as Any), ("errors", errors as Any), ("users", users as Any), ("privacyPolicyUrl", privacyPolicyUrl as Any)]) - } - } - - public static func parse_authorizationForm(_ reader: BufferReader) -> AuthorizationForm? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.SecureRequiredType]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureRequiredType.self) + var _12: [Api.MessageEntity]? + if Int(_1!) & Int(1 << 7) != 0 { + if let _ = reader.readInt32() { + _12 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } } - var _3: [Api.SecureValue]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureValue.self) - } - var _4: [Api.SecureValueError]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureValueError.self) - } - var _5: [Api.User]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - var _6: String? - if Int(_1!) & Int(1 << 0) != 0 {_6 = parseString(reader) } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.account.AuthorizationForm.authorizationForm(flags: _1!, requiredTypes: _2!, values: _3!, errors: _4!, users: _5!, privacyPolicyUrl: _6) - } - - } -} -public extension Api.account { - enum Authorizations: TypeConstructorDescription { - case authorizations(authorizationTtlDays: Int32, authorizations: [Api.Authorization]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .authorizations(let authorizationTtlDays, let authorizations): - if boxed { - buffer.appendInt32(1275039392) - } - serializeInt32(authorizationTtlDays, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(authorizations.count)) - for item in authorizations { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .authorizations(let authorizationTtlDays, let authorizations): - return ("authorizations", [("authorizationTtlDays", authorizationTtlDays as Any), ("authorizations", authorizations as Any)]) - } - } - - public static func parse_authorizations(_ reader: BufferReader) -> Authorizations? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.Authorization]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Authorization.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.account.Authorizations.authorizations(authorizationTtlDays: _1!, authorizations: _2!) - } - - } -} -public extension Api.account { - enum AutoDownloadSettings: TypeConstructorDescription { - case autoDownloadSettings(low: Api.AutoDownloadSettings, medium: Api.AutoDownloadSettings, high: Api.AutoDownloadSettings) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .autoDownloadSettings(let low, let medium, let high): - if boxed { - buffer.appendInt32(1674235686) - } - low.serialize(buffer, true) - medium.serialize(buffer, true) - high.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .autoDownloadSettings(let low, let medium, let high): - return ("autoDownloadSettings", [("low", low as Any), ("medium", medium as Any), ("high", high as Any)]) - } - } - - public static func parse_autoDownloadSettings(_ reader: BufferReader) -> AutoDownloadSettings? { - var _1: Api.AutoDownloadSettings? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.AutoDownloadSettings - } - var _2: Api.AutoDownloadSettings? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.AutoDownloadSettings - } - var _3: Api.AutoDownloadSettings? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.AutoDownloadSettings - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.account.AutoDownloadSettings.autoDownloadSettings(low: _1!, medium: _2!, high: _3!) - } - - } -} -public extension Api.account { - enum AutoSaveSettings: TypeConstructorDescription { - case autoSaveSettings(usersSettings: Api.AutoSaveSettings, chatsSettings: Api.AutoSaveSettings, broadcastsSettings: Api.AutoSaveSettings, exceptions: [Api.AutoSaveException], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .autoSaveSettings(let usersSettings, let chatsSettings, let broadcastsSettings, let exceptions, let chats, let users): - if boxed { - buffer.appendInt32(1279133341) - } - usersSettings.serialize(buffer, true) - chatsSettings.serialize(buffer, true) - broadcastsSettings.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(exceptions.count)) - for item in exceptions { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .autoSaveSettings(let usersSettings, let chatsSettings, let broadcastsSettings, let exceptions, let chats, let users): - return ("autoSaveSettings", [("usersSettings", usersSettings as Any), ("chatsSettings", chatsSettings as Any), ("broadcastsSettings", broadcastsSettings as Any), ("exceptions", exceptions as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_autoSaveSettings(_ reader: BufferReader) -> AutoSaveSettings? { - var _1: Api.AutoSaveSettings? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.AutoSaveSettings - } - var _2: Api.AutoSaveSettings? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.AutoSaveSettings - } - var _3: Api.AutoSaveSettings? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.AutoSaveSettings - } - var _4: [Api.AutoSaveException]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.AutoSaveException.self) - } - var _5: [Api.Chat]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _6: [Api.User]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + var _13: Int32? + if Int(_1!) & Int(1 << 25) != 0 { + _13 = reader.readInt32() } let _c1 = _1 != nil let _c2 = _2 != nil @@ -496,846 +356,2294 @@ public extension Api.account { let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.account.AutoSaveSettings.autoSaveSettings(usersSettings: _1!, chatsSettings: _2!, broadcastsSettings: _3!, exceptions: _4!, chats: _5!, users: _6!) + let _c7 = _7 != nil + let _c8 = _8 != nil + let _c9 = (Int(_1!) & Int(1 << 2) == 0) || _9 != nil + let _c10 = (Int(_1!) & Int(1 << 11) == 0) || _10 != nil + let _c11 = (Int(_1!) & Int(1 << 3) == 0) || _11 != nil + let _c12 = (Int(_1!) & Int(1 << 7) == 0) || _12 != nil + let _c13 = (Int(_1!) & Int(1 << 25) == 0) || _13 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 { + return Api.Updates.updateShortChatMessage(Cons_updateShortChatMessage(flags: _1!, id: _2!, fromId: _3!, chatId: _4!, message: _5!, pts: _6!, ptsCount: _7!, date: _8!, fwdFrom: _9, viaBotId: _10, replyTo: _11, entities: _12, ttlPeriod: _13)) + } + else { + return nil + } } - - } -} -public extension Api.account { - enum BusinessChatLinks: TypeConstructorDescription { - case businessChatLinks(links: [Api.BusinessChatLink], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .businessChatLinks(let links, let chats, let users): - if boxed { - buffer.appendInt32(-331111727) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(links.count)) - for item in links { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .businessChatLinks(let links, let chats, let users): - return ("businessChatLinks", [("links", links as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_businessChatLinks(_ reader: BufferReader) -> BusinessChatLinks? { - var _1: [Api.BusinessChatLink]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.BusinessChatLink.self) - } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.account.BusinessChatLinks.businessChatLinks(links: _1!, chats: _2!, users: _3!) - } - - } -} -public extension Api.account { - enum ChatThemes: TypeConstructorDescription { - case chatThemes(flags: Int32, hash: Int64, themes: [Api.ChatTheme], chats: [Api.Chat], users: [Api.User], nextOffset: String?) - case chatThemesNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatThemes(let flags, let hash, let themes, let chats, let users, let nextOffset): - if boxed { - buffer.appendInt32(-1106673293) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(themes.count)) - for item in themes { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 0) != 0 {serializeString(nextOffset!, buffer: buffer, boxed: false)} - break - case .chatThemesNotModified: - if boxed { - buffer.appendInt32(-535699004) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatThemes(let flags, let hash, let themes, let chats, let users, let nextOffset): - return ("chatThemes", [("flags", flags as Any), ("hash", hash as Any), ("themes", themes as Any), ("chats", chats as Any), ("users", users as Any), ("nextOffset", nextOffset as Any)]) - case .chatThemesNotModified: - return ("chatThemesNotModified", []) - } - } - - public static func parse_chatThemes(_ reader: BufferReader) -> ChatThemes? { + public static func parse_updateShortMessage(_ reader: BufferReader) -> Updates? { var _1: Int32? _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: [Api.ChatTheme]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ChatTheme.self) + var _2: Int32? + _2 = reader.readInt32() + var _3: Int64? + _3 = reader.readInt64() + var _4: String? + _4 = parseString(reader) + var _5: Int32? + _5 = reader.readInt32() + var _6: Int32? + _6 = reader.readInt32() + var _7: Int32? + _7 = reader.readInt32() + var _8: Api.MessageFwdHeader? + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.MessageFwdHeader + } } - var _4: [Api.Chat]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + var _9: Int64? + if Int(_1!) & Int(1 << 11) != 0 { + _9 = reader.readInt64() } - var _5: [Api.User]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + var _10: Api.MessageReplyHeader? + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _10 = Api.parse(reader, signature: signature) as? Api.MessageReplyHeader + } + } + var _11: [Api.MessageEntity]? + if Int(_1!) & Int(1 << 7) != 0 { + if let _ = reader.readInt32() { + _11 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } + var _12: Int32? + if Int(_1!) & Int(1 << 25) != 0 { + _12 = reader.readInt32() } - var _6: String? - if Int(_1!) & Int(1 << 0) != 0 {_6 = parseString(reader) } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.account.ChatThemes.chatThemes(flags: _1!, hash: _2!, themes: _3!, chats: _4!, users: _5!, nextOffset: _6) + let _c6 = _6 != nil + let _c7 = _7 != nil + let _c8 = (Int(_1!) & Int(1 << 2) == 0) || _8 != nil + let _c9 = (Int(_1!) & Int(1 << 11) == 0) || _9 != nil + let _c10 = (Int(_1!) & Int(1 << 3) == 0) || _10 != nil + let _c11 = (Int(_1!) & Int(1 << 7) == 0) || _11 != nil + let _c12 = (Int(_1!) & Int(1 << 25) == 0) || _12 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 { + return Api.Updates.updateShortMessage(Cons_updateShortMessage(flags: _1!, id: _2!, userId: _3!, message: _4!, pts: _5!, ptsCount: _6!, date: _7!, fwdFrom: _8, viaBotId: _9, replyTo: _10, entities: _11, ttlPeriod: _12)) + } + else { + return nil + } } - public static func parse_chatThemesNotModified(_ reader: BufferReader) -> ChatThemes? { - return Api.account.ChatThemes.chatThemesNotModified + public static func parse_updateShortSentMessage(_ reader: BufferReader) -> Updates? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + var _4: Int32? + _4 = reader.readInt32() + var _5: Int32? + _5 = reader.readInt32() + var _6: Api.MessageMedia? + if Int(_1!) & Int(1 << 9) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.MessageMedia + } + } + var _7: [Api.MessageEntity]? + if Int(_1!) & Int(1 << 7) != 0 { + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } + var _8: Int32? + if Int(_1!) & Int(1 << 25) != 0 { + _8 = reader.readInt32() + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = (Int(_1!) & Int(1 << 9) == 0) || _6 != nil + let _c7 = (Int(_1!) & Int(1 << 7) == 0) || _7 != nil + let _c8 = (Int(_1!) & Int(1 << 25) == 0) || _8 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.Updates.updateShortSentMessage(Cons_updateShortSentMessage(flags: _1!, id: _2!, pts: _3!, ptsCount: _4!, date: _5!, media: _6, entities: _7, ttlPeriod: _8)) + } + else { + return nil + } } - - } -} -public extension Api.account { - enum ConnectedBots: TypeConstructorDescription { - case connectedBots(connectedBots: [Api.ConnectedBot], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .connectedBots(let connectedBots, let users): - if boxed { - buffer.appendInt32(400029819) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(connectedBots.count)) - for item in connectedBots { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .connectedBots(let connectedBots, let users): - return ("connectedBots", [("connectedBots", connectedBots as Any), ("users", users as Any)]) - } - } - - public static func parse_connectedBots(_ reader: BufferReader) -> ConnectedBots? { - var _1: [Api.ConnectedBot]? + public static func parse_updates(_ reader: BufferReader) -> Updates? { + var _1: [Api.Update]? if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ConnectedBot.self) + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Update.self) } var _2: [Api.User]? if let _ = reader.readInt32() { _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.account.ConnectedBots.connectedBots(connectedBots: _1!, users: _2!) - } - - } -} -public extension Api.account { - enum ContentSettings: TypeConstructorDescription { - case contentSettings(flags: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .contentSettings(let flags): - if boxed { - buffer.appendInt32(1474462241) - } - serializeInt32(flags, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .contentSettings(let flags): - return ("contentSettings", [("flags", flags as Any)]) - } - } - - public static func parse_contentSettings(_ reader: BufferReader) -> ContentSettings? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.account.ContentSettings.contentSettings(flags: _1!) - } - - } -} -public extension Api.account { - enum EmailVerified: TypeConstructorDescription { - case emailVerified(email: String) - case emailVerifiedLogin(email: String, sentCode: Api.auth.SentCode) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .emailVerified(let email): - if boxed { - buffer.appendInt32(731303195) - } - serializeString(email, buffer: buffer, boxed: false) - break - case .emailVerifiedLogin(let email, let sentCode): - if boxed { - buffer.appendInt32(-507835039) - } - serializeString(email, buffer: buffer, boxed: false) - sentCode.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .emailVerified(let email): - return ("emailVerified", [("email", email as Any)]) - case .emailVerifiedLogin(let email, let sentCode): - return ("emailVerifiedLogin", [("email", email as Any), ("sentCode", sentCode as Any)]) - } - } - - public static func parse_emailVerified(_ reader: BufferReader) -> EmailVerified? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.account.EmailVerified.emailVerified(email: _1!) - } - public static func parse_emailVerifiedLogin(_ reader: BufferReader) -> EmailVerified? { - var _1: String? - _1 = parseString(reader) - var _2: Api.auth.SentCode? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.auth.SentCode - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.account.EmailVerified.emailVerifiedLogin(email: _1!, sentCode: _2!) - } - - } -} -public extension Api.account { - enum EmojiStatuses: TypeConstructorDescription { - case emojiStatuses(hash: Int64, statuses: [Api.EmojiStatus]) - case emojiStatusesNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .emojiStatuses(let hash, let statuses): - if boxed { - buffer.appendInt32(-1866176559) - } - serializeInt64(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(statuses.count)) - for item in statuses { - item.serialize(buffer, true) - } - break - case .emojiStatusesNotModified: - if boxed { - buffer.appendInt32(-796072379) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .emojiStatuses(let hash, let statuses): - return ("emojiStatuses", [("hash", hash as Any), ("statuses", statuses as Any)]) - case .emojiStatusesNotModified: - return ("emojiStatusesNotModified", []) - } - } - - public static func parse_emojiStatuses(_ reader: BufferReader) -> EmojiStatuses? { - var _1: Int64? - _1 = reader.readInt64() - var _2: [Api.EmojiStatus]? + var _3: [Api.Chat]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.EmojiStatus.self) + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) } + var _4: Int32? + _4 = reader.readInt32() + var _5: Int32? + _5 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.account.EmojiStatuses.emojiStatuses(hash: _1!, statuses: _2!) - } - public static func parse_emojiStatusesNotModified(_ reader: BufferReader) -> EmojiStatuses? { - return Api.account.EmojiStatuses.emojiStatusesNotModified - } - - } -} -public extension Api.account { - enum PaidMessagesRevenue: TypeConstructorDescription { - case paidMessagesRevenue(starsAmount: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .paidMessagesRevenue(let starsAmount): - if boxed { - buffer.appendInt32(504403720) - } - serializeInt64(starsAmount, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .paidMessagesRevenue(let starsAmount): - return ("paidMessagesRevenue", [("starsAmount", starsAmount as Any)]) - } - } - - public static func parse_paidMessagesRevenue(_ reader: BufferReader) -> PaidMessagesRevenue? { - var _1: Int64? - _1 = reader.readInt64() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.account.PaidMessagesRevenue.paidMessagesRevenue(starsAmount: _1!) - } - - } -} -public extension Api.account { - enum PasskeyRegistrationOptions: TypeConstructorDescription { - case passkeyRegistrationOptions(options: Api.DataJSON) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .passkeyRegistrationOptions(let options): - if boxed { - buffer.appendInt32(-513057567) - } - options.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .passkeyRegistrationOptions(let options): - return ("passkeyRegistrationOptions", [("options", options as Any)]) - } - } - - public static func parse_passkeyRegistrationOptions(_ reader: BufferReader) -> PasskeyRegistrationOptions? { - var _1: Api.DataJSON? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.DataJSON + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.Updates.updates(Cons_updates(updates: _1!, users: _2!, chats: _3!, date: _4!, seq: _5!)) + } + else { + return nil } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.account.PasskeyRegistrationOptions.passkeyRegistrationOptions(options: _1!) } - - } -} -public extension Api.account { - enum Passkeys: TypeConstructorDescription { - case passkeys(passkeys: [Api.Passkey]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .passkeys(let passkeys): - if boxed { - buffer.appendInt32(-119494116) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(passkeys.count)) - for item in passkeys { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .passkeys(let passkeys): - return ("passkeys", [("passkeys", passkeys as Any)]) - } - } - - public static func parse_passkeys(_ reader: BufferReader) -> Passkeys? { - var _1: [Api.Passkey]? + public static func parse_updatesCombined(_ reader: BufferReader) -> Updates? { + var _1: [Api.Update]? if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Passkey.self) + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Update.self) } + var _2: [Api.User]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + var _3: [Api.Chat]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _4: Int32? + _4 = reader.readInt32() + var _5: Int32? + _5 = reader.readInt32() + var _6: Int32? + _6 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.account.Passkeys.passkeys(passkeys: _1!) + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.Updates.updatesCombined(Cons_updatesCombined(updates: _1!, users: _2!, chats: _3!, date: _4!, seqStart: _5!, seq: _6!)) + } + else { + return nil + } + } + public static func parse_updatesTooLong(_ reader: BufferReader) -> Updates? { + return Api.Updates.updatesTooLong } - } } -public extension Api.account { - enum Password: TypeConstructorDescription { - case password(flags: Int32, currentAlgo: Api.PasswordKdfAlgo?, srpB: Buffer?, srpId: Int64?, hint: String?, emailUnconfirmedPattern: String?, newAlgo: Api.PasswordKdfAlgo, newSecureAlgo: Api.SecurePasswordKdfAlgo, secureRandom: Buffer, pendingResetDate: Int32?, loginEmailPattern: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .password(let flags, let currentAlgo, let srpB, let srpId, let hint, let emailUnconfirmedPattern, let newAlgo, let newSecureAlgo, let secureRandom, let pendingResetDate, let loginEmailPattern): - if boxed { - buffer.appendInt32(-1787080453) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {currentAlgo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeBytes(srpB!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt64(srpId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeString(hint!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeString(emailUnconfirmedPattern!, buffer: buffer, boxed: false)} - newAlgo.serialize(buffer, true) - newSecureAlgo.serialize(buffer, true) - serializeBytes(secureRandom, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 5) != 0 {serializeInt32(pendingResetDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 6) != 0 {serializeString(loginEmailPattern!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .password(let flags, let currentAlgo, let srpB, let srpId, let hint, let emailUnconfirmedPattern, let newAlgo, let newSecureAlgo, let secureRandom, let pendingResetDate, let loginEmailPattern): - return ("password", [("flags", flags as Any), ("currentAlgo", currentAlgo as Any), ("srpB", srpB as Any), ("srpId", srpId as Any), ("hint", hint as Any), ("emailUnconfirmedPattern", emailUnconfirmedPattern as Any), ("newAlgo", newAlgo as Any), ("newSecureAlgo", newSecureAlgo as Any), ("secureRandom", secureRandom as Any), ("pendingResetDate", pendingResetDate as Any), ("loginEmailPattern", loginEmailPattern as Any)]) - } - } - - public static func parse_password(_ reader: BufferReader) -> Password? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.PasswordKdfAlgo? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.PasswordKdfAlgo - } } - var _3: Buffer? - if Int(_1!) & Int(1 << 2) != 0 {_3 = parseBytes(reader) } - var _4: Int64? - if Int(_1!) & Int(1 << 2) != 0 {_4 = reader.readInt64() } - var _5: String? - if Int(_1!) & Int(1 << 3) != 0 {_5 = parseString(reader) } - var _6: String? - if Int(_1!) & Int(1 << 4) != 0 {_6 = parseString(reader) } - var _7: Api.PasswordKdfAlgo? - if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.PasswordKdfAlgo +public extension Api { + enum UrlAuthResult: TypeConstructorDescription { + public class Cons_urlAuthResultAccepted { + public var flags: Int32 + public var url: String? + public init(flags: Int32, url: String?) { + self.flags = flags + self.url = url } - var _8: Api.SecurePasswordKdfAlgo? - if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.SecurePasswordKdfAlgo + } + public class Cons_urlAuthResultRequest { + public var flags: Int32 + public var bot: Api.User + public var domain: String + public var browser: String? + public var platform: String? + public var ip: String? + public var region: String? + public init(flags: Int32, bot: Api.User, domain: String, browser: String?, platform: String?, ip: String?, region: String?) { + self.flags = flags + self.bot = bot + self.domain = domain + self.browser = browser + self.platform = platform + self.ip = ip + self.region = region } - var _9: Buffer? - _9 = parseBytes(reader) - var _10: Int32? - if Int(_1!) & Int(1 << 5) != 0 {_10 = reader.readInt32() } - var _11: String? - if Int(_1!) & Int(1 << 6) != 0 {_11 = parseString(reader) } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 2) == 0) || _2 != nil - let _c3 = (Int(_1!) & Int(1 << 2) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 3) == 0) || _5 != nil - let _c6 = (Int(_1!) & Int(1 << 4) == 0) || _6 != nil - let _c7 = _7 != nil - let _c8 = _8 != nil - let _c9 = _9 != nil - let _c10 = (Int(_1!) & Int(1 << 5) == 0) || _10 != nil - let _c11 = (Int(_1!) & Int(1 << 6) == 0) || _11 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - return Api.account.Password.password(flags: _1!, currentAlgo: _2, srpB: _3, srpId: _4, hint: _5, emailUnconfirmedPattern: _6, newAlgo: _7!, newSecureAlgo: _8!, secureRandom: _9!, pendingResetDate: _10, loginEmailPattern: _11) } - - } -} -public extension Api.account { - enum PasswordInputSettings: TypeConstructorDescription { - case passwordInputSettings(flags: Int32, newAlgo: Api.PasswordKdfAlgo?, newPasswordHash: Buffer?, hint: String?, email: String?, newSecureSettings: Api.SecureSecretSettings?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .passwordInputSettings(let flags, let newAlgo, let newPasswordHash, let hint, let email, let newSecureSettings): - if boxed { - buffer.appendInt32(-1036572727) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {newAlgo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 0) != 0 {serializeBytes(newPasswordHash!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeString(hint!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(email!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {newSecureSettings!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .passwordInputSettings(let flags, let newAlgo, let newPasswordHash, let hint, let email, let newSecureSettings): - return ("passwordInputSettings", [("flags", flags as Any), ("newAlgo", newAlgo as Any), ("newPasswordHash", newPasswordHash as Any), ("hint", hint as Any), ("email", email as Any), ("newSecureSettings", newSecureSettings as Any)]) - } - } - - public static func parse_passwordInputSettings(_ reader: BufferReader) -> PasswordInputSettings? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.PasswordKdfAlgo? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.PasswordKdfAlgo - } } - var _3: Buffer? - if Int(_1!) & Int(1 << 0) != 0 {_3 = parseBytes(reader) } - var _4: String? - if Int(_1!) & Int(1 << 0) != 0 {_4 = parseString(reader) } - var _5: String? - if Int(_1!) & Int(1 << 1) != 0 {_5 = parseString(reader) } - var _6: Api.SecureSecretSettings? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.SecureSecretSettings - } } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.account.PasswordInputSettings.passwordInputSettings(flags: _1!, newAlgo: _2, newPasswordHash: _3, hint: _4, email: _5, newSecureSettings: _6) + case urlAuthResultAccepted(Cons_urlAuthResultAccepted) + case urlAuthResultDefault + case urlAuthResultRequest(Cons_urlAuthResultRequest) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .urlAuthResultAccepted(let _data): + if boxed { + buffer.appendInt32(1648005024) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.url!, buffer: buffer, boxed: false) + } + break + case .urlAuthResultDefault: + if boxed { + buffer.appendInt32(-1445536993) + } + break + case .urlAuthResultRequest(let _data): + if boxed { + buffer.appendInt32(855293722) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.bot.serialize(buffer, true) + serializeString(_data.domain, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.browser!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.platform!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.ip!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.region!, buffer: buffer, boxed: false) + } + break + } } - - } -} -public extension Api.account { - enum PasswordSettings: TypeConstructorDescription { - case passwordSettings(flags: Int32, email: String?, secureSettings: Api.SecureSecretSettings?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .passwordSettings(let flags, let email, let secureSettings): - if boxed { - buffer.appendInt32(-1705233435) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(email!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {secureSettings!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .passwordSettings(let flags, let email, let secureSettings): - return ("passwordSettings", [("flags", flags as Any), ("email", email as Any), ("secureSettings", secureSettings as Any)]) - } - } - - public static func parse_passwordSettings(_ reader: BufferReader) -> PasswordSettings? { + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .urlAuthResultAccepted(let _data): + return ("urlAuthResultAccepted", [("flags", _data.flags as Any), ("url", _data.url as Any)]) + case .urlAuthResultDefault: + return ("urlAuthResultDefault", []) + case .urlAuthResultRequest(let _data): + return ("urlAuthResultRequest", [("flags", _data.flags as Any), ("bot", _data.bot as Any), ("domain", _data.domain as Any), ("browser", _data.browser as Any), ("platform", _data.platform as Any), ("ip", _data.ip as Any), ("region", _data.region as Any)]) + } + } + + public static func parse_urlAuthResultAccepted(_ reader: BufferReader) -> UrlAuthResult? { var _1: Int32? _1 = reader.readInt32() var _2: String? - if Int(_1!) & Int(1 << 0) != 0 {_2 = parseString(reader) } - var _3: Api.SecureSecretSettings? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.SecureSecretSettings - } } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = parseString(reader) + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.account.PasswordSettings.passwordSettings(flags: _1!, email: _2, secureSettings: _3) + if _c1 && _c2 { + return Api.UrlAuthResult.urlAuthResultAccepted(Cons_urlAuthResultAccepted(flags: _1!, url: _2)) + } + else { + return nil + } } - - } -} -public extension Api.account { - enum PrivacyRules: TypeConstructorDescription { - case privacyRules(rules: [Api.PrivacyRule], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .privacyRules(let rules, let chats, let users): - if boxed { - buffer.appendInt32(1352683077) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(rules.count)) - for item in rules { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .privacyRules(let rules, let chats, let users): - return ("privacyRules", [("rules", rules as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_privacyRules(_ reader: BufferReader) -> PrivacyRules? { - var _1: [Api.PrivacyRule]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PrivacyRule.self) + public static func parse_urlAuthResultDefault(_ reader: BufferReader) -> UrlAuthResult? { + return Api.UrlAuthResult.urlAuthResultDefault + } + public static func parse_urlAuthResultRequest(_ reader: BufferReader) -> UrlAuthResult? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.User? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.User } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + var _3: String? + _3 = parseString(reader) + var _4: String? + if Int(_1!) & Int(1 << 2) != 0 { + _4 = parseString(reader) } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + var _5: String? + if Int(_1!) & Int(1 << 2) != 0 { + _5 = parseString(reader) + } + var _6: String? + if Int(_1!) & Int(1 << 2) != 0 { + _6 = parseString(reader) + } + var _7: String? + if Int(_1!) & Int(1 << 2) != 0 { + _7 = parseString(reader) } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.account.PrivacyRules.privacyRules(rules: _1!, chats: _2!, users: _3!) + let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil + let _c5 = (Int(_1!) & Int(1 << 2) == 0) || _5 != nil + let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil + let _c7 = (Int(_1!) & Int(1 << 2) == 0) || _7 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.UrlAuthResult.urlAuthResultRequest(Cons_urlAuthResultRequest(flags: _1!, bot: _2!, domain: _3!, browser: _4, platform: _5, ip: _6, region: _7)) + } + else { + return nil + } } - } } -public extension Api.account { - enum ResetPasswordResult: TypeConstructorDescription { - case resetPasswordFailedWait(retryDate: Int32) - case resetPasswordOk - case resetPasswordRequestedWait(untilDate: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .resetPasswordFailedWait(let retryDate): - if boxed { - buffer.appendInt32(-478701471) - } - serializeInt32(retryDate, buffer: buffer, boxed: false) - break - case .resetPasswordOk: - if boxed { - buffer.appendInt32(-383330754) - } - - break - case .resetPasswordRequestedWait(let untilDate): - if boxed { - buffer.appendInt32(-370148227) - } - serializeInt32(untilDate, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .resetPasswordFailedWait(let retryDate): - return ("resetPasswordFailedWait", [("retryDate", retryDate as Any)]) - case .resetPasswordOk: - return ("resetPasswordOk", []) - case .resetPasswordRequestedWait(let untilDate): - return ("resetPasswordRequestedWait", [("untilDate", untilDate as Any)]) - } - } - - public static func parse_resetPasswordFailedWait(_ reader: BufferReader) -> ResetPasswordResult? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.account.ResetPasswordResult.resetPasswordFailedWait(retryDate: _1!) - } - public static func parse_resetPasswordOk(_ reader: BufferReader) -> ResetPasswordResult? { - return Api.account.ResetPasswordResult.resetPasswordOk - } - public static func parse_resetPasswordRequestedWait(_ reader: BufferReader) -> ResetPasswordResult? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.account.ResetPasswordResult.resetPasswordRequestedWait(untilDate: _1!) - } - - } -} -public extension Api.account { - enum ResolvedBusinessChatLinks: TypeConstructorDescription { - case resolvedBusinessChatLinks(flags: Int32, peer: Api.Peer, message: String, entities: [Api.MessageEntity]?, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .resolvedBusinessChatLinks(let flags, let peer, let message, let entities, let chats, let users): - if boxed { - buffer.appendInt32(-1708937439) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { - item.serialize(buffer, true) - }} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .resolvedBusinessChatLinks(let flags, let peer, let message, let entities, let chats, let users): - return ("resolvedBusinessChatLinks", [("flags", flags as Any), ("peer", peer as Any), ("message", message as Any), ("entities", entities as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_resolvedBusinessChatLinks(_ reader: BufferReader) -> ResolvedBusinessChatLinks? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.Peer? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer +public extension Api { + enum User: TypeConstructorDescription { + public class Cons_user { + public var flags: Int32 + public var flags2: Int32 + public var id: Int64 + public var accessHash: Int64? + public var firstName: String? + public var lastName: String? + public var username: String? + public var phone: String? + public var photo: Api.UserProfilePhoto? + public var status: Api.UserStatus? + public var botInfoVersion: Int32? + public var restrictionReason: [Api.RestrictionReason]? + public var botInlinePlaceholder: String? + public var langCode: String? + public var emojiStatus: Api.EmojiStatus? + public var usernames: [Api.Username]? + public var storiesMaxId: Api.RecentStory? + public var color: Api.PeerColor? + public var profileColor: Api.PeerColor? + public var botActiveUsers: Int32? + public var botVerificationIcon: Int64? + public var sendPaidMessagesStars: Int64? + public init(flags: Int32, flags2: Int32, id: Int64, accessHash: Int64?, firstName: String?, lastName: String?, username: String?, phone: String?, photo: Api.UserProfilePhoto?, status: Api.UserStatus?, botInfoVersion: Int32?, restrictionReason: [Api.RestrictionReason]?, botInlinePlaceholder: String?, langCode: String?, emojiStatus: Api.EmojiStatus?, usernames: [Api.Username]?, storiesMaxId: Api.RecentStory?, color: Api.PeerColor?, profileColor: Api.PeerColor?, botActiveUsers: Int32?, botVerificationIcon: Int64?, sendPaidMessagesStars: Int64?) { + self.flags = flags + self.flags2 = flags2 + self.id = id + self.accessHash = accessHash + self.firstName = firstName + self.lastName = lastName + self.username = username + self.phone = phone + self.photo = photo + self.status = status + self.botInfoVersion = botInfoVersion + self.restrictionReason = restrictionReason + self.botInlinePlaceholder = botInlinePlaceholder + self.langCode = langCode + self.emojiStatus = emojiStatus + self.usernames = usernames + self.storiesMaxId = storiesMaxId + self.color = color + self.profileColor = profileColor + self.botActiveUsers = botActiveUsers + self.botVerificationIcon = botVerificationIcon + self.sendPaidMessagesStars = sendPaidMessagesStars } - var _3: String? - _3 = parseString(reader) - var _4: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } - var _5: [Api.Chat]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + public class Cons_userEmpty { + public var id: Int64 + public init(id: Int64) { + self.id = id } - var _6: [Api.User]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + case user(Cons_user) + case userEmpty(Cons_userEmpty) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .user(let _data): + if boxed { + buffer.appendInt32(829899656) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.flags2, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.accessHash!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.firstName!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.lastName!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.username!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeString(_data.phone!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + _data.photo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + _data.status!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 14) != 0 { + serializeInt32(_data.botInfoVersion!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 18) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.restrictionReason!.count)) + for item in _data.restrictionReason! { + item.serialize(buffer, true) + } + } + if Int(_data.flags) & Int(1 << 19) != 0 { + serializeString(_data.botInlinePlaceholder!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 22) != 0 { + serializeString(_data.langCode!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 30) != 0 { + _data.emojiStatus!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.usernames!.count)) + for item in _data.usernames! { + item.serialize(buffer, true) + } + } + if Int(_data.flags2) & Int(1 << 5) != 0 { + _data.storiesMaxId!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 8) != 0 { + _data.color!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 9) != 0 { + _data.profileColor!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 12) != 0 { + serializeInt32(_data.botActiveUsers!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 14) != 0 { + serializeInt64(_data.botVerificationIcon!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 15) != 0 { + serializeInt64(_data.sendPaidMessagesStars!, buffer: buffer, boxed: false) + } + break + case .userEmpty(let _data): + if boxed { + buffer.appendInt32(-742634630) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .user(let _data): + return ("user", [("flags", _data.flags as Any), ("flags2", _data.flags2 as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("firstName", _data.firstName as Any), ("lastName", _data.lastName as Any), ("username", _data.username as Any), ("phone", _data.phone as Any), ("photo", _data.photo as Any), ("status", _data.status as Any), ("botInfoVersion", _data.botInfoVersion as Any), ("restrictionReason", _data.restrictionReason as Any), ("botInlinePlaceholder", _data.botInlinePlaceholder as Any), ("langCode", _data.langCode as Any), ("emojiStatus", _data.emojiStatus as Any), ("usernames", _data.usernames as Any), ("storiesMaxId", _data.storiesMaxId as Any), ("color", _data.color as Any), ("profileColor", _data.profileColor as Any), ("botActiveUsers", _data.botActiveUsers as Any), ("botVerificationIcon", _data.botVerificationIcon as Any), ("sendPaidMessagesStars", _data.sendPaidMessagesStars as Any)]) + case .userEmpty(let _data): + return ("userEmpty", [("id", _data.id as Any)]) + } + } + + public static func parse_user(_ reader: BufferReader) -> User? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int64? + _3 = reader.readInt64() + var _4: Int64? + if Int(_1!) & Int(1 << 0) != 0 { + _4 = reader.readInt64() + } + var _5: String? + if Int(_1!) & Int(1 << 1) != 0 { + _5 = parseString(reader) + } + var _6: String? + if Int(_1!) & Int(1 << 2) != 0 { + _6 = parseString(reader) + } + var _7: String? + if Int(_1!) & Int(1 << 3) != 0 { + _7 = parseString(reader) + } + var _8: String? + if Int(_1!) & Int(1 << 4) != 0 { + _8 = parseString(reader) + } + var _9: Api.UserProfilePhoto? + if Int(_1!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.UserProfilePhoto + } + } + var _10: Api.UserStatus? + if Int(_1!) & Int(1 << 6) != 0 { + if let signature = reader.readInt32() { + _10 = Api.parse(reader, signature: signature) as? Api.UserStatus + } + } + var _11: Int32? + if Int(_1!) & Int(1 << 14) != 0 { + _11 = reader.readInt32() + } + var _12: [Api.RestrictionReason]? + if Int(_1!) & Int(1 << 18) != 0 { + if let _ = reader.readInt32() { + _12 = Api.parseVector(reader, elementSignature: 0, elementType: Api.RestrictionReason.self) + } + } + var _13: String? + if Int(_1!) & Int(1 << 19) != 0 { + _13 = parseString(reader) + } + var _14: String? + if Int(_1!) & Int(1 << 22) != 0 { + _14 = parseString(reader) + } + var _15: Api.EmojiStatus? + if Int(_1!) & Int(1 << 30) != 0 { + if let signature = reader.readInt32() { + _15 = Api.parse(reader, signature: signature) as? Api.EmojiStatus + } + } + var _16: [Api.Username]? + if Int(_2!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _16 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Username.self) + } + } + var _17: Api.RecentStory? + if Int(_2!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _17 = Api.parse(reader, signature: signature) as? Api.RecentStory + } + } + var _18: Api.PeerColor? + if Int(_2!) & Int(1 << 8) != 0 { + if let signature = reader.readInt32() { + _18 = Api.parse(reader, signature: signature) as? Api.PeerColor + } + } + var _19: Api.PeerColor? + if Int(_2!) & Int(1 << 9) != 0 { + if let signature = reader.readInt32() { + _19 = Api.parse(reader, signature: signature) as? Api.PeerColor + } + } + var _20: Int32? + if Int(_2!) & Int(1 << 12) != 0 { + _20 = reader.readInt32() + } + var _21: Int64? + if Int(_2!) & Int(1 << 14) != 0 { + _21 = reader.readInt64() + } + var _22: Int64? + if Int(_2!) & Int(1 << 15) != 0 { + _22 = reader.readInt64() } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.account.ResolvedBusinessChatLinks.resolvedBusinessChatLinks(flags: _1!, peer: _2!, message: _3!, entities: _4, chats: _5!, users: _6!) + let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil + let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil + let _c7 = (Int(_1!) & Int(1 << 3) == 0) || _7 != nil + let _c8 = (Int(_1!) & Int(1 << 4) == 0) || _8 != nil + let _c9 = (Int(_1!) & Int(1 << 5) == 0) || _9 != nil + let _c10 = (Int(_1!) & Int(1 << 6) == 0) || _10 != nil + let _c11 = (Int(_1!) & Int(1 << 14) == 0) || _11 != nil + let _c12 = (Int(_1!) & Int(1 << 18) == 0) || _12 != nil + let _c13 = (Int(_1!) & Int(1 << 19) == 0) || _13 != nil + let _c14 = (Int(_1!) & Int(1 << 22) == 0) || _14 != nil + let _c15 = (Int(_1!) & Int(1 << 30) == 0) || _15 != nil + let _c16 = (Int(_2!) & Int(1 << 0) == 0) || _16 != nil + let _c17 = (Int(_2!) & Int(1 << 5) == 0) || _17 != nil + let _c18 = (Int(_2!) & Int(1 << 8) == 0) || _18 != nil + let _c19 = (Int(_2!) & Int(1 << 9) == 0) || _19 != nil + let _c20 = (Int(_2!) & Int(1 << 12) == 0) || _20 != nil + let _c21 = (Int(_2!) & Int(1 << 14) == 0) || _21 != nil + let _c22 = (Int(_2!) & Int(1 << 15) == 0) || _22 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 && _c18 && _c19 && _c20 && _c21 && _c22 { + return Api.User.user(Cons_user(flags: _1!, flags2: _2!, id: _3!, accessHash: _4, firstName: _5, lastName: _6, username: _7, phone: _8, photo: _9, status: _10, botInfoVersion: _11, restrictionReason: _12, botInlinePlaceholder: _13, langCode: _14, emojiStatus: _15, usernames: _16, storiesMaxId: _17, color: _18, profileColor: _19, botActiveUsers: _20, botVerificationIcon: _21, sendPaidMessagesStars: _22)) + } + else { + return nil + } + } + public static func parse_userEmpty(_ reader: BufferReader) -> User? { + var _1: Int64? + _1 = reader.readInt64() + let _c1 = _1 != nil + if _c1 { + return Api.User.userEmpty(Cons_userEmpty(id: _1!)) + } + else { + return nil + } + } + } +} +public extension Api { + enum UserFull: TypeConstructorDescription { + public class Cons_userFull { + public var flags: Int32 + public var flags2: Int32 + public var id: Int64 + public var about: String? + public var settings: Api.PeerSettings + public var personalPhoto: Api.Photo? + public var profilePhoto: Api.Photo? + public var fallbackPhoto: Api.Photo? + public var notifySettings: Api.PeerNotifySettings + public var botInfo: Api.BotInfo? + public var pinnedMsgId: Int32? + public var commonChatsCount: Int32 + public var folderId: Int32? + public var ttlPeriod: Int32? + public var theme: Api.ChatTheme? + public var privateForwardName: String? + public var botGroupAdminRights: Api.ChatAdminRights? + public var botBroadcastAdminRights: Api.ChatAdminRights? + public var wallpaper: Api.WallPaper? + public var stories: Api.PeerStories? + public var businessWorkHours: Api.BusinessWorkHours? + public var businessLocation: Api.BusinessLocation? + public var businessGreetingMessage: Api.BusinessGreetingMessage? + public var businessAwayMessage: Api.BusinessAwayMessage? + public var businessIntro: Api.BusinessIntro? + public var birthday: Api.Birthday? + public var personalChannelId: Int64? + public var personalChannelMessage: Int32? + public var stargiftsCount: Int32? + public var starrefProgram: Api.StarRefProgram? + public var botVerification: Api.BotVerification? + public var sendPaidMessagesStars: Int64? + public var disallowedGifts: Api.DisallowedGiftsSettings? + public var starsRating: Api.StarsRating? + public var starsMyPendingRating: Api.StarsRating? + public var starsMyPendingRatingDate: Int32? + public var mainTab: Api.ProfileTab? + public var savedMusic: Api.Document? + public var note: Api.TextWithEntities? + public init(flags: Int32, flags2: Int32, id: Int64, about: String?, settings: Api.PeerSettings, personalPhoto: Api.Photo?, profilePhoto: Api.Photo?, fallbackPhoto: Api.Photo?, notifySettings: Api.PeerNotifySettings, botInfo: Api.BotInfo?, pinnedMsgId: Int32?, commonChatsCount: Int32, folderId: Int32?, ttlPeriod: Int32?, theme: Api.ChatTheme?, privateForwardName: String?, botGroupAdminRights: Api.ChatAdminRights?, botBroadcastAdminRights: Api.ChatAdminRights?, wallpaper: Api.WallPaper?, stories: Api.PeerStories?, businessWorkHours: Api.BusinessWorkHours?, businessLocation: Api.BusinessLocation?, businessGreetingMessage: Api.BusinessGreetingMessage?, businessAwayMessage: Api.BusinessAwayMessage?, businessIntro: Api.BusinessIntro?, birthday: Api.Birthday?, personalChannelId: Int64?, personalChannelMessage: Int32?, stargiftsCount: Int32?, starrefProgram: Api.StarRefProgram?, botVerification: Api.BotVerification?, sendPaidMessagesStars: Int64?, disallowedGifts: Api.DisallowedGiftsSettings?, starsRating: Api.StarsRating?, starsMyPendingRating: Api.StarsRating?, starsMyPendingRatingDate: Int32?, mainTab: Api.ProfileTab?, savedMusic: Api.Document?, note: Api.TextWithEntities?) { + self.flags = flags + self.flags2 = flags2 + self.id = id + self.about = about + self.settings = settings + self.personalPhoto = personalPhoto + self.profilePhoto = profilePhoto + self.fallbackPhoto = fallbackPhoto + self.notifySettings = notifySettings + self.botInfo = botInfo + self.pinnedMsgId = pinnedMsgId + self.commonChatsCount = commonChatsCount + self.folderId = folderId + self.ttlPeriod = ttlPeriod + self.theme = theme + self.privateForwardName = privateForwardName + self.botGroupAdminRights = botGroupAdminRights + self.botBroadcastAdminRights = botBroadcastAdminRights + self.wallpaper = wallpaper + self.stories = stories + self.businessWorkHours = businessWorkHours + self.businessLocation = businessLocation + self.businessGreetingMessage = businessGreetingMessage + self.businessAwayMessage = businessAwayMessage + self.businessIntro = businessIntro + self.birthday = birthday + self.personalChannelId = personalChannelId + self.personalChannelMessage = personalChannelMessage + self.stargiftsCount = stargiftsCount + self.starrefProgram = starrefProgram + self.botVerification = botVerification + self.sendPaidMessagesStars = sendPaidMessagesStars + self.disallowedGifts = disallowedGifts + self.starsRating = starsRating + self.starsMyPendingRating = starsMyPendingRating + self.starsMyPendingRatingDate = starsMyPendingRatingDate + self.mainTab = mainTab + self.savedMusic = savedMusic + self.note = note + } + } + case userFull(Cons_userFull) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .userFull(let _data): + if boxed { + buffer.appendInt32(-1607745218) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.flags2, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.about!, buffer: buffer, boxed: false) + } + _data.settings.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 21) != 0 { + _data.personalPhoto!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.profilePhoto!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 22) != 0 { + _data.fallbackPhoto!.serialize(buffer, true) + } + _data.notifySettings.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.botInfo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + serializeInt32(_data.pinnedMsgId!, buffer: buffer, boxed: false) + } + serializeInt32(_data.commonChatsCount, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 11) != 0 { + serializeInt32(_data.folderId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 14) != 0 { + serializeInt32(_data.ttlPeriod!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 15) != 0 { + _data.theme!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 16) != 0 { + serializeString(_data.privateForwardName!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 17) != 0 { + _data.botGroupAdminRights!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 18) != 0 { + _data.botBroadcastAdminRights!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 24) != 0 { + _data.wallpaper!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 25) != 0 { + _data.stories!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 0) != 0 { + _data.businessWorkHours!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 1) != 0 { + _data.businessLocation!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 2) != 0 { + _data.businessGreetingMessage!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 3) != 0 { + _data.businessAwayMessage!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 4) != 0 { + _data.businessIntro!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 5) != 0 { + _data.birthday!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 6) != 0 { + serializeInt64(_data.personalChannelId!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 6) != 0 { + serializeInt32(_data.personalChannelMessage!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 8) != 0 { + serializeInt32(_data.stargiftsCount!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 11) != 0 { + _data.starrefProgram!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 12) != 0 { + _data.botVerification!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 14) != 0 { + serializeInt64(_data.sendPaidMessagesStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 15) != 0 { + _data.disallowedGifts!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 17) != 0 { + _data.starsRating!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 18) != 0 { + _data.starsMyPendingRating!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 18) != 0 { + serializeInt32(_data.starsMyPendingRatingDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 20) != 0 { + _data.mainTab!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 21) != 0 { + _data.savedMusic!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 22) != 0 { + _data.note!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .userFull(let _data): + return ("userFull", [("flags", _data.flags as Any), ("flags2", _data.flags2 as Any), ("id", _data.id as Any), ("about", _data.about as Any), ("settings", _data.settings as Any), ("personalPhoto", _data.personalPhoto as Any), ("profilePhoto", _data.profilePhoto as Any), ("fallbackPhoto", _data.fallbackPhoto as Any), ("notifySettings", _data.notifySettings as Any), ("botInfo", _data.botInfo as Any), ("pinnedMsgId", _data.pinnedMsgId as Any), ("commonChatsCount", _data.commonChatsCount as Any), ("folderId", _data.folderId as Any), ("ttlPeriod", _data.ttlPeriod as Any), ("theme", _data.theme as Any), ("privateForwardName", _data.privateForwardName as Any), ("botGroupAdminRights", _data.botGroupAdminRights as Any), ("botBroadcastAdminRights", _data.botBroadcastAdminRights as Any), ("wallpaper", _data.wallpaper as Any), ("stories", _data.stories as Any), ("businessWorkHours", _data.businessWorkHours as Any), ("businessLocation", _data.businessLocation as Any), ("businessGreetingMessage", _data.businessGreetingMessage as Any), ("businessAwayMessage", _data.businessAwayMessage as Any), ("businessIntro", _data.businessIntro as Any), ("birthday", _data.birthday as Any), ("personalChannelId", _data.personalChannelId as Any), ("personalChannelMessage", _data.personalChannelMessage as Any), ("stargiftsCount", _data.stargiftsCount as Any), ("starrefProgram", _data.starrefProgram as Any), ("botVerification", _data.botVerification as Any), ("sendPaidMessagesStars", _data.sendPaidMessagesStars as Any), ("disallowedGifts", _data.disallowedGifts as Any), ("starsRating", _data.starsRating as Any), ("starsMyPendingRating", _data.starsMyPendingRating as Any), ("starsMyPendingRatingDate", _data.starsMyPendingRatingDate as Any), ("mainTab", _data.mainTab as Any), ("savedMusic", _data.savedMusic as Any), ("note", _data.note as Any)]) + } + } + + public static func parse_userFull(_ reader: BufferReader) -> UserFull? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int64? + _3 = reader.readInt64() + var _4: String? + if Int(_1!) & Int(1 << 1) != 0 { + _4 = parseString(reader) + } + var _5: Api.PeerSettings? + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.PeerSettings + } + var _6: Api.Photo? + if Int(_1!) & Int(1 << 21) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.Photo + } + } + var _7: Api.Photo? + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.Photo + } + } + var _8: Api.Photo? + if Int(_1!) & Int(1 << 22) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.Photo + } + } + var _9: Api.PeerNotifySettings? + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.PeerNotifySettings + } + var _10: Api.BotInfo? + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _10 = Api.parse(reader, signature: signature) as? Api.BotInfo + } + } + var _11: Int32? + if Int(_1!) & Int(1 << 6) != 0 { + _11 = reader.readInt32() + } + var _12: Int32? + _12 = reader.readInt32() + var _13: Int32? + if Int(_1!) & Int(1 << 11) != 0 { + _13 = reader.readInt32() + } + var _14: Int32? + if Int(_1!) & Int(1 << 14) != 0 { + _14 = reader.readInt32() + } + var _15: Api.ChatTheme? + if Int(_1!) & Int(1 << 15) != 0 { + if let signature = reader.readInt32() { + _15 = Api.parse(reader, signature: signature) as? Api.ChatTheme + } + } + var _16: String? + if Int(_1!) & Int(1 << 16) != 0 { + _16 = parseString(reader) + } + var _17: Api.ChatAdminRights? + if Int(_1!) & Int(1 << 17) != 0 { + if let signature = reader.readInt32() { + _17 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights + } + } + var _18: Api.ChatAdminRights? + if Int(_1!) & Int(1 << 18) != 0 { + if let signature = reader.readInt32() { + _18 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights + } + } + var _19: Api.WallPaper? + if Int(_1!) & Int(1 << 24) != 0 { + if let signature = reader.readInt32() { + _19 = Api.parse(reader, signature: signature) as? Api.WallPaper + } + } + var _20: Api.PeerStories? + if Int(_1!) & Int(1 << 25) != 0 { + if let signature = reader.readInt32() { + _20 = Api.parse(reader, signature: signature) as? Api.PeerStories + } + } + var _21: Api.BusinessWorkHours? + if Int(_2!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _21 = Api.parse(reader, signature: signature) as? Api.BusinessWorkHours + } + } + var _22: Api.BusinessLocation? + if Int(_2!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _22 = Api.parse(reader, signature: signature) as? Api.BusinessLocation + } + } + var _23: Api.BusinessGreetingMessage? + if Int(_2!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _23 = Api.parse(reader, signature: signature) as? Api.BusinessGreetingMessage + } + } + var _24: Api.BusinessAwayMessage? + if Int(_2!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _24 = Api.parse(reader, signature: signature) as? Api.BusinessAwayMessage + } + } + var _25: Api.BusinessIntro? + if Int(_2!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _25 = Api.parse(reader, signature: signature) as? Api.BusinessIntro + } + } + var _26: Api.Birthday? + if Int(_2!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _26 = Api.parse(reader, signature: signature) as? Api.Birthday + } + } + var _27: Int64? + if Int(_2!) & Int(1 << 6) != 0 { + _27 = reader.readInt64() + } + var _28: Int32? + if Int(_2!) & Int(1 << 6) != 0 { + _28 = reader.readInt32() + } + var _29: Int32? + if Int(_2!) & Int(1 << 8) != 0 { + _29 = reader.readInt32() + } + var _30: Api.StarRefProgram? + if Int(_2!) & Int(1 << 11) != 0 { + if let signature = reader.readInt32() { + _30 = Api.parse(reader, signature: signature) as? Api.StarRefProgram + } + } + var _31: Api.BotVerification? + if Int(_2!) & Int(1 << 12) != 0 { + if let signature = reader.readInt32() { + _31 = Api.parse(reader, signature: signature) as? Api.BotVerification + } + } + var _32: Int64? + if Int(_2!) & Int(1 << 14) != 0 { + _32 = reader.readInt64() + } + var _33: Api.DisallowedGiftsSettings? + if Int(_2!) & Int(1 << 15) != 0 { + if let signature = reader.readInt32() { + _33 = Api.parse(reader, signature: signature) as? Api.DisallowedGiftsSettings + } + } + var _34: Api.StarsRating? + if Int(_2!) & Int(1 << 17) != 0 { + if let signature = reader.readInt32() { + _34 = Api.parse(reader, signature: signature) as? Api.StarsRating + } + } + var _35: Api.StarsRating? + if Int(_2!) & Int(1 << 18) != 0 { + if let signature = reader.readInt32() { + _35 = Api.parse(reader, signature: signature) as? Api.StarsRating + } + } + var _36: Int32? + if Int(_2!) & Int(1 << 18) != 0 { + _36 = reader.readInt32() + } + var _37: Api.ProfileTab? + if Int(_2!) & Int(1 << 20) != 0 { + if let signature = reader.readInt32() { + _37 = Api.parse(reader, signature: signature) as? Api.ProfileTab + } + } + var _38: Api.Document? + if Int(_2!) & Int(1 << 21) != 0 { + if let signature = reader.readInt32() { + _38 = Api.parse(reader, signature: signature) as? Api.Document + } + } + var _39: Api.TextWithEntities? + if Int(_2!) & Int(1 << 22) != 0 { + if let signature = reader.readInt32() { + _39 = Api.parse(reader, signature: signature) as? Api.TextWithEntities + } + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil + let _c5 = _5 != nil + let _c6 = (Int(_1!) & Int(1 << 21) == 0) || _6 != nil + let _c7 = (Int(_1!) & Int(1 << 2) == 0) || _7 != nil + let _c8 = (Int(_1!) & Int(1 << 22) == 0) || _8 != nil + let _c9 = _9 != nil + let _c10 = (Int(_1!) & Int(1 << 3) == 0) || _10 != nil + let _c11 = (Int(_1!) & Int(1 << 6) == 0) || _11 != nil + let _c12 = _12 != nil + let _c13 = (Int(_1!) & Int(1 << 11) == 0) || _13 != nil + let _c14 = (Int(_1!) & Int(1 << 14) == 0) || _14 != nil + let _c15 = (Int(_1!) & Int(1 << 15) == 0) || _15 != nil + let _c16 = (Int(_1!) & Int(1 << 16) == 0) || _16 != nil + let _c17 = (Int(_1!) & Int(1 << 17) == 0) || _17 != nil + let _c18 = (Int(_1!) & Int(1 << 18) == 0) || _18 != nil + let _c19 = (Int(_1!) & Int(1 << 24) == 0) || _19 != nil + let _c20 = (Int(_1!) & Int(1 << 25) == 0) || _20 != nil + let _c21 = (Int(_2!) & Int(1 << 0) == 0) || _21 != nil + let _c22 = (Int(_2!) & Int(1 << 1) == 0) || _22 != nil + let _c23 = (Int(_2!) & Int(1 << 2) == 0) || _23 != nil + let _c24 = (Int(_2!) & Int(1 << 3) == 0) || _24 != nil + let _c25 = (Int(_2!) & Int(1 << 4) == 0) || _25 != nil + let _c26 = (Int(_2!) & Int(1 << 5) == 0) || _26 != nil + let _c27 = (Int(_2!) & Int(1 << 6) == 0) || _27 != nil + let _c28 = (Int(_2!) & Int(1 << 6) == 0) || _28 != nil + let _c29 = (Int(_2!) & Int(1 << 8) == 0) || _29 != nil + let _c30 = (Int(_2!) & Int(1 << 11) == 0) || _30 != nil + let _c31 = (Int(_2!) & Int(1 << 12) == 0) || _31 != nil + let _c32 = (Int(_2!) & Int(1 << 14) == 0) || _32 != nil + let _c33 = (Int(_2!) & Int(1 << 15) == 0) || _33 != nil + let _c34 = (Int(_2!) & Int(1 << 17) == 0) || _34 != nil + let _c35 = (Int(_2!) & Int(1 << 18) == 0) || _35 != nil + let _c36 = (Int(_2!) & Int(1 << 18) == 0) || _36 != nil + let _c37 = (Int(_2!) & Int(1 << 20) == 0) || _37 != nil + let _c38 = (Int(_2!) & Int(1 << 21) == 0) || _38 != nil + let _c39 = (Int(_2!) & Int(1 << 22) == 0) || _39 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 && _c18 && _c19 && _c20 && _c21 && _c22 && _c23 && _c24 && _c25 && _c26 && _c27 && _c28 && _c29 && _c30 && _c31 && _c32 && _c33 && _c34 && _c35 && _c36 && _c37 && _c38 && _c39 { + return Api.UserFull.userFull(Cons_userFull(flags: _1!, flags2: _2!, id: _3!, about: _4, settings: _5!, personalPhoto: _6, profilePhoto: _7, fallbackPhoto: _8, notifySettings: _9!, botInfo: _10, pinnedMsgId: _11, commonChatsCount: _12!, folderId: _13, ttlPeriod: _14, theme: _15, privateForwardName: _16, botGroupAdminRights: _17, botBroadcastAdminRights: _18, wallpaper: _19, stories: _20, businessWorkHours: _21, businessLocation: _22, businessGreetingMessage: _23, businessAwayMessage: _24, businessIntro: _25, birthday: _26, personalChannelId: _27, personalChannelMessage: _28, stargiftsCount: _29, starrefProgram: _30, botVerification: _31, sendPaidMessagesStars: _32, disallowedGifts: _33, starsRating: _34, starsMyPendingRating: _35, starsMyPendingRatingDate: _36, mainTab: _37, savedMusic: _38, note: _39)) + } + else { + return nil + } + } + } +} +public extension Api { + enum UserProfilePhoto: TypeConstructorDescription { + public class Cons_userProfilePhoto { + public var flags: Int32 + public var photoId: Int64 + public var strippedThumb: Buffer? + public var dcId: Int32 + public init(flags: Int32, photoId: Int64, strippedThumb: Buffer?, dcId: Int32) { + self.flags = flags + self.photoId = photoId + self.strippedThumb = strippedThumb + self.dcId = dcId + } + } + case userProfilePhoto(Cons_userProfilePhoto) + case userProfilePhotoEmpty + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .userProfilePhoto(let _data): + if boxed { + buffer.appendInt32(-2100168954) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.photoId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeBytes(_data.strippedThumb!, buffer: buffer, boxed: false) + } + serializeInt32(_data.dcId, buffer: buffer, boxed: false) + break + case .userProfilePhotoEmpty: + if boxed { + buffer.appendInt32(1326562017) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .userProfilePhoto(let _data): + return ("userProfilePhoto", [("flags", _data.flags as Any), ("photoId", _data.photoId as Any), ("strippedThumb", _data.strippedThumb as Any), ("dcId", _data.dcId as Any)]) + case .userProfilePhotoEmpty: + return ("userProfilePhotoEmpty", []) + } + } + + public static func parse_userProfilePhoto(_ reader: BufferReader) -> UserProfilePhoto? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: Buffer? + if Int(_1!) & Int(1 << 1) != 0 { + _3 = parseBytes(reader) + } + var _4: Int32? + _4 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.UserProfilePhoto.userProfilePhoto(Cons_userProfilePhoto(flags: _1!, photoId: _2!, strippedThumb: _3, dcId: _4!)) + } + else { + return nil + } + } + public static func parse_userProfilePhotoEmpty(_ reader: BufferReader) -> UserProfilePhoto? { + return Api.UserProfilePhoto.userProfilePhotoEmpty + } + } +} +public extension Api { + enum UserStatus: TypeConstructorDescription { + public class Cons_userStatusLastMonth { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } + public class Cons_userStatusLastWeek { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } + public class Cons_userStatusOffline { + public var wasOnline: Int32 + public init(wasOnline: Int32) { + self.wasOnline = wasOnline + } + } + public class Cons_userStatusOnline { + public var expires: Int32 + public init(expires: Int32) { + self.expires = expires + } + } + public class Cons_userStatusRecently { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } + case userStatusEmpty + case userStatusLastMonth(Cons_userStatusLastMonth) + case userStatusLastWeek(Cons_userStatusLastWeek) + case userStatusOffline(Cons_userStatusOffline) + case userStatusOnline(Cons_userStatusOnline) + case userStatusRecently(Cons_userStatusRecently) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .userStatusEmpty: + if boxed { + buffer.appendInt32(164646985) + } + break + case .userStatusLastMonth(let _data): + if boxed { + buffer.appendInt32(1703516023) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + case .userStatusLastWeek(let _data): + if boxed { + buffer.appendInt32(1410997530) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + case .userStatusOffline(let _data): + if boxed { + buffer.appendInt32(9203775) + } + serializeInt32(_data.wasOnline, buffer: buffer, boxed: false) + break + case .userStatusOnline(let _data): + if boxed { + buffer.appendInt32(-306628279) + } + serializeInt32(_data.expires, buffer: buffer, boxed: false) + break + case .userStatusRecently(let _data): + if boxed { + buffer.appendInt32(2065268168) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .userStatusEmpty: + return ("userStatusEmpty", []) + case .userStatusLastMonth(let _data): + return ("userStatusLastMonth", [("flags", _data.flags as Any)]) + case .userStatusLastWeek(let _data): + return ("userStatusLastWeek", [("flags", _data.flags as Any)]) + case .userStatusOffline(let _data): + return ("userStatusOffline", [("wasOnline", _data.wasOnline as Any)]) + case .userStatusOnline(let _data): + return ("userStatusOnline", [("expires", _data.expires as Any)]) + case .userStatusRecently(let _data): + return ("userStatusRecently", [("flags", _data.flags as Any)]) + } + } + + public static func parse_userStatusEmpty(_ reader: BufferReader) -> UserStatus? { + return Api.UserStatus.userStatusEmpty + } + public static func parse_userStatusLastMonth(_ reader: BufferReader) -> UserStatus? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.UserStatus.userStatusLastMonth(Cons_userStatusLastMonth(flags: _1!)) + } + else { + return nil + } + } + public static func parse_userStatusLastWeek(_ reader: BufferReader) -> UserStatus? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.UserStatus.userStatusLastWeek(Cons_userStatusLastWeek(flags: _1!)) + } + else { + return nil + } + } + public static func parse_userStatusOffline(_ reader: BufferReader) -> UserStatus? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.UserStatus.userStatusOffline(Cons_userStatusOffline(wasOnline: _1!)) + } + else { + return nil + } + } + public static func parse_userStatusOnline(_ reader: BufferReader) -> UserStatus? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.UserStatus.userStatusOnline(Cons_userStatusOnline(expires: _1!)) + } + else { + return nil + } + } + public static func parse_userStatusRecently(_ reader: BufferReader) -> UserStatus? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.UserStatus.userStatusRecently(Cons_userStatusRecently(flags: _1!)) + } + else { + return nil + } + } + } +} +public extension Api { + enum Username: TypeConstructorDescription { + public class Cons_username { + public var flags: Int32 + public var username: String + public init(flags: Int32, username: String) { + self.flags = flags + self.username = username + } + } + case username(Cons_username) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .username(let _data): + if boxed { + buffer.appendInt32(-1274595769) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.username, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .username(let _data): + return ("username", [("flags", _data.flags as Any), ("username", _data.username as Any)]) + } + } + + public static func parse_username(_ reader: BufferReader) -> Username? { + var _1: Int32? + _1 = reader.readInt32() + var _2: String? + _2 = parseString(reader) + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.Username.username(Cons_username(flags: _1!, username: _2!)) + } + else { + return nil + } + } + } +} +public extension Api { + enum VideoSize: TypeConstructorDescription { + public class Cons_videoSize { + public var flags: Int32 + public var type: String + public var w: Int32 + public var h: Int32 + public var size: Int32 + public var videoStartTs: Double? + public init(flags: Int32, type: String, w: Int32, h: Int32, size: Int32, videoStartTs: Double?) { + self.flags = flags + self.type = type + self.w = w + self.h = h + self.size = size + self.videoStartTs = videoStartTs + } + } + public class Cons_videoSizeEmojiMarkup { + public var emojiId: Int64 + public var backgroundColors: [Int32] + public init(emojiId: Int64, backgroundColors: [Int32]) { + self.emojiId = emojiId + self.backgroundColors = backgroundColors + } + } + public class Cons_videoSizeStickerMarkup { + public var stickerset: Api.InputStickerSet + public var stickerId: Int64 + public var backgroundColors: [Int32] + public init(stickerset: Api.InputStickerSet, stickerId: Int64, backgroundColors: [Int32]) { + self.stickerset = stickerset + self.stickerId = stickerId + self.backgroundColors = backgroundColors + } + } + case videoSize(Cons_videoSize) + case videoSizeEmojiMarkup(Cons_videoSizeEmojiMarkup) + case videoSizeStickerMarkup(Cons_videoSizeStickerMarkup) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .videoSize(let _data): + if boxed { + buffer.appendInt32(-567037804) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.type, buffer: buffer, boxed: false) + serializeInt32(_data.w, buffer: buffer, boxed: false) + serializeInt32(_data.h, buffer: buffer, boxed: false) + serializeInt32(_data.size, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeDouble(_data.videoStartTs!, buffer: buffer, boxed: false) + } + break + case .videoSizeEmojiMarkup(let _data): + if boxed { + buffer.appendInt32(-128171716) + } + serializeInt64(_data.emojiId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.backgroundColors.count)) + for item in _data.backgroundColors { + serializeInt32(item, buffer: buffer, boxed: false) + } + break + case .videoSizeStickerMarkup(let _data): + if boxed { + buffer.appendInt32(228623102) + } + _data.stickerset.serialize(buffer, true) + serializeInt64(_data.stickerId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.backgroundColors.count)) + for item in _data.backgroundColors { + serializeInt32(item, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .videoSize(let _data): + return ("videoSize", [("flags", _data.flags as Any), ("type", _data.type as Any), ("w", _data.w as Any), ("h", _data.h as Any), ("size", _data.size as Any), ("videoStartTs", _data.videoStartTs as Any)]) + case .videoSizeEmojiMarkup(let _data): + return ("videoSizeEmojiMarkup", [("emojiId", _data.emojiId as Any), ("backgroundColors", _data.backgroundColors as Any)]) + case .videoSizeStickerMarkup(let _data): + return ("videoSizeStickerMarkup", [("stickerset", _data.stickerset as Any), ("stickerId", _data.stickerId as Any), ("backgroundColors", _data.backgroundColors as Any)]) + } + } + + public static func parse_videoSize(_ reader: BufferReader) -> VideoSize? { + var _1: Int32? + _1 = reader.readInt32() + var _2: String? + _2 = parseString(reader) + var _3: Int32? + _3 = reader.readInt32() + var _4: Int32? + _4 = reader.readInt32() + var _5: Int32? + _5 = reader.readInt32() + var _6: Double? + if Int(_1!) & Int(1 << 0) != 0 { + _6 = reader.readDouble() + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.VideoSize.videoSize(Cons_videoSize(flags: _1!, type: _2!, w: _3!, h: _4!, size: _5!, videoStartTs: _6)) + } + else { + return nil + } + } + public static func parse_videoSizeEmojiMarkup(_ reader: BufferReader) -> VideoSize? { + var _1: Int64? + _1 = reader.readInt64() + var _2: [Int32]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.VideoSize.videoSizeEmojiMarkup(Cons_videoSizeEmojiMarkup(emojiId: _1!, backgroundColors: _2!)) + } + else { + return nil + } + } + public static func parse_videoSizeStickerMarkup(_ reader: BufferReader) -> VideoSize? { + var _1: Api.InputStickerSet? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.InputStickerSet + } + var _2: Int64? + _2 = reader.readInt64() + var _3: [Int32]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.VideoSize.videoSizeStickerMarkup(Cons_videoSizeStickerMarkup(stickerset: _1!, stickerId: _2!, backgroundColors: _3!)) + } + else { + return nil + } + } + } +} +public extension Api { + enum WallPaper: TypeConstructorDescription { + public class Cons_wallPaper { + public var id: Int64 + public var flags: Int32 + public var accessHash: Int64 + public var slug: String + public var document: Api.Document + public var settings: Api.WallPaperSettings? + public init(id: Int64, flags: Int32, accessHash: Int64, slug: String, document: Api.Document, settings: Api.WallPaperSettings?) { + self.id = id + self.flags = flags + self.accessHash = accessHash + self.slug = slug + self.document = document + self.settings = settings + } + } + public class Cons_wallPaperNoFile { + public var id: Int64 + public var flags: Int32 + public var settings: Api.WallPaperSettings? + public init(id: Int64, flags: Int32, settings: Api.WallPaperSettings?) { + self.id = id + self.flags = flags + self.settings = settings + } + } + case wallPaper(Cons_wallPaper) + case wallPaperNoFile(Cons_wallPaperNoFile) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .wallPaper(let _data): + if boxed { + buffer.appendInt32(-1539849235) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeString(_data.slug, buffer: buffer, boxed: false) + _data.document.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.settings!.serialize(buffer, true) + } + break + case .wallPaperNoFile(let _data): + if boxed { + buffer.appendInt32(-528465642) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.settings!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .wallPaper(let _data): + return ("wallPaper", [("id", _data.id as Any), ("flags", _data.flags as Any), ("accessHash", _data.accessHash as Any), ("slug", _data.slug as Any), ("document", _data.document as Any), ("settings", _data.settings as Any)]) + case .wallPaperNoFile(let _data): + return ("wallPaperNoFile", [("id", _data.id as Any), ("flags", _data.flags as Any), ("settings", _data.settings as Any)]) + } + } + + public static func parse_wallPaper(_ reader: BufferReader) -> WallPaper? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int64? + _3 = reader.readInt64() + var _4: String? + _4 = parseString(reader) + var _5: Api.Document? + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.Document + } + var _6: Api.WallPaperSettings? + if Int(_2!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.WallPaperSettings + } + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = (Int(_2!) & Int(1 << 2) == 0) || _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.WallPaper.wallPaper(Cons_wallPaper(id: _1!, flags: _2!, accessHash: _3!, slug: _4!, document: _5!, settings: _6)) + } + else { + return nil + } + } + public static func parse_wallPaperNoFile(_ reader: BufferReader) -> WallPaper? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Int32? + _2 = reader.readInt32() + var _3: Api.WallPaperSettings? + if Int(_2!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.WallPaperSettings + } + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_2!) & Int(1 << 2) == 0) || _3 != nil + if _c1 && _c2 && _c3 { + return Api.WallPaper.wallPaperNoFile(Cons_wallPaperNoFile(id: _1!, flags: _2!, settings: _3)) + } + else { + return nil + } + } + } +} +public extension Api { + enum WallPaperSettings: TypeConstructorDescription { + public class Cons_wallPaperSettings { + public var flags: Int32 + public var backgroundColor: Int32? + public var secondBackgroundColor: Int32? + public var thirdBackgroundColor: Int32? + public var fourthBackgroundColor: Int32? + public var intensity: Int32? + public var rotation: Int32? + public var emoticon: String? + public init(flags: Int32, backgroundColor: Int32?, secondBackgroundColor: Int32?, thirdBackgroundColor: Int32?, fourthBackgroundColor: Int32?, intensity: Int32?, rotation: Int32?, emoticon: String?) { + self.flags = flags + self.backgroundColor = backgroundColor + self.secondBackgroundColor = secondBackgroundColor + self.thirdBackgroundColor = thirdBackgroundColor + self.fourthBackgroundColor = fourthBackgroundColor + self.intensity = intensity + self.rotation = rotation + self.emoticon = emoticon + } + } + case wallPaperSettings(Cons_wallPaperSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .wallPaperSettings(let _data): + if boxed { + buffer.appendInt32(925826256) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.backgroundColor!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.secondBackgroundColor!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeInt32(_data.thirdBackgroundColor!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + serializeInt32(_data.fourthBackgroundColor!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.intensity!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.rotation!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 7) != 0 { + serializeString(_data.emoticon!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .wallPaperSettings(let _data): + return ("wallPaperSettings", [("flags", _data.flags as Any), ("backgroundColor", _data.backgroundColor as Any), ("secondBackgroundColor", _data.secondBackgroundColor as Any), ("thirdBackgroundColor", _data.thirdBackgroundColor as Any), ("fourthBackgroundColor", _data.fourthBackgroundColor as Any), ("intensity", _data.intensity as Any), ("rotation", _data.rotation as Any), ("emoticon", _data.emoticon as Any)]) + } + } + + public static func parse_wallPaperSettings(_ reader: BufferReader) -> WallPaperSettings? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt32() + } + var _3: Int32? + if Int(_1!) & Int(1 << 4) != 0 { + _3 = reader.readInt32() + } + var _4: Int32? + if Int(_1!) & Int(1 << 5) != 0 { + _4 = reader.readInt32() + } + var _5: Int32? + if Int(_1!) & Int(1 << 6) != 0 { + _5 = reader.readInt32() + } + var _6: Int32? + if Int(_1!) & Int(1 << 3) != 0 { + _6 = reader.readInt32() + } + var _7: Int32? + if Int(_1!) & Int(1 << 4) != 0 { + _7 = reader.readInt32() + } + var _8: String? + if Int(_1!) & Int(1 << 7) != 0 { + _8 = parseString(reader) + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + let _c3 = (Int(_1!) & Int(1 << 4) == 0) || _3 != nil + let _c4 = (Int(_1!) & Int(1 << 5) == 0) || _4 != nil + let _c5 = (Int(_1!) & Int(1 << 6) == 0) || _5 != nil + let _c6 = (Int(_1!) & Int(1 << 3) == 0) || _6 != nil + let _c7 = (Int(_1!) & Int(1 << 4) == 0) || _7 != nil + let _c8 = (Int(_1!) & Int(1 << 7) == 0) || _8 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.WallPaperSettings.wallPaperSettings(Cons_wallPaperSettings(flags: _1!, backgroundColor: _2, secondBackgroundColor: _3, thirdBackgroundColor: _4, fourthBackgroundColor: _5, intensity: _6, rotation: _7, emoticon: _8)) + } + else { + return nil + } + } + } +} +public extension Api { + enum WebAuthorization: TypeConstructorDescription { + public class Cons_webAuthorization { + public var hash: Int64 + public var botId: Int64 + public var domain: String + public var browser: String + public var platform: String + public var dateCreated: Int32 + public var dateActive: Int32 + public var ip: String + public var region: String + public init(hash: Int64, botId: Int64, domain: String, browser: String, platform: String, dateCreated: Int32, dateActive: Int32, ip: String, region: String) { + self.hash = hash + self.botId = botId + self.domain = domain + self.browser = browser + self.platform = platform + self.dateCreated = dateCreated + self.dateActive = dateActive + self.ip = ip + self.region = region + } + } + case webAuthorization(Cons_webAuthorization) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .webAuthorization(let _data): + if boxed { + buffer.appendInt32(-1493633966) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + serializeInt64(_data.botId, buffer: buffer, boxed: false) + serializeString(_data.domain, buffer: buffer, boxed: false) + serializeString(_data.browser, buffer: buffer, boxed: false) + serializeString(_data.platform, buffer: buffer, boxed: false) + serializeInt32(_data.dateCreated, buffer: buffer, boxed: false) + serializeInt32(_data.dateActive, buffer: buffer, boxed: false) + serializeString(_data.ip, buffer: buffer, boxed: false) + serializeString(_data.region, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .webAuthorization(let _data): + return ("webAuthorization", [("hash", _data.hash as Any), ("botId", _data.botId as Any), ("domain", _data.domain as Any), ("browser", _data.browser as Any), ("platform", _data.platform as Any), ("dateCreated", _data.dateCreated as Any), ("dateActive", _data.dateActive as Any), ("ip", _data.ip as Any), ("region", _data.region as Any)]) + } + } + + public static func parse_webAuthorization(_ reader: BufferReader) -> WebAuthorization? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Int64? + _2 = reader.readInt64() + var _3: String? + _3 = parseString(reader) + var _4: String? + _4 = parseString(reader) + var _5: String? + _5 = parseString(reader) + var _6: Int32? + _6 = reader.readInt32() + var _7: Int32? + _7 = reader.readInt32() + var _8: String? + _8 = parseString(reader) + var _9: String? + _9 = parseString(reader) + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + let _c7 = _7 != nil + let _c8 = _8 != nil + let _c9 = _9 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.WebAuthorization.webAuthorization(Cons_webAuthorization(hash: _1!, botId: _2!, domain: _3!, browser: _4!, platform: _5!, dateCreated: _6!, dateActive: _7!, ip: _8!, region: _9!)) + } + else { + return nil + } + } + } +} +public extension Api { + enum WebDocument: TypeConstructorDescription { + public class Cons_webDocument { + public var url: String + public var accessHash: Int64 + public var size: Int32 + public var mimeType: String + public var attributes: [Api.DocumentAttribute] + public init(url: String, accessHash: Int64, size: Int32, mimeType: String, attributes: [Api.DocumentAttribute]) { + self.url = url + self.accessHash = accessHash + self.size = size + self.mimeType = mimeType + self.attributes = attributes + } + } + public class Cons_webDocumentNoProxy { + public var url: String + public var size: Int32 + public var mimeType: String + public var attributes: [Api.DocumentAttribute] + public init(url: String, size: Int32, mimeType: String, attributes: [Api.DocumentAttribute]) { + self.url = url + self.size = size + self.mimeType = mimeType + self.attributes = attributes + } + } + case webDocument(Cons_webDocument) + case webDocumentNoProxy(Cons_webDocumentNoProxy) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .webDocument(let _data): + if boxed { + buffer.appendInt32(475467473) + } + serializeString(_data.url, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeInt32(_data.size, buffer: buffer, boxed: false) + serializeString(_data.mimeType, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.attributes.count)) + for item in _data.attributes { + item.serialize(buffer, true) + } + break + case .webDocumentNoProxy(let _data): + if boxed { + buffer.appendInt32(-104284986) + } + serializeString(_data.url, buffer: buffer, boxed: false) + serializeInt32(_data.size, buffer: buffer, boxed: false) + serializeString(_data.mimeType, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.attributes.count)) + for item in _data.attributes { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .webDocument(let _data): + return ("webDocument", [("url", _data.url as Any), ("accessHash", _data.accessHash as Any), ("size", _data.size as Any), ("mimeType", _data.mimeType as Any), ("attributes", _data.attributes as Any)]) + case .webDocumentNoProxy(let _data): + return ("webDocumentNoProxy", [("url", _data.url as Any), ("size", _data.size as Any), ("mimeType", _data.mimeType as Any), ("attributes", _data.attributes as Any)]) + } + } + + public static func parse_webDocument(_ reader: BufferReader) -> WebDocument? { + var _1: String? + _1 = parseString(reader) + var _2: Int64? + _2 = reader.readInt64() + var _3: Int32? + _3 = reader.readInt32() + var _4: String? + _4 = parseString(reader) + var _5: [Api.DocumentAttribute]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.DocumentAttribute.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.WebDocument.webDocument(Cons_webDocument(url: _1!, accessHash: _2!, size: _3!, mimeType: _4!, attributes: _5!)) + } + else { + return nil + } + } + public static func parse_webDocumentNoProxy(_ reader: BufferReader) -> WebDocument? { + var _1: String? + _1 = parseString(reader) + var _2: Int32? + _2 = reader.readInt32() + var _3: String? + _3 = parseString(reader) + var _4: [Api.DocumentAttribute]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.DocumentAttribute.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.WebDocument.webDocumentNoProxy(Cons_webDocumentNoProxy(url: _1!, size: _2!, mimeType: _3!, attributes: _4!)) + } + else { + return nil + } + } + } +} +public extension Api { + enum WebPage: TypeConstructorDescription { + public class Cons_webPage { + public var flags: Int32 + public var id: Int64 + public var url: String + public var displayUrl: String + public var hash: Int32 + public var type: String? + public var siteName: String? + public var title: String? + public var description: String? + public var photo: Api.Photo? + public var embedUrl: String? + public var embedType: String? + public var embedWidth: Int32? + public var embedHeight: Int32? + public var duration: Int32? + public var author: String? + public var document: Api.Document? + public var cachedPage: Api.Page? + public var attributes: [Api.WebPageAttribute]? + public init(flags: Int32, id: Int64, url: String, displayUrl: String, hash: Int32, type: String?, siteName: String?, title: String?, description: String?, photo: Api.Photo?, embedUrl: String?, embedType: String?, embedWidth: Int32?, embedHeight: Int32?, duration: Int32?, author: String?, document: Api.Document?, cachedPage: Api.Page?, attributes: [Api.WebPageAttribute]?) { + self.flags = flags + self.id = id + self.url = url + self.displayUrl = displayUrl + self.hash = hash + self.type = type + self.siteName = siteName + self.title = title + self.description = description + self.photo = photo + self.embedUrl = embedUrl + self.embedType = embedType + self.embedWidth = embedWidth + self.embedHeight = embedHeight + self.duration = duration + self.author = author + self.document = document + self.cachedPage = cachedPage + self.attributes = attributes + } + } + public class Cons_webPageEmpty { + public var flags: Int32 + public var id: Int64 + public var url: String? + public init(flags: Int32, id: Int64, url: String?) { + self.flags = flags + self.id = id + self.url = url + } + } + public class Cons_webPageNotModified { + public var flags: Int32 + public var cachedPageViews: Int32? + public init(flags: Int32, cachedPageViews: Int32?) { + self.flags = flags + self.cachedPageViews = cachedPageViews + } + } + public class Cons_webPagePending { + public var flags: Int32 + public var id: Int64 + public var url: String? + public var date: Int32 + public init(flags: Int32, id: Int64, url: String?, date: Int32) { + self.flags = flags + self.id = id + self.url = url + self.date = date + } + } + case webPage(Cons_webPage) + case webPageEmpty(Cons_webPageEmpty) + case webPageNotModified(Cons_webPageNotModified) + case webPagePending(Cons_webPagePending) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .webPage(let _data): + if boxed { + buffer.appendInt32(-392411726) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + serializeString(_data.displayUrl, buffer: buffer, boxed: false) + serializeInt32(_data.hash, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.type!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.siteName!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.description!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + _data.photo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeString(_data.embedUrl!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeString(_data.embedType!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + serializeInt32(_data.embedWidth!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + serializeInt32(_data.embedHeight!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 7) != 0 { + serializeInt32(_data.duration!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + serializeString(_data.author!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 9) != 0 { + _data.document!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.cachedPage!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 12) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.attributes!.count)) + for item in _data.attributes! { + item.serialize(buffer, true) + } + } + break + case .webPageEmpty(let _data): + if boxed { + buffer.appendInt32(555358088) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.url!, buffer: buffer, boxed: false) + } + break + case .webPageNotModified(let _data): + if boxed { + buffer.appendInt32(1930545681) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.cachedPageViews!, buffer: buffer, boxed: false) + } + break + case .webPagePending(let _data): + if boxed { + buffer.appendInt32(-1328464313) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.url!, buffer: buffer, boxed: false) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .webPage(let _data): + return ("webPage", [("flags", _data.flags as Any), ("id", _data.id as Any), ("url", _data.url as Any), ("displayUrl", _data.displayUrl as Any), ("hash", _data.hash as Any), ("type", _data.type as Any), ("siteName", _data.siteName as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("photo", _data.photo as Any), ("embedUrl", _data.embedUrl as Any), ("embedType", _data.embedType as Any), ("embedWidth", _data.embedWidth as Any), ("embedHeight", _data.embedHeight as Any), ("duration", _data.duration as Any), ("author", _data.author as Any), ("document", _data.document as Any), ("cachedPage", _data.cachedPage as Any), ("attributes", _data.attributes as Any)]) + case .webPageEmpty(let _data): + return ("webPageEmpty", [("flags", _data.flags as Any), ("id", _data.id as Any), ("url", _data.url as Any)]) + case .webPageNotModified(let _data): + return ("webPageNotModified", [("flags", _data.flags as Any), ("cachedPageViews", _data.cachedPageViews as Any)]) + case .webPagePending(let _data): + return ("webPagePending", [("flags", _data.flags as Any), ("id", _data.id as Any), ("url", _data.url as Any), ("date", _data.date as Any)]) + } + } + + public static func parse_webPage(_ reader: BufferReader) -> WebPage? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: String? + _3 = parseString(reader) + var _4: String? + _4 = parseString(reader) + var _5: Int32? + _5 = reader.readInt32() + var _6: String? + if Int(_1!) & Int(1 << 0) != 0 { + _6 = parseString(reader) + } + var _7: String? + if Int(_1!) & Int(1 << 1) != 0 { + _7 = parseString(reader) + } + var _8: String? + if Int(_1!) & Int(1 << 2) != 0 { + _8 = parseString(reader) + } + var _9: String? + if Int(_1!) & Int(1 << 3) != 0 { + _9 = parseString(reader) + } + var _10: Api.Photo? + if Int(_1!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _10 = Api.parse(reader, signature: signature) as? Api.Photo + } + } + var _11: String? + if Int(_1!) & Int(1 << 5) != 0 { + _11 = parseString(reader) + } + var _12: String? + if Int(_1!) & Int(1 << 5) != 0 { + _12 = parseString(reader) + } + var _13: Int32? + if Int(_1!) & Int(1 << 6) != 0 { + _13 = reader.readInt32() + } + var _14: Int32? + if Int(_1!) & Int(1 << 6) != 0 { + _14 = reader.readInt32() + } + var _15: Int32? + if Int(_1!) & Int(1 << 7) != 0 { + _15 = reader.readInt32() + } + var _16: String? + if Int(_1!) & Int(1 << 8) != 0 { + _16 = parseString(reader) + } + var _17: Api.Document? + if Int(_1!) & Int(1 << 9) != 0 { + if let signature = reader.readInt32() { + _17 = Api.parse(reader, signature: signature) as? Api.Document + } + } + var _18: Api.Page? + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _18 = Api.parse(reader, signature: signature) as? Api.Page + } + } + var _19: [Api.WebPageAttribute]? + if Int(_1!) & Int(1 << 12) != 0 { + if let _ = reader.readInt32() { + _19 = Api.parseVector(reader, elementSignature: 0, elementType: Api.WebPageAttribute.self) + } + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil + let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil + let _c8 = (Int(_1!) & Int(1 << 2) == 0) || _8 != nil + let _c9 = (Int(_1!) & Int(1 << 3) == 0) || _9 != nil + let _c10 = (Int(_1!) & Int(1 << 4) == 0) || _10 != nil + let _c11 = (Int(_1!) & Int(1 << 5) == 0) || _11 != nil + let _c12 = (Int(_1!) & Int(1 << 5) == 0) || _12 != nil + let _c13 = (Int(_1!) & Int(1 << 6) == 0) || _13 != nil + let _c14 = (Int(_1!) & Int(1 << 6) == 0) || _14 != nil + let _c15 = (Int(_1!) & Int(1 << 7) == 0) || _15 != nil + let _c16 = (Int(_1!) & Int(1 << 8) == 0) || _16 != nil + let _c17 = (Int(_1!) & Int(1 << 9) == 0) || _17 != nil + let _c18 = (Int(_1!) & Int(1 << 10) == 0) || _18 != nil + let _c19 = (Int(_1!) & Int(1 << 12) == 0) || _19 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 && _c18 && _c19 { + return Api.WebPage.webPage(Cons_webPage(flags: _1!, id: _2!, url: _3!, displayUrl: _4!, hash: _5!, type: _6, siteName: _7, title: _8, description: _9, photo: _10, embedUrl: _11, embedType: _12, embedWidth: _13, embedHeight: _14, duration: _15, author: _16, document: _17, cachedPage: _18, attributes: _19)) + } + else { + return nil + } + } + public static func parse_webPageEmpty(_ reader: BufferReader) -> WebPage? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: String? + if Int(_1!) & Int(1 << 0) != 0 { + _3 = parseString(reader) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + if _c1 && _c2 && _c3 { + return Api.WebPage.webPageEmpty(Cons_webPageEmpty(flags: _1!, id: _2!, url: _3)) + } + else { + return nil + } + } + public static func parse_webPageNotModified(_ reader: BufferReader) -> WebPage? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt32() + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + if _c1 && _c2 { + return Api.WebPage.webPageNotModified(Cons_webPageNotModified(flags: _1!, cachedPageViews: _2)) + } + else { + return nil + } + } + public static func parse_webPagePending(_ reader: BufferReader) -> WebPage? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: String? + if Int(_1!) & Int(1 << 0) != 0 { + _3 = parseString(reader) + } + var _4: Int32? + _4 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.WebPage.webPagePending(Cons_webPagePending(flags: _1!, id: _2!, url: _3, date: _4!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api3.swift b/submodules/TelegramApi/Sources/Api3.swift index b71ce826..00a1f59b 100644 --- a/submodules/TelegramApi/Sources/Api3.swift +++ b/submodules/TelegramApi/Sources/Api3.swift @@ -1,27 +1,37 @@ public extension Api { enum BusinessGreetingMessage: TypeConstructorDescription { - case businessGreetingMessage(shortcutId: Int32, recipients: Api.BusinessRecipients, noActivityDays: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .businessGreetingMessage(let shortcutId, let recipients, let noActivityDays): - if boxed { - buffer.appendInt32(-451302485) - } - serializeInt32(shortcutId, buffer: buffer, boxed: false) - recipients.serialize(buffer, true) - serializeInt32(noActivityDays, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .businessGreetingMessage(let shortcutId, let recipients, let noActivityDays): - return ("businessGreetingMessage", [("shortcutId", shortcutId as Any), ("recipients", recipients as Any), ("noActivityDays", noActivityDays as Any)]) - } - } - + public class Cons_businessGreetingMessage { + public var shortcutId: Int32 + public var recipients: Api.BusinessRecipients + public var noActivityDays: Int32 + public init(shortcutId: Int32, recipients: Api.BusinessRecipients, noActivityDays: Int32) { + self.shortcutId = shortcutId + self.recipients = recipients + self.noActivityDays = noActivityDays + } + } + case businessGreetingMessage(Cons_businessGreetingMessage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .businessGreetingMessage(let _data): + if boxed { + buffer.appendInt32(-451302485) + } + serializeInt32(_data.shortcutId, buffer: buffer, boxed: false) + _data.recipients.serialize(buffer, true) + serializeInt32(_data.noActivityDays, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .businessGreetingMessage(let _data): + return ("businessGreetingMessage", [("shortcutId", _data.shortcutId as Any), ("recipients", _data.recipients as Any), ("noActivityDays", _data.noActivityDays as Any)]) + } + } + public static func parse_businessGreetingMessage(_ reader: BufferReader) -> BusinessGreetingMessage? { var _1: Int32? _1 = reader.readInt32() @@ -34,39 +44,54 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.BusinessGreetingMessage.businessGreetingMessage(shortcutId: _1!, recipients: _2!, noActivityDays: _3!) + if _c1 && _c2 && _c3 { + return Api.BusinessGreetingMessage.businessGreetingMessage(Cons_businessGreetingMessage(shortcutId: _1!, recipients: _2!, noActivityDays: _3!)) + } + else { + return nil + } } - } } public extension Api { enum BusinessIntro: TypeConstructorDescription { - case businessIntro(flags: Int32, title: String, description: String, sticker: Api.Document?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .businessIntro(let flags, let title, let description, let sticker): - if boxed { - buffer.appendInt32(1510606445) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(description, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {sticker!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .businessIntro(let flags, let title, let description, let sticker): - return ("businessIntro", [("flags", flags as Any), ("title", title as Any), ("description", description as Any), ("sticker", sticker as Any)]) - } - } - + public class Cons_businessIntro { + public var flags: Int32 + public var title: String + public var description: String + public var sticker: Api.Document? + public init(flags: Int32, title: String, description: String, sticker: Api.Document?) { + self.flags = flags + self.title = title + self.description = description + self.sticker = sticker + } + } + case businessIntro(Cons_businessIntro) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .businessIntro(let _data): + if boxed { + buffer.appendInt32(1510606445) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.description, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.sticker!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .businessIntro(let _data): + return ("businessIntro", [("flags", _data.flags as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("sticker", _data.sticker as Any)]) + } + } + public static func parse_businessIntro(_ reader: BufferReader) -> BusinessIntro? { var _1: Int32? _1 = reader.readInt32() @@ -75,132 +100,171 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: Api.Document? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Document - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Document + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.BusinessIntro.businessIntro(flags: _1!, title: _2!, description: _3!, sticker: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.BusinessIntro.businessIntro(Cons_businessIntro(flags: _1!, title: _2!, description: _3!, sticker: _4)) + } + else { + return nil + } } - } } public extension Api { enum BusinessLocation: TypeConstructorDescription { - case businessLocation(flags: Int32, geoPoint: Api.GeoPoint?, address: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .businessLocation(let flags, let geoPoint, let address): - if boxed { - buffer.appendInt32(-1403249929) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {geoPoint!.serialize(buffer, true)} - serializeString(address, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .businessLocation(let flags, let geoPoint, let address): - return ("businessLocation", [("flags", flags as Any), ("geoPoint", geoPoint as Any), ("address", address as Any)]) - } - } - + public class Cons_businessLocation { + public var flags: Int32 + public var geoPoint: Api.GeoPoint? + public var address: String + public init(flags: Int32, geoPoint: Api.GeoPoint?, address: String) { + self.flags = flags + self.geoPoint = geoPoint + self.address = address + } + } + case businessLocation(Cons_businessLocation) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .businessLocation(let _data): + if boxed { + buffer.appendInt32(-1403249929) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.geoPoint!.serialize(buffer, true) + } + serializeString(_data.address, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .businessLocation(let _data): + return ("businessLocation", [("flags", _data.flags as Any), ("geoPoint", _data.geoPoint as Any), ("address", _data.address as Any)]) + } + } + public static func parse_businessLocation(_ reader: BufferReader) -> BusinessLocation? { var _1: Int32? _1 = reader.readInt32() var _2: Api.GeoPoint? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.GeoPoint - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.GeoPoint + } + } var _3: String? _3 = parseString(reader) let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.BusinessLocation.businessLocation(flags: _1!, geoPoint: _2, address: _3!) + if _c1 && _c2 && _c3 { + return Api.BusinessLocation.businessLocation(Cons_businessLocation(flags: _1!, geoPoint: _2, address: _3!)) + } + else { + return nil + } } - } } public extension Api { enum BusinessRecipients: TypeConstructorDescription { - case businessRecipients(flags: Int32, users: [Int64]?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .businessRecipients(let flags, let users): - if boxed { - buffer.appendInt32(554733559) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users!.count)) - for item in users! { + public class Cons_businessRecipients { + public var flags: Int32 + public var users: [Int64]? + public init(flags: Int32, users: [Int64]?) { + self.flags = flags + self.users = users + } + } + case businessRecipients(Cons_businessRecipients) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .businessRecipients(let _data): + if boxed { + buffer.appendInt32(554733559) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 4) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users!.count)) + for item in _data.users! { serializeInt64(item, buffer: buffer, boxed: false) - }} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .businessRecipients(let flags, let users): - return ("businessRecipients", [("flags", flags as Any), ("users", users as Any)]) - } - } - + } + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .businessRecipients(let _data): + return ("businessRecipients", [("flags", _data.flags as Any), ("users", _data.users as Any)]) + } + } + public static func parse_businessRecipients(_ reader: BufferReader) -> BusinessRecipients? { var _1: Int32? _1 = reader.readInt32() var _2: [Int64]? - if Int(_1!) & Int(1 << 4) != 0 {if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 4) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.BusinessRecipients.businessRecipients(flags: _1!, users: _2) + if _c1 && _c2 { + return Api.BusinessRecipients.businessRecipients(Cons_businessRecipients(flags: _1!, users: _2)) + } + else { + return nil + } } - } } public extension Api { enum BusinessWeeklyOpen: TypeConstructorDescription { - case businessWeeklyOpen(startMinute: Int32, endMinute: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .businessWeeklyOpen(let startMinute, let endMinute): - if boxed { - buffer.appendInt32(302717625) - } - serializeInt32(startMinute, buffer: buffer, boxed: false) - serializeInt32(endMinute, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .businessWeeklyOpen(let startMinute, let endMinute): - return ("businessWeeklyOpen", [("startMinute", startMinute as Any), ("endMinute", endMinute as Any)]) - } - } - + public class Cons_businessWeeklyOpen { + public var startMinute: Int32 + public var endMinute: Int32 + public init(startMinute: Int32, endMinute: Int32) { + self.startMinute = startMinute + self.endMinute = endMinute + } + } + case businessWeeklyOpen(Cons_businessWeeklyOpen) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .businessWeeklyOpen(let _data): + if boxed { + buffer.appendInt32(302717625) + } + serializeInt32(_data.startMinute, buffer: buffer, boxed: false) + serializeInt32(_data.endMinute, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .businessWeeklyOpen(let _data): + return ("businessWeeklyOpen", [("startMinute", _data.startMinute as Any), ("endMinute", _data.endMinute as Any)]) + } + } + public static func parse_businessWeeklyOpen(_ reader: BufferReader) -> BusinessWeeklyOpen? { var _1: Int32? _1 = reader.readInt32() @@ -208,41 +272,53 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.BusinessWeeklyOpen.businessWeeklyOpen(startMinute: _1!, endMinute: _2!) + if _c1 && _c2 { + return Api.BusinessWeeklyOpen.businessWeeklyOpen(Cons_businessWeeklyOpen(startMinute: _1!, endMinute: _2!)) + } + else { + return nil + } } - } } public extension Api { enum BusinessWorkHours: TypeConstructorDescription { - case businessWorkHours(flags: Int32, timezoneId: String, weeklyOpen: [Api.BusinessWeeklyOpen]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .businessWorkHours(let flags, let timezoneId, let weeklyOpen): - if boxed { - buffer.appendInt32(-1936543592) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(timezoneId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(weeklyOpen.count)) - for item in weeklyOpen { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .businessWorkHours(let flags, let timezoneId, let weeklyOpen): - return ("businessWorkHours", [("flags", flags as Any), ("timezoneId", timezoneId as Any), ("weeklyOpen", weeklyOpen as Any)]) - } - } - + public class Cons_businessWorkHours { + public var flags: Int32 + public var timezoneId: String + public var weeklyOpen: [Api.BusinessWeeklyOpen] + public init(flags: Int32, timezoneId: String, weeklyOpen: [Api.BusinessWeeklyOpen]) { + self.flags = flags + self.timezoneId = timezoneId + self.weeklyOpen = weeklyOpen + } + } + case businessWorkHours(Cons_businessWorkHours) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .businessWorkHours(let _data): + if boxed { + buffer.appendInt32(-1936543592) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.timezoneId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.weeklyOpen.count)) + for item in _data.weeklyOpen { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .businessWorkHours(let _data): + return ("businessWorkHours", [("flags", _data.flags as Any), ("timezoneId", _data.timezoneId as Any), ("weeklyOpen", _data.weeklyOpen as Any)]) + } + } + public static func parse_businessWorkHours(_ reader: BufferReader) -> BusinessWorkHours? { var _1: Int32? _1 = reader.readInt32() @@ -255,75 +331,93 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.BusinessWorkHours.businessWorkHours(flags: _1!, timezoneId: _2!, weeklyOpen: _3!) + if _c1 && _c2 && _c3 { + return Api.BusinessWorkHours.businessWorkHours(Cons_businessWorkHours(flags: _1!, timezoneId: _2!, weeklyOpen: _3!)) + } + else { + return nil + } } - } } public extension Api { enum CdnConfig: TypeConstructorDescription { - case cdnConfig(publicKeys: [Api.CdnPublicKey]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .cdnConfig(let publicKeys): - if boxed { - buffer.appendInt32(1462101002) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(publicKeys.count)) - for item in publicKeys { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .cdnConfig(let publicKeys): - return ("cdnConfig", [("publicKeys", publicKeys as Any)]) - } - } - + public class Cons_cdnConfig { + public var publicKeys: [Api.CdnPublicKey] + public init(publicKeys: [Api.CdnPublicKey]) { + self.publicKeys = publicKeys + } + } + case cdnConfig(Cons_cdnConfig) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .cdnConfig(let _data): + if boxed { + buffer.appendInt32(1462101002) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.publicKeys.count)) + for item in _data.publicKeys { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .cdnConfig(let _data): + return ("cdnConfig", [("publicKeys", _data.publicKeys as Any)]) + } + } + public static func parse_cdnConfig(_ reader: BufferReader) -> CdnConfig? { var _1: [Api.CdnPublicKey]? if let _ = reader.readInt32() { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.CdnPublicKey.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.CdnConfig.cdnConfig(publicKeys: _1!) + if _c1 { + return Api.CdnConfig.cdnConfig(Cons_cdnConfig(publicKeys: _1!)) + } + else { + return nil + } } - } } public extension Api { enum CdnPublicKey: TypeConstructorDescription { - case cdnPublicKey(dcId: Int32, publicKey: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .cdnPublicKey(let dcId, let publicKey): - if boxed { - buffer.appendInt32(-914167110) - } - serializeInt32(dcId, buffer: buffer, boxed: false) - serializeString(publicKey, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .cdnPublicKey(let dcId, let publicKey): - return ("cdnPublicKey", [("dcId", dcId as Any), ("publicKey", publicKey as Any)]) - } - } - + public class Cons_cdnPublicKey { + public var dcId: Int32 + public var publicKey: String + public init(dcId: Int32, publicKey: String) { + self.dcId = dcId + self.publicKey = publicKey + } + } + case cdnPublicKey(Cons_cdnPublicKey) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .cdnPublicKey(let _data): + if boxed { + buffer.appendInt32(-914167110) + } + serializeInt32(_data.dcId, buffer: buffer, boxed: false) + serializeString(_data.publicKey, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .cdnPublicKey(let _data): + return ("cdnPublicKey", [("dcId", _data.dcId as Any), ("publicKey", _data.publicKey as Any)]) + } + } + public static func parse_cdnPublicKey(_ reader: BufferReader) -> CdnPublicKey? { var _1: Int32? _1 = reader.readInt32() @@ -331,38 +425,52 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.CdnPublicKey.cdnPublicKey(dcId: _1!, publicKey: _2!) + if _c1 && _c2 { + return Api.CdnPublicKey.cdnPublicKey(Cons_cdnPublicKey(dcId: _1!, publicKey: _2!)) + } + else { + return nil + } } - } } public extension Api { indirect enum ChannelAdminLogEvent: TypeConstructorDescription { - case channelAdminLogEvent(id: Int64, date: Int32, userId: Int64, action: Api.ChannelAdminLogEventAction) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .channelAdminLogEvent(let id, let date, let userId, let action): - if boxed { - buffer.appendInt32(531458253) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - action.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .channelAdminLogEvent(let id, let date, let userId, let action): - return ("channelAdminLogEvent", [("id", id as Any), ("date", date as Any), ("userId", userId as Any), ("action", action as Any)]) - } - } - + public class Cons_channelAdminLogEvent { + public var id: Int64 + public var date: Int32 + public var userId: Int64 + public var action: Api.ChannelAdminLogEventAction + public init(id: Int64, date: Int32, userId: Int64, action: Api.ChannelAdminLogEventAction) { + self.id = id + self.date = date + self.userId = userId + self.action = action + } + } + case channelAdminLogEvent(Cons_channelAdminLogEvent) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .channelAdminLogEvent(let _data): + if boxed { + buffer.appendInt32(531458253) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + _data.action.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .channelAdminLogEvent(let _data): + return ("channelAdminLogEvent", [("id", _data.id as Any), ("date", _data.date as Any), ("userId", _data.userId as Any), ("action", _data.action as Any)]) + } + } + public static func parse_channelAdminLogEvent(_ reader: BufferReader) -> ChannelAdminLogEvent? { var _1: Int64? _1 = reader.readInt64() @@ -378,522 +486,872 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.ChannelAdminLogEvent.channelAdminLogEvent(id: _1!, date: _2!, userId: _3!, action: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.ChannelAdminLogEvent.channelAdminLogEvent(Cons_channelAdminLogEvent(id: _1!, date: _2!, userId: _3!, action: _4!)) + } + else { + return nil + } } - } } public extension Api { indirect enum ChannelAdminLogEventAction: TypeConstructorDescription { - case channelAdminLogEventActionChangeAbout(prevValue: String, newValue: String) - case channelAdminLogEventActionChangeAvailableReactions(prevValue: Api.ChatReactions, newValue: Api.ChatReactions) - case channelAdminLogEventActionChangeEmojiStatus(prevValue: Api.EmojiStatus, newValue: Api.EmojiStatus) - case channelAdminLogEventActionChangeEmojiStickerSet(prevStickerset: Api.InputStickerSet, newStickerset: Api.InputStickerSet) - case channelAdminLogEventActionChangeHistoryTTL(prevValue: Int32, newValue: Int32) - case channelAdminLogEventActionChangeLinkedChat(prevValue: Int64, newValue: Int64) - case channelAdminLogEventActionChangeLocation(prevValue: Api.ChannelLocation, newValue: Api.ChannelLocation) - case channelAdminLogEventActionChangePeerColor(prevValue: Api.PeerColor, newValue: Api.PeerColor) - case channelAdminLogEventActionChangePhoto(prevPhoto: Api.Photo, newPhoto: Api.Photo) - case channelAdminLogEventActionChangeProfilePeerColor(prevValue: Api.PeerColor, newValue: Api.PeerColor) - case channelAdminLogEventActionChangeStickerSet(prevStickerset: Api.InputStickerSet, newStickerset: Api.InputStickerSet) - case channelAdminLogEventActionChangeTitle(prevValue: String, newValue: String) - case channelAdminLogEventActionChangeUsername(prevValue: String, newValue: String) - case channelAdminLogEventActionChangeUsernames(prevValue: [String], newValue: [String]) - case channelAdminLogEventActionChangeWallpaper(prevValue: Api.WallPaper, newValue: Api.WallPaper) - case channelAdminLogEventActionCreateTopic(topic: Api.ForumTopic) - case channelAdminLogEventActionDefaultBannedRights(prevBannedRights: Api.ChatBannedRights, newBannedRights: Api.ChatBannedRights) - case channelAdminLogEventActionDeleteMessage(message: Api.Message) - case channelAdminLogEventActionDeleteTopic(topic: Api.ForumTopic) - case channelAdminLogEventActionDiscardGroupCall(call: Api.InputGroupCall) - case channelAdminLogEventActionEditMessage(prevMessage: Api.Message, newMessage: Api.Message) - case channelAdminLogEventActionEditTopic(prevTopic: Api.ForumTopic, newTopic: Api.ForumTopic) - case channelAdminLogEventActionExportedInviteDelete(invite: Api.ExportedChatInvite) - case channelAdminLogEventActionExportedInviteEdit(prevInvite: Api.ExportedChatInvite, newInvite: Api.ExportedChatInvite) - case channelAdminLogEventActionExportedInviteRevoke(invite: Api.ExportedChatInvite) - case channelAdminLogEventActionParticipantInvite(participant: Api.ChannelParticipant) + public class Cons_channelAdminLogEventActionChangeAbout { + public var prevValue: String + public var newValue: String + public init(prevValue: String, newValue: String) { + self.prevValue = prevValue + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionChangeAvailableReactions { + public var prevValue: Api.ChatReactions + public var newValue: Api.ChatReactions + public init(prevValue: Api.ChatReactions, newValue: Api.ChatReactions) { + self.prevValue = prevValue + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionChangeEmojiStatus { + public var prevValue: Api.EmojiStatus + public var newValue: Api.EmojiStatus + public init(prevValue: Api.EmojiStatus, newValue: Api.EmojiStatus) { + self.prevValue = prevValue + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionChangeEmojiStickerSet { + public var prevStickerset: Api.InputStickerSet + public var newStickerset: Api.InputStickerSet + public init(prevStickerset: Api.InputStickerSet, newStickerset: Api.InputStickerSet) { + self.prevStickerset = prevStickerset + self.newStickerset = newStickerset + } + } + public class Cons_channelAdminLogEventActionChangeHistoryTTL { + public var prevValue: Int32 + public var newValue: Int32 + public init(prevValue: Int32, newValue: Int32) { + self.prevValue = prevValue + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionChangeLinkedChat { + public var prevValue: Int64 + public var newValue: Int64 + public init(prevValue: Int64, newValue: Int64) { + self.prevValue = prevValue + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionChangeLocation { + public var prevValue: Api.ChannelLocation + public var newValue: Api.ChannelLocation + public init(prevValue: Api.ChannelLocation, newValue: Api.ChannelLocation) { + self.prevValue = prevValue + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionChangePeerColor { + public var prevValue: Api.PeerColor + public var newValue: Api.PeerColor + public init(prevValue: Api.PeerColor, newValue: Api.PeerColor) { + self.prevValue = prevValue + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionChangePhoto { + public var prevPhoto: Api.Photo + public var newPhoto: Api.Photo + public init(prevPhoto: Api.Photo, newPhoto: Api.Photo) { + self.prevPhoto = prevPhoto + self.newPhoto = newPhoto + } + } + public class Cons_channelAdminLogEventActionChangeProfilePeerColor { + public var prevValue: Api.PeerColor + public var newValue: Api.PeerColor + public init(prevValue: Api.PeerColor, newValue: Api.PeerColor) { + self.prevValue = prevValue + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionChangeStickerSet { + public var prevStickerset: Api.InputStickerSet + public var newStickerset: Api.InputStickerSet + public init(prevStickerset: Api.InputStickerSet, newStickerset: Api.InputStickerSet) { + self.prevStickerset = prevStickerset + self.newStickerset = newStickerset + } + } + public class Cons_channelAdminLogEventActionChangeTitle { + public var prevValue: String + public var newValue: String + public init(prevValue: String, newValue: String) { + self.prevValue = prevValue + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionChangeUsername { + public var prevValue: String + public var newValue: String + public init(prevValue: String, newValue: String) { + self.prevValue = prevValue + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionChangeUsernames { + public var prevValue: [String] + public var newValue: [String] + public init(prevValue: [String], newValue: [String]) { + self.prevValue = prevValue + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionChangeWallpaper { + public var prevValue: Api.WallPaper + public var newValue: Api.WallPaper + public init(prevValue: Api.WallPaper, newValue: Api.WallPaper) { + self.prevValue = prevValue + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionCreateTopic { + public var topic: Api.ForumTopic + public init(topic: Api.ForumTopic) { + self.topic = topic + } + } + public class Cons_channelAdminLogEventActionDefaultBannedRights { + public var prevBannedRights: Api.ChatBannedRights + public var newBannedRights: Api.ChatBannedRights + public init(prevBannedRights: Api.ChatBannedRights, newBannedRights: Api.ChatBannedRights) { + self.prevBannedRights = prevBannedRights + self.newBannedRights = newBannedRights + } + } + public class Cons_channelAdminLogEventActionDeleteMessage { + public var message: Api.Message + public init(message: Api.Message) { + self.message = message + } + } + public class Cons_channelAdminLogEventActionDeleteTopic { + public var topic: Api.ForumTopic + public init(topic: Api.ForumTopic) { + self.topic = topic + } + } + public class Cons_channelAdminLogEventActionDiscardGroupCall { + public var call: Api.InputGroupCall + public init(call: Api.InputGroupCall) { + self.call = call + } + } + public class Cons_channelAdminLogEventActionEditMessage { + public var prevMessage: Api.Message + public var newMessage: Api.Message + public init(prevMessage: Api.Message, newMessage: Api.Message) { + self.prevMessage = prevMessage + self.newMessage = newMessage + } + } + public class Cons_channelAdminLogEventActionEditTopic { + public var prevTopic: Api.ForumTopic + public var newTopic: Api.ForumTopic + public init(prevTopic: Api.ForumTopic, newTopic: Api.ForumTopic) { + self.prevTopic = prevTopic + self.newTopic = newTopic + } + } + public class Cons_channelAdminLogEventActionExportedInviteDelete { + public var invite: Api.ExportedChatInvite + public init(invite: Api.ExportedChatInvite) { + self.invite = invite + } + } + public class Cons_channelAdminLogEventActionExportedInviteEdit { + public var prevInvite: Api.ExportedChatInvite + public var newInvite: Api.ExportedChatInvite + public init(prevInvite: Api.ExportedChatInvite, newInvite: Api.ExportedChatInvite) { + self.prevInvite = prevInvite + self.newInvite = newInvite + } + } + public class Cons_channelAdminLogEventActionExportedInviteRevoke { + public var invite: Api.ExportedChatInvite + public init(invite: Api.ExportedChatInvite) { + self.invite = invite + } + } + public class Cons_channelAdminLogEventActionParticipantInvite { + public var participant: Api.ChannelParticipant + public init(participant: Api.ChannelParticipant) { + self.participant = participant + } + } + public class Cons_channelAdminLogEventActionParticipantJoinByInvite { + public var flags: Int32 + public var invite: Api.ExportedChatInvite + public init(flags: Int32, invite: Api.ExportedChatInvite) { + self.flags = flags + self.invite = invite + } + } + public class Cons_channelAdminLogEventActionParticipantJoinByRequest { + public var invite: Api.ExportedChatInvite + public var approvedBy: Int64 + public init(invite: Api.ExportedChatInvite, approvedBy: Int64) { + self.invite = invite + self.approvedBy = approvedBy + } + } + public class Cons_channelAdminLogEventActionParticipantMute { + public var participant: Api.GroupCallParticipant + public init(participant: Api.GroupCallParticipant) { + self.participant = participant + } + } + public class Cons_channelAdminLogEventActionParticipantSubExtend { + public var prevParticipant: Api.ChannelParticipant + public var newParticipant: Api.ChannelParticipant + public init(prevParticipant: Api.ChannelParticipant, newParticipant: Api.ChannelParticipant) { + self.prevParticipant = prevParticipant + self.newParticipant = newParticipant + } + } + public class Cons_channelAdminLogEventActionParticipantToggleAdmin { + public var prevParticipant: Api.ChannelParticipant + public var newParticipant: Api.ChannelParticipant + public init(prevParticipant: Api.ChannelParticipant, newParticipant: Api.ChannelParticipant) { + self.prevParticipant = prevParticipant + self.newParticipant = newParticipant + } + } + public class Cons_channelAdminLogEventActionParticipantToggleBan { + public var prevParticipant: Api.ChannelParticipant + public var newParticipant: Api.ChannelParticipant + public init(prevParticipant: Api.ChannelParticipant, newParticipant: Api.ChannelParticipant) { + self.prevParticipant = prevParticipant + self.newParticipant = newParticipant + } + } + public class Cons_channelAdminLogEventActionParticipantUnmute { + public var participant: Api.GroupCallParticipant + public init(participant: Api.GroupCallParticipant) { + self.participant = participant + } + } + public class Cons_channelAdminLogEventActionParticipantVolume { + public var participant: Api.GroupCallParticipant + public init(participant: Api.GroupCallParticipant) { + self.participant = participant + } + } + public class Cons_channelAdminLogEventActionPinTopic { + public var flags: Int32 + public var prevTopic: Api.ForumTopic? + public var newTopic: Api.ForumTopic? + public init(flags: Int32, prevTopic: Api.ForumTopic?, newTopic: Api.ForumTopic?) { + self.flags = flags + self.prevTopic = prevTopic + self.newTopic = newTopic + } + } + public class Cons_channelAdminLogEventActionSendMessage { + public var message: Api.Message + public init(message: Api.Message) { + self.message = message + } + } + public class Cons_channelAdminLogEventActionStartGroupCall { + public var call: Api.InputGroupCall + public init(call: Api.InputGroupCall) { + self.call = call + } + } + public class Cons_channelAdminLogEventActionStopPoll { + public var message: Api.Message + public init(message: Api.Message) { + self.message = message + } + } + public class Cons_channelAdminLogEventActionToggleAntiSpam { + public var newValue: Api.Bool + public init(newValue: Api.Bool) { + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionToggleAutotranslation { + public var newValue: Api.Bool + public init(newValue: Api.Bool) { + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionToggleForum { + public var newValue: Api.Bool + public init(newValue: Api.Bool) { + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionToggleGroupCallSetting { + public var joinMuted: Api.Bool + public init(joinMuted: Api.Bool) { + self.joinMuted = joinMuted + } + } + public class Cons_channelAdminLogEventActionToggleInvites { + public var newValue: Api.Bool + public init(newValue: Api.Bool) { + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionToggleNoForwards { + public var newValue: Api.Bool + public init(newValue: Api.Bool) { + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionTogglePreHistoryHidden { + public var newValue: Api.Bool + public init(newValue: Api.Bool) { + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionToggleSignatureProfiles { + public var newValue: Api.Bool + public init(newValue: Api.Bool) { + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionToggleSignatures { + public var newValue: Api.Bool + public init(newValue: Api.Bool) { + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionToggleSlowMode { + public var prevValue: Int32 + public var newValue: Int32 + public init(prevValue: Int32, newValue: Int32) { + self.prevValue = prevValue + self.newValue = newValue + } + } + public class Cons_channelAdminLogEventActionUpdatePinned { + public var message: Api.Message + public init(message: Api.Message) { + self.message = message + } + } + case channelAdminLogEventActionChangeAbout(Cons_channelAdminLogEventActionChangeAbout) + case channelAdminLogEventActionChangeAvailableReactions(Cons_channelAdminLogEventActionChangeAvailableReactions) + case channelAdminLogEventActionChangeEmojiStatus(Cons_channelAdminLogEventActionChangeEmojiStatus) + case channelAdminLogEventActionChangeEmojiStickerSet(Cons_channelAdminLogEventActionChangeEmojiStickerSet) + case channelAdminLogEventActionChangeHistoryTTL(Cons_channelAdminLogEventActionChangeHistoryTTL) + case channelAdminLogEventActionChangeLinkedChat(Cons_channelAdminLogEventActionChangeLinkedChat) + case channelAdminLogEventActionChangeLocation(Cons_channelAdminLogEventActionChangeLocation) + case channelAdminLogEventActionChangePeerColor(Cons_channelAdminLogEventActionChangePeerColor) + case channelAdminLogEventActionChangePhoto(Cons_channelAdminLogEventActionChangePhoto) + case channelAdminLogEventActionChangeProfilePeerColor(Cons_channelAdminLogEventActionChangeProfilePeerColor) + case channelAdminLogEventActionChangeStickerSet(Cons_channelAdminLogEventActionChangeStickerSet) + case channelAdminLogEventActionChangeTitle(Cons_channelAdminLogEventActionChangeTitle) + case channelAdminLogEventActionChangeUsername(Cons_channelAdminLogEventActionChangeUsername) + case channelAdminLogEventActionChangeUsernames(Cons_channelAdminLogEventActionChangeUsernames) + case channelAdminLogEventActionChangeWallpaper(Cons_channelAdminLogEventActionChangeWallpaper) + case channelAdminLogEventActionCreateTopic(Cons_channelAdminLogEventActionCreateTopic) + case channelAdminLogEventActionDefaultBannedRights(Cons_channelAdminLogEventActionDefaultBannedRights) + case channelAdminLogEventActionDeleteMessage(Cons_channelAdminLogEventActionDeleteMessage) + case channelAdminLogEventActionDeleteTopic(Cons_channelAdminLogEventActionDeleteTopic) + case channelAdminLogEventActionDiscardGroupCall(Cons_channelAdminLogEventActionDiscardGroupCall) + case channelAdminLogEventActionEditMessage(Cons_channelAdminLogEventActionEditMessage) + case channelAdminLogEventActionEditTopic(Cons_channelAdminLogEventActionEditTopic) + case channelAdminLogEventActionExportedInviteDelete(Cons_channelAdminLogEventActionExportedInviteDelete) + case channelAdminLogEventActionExportedInviteEdit(Cons_channelAdminLogEventActionExportedInviteEdit) + case channelAdminLogEventActionExportedInviteRevoke(Cons_channelAdminLogEventActionExportedInviteRevoke) + case channelAdminLogEventActionParticipantInvite(Cons_channelAdminLogEventActionParticipantInvite) case channelAdminLogEventActionParticipantJoin - case channelAdminLogEventActionParticipantJoinByInvite(flags: Int32, invite: Api.ExportedChatInvite) - case channelAdminLogEventActionParticipantJoinByRequest(invite: Api.ExportedChatInvite, approvedBy: Int64) + case channelAdminLogEventActionParticipantJoinByInvite(Cons_channelAdminLogEventActionParticipantJoinByInvite) + case channelAdminLogEventActionParticipantJoinByRequest(Cons_channelAdminLogEventActionParticipantJoinByRequest) case channelAdminLogEventActionParticipantLeave - case channelAdminLogEventActionParticipantMute(participant: Api.GroupCallParticipant) - case channelAdminLogEventActionParticipantSubExtend(prevParticipant: Api.ChannelParticipant, newParticipant: Api.ChannelParticipant) - case channelAdminLogEventActionParticipantToggleAdmin(prevParticipant: Api.ChannelParticipant, newParticipant: Api.ChannelParticipant) - case channelAdminLogEventActionParticipantToggleBan(prevParticipant: Api.ChannelParticipant, newParticipant: Api.ChannelParticipant) - case channelAdminLogEventActionParticipantUnmute(participant: Api.GroupCallParticipant) - case channelAdminLogEventActionParticipantVolume(participant: Api.GroupCallParticipant) - case channelAdminLogEventActionPinTopic(flags: Int32, prevTopic: Api.ForumTopic?, newTopic: Api.ForumTopic?) - case channelAdminLogEventActionSendMessage(message: Api.Message) - case channelAdminLogEventActionStartGroupCall(call: Api.InputGroupCall) - case channelAdminLogEventActionStopPoll(message: Api.Message) - case channelAdminLogEventActionToggleAntiSpam(newValue: Api.Bool) - case channelAdminLogEventActionToggleAutotranslation(newValue: Api.Bool) - case channelAdminLogEventActionToggleForum(newValue: Api.Bool) - case channelAdminLogEventActionToggleGroupCallSetting(joinMuted: Api.Bool) - case channelAdminLogEventActionToggleInvites(newValue: Api.Bool) - case channelAdminLogEventActionToggleNoForwards(newValue: Api.Bool) - case channelAdminLogEventActionTogglePreHistoryHidden(newValue: Api.Bool) - case channelAdminLogEventActionToggleSignatureProfiles(newValue: Api.Bool) - case channelAdminLogEventActionToggleSignatures(newValue: Api.Bool) - case channelAdminLogEventActionToggleSlowMode(prevValue: Int32, newValue: Int32) - case channelAdminLogEventActionUpdatePinned(message: Api.Message) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .channelAdminLogEventActionChangeAbout(let prevValue, let newValue): - if boxed { - buffer.appendInt32(1427671598) - } - serializeString(prevValue, buffer: buffer, boxed: false) - serializeString(newValue, buffer: buffer, boxed: false) - break - case .channelAdminLogEventActionChangeAvailableReactions(let prevValue, let newValue): - if boxed { - buffer.appendInt32(-1102180616) - } - prevValue.serialize(buffer, true) - newValue.serialize(buffer, true) - break - case .channelAdminLogEventActionChangeEmojiStatus(let prevValue, let newValue): - if boxed { - buffer.appendInt32(1051328177) - } - prevValue.serialize(buffer, true) - newValue.serialize(buffer, true) - break - case .channelAdminLogEventActionChangeEmojiStickerSet(let prevStickerset, let newStickerset): - if boxed { - buffer.appendInt32(1188577451) - } - prevStickerset.serialize(buffer, true) - newStickerset.serialize(buffer, true) - break - case .channelAdminLogEventActionChangeHistoryTTL(let prevValue, let newValue): - if boxed { - buffer.appendInt32(1855199800) - } - serializeInt32(prevValue, buffer: buffer, boxed: false) - serializeInt32(newValue, buffer: buffer, boxed: false) - break - case .channelAdminLogEventActionChangeLinkedChat(let prevValue, let newValue): - if boxed { - buffer.appendInt32(84703944) - } - serializeInt64(prevValue, buffer: buffer, boxed: false) - serializeInt64(newValue, buffer: buffer, boxed: false) - break - case .channelAdminLogEventActionChangeLocation(let prevValue, let newValue): - if boxed { - buffer.appendInt32(241923758) - } - prevValue.serialize(buffer, true) - newValue.serialize(buffer, true) - break - case .channelAdminLogEventActionChangePeerColor(let prevValue, let newValue): - if boxed { - buffer.appendInt32(1469507456) - } - prevValue.serialize(buffer, true) - newValue.serialize(buffer, true) - break - case .channelAdminLogEventActionChangePhoto(let prevPhoto, let newPhoto): - if boxed { - buffer.appendInt32(1129042607) - } - prevPhoto.serialize(buffer, true) - newPhoto.serialize(buffer, true) - break - case .channelAdminLogEventActionChangeProfilePeerColor(let prevValue, let newValue): - if boxed { - buffer.appendInt32(1581742885) - } - prevValue.serialize(buffer, true) - newValue.serialize(buffer, true) - break - case .channelAdminLogEventActionChangeStickerSet(let prevStickerset, let newStickerset): - if boxed { - buffer.appendInt32(-1312568665) - } - prevStickerset.serialize(buffer, true) - newStickerset.serialize(buffer, true) - break - case .channelAdminLogEventActionChangeTitle(let prevValue, let newValue): - if boxed { - buffer.appendInt32(-421545947) - } - serializeString(prevValue, buffer: buffer, boxed: false) - serializeString(newValue, buffer: buffer, boxed: false) - break - case .channelAdminLogEventActionChangeUsername(let prevValue, let newValue): - if boxed { - buffer.appendInt32(1783299128) - } - serializeString(prevValue, buffer: buffer, boxed: false) - serializeString(newValue, buffer: buffer, boxed: false) - break - case .channelAdminLogEventActionChangeUsernames(let prevValue, let newValue): - if boxed { - buffer.appendInt32(-263212119) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(prevValue.count)) - for item in prevValue { - serializeString(item, buffer: buffer, boxed: false) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(newValue.count)) - for item in newValue { - serializeString(item, buffer: buffer, boxed: false) - } - break - case .channelAdminLogEventActionChangeWallpaper(let prevValue, let newValue): - if boxed { - buffer.appendInt32(834362706) - } - prevValue.serialize(buffer, true) - newValue.serialize(buffer, true) - break - case .channelAdminLogEventActionCreateTopic(let topic): - if boxed { - buffer.appendInt32(1483767080) - } - topic.serialize(buffer, true) - break - case .channelAdminLogEventActionDefaultBannedRights(let prevBannedRights, let newBannedRights): - if boxed { - buffer.appendInt32(771095562) - } - prevBannedRights.serialize(buffer, true) - newBannedRights.serialize(buffer, true) - break - case .channelAdminLogEventActionDeleteMessage(let message): - if boxed { - buffer.appendInt32(1121994683) - } - message.serialize(buffer, true) - break - case .channelAdminLogEventActionDeleteTopic(let topic): - if boxed { - buffer.appendInt32(-1374254839) - } - topic.serialize(buffer, true) - break - case .channelAdminLogEventActionDiscardGroupCall(let call): - if boxed { - buffer.appendInt32(-610299584) - } - call.serialize(buffer, true) - break - case .channelAdminLogEventActionEditMessage(let prevMessage, let newMessage): - if boxed { - buffer.appendInt32(1889215493) - } - prevMessage.serialize(buffer, true) - newMessage.serialize(buffer, true) - break - case .channelAdminLogEventActionEditTopic(let prevTopic, let newTopic): - if boxed { - buffer.appendInt32(-261103096) - } - prevTopic.serialize(buffer, true) - newTopic.serialize(buffer, true) - break - case .channelAdminLogEventActionExportedInviteDelete(let invite): - if boxed { - buffer.appendInt32(1515256996) - } - invite.serialize(buffer, true) - break - case .channelAdminLogEventActionExportedInviteEdit(let prevInvite, let newInvite): - if boxed { - buffer.appendInt32(-384910503) - } - prevInvite.serialize(buffer, true) - newInvite.serialize(buffer, true) - break - case .channelAdminLogEventActionExportedInviteRevoke(let invite): - if boxed { - buffer.appendInt32(1091179342) - } - invite.serialize(buffer, true) - break - case .channelAdminLogEventActionParticipantInvite(let participant): - if boxed { - buffer.appendInt32(-484690728) - } - participant.serialize(buffer, true) - break - case .channelAdminLogEventActionParticipantJoin: - if boxed { - buffer.appendInt32(405815507) - } - - break - case .channelAdminLogEventActionParticipantJoinByInvite(let flags, let invite): - if boxed { - buffer.appendInt32(-23084712) - } - serializeInt32(flags, buffer: buffer, boxed: false) - invite.serialize(buffer, true) - break - case .channelAdminLogEventActionParticipantJoinByRequest(let invite, let approvedBy): - if boxed { - buffer.appendInt32(-1347021750) - } - invite.serialize(buffer, true) - serializeInt64(approvedBy, buffer: buffer, boxed: false) - break - case .channelAdminLogEventActionParticipantLeave: - if boxed { - buffer.appendInt32(-124291086) - } - - break - case .channelAdminLogEventActionParticipantMute(let participant): - if boxed { - buffer.appendInt32(-115071790) - } - participant.serialize(buffer, true) - break - case .channelAdminLogEventActionParticipantSubExtend(let prevParticipant, let newParticipant): - if boxed { - buffer.appendInt32(1684286899) - } - prevParticipant.serialize(buffer, true) - newParticipant.serialize(buffer, true) - break - case .channelAdminLogEventActionParticipantToggleAdmin(let prevParticipant, let newParticipant): - if boxed { - buffer.appendInt32(-714643696) - } - prevParticipant.serialize(buffer, true) - newParticipant.serialize(buffer, true) - break - case .channelAdminLogEventActionParticipantToggleBan(let prevParticipant, let newParticipant): - if boxed { - buffer.appendInt32(-422036098) - } - prevParticipant.serialize(buffer, true) - newParticipant.serialize(buffer, true) - break - case .channelAdminLogEventActionParticipantUnmute(let participant): - if boxed { - buffer.appendInt32(-431740480) - } - participant.serialize(buffer, true) - break - case .channelAdminLogEventActionParticipantVolume(let participant): - if boxed { - buffer.appendInt32(1048537159) - } - participant.serialize(buffer, true) - break - case .channelAdminLogEventActionPinTopic(let flags, let prevTopic, let newTopic): - if boxed { - buffer.appendInt32(1569535291) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {prevTopic!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {newTopic!.serialize(buffer, true)} - break - case .channelAdminLogEventActionSendMessage(let message): - if boxed { - buffer.appendInt32(663693416) - } - message.serialize(buffer, true) - break - case .channelAdminLogEventActionStartGroupCall(let call): - if boxed { - buffer.appendInt32(589338437) - } - call.serialize(buffer, true) - break - case .channelAdminLogEventActionStopPoll(let message): - if boxed { - buffer.appendInt32(-1895328189) - } - message.serialize(buffer, true) - break - case .channelAdminLogEventActionToggleAntiSpam(let newValue): - if boxed { - buffer.appendInt32(1693675004) - } - newValue.serialize(buffer, true) - break - case .channelAdminLogEventActionToggleAutotranslation(let newValue): - if boxed { - buffer.appendInt32(-988285058) - } - newValue.serialize(buffer, true) - break - case .channelAdminLogEventActionToggleForum(let newValue): - if boxed { - buffer.appendInt32(46949251) - } - newValue.serialize(buffer, true) - break - case .channelAdminLogEventActionToggleGroupCallSetting(let joinMuted): - if boxed { - buffer.appendInt32(1456906823) - } - joinMuted.serialize(buffer, true) - break - case .channelAdminLogEventActionToggleInvites(let newValue): - if boxed { - buffer.appendInt32(460916654) - } - newValue.serialize(buffer, true) - break - case .channelAdminLogEventActionToggleNoForwards(let newValue): - if boxed { - buffer.appendInt32(-886388890) - } - newValue.serialize(buffer, true) - break - case .channelAdminLogEventActionTogglePreHistoryHidden(let newValue): - if boxed { - buffer.appendInt32(1599903217) - } - newValue.serialize(buffer, true) - break - case .channelAdminLogEventActionToggleSignatureProfiles(let newValue): - if boxed { - buffer.appendInt32(1621597305) - } - newValue.serialize(buffer, true) - break - case .channelAdminLogEventActionToggleSignatures(let newValue): - if boxed { - buffer.appendInt32(648939889) - } - newValue.serialize(buffer, true) - break - case .channelAdminLogEventActionToggleSlowMode(let prevValue, let newValue): - if boxed { - buffer.appendInt32(1401984889) - } - serializeInt32(prevValue, buffer: buffer, boxed: false) - serializeInt32(newValue, buffer: buffer, boxed: false) - break - case .channelAdminLogEventActionUpdatePinned(let message): - if boxed { - buffer.appendInt32(-370660328) - } - message.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .channelAdminLogEventActionChangeAbout(let prevValue, let newValue): - return ("channelAdminLogEventActionChangeAbout", [("prevValue", prevValue as Any), ("newValue", newValue as Any)]) - case .channelAdminLogEventActionChangeAvailableReactions(let prevValue, let newValue): - return ("channelAdminLogEventActionChangeAvailableReactions", [("prevValue", prevValue as Any), ("newValue", newValue as Any)]) - case .channelAdminLogEventActionChangeEmojiStatus(let prevValue, let newValue): - return ("channelAdminLogEventActionChangeEmojiStatus", [("prevValue", prevValue as Any), ("newValue", newValue as Any)]) - case .channelAdminLogEventActionChangeEmojiStickerSet(let prevStickerset, let newStickerset): - return ("channelAdminLogEventActionChangeEmojiStickerSet", [("prevStickerset", prevStickerset as Any), ("newStickerset", newStickerset as Any)]) - case .channelAdminLogEventActionChangeHistoryTTL(let prevValue, let newValue): - return ("channelAdminLogEventActionChangeHistoryTTL", [("prevValue", prevValue as Any), ("newValue", newValue as Any)]) - case .channelAdminLogEventActionChangeLinkedChat(let prevValue, let newValue): - return ("channelAdminLogEventActionChangeLinkedChat", [("prevValue", prevValue as Any), ("newValue", newValue as Any)]) - case .channelAdminLogEventActionChangeLocation(let prevValue, let newValue): - return ("channelAdminLogEventActionChangeLocation", [("prevValue", prevValue as Any), ("newValue", newValue as Any)]) - case .channelAdminLogEventActionChangePeerColor(let prevValue, let newValue): - return ("channelAdminLogEventActionChangePeerColor", [("prevValue", prevValue as Any), ("newValue", newValue as Any)]) - case .channelAdminLogEventActionChangePhoto(let prevPhoto, let newPhoto): - return ("channelAdminLogEventActionChangePhoto", [("prevPhoto", prevPhoto as Any), ("newPhoto", newPhoto as Any)]) - case .channelAdminLogEventActionChangeProfilePeerColor(let prevValue, let newValue): - return ("channelAdminLogEventActionChangeProfilePeerColor", [("prevValue", prevValue as Any), ("newValue", newValue as Any)]) - case .channelAdminLogEventActionChangeStickerSet(let prevStickerset, let newStickerset): - return ("channelAdminLogEventActionChangeStickerSet", [("prevStickerset", prevStickerset as Any), ("newStickerset", newStickerset as Any)]) - case .channelAdminLogEventActionChangeTitle(let prevValue, let newValue): - return ("channelAdminLogEventActionChangeTitle", [("prevValue", prevValue as Any), ("newValue", newValue as Any)]) - case .channelAdminLogEventActionChangeUsername(let prevValue, let newValue): - return ("channelAdminLogEventActionChangeUsername", [("prevValue", prevValue as Any), ("newValue", newValue as Any)]) - case .channelAdminLogEventActionChangeUsernames(let prevValue, let newValue): - return ("channelAdminLogEventActionChangeUsernames", [("prevValue", prevValue as Any), ("newValue", newValue as Any)]) - case .channelAdminLogEventActionChangeWallpaper(let prevValue, let newValue): - return ("channelAdminLogEventActionChangeWallpaper", [("prevValue", prevValue as Any), ("newValue", newValue as Any)]) - case .channelAdminLogEventActionCreateTopic(let topic): - return ("channelAdminLogEventActionCreateTopic", [("topic", topic as Any)]) - case .channelAdminLogEventActionDefaultBannedRights(let prevBannedRights, let newBannedRights): - return ("channelAdminLogEventActionDefaultBannedRights", [("prevBannedRights", prevBannedRights as Any), ("newBannedRights", newBannedRights as Any)]) - case .channelAdminLogEventActionDeleteMessage(let message): - return ("channelAdminLogEventActionDeleteMessage", [("message", message as Any)]) - case .channelAdminLogEventActionDeleteTopic(let topic): - return ("channelAdminLogEventActionDeleteTopic", [("topic", topic as Any)]) - case .channelAdminLogEventActionDiscardGroupCall(let call): - return ("channelAdminLogEventActionDiscardGroupCall", [("call", call as Any)]) - case .channelAdminLogEventActionEditMessage(let prevMessage, let newMessage): - return ("channelAdminLogEventActionEditMessage", [("prevMessage", prevMessage as Any), ("newMessage", newMessage as Any)]) - case .channelAdminLogEventActionEditTopic(let prevTopic, let newTopic): - return ("channelAdminLogEventActionEditTopic", [("prevTopic", prevTopic as Any), ("newTopic", newTopic as Any)]) - case .channelAdminLogEventActionExportedInviteDelete(let invite): - return ("channelAdminLogEventActionExportedInviteDelete", [("invite", invite as Any)]) - case .channelAdminLogEventActionExportedInviteEdit(let prevInvite, let newInvite): - return ("channelAdminLogEventActionExportedInviteEdit", [("prevInvite", prevInvite as Any), ("newInvite", newInvite as Any)]) - case .channelAdminLogEventActionExportedInviteRevoke(let invite): - return ("channelAdminLogEventActionExportedInviteRevoke", [("invite", invite as Any)]) - case .channelAdminLogEventActionParticipantInvite(let participant): - return ("channelAdminLogEventActionParticipantInvite", [("participant", participant as Any)]) - case .channelAdminLogEventActionParticipantJoin: + case channelAdminLogEventActionParticipantMute(Cons_channelAdminLogEventActionParticipantMute) + case channelAdminLogEventActionParticipantSubExtend(Cons_channelAdminLogEventActionParticipantSubExtend) + case channelAdminLogEventActionParticipantToggleAdmin(Cons_channelAdminLogEventActionParticipantToggleAdmin) + case channelAdminLogEventActionParticipantToggleBan(Cons_channelAdminLogEventActionParticipantToggleBan) + case channelAdminLogEventActionParticipantUnmute(Cons_channelAdminLogEventActionParticipantUnmute) + case channelAdminLogEventActionParticipantVolume(Cons_channelAdminLogEventActionParticipantVolume) + case channelAdminLogEventActionPinTopic(Cons_channelAdminLogEventActionPinTopic) + case channelAdminLogEventActionSendMessage(Cons_channelAdminLogEventActionSendMessage) + case channelAdminLogEventActionStartGroupCall(Cons_channelAdminLogEventActionStartGroupCall) + case channelAdminLogEventActionStopPoll(Cons_channelAdminLogEventActionStopPoll) + case channelAdminLogEventActionToggleAntiSpam(Cons_channelAdminLogEventActionToggleAntiSpam) + case channelAdminLogEventActionToggleAutotranslation(Cons_channelAdminLogEventActionToggleAutotranslation) + case channelAdminLogEventActionToggleForum(Cons_channelAdminLogEventActionToggleForum) + case channelAdminLogEventActionToggleGroupCallSetting(Cons_channelAdminLogEventActionToggleGroupCallSetting) + case channelAdminLogEventActionToggleInvites(Cons_channelAdminLogEventActionToggleInvites) + case channelAdminLogEventActionToggleNoForwards(Cons_channelAdminLogEventActionToggleNoForwards) + case channelAdminLogEventActionTogglePreHistoryHidden(Cons_channelAdminLogEventActionTogglePreHistoryHidden) + case channelAdminLogEventActionToggleSignatureProfiles(Cons_channelAdminLogEventActionToggleSignatureProfiles) + case channelAdminLogEventActionToggleSignatures(Cons_channelAdminLogEventActionToggleSignatures) + case channelAdminLogEventActionToggleSlowMode(Cons_channelAdminLogEventActionToggleSlowMode) + case channelAdminLogEventActionUpdatePinned(Cons_channelAdminLogEventActionUpdatePinned) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .channelAdminLogEventActionChangeAbout(let _data): + if boxed { + buffer.appendInt32(1427671598) + } + serializeString(_data.prevValue, buffer: buffer, boxed: false) + serializeString(_data.newValue, buffer: buffer, boxed: false) + break + case .channelAdminLogEventActionChangeAvailableReactions(let _data): + if boxed { + buffer.appendInt32(-1102180616) + } + _data.prevValue.serialize(buffer, true) + _data.newValue.serialize(buffer, true) + break + case .channelAdminLogEventActionChangeEmojiStatus(let _data): + if boxed { + buffer.appendInt32(1051328177) + } + _data.prevValue.serialize(buffer, true) + _data.newValue.serialize(buffer, true) + break + case .channelAdminLogEventActionChangeEmojiStickerSet(let _data): + if boxed { + buffer.appendInt32(1188577451) + } + _data.prevStickerset.serialize(buffer, true) + _data.newStickerset.serialize(buffer, true) + break + case .channelAdminLogEventActionChangeHistoryTTL(let _data): + if boxed { + buffer.appendInt32(1855199800) + } + serializeInt32(_data.prevValue, buffer: buffer, boxed: false) + serializeInt32(_data.newValue, buffer: buffer, boxed: false) + break + case .channelAdminLogEventActionChangeLinkedChat(let _data): + if boxed { + buffer.appendInt32(84703944) + } + serializeInt64(_data.prevValue, buffer: buffer, boxed: false) + serializeInt64(_data.newValue, buffer: buffer, boxed: false) + break + case .channelAdminLogEventActionChangeLocation(let _data): + if boxed { + buffer.appendInt32(241923758) + } + _data.prevValue.serialize(buffer, true) + _data.newValue.serialize(buffer, true) + break + case .channelAdminLogEventActionChangePeerColor(let _data): + if boxed { + buffer.appendInt32(1469507456) + } + _data.prevValue.serialize(buffer, true) + _data.newValue.serialize(buffer, true) + break + case .channelAdminLogEventActionChangePhoto(let _data): + if boxed { + buffer.appendInt32(1129042607) + } + _data.prevPhoto.serialize(buffer, true) + _data.newPhoto.serialize(buffer, true) + break + case .channelAdminLogEventActionChangeProfilePeerColor(let _data): + if boxed { + buffer.appendInt32(1581742885) + } + _data.prevValue.serialize(buffer, true) + _data.newValue.serialize(buffer, true) + break + case .channelAdminLogEventActionChangeStickerSet(let _data): + if boxed { + buffer.appendInt32(-1312568665) + } + _data.prevStickerset.serialize(buffer, true) + _data.newStickerset.serialize(buffer, true) + break + case .channelAdminLogEventActionChangeTitle(let _data): + if boxed { + buffer.appendInt32(-421545947) + } + serializeString(_data.prevValue, buffer: buffer, boxed: false) + serializeString(_data.newValue, buffer: buffer, boxed: false) + break + case .channelAdminLogEventActionChangeUsername(let _data): + if boxed { + buffer.appendInt32(1783299128) + } + serializeString(_data.prevValue, buffer: buffer, boxed: false) + serializeString(_data.newValue, buffer: buffer, boxed: false) + break + case .channelAdminLogEventActionChangeUsernames(let _data): + if boxed { + buffer.appendInt32(-263212119) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.prevValue.count)) + for item in _data.prevValue { + serializeString(item, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.newValue.count)) + for item in _data.newValue { + serializeString(item, buffer: buffer, boxed: false) + } + break + case .channelAdminLogEventActionChangeWallpaper(let _data): + if boxed { + buffer.appendInt32(834362706) + } + _data.prevValue.serialize(buffer, true) + _data.newValue.serialize(buffer, true) + break + case .channelAdminLogEventActionCreateTopic(let _data): + if boxed { + buffer.appendInt32(1483767080) + } + _data.topic.serialize(buffer, true) + break + case .channelAdminLogEventActionDefaultBannedRights(let _data): + if boxed { + buffer.appendInt32(771095562) + } + _data.prevBannedRights.serialize(buffer, true) + _data.newBannedRights.serialize(buffer, true) + break + case .channelAdminLogEventActionDeleteMessage(let _data): + if boxed { + buffer.appendInt32(1121994683) + } + _data.message.serialize(buffer, true) + break + case .channelAdminLogEventActionDeleteTopic(let _data): + if boxed { + buffer.appendInt32(-1374254839) + } + _data.topic.serialize(buffer, true) + break + case .channelAdminLogEventActionDiscardGroupCall(let _data): + if boxed { + buffer.appendInt32(-610299584) + } + _data.call.serialize(buffer, true) + break + case .channelAdminLogEventActionEditMessage(let _data): + if boxed { + buffer.appendInt32(1889215493) + } + _data.prevMessage.serialize(buffer, true) + _data.newMessage.serialize(buffer, true) + break + case .channelAdminLogEventActionEditTopic(let _data): + if boxed { + buffer.appendInt32(-261103096) + } + _data.prevTopic.serialize(buffer, true) + _data.newTopic.serialize(buffer, true) + break + case .channelAdminLogEventActionExportedInviteDelete(let _data): + if boxed { + buffer.appendInt32(1515256996) + } + _data.invite.serialize(buffer, true) + break + case .channelAdminLogEventActionExportedInviteEdit(let _data): + if boxed { + buffer.appendInt32(-384910503) + } + _data.prevInvite.serialize(buffer, true) + _data.newInvite.serialize(buffer, true) + break + case .channelAdminLogEventActionExportedInviteRevoke(let _data): + if boxed { + buffer.appendInt32(1091179342) + } + _data.invite.serialize(buffer, true) + break + case .channelAdminLogEventActionParticipantInvite(let _data): + if boxed { + buffer.appendInt32(-484690728) + } + _data.participant.serialize(buffer, true) + break + case .channelAdminLogEventActionParticipantJoin: + if boxed { + buffer.appendInt32(405815507) + } + break + case .channelAdminLogEventActionParticipantJoinByInvite(let _data): + if boxed { + buffer.appendInt32(-23084712) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.invite.serialize(buffer, true) + break + case .channelAdminLogEventActionParticipantJoinByRequest(let _data): + if boxed { + buffer.appendInt32(-1347021750) + } + _data.invite.serialize(buffer, true) + serializeInt64(_data.approvedBy, buffer: buffer, boxed: false) + break + case .channelAdminLogEventActionParticipantLeave: + if boxed { + buffer.appendInt32(-124291086) + } + break + case .channelAdminLogEventActionParticipantMute(let _data): + if boxed { + buffer.appendInt32(-115071790) + } + _data.participant.serialize(buffer, true) + break + case .channelAdminLogEventActionParticipantSubExtend(let _data): + if boxed { + buffer.appendInt32(1684286899) + } + _data.prevParticipant.serialize(buffer, true) + _data.newParticipant.serialize(buffer, true) + break + case .channelAdminLogEventActionParticipantToggleAdmin(let _data): + if boxed { + buffer.appendInt32(-714643696) + } + _data.prevParticipant.serialize(buffer, true) + _data.newParticipant.serialize(buffer, true) + break + case .channelAdminLogEventActionParticipantToggleBan(let _data): + if boxed { + buffer.appendInt32(-422036098) + } + _data.prevParticipant.serialize(buffer, true) + _data.newParticipant.serialize(buffer, true) + break + case .channelAdminLogEventActionParticipantUnmute(let _data): + if boxed { + buffer.appendInt32(-431740480) + } + _data.participant.serialize(buffer, true) + break + case .channelAdminLogEventActionParticipantVolume(let _data): + if boxed { + buffer.appendInt32(1048537159) + } + _data.participant.serialize(buffer, true) + break + case .channelAdminLogEventActionPinTopic(let _data): + if boxed { + buffer.appendInt32(1569535291) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.prevTopic!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.newTopic!.serialize(buffer, true) + } + break + case .channelAdminLogEventActionSendMessage(let _data): + if boxed { + buffer.appendInt32(663693416) + } + _data.message.serialize(buffer, true) + break + case .channelAdminLogEventActionStartGroupCall(let _data): + if boxed { + buffer.appendInt32(589338437) + } + _data.call.serialize(buffer, true) + break + case .channelAdminLogEventActionStopPoll(let _data): + if boxed { + buffer.appendInt32(-1895328189) + } + _data.message.serialize(buffer, true) + break + case .channelAdminLogEventActionToggleAntiSpam(let _data): + if boxed { + buffer.appendInt32(1693675004) + } + _data.newValue.serialize(buffer, true) + break + case .channelAdminLogEventActionToggleAutotranslation(let _data): + if boxed { + buffer.appendInt32(-988285058) + } + _data.newValue.serialize(buffer, true) + break + case .channelAdminLogEventActionToggleForum(let _data): + if boxed { + buffer.appendInt32(46949251) + } + _data.newValue.serialize(buffer, true) + break + case .channelAdminLogEventActionToggleGroupCallSetting(let _data): + if boxed { + buffer.appendInt32(1456906823) + } + _data.joinMuted.serialize(buffer, true) + break + case .channelAdminLogEventActionToggleInvites(let _data): + if boxed { + buffer.appendInt32(460916654) + } + _data.newValue.serialize(buffer, true) + break + case .channelAdminLogEventActionToggleNoForwards(let _data): + if boxed { + buffer.appendInt32(-886388890) + } + _data.newValue.serialize(buffer, true) + break + case .channelAdminLogEventActionTogglePreHistoryHidden(let _data): + if boxed { + buffer.appendInt32(1599903217) + } + _data.newValue.serialize(buffer, true) + break + case .channelAdminLogEventActionToggleSignatureProfiles(let _data): + if boxed { + buffer.appendInt32(1621597305) + } + _data.newValue.serialize(buffer, true) + break + case .channelAdminLogEventActionToggleSignatures(let _data): + if boxed { + buffer.appendInt32(648939889) + } + _data.newValue.serialize(buffer, true) + break + case .channelAdminLogEventActionToggleSlowMode(let _data): + if boxed { + buffer.appendInt32(1401984889) + } + serializeInt32(_data.prevValue, buffer: buffer, boxed: false) + serializeInt32(_data.newValue, buffer: buffer, boxed: false) + break + case .channelAdminLogEventActionUpdatePinned(let _data): + if boxed { + buffer.appendInt32(-370660328) + } + _data.message.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .channelAdminLogEventActionChangeAbout(let _data): + return ("channelAdminLogEventActionChangeAbout", [("prevValue", _data.prevValue as Any), ("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionChangeAvailableReactions(let _data): + return ("channelAdminLogEventActionChangeAvailableReactions", [("prevValue", _data.prevValue as Any), ("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionChangeEmojiStatus(let _data): + return ("channelAdminLogEventActionChangeEmojiStatus", [("prevValue", _data.prevValue as Any), ("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionChangeEmojiStickerSet(let _data): + return ("channelAdminLogEventActionChangeEmojiStickerSet", [("prevStickerset", _data.prevStickerset as Any), ("newStickerset", _data.newStickerset as Any)]) + case .channelAdminLogEventActionChangeHistoryTTL(let _data): + return ("channelAdminLogEventActionChangeHistoryTTL", [("prevValue", _data.prevValue as Any), ("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionChangeLinkedChat(let _data): + return ("channelAdminLogEventActionChangeLinkedChat", [("prevValue", _data.prevValue as Any), ("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionChangeLocation(let _data): + return ("channelAdminLogEventActionChangeLocation", [("prevValue", _data.prevValue as Any), ("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionChangePeerColor(let _data): + return ("channelAdminLogEventActionChangePeerColor", [("prevValue", _data.prevValue as Any), ("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionChangePhoto(let _data): + return ("channelAdminLogEventActionChangePhoto", [("prevPhoto", _data.prevPhoto as Any), ("newPhoto", _data.newPhoto as Any)]) + case .channelAdminLogEventActionChangeProfilePeerColor(let _data): + return ("channelAdminLogEventActionChangeProfilePeerColor", [("prevValue", _data.prevValue as Any), ("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionChangeStickerSet(let _data): + return ("channelAdminLogEventActionChangeStickerSet", [("prevStickerset", _data.prevStickerset as Any), ("newStickerset", _data.newStickerset as Any)]) + case .channelAdminLogEventActionChangeTitle(let _data): + return ("channelAdminLogEventActionChangeTitle", [("prevValue", _data.prevValue as Any), ("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionChangeUsername(let _data): + return ("channelAdminLogEventActionChangeUsername", [("prevValue", _data.prevValue as Any), ("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionChangeUsernames(let _data): + return ("channelAdminLogEventActionChangeUsernames", [("prevValue", _data.prevValue as Any), ("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionChangeWallpaper(let _data): + return ("channelAdminLogEventActionChangeWallpaper", [("prevValue", _data.prevValue as Any), ("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionCreateTopic(let _data): + return ("channelAdminLogEventActionCreateTopic", [("topic", _data.topic as Any)]) + case .channelAdminLogEventActionDefaultBannedRights(let _data): + return ("channelAdminLogEventActionDefaultBannedRights", [("prevBannedRights", _data.prevBannedRights as Any), ("newBannedRights", _data.newBannedRights as Any)]) + case .channelAdminLogEventActionDeleteMessage(let _data): + return ("channelAdminLogEventActionDeleteMessage", [("message", _data.message as Any)]) + case .channelAdminLogEventActionDeleteTopic(let _data): + return ("channelAdminLogEventActionDeleteTopic", [("topic", _data.topic as Any)]) + case .channelAdminLogEventActionDiscardGroupCall(let _data): + return ("channelAdminLogEventActionDiscardGroupCall", [("call", _data.call as Any)]) + case .channelAdminLogEventActionEditMessage(let _data): + return ("channelAdminLogEventActionEditMessage", [("prevMessage", _data.prevMessage as Any), ("newMessage", _data.newMessage as Any)]) + case .channelAdminLogEventActionEditTopic(let _data): + return ("channelAdminLogEventActionEditTopic", [("prevTopic", _data.prevTopic as Any), ("newTopic", _data.newTopic as Any)]) + case .channelAdminLogEventActionExportedInviteDelete(let _data): + return ("channelAdminLogEventActionExportedInviteDelete", [("invite", _data.invite as Any)]) + case .channelAdminLogEventActionExportedInviteEdit(let _data): + return ("channelAdminLogEventActionExportedInviteEdit", [("prevInvite", _data.prevInvite as Any), ("newInvite", _data.newInvite as Any)]) + case .channelAdminLogEventActionExportedInviteRevoke(let _data): + return ("channelAdminLogEventActionExportedInviteRevoke", [("invite", _data.invite as Any)]) + case .channelAdminLogEventActionParticipantInvite(let _data): + return ("channelAdminLogEventActionParticipantInvite", [("participant", _data.participant as Any)]) + case .channelAdminLogEventActionParticipantJoin: return ("channelAdminLogEventActionParticipantJoin", []) - case .channelAdminLogEventActionParticipantJoinByInvite(let flags, let invite): - return ("channelAdminLogEventActionParticipantJoinByInvite", [("flags", flags as Any), ("invite", invite as Any)]) - case .channelAdminLogEventActionParticipantJoinByRequest(let invite, let approvedBy): - return ("channelAdminLogEventActionParticipantJoinByRequest", [("invite", invite as Any), ("approvedBy", approvedBy as Any)]) - case .channelAdminLogEventActionParticipantLeave: + case .channelAdminLogEventActionParticipantJoinByInvite(let _data): + return ("channelAdminLogEventActionParticipantJoinByInvite", [("flags", _data.flags as Any), ("invite", _data.invite as Any)]) + case .channelAdminLogEventActionParticipantJoinByRequest(let _data): + return ("channelAdminLogEventActionParticipantJoinByRequest", [("invite", _data.invite as Any), ("approvedBy", _data.approvedBy as Any)]) + case .channelAdminLogEventActionParticipantLeave: return ("channelAdminLogEventActionParticipantLeave", []) - case .channelAdminLogEventActionParticipantMute(let participant): - return ("channelAdminLogEventActionParticipantMute", [("participant", participant as Any)]) - case .channelAdminLogEventActionParticipantSubExtend(let prevParticipant, let newParticipant): - return ("channelAdminLogEventActionParticipantSubExtend", [("prevParticipant", prevParticipant as Any), ("newParticipant", newParticipant as Any)]) - case .channelAdminLogEventActionParticipantToggleAdmin(let prevParticipant, let newParticipant): - return ("channelAdminLogEventActionParticipantToggleAdmin", [("prevParticipant", prevParticipant as Any), ("newParticipant", newParticipant as Any)]) - case .channelAdminLogEventActionParticipantToggleBan(let prevParticipant, let newParticipant): - return ("channelAdminLogEventActionParticipantToggleBan", [("prevParticipant", prevParticipant as Any), ("newParticipant", newParticipant as Any)]) - case .channelAdminLogEventActionParticipantUnmute(let participant): - return ("channelAdminLogEventActionParticipantUnmute", [("participant", participant as Any)]) - case .channelAdminLogEventActionParticipantVolume(let participant): - return ("channelAdminLogEventActionParticipantVolume", [("participant", participant as Any)]) - case .channelAdminLogEventActionPinTopic(let flags, let prevTopic, let newTopic): - return ("channelAdminLogEventActionPinTopic", [("flags", flags as Any), ("prevTopic", prevTopic as Any), ("newTopic", newTopic as Any)]) - case .channelAdminLogEventActionSendMessage(let message): - return ("channelAdminLogEventActionSendMessage", [("message", message as Any)]) - case .channelAdminLogEventActionStartGroupCall(let call): - return ("channelAdminLogEventActionStartGroupCall", [("call", call as Any)]) - case .channelAdminLogEventActionStopPoll(let message): - return ("channelAdminLogEventActionStopPoll", [("message", message as Any)]) - case .channelAdminLogEventActionToggleAntiSpam(let newValue): - return ("channelAdminLogEventActionToggleAntiSpam", [("newValue", newValue as Any)]) - case .channelAdminLogEventActionToggleAutotranslation(let newValue): - return ("channelAdminLogEventActionToggleAutotranslation", [("newValue", newValue as Any)]) - case .channelAdminLogEventActionToggleForum(let newValue): - return ("channelAdminLogEventActionToggleForum", [("newValue", newValue as Any)]) - case .channelAdminLogEventActionToggleGroupCallSetting(let joinMuted): - return ("channelAdminLogEventActionToggleGroupCallSetting", [("joinMuted", joinMuted as Any)]) - case .channelAdminLogEventActionToggleInvites(let newValue): - return ("channelAdminLogEventActionToggleInvites", [("newValue", newValue as Any)]) - case .channelAdminLogEventActionToggleNoForwards(let newValue): - return ("channelAdminLogEventActionToggleNoForwards", [("newValue", newValue as Any)]) - case .channelAdminLogEventActionTogglePreHistoryHidden(let newValue): - return ("channelAdminLogEventActionTogglePreHistoryHidden", [("newValue", newValue as Any)]) - case .channelAdminLogEventActionToggleSignatureProfiles(let newValue): - return ("channelAdminLogEventActionToggleSignatureProfiles", [("newValue", newValue as Any)]) - case .channelAdminLogEventActionToggleSignatures(let newValue): - return ("channelAdminLogEventActionToggleSignatures", [("newValue", newValue as Any)]) - case .channelAdminLogEventActionToggleSlowMode(let prevValue, let newValue): - return ("channelAdminLogEventActionToggleSlowMode", [("prevValue", prevValue as Any), ("newValue", newValue as Any)]) - case .channelAdminLogEventActionUpdatePinned(let message): - return ("channelAdminLogEventActionUpdatePinned", [("message", message as Any)]) - } - } - + case .channelAdminLogEventActionParticipantMute(let _data): + return ("channelAdminLogEventActionParticipantMute", [("participant", _data.participant as Any)]) + case .channelAdminLogEventActionParticipantSubExtend(let _data): + return ("channelAdminLogEventActionParticipantSubExtend", [("prevParticipant", _data.prevParticipant as Any), ("newParticipant", _data.newParticipant as Any)]) + case .channelAdminLogEventActionParticipantToggleAdmin(let _data): + return ("channelAdminLogEventActionParticipantToggleAdmin", [("prevParticipant", _data.prevParticipant as Any), ("newParticipant", _data.newParticipant as Any)]) + case .channelAdminLogEventActionParticipantToggleBan(let _data): + return ("channelAdminLogEventActionParticipantToggleBan", [("prevParticipant", _data.prevParticipant as Any), ("newParticipant", _data.newParticipant as Any)]) + case .channelAdminLogEventActionParticipantUnmute(let _data): + return ("channelAdminLogEventActionParticipantUnmute", [("participant", _data.participant as Any)]) + case .channelAdminLogEventActionParticipantVolume(let _data): + return ("channelAdminLogEventActionParticipantVolume", [("participant", _data.participant as Any)]) + case .channelAdminLogEventActionPinTopic(let _data): + return ("channelAdminLogEventActionPinTopic", [("flags", _data.flags as Any), ("prevTopic", _data.prevTopic as Any), ("newTopic", _data.newTopic as Any)]) + case .channelAdminLogEventActionSendMessage(let _data): + return ("channelAdminLogEventActionSendMessage", [("message", _data.message as Any)]) + case .channelAdminLogEventActionStartGroupCall(let _data): + return ("channelAdminLogEventActionStartGroupCall", [("call", _data.call as Any)]) + case .channelAdminLogEventActionStopPoll(let _data): + return ("channelAdminLogEventActionStopPoll", [("message", _data.message as Any)]) + case .channelAdminLogEventActionToggleAntiSpam(let _data): + return ("channelAdminLogEventActionToggleAntiSpam", [("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionToggleAutotranslation(let _data): + return ("channelAdminLogEventActionToggleAutotranslation", [("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionToggleForum(let _data): + return ("channelAdminLogEventActionToggleForum", [("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionToggleGroupCallSetting(let _data): + return ("channelAdminLogEventActionToggleGroupCallSetting", [("joinMuted", _data.joinMuted as Any)]) + case .channelAdminLogEventActionToggleInvites(let _data): + return ("channelAdminLogEventActionToggleInvites", [("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionToggleNoForwards(let _data): + return ("channelAdminLogEventActionToggleNoForwards", [("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionTogglePreHistoryHidden(let _data): + return ("channelAdminLogEventActionTogglePreHistoryHidden", [("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionToggleSignatureProfiles(let _data): + return ("channelAdminLogEventActionToggleSignatureProfiles", [("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionToggleSignatures(let _data): + return ("channelAdminLogEventActionToggleSignatures", [("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionToggleSlowMode(let _data): + return ("channelAdminLogEventActionToggleSlowMode", [("prevValue", _data.prevValue as Any), ("newValue", _data.newValue as Any)]) + case .channelAdminLogEventActionUpdatePinned(let _data): + return ("channelAdminLogEventActionUpdatePinned", [("message", _data.message as Any)]) + } + } + public static func parse_channelAdminLogEventActionChangeAbout(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: String? _1 = parseString(reader) @@ -901,9 +1359,12 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeAbout(prevValue: _1!, newValue: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeAbout(Cons_channelAdminLogEventActionChangeAbout(prevValue: _1!, newValue: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionChangeAvailableReactions(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.ChatReactions? @@ -916,9 +1377,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeAvailableReactions(prevValue: _1!, newValue: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeAvailableReactions(Cons_channelAdminLogEventActionChangeAvailableReactions(prevValue: _1!, newValue: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionChangeEmojiStatus(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.EmojiStatus? @@ -931,9 +1395,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeEmojiStatus(prevValue: _1!, newValue: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeEmojiStatus(Cons_channelAdminLogEventActionChangeEmojiStatus(prevValue: _1!, newValue: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionChangeEmojiStickerSet(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.InputStickerSet? @@ -946,9 +1413,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeEmojiStickerSet(prevStickerset: _1!, newStickerset: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeEmojiStickerSet(Cons_channelAdminLogEventActionChangeEmojiStickerSet(prevStickerset: _1!, newStickerset: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionChangeHistoryTTL(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Int32? @@ -957,9 +1427,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeHistoryTTL(prevValue: _1!, newValue: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeHistoryTTL(Cons_channelAdminLogEventActionChangeHistoryTTL(prevValue: _1!, newValue: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionChangeLinkedChat(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Int64? @@ -968,9 +1441,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeLinkedChat(prevValue: _1!, newValue: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeLinkedChat(Cons_channelAdminLogEventActionChangeLinkedChat(prevValue: _1!, newValue: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionChangeLocation(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.ChannelLocation? @@ -983,9 +1459,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeLocation(prevValue: _1!, newValue: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeLocation(Cons_channelAdminLogEventActionChangeLocation(prevValue: _1!, newValue: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionChangePeerColor(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.PeerColor? @@ -998,9 +1477,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangePeerColor(prevValue: _1!, newValue: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangePeerColor(Cons_channelAdminLogEventActionChangePeerColor(prevValue: _1!, newValue: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionChangePhoto(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.Photo? @@ -1013,9 +1495,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangePhoto(prevPhoto: _1!, newPhoto: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangePhoto(Cons_channelAdminLogEventActionChangePhoto(prevPhoto: _1!, newPhoto: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionChangeProfilePeerColor(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.PeerColor? @@ -1028,9 +1513,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeProfilePeerColor(prevValue: _1!, newValue: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeProfilePeerColor(Cons_channelAdminLogEventActionChangeProfilePeerColor(prevValue: _1!, newValue: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionChangeStickerSet(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.InputStickerSet? @@ -1043,9 +1531,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeStickerSet(prevStickerset: _1!, newStickerset: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeStickerSet(Cons_channelAdminLogEventActionChangeStickerSet(prevStickerset: _1!, newStickerset: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionChangeTitle(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: String? @@ -1054,9 +1545,12 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeTitle(prevValue: _1!, newValue: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeTitle(Cons_channelAdminLogEventActionChangeTitle(prevValue: _1!, newValue: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionChangeUsername(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: String? @@ -1065,9 +1559,12 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeUsername(prevValue: _1!, newValue: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeUsername(Cons_channelAdminLogEventActionChangeUsername(prevValue: _1!, newValue: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionChangeUsernames(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: [String]? @@ -1080,9 +1577,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeUsernames(prevValue: _1!, newValue: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeUsernames(Cons_channelAdminLogEventActionChangeUsernames(prevValue: _1!, newValue: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionChangeWallpaper(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.WallPaper? @@ -1095,9 +1595,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeWallpaper(prevValue: _1!, newValue: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionChangeWallpaper(Cons_channelAdminLogEventActionChangeWallpaper(prevValue: _1!, newValue: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionCreateTopic(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.ForumTopic? @@ -1105,8 +1608,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.ForumTopic } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionCreateTopic(topic: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionCreateTopic(Cons_channelAdminLogEventActionCreateTopic(topic: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionDefaultBannedRights(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.ChatBannedRights? @@ -1119,9 +1626,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionDefaultBannedRights(prevBannedRights: _1!, newBannedRights: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionDefaultBannedRights(Cons_channelAdminLogEventActionDefaultBannedRights(prevBannedRights: _1!, newBannedRights: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionDeleteMessage(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.Message? @@ -1129,8 +1639,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Message } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionDeleteMessage(message: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionDeleteMessage(Cons_channelAdminLogEventActionDeleteMessage(message: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionDeleteTopic(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.ForumTopic? @@ -1138,8 +1652,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.ForumTopic } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionDeleteTopic(topic: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionDeleteTopic(Cons_channelAdminLogEventActionDeleteTopic(topic: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionDiscardGroupCall(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.InputGroupCall? @@ -1147,8 +1665,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.InputGroupCall } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionDiscardGroupCall(call: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionDiscardGroupCall(Cons_channelAdminLogEventActionDiscardGroupCall(call: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionEditMessage(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.Message? @@ -1161,9 +1683,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionEditMessage(prevMessage: _1!, newMessage: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionEditMessage(Cons_channelAdminLogEventActionEditMessage(prevMessage: _1!, newMessage: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionEditTopic(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.ForumTopic? @@ -1176,9 +1701,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionEditTopic(prevTopic: _1!, newTopic: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionEditTopic(Cons_channelAdminLogEventActionEditTopic(prevTopic: _1!, newTopic: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionExportedInviteDelete(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.ExportedChatInvite? @@ -1186,8 +1714,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionExportedInviteDelete(invite: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionExportedInviteDelete(Cons_channelAdminLogEventActionExportedInviteDelete(invite: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionExportedInviteEdit(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.ExportedChatInvite? @@ -1200,9 +1732,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionExportedInviteEdit(prevInvite: _1!, newInvite: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionExportedInviteEdit(Cons_channelAdminLogEventActionExportedInviteEdit(prevInvite: _1!, newInvite: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionExportedInviteRevoke(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.ExportedChatInvite? @@ -1210,8 +1745,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionExportedInviteRevoke(invite: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionExportedInviteRevoke(Cons_channelAdminLogEventActionExportedInviteRevoke(invite: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionParticipantInvite(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.ChannelParticipant? @@ -1219,8 +1758,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.ChannelParticipant } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantInvite(participant: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantInvite(Cons_channelAdminLogEventActionParticipantInvite(participant: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionParticipantJoin(_ reader: BufferReader) -> ChannelAdminLogEventAction? { return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantJoin @@ -1234,9 +1777,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantJoinByInvite(flags: _1!, invite: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantJoinByInvite(Cons_channelAdminLogEventActionParticipantJoinByInvite(flags: _1!, invite: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionParticipantJoinByRequest(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.ExportedChatInvite? @@ -1247,9 +1793,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantJoinByRequest(invite: _1!, approvedBy: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantJoinByRequest(Cons_channelAdminLogEventActionParticipantJoinByRequest(invite: _1!, approvedBy: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionParticipantLeave(_ reader: BufferReader) -> ChannelAdminLogEventAction? { return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantLeave @@ -1260,8 +1809,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.GroupCallParticipant } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantMute(participant: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantMute(Cons_channelAdminLogEventActionParticipantMute(participant: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionParticipantSubExtend(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.ChannelParticipant? @@ -1274,9 +1827,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantSubExtend(prevParticipant: _1!, newParticipant: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantSubExtend(Cons_channelAdminLogEventActionParticipantSubExtend(prevParticipant: _1!, newParticipant: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionParticipantToggleAdmin(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.ChannelParticipant? @@ -1289,9 +1845,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantToggleAdmin(prevParticipant: _1!, newParticipant: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantToggleAdmin(Cons_channelAdminLogEventActionParticipantToggleAdmin(prevParticipant: _1!, newParticipant: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionParticipantToggleBan(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.ChannelParticipant? @@ -1304,9 +1863,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantToggleBan(prevParticipant: _1!, newParticipant: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantToggleBan(Cons_channelAdminLogEventActionParticipantToggleBan(prevParticipant: _1!, newParticipant: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionParticipantUnmute(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.GroupCallParticipant? @@ -1314,8 +1876,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.GroupCallParticipant } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantUnmute(participant: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantUnmute(Cons_channelAdminLogEventActionParticipantUnmute(participant: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionParticipantVolume(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.GroupCallParticipant? @@ -1323,27 +1889,37 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.GroupCallParticipant } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantVolume(participant: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionParticipantVolume(Cons_channelAdminLogEventActionParticipantVolume(participant: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionPinTopic(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Int32? _1 = reader.readInt32() var _2: Api.ForumTopic? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.ForumTopic - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.ForumTopic + } + } var _3: Api.ForumTopic? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.ForumTopic - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.ForumTopic + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionPinTopic(flags: _1!, prevTopic: _2, newTopic: _3) + if _c1 && _c2 && _c3 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionPinTopic(Cons_channelAdminLogEventActionPinTopic(flags: _1!, prevTopic: _2, newTopic: _3)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionSendMessage(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.Message? @@ -1351,8 +1927,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Message } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionSendMessage(message: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionSendMessage(Cons_channelAdminLogEventActionSendMessage(message: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionStartGroupCall(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.InputGroupCall? @@ -1360,8 +1940,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.InputGroupCall } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionStartGroupCall(call: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionStartGroupCall(Cons_channelAdminLogEventActionStartGroupCall(call: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionStopPoll(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.Message? @@ -1369,8 +1953,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Message } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionStopPoll(message: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionStopPoll(Cons_channelAdminLogEventActionStopPoll(message: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionToggleAntiSpam(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.Bool? @@ -1378,8 +1966,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Bool } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleAntiSpam(newValue: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleAntiSpam(Cons_channelAdminLogEventActionToggleAntiSpam(newValue: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionToggleAutotranslation(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.Bool? @@ -1387,8 +1979,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Bool } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleAutotranslation(newValue: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleAutotranslation(Cons_channelAdminLogEventActionToggleAutotranslation(newValue: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionToggleForum(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.Bool? @@ -1396,8 +1992,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Bool } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleForum(newValue: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleForum(Cons_channelAdminLogEventActionToggleForum(newValue: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionToggleGroupCallSetting(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.Bool? @@ -1405,8 +2005,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Bool } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleGroupCallSetting(joinMuted: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleGroupCallSetting(Cons_channelAdminLogEventActionToggleGroupCallSetting(joinMuted: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionToggleInvites(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.Bool? @@ -1414,8 +2018,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Bool } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleInvites(newValue: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleInvites(Cons_channelAdminLogEventActionToggleInvites(newValue: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionToggleNoForwards(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.Bool? @@ -1423,8 +2031,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Bool } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleNoForwards(newValue: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleNoForwards(Cons_channelAdminLogEventActionToggleNoForwards(newValue: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionTogglePreHistoryHidden(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.Bool? @@ -1432,8 +2044,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Bool } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionTogglePreHistoryHidden(newValue: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionTogglePreHistoryHidden(Cons_channelAdminLogEventActionTogglePreHistoryHidden(newValue: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionToggleSignatureProfiles(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.Bool? @@ -1441,8 +2057,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Bool } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleSignatureProfiles(newValue: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleSignatureProfiles(Cons_channelAdminLogEventActionToggleSignatureProfiles(newValue: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionToggleSignatures(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.Bool? @@ -1450,8 +2070,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Bool } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleSignatures(newValue: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleSignatures(Cons_channelAdminLogEventActionToggleSignatures(newValue: _1!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionToggleSlowMode(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Int32? @@ -1460,9 +2084,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleSlowMode(prevValue: _1!, newValue: _2!) + if _c1 && _c2 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionToggleSlowMode(Cons_channelAdminLogEventActionToggleSlowMode(prevValue: _1!, newValue: _2!)) + } + else { + return nil + } } public static func parse_channelAdminLogEventActionUpdatePinned(_ reader: BufferReader) -> ChannelAdminLogEventAction? { var _1: Api.Message? @@ -1470,9 +2097,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Message } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventAction.channelAdminLogEventActionUpdatePinned(message: _1!) + if _c1 { + return Api.ChannelAdminLogEventAction.channelAdminLogEventActionUpdatePinned(Cons_channelAdminLogEventActionUpdatePinned(message: _1!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api30.swift b/submodules/TelegramApi/Sources/Api30.swift index b10d58f7..3e25dcd6 100644 --- a/submodules/TelegramApi/Sources/Api30.swift +++ b/submodules/TelegramApi/Sources/Api30.swift @@ -1,405 +1,890 @@ -public extension Api.account { - enum SavedMusicIds: TypeConstructorDescription { - case savedMusicIds(ids: [Int64]) - case savedMusicIdsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .savedMusicIds(let ids): - if boxed { - buffer.appendInt32(-1718786506) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(ids.count)) - for item in ids { - serializeInt64(item, buffer: buffer, boxed: false) - } - break - case .savedMusicIdsNotModified: - if boxed { - buffer.appendInt32(1338514798) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .savedMusicIds(let ids): - return ("savedMusicIds", [("ids", ids as Any)]) - case .savedMusicIdsNotModified: - return ("savedMusicIdsNotModified", []) - } - } - - public static func parse_savedMusicIds(_ reader: BufferReader) -> SavedMusicIds? { - var _1: [Int64]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) +public extension Api { + indirect enum WebPageAttribute: TypeConstructorDescription { + public class Cons_webPageAttributeStarGiftAuction { + public var gift: Api.StarGift + public var endDate: Int32 + public init(gift: Api.StarGift, endDate: Int32) { + self.gift = gift + self.endDate = endDate } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.account.SavedMusicIds.savedMusicIds(ids: _1!) } - public static func parse_savedMusicIdsNotModified(_ reader: BufferReader) -> SavedMusicIds? { - return Api.account.SavedMusicIds.savedMusicIdsNotModified - } - - } -} -public extension Api.account { - enum SavedRingtone: TypeConstructorDescription { - case savedRingtone - case savedRingtoneConverted(document: Api.Document) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .savedRingtone: - if boxed { - buffer.appendInt32(-1222230163) - } - - break - case .savedRingtoneConverted(let document): - if boxed { - buffer.appendInt32(523271863) - } - document.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .savedRingtone: - return ("savedRingtone", []) - case .savedRingtoneConverted(let document): - return ("savedRingtoneConverted", [("document", document as Any)]) - } - } - - public static func parse_savedRingtone(_ reader: BufferReader) -> SavedRingtone? { - return Api.account.SavedRingtone.savedRingtone - } - public static func parse_savedRingtoneConverted(_ reader: BufferReader) -> SavedRingtone? { - var _1: Api.Document? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Document + public class Cons_webPageAttributeStarGiftCollection { + public var icons: [Api.Document] + public init(icons: [Api.Document]) { + self.icons = icons } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.account.SavedRingtone.savedRingtoneConverted(document: _1!) } - - } -} -public extension Api.account { - enum SavedRingtones: TypeConstructorDescription { - case savedRingtones(hash: Int64, ringtones: [Api.Document]) - case savedRingtonesNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .savedRingtones(let hash, let ringtones): - if boxed { - buffer.appendInt32(-1041683259) - } - serializeInt64(hash, buffer: buffer, boxed: false) + public class Cons_webPageAttributeStickerSet { + public var flags: Int32 + public var stickers: [Api.Document] + public init(flags: Int32, stickers: [Api.Document]) { + self.flags = flags + self.stickers = stickers + } + } + public class Cons_webPageAttributeStory { + public var flags: Int32 + public var peer: Api.Peer + public var id: Int32 + public var story: Api.StoryItem? + public init(flags: Int32, peer: Api.Peer, id: Int32, story: Api.StoryItem?) { + self.flags = flags + self.peer = peer + self.id = id + self.story = story + } + } + public class Cons_webPageAttributeTheme { + public var flags: Int32 + public var documents: [Api.Document]? + public var settings: Api.ThemeSettings? + public init(flags: Int32, documents: [Api.Document]?, settings: Api.ThemeSettings?) { + self.flags = flags + self.documents = documents + self.settings = settings + } + } + public class Cons_webPageAttributeUniqueStarGift { + public var gift: Api.StarGift + public init(gift: Api.StarGift) { + self.gift = gift + } + } + case webPageAttributeStarGiftAuction(Cons_webPageAttributeStarGiftAuction) + case webPageAttributeStarGiftCollection(Cons_webPageAttributeStarGiftCollection) + case webPageAttributeStickerSet(Cons_webPageAttributeStickerSet) + case webPageAttributeStory(Cons_webPageAttributeStory) + case webPageAttributeTheme(Cons_webPageAttributeTheme) + case webPageAttributeUniqueStarGift(Cons_webPageAttributeUniqueStarGift) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .webPageAttributeStarGiftAuction(let _data): + if boxed { + buffer.appendInt32(29770178) + } + _data.gift.serialize(buffer, true) + serializeInt32(_data.endDate, buffer: buffer, boxed: false) + break + case .webPageAttributeStarGiftCollection(let _data): + if boxed { + buffer.appendInt32(835375875) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.icons.count)) + for item in _data.icons { + item.serialize(buffer, true) + } + break + case .webPageAttributeStickerSet(let _data): + if boxed { + buffer.appendInt32(1355547603) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.stickers.count)) + for item in _data.stickers { + item.serialize(buffer, true) + } + break + case .webPageAttributeStory(let _data): + if boxed { + buffer.appendInt32(781501415) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeInt32(_data.id, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.story!.serialize(buffer, true) + } + break + case .webPageAttributeTheme(let _data): + if boxed { + buffer.appendInt32(1421174295) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(ringtones.count)) - for item in ringtones { + buffer.appendInt32(Int32(_data.documents!.count)) + for item in _data.documents! { item.serialize(buffer, true) } - break - case .savedRingtonesNotModified: - if boxed { - buffer.appendInt32(-67704655) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .savedRingtones(let hash, let ringtones): - return ("savedRingtones", [("hash", hash as Any), ("ringtones", ringtones as Any)]) - case .savedRingtonesNotModified: - return ("savedRingtonesNotModified", []) - } - } - - public static func parse_savedRingtones(_ reader: BufferReader) -> SavedRingtones? { - var _1: Int64? - _1 = reader.readInt64() + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.settings!.serialize(buffer, true) + } + break + case .webPageAttributeUniqueStarGift(let _data): + if boxed { + buffer.appendInt32(-814781000) + } + _data.gift.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .webPageAttributeStarGiftAuction(let _data): + return ("webPageAttributeStarGiftAuction", [("gift", _data.gift as Any), ("endDate", _data.endDate as Any)]) + case .webPageAttributeStarGiftCollection(let _data): + return ("webPageAttributeStarGiftCollection", [("icons", _data.icons as Any)]) + case .webPageAttributeStickerSet(let _data): + return ("webPageAttributeStickerSet", [("flags", _data.flags as Any), ("stickers", _data.stickers as Any)]) + case .webPageAttributeStory(let _data): + return ("webPageAttributeStory", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("id", _data.id as Any), ("story", _data.story as Any)]) + case .webPageAttributeTheme(let _data): + return ("webPageAttributeTheme", [("flags", _data.flags as Any), ("documents", _data.documents as Any), ("settings", _data.settings as Any)]) + case .webPageAttributeUniqueStarGift(let _data): + return ("webPageAttributeUniqueStarGift", [("gift", _data.gift as Any)]) + } + } + + public static func parse_webPageAttributeStarGiftAuction(_ reader: BufferReader) -> WebPageAttribute? { + var _1: Api.StarGift? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.StarGift + } + var _2: Int32? + _2 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.WebPageAttribute.webPageAttributeStarGiftAuction(Cons_webPageAttributeStarGiftAuction(gift: _1!, endDate: _2!)) + } + else { + return nil + } + } + public static func parse_webPageAttributeStarGiftCollection(_ reader: BufferReader) -> WebPageAttribute? { + var _1: [Api.Document]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + } + let _c1 = _1 != nil + if _c1 { + return Api.WebPageAttribute.webPageAttributeStarGiftCollection(Cons_webPageAttributeStarGiftCollection(icons: _1!)) + } + else { + return nil + } + } + public static func parse_webPageAttributeStickerSet(_ reader: BufferReader) -> WebPageAttribute? { + var _1: Int32? + _1 = reader.readInt32() var _2: [Api.Document]? if let _ = reader.readInt32() { _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.account.SavedRingtones.savedRingtones(hash: _1!, ringtones: _2!) + if _c1 && _c2 { + return Api.WebPageAttribute.webPageAttributeStickerSet(Cons_webPageAttributeStickerSet(flags: _1!, stickers: _2!)) + } + else { + return nil + } } - public static func parse_savedRingtonesNotModified(_ reader: BufferReader) -> SavedRingtones? { - return Api.account.SavedRingtones.savedRingtonesNotModified - } - - } -} -public extension Api.account { - enum SentEmailCode: TypeConstructorDescription { - case sentEmailCode(emailPattern: String, length: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .sentEmailCode(let emailPattern, let length): - if boxed { - buffer.appendInt32(-2128640689) - } - serializeString(emailPattern, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .sentEmailCode(let emailPattern, let length): - return ("sentEmailCode", [("emailPattern", emailPattern as Any), ("length", length as Any)]) - } - } - - public static func parse_sentEmailCode(_ reader: BufferReader) -> SentEmailCode? { - var _1: String? - _1 = parseString(reader) - var _2: Int32? - _2 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.account.SentEmailCode.sentEmailCode(emailPattern: _1!, length: _2!) - } - - } -} -public extension Api.account { - enum Takeout: TypeConstructorDescription { - case takeout(id: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .takeout(let id): - if boxed { - buffer.appendInt32(1304052993) - } - serializeInt64(id, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .takeout(let id): - return ("takeout", [("id", id as Any)]) - } - } - - public static func parse_takeout(_ reader: BufferReader) -> Takeout? { - var _1: Int64? - _1 = reader.readInt64() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.account.Takeout.takeout(id: _1!) - } - - } -} -public extension Api.account { - enum Themes: TypeConstructorDescription { - case themes(hash: Int64, themes: [Api.Theme]) - case themesNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .themes(let hash, let themes): - if boxed { - buffer.appendInt32(-1707242387) - } - serializeInt64(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(themes.count)) - for item in themes { - item.serialize(buffer, true) - } - break - case .themesNotModified: - if boxed { - buffer.appendInt32(-199313886) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .themes(let hash, let themes): - return ("themes", [("hash", hash as Any), ("themes", themes as Any)]) - case .themesNotModified: - return ("themesNotModified", []) - } - } - - public static func parse_themes(_ reader: BufferReader) -> Themes? { - var _1: Int64? - _1 = reader.readInt64() - var _2: [Api.Theme]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Theme.self) + public static func parse_webPageAttributeStory(_ reader: BufferReader) -> WebPageAttribute? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: Int32? + _3 = reader.readInt32() + var _4: Api.StoryItem? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.StoryItem + } } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.account.Themes.themes(hash: _1!, themes: _2!) + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.WebPageAttribute.webPageAttributeStory(Cons_webPageAttributeStory(flags: _1!, peer: _2!, id: _3!, story: _4)) + } + else { + return nil + } } - public static func parse_themesNotModified(_ reader: BufferReader) -> Themes? { - return Api.account.Themes.themesNotModified - } - - } -} -public extension Api.account { - enum TmpPassword: TypeConstructorDescription { - case tmpPassword(tmpPassword: Buffer, validUntil: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .tmpPassword(let tmpPassword, let validUntil): - if boxed { - buffer.appendInt32(-614138572) - } - serializeBytes(tmpPassword, buffer: buffer, boxed: false) - serializeInt32(validUntil, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .tmpPassword(let tmpPassword, let validUntil): - return ("tmpPassword", [("tmpPassword", tmpPassword as Any), ("validUntil", validUntil as Any)]) - } - } - - public static func parse_tmpPassword(_ reader: BufferReader) -> TmpPassword? { - var _1: Buffer? - _1 = parseBytes(reader) - var _2: Int32? - _2 = reader.readInt32() + public static func parse_webPageAttributeTheme(_ reader: BufferReader) -> WebPageAttribute? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.Document]? + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + } + } + var _3: Api.ThemeSettings? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.ThemeSettings + } + } let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.account.TmpPassword.tmpPassword(tmpPassword: _1!, validUntil: _2!) + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil + if _c1 && _c2 && _c3 { + return Api.WebPageAttribute.webPageAttributeTheme(Cons_webPageAttributeTheme(flags: _1!, documents: _2, settings: _3)) + } + else { + return nil + } + } + public static func parse_webPageAttributeUniqueStarGift(_ reader: BufferReader) -> WebPageAttribute? { + var _1: Api.StarGift? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.StarGift + } + let _c1 = _1 != nil + if _c1 { + return Api.WebPageAttribute.webPageAttributeUniqueStarGift(Cons_webPageAttributeUniqueStarGift(gift: _1!)) + } + else { + return nil + } + } + } +} +public extension Api { + enum WebViewMessageSent: TypeConstructorDescription { + public class Cons_webViewMessageSent { + public var flags: Int32 + public var msgId: Api.InputBotInlineMessageID? + public init(flags: Int32, msgId: Api.InputBotInlineMessageID?) { + self.flags = flags + self.msgId = msgId + } + } + case webViewMessageSent(Cons_webViewMessageSent) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .webViewMessageSent(let _data): + if boxed { + buffer.appendInt32(211046684) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.msgId!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .webViewMessageSent(let _data): + return ("webViewMessageSent", [("flags", _data.flags as Any), ("msgId", _data.msgId as Any)]) + } + } + + public static func parse_webViewMessageSent(_ reader: BufferReader) -> WebViewMessageSent? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.InputBotInlineMessageID? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.InputBotInlineMessageID + } + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + if _c1 && _c2 { + return Api.WebViewMessageSent.webViewMessageSent(Cons_webViewMessageSent(flags: _1!, msgId: _2)) + } + else { + return nil + } + } + } +} +public extension Api { + enum WebViewResult: TypeConstructorDescription { + public class Cons_webViewResultUrl { + public var flags: Int32 + public var queryId: Int64? + public var url: String + public init(flags: Int32, queryId: Int64?, url: String) { + self.flags = flags + self.queryId = queryId + self.url = url + } + } + case webViewResultUrl(Cons_webViewResultUrl) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .webViewResultUrl(let _data): + if boxed { + buffer.appendInt32(1294139288) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.queryId!, buffer: buffer, boxed: false) + } + serializeString(_data.url, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .webViewResultUrl(let _data): + return ("webViewResultUrl", [("flags", _data.flags as Any), ("queryId", _data.queryId as Any), ("url", _data.url as Any)]) + } + } + + public static func parse_webViewResultUrl(_ reader: BufferReader) -> WebViewResult? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt64() + } + var _3: String? + _3 = parseString(reader) + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.WebViewResult.webViewResultUrl(Cons_webViewResultUrl(flags: _1!, queryId: _2, url: _3!)) + } + else { + return nil + } } - } } public extension Api.account { - enum WallPapers: TypeConstructorDescription { - case wallPapers(hash: Int64, wallpapers: [Api.WallPaper]) - case wallPapersNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .wallPapers(let hash, let wallpapers): - if boxed { - buffer.appendInt32(-842824308) - } - serializeInt64(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(wallpapers.count)) - for item in wallpapers { - item.serialize(buffer, true) - } - break - case .wallPapersNotModified: - if boxed { - buffer.appendInt32(471437699) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .wallPapers(let hash, let wallpapers): - return ("wallPapers", [("hash", hash as Any), ("wallpapers", wallpapers as Any)]) - case .wallPapersNotModified: - return ("wallPapersNotModified", []) - } - } - - public static func parse_wallPapers(_ reader: BufferReader) -> WallPapers? { - var _1: Int64? - _1 = reader.readInt64() - var _2: [Api.WallPaper]? + enum AuthorizationForm: TypeConstructorDescription { + public class Cons_authorizationForm { + public var flags: Int32 + public var requiredTypes: [Api.SecureRequiredType] + public var values: [Api.SecureValue] + public var errors: [Api.SecureValueError] + public var users: [Api.User] + public var privacyPolicyUrl: String? + public init(flags: Int32, requiredTypes: [Api.SecureRequiredType], values: [Api.SecureValue], errors: [Api.SecureValueError], users: [Api.User], privacyPolicyUrl: String?) { + self.flags = flags + self.requiredTypes = requiredTypes + self.values = values + self.errors = errors + self.users = users + self.privacyPolicyUrl = privacyPolicyUrl + } + } + case authorizationForm(Cons_authorizationForm) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .authorizationForm(let _data): + if boxed { + buffer.appendInt32(-1389486888) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.requiredTypes.count)) + for item in _data.requiredTypes { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.values.count)) + for item in _data.values { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.errors.count)) + for item in _data.errors { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.privacyPolicyUrl!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .authorizationForm(let _data): + return ("authorizationForm", [("flags", _data.flags as Any), ("requiredTypes", _data.requiredTypes as Any), ("values", _data.values as Any), ("errors", _data.errors as Any), ("users", _data.users as Any), ("privacyPolicyUrl", _data.privacyPolicyUrl as Any)]) + } + } + + public static func parse_authorizationForm(_ reader: BufferReader) -> AuthorizationForm? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.SecureRequiredType]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.WallPaper.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureRequiredType.self) + } + var _3: [Api.SecureValue]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureValue.self) + } + var _4: [Api.SecureValueError]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureValueError.self) + } + var _5: [Api.User]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + var _6: String? + if Int(_1!) & Int(1 << 0) != 0 { + _6 = parseString(reader) } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.account.WallPapers.wallPapers(hash: _1!, wallpapers: _2!) + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.account.AuthorizationForm.authorizationForm(Cons_authorizationForm(flags: _1!, requiredTypes: _2!, values: _3!, errors: _4!, users: _5!, privacyPolicyUrl: _6)) + } + else { + return nil + } } - public static func parse_wallPapersNotModified(_ reader: BufferReader) -> WallPapers? { - return Api.account.WallPapers.wallPapersNotModified - } - } } public extension Api.account { - enum WebAuthorizations: TypeConstructorDescription { - case webAuthorizations(authorizations: [Api.WebAuthorization], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .webAuthorizations(let authorizations, let users): - if boxed { - buffer.appendInt32(-313079300) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(authorizations.count)) - for item in authorizations { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .webAuthorizations(let authorizations, let users): - return ("webAuthorizations", [("authorizations", authorizations as Any), ("users", users as Any)]) - } - } - - public static func parse_webAuthorizations(_ reader: BufferReader) -> WebAuthorizations? { - var _1: [Api.WebAuthorization]? + enum Authorizations: TypeConstructorDescription { + public class Cons_authorizations { + public var authorizationTtlDays: Int32 + public var authorizations: [Api.Authorization] + public init(authorizationTtlDays: Int32, authorizations: [Api.Authorization]) { + self.authorizationTtlDays = authorizationTtlDays + self.authorizations = authorizations + } + } + case authorizations(Cons_authorizations) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .authorizations(let _data): + if boxed { + buffer.appendInt32(1275039392) + } + serializeInt32(_data.authorizationTtlDays, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.authorizations.count)) + for item in _data.authorizations { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .authorizations(let _data): + return ("authorizations", [("authorizationTtlDays", _data.authorizationTtlDays as Any), ("authorizations", _data.authorizations as Any)]) + } + } + + public static func parse_authorizations(_ reader: BufferReader) -> Authorizations? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.Authorization]? if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.WebAuthorization.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Authorization.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.account.Authorizations.authorizations(Cons_authorizations(authorizationTtlDays: _1!, authorizations: _2!)) + } + else { + return nil + } + } + } +} +public extension Api.account { + enum AutoDownloadSettings: TypeConstructorDescription { + public class Cons_autoDownloadSettings { + public var low: Api.AutoDownloadSettings + public var medium: Api.AutoDownloadSettings + public var high: Api.AutoDownloadSettings + public init(low: Api.AutoDownloadSettings, medium: Api.AutoDownloadSettings, high: Api.AutoDownloadSettings) { + self.low = low + self.medium = medium + self.high = high + } + } + case autoDownloadSettings(Cons_autoDownloadSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .autoDownloadSettings(let _data): + if boxed { + buffer.appendInt32(1674235686) + } + _data.low.serialize(buffer, true) + _data.medium.serialize(buffer, true) + _data.high.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .autoDownloadSettings(let _data): + return ("autoDownloadSettings", [("low", _data.low as Any), ("medium", _data.medium as Any), ("high", _data.high as Any)]) + } + } + + public static func parse_autoDownloadSettings(_ reader: BufferReader) -> AutoDownloadSettings? { + var _1: Api.AutoDownloadSettings? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.AutoDownloadSettings + } + var _2: Api.AutoDownloadSettings? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.AutoDownloadSettings + } + var _3: Api.AutoDownloadSettings? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.AutoDownloadSettings + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.account.AutoDownloadSettings.autoDownloadSettings(Cons_autoDownloadSettings(low: _1!, medium: _2!, high: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.account { + enum AutoSaveSettings: TypeConstructorDescription { + public class Cons_autoSaveSettings { + public var usersSettings: Api.AutoSaveSettings + public var chatsSettings: Api.AutoSaveSettings + public var broadcastsSettings: Api.AutoSaveSettings + public var exceptions: [Api.AutoSaveException] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(usersSettings: Api.AutoSaveSettings, chatsSettings: Api.AutoSaveSettings, broadcastsSettings: Api.AutoSaveSettings, exceptions: [Api.AutoSaveException], chats: [Api.Chat], users: [Api.User]) { + self.usersSettings = usersSettings + self.chatsSettings = chatsSettings + self.broadcastsSettings = broadcastsSettings + self.exceptions = exceptions + self.chats = chats + self.users = users + } + } + case autoSaveSettings(Cons_autoSaveSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .autoSaveSettings(let _data): + if boxed { + buffer.appendInt32(1279133341) + } + _data.usersSettings.serialize(buffer, true) + _data.chatsSettings.serialize(buffer, true) + _data.broadcastsSettings.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.exceptions.count)) + for item in _data.exceptions { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .autoSaveSettings(let _data): + return ("autoSaveSettings", [("usersSettings", _data.usersSettings as Any), ("chatsSettings", _data.chatsSettings as Any), ("broadcastsSettings", _data.broadcastsSettings as Any), ("exceptions", _data.exceptions as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_autoSaveSettings(_ reader: BufferReader) -> AutoSaveSettings? { + var _1: Api.AutoSaveSettings? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.AutoSaveSettings + } + var _2: Api.AutoSaveSettings? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.AutoSaveSettings + } + var _3: Api.AutoSaveSettings? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.AutoSaveSettings + } + var _4: [Api.AutoSaveException]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.AutoSaveException.self) + } + var _5: [Api.Chat]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _6: [Api.User]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.account.AutoSaveSettings.autoSaveSettings(Cons_autoSaveSettings(usersSettings: _1!, chatsSettings: _2!, broadcastsSettings: _3!, exceptions: _4!, chats: _5!, users: _6!)) + } + else { + return nil + } + } + } +} +public extension Api.account { + enum BusinessChatLinks: TypeConstructorDescription { + public class Cons_businessChatLinks { + public var links: [Api.BusinessChatLink] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(links: [Api.BusinessChatLink], chats: [Api.Chat], users: [Api.User]) { + self.links = links + self.chats = chats + self.users = users + } + } + case businessChatLinks(Cons_businessChatLinks) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .businessChatLinks(let _data): + if boxed { + buffer.appendInt32(-331111727) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.links.count)) + for item in _data.links { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .businessChatLinks(let _data): + return ("businessChatLinks", [("links", _data.links as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_businessChatLinks(_ reader: BufferReader) -> BusinessChatLinks? { + var _1: [Api.BusinessChatLink]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.BusinessChatLink.self) + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.account.BusinessChatLinks.businessChatLinks(Cons_businessChatLinks(links: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.account { + enum ChatThemes: TypeConstructorDescription { + public class Cons_chatThemes { + public var flags: Int32 + public var hash: Int64 + public var themes: [Api.ChatTheme] + public var chats: [Api.Chat] + public var users: [Api.User] + public var nextOffset: String? + public init(flags: Int32, hash: Int64, themes: [Api.ChatTheme], chats: [Api.Chat], users: [Api.User], nextOffset: String?) { + self.flags = flags + self.hash = hash + self.themes = themes + self.chats = chats + self.users = users + self.nextOffset = nextOffset + } + } + case chatThemes(Cons_chatThemes) + case chatThemesNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatThemes(let _data): + if boxed { + buffer.appendInt32(-1106673293) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.themes.count)) + for item in _data.themes { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.nextOffset!, buffer: buffer, boxed: false) + } + break + case .chatThemesNotModified: + if boxed { + buffer.appendInt32(-535699004) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatThemes(let _data): + return ("chatThemes", [("flags", _data.flags as Any), ("hash", _data.hash as Any), ("themes", _data.themes as Any), ("chats", _data.chats as Any), ("users", _data.users as Any), ("nextOffset", _data.nextOffset as Any)]) + case .chatThemesNotModified: + return ("chatThemesNotModified", []) + } + } + + public static func parse_chatThemes(_ reader: BufferReader) -> ChatThemes? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: [Api.ChatTheme]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ChatTheme.self) + } + var _4: [Api.Chat]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _5: [Api.User]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + var _6: String? + if Int(_1!) & Int(1 << 0) != 0 { + _6 = parseString(reader) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.account.ChatThemes.chatThemes(Cons_chatThemes(flags: _1!, hash: _2!, themes: _3!, chats: _4!, users: _5!, nextOffset: _6)) + } + else { + return nil + } + } + public static func parse_chatThemesNotModified(_ reader: BufferReader) -> ChatThemes? { + return Api.account.ChatThemes.chatThemesNotModified + } + } +} +public extension Api.account { + enum ConnectedBots: TypeConstructorDescription { + public class Cons_connectedBots { + public var connectedBots: [Api.ConnectedBot] + public var users: [Api.User] + public init(connectedBots: [Api.ConnectedBot], users: [Api.User]) { + self.connectedBots = connectedBots + self.users = users + } + } + case connectedBots(Cons_connectedBots) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .connectedBots(let _data): + if boxed { + buffer.appendInt32(400029819) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.connectedBots.count)) + for item in _data.connectedBots { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .connectedBots(let _data): + return ("connectedBots", [("connectedBots", _data.connectedBots as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_connectedBots(_ reader: BufferReader) -> ConnectedBots? { + var _1: [Api.ConnectedBot]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ConnectedBot.self) } var _2: [Api.User]? if let _ = reader.readInt32() { @@ -407,756 +892,860 @@ public extension Api.account { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.account.WebAuthorizations.webAuthorizations(authorizations: _1!, users: _2!) + if _c1 && _c2 { + return Api.account.ConnectedBots.connectedBots(Cons_connectedBots(connectedBots: _1!, users: _2!)) + } + else { + return nil + } } - } } -public extension Api.auth { - enum Authorization: TypeConstructorDescription { - case authorization(flags: Int32, otherwiseReloginDays: Int32?, tmpSessions: Int32?, futureAuthToken: Buffer?, user: Api.User) - case authorizationSignUpRequired(flags: Int32, termsOfService: Api.help.TermsOfService?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .authorization(let flags, let otherwiseReloginDays, let tmpSessions, let futureAuthToken, let user): - if boxed { - buffer.appendInt32(782418132) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(otherwiseReloginDays!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(tmpSessions!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeBytes(futureAuthToken!, buffer: buffer, boxed: false)} - user.serialize(buffer, true) - break - case .authorizationSignUpRequired(let flags, let termsOfService): - if boxed { - buffer.appendInt32(1148485274) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {termsOfService!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .authorization(let flags, let otherwiseReloginDays, let tmpSessions, let futureAuthToken, let user): - return ("authorization", [("flags", flags as Any), ("otherwiseReloginDays", otherwiseReloginDays as Any), ("tmpSessions", tmpSessions as Any), ("futureAuthToken", futureAuthToken as Any), ("user", user as Any)]) - case .authorizationSignUpRequired(let flags, let termsOfService): - return ("authorizationSignUpRequired", [("flags", flags as Any), ("termsOfService", termsOfService as Any)]) - } - } - - public static func parse_authorization(_ reader: BufferReader) -> Authorization? { +public extension Api.account { + enum ContentSettings: TypeConstructorDescription { + public class Cons_contentSettings { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } + case contentSettings(Cons_contentSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .contentSettings(let _data): + if boxed { + buffer.appendInt32(1474462241) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .contentSettings(let _data): + return ("contentSettings", [("flags", _data.flags as Any)]) + } + } + + public static func parse_contentSettings(_ reader: BufferReader) -> ContentSettings? { var _1: Int32? _1 = reader.readInt32() - var _2: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_2 = reader.readInt32() } - var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } - var _4: Buffer? - if Int(_1!) & Int(1 << 2) != 0 {_4 = parseBytes(reader) } - var _5: Api.User? + let _c1 = _1 != nil + if _c1 { + return Api.account.ContentSettings.contentSettings(Cons_contentSettings(flags: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.account { + enum EmailVerified: TypeConstructorDescription { + public class Cons_emailVerified { + public var email: String + public init(email: String) { + self.email = email + } + } + public class Cons_emailVerifiedLogin { + public var email: String + public var sentCode: Api.auth.SentCode + public init(email: String, sentCode: Api.auth.SentCode) { + self.email = email + self.sentCode = sentCode + } + } + case emailVerified(Cons_emailVerified) + case emailVerifiedLogin(Cons_emailVerifiedLogin) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .emailVerified(let _data): + if boxed { + buffer.appendInt32(731303195) + } + serializeString(_data.email, buffer: buffer, boxed: false) + break + case .emailVerifiedLogin(let _data): + if boxed { + buffer.appendInt32(-507835039) + } + serializeString(_data.email, buffer: buffer, boxed: false) + _data.sentCode.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .emailVerified(let _data): + return ("emailVerified", [("email", _data.email as Any)]) + case .emailVerifiedLogin(let _data): + return ("emailVerifiedLogin", [("email", _data.email as Any), ("sentCode", _data.sentCode as Any)]) + } + } + + public static func parse_emailVerified(_ reader: BufferReader) -> EmailVerified? { + var _1: String? + _1 = parseString(reader) + let _c1 = _1 != nil + if _c1 { + return Api.account.EmailVerified.emailVerified(Cons_emailVerified(email: _1!)) + } + else { + return nil + } + } + public static func parse_emailVerifiedLogin(_ reader: BufferReader) -> EmailVerified? { + var _1: String? + _1 = parseString(reader) + var _2: Api.auth.SentCode? if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.User + _2 = Api.parse(reader, signature: signature) as? Api.auth.SentCode } let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.auth.Authorization.authorization(flags: _1!, otherwiseReloginDays: _2, tmpSessions: _3, futureAuthToken: _4, user: _5!) + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.account.EmailVerified.emailVerifiedLogin(Cons_emailVerifiedLogin(email: _1!, sentCode: _2!)) + } + else { + return nil + } } - public static func parse_authorizationSignUpRequired(_ reader: BufferReader) -> Authorization? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.help.TermsOfService? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.help.TermsOfService - } } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.auth.Authorization.authorizationSignUpRequired(flags: _1!, termsOfService: _2) - } - } } -public extension Api.auth { - enum CodeType: TypeConstructorDescription { - case codeTypeCall - case codeTypeFlashCall - case codeTypeFragmentSms - case codeTypeMissedCall - case codeTypeSms - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .codeTypeCall: - if boxed { - buffer.appendInt32(1948046307) - } - - break - case .codeTypeFlashCall: - if boxed { - buffer.appendInt32(577556219) - } - - break - case .codeTypeFragmentSms: - if boxed { - buffer.appendInt32(116234636) - } - - break - case .codeTypeMissedCall: - if boxed { - buffer.appendInt32(-702884114) - } - - break - case .codeTypeSms: - if boxed { - buffer.appendInt32(1923290508) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .codeTypeCall: - return ("codeTypeCall", []) - case .codeTypeFlashCall: - return ("codeTypeFlashCall", []) - case .codeTypeFragmentSms: - return ("codeTypeFragmentSms", []) - case .codeTypeMissedCall: - return ("codeTypeMissedCall", []) - case .codeTypeSms: - return ("codeTypeSms", []) - } - } - - public static func parse_codeTypeCall(_ reader: BufferReader) -> CodeType? { - return Api.auth.CodeType.codeTypeCall +public extension Api.account { + enum EmojiStatuses: TypeConstructorDescription { + public class Cons_emojiStatuses { + public var hash: Int64 + public var statuses: [Api.EmojiStatus] + public init(hash: Int64, statuses: [Api.EmojiStatus]) { + self.hash = hash + self.statuses = statuses + } } - public static func parse_codeTypeFlashCall(_ reader: BufferReader) -> CodeType? { - return Api.auth.CodeType.codeTypeFlashCall + case emojiStatuses(Cons_emojiStatuses) + case emojiStatusesNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .emojiStatuses(let _data): + if boxed { + buffer.appendInt32(-1866176559) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.statuses.count)) + for item in _data.statuses { + item.serialize(buffer, true) + } + break + case .emojiStatusesNotModified: + if boxed { + buffer.appendInt32(-796072379) + } + break + } } - public static func parse_codeTypeFragmentSms(_ reader: BufferReader) -> CodeType? { - return Api.auth.CodeType.codeTypeFragmentSms + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .emojiStatuses(let _data): + return ("emojiStatuses", [("hash", _data.hash as Any), ("statuses", _data.statuses as Any)]) + case .emojiStatusesNotModified: + return ("emojiStatusesNotModified", []) + } } - public static func parse_codeTypeMissedCall(_ reader: BufferReader) -> CodeType? { - return Api.auth.CodeType.codeTypeMissedCall - } - public static func parse_codeTypeSms(_ reader: BufferReader) -> CodeType? { - return Api.auth.CodeType.codeTypeSms - } - - } -} -public extension Api.auth { - enum ExportedAuthorization: TypeConstructorDescription { - case exportedAuthorization(id: Int64, bytes: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .exportedAuthorization(let id, let bytes): - if boxed { - buffer.appendInt32(-1271602504) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeBytes(bytes, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .exportedAuthorization(let id, let bytes): - return ("exportedAuthorization", [("id", id as Any), ("bytes", bytes as Any)]) - } - } - - public static func parse_exportedAuthorization(_ reader: BufferReader) -> ExportedAuthorization? { + + public static func parse_emojiStatuses(_ reader: BufferReader) -> EmojiStatuses? { var _1: Int64? _1 = reader.readInt64() - var _2: Buffer? - _2 = parseBytes(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.auth.ExportedAuthorization.exportedAuthorization(id: _1!, bytes: _2!) - } - - } -} -public extension Api.auth { - enum LoggedOut: TypeConstructorDescription { - case loggedOut(flags: Int32, futureAuthToken: Buffer?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .loggedOut(let flags, let futureAuthToken): - if boxed { - buffer.appendInt32(-1012759713) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeBytes(futureAuthToken!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .loggedOut(let flags, let futureAuthToken): - return ("loggedOut", [("flags", flags as Any), ("futureAuthToken", futureAuthToken as Any)]) - } - } - - public static func parse_loggedOut(_ reader: BufferReader) -> LoggedOut? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Buffer? - if Int(_1!) & Int(1 << 0) != 0 {_2 = parseBytes(reader) } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.auth.LoggedOut.loggedOut(flags: _1!, futureAuthToken: _2) - } - - } -} -public extension Api.auth { - enum LoginToken: TypeConstructorDescription { - case loginToken(expires: Int32, token: Buffer) - case loginTokenMigrateTo(dcId: Int32, token: Buffer) - case loginTokenSuccess(authorization: Api.auth.Authorization) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .loginToken(let expires, let token): - if boxed { - buffer.appendInt32(1654593920) - } - serializeInt32(expires, buffer: buffer, boxed: false) - serializeBytes(token, buffer: buffer, boxed: false) - break - case .loginTokenMigrateTo(let dcId, let token): - if boxed { - buffer.appendInt32(110008598) - } - serializeInt32(dcId, buffer: buffer, boxed: false) - serializeBytes(token, buffer: buffer, boxed: false) - break - case .loginTokenSuccess(let authorization): - if boxed { - buffer.appendInt32(957176926) - } - authorization.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .loginToken(let expires, let token): - return ("loginToken", [("expires", expires as Any), ("token", token as Any)]) - case .loginTokenMigrateTo(let dcId, let token): - return ("loginTokenMigrateTo", [("dcId", dcId as Any), ("token", token as Any)]) - case .loginTokenSuccess(let authorization): - return ("loginTokenSuccess", [("authorization", authorization as Any)]) - } - } - - public static func parse_loginToken(_ reader: BufferReader) -> LoginToken? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Buffer? - _2 = parseBytes(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.auth.LoginToken.loginToken(expires: _1!, token: _2!) - } - public static func parse_loginTokenMigrateTo(_ reader: BufferReader) -> LoginToken? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Buffer? - _2 = parseBytes(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.auth.LoginToken.loginTokenMigrateTo(dcId: _1!, token: _2!) - } - public static func parse_loginTokenSuccess(_ reader: BufferReader) -> LoginToken? { - var _1: Api.auth.Authorization? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.auth.Authorization + var _2: [Api.EmojiStatus]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.EmojiStatus.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.auth.LoginToken.loginTokenSuccess(authorization: _1!) + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.account.EmojiStatuses.emojiStatuses(Cons_emojiStatuses(hash: _1!, statuses: _2!)) + } + else { + return nil + } + } + public static func parse_emojiStatusesNotModified(_ reader: BufferReader) -> EmojiStatuses? { + return Api.account.EmojiStatuses.emojiStatusesNotModified } - } } -public extension Api.auth { - enum PasskeyLoginOptions: TypeConstructorDescription { - case passkeyLoginOptions(options: Api.DataJSON) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .passkeyLoginOptions(let options): - if boxed { - buffer.appendInt32(-503089271) - } - options.serialize(buffer, true) - break +public extension Api.account { + enum PaidMessagesRevenue: TypeConstructorDescription { + public class Cons_paidMessagesRevenue { + public var starsAmount: Int64 + public init(starsAmount: Int64) { + self.starsAmount = starsAmount + } + } + case paidMessagesRevenue(Cons_paidMessagesRevenue) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .paidMessagesRevenue(let _data): + if boxed { + buffer.appendInt32(504403720) + } + serializeInt64(_data.starsAmount, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .paidMessagesRevenue(let _data): + return ("paidMessagesRevenue", [("starsAmount", _data.starsAmount as Any)]) + } + } + + public static func parse_paidMessagesRevenue(_ reader: BufferReader) -> PaidMessagesRevenue? { + var _1: Int64? + _1 = reader.readInt64() + let _c1 = _1 != nil + if _c1 { + return Api.account.PaidMessagesRevenue.paidMessagesRevenue(Cons_paidMessagesRevenue(starsAmount: _1!)) + } + else { + return nil + } + } } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .passkeyLoginOptions(let options): - return ("passkeyLoginOptions", [("options", options as Any)]) - } - } - - public static func parse_passkeyLoginOptions(_ reader: BufferReader) -> PasskeyLoginOptions? { +} +public extension Api.account { + enum PasskeyRegistrationOptions: TypeConstructorDescription { + public class Cons_passkeyRegistrationOptions { + public var options: Api.DataJSON + public init(options: Api.DataJSON) { + self.options = options + } + } + case passkeyRegistrationOptions(Cons_passkeyRegistrationOptions) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .passkeyRegistrationOptions(let _data): + if boxed { + buffer.appendInt32(-513057567) + } + _data.options.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .passkeyRegistrationOptions(let _data): + return ("passkeyRegistrationOptions", [("options", _data.options as Any)]) + } + } + + public static func parse_passkeyRegistrationOptions(_ reader: BufferReader) -> PasskeyRegistrationOptions? { var _1: Api.DataJSON? if let signature = reader.readInt32() { _1 = Api.parse(reader, signature: signature) as? Api.DataJSON } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.auth.PasskeyLoginOptions.passkeyLoginOptions(options: _1!) - } - - } -} -public extension Api.auth { - enum PasswordRecovery: TypeConstructorDescription { - case passwordRecovery(emailPattern: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .passwordRecovery(let emailPattern): - if boxed { - buffer.appendInt32(326715557) - } - serializeString(emailPattern, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .passwordRecovery(let emailPattern): - return ("passwordRecovery", [("emailPattern", emailPattern as Any)]) - } - } - - public static func parse_passwordRecovery(_ reader: BufferReader) -> PasswordRecovery? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.auth.PasswordRecovery.passwordRecovery(emailPattern: _1!) - } - - } -} -public extension Api.auth { - enum SentCode: TypeConstructorDescription { - case sentCode(flags: Int32, type: Api.auth.SentCodeType, phoneCodeHash: String, nextType: Api.auth.CodeType?, timeout: Int32?) - case sentCodePaymentRequired(storeProduct: String, phoneCodeHash: String, supportEmailAddress: String, supportEmailSubject: String, currency: String, amount: Int64) - case sentCodeSuccess(authorization: Api.auth.Authorization) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .sentCode(let flags, let type, let phoneCodeHash, let nextType, let timeout): - if boxed { - buffer.appendInt32(1577067778) - } - serializeInt32(flags, buffer: buffer, boxed: false) - type.serialize(buffer, true) - serializeString(phoneCodeHash, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {nextType!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(timeout!, buffer: buffer, boxed: false)} - break - case .sentCodePaymentRequired(let storeProduct, let phoneCodeHash, let supportEmailAddress, let supportEmailSubject, let currency, let amount): - if boxed { - buffer.appendInt32(-527082948) - } - serializeString(storeProduct, buffer: buffer, boxed: false) - serializeString(phoneCodeHash, buffer: buffer, boxed: false) - serializeString(supportEmailAddress, buffer: buffer, boxed: false) - serializeString(supportEmailSubject, buffer: buffer, boxed: false) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - break - case .sentCodeSuccess(let authorization): - if boxed { - buffer.appendInt32(596704836) - } - authorization.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .sentCode(let flags, let type, let phoneCodeHash, let nextType, let timeout): - return ("sentCode", [("flags", flags as Any), ("type", type as Any), ("phoneCodeHash", phoneCodeHash as Any), ("nextType", nextType as Any), ("timeout", timeout as Any)]) - case .sentCodePaymentRequired(let storeProduct, let phoneCodeHash, let supportEmailAddress, let supportEmailSubject, let currency, let amount): - return ("sentCodePaymentRequired", [("storeProduct", storeProduct as Any), ("phoneCodeHash", phoneCodeHash as Any), ("supportEmailAddress", supportEmailAddress as Any), ("supportEmailSubject", supportEmailSubject as Any), ("currency", currency as Any), ("amount", amount as Any)]) - case .sentCodeSuccess(let authorization): - return ("sentCodeSuccess", [("authorization", authorization as Any)]) - } - } - - public static func parse_sentCode(_ reader: BufferReader) -> SentCode? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.auth.SentCodeType? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.auth.SentCodeType + if _c1 { + return Api.account.PasskeyRegistrationOptions.passkeyRegistrationOptions(Cons_passkeyRegistrationOptions(options: _1!)) + } + else { + return nil } - var _3: String? - _3 = parseString(reader) - var _4: Api.auth.CodeType? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.auth.CodeType - } } - var _5: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_5 = reader.readInt32() } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 2) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.auth.SentCode.sentCode(flags: _1!, type: _2!, phoneCodeHash: _3!, nextType: _4, timeout: _5) } - public static func parse_sentCodePaymentRequired(_ reader: BufferReader) -> SentCode? { - var _1: String? - _1 = parseString(reader) - var _2: String? - _2 = parseString(reader) - var _3: String? - _3 = parseString(reader) - var _4: String? - _4 = parseString(reader) - var _5: String? - _5 = parseString(reader) - var _6: Int64? - _6 = reader.readInt64() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.auth.SentCode.sentCodePaymentRequired(storeProduct: _1!, phoneCodeHash: _2!, supportEmailAddress: _3!, supportEmailSubject: _4!, currency: _5!, amount: _6!) + } +} +public extension Api.account { + enum Passkeys: TypeConstructorDescription { + public class Cons_passkeys { + public var passkeys: [Api.Passkey] + public init(passkeys: [Api.Passkey]) { + self.passkeys = passkeys + } } - public static func parse_sentCodeSuccess(_ reader: BufferReader) -> SentCode? { - var _1: Api.auth.Authorization? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.auth.Authorization + case passkeys(Cons_passkeys) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .passkeys(let _data): + if boxed { + buffer.appendInt32(-119494116) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.passkeys.count)) + for item in _data.passkeys { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .passkeys(let _data): + return ("passkeys", [("passkeys", _data.passkeys as Any)]) + } + } + + public static func parse_passkeys(_ reader: BufferReader) -> Passkeys? { + var _1: [Api.Passkey]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Passkey.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.auth.SentCode.sentCodeSuccess(authorization: _1!) + if _c1 { + return Api.account.Passkeys.passkeys(Cons_passkeys(passkeys: _1!)) + } + else { + return nil + } } - } } -public extension Api.auth { - enum SentCodeType: TypeConstructorDescription { - case sentCodeTypeApp(length: Int32) - case sentCodeTypeCall(length: Int32) - case sentCodeTypeEmailCode(flags: Int32, emailPattern: String, length: Int32, resetAvailablePeriod: Int32?, resetPendingDate: Int32?) - case sentCodeTypeFirebaseSms(flags: Int32, nonce: Buffer?, playIntegrityProjectId: Int64?, playIntegrityNonce: Buffer?, receipt: String?, pushTimeout: Int32?, length: Int32) - case sentCodeTypeFlashCall(pattern: String) - case sentCodeTypeFragmentSms(url: String, length: Int32) - case sentCodeTypeMissedCall(prefix: String, length: Int32) - case sentCodeTypeSetUpEmailRequired(flags: Int32) - case sentCodeTypeSms(length: Int32) - case sentCodeTypeSmsPhrase(flags: Int32, beginning: String?) - case sentCodeTypeSmsWord(flags: Int32, beginning: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .sentCodeTypeApp(let length): - if boxed { - buffer.appendInt32(1035688326) - } - serializeInt32(length, buffer: buffer, boxed: false) - break - case .sentCodeTypeCall(let length): - if boxed { - buffer.appendInt32(1398007207) - } - serializeInt32(length, buffer: buffer, boxed: false) - break - case .sentCodeTypeEmailCode(let flags, let emailPattern, let length, let resetAvailablePeriod, let resetPendingDate): - if boxed { - buffer.appendInt32(-196020837) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(emailPattern, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(resetAvailablePeriod!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(resetPendingDate!, buffer: buffer, boxed: false)} - break - case .sentCodeTypeFirebaseSms(let flags, let nonce, let playIntegrityProjectId, let playIntegrityNonce, let receipt, let pushTimeout, let length): - if boxed { - buffer.appendInt32(10475318) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeBytes(nonce!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt64(playIntegrityProjectId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeBytes(playIntegrityNonce!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(receipt!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(pushTimeout!, buffer: buffer, boxed: false)} - serializeInt32(length, buffer: buffer, boxed: false) - break - case .sentCodeTypeFlashCall(let pattern): - if boxed { - buffer.appendInt32(-1425815847) - } - serializeString(pattern, buffer: buffer, boxed: false) - break - case .sentCodeTypeFragmentSms(let url, let length): - if boxed { - buffer.appendInt32(-648651719) - } - serializeString(url, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .sentCodeTypeMissedCall(let prefix, let length): - if boxed { - buffer.appendInt32(-2113903484) - } - serializeString(prefix, buffer: buffer, boxed: false) - serializeInt32(length, buffer: buffer, boxed: false) - break - case .sentCodeTypeSetUpEmailRequired(let flags): - if boxed { - buffer.appendInt32(-1521934870) - } - serializeInt32(flags, buffer: buffer, boxed: false) - break - case .sentCodeTypeSms(let length): - if boxed { - buffer.appendInt32(-1073693790) - } - serializeInt32(length, buffer: buffer, boxed: false) - break - case .sentCodeTypeSmsPhrase(let flags, let beginning): - if boxed { - buffer.appendInt32(-1284008785) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(beginning!, buffer: buffer, boxed: false)} - break - case .sentCodeTypeSmsWord(let flags, let beginning): - if boxed { - buffer.appendInt32(-1542017919) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(beginning!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .sentCodeTypeApp(let length): - return ("sentCodeTypeApp", [("length", length as Any)]) - case .sentCodeTypeCall(let length): - return ("sentCodeTypeCall", [("length", length as Any)]) - case .sentCodeTypeEmailCode(let flags, let emailPattern, let length, let resetAvailablePeriod, let resetPendingDate): - return ("sentCodeTypeEmailCode", [("flags", flags as Any), ("emailPattern", emailPattern as Any), ("length", length as Any), ("resetAvailablePeriod", resetAvailablePeriod as Any), ("resetPendingDate", resetPendingDate as Any)]) - case .sentCodeTypeFirebaseSms(let flags, let nonce, let playIntegrityProjectId, let playIntegrityNonce, let receipt, let pushTimeout, let length): - return ("sentCodeTypeFirebaseSms", [("flags", flags as Any), ("nonce", nonce as Any), ("playIntegrityProjectId", playIntegrityProjectId as Any), ("playIntegrityNonce", playIntegrityNonce as Any), ("receipt", receipt as Any), ("pushTimeout", pushTimeout as Any), ("length", length as Any)]) - case .sentCodeTypeFlashCall(let pattern): - return ("sentCodeTypeFlashCall", [("pattern", pattern as Any)]) - case .sentCodeTypeFragmentSms(let url, let length): - return ("sentCodeTypeFragmentSms", [("url", url as Any), ("length", length as Any)]) - case .sentCodeTypeMissedCall(let prefix, let length): - return ("sentCodeTypeMissedCall", [("prefix", prefix as Any), ("length", length as Any)]) - case .sentCodeTypeSetUpEmailRequired(let flags): - return ("sentCodeTypeSetUpEmailRequired", [("flags", flags as Any)]) - case .sentCodeTypeSms(let length): - return ("sentCodeTypeSms", [("length", length as Any)]) - case .sentCodeTypeSmsPhrase(let flags, let beginning): - return ("sentCodeTypeSmsPhrase", [("flags", flags as Any), ("beginning", beginning as Any)]) - case .sentCodeTypeSmsWord(let flags, let beginning): - return ("sentCodeTypeSmsWord", [("flags", flags as Any), ("beginning", beginning as Any)]) - } - } - - public static func parse_sentCodeTypeApp(_ reader: BufferReader) -> SentCodeType? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.auth.SentCodeType.sentCodeTypeApp(length: _1!) +public extension Api.account { + enum Password: TypeConstructorDescription { + public class Cons_password { + public var flags: Int32 + public var currentAlgo: Api.PasswordKdfAlgo? + public var srpB: Buffer? + public var srpId: Int64? + public var hint: String? + public var emailUnconfirmedPattern: String? + public var newAlgo: Api.PasswordKdfAlgo + public var newSecureAlgo: Api.SecurePasswordKdfAlgo + public var secureRandom: Buffer + public var pendingResetDate: Int32? + public var loginEmailPattern: String? + public init(flags: Int32, currentAlgo: Api.PasswordKdfAlgo?, srpB: Buffer?, srpId: Int64?, hint: String?, emailUnconfirmedPattern: String?, newAlgo: Api.PasswordKdfAlgo, newSecureAlgo: Api.SecurePasswordKdfAlgo, secureRandom: Buffer, pendingResetDate: Int32?, loginEmailPattern: String?) { + self.flags = flags + self.currentAlgo = currentAlgo + self.srpB = srpB + self.srpId = srpId + self.hint = hint + self.emailUnconfirmedPattern = emailUnconfirmedPattern + self.newAlgo = newAlgo + self.newSecureAlgo = newSecureAlgo + self.secureRandom = secureRandom + self.pendingResetDate = pendingResetDate + self.loginEmailPattern = loginEmailPattern + } } - public static func parse_sentCodeTypeCall(_ reader: BufferReader) -> SentCodeType? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.auth.SentCodeType.sentCodeTypeCall(length: _1!) + case password(Cons_password) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .password(let _data): + if boxed { + buffer.appendInt32(-1787080453) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.currentAlgo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeBytes(_data.srpB!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt64(_data.srpId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.hint!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeString(_data.emailUnconfirmedPattern!, buffer: buffer, boxed: false) + } + _data.newAlgo.serialize(buffer, true) + _data.newSecureAlgo.serialize(buffer, true) + serializeBytes(_data.secureRandom, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeInt32(_data.pendingResetDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + serializeString(_data.loginEmailPattern!, buffer: buffer, boxed: false) + } + break + } } - public static func parse_sentCodeTypeEmailCode(_ reader: BufferReader) -> SentCodeType? { - var _1: Int32? - _1 = reader.readInt32() - var _2: String? - _2 = parseString(reader) - var _3: Int32? - _3 = reader.readInt32() - var _4: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_4 = reader.readInt32() } - var _5: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_5 = reader.readInt32() } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 3) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 4) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.auth.SentCodeType.sentCodeTypeEmailCode(flags: _1!, emailPattern: _2!, length: _3!, resetAvailablePeriod: _4, resetPendingDate: _5) + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .password(let _data): + return ("password", [("flags", _data.flags as Any), ("currentAlgo", _data.currentAlgo as Any), ("srpB", _data.srpB as Any), ("srpId", _data.srpId as Any), ("hint", _data.hint as Any), ("emailUnconfirmedPattern", _data.emailUnconfirmedPattern as Any), ("newAlgo", _data.newAlgo as Any), ("newSecureAlgo", _data.newSecureAlgo as Any), ("secureRandom", _data.secureRandom as Any), ("pendingResetDate", _data.pendingResetDate as Any), ("loginEmailPattern", _data.loginEmailPattern as Any)]) + } } - public static func parse_sentCodeTypeFirebaseSms(_ reader: BufferReader) -> SentCodeType? { + + public static func parse_password(_ reader: BufferReader) -> Password? { var _1: Int32? _1 = reader.readInt32() - var _2: Buffer? - if Int(_1!) & Int(1 << 0) != 0 {_2 = parseBytes(reader) } - var _3: Int64? - if Int(_1!) & Int(1 << 2) != 0 {_3 = reader.readInt64() } - var _4: Buffer? - if Int(_1!) & Int(1 << 2) != 0 {_4 = parseBytes(reader) } + var _2: Api.PasswordKdfAlgo? + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.PasswordKdfAlgo + } + } + var _3: Buffer? + if Int(_1!) & Int(1 << 2) != 0 { + _3 = parseBytes(reader) + } + var _4: Int64? + if Int(_1!) & Int(1 << 2) != 0 { + _4 = reader.readInt64() + } var _5: String? - if Int(_1!) & Int(1 << 1) != 0 {_5 = parseString(reader) } - var _6: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_6 = reader.readInt32() } - var _7: Int32? - _7 = reader.readInt32() + if Int(_1!) & Int(1 << 3) != 0 { + _5 = parseString(reader) + } + var _6: String? + if Int(_1!) & Int(1 << 4) != 0 { + _6 = parseString(reader) + } + var _7: Api.PasswordKdfAlgo? + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.PasswordKdfAlgo + } + var _8: Api.SecurePasswordKdfAlgo? + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.SecurePasswordKdfAlgo + } + var _9: Buffer? + _9 = parseBytes(reader) + var _10: Int32? + if Int(_1!) & Int(1 << 5) != 0 { + _10 = reader.readInt32() + } + var _11: String? + if Int(_1!) & Int(1 << 6) != 0 { + _11 = parseString(reader) + } let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + let _c2 = (Int(_1!) & Int(1 << 2) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 2) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil + let _c5 = (Int(_1!) & Int(1 << 3) == 0) || _5 != nil + let _c6 = (Int(_1!) & Int(1 << 4) == 0) || _6 != nil let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.auth.SentCodeType.sentCodeTypeFirebaseSms(flags: _1!, nonce: _2, playIntegrityProjectId: _3, playIntegrityNonce: _4, receipt: _5, pushTimeout: _6, length: _7!) + let _c8 = _8 != nil + let _c9 = _9 != nil + let _c10 = (Int(_1!) & Int(1 << 5) == 0) || _10 != nil + let _c11 = (Int(_1!) & Int(1 << 6) == 0) || _11 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 { + return Api.account.Password.password(Cons_password(flags: _1!, currentAlgo: _2, srpB: _3, srpId: _4, hint: _5, emailUnconfirmedPattern: _6, newAlgo: _7!, newSecureAlgo: _8!, secureRandom: _9!, pendingResetDate: _10, loginEmailPattern: _11)) + } + else { + return nil + } + } + } +} +public extension Api.account { + enum PasswordInputSettings: TypeConstructorDescription { + public class Cons_passwordInputSettings { + public var flags: Int32 + public var newAlgo: Api.PasswordKdfAlgo? + public var newPasswordHash: Buffer? + public var hint: String? + public var email: String? + public var newSecureSettings: Api.SecureSecretSettings? + public init(flags: Int32, newAlgo: Api.PasswordKdfAlgo?, newPasswordHash: Buffer?, hint: String?, email: String?, newSecureSettings: Api.SecureSecretSettings?) { + self.flags = flags + self.newAlgo = newAlgo + self.newPasswordHash = newPasswordHash + self.hint = hint + self.email = email + self.newSecureSettings = newSecureSettings + } + } + case passwordInputSettings(Cons_passwordInputSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .passwordInputSettings(let _data): + if boxed { + buffer.appendInt32(-1036572727) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.newAlgo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeBytes(_data.newPasswordHash!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.hint!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.email!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.newSecureSettings!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .passwordInputSettings(let _data): + return ("passwordInputSettings", [("flags", _data.flags as Any), ("newAlgo", _data.newAlgo as Any), ("newPasswordHash", _data.newPasswordHash as Any), ("hint", _data.hint as Any), ("email", _data.email as Any), ("newSecureSettings", _data.newSecureSettings as Any)]) + } + } + + public static func parse_passwordInputSettings(_ reader: BufferReader) -> PasswordInputSettings? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.PasswordKdfAlgo? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.PasswordKdfAlgo + } + } + var _3: Buffer? + if Int(_1!) & Int(1 << 0) != 0 { + _3 = parseBytes(reader) + } + var _4: String? + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) + } + var _5: String? + if Int(_1!) & Int(1 << 1) != 0 { + _5 = parseString(reader) + } + var _6: Api.SecureSecretSettings? + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.SecureSecretSettings + } + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil + let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil + let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.account.PasswordInputSettings.passwordInputSettings(Cons_passwordInputSettings(flags: _1!, newAlgo: _2, newPasswordHash: _3, hint: _4, email: _5, newSecureSettings: _6)) + } + else { + return nil + } + } + } +} +public extension Api.account { + enum PasswordSettings: TypeConstructorDescription { + public class Cons_passwordSettings { + public var flags: Int32 + public var email: String? + public var secureSettings: Api.SecureSecretSettings? + public init(flags: Int32, email: String?, secureSettings: Api.SecureSecretSettings?) { + self.flags = flags + self.email = email + self.secureSettings = secureSettings + } + } + case passwordSettings(Cons_passwordSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .passwordSettings(let _data): + if boxed { + buffer.appendInt32(-1705233435) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.email!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.secureSettings!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .passwordSettings(let _data): + return ("passwordSettings", [("flags", _data.flags as Any), ("email", _data.email as Any), ("secureSettings", _data.secureSettings as Any)]) + } + } + + public static func parse_passwordSettings(_ reader: BufferReader) -> PasswordSettings? { + var _1: Int32? + _1 = reader.readInt32() + var _2: String? + if Int(_1!) & Int(1 << 0) != 0 { + _2 = parseString(reader) + } + var _3: Api.SecureSecretSettings? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.SecureSecretSettings + } + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil + if _c1 && _c2 && _c3 { + return Api.account.PasswordSettings.passwordSettings(Cons_passwordSettings(flags: _1!, email: _2, secureSettings: _3)) + } + else { + return nil + } + } + } +} +public extension Api.account { + enum PrivacyRules: TypeConstructorDescription { + public class Cons_privacyRules { + public var rules: [Api.PrivacyRule] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(rules: [Api.PrivacyRule], chats: [Api.Chat], users: [Api.User]) { + self.rules = rules + self.chats = chats + self.users = users + } + } + case privacyRules(Cons_privacyRules) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .privacyRules(let _data): + if boxed { + buffer.appendInt32(1352683077) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.rules.count)) + for item in _data.rules { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .privacyRules(let _data): + return ("privacyRules", [("rules", _data.rules as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_privacyRules(_ reader: BufferReader) -> PrivacyRules? { + var _1: [Api.PrivacyRule]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PrivacyRule.self) + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.account.PrivacyRules.privacyRules(Cons_privacyRules(rules: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.account { + enum ResetPasswordResult: TypeConstructorDescription { + public class Cons_resetPasswordFailedWait { + public var retryDate: Int32 + public init(retryDate: Int32) { + self.retryDate = retryDate + } + } + public class Cons_resetPasswordRequestedWait { + public var untilDate: Int32 + public init(untilDate: Int32) { + self.untilDate = untilDate + } + } + case resetPasswordFailedWait(Cons_resetPasswordFailedWait) + case resetPasswordOk + case resetPasswordRequestedWait(Cons_resetPasswordRequestedWait) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .resetPasswordFailedWait(let _data): + if boxed { + buffer.appendInt32(-478701471) + } + serializeInt32(_data.retryDate, buffer: buffer, boxed: false) + break + case .resetPasswordOk: + if boxed { + buffer.appendInt32(-383330754) + } + break + case .resetPasswordRequestedWait(let _data): + if boxed { + buffer.appendInt32(-370148227) + } + serializeInt32(_data.untilDate, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .resetPasswordFailedWait(let _data): + return ("resetPasswordFailedWait", [("retryDate", _data.retryDate as Any)]) + case .resetPasswordOk: + return ("resetPasswordOk", []) + case .resetPasswordRequestedWait(let _data): + return ("resetPasswordRequestedWait", [("untilDate", _data.untilDate as Any)]) + } + } + + public static func parse_resetPasswordFailedWait(_ reader: BufferReader) -> ResetPasswordResult? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.account.ResetPasswordResult.resetPasswordFailedWait(Cons_resetPasswordFailedWait(retryDate: _1!)) + } + else { + return nil + } + } + public static func parse_resetPasswordOk(_ reader: BufferReader) -> ResetPasswordResult? { + return Api.account.ResetPasswordResult.resetPasswordOk + } + public static func parse_resetPasswordRequestedWait(_ reader: BufferReader) -> ResetPasswordResult? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.account.ResetPasswordResult.resetPasswordRequestedWait(Cons_resetPasswordRequestedWait(untilDate: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.account { + enum ResolvedBusinessChatLinks: TypeConstructorDescription { + public class Cons_resolvedBusinessChatLinks { + public var flags: Int32 + public var peer: Api.Peer + public var message: String + public var entities: [Api.MessageEntity]? + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, peer: Api.Peer, message: String, entities: [Api.MessageEntity]?, chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.peer = peer + self.message = message + self.entities = entities + self.chats = chats + self.users = users + } + } + case resolvedBusinessChatLinks(Cons_resolvedBusinessChatLinks) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .resolvedBusinessChatLinks(let _data): + if boxed { + buffer.appendInt32(-1708937439) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeString(_data.message, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { + item.serialize(buffer, true) + } + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .resolvedBusinessChatLinks(let _data): + return ("resolvedBusinessChatLinks", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("message", _data.message as Any), ("entities", _data.entities as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_resolvedBusinessChatLinks(_ reader: BufferReader) -> ResolvedBusinessChatLinks? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.Peer? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _3: String? + _3 = parseString(reader) + var _4: [Api.MessageEntity]? + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } + var _5: [Api.Chat]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _6: [Api.User]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.account.ResolvedBusinessChatLinks.resolvedBusinessChatLinks(Cons_resolvedBusinessChatLinks(flags: _1!, peer: _2!, message: _3!, entities: _4, chats: _5!, users: _6!)) + } + else { + return nil + } } - public static func parse_sentCodeTypeFlashCall(_ reader: BufferReader) -> SentCodeType? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.auth.SentCodeType.sentCodeTypeFlashCall(pattern: _1!) - } - public static func parse_sentCodeTypeFragmentSms(_ reader: BufferReader) -> SentCodeType? { - var _1: String? - _1 = parseString(reader) - var _2: Int32? - _2 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.auth.SentCodeType.sentCodeTypeFragmentSms(url: _1!, length: _2!) - } - public static func parse_sentCodeTypeMissedCall(_ reader: BufferReader) -> SentCodeType? { - var _1: String? - _1 = parseString(reader) - var _2: Int32? - _2 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.auth.SentCodeType.sentCodeTypeMissedCall(prefix: _1!, length: _2!) - } - public static func parse_sentCodeTypeSetUpEmailRequired(_ reader: BufferReader) -> SentCodeType? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.auth.SentCodeType.sentCodeTypeSetUpEmailRequired(flags: _1!) - } - public static func parse_sentCodeTypeSms(_ reader: BufferReader) -> SentCodeType? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.auth.SentCodeType.sentCodeTypeSms(length: _1!) - } - public static func parse_sentCodeTypeSmsPhrase(_ reader: BufferReader) -> SentCodeType? { - var _1: Int32? - _1 = reader.readInt32() - var _2: String? - if Int(_1!) & Int(1 << 0) != 0 {_2 = parseString(reader) } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.auth.SentCodeType.sentCodeTypeSmsPhrase(flags: _1!, beginning: _2) - } - public static func parse_sentCodeTypeSmsWord(_ reader: BufferReader) -> SentCodeType? { - var _1: Int32? - _1 = reader.readInt32() - var _2: String? - if Int(_1!) & Int(1 << 0) != 0 {_2 = parseString(reader) } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.auth.SentCodeType.sentCodeTypeSmsWord(flags: _1!, beginning: _2) - } - } } diff --git a/submodules/TelegramApi/Sources/Api31.swift b/submodules/TelegramApi/Sources/Api31.swift index d713950b..76a151e4 100644 --- a/submodules/TelegramApi/Sources/Api31.swift +++ b/submodules/TelegramApi/Sources/Api31.swift @@ -1,904 +1,485 @@ -public extension Api.bots { - enum BotInfo: TypeConstructorDescription { - case botInfo(name: String, about: String, description: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botInfo(let name, let about, let description): - if boxed { - buffer.appendInt32(-391678544) - } - serializeString(name, buffer: buffer, boxed: false) - serializeString(about, buffer: buffer, boxed: false) - serializeString(description, buffer: buffer, boxed: false) - break +public extension Api.account { + enum SavedMusicIds: TypeConstructorDescription { + public class Cons_savedMusicIds { + public var ids: [Int64] + public init(ids: [Int64]) { + self.ids = ids + } + } + case savedMusicIds(Cons_savedMusicIds) + case savedMusicIdsNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .savedMusicIds(let _data): + if boxed { + buffer.appendInt32(-1718786506) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.ids.count)) + for item in _data.ids { + serializeInt64(item, buffer: buffer, boxed: false) + } + break + case .savedMusicIdsNotModified: + if boxed { + buffer.appendInt32(1338514798) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .savedMusicIds(let _data): + return ("savedMusicIds", [("ids", _data.ids as Any)]) + case .savedMusicIdsNotModified: + return ("savedMusicIdsNotModified", []) + } + } + + public static func parse_savedMusicIds(_ reader: BufferReader) -> SavedMusicIds? { + var _1: [Int64]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) + } + let _c1 = _1 != nil + if _c1 { + return Api.account.SavedMusicIds.savedMusicIds(Cons_savedMusicIds(ids: _1!)) + } + else { + return nil + } + } + public static func parse_savedMusicIdsNotModified(_ reader: BufferReader) -> SavedMusicIds? { + return Api.account.SavedMusicIds.savedMusicIdsNotModified + } } +} +public extension Api.account { + enum SavedRingtone: TypeConstructorDescription { + public class Cons_savedRingtoneConverted { + public var document: Api.Document + public init(document: Api.Document) { + self.document = document + } + } + case savedRingtone + case savedRingtoneConverted(Cons_savedRingtoneConverted) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .savedRingtone: + if boxed { + buffer.appendInt32(-1222230163) + } + break + case .savedRingtoneConverted(let _data): + if boxed { + buffer.appendInt32(523271863) + } + _data.document.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .savedRingtone: + return ("savedRingtone", []) + case .savedRingtoneConverted(let _data): + return ("savedRingtoneConverted", [("document", _data.document as Any)]) + } + } + + public static func parse_savedRingtone(_ reader: BufferReader) -> SavedRingtone? { + return Api.account.SavedRingtone.savedRingtone + } + public static func parse_savedRingtoneConverted(_ reader: BufferReader) -> SavedRingtone? { + var _1: Api.Document? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Document + } + let _c1 = _1 != nil + if _c1 { + return Api.account.SavedRingtone.savedRingtoneConverted(Cons_savedRingtoneConverted(document: _1!)) + } + else { + return nil + } + } } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botInfo(let name, let about, let description): - return ("botInfo", [("name", name as Any), ("about", about as Any), ("description", description as Any)]) +} +public extension Api.account { + enum SavedRingtones: TypeConstructorDescription { + public class Cons_savedRingtones { + public var hash: Int64 + public var ringtones: [Api.Document] + public init(hash: Int64, ringtones: [Api.Document]) { + self.hash = hash + self.ringtones = ringtones + } + } + case savedRingtones(Cons_savedRingtones) + case savedRingtonesNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .savedRingtones(let _data): + if boxed { + buffer.appendInt32(-1041683259) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.ringtones.count)) + for item in _data.ringtones { + item.serialize(buffer, true) + } + break + case .savedRingtonesNotModified: + if boxed { + buffer.appendInt32(-67704655) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .savedRingtones(let _data): + return ("savedRingtones", [("hash", _data.hash as Any), ("ringtones", _data.ringtones as Any)]) + case .savedRingtonesNotModified: + return ("savedRingtonesNotModified", []) + } + } + + public static func parse_savedRingtones(_ reader: BufferReader) -> SavedRingtones? { + var _1: Int64? + _1 = reader.readInt64() + var _2: [Api.Document]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.account.SavedRingtones.savedRingtones(Cons_savedRingtones(hash: _1!, ringtones: _2!)) + } + else { + return nil + } + } + public static func parse_savedRingtonesNotModified(_ reader: BufferReader) -> SavedRingtones? { + return Api.account.SavedRingtones.savedRingtonesNotModified + } } - } - - public static func parse_botInfo(_ reader: BufferReader) -> BotInfo? { +} +public extension Api.account { + enum SentEmailCode: TypeConstructorDescription { + public class Cons_sentEmailCode { + public var emailPattern: String + public var length: Int32 + public init(emailPattern: String, length: Int32) { + self.emailPattern = emailPattern + self.length = length + } + } + case sentEmailCode(Cons_sentEmailCode) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .sentEmailCode(let _data): + if boxed { + buffer.appendInt32(-2128640689) + } + serializeString(_data.emailPattern, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .sentEmailCode(let _data): + return ("sentEmailCode", [("emailPattern", _data.emailPattern as Any), ("length", _data.length as Any)]) + } + } + + public static func parse_sentEmailCode(_ reader: BufferReader) -> SentEmailCode? { var _1: String? _1 = parseString(reader) - var _2: String? - _2 = parseString(reader) - var _3: String? - _3 = parseString(reader) + var _2: Int32? + _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.bots.BotInfo.botInfo(name: _1!, about: _2!, description: _3!) + if _c1 && _c2 { + return Api.account.SentEmailCode.sentEmailCode(Cons_sentEmailCode(emailPattern: _1!, length: _2!)) + } + else { + return nil + } } - } } -public extension Api.bots { - enum PopularAppBots: TypeConstructorDescription { - case popularAppBots(flags: Int32, nextOffset: String?, users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .popularAppBots(let flags, let nextOffset, let users): - if boxed { - buffer.appendInt32(428978491) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(nextOffset!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .popularAppBots(let flags, let nextOffset, let users): - return ("popularAppBots", [("flags", flags as Any), ("nextOffset", nextOffset as Any), ("users", users as Any)]) - } - } - - public static func parse_popularAppBots(_ reader: BufferReader) -> PopularAppBots? { - var _1: Int32? - _1 = reader.readInt32() - var _2: String? - if Int(_1!) & Int(1 << 0) != 0 {_2 = parseString(reader) } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) +public extension Api.account { + enum Takeout: TypeConstructorDescription { + public class Cons_takeout { + public var id: Int64 + public init(id: Int64) { + self.id = id + } + } + case takeout(Cons_takeout) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .takeout(let _data): + if boxed { + buffer.appendInt32(1304052993) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .takeout(let _data): + return ("takeout", [("id", _data.id as Any)]) + } + } + + public static func parse_takeout(_ reader: BufferReader) -> Takeout? { + var _1: Int64? + _1 = reader.readInt64() + let _c1 = _1 != nil + if _c1 { + return Api.account.Takeout.takeout(Cons_takeout(id: _1!)) + } + else { + return nil } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.bots.PopularAppBots.popularAppBots(flags: _1!, nextOffset: _2, users: _3!) } - } } -public extension Api.bots { - enum PreviewInfo: TypeConstructorDescription { - case previewInfo(media: [Api.BotPreviewMedia], langCodes: [String]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .previewInfo(let media, let langCodes): - if boxed { - buffer.appendInt32(212278628) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(media.count)) - for item in media { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(langCodes.count)) - for item in langCodes { - serializeString(item, buffer: buffer, boxed: false) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .previewInfo(let media, let langCodes): - return ("previewInfo", [("media", media as Any), ("langCodes", langCodes as Any)]) - } - } - - public static func parse_previewInfo(_ reader: BufferReader) -> PreviewInfo? { - var _1: [Api.BotPreviewMedia]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.BotPreviewMedia.self) +public extension Api.account { + enum Themes: TypeConstructorDescription { + public class Cons_themes { + public var hash: Int64 + public var themes: [Api.Theme] + public init(hash: Int64, themes: [Api.Theme]) { + self.hash = hash + self.themes = themes } - var _2: [String]? + } + case themes(Cons_themes) + case themesNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .themes(let _data): + if boxed { + buffer.appendInt32(-1707242387) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.themes.count)) + for item in _data.themes { + item.serialize(buffer, true) + } + break + case .themesNotModified: + if boxed { + buffer.appendInt32(-199313886) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .themes(let _data): + return ("themes", [("hash", _data.hash as Any), ("themes", _data.themes as Any)]) + case .themesNotModified: + return ("themesNotModified", []) + } + } + + public static func parse_themes(_ reader: BufferReader) -> Themes? { + var _1: Int64? + _1 = reader.readInt64() + var _2: [Api.Theme]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Theme.self) } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.bots.PreviewInfo.previewInfo(media: _1!, langCodes: _2!) + if _c1 && _c2 { + return Api.account.Themes.themes(Cons_themes(hash: _1!, themes: _2!)) + } + else { + return nil + } + } + public static func parse_themesNotModified(_ reader: BufferReader) -> Themes? { + return Api.account.Themes.themesNotModified } - } } -public extension Api.channels { - enum AdminLogResults: TypeConstructorDescription { - case adminLogResults(events: [Api.ChannelAdminLogEvent], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .adminLogResults(let events, let chats, let users): - if boxed { - buffer.appendInt32(-309659827) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(events.count)) - for item in events { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .adminLogResults(let events, let chats, let users): - return ("adminLogResults", [("events", events as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_adminLogResults(_ reader: BufferReader) -> AdminLogResults? { - var _1: [Api.ChannelAdminLogEvent]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ChannelAdminLogEvent.self) +public extension Api.account { + enum TmpPassword: TypeConstructorDescription { + public class Cons_tmpPassword { + public var tmpPassword: Buffer + public var validUntil: Int32 + public init(tmpPassword: Buffer, validUntil: Int32) { + self.tmpPassword = tmpPassword + self.validUntil = validUntil } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + case tmpPassword(Cons_tmpPassword) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .tmpPassword(let _data): + if boxed { + buffer.appendInt32(-614138572) + } + serializeBytes(_data.tmpPassword, buffer: buffer, boxed: false) + serializeInt32(_data.validUntil, buffer: buffer, boxed: false) + break } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .tmpPassword(let _data): + return ("tmpPassword", [("tmpPassword", _data.tmpPassword as Any), ("validUntil", _data.validUntil as Any)]) } + } + + public static func parse_tmpPassword(_ reader: BufferReader) -> TmpPassword? { + var _1: Buffer? + _1 = parseBytes(reader) + var _2: Int32? + _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.channels.AdminLogResults.adminLogResults(events: _1!, chats: _2!, users: _3!) + if _c1 && _c2 { + return Api.account.TmpPassword.tmpPassword(Cons_tmpPassword(tmpPassword: _1!, validUntil: _2!)) + } + else { + return nil + } } - } } -public extension Api.channels { - enum ChannelParticipant: TypeConstructorDescription { - case channelParticipant(participant: Api.ChannelParticipant, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .channelParticipant(let participant, let chats, let users): - if boxed { - buffer.appendInt32(-541588713) - } - participant.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .channelParticipant(let participant, let chats, let users): - return ("channelParticipant", [("participant", participant as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_channelParticipant(_ reader: BufferReader) -> ChannelParticipant? { - var _1: Api.ChannelParticipant? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.ChannelParticipant +public extension Api.account { + enum WallPapers: TypeConstructorDescription { + public class Cons_wallPapers { + public var hash: Int64 + public var wallpapers: [Api.WallPaper] + public init(hash: Int64, wallpapers: [Api.WallPaper]) { + self.hash = hash + self.wallpapers = wallpapers } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + case wallPapers(Cons_wallPapers) + case wallPapersNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .wallPapers(let _data): + if boxed { + buffer.appendInt32(-842824308) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.wallpapers.count)) + for item in _data.wallpapers { + item.serialize(buffer, true) + } + break + case .wallPapersNotModified: + if boxed { + buffer.appendInt32(471437699) + } + break } - var _3: [Api.User]? + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .wallPapers(let _data): + return ("wallPapers", [("hash", _data.hash as Any), ("wallpapers", _data.wallpapers as Any)]) + case .wallPapersNotModified: + return ("wallPapersNotModified", []) + } + } + + public static func parse_wallPapers(_ reader: BufferReader) -> WallPapers? { + var _1: Int64? + _1 = reader.readInt64() + var _2: [Api.WallPaper]? if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.WallPaper.self) } let _c1 = _1 != nil let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.channels.ChannelParticipant.channelParticipant(participant: _1!, chats: _2!, users: _3!) + if _c1 && _c2 { + return Api.account.WallPapers.wallPapers(Cons_wallPapers(hash: _1!, wallpapers: _2!)) + } + else { + return nil + } + } + public static func parse_wallPapersNotModified(_ reader: BufferReader) -> WallPapers? { + return Api.account.WallPapers.wallPapersNotModified } - } } -public extension Api.channels { - enum ChannelParticipants: TypeConstructorDescription { - case channelParticipants(count: Int32, participants: [Api.ChannelParticipant], chats: [Api.Chat], users: [Api.User]) - case channelParticipantsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .channelParticipants(let count, let participants, let chats, let users): - if boxed { - buffer.appendInt32(-1699676497) - } - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(participants.count)) - for item in participants { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .channelParticipantsNotModified: - if boxed { - buffer.appendInt32(-266911767) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .channelParticipants(let count, let participants, let chats, let users): - return ("channelParticipants", [("count", count as Any), ("participants", participants as Any), ("chats", chats as Any), ("users", users as Any)]) - case .channelParticipantsNotModified: - return ("channelParticipantsNotModified", []) - } - } - - public static func parse_channelParticipants(_ reader: BufferReader) -> ChannelParticipants? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.ChannelParticipant]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ChannelParticipant.self) +public extension Api.account { + enum WebAuthorizations: TypeConstructorDescription { + public class Cons_webAuthorizations { + public var authorizations: [Api.WebAuthorization] + public var users: [Api.User] + public init(authorizations: [Api.WebAuthorization], users: [Api.User]) { + self.authorizations = authorizations + self.users = users } - var _3: [Api.Chat]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _4: [Api.User]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.channels.ChannelParticipants.channelParticipants(count: _1!, participants: _2!, chats: _3!, users: _4!) } - public static func parse_channelParticipantsNotModified(_ reader: BufferReader) -> ChannelParticipants? { - return Api.channels.ChannelParticipants.channelParticipantsNotModified + case webAuthorizations(Cons_webAuthorizations) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .webAuthorizations(let _data): + if boxed { + buffer.appendInt32(-313079300) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.authorizations.count)) + for item in _data.authorizations { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } } - - } -} -public extension Api.channels { - enum SendAsPeers: TypeConstructorDescription { - case sendAsPeers(peers: [Api.SendAsPeer], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .sendAsPeers(let peers, let chats, let users): - if boxed { - buffer.appendInt32(-191450938) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peers.count)) - for item in peers { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .sendAsPeers(let peers, let chats, let users): - return ("sendAsPeers", [("peers", peers as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_sendAsPeers(_ reader: BufferReader) -> SendAsPeers? { - var _1: [Api.SendAsPeer]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SendAsPeer.self) + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .webAuthorizations(let _data): + return ("webAuthorizations", [("authorizations", _data.authorizations as Any), ("users", _data.users as Any)]) } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.channels.SendAsPeers.sendAsPeers(peers: _1!, chats: _2!, users: _3!) } - - } -} -public extension Api.channels { - enum SponsoredMessageReportResult: TypeConstructorDescription { - case sponsoredMessageReportResultAdsHidden - case sponsoredMessageReportResultChooseOption(title: String, options: [Api.SponsoredMessageReportOption]) - case sponsoredMessageReportResultReported - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .sponsoredMessageReportResultAdsHidden: - if boxed { - buffer.appendInt32(1044107055) - } - - break - case .sponsoredMessageReportResultChooseOption(let title, let options): - if boxed { - buffer.appendInt32(-2073059774) - } - serializeString(title, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(options.count)) - for item in options { - item.serialize(buffer, true) - } - break - case .sponsoredMessageReportResultReported: - if boxed { - buffer.appendInt32(-1384544183) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .sponsoredMessageReportResultAdsHidden: - return ("sponsoredMessageReportResultAdsHidden", []) - case .sponsoredMessageReportResultChooseOption(let title, let options): - return ("sponsoredMessageReportResultChooseOption", [("title", title as Any), ("options", options as Any)]) - case .sponsoredMessageReportResultReported: - return ("sponsoredMessageReportResultReported", []) - } - } - - public static func parse_sponsoredMessageReportResultAdsHidden(_ reader: BufferReader) -> SponsoredMessageReportResult? { - return Api.channels.SponsoredMessageReportResult.sponsoredMessageReportResultAdsHidden - } - public static func parse_sponsoredMessageReportResultChooseOption(_ reader: BufferReader) -> SponsoredMessageReportResult? { - var _1: String? - _1 = parseString(reader) - var _2: [Api.SponsoredMessageReportOption]? + + public static func parse_webAuthorizations(_ reader: BufferReader) -> WebAuthorizations? { + var _1: [Api.WebAuthorization]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SponsoredMessageReportOption.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.channels.SponsoredMessageReportResult.sponsoredMessageReportResultChooseOption(title: _1!, options: _2!) - } - public static func parse_sponsoredMessageReportResultReported(_ reader: BufferReader) -> SponsoredMessageReportResult? { - return Api.channels.SponsoredMessageReportResult.sponsoredMessageReportResultReported - } - - } -} -public extension Api.chatlists { - enum ChatlistInvite: TypeConstructorDescription { - case chatlistInvite(flags: Int32, title: Api.TextWithEntities, emoticon: String?, peers: [Api.Peer], chats: [Api.Chat], users: [Api.User]) - case chatlistInviteAlready(filterId: Int32, missingPeers: [Api.Peer], alreadyPeers: [Api.Peer], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatlistInvite(let flags, let title, let emoticon, let peers, let chats, let users): - if boxed { - buffer.appendInt32(-250687953) - } - serializeInt32(flags, buffer: buffer, boxed: false) - title.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeString(emoticon!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peers.count)) - for item in peers { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .chatlistInviteAlready(let filterId, let missingPeers, let alreadyPeers, let chats, let users): - if boxed { - buffer.appendInt32(-91752871) - } - serializeInt32(filterId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(missingPeers.count)) - for item in missingPeers { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(alreadyPeers.count)) - for item in alreadyPeers { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatlistInvite(let flags, let title, let emoticon, let peers, let chats, let users): - return ("chatlistInvite", [("flags", flags as Any), ("title", title as Any), ("emoticon", emoticon as Any), ("peers", peers as Any), ("chats", chats as Any), ("users", users as Any)]) - case .chatlistInviteAlready(let filterId, let missingPeers, let alreadyPeers, let chats, let users): - return ("chatlistInviteAlready", [("filterId", filterId as Any), ("missingPeers", missingPeers as Any), ("alreadyPeers", alreadyPeers as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_chatlistInvite(_ reader: BufferReader) -> ChatlistInvite? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.TextWithEntities? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.TextWithEntities - } - var _3: String? - if Int(_1!) & Int(1 << 0) != 0 {_3 = parseString(reader) } - var _4: [Api.Peer]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) - } - var _5: [Api.Chat]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _6: [Api.User]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.chatlists.ChatlistInvite.chatlistInvite(flags: _1!, title: _2!, emoticon: _3, peers: _4!, chats: _5!, users: _6!) - } - public static func parse_chatlistInviteAlready(_ reader: BufferReader) -> ChatlistInvite? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.Peer]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) - } - var _3: [Api.Peer]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) - } - var _4: [Api.Chat]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _5: [Api.User]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.chatlists.ChatlistInvite.chatlistInviteAlready(filterId: _1!, missingPeers: _2!, alreadyPeers: _3!, chats: _4!, users: _5!) - } - - } -} -public extension Api.chatlists { - enum ChatlistUpdates: TypeConstructorDescription { - case chatlistUpdates(missingPeers: [Api.Peer], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatlistUpdates(let missingPeers, let chats, let users): - if boxed { - buffer.appendInt32(-1816295539) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(missingPeers.count)) - for item in missingPeers { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatlistUpdates(let missingPeers, let chats, let users): - return ("chatlistUpdates", [("missingPeers", missingPeers as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_chatlistUpdates(_ reader: BufferReader) -> ChatlistUpdates? { - var _1: [Api.Peer]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) - } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.chatlists.ChatlistUpdates.chatlistUpdates(missingPeers: _1!, chats: _2!, users: _3!) - } - - } -} -public extension Api.chatlists { - enum ExportedChatlistInvite: TypeConstructorDescription { - case exportedChatlistInvite(filter: Api.DialogFilter, invite: Api.ExportedChatlistInvite) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .exportedChatlistInvite(let filter, let invite): - if boxed { - buffer.appendInt32(283567014) - } - filter.serialize(buffer, true) - invite.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .exportedChatlistInvite(let filter, let invite): - return ("exportedChatlistInvite", [("filter", filter as Any), ("invite", invite as Any)]) - } - } - - public static func parse_exportedChatlistInvite(_ reader: BufferReader) -> ExportedChatlistInvite? { - var _1: Api.DialogFilter? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.DialogFilter - } - var _2: Api.ExportedChatlistInvite? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.ExportedChatlistInvite - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.chatlists.ExportedChatlistInvite.exportedChatlistInvite(filter: _1!, invite: _2!) - } - - } -} -public extension Api.chatlists { - enum ExportedInvites: TypeConstructorDescription { - case exportedInvites(invites: [Api.ExportedChatlistInvite], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .exportedInvites(let invites, let chats, let users): - if boxed { - buffer.appendInt32(279670215) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(invites.count)) - for item in invites { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .exportedInvites(let invites, let chats, let users): - return ("exportedInvites", [("invites", invites as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_exportedInvites(_ reader: BufferReader) -> ExportedInvites? { - var _1: [Api.ExportedChatlistInvite]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ExportedChatlistInvite.self) - } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.chatlists.ExportedInvites.exportedInvites(invites: _1!, chats: _2!, users: _3!) - } - - } -} -public extension Api.contacts { - enum Blocked: TypeConstructorDescription { - case blocked(blocked: [Api.PeerBlocked], chats: [Api.Chat], users: [Api.User]) - case blockedSlice(count: Int32, blocked: [Api.PeerBlocked], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .blocked(let blocked, let chats, let users): - if boxed { - buffer.appendInt32(182326673) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(blocked.count)) - for item in blocked { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .blockedSlice(let count, let blocked, let chats, let users): - if boxed { - buffer.appendInt32(-513392236) - } - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(blocked.count)) - for item in blocked { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .blocked(let blocked, let chats, let users): - return ("blocked", [("blocked", blocked as Any), ("chats", chats as Any), ("users", users as Any)]) - case .blockedSlice(let count, let blocked, let chats, let users): - return ("blockedSlice", [("count", count as Any), ("blocked", blocked as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_blocked(_ reader: BufferReader) -> Blocked? { - var _1: [Api.PeerBlocked]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PeerBlocked.self) - } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.contacts.Blocked.blocked(blocked: _1!, chats: _2!, users: _3!) - } - public static func parse_blockedSlice(_ reader: BufferReader) -> Blocked? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.PeerBlocked]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PeerBlocked.self) - } - var _3: [Api.Chat]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _4: [Api.User]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.contacts.Blocked.blockedSlice(count: _1!, blocked: _2!, chats: _3!, users: _4!) - } - - } -} -public extension Api.contacts { - enum ContactBirthdays: TypeConstructorDescription { - case contactBirthdays(contacts: [Api.ContactBirthday], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .contactBirthdays(let contacts, let users): - if boxed { - buffer.appendInt32(290452237) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(contacts.count)) - for item in contacts { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .contactBirthdays(let contacts, let users): - return ("contactBirthdays", [("contacts", contacts as Any), ("users", users as Any)]) - } - } - - public static func parse_contactBirthdays(_ reader: BufferReader) -> ContactBirthdays? { - var _1: [Api.ContactBirthday]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ContactBirthday.self) + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.WebAuthorization.self) } var _2: [Api.User]? if let _ = reader.readInt32() { @@ -906,538 +487,1070 @@ public extension Api.contacts { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.contacts.ContactBirthdays.contactBirthdays(contacts: _1!, users: _2!) + if _c1 && _c2 { + return Api.account.WebAuthorizations.webAuthorizations(Cons_webAuthorizations(authorizations: _1!, users: _2!)) + } + else { + return nil + } } - } } -public extension Api.contacts { - enum Contacts: TypeConstructorDescription { - case contacts(contacts: [Api.Contact], savedCount: Int32, users: [Api.User]) - case contactsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .contacts(let contacts, let savedCount, let users): - if boxed { - buffer.appendInt32(-353862078) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(contacts.count)) - for item in contacts { - item.serialize(buffer, true) - } - serializeInt32(savedCount, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .contactsNotModified: - if boxed { - buffer.appendInt32(-1219778094) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .contacts(let contacts, let savedCount, let users): - return ("contacts", [("contacts", contacts as Any), ("savedCount", savedCount as Any), ("users", users as Any)]) - case .contactsNotModified: - return ("contactsNotModified", []) - } - } - - public static func parse_contacts(_ reader: BufferReader) -> Contacts? { - var _1: [Api.Contact]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Contact.self) +public extension Api.auth { + enum Authorization: TypeConstructorDescription { + public class Cons_authorization { + public var flags: Int32 + public var otherwiseReloginDays: Int32? + public var tmpSessions: Int32? + public var futureAuthToken: Buffer? + public var user: Api.User + public init(flags: Int32, otherwiseReloginDays: Int32?, tmpSessions: Int32?, futureAuthToken: Buffer?, user: Api.User) { + self.flags = flags + self.otherwiseReloginDays = otherwiseReloginDays + self.tmpSessions = tmpSessions + self.futureAuthToken = futureAuthToken + self.user = user } - var _2: Int32? - _2 = reader.readInt32() - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.contacts.Contacts.contacts(contacts: _1!, savedCount: _2!, users: _3!) } - public static func parse_contactsNotModified(_ reader: BufferReader) -> Contacts? { - return Api.contacts.Contacts.contactsNotModified + public class Cons_authorizationSignUpRequired { + public var flags: Int32 + public var termsOfService: Api.help.TermsOfService? + public init(flags: Int32, termsOfService: Api.help.TermsOfService?) { + self.flags = flags + self.termsOfService = termsOfService + } } - - } -} -public extension Api.contacts { - enum Found: TypeConstructorDescription { - case found(myResults: [Api.Peer], results: [Api.Peer], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .found(let myResults, let results, let chats, let users): - if boxed { - buffer.appendInt32(-1290580579) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(myResults.count)) - for item in myResults { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(results.count)) - for item in results { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .found(let myResults, let results, let chats, let users): - return ("found", [("myResults", myResults as Any), ("results", results as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_found(_ reader: BufferReader) -> Found? { - var _1: [Api.Peer]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) + case authorization(Cons_authorization) + case authorizationSignUpRequired(Cons_authorizationSignUpRequired) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .authorization(let _data): + if boxed { + buffer.appendInt32(782418132) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.otherwiseReloginDays!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.tmpSessions!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeBytes(_data.futureAuthToken!, buffer: buffer, boxed: false) + } + _data.user.serialize(buffer, true) + break + case .authorizationSignUpRequired(let _data): + if boxed { + buffer.appendInt32(1148485274) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.termsOfService!.serialize(buffer, true) + } + break } - var _2: [Api.Peer]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) - } - var _3: [Api.Chat]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _4: [Api.User]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.contacts.Found.found(myResults: _1!, results: _2!, chats: _3!, users: _4!) } - - } -} -public extension Api.contacts { - enum ImportedContacts: TypeConstructorDescription { - case importedContacts(imported: [Api.ImportedContact], popularInvites: [Api.PopularContact], retryContacts: [Int64], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .importedContacts(let imported, let popularInvites, let retryContacts, let users): - if boxed { - buffer.appendInt32(2010127419) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(imported.count)) - for item in imported { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(popularInvites.count)) - for item in popularInvites { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(retryContacts.count)) - for item in retryContacts { - serializeInt64(item, buffer: buffer, boxed: false) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .importedContacts(let imported, let popularInvites, let retryContacts, let users): - return ("importedContacts", [("imported", imported as Any), ("popularInvites", popularInvites as Any), ("retryContacts", retryContacts as Any), ("users", users as Any)]) - } - } - - public static func parse_importedContacts(_ reader: BufferReader) -> ImportedContacts? { - var _1: [Api.ImportedContact]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ImportedContact.self) + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .authorization(let _data): + return ("authorization", [("flags", _data.flags as Any), ("otherwiseReloginDays", _data.otherwiseReloginDays as Any), ("tmpSessions", _data.tmpSessions as Any), ("futureAuthToken", _data.futureAuthToken as Any), ("user", _data.user as Any)]) + case .authorizationSignUpRequired(let _data): + return ("authorizationSignUpRequired", [("flags", _data.flags as Any), ("termsOfService", _data.termsOfService as Any)]) } - var _2: [Api.PopularContact]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PopularContact.self) - } - var _3: [Int64]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) - } - var _4: [Api.User]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.contacts.ImportedContacts.importedContacts(imported: _1!, popularInvites: _2!, retryContacts: _3!, users: _4!) } - - } -} -public extension Api.contacts { - enum ResolvedPeer: TypeConstructorDescription { - case resolvedPeer(peer: Api.Peer, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .resolvedPeer(let peer, let chats, let users): - if boxed { - buffer.appendInt32(2131196633) - } - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .resolvedPeer(let peer, let chats, let users): - return ("resolvedPeer", [("peer", peer as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_resolvedPeer(_ reader: BufferReader) -> ResolvedPeer? { - var _1: Api.Peer? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Peer - } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.contacts.ResolvedPeer.resolvedPeer(peer: _1!, chats: _2!, users: _3!) - } - - } -} -public extension Api.contacts { - enum SponsoredPeers: TypeConstructorDescription { - case sponsoredPeers(peers: [Api.SponsoredPeer], chats: [Api.Chat], users: [Api.User]) - case sponsoredPeersEmpty - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .sponsoredPeers(let peers, let chats, let users): - if boxed { - buffer.appendInt32(-352114556) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peers.count)) - for item in peers { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .sponsoredPeersEmpty: - if boxed { - buffer.appendInt32(-365775695) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .sponsoredPeers(let peers, let chats, let users): - return ("sponsoredPeers", [("peers", peers as Any), ("chats", chats as Any), ("users", users as Any)]) - case .sponsoredPeersEmpty: - return ("sponsoredPeersEmpty", []) - } - } - - public static func parse_sponsoredPeers(_ reader: BufferReader) -> SponsoredPeers? { - var _1: [Api.SponsoredPeer]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SponsoredPeer.self) - } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.contacts.SponsoredPeers.sponsoredPeers(peers: _1!, chats: _2!, users: _3!) - } - public static func parse_sponsoredPeersEmpty(_ reader: BufferReader) -> SponsoredPeers? { - return Api.contacts.SponsoredPeers.sponsoredPeersEmpty - } - - } -} -public extension Api.contacts { - enum TopPeers: TypeConstructorDescription { - case topPeers(categories: [Api.TopPeerCategoryPeers], chats: [Api.Chat], users: [Api.User]) - case topPeersDisabled - case topPeersNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .topPeers(let categories, let chats, let users): - if boxed { - buffer.appendInt32(1891070632) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(categories.count)) - for item in categories { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .topPeersDisabled: - if boxed { - buffer.appendInt32(-1255369827) - } - - break - case .topPeersNotModified: - if boxed { - buffer.appendInt32(-567906571) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .topPeers(let categories, let chats, let users): - return ("topPeers", [("categories", categories as Any), ("chats", chats as Any), ("users", users as Any)]) - case .topPeersDisabled: - return ("topPeersDisabled", []) - case .topPeersNotModified: - return ("topPeersNotModified", []) - } - } - - public static func parse_topPeers(_ reader: BufferReader) -> TopPeers? { - var _1: [Api.TopPeerCategoryPeers]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.TopPeerCategoryPeers.self) - } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.contacts.TopPeers.topPeers(categories: _1!, chats: _2!, users: _3!) - } - public static func parse_topPeersDisabled(_ reader: BufferReader) -> TopPeers? { - return Api.contacts.TopPeers.topPeersDisabled - } - public static func parse_topPeersNotModified(_ reader: BufferReader) -> TopPeers? { - return Api.contacts.TopPeers.topPeersNotModified - } - - } -} -public extension Api.fragment { - enum CollectibleInfo: TypeConstructorDescription { - case collectibleInfo(purchaseDate: Int32, currency: String, amount: Int64, cryptoCurrency: String, cryptoAmount: Int64, url: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .collectibleInfo(let purchaseDate, let currency, let amount, let cryptoCurrency, let cryptoAmount, let url): - if boxed { - buffer.appendInt32(1857945489) - } - serializeInt32(purchaseDate, buffer: buffer, boxed: false) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(amount, buffer: buffer, boxed: false) - serializeString(cryptoCurrency, buffer: buffer, boxed: false) - serializeInt64(cryptoAmount, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .collectibleInfo(let purchaseDate, let currency, let amount, let cryptoCurrency, let cryptoAmount, let url): - return ("collectibleInfo", [("purchaseDate", purchaseDate as Any), ("currency", currency as Any), ("amount", amount as Any), ("cryptoCurrency", cryptoCurrency as Any), ("cryptoAmount", cryptoAmount as Any), ("url", url as Any)]) - } - } - - public static func parse_collectibleInfo(_ reader: BufferReader) -> CollectibleInfo? { + + public static func parse_authorization(_ reader: BufferReader) -> Authorization? { var _1: Int32? _1 = reader.readInt32() + var _2: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _2 = reader.readInt32() + } + var _3: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } + var _4: Buffer? + if Int(_1!) & Int(1 << 2) != 0 { + _4 = parseBytes(reader) + } + var _5: Api.User? + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.User + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.auth.Authorization.authorization(Cons_authorization(flags: _1!, otherwiseReloginDays: _2, tmpSessions: _3, futureAuthToken: _4, user: _5!)) + } + else { + return nil + } + } + public static func parse_authorizationSignUpRequired(_ reader: BufferReader) -> Authorization? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.help.TermsOfService? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.help.TermsOfService + } + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + if _c1 && _c2 { + return Api.auth.Authorization.authorizationSignUpRequired(Cons_authorizationSignUpRequired(flags: _1!, termsOfService: _2)) + } + else { + return nil + } + } + } +} +public extension Api.auth { + enum CodeType: TypeConstructorDescription { + case codeTypeCall + case codeTypeFlashCall + case codeTypeFragmentSms + case codeTypeMissedCall + case codeTypeSms + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .codeTypeCall: + if boxed { + buffer.appendInt32(1948046307) + } + break + case .codeTypeFlashCall: + if boxed { + buffer.appendInt32(577556219) + } + break + case .codeTypeFragmentSms: + if boxed { + buffer.appendInt32(116234636) + } + break + case .codeTypeMissedCall: + if boxed { + buffer.appendInt32(-702884114) + } + break + case .codeTypeSms: + if boxed { + buffer.appendInt32(1923290508) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .codeTypeCall: + return ("codeTypeCall", []) + case .codeTypeFlashCall: + return ("codeTypeFlashCall", []) + case .codeTypeFragmentSms: + return ("codeTypeFragmentSms", []) + case .codeTypeMissedCall: + return ("codeTypeMissedCall", []) + case .codeTypeSms: + return ("codeTypeSms", []) + } + } + + public static func parse_codeTypeCall(_ reader: BufferReader) -> CodeType? { + return Api.auth.CodeType.codeTypeCall + } + public static func parse_codeTypeFlashCall(_ reader: BufferReader) -> CodeType? { + return Api.auth.CodeType.codeTypeFlashCall + } + public static func parse_codeTypeFragmentSms(_ reader: BufferReader) -> CodeType? { + return Api.auth.CodeType.codeTypeFragmentSms + } + public static func parse_codeTypeMissedCall(_ reader: BufferReader) -> CodeType? { + return Api.auth.CodeType.codeTypeMissedCall + } + public static func parse_codeTypeSms(_ reader: BufferReader) -> CodeType? { + return Api.auth.CodeType.codeTypeSms + } + } +} +public extension Api.auth { + enum ExportedAuthorization: TypeConstructorDescription { + public class Cons_exportedAuthorization { + public var id: Int64 + public var bytes: Buffer + public init(id: Int64, bytes: Buffer) { + self.id = id + self.bytes = bytes + } + } + case exportedAuthorization(Cons_exportedAuthorization) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .exportedAuthorization(let _data): + if boxed { + buffer.appendInt32(-1271602504) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeBytes(_data.bytes, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .exportedAuthorization(let _data): + return ("exportedAuthorization", [("id", _data.id as Any), ("bytes", _data.bytes as Any)]) + } + } + + public static func parse_exportedAuthorization(_ reader: BufferReader) -> ExportedAuthorization? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Buffer? + _2 = parseBytes(reader) + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.auth.ExportedAuthorization.exportedAuthorization(Cons_exportedAuthorization(id: _1!, bytes: _2!)) + } + else { + return nil + } + } + } +} +public extension Api.auth { + enum LoggedOut: TypeConstructorDescription { + public class Cons_loggedOut { + public var flags: Int32 + public var futureAuthToken: Buffer? + public init(flags: Int32, futureAuthToken: Buffer?) { + self.flags = flags + self.futureAuthToken = futureAuthToken + } + } + case loggedOut(Cons_loggedOut) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .loggedOut(let _data): + if boxed { + buffer.appendInt32(-1012759713) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeBytes(_data.futureAuthToken!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .loggedOut(let _data): + return ("loggedOut", [("flags", _data.flags as Any), ("futureAuthToken", _data.futureAuthToken as Any)]) + } + } + + public static func parse_loggedOut(_ reader: BufferReader) -> LoggedOut? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Buffer? + if Int(_1!) & Int(1 << 0) != 0 { + _2 = parseBytes(reader) + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + if _c1 && _c2 { + return Api.auth.LoggedOut.loggedOut(Cons_loggedOut(flags: _1!, futureAuthToken: _2)) + } + else { + return nil + } + } + } +} +public extension Api.auth { + enum LoginToken: TypeConstructorDescription { + public class Cons_loginToken { + public var expires: Int32 + public var token: Buffer + public init(expires: Int32, token: Buffer) { + self.expires = expires + self.token = token + } + } + public class Cons_loginTokenMigrateTo { + public var dcId: Int32 + public var token: Buffer + public init(dcId: Int32, token: Buffer) { + self.dcId = dcId + self.token = token + } + } + public class Cons_loginTokenSuccess { + public var authorization: Api.auth.Authorization + public init(authorization: Api.auth.Authorization) { + self.authorization = authorization + } + } + case loginToken(Cons_loginToken) + case loginTokenMigrateTo(Cons_loginTokenMigrateTo) + case loginTokenSuccess(Cons_loginTokenSuccess) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .loginToken(let _data): + if boxed { + buffer.appendInt32(1654593920) + } + serializeInt32(_data.expires, buffer: buffer, boxed: false) + serializeBytes(_data.token, buffer: buffer, boxed: false) + break + case .loginTokenMigrateTo(let _data): + if boxed { + buffer.appendInt32(110008598) + } + serializeInt32(_data.dcId, buffer: buffer, boxed: false) + serializeBytes(_data.token, buffer: buffer, boxed: false) + break + case .loginTokenSuccess(let _data): + if boxed { + buffer.appendInt32(957176926) + } + _data.authorization.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .loginToken(let _data): + return ("loginToken", [("expires", _data.expires as Any), ("token", _data.token as Any)]) + case .loginTokenMigrateTo(let _data): + return ("loginTokenMigrateTo", [("dcId", _data.dcId as Any), ("token", _data.token as Any)]) + case .loginTokenSuccess(let _data): + return ("loginTokenSuccess", [("authorization", _data.authorization as Any)]) + } + } + + public static func parse_loginToken(_ reader: BufferReader) -> LoginToken? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Buffer? + _2 = parseBytes(reader) + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.auth.LoginToken.loginToken(Cons_loginToken(expires: _1!, token: _2!)) + } + else { + return nil + } + } + public static func parse_loginTokenMigrateTo(_ reader: BufferReader) -> LoginToken? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Buffer? + _2 = parseBytes(reader) + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.auth.LoginToken.loginTokenMigrateTo(Cons_loginTokenMigrateTo(dcId: _1!, token: _2!)) + } + else { + return nil + } + } + public static func parse_loginTokenSuccess(_ reader: BufferReader) -> LoginToken? { + var _1: Api.auth.Authorization? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.auth.Authorization + } + let _c1 = _1 != nil + if _c1 { + return Api.auth.LoginToken.loginTokenSuccess(Cons_loginTokenSuccess(authorization: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.auth { + enum PasskeyLoginOptions: TypeConstructorDescription { + public class Cons_passkeyLoginOptions { + public var options: Api.DataJSON + public init(options: Api.DataJSON) { + self.options = options + } + } + case passkeyLoginOptions(Cons_passkeyLoginOptions) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .passkeyLoginOptions(let _data): + if boxed { + buffer.appendInt32(-503089271) + } + _data.options.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .passkeyLoginOptions(let _data): + return ("passkeyLoginOptions", [("options", _data.options as Any)]) + } + } + + public static func parse_passkeyLoginOptions(_ reader: BufferReader) -> PasskeyLoginOptions? { + var _1: Api.DataJSON? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.DataJSON + } + let _c1 = _1 != nil + if _c1 { + return Api.auth.PasskeyLoginOptions.passkeyLoginOptions(Cons_passkeyLoginOptions(options: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.auth { + enum PasswordRecovery: TypeConstructorDescription { + public class Cons_passwordRecovery { + public var emailPattern: String + public init(emailPattern: String) { + self.emailPattern = emailPattern + } + } + case passwordRecovery(Cons_passwordRecovery) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .passwordRecovery(let _data): + if boxed { + buffer.appendInt32(326715557) + } + serializeString(_data.emailPattern, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .passwordRecovery(let _data): + return ("passwordRecovery", [("emailPattern", _data.emailPattern as Any)]) + } + } + + public static func parse_passwordRecovery(_ reader: BufferReader) -> PasswordRecovery? { + var _1: String? + _1 = parseString(reader) + let _c1 = _1 != nil + if _c1 { + return Api.auth.PasswordRecovery.passwordRecovery(Cons_passwordRecovery(emailPattern: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.auth { + enum SentCode: TypeConstructorDescription { + public class Cons_sentCode { + public var flags: Int32 + public var type: Api.auth.SentCodeType + public var phoneCodeHash: String + public var nextType: Api.auth.CodeType? + public var timeout: Int32? + public init(flags: Int32, type: Api.auth.SentCodeType, phoneCodeHash: String, nextType: Api.auth.CodeType?, timeout: Int32?) { + self.flags = flags + self.type = type + self.phoneCodeHash = phoneCodeHash + self.nextType = nextType + self.timeout = timeout + } + } + public class Cons_sentCodePaymentRequired { + public var storeProduct: String + public var phoneCodeHash: String + public var supportEmailAddress: String + public var supportEmailSubject: String + public var currency: String + public var amount: Int64 + public init(storeProduct: String, phoneCodeHash: String, supportEmailAddress: String, supportEmailSubject: String, currency: String, amount: Int64) { + self.storeProduct = storeProduct + self.phoneCodeHash = phoneCodeHash + self.supportEmailAddress = supportEmailAddress + self.supportEmailSubject = supportEmailSubject + self.currency = currency + self.amount = amount + } + } + public class Cons_sentCodeSuccess { + public var authorization: Api.auth.Authorization + public init(authorization: Api.auth.Authorization) { + self.authorization = authorization + } + } + case sentCode(Cons_sentCode) + case sentCodePaymentRequired(Cons_sentCodePaymentRequired) + case sentCodeSuccess(Cons_sentCodeSuccess) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .sentCode(let _data): + if boxed { + buffer.appendInt32(1577067778) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.type.serialize(buffer, true) + serializeString(_data.phoneCodeHash, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.nextType!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.timeout!, buffer: buffer, boxed: false) + } + break + case .sentCodePaymentRequired(let _data): + if boxed { + buffer.appendInt32(-527082948) + } + serializeString(_data.storeProduct, buffer: buffer, boxed: false) + serializeString(_data.phoneCodeHash, buffer: buffer, boxed: false) + serializeString(_data.supportEmailAddress, buffer: buffer, boxed: false) + serializeString(_data.supportEmailSubject, buffer: buffer, boxed: false) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + break + case .sentCodeSuccess(let _data): + if boxed { + buffer.appendInt32(596704836) + } + _data.authorization.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .sentCode(let _data): + return ("sentCode", [("flags", _data.flags as Any), ("type", _data.type as Any), ("phoneCodeHash", _data.phoneCodeHash as Any), ("nextType", _data.nextType as Any), ("timeout", _data.timeout as Any)]) + case .sentCodePaymentRequired(let _data): + return ("sentCodePaymentRequired", [("storeProduct", _data.storeProduct as Any), ("phoneCodeHash", _data.phoneCodeHash as Any), ("supportEmailAddress", _data.supportEmailAddress as Any), ("supportEmailSubject", _data.supportEmailSubject as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any)]) + case .sentCodeSuccess(let _data): + return ("sentCodeSuccess", [("authorization", _data.authorization as Any)]) + } + } + + public static func parse_sentCode(_ reader: BufferReader) -> SentCode? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.auth.SentCodeType? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.auth.SentCodeType + } + var _3: String? + _3 = parseString(reader) + var _4: Api.auth.CodeType? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.auth.CodeType + } + } + var _5: Int32? + if Int(_1!) & Int(1 << 2) != 0 { + _5 = reader.readInt32() + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil + let _c5 = (Int(_1!) & Int(1 << 2) == 0) || _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.auth.SentCode.sentCode(Cons_sentCode(flags: _1!, type: _2!, phoneCodeHash: _3!, nextType: _4, timeout: _5)) + } + else { + return nil + } + } + public static func parse_sentCodePaymentRequired(_ reader: BufferReader) -> SentCode? { + var _1: String? + _1 = parseString(reader) var _2: String? _2 = parseString(reader) - var _3: Int64? - _3 = reader.readInt64() + var _3: String? + _3 = parseString(reader) var _4: String? _4 = parseString(reader) - var _5: Int64? - _5 = reader.readInt64() - var _6: String? - _6 = parseString(reader) + var _5: String? + _5 = parseString(reader) + var _6: Int64? + _6 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.fragment.CollectibleInfo.collectibleInfo(purchaseDate: _1!, currency: _2!, amount: _3!, cryptoCurrency: _4!, cryptoAmount: _5!, url: _6!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.auth.SentCode.sentCodePaymentRequired(Cons_sentCodePaymentRequired(storeProduct: _1!, phoneCodeHash: _2!, supportEmailAddress: _3!, supportEmailSubject: _4!, currency: _5!, amount: _6!)) + } + else { + return nil + } + } + public static func parse_sentCodeSuccess(_ reader: BufferReader) -> SentCode? { + var _1: Api.auth.Authorization? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.auth.Authorization + } + let _c1 = _1 != nil + if _c1 { + return Api.auth.SentCode.sentCodeSuccess(Cons_sentCodeSuccess(authorization: _1!)) + } + else { + return nil + } } - } } -public extension Api.help { - enum AppConfig: TypeConstructorDescription { - case appConfig(hash: Int32, config: Api.JSONValue) - case appConfigNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .appConfig(let hash, let config): - if boxed { - buffer.appendInt32(-585598930) - } - serializeInt32(hash, buffer: buffer, boxed: false) - config.serialize(buffer, true) - break - case .appConfigNotModified: - if boxed { - buffer.appendInt32(2094949405) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .appConfig(let hash, let config): - return ("appConfig", [("hash", hash as Any), ("config", config as Any)]) - case .appConfigNotModified: - return ("appConfigNotModified", []) - } - } - - public static func parse_appConfig(_ reader: BufferReader) -> AppConfig? { +public extension Api.auth { + enum SentCodeType: TypeConstructorDescription { + public class Cons_sentCodeTypeApp { + public var length: Int32 + public init(length: Int32) { + self.length = length + } + } + public class Cons_sentCodeTypeCall { + public var length: Int32 + public init(length: Int32) { + self.length = length + } + } + public class Cons_sentCodeTypeEmailCode { + public var flags: Int32 + public var emailPattern: String + public var length: Int32 + public var resetAvailablePeriod: Int32? + public var resetPendingDate: Int32? + public init(flags: Int32, emailPattern: String, length: Int32, resetAvailablePeriod: Int32?, resetPendingDate: Int32?) { + self.flags = flags + self.emailPattern = emailPattern + self.length = length + self.resetAvailablePeriod = resetAvailablePeriod + self.resetPendingDate = resetPendingDate + } + } + public class Cons_sentCodeTypeFirebaseSms { + public var flags: Int32 + public var nonce: Buffer? + public var playIntegrityProjectId: Int64? + public var playIntegrityNonce: Buffer? + public var receipt: String? + public var pushTimeout: Int32? + public var length: Int32 + public init(flags: Int32, nonce: Buffer?, playIntegrityProjectId: Int64?, playIntegrityNonce: Buffer?, receipt: String?, pushTimeout: Int32?, length: Int32) { + self.flags = flags + self.nonce = nonce + self.playIntegrityProjectId = playIntegrityProjectId + self.playIntegrityNonce = playIntegrityNonce + self.receipt = receipt + self.pushTimeout = pushTimeout + self.length = length + } + } + public class Cons_sentCodeTypeFlashCall { + public var pattern: String + public init(pattern: String) { + self.pattern = pattern + } + } + public class Cons_sentCodeTypeFragmentSms { + public var url: String + public var length: Int32 + public init(url: String, length: Int32) { + self.url = url + self.length = length + } + } + public class Cons_sentCodeTypeMissedCall { + public var prefix: String + public var length: Int32 + public init(prefix: String, length: Int32) { + self.prefix = prefix + self.length = length + } + } + public class Cons_sentCodeTypeSetUpEmailRequired { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } + public class Cons_sentCodeTypeSms { + public var length: Int32 + public init(length: Int32) { + self.length = length + } + } + public class Cons_sentCodeTypeSmsPhrase { + public var flags: Int32 + public var beginning: String? + public init(flags: Int32, beginning: String?) { + self.flags = flags + self.beginning = beginning + } + } + public class Cons_sentCodeTypeSmsWord { + public var flags: Int32 + public var beginning: String? + public init(flags: Int32, beginning: String?) { + self.flags = flags + self.beginning = beginning + } + } + case sentCodeTypeApp(Cons_sentCodeTypeApp) + case sentCodeTypeCall(Cons_sentCodeTypeCall) + case sentCodeTypeEmailCode(Cons_sentCodeTypeEmailCode) + case sentCodeTypeFirebaseSms(Cons_sentCodeTypeFirebaseSms) + case sentCodeTypeFlashCall(Cons_sentCodeTypeFlashCall) + case sentCodeTypeFragmentSms(Cons_sentCodeTypeFragmentSms) + case sentCodeTypeMissedCall(Cons_sentCodeTypeMissedCall) + case sentCodeTypeSetUpEmailRequired(Cons_sentCodeTypeSetUpEmailRequired) + case sentCodeTypeSms(Cons_sentCodeTypeSms) + case sentCodeTypeSmsPhrase(Cons_sentCodeTypeSmsPhrase) + case sentCodeTypeSmsWord(Cons_sentCodeTypeSmsWord) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .sentCodeTypeApp(let _data): + if boxed { + buffer.appendInt32(1035688326) + } + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .sentCodeTypeCall(let _data): + if boxed { + buffer.appendInt32(1398007207) + } + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .sentCodeTypeEmailCode(let _data): + if boxed { + buffer.appendInt32(-196020837) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.emailPattern, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.resetAvailablePeriod!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.resetPendingDate!, buffer: buffer, boxed: false) + } + break + case .sentCodeTypeFirebaseSms(let _data): + if boxed { + buffer.appendInt32(10475318) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeBytes(_data.nonce!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt64(_data.playIntegrityProjectId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeBytes(_data.playIntegrityNonce!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.receipt!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.pushTimeout!, buffer: buffer, boxed: false) + } + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .sentCodeTypeFlashCall(let _data): + if boxed { + buffer.appendInt32(-1425815847) + } + serializeString(_data.pattern, buffer: buffer, boxed: false) + break + case .sentCodeTypeFragmentSms(let _data): + if boxed { + buffer.appendInt32(-648651719) + } + serializeString(_data.url, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .sentCodeTypeMissedCall(let _data): + if boxed { + buffer.appendInt32(-2113903484) + } + serializeString(_data.prefix, buffer: buffer, boxed: false) + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .sentCodeTypeSetUpEmailRequired(let _data): + if boxed { + buffer.appendInt32(-1521934870) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + case .sentCodeTypeSms(let _data): + if boxed { + buffer.appendInt32(-1073693790) + } + serializeInt32(_data.length, buffer: buffer, boxed: false) + break + case .sentCodeTypeSmsPhrase(let _data): + if boxed { + buffer.appendInt32(-1284008785) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.beginning!, buffer: buffer, boxed: false) + } + break + case .sentCodeTypeSmsWord(let _data): + if boxed { + buffer.appendInt32(-1542017919) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.beginning!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .sentCodeTypeApp(let _data): + return ("sentCodeTypeApp", [("length", _data.length as Any)]) + case .sentCodeTypeCall(let _data): + return ("sentCodeTypeCall", [("length", _data.length as Any)]) + case .sentCodeTypeEmailCode(let _data): + return ("sentCodeTypeEmailCode", [("flags", _data.flags as Any), ("emailPattern", _data.emailPattern as Any), ("length", _data.length as Any), ("resetAvailablePeriod", _data.resetAvailablePeriod as Any), ("resetPendingDate", _data.resetPendingDate as Any)]) + case .sentCodeTypeFirebaseSms(let _data): + return ("sentCodeTypeFirebaseSms", [("flags", _data.flags as Any), ("nonce", _data.nonce as Any), ("playIntegrityProjectId", _data.playIntegrityProjectId as Any), ("playIntegrityNonce", _data.playIntegrityNonce as Any), ("receipt", _data.receipt as Any), ("pushTimeout", _data.pushTimeout as Any), ("length", _data.length as Any)]) + case .sentCodeTypeFlashCall(let _data): + return ("sentCodeTypeFlashCall", [("pattern", _data.pattern as Any)]) + case .sentCodeTypeFragmentSms(let _data): + return ("sentCodeTypeFragmentSms", [("url", _data.url as Any), ("length", _data.length as Any)]) + case .sentCodeTypeMissedCall(let _data): + return ("sentCodeTypeMissedCall", [("prefix", _data.prefix as Any), ("length", _data.length as Any)]) + case .sentCodeTypeSetUpEmailRequired(let _data): + return ("sentCodeTypeSetUpEmailRequired", [("flags", _data.flags as Any)]) + case .sentCodeTypeSms(let _data): + return ("sentCodeTypeSms", [("length", _data.length as Any)]) + case .sentCodeTypeSmsPhrase(let _data): + return ("sentCodeTypeSmsPhrase", [("flags", _data.flags as Any), ("beginning", _data.beginning as Any)]) + case .sentCodeTypeSmsWord(let _data): + return ("sentCodeTypeSmsWord", [("flags", _data.flags as Any), ("beginning", _data.beginning as Any)]) + } + } + + public static func parse_sentCodeTypeApp(_ reader: BufferReader) -> SentCodeType? { var _1: Int32? _1 = reader.readInt32() - var _2: Api.JSONValue? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.JSONValue + let _c1 = _1 != nil + if _c1 { + return Api.auth.SentCodeType.sentCodeTypeApp(Cons_sentCodeTypeApp(length: _1!)) + } + else { + return nil + } + } + public static func parse_sentCodeTypeCall(_ reader: BufferReader) -> SentCodeType? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.auth.SentCodeType.sentCodeTypeCall(Cons_sentCodeTypeCall(length: _1!)) + } + else { + return nil + } + } + public static func parse_sentCodeTypeEmailCode(_ reader: BufferReader) -> SentCodeType? { + var _1: Int32? + _1 = reader.readInt32() + var _2: String? + _2 = parseString(reader) + var _3: Int32? + _3 = reader.readInt32() + var _4: Int32? + if Int(_1!) & Int(1 << 3) != 0 { + _4 = reader.readInt32() + } + var _5: Int32? + if Int(_1!) & Int(1 << 4) != 0 { + _5 = reader.readInt32() } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.help.AppConfig.appConfig(hash: _1!, config: _2!) + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 3) == 0) || _4 != nil + let _c5 = (Int(_1!) & Int(1 << 4) == 0) || _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.auth.SentCodeType.sentCodeTypeEmailCode(Cons_sentCodeTypeEmailCode(flags: _1!, emailPattern: _2!, length: _3!, resetAvailablePeriod: _4, resetPendingDate: _5)) + } + else { + return nil + } } - public static func parse_appConfigNotModified(_ reader: BufferReader) -> AppConfig? { - return Api.help.AppConfig.appConfigNotModified + public static func parse_sentCodeTypeFirebaseSms(_ reader: BufferReader) -> SentCodeType? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Buffer? + if Int(_1!) & Int(1 << 0) != 0 { + _2 = parseBytes(reader) + } + var _3: Int64? + if Int(_1!) & Int(1 << 2) != 0 { + _3 = reader.readInt64() + } + var _4: Buffer? + if Int(_1!) & Int(1 << 2) != 0 { + _4 = parseBytes(reader) + } + var _5: String? + if Int(_1!) & Int(1 << 1) != 0 { + _5 = parseString(reader) + } + var _6: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _6 = reader.readInt32() + } + var _7: Int32? + _7 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + let _c3 = (Int(_1!) & Int(1 << 2) == 0) || _3 != nil + let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil + let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil + let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil + let _c7 = _7 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.auth.SentCodeType.sentCodeTypeFirebaseSms(Cons_sentCodeTypeFirebaseSms(flags: _1!, nonce: _2, playIntegrityProjectId: _3, playIntegrityNonce: _4, receipt: _5, pushTimeout: _6, length: _7!)) + } + else { + return nil + } + } + public static func parse_sentCodeTypeFlashCall(_ reader: BufferReader) -> SentCodeType? { + var _1: String? + _1 = parseString(reader) + let _c1 = _1 != nil + if _c1 { + return Api.auth.SentCodeType.sentCodeTypeFlashCall(Cons_sentCodeTypeFlashCall(pattern: _1!)) + } + else { + return nil + } + } + public static func parse_sentCodeTypeFragmentSms(_ reader: BufferReader) -> SentCodeType? { + var _1: String? + _1 = parseString(reader) + var _2: Int32? + _2 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.auth.SentCodeType.sentCodeTypeFragmentSms(Cons_sentCodeTypeFragmentSms(url: _1!, length: _2!)) + } + else { + return nil + } + } + public static func parse_sentCodeTypeMissedCall(_ reader: BufferReader) -> SentCodeType? { + var _1: String? + _1 = parseString(reader) + var _2: Int32? + _2 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.auth.SentCodeType.sentCodeTypeMissedCall(Cons_sentCodeTypeMissedCall(prefix: _1!, length: _2!)) + } + else { + return nil + } + } + public static func parse_sentCodeTypeSetUpEmailRequired(_ reader: BufferReader) -> SentCodeType? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.auth.SentCodeType.sentCodeTypeSetUpEmailRequired(Cons_sentCodeTypeSetUpEmailRequired(flags: _1!)) + } + else { + return nil + } + } + public static func parse_sentCodeTypeSms(_ reader: BufferReader) -> SentCodeType? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.auth.SentCodeType.sentCodeTypeSms(Cons_sentCodeTypeSms(length: _1!)) + } + else { + return nil + } + } + public static func parse_sentCodeTypeSmsPhrase(_ reader: BufferReader) -> SentCodeType? { + var _1: Int32? + _1 = reader.readInt32() + var _2: String? + if Int(_1!) & Int(1 << 0) != 0 { + _2 = parseString(reader) + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + if _c1 && _c2 { + return Api.auth.SentCodeType.sentCodeTypeSmsPhrase(Cons_sentCodeTypeSmsPhrase(flags: _1!, beginning: _2)) + } + else { + return nil + } + } + public static func parse_sentCodeTypeSmsWord(_ reader: BufferReader) -> SentCodeType? { + var _1: Int32? + _1 = reader.readInt32() + var _2: String? + if Int(_1!) & Int(1 << 0) != 0 { + _2 = parseString(reader) + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + if _c1 && _c2 { + return Api.auth.SentCodeType.sentCodeTypeSmsWord(Cons_sentCodeTypeSmsWord(flags: _1!, beginning: _2)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api32.swift b/submodules/TelegramApi/Sources/Api32.swift index 5649eb9f..c066d8ed 100644 --- a/submodules/TelegramApi/Sources/Api32.swift +++ b/submodules/TelegramApi/Sources/Api32.swift @@ -1,853 +1,228 @@ -public extension Api.help { - enum AppUpdate: TypeConstructorDescription { - case appUpdate(flags: Int32, id: Int32, version: String, text: String, entities: [Api.MessageEntity], document: Api.Document?, url: String?, sticker: Api.Document?) - case noAppUpdate - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .appUpdate(let flags, let id, let version, let text, let entities, let document, let url, let sticker): - if boxed { - buffer.appendInt32(-860107216) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - serializeString(version, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities.count)) - for item in entities { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 1) != 0 {document!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(url!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {sticker!.serialize(buffer, true)} - break - case .noAppUpdate: - if boxed { - buffer.appendInt32(-1000708810) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .appUpdate(let flags, let id, let version, let text, let entities, let document, let url, let sticker): - return ("appUpdate", [("flags", flags as Any), ("id", id as Any), ("version", version as Any), ("text", text as Any), ("entities", entities as Any), ("document", document as Any), ("url", url as Any), ("sticker", sticker as Any)]) - case .noAppUpdate: - return ("noAppUpdate", []) - } - } - - public static func parse_appUpdate(_ reader: BufferReader) -> AppUpdate? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: String? - _3 = parseString(reader) - var _4: String? - _4 = parseString(reader) - var _5: [Api.MessageEntity]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) +public extension Api.bots { + enum BotInfo: TypeConstructorDescription { + public class Cons_botInfo { + public var name: String + public var about: String + public var description: String + public init(name: String, about: String, description: String) { + self.name = name + self.about = about + self.description = description } - var _6: Api.Document? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.Document - } } - var _7: String? - if Int(_1!) & Int(1 << 2) != 0 {_7 = parseString(reader) } - var _8: Api.Document? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.Document - } } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil - let _c7 = (Int(_1!) & Int(1 << 2) == 0) || _7 != nil - let _c8 = (Int(_1!) & Int(1 << 3) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.help.AppUpdate.appUpdate(flags: _1!, id: _2!, version: _3!, text: _4!, entities: _5!, document: _6, url: _7, sticker: _8) } - public static func parse_noAppUpdate(_ reader: BufferReader) -> AppUpdate? { - return Api.help.AppUpdate.noAppUpdate - } - - } -} -public extension Api.help { - enum CountriesList: TypeConstructorDescription { - case countriesList(countries: [Api.help.Country], hash: Int32) - case countriesListNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .countriesList(let countries, let hash): - if boxed { - buffer.appendInt32(-2016381538) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(countries.count)) - for item in countries { - item.serialize(buffer, true) - } - serializeInt32(hash, buffer: buffer, boxed: false) - break - case .countriesListNotModified: - if boxed { - buffer.appendInt32(-1815339214) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .countriesList(let countries, let hash): - return ("countriesList", [("countries", countries as Any), ("hash", hash as Any)]) - case .countriesListNotModified: - return ("countriesListNotModified", []) - } - } - - public static func parse_countriesList(_ reader: BufferReader) -> CountriesList? { - var _1: [Api.help.Country]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.help.Country.self) + case botInfo(Cons_botInfo) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botInfo(let _data): + if boxed { + buffer.appendInt32(-391678544) + } + serializeString(_data.name, buffer: buffer, boxed: false) + serializeString(_data.about, buffer: buffer, boxed: false) + serializeString(_data.description, buffer: buffer, boxed: false) + break } - var _2: Int32? - _2 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.help.CountriesList.countriesList(countries: _1!, hash: _2!) } - public static func parse_countriesListNotModified(_ reader: BufferReader) -> CountriesList? { - return Api.help.CountriesList.countriesListNotModified + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botInfo(let _data): + return ("botInfo", [("name", _data.name as Any), ("about", _data.about as Any), ("description", _data.description as Any)]) + } } - - } -} -public extension Api.help { - enum Country: TypeConstructorDescription { - case country(flags: Int32, iso2: String, defaultName: String, name: String?, countryCodes: [Api.help.CountryCode]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .country(let flags, let iso2, let defaultName, let name, let countryCodes): - if boxed { - buffer.appendInt32(-1014526429) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(iso2, buffer: buffer, boxed: false) - serializeString(defaultName, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeString(name!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(countryCodes.count)) - for item in countryCodes { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .country(let flags, let iso2, let defaultName, let name, let countryCodes): - return ("country", [("flags", flags as Any), ("iso2", iso2 as Any), ("defaultName", defaultName as Any), ("name", name as Any), ("countryCodes", countryCodes as Any)]) - } - } - - public static func parse_country(_ reader: BufferReader) -> Country? { - var _1: Int32? - _1 = reader.readInt32() + + public static func parse_botInfo(_ reader: BufferReader) -> BotInfo? { + var _1: String? + _1 = parseString(reader) var _2: String? _2 = parseString(reader) var _3: String? _3 = parseString(reader) - var _4: String? - if Int(_1!) & Int(1 << 1) != 0 {_4 = parseString(reader) } - var _5: [Api.help.CountryCode]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.help.CountryCode.self) - } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.help.Country.country(flags: _1!, iso2: _2!, defaultName: _3!, name: _4, countryCodes: _5!) + if _c1 && _c2 && _c3 { + return Api.bots.BotInfo.botInfo(Cons_botInfo(name: _1!, about: _2!, description: _3!)) + } + else { + return nil + } } - } } -public extension Api.help { - enum CountryCode: TypeConstructorDescription { - case countryCode(flags: Int32, countryCode: String, prefixes: [String]?, patterns: [String]?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .countryCode(let flags, let countryCode, let prefixes, let patterns): - if boxed { - buffer.appendInt32(1107543535) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(countryCode, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(prefixes!.count)) - for item in prefixes! { - serializeString(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(patterns!.count)) - for item in patterns! { - serializeString(item, buffer: buffer, boxed: false) - }} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .countryCode(let flags, let countryCode, let prefixes, let patterns): - return ("countryCode", [("flags", flags as Any), ("countryCode", countryCode as Any), ("prefixes", prefixes as Any), ("patterns", patterns as Any)]) - } - } - - public static func parse_countryCode(_ reader: BufferReader) -> CountryCode? { +public extension Api.bots { + enum PopularAppBots: TypeConstructorDescription { + public class Cons_popularAppBots { + public var flags: Int32 + public var nextOffset: String? + public var users: [Api.User] + public init(flags: Int32, nextOffset: String?, users: [Api.User]) { + self.flags = flags + self.nextOffset = nextOffset + self.users = users + } + } + case popularAppBots(Cons_popularAppBots) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .popularAppBots(let _data): + if boxed { + buffer.appendInt32(428978491) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.nextOffset!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .popularAppBots(let _data): + return ("popularAppBots", [("flags", _data.flags as Any), ("nextOffset", _data.nextOffset as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_popularAppBots(_ reader: BufferReader) -> PopularAppBots? { var _1: Int32? _1 = reader.readInt32() var _2: String? - _2 = parseString(reader) - var _3: [String]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) - } } - var _4: [String]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) - } } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.help.CountryCode.countryCode(flags: _1!, countryCode: _2!, prefixes: _3, patterns: _4) - } - - } -} -public extension Api.help { - enum DeepLinkInfo: TypeConstructorDescription { - case deepLinkInfo(flags: Int32, message: String, entities: [Api.MessageEntity]?) - case deepLinkInfoEmpty - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .deepLinkInfo(let flags, let message, let entities): - if boxed { - buffer.appendInt32(1783556146) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { - item.serialize(buffer, true) - }} - break - case .deepLinkInfoEmpty: - if boxed { - buffer.appendInt32(1722786150) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .deepLinkInfo(let flags, let message, let entities): - return ("deepLinkInfo", [("flags", flags as Any), ("message", message as Any), ("entities", entities as Any)]) - case .deepLinkInfoEmpty: - return ("deepLinkInfoEmpty", []) - } - } - - public static func parse_deepLinkInfo(_ reader: BufferReader) -> DeepLinkInfo? { - var _1: Int32? - _1 = reader.readInt32() - var _2: String? - _2 = parseString(reader) - var _3: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.help.DeepLinkInfo.deepLinkInfo(flags: _1!, message: _2!, entities: _3) - } - public static func parse_deepLinkInfoEmpty(_ reader: BufferReader) -> DeepLinkInfo? { - return Api.help.DeepLinkInfo.deepLinkInfoEmpty - } - - } -} -public extension Api.help { - enum InviteText: TypeConstructorDescription { - case inviteText(message: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inviteText(let message): - if boxed { - buffer.appendInt32(415997816) - } - serializeString(message, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inviteText(let message): - return ("inviteText", [("message", message as Any)]) - } - } - - public static func parse_inviteText(_ reader: BufferReader) -> InviteText? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.help.InviteText.inviteText(message: _1!) - } - - } -} -public extension Api.help { - enum PassportConfig: TypeConstructorDescription { - case passportConfig(hash: Int32, countriesLangs: Api.DataJSON) - case passportConfigNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .passportConfig(let hash, let countriesLangs): - if boxed { - buffer.appendInt32(-1600596305) - } - serializeInt32(hash, buffer: buffer, boxed: false) - countriesLangs.serialize(buffer, true) - break - case .passportConfigNotModified: - if boxed { - buffer.appendInt32(-1078332329) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .passportConfig(let hash, let countriesLangs): - return ("passportConfig", [("hash", hash as Any), ("countriesLangs", countriesLangs as Any)]) - case .passportConfigNotModified: - return ("passportConfigNotModified", []) - } - } - - public static func parse_passportConfig(_ reader: BufferReader) -> PassportConfig? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.DataJSON? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.DataJSON + if Int(_1!) & Int(1 << 0) != 0 { + _2 = parseString(reader) } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.help.PassportConfig.passportConfig(hash: _1!, countriesLangs: _2!) - } - public static func parse_passportConfigNotModified(_ reader: BufferReader) -> PassportConfig? { - return Api.help.PassportConfig.passportConfigNotModified - } - - } -} -public extension Api.help { - enum PeerColorOption: TypeConstructorDescription { - case peerColorOption(flags: Int32, colorId: Int32, colors: Api.help.PeerColorSet?, darkColors: Api.help.PeerColorSet?, channelMinLevel: Int32?, groupMinLevel: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .peerColorOption(let flags, let colorId, let colors, let darkColors, let channelMinLevel, let groupMinLevel): - if boxed { - buffer.appendInt32(-1377014082) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(colorId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {colors!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {darkColors!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(channelMinLevel!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(groupMinLevel!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .peerColorOption(let flags, let colorId, let colors, let darkColors, let channelMinLevel, let groupMinLevel): - return ("peerColorOption", [("flags", flags as Any), ("colorId", colorId as Any), ("colors", colors as Any), ("darkColors", darkColors as Any), ("channelMinLevel", channelMinLevel as Any), ("groupMinLevel", groupMinLevel as Any)]) - } - } - - public static func parse_peerColorOption(_ reader: BufferReader) -> PeerColorOption? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Api.help.PeerColorSet? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.help.PeerColorSet - } } - var _4: Api.help.PeerColorSet? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.help.PeerColorSet - } } - var _5: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_5 = reader.readInt32() } - var _6: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_6 = reader.readInt32() } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 3) == 0) || _5 != nil - let _c6 = (Int(_1!) & Int(1 << 4) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.help.PeerColorOption.peerColorOption(flags: _1!, colorId: _2!, colors: _3, darkColors: _4, channelMinLevel: _5, groupMinLevel: _6) - } - - } -} -public extension Api.help { - enum PeerColorSet: TypeConstructorDescription { - case peerColorProfileSet(paletteColors: [Int32], bgColors: [Int32], storyColors: [Int32]) - case peerColorSet(colors: [Int32]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .peerColorProfileSet(let paletteColors, let bgColors, let storyColors): - if boxed { - buffer.appendInt32(1987928555) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(paletteColors.count)) - for item in paletteColors { - serializeInt32(item, buffer: buffer, boxed: false) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(bgColors.count)) - for item in bgColors { - serializeInt32(item, buffer: buffer, boxed: false) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(storyColors.count)) - for item in storyColors { - serializeInt32(item, buffer: buffer, boxed: false) - } - break - case .peerColorSet(let colors): - if boxed { - buffer.appendInt32(639736408) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(colors.count)) - for item in colors { - serializeInt32(item, buffer: buffer, boxed: false) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .peerColorProfileSet(let paletteColors, let bgColors, let storyColors): - return ("peerColorProfileSet", [("paletteColors", paletteColors as Any), ("bgColors", bgColors as Any), ("storyColors", storyColors as Any)]) - case .peerColorSet(let colors): - return ("peerColorSet", [("colors", colors as Any)]) - } - } - - public static func parse_peerColorProfileSet(_ reader: BufferReader) -> PeerColorSet? { - var _1: [Int32]? + var _3: [Api.User]? if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - var _2: [Int32]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - var _3: [Int32]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } let _c1 = _1 != nil - let _c2 = _2 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.help.PeerColorSet.peerColorProfileSet(paletteColors: _1!, bgColors: _2!, storyColors: _3!) - } - public static func parse_peerColorSet(_ reader: BufferReader) -> PeerColorSet? { - var _1: [Int32]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + if _c1 && _c2 && _c3 { + return Api.bots.PopularAppBots.popularAppBots(Cons_popularAppBots(flags: _1!, nextOffset: _2, users: _3!)) + } + else { + return nil } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.help.PeerColorSet.peerColorSet(colors: _1!) } - } } -public extension Api.help { - enum PeerColors: TypeConstructorDescription { - case peerColors(hash: Int32, colors: [Api.help.PeerColorOption]) - case peerColorsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .peerColors(let hash, let colors): - if boxed { - buffer.appendInt32(16313608) - } - serializeInt32(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(colors.count)) - for item in colors { - item.serialize(buffer, true) - } - break - case .peerColorsNotModified: - if boxed { - buffer.appendInt32(732034510) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .peerColors(let hash, let colors): - return ("peerColors", [("hash", hash as Any), ("colors", colors as Any)]) - case .peerColorsNotModified: - return ("peerColorsNotModified", []) - } - } - - public static func parse_peerColors(_ reader: BufferReader) -> PeerColors? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.help.PeerColorOption]? +public extension Api.bots { + enum PreviewInfo: TypeConstructorDescription { + public class Cons_previewInfo { + public var media: [Api.BotPreviewMedia] + public var langCodes: [String] + public init(media: [Api.BotPreviewMedia], langCodes: [String]) { + self.media = media + self.langCodes = langCodes + } + } + case previewInfo(Cons_previewInfo) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .previewInfo(let _data): + if boxed { + buffer.appendInt32(212278628) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.media.count)) + for item in _data.media { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.langCodes.count)) + for item in _data.langCodes { + serializeString(item, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .previewInfo(let _data): + return ("previewInfo", [("media", _data.media as Any), ("langCodes", _data.langCodes as Any)]) + } + } + + public static func parse_previewInfo(_ reader: BufferReader) -> PreviewInfo? { + var _1: [Api.BotPreviewMedia]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.help.PeerColorOption.self) + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.BotPreviewMedia.self) + } + var _2: [String]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.help.PeerColors.peerColors(hash: _1!, colors: _2!) + if _c1 && _c2 { + return Api.bots.PreviewInfo.previewInfo(Cons_previewInfo(media: _1!, langCodes: _2!)) + } + else { + return nil + } } - public static func parse_peerColorsNotModified(_ reader: BufferReader) -> PeerColors? { - return Api.help.PeerColors.peerColorsNotModified - } - } } -public extension Api.help { - enum PremiumPromo: TypeConstructorDescription { - case premiumPromo(statusText: String, statusEntities: [Api.MessageEntity], videoSections: [String], videos: [Api.Document], periodOptions: [Api.PremiumSubscriptionOption], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .premiumPromo(let statusText, let statusEntities, let videoSections, let videos, let periodOptions, let users): - if boxed { - buffer.appendInt32(1395946908) - } - serializeString(statusText, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(statusEntities.count)) - for item in statusEntities { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(videoSections.count)) - for item in videoSections { - serializeString(item, buffer: buffer, boxed: false) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(videos.count)) - for item in videos { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(periodOptions.count)) - for item in periodOptions { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .premiumPromo(let statusText, let statusEntities, let videoSections, let videos, let periodOptions, let users): - return ("premiumPromo", [("statusText", statusText as Any), ("statusEntities", statusEntities as Any), ("videoSections", videoSections as Any), ("videos", videos as Any), ("periodOptions", periodOptions as Any), ("users", users as Any)]) - } - } - - public static func parse_premiumPromo(_ reader: BufferReader) -> PremiumPromo? { - var _1: String? - _1 = parseString(reader) - var _2: [Api.MessageEntity]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) +public extension Api.channels { + enum AdminLogResults: TypeConstructorDescription { + public class Cons_adminLogResults { + public var events: [Api.ChannelAdminLogEvent] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(events: [Api.ChannelAdminLogEvent], chats: [Api.Chat], users: [Api.User]) { + self.events = events + self.chats = chats + self.users = users } - var _3: [String]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) - } - var _4: [Api.Document]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) - } - var _5: [Api.PremiumSubscriptionOption]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PremiumSubscriptionOption.self) - } - var _6: [Api.User]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.help.PremiumPromo.premiumPromo(statusText: _1!, statusEntities: _2!, videoSections: _3!, videos: _4!, periodOptions: _5!, users: _6!) } - - } -} -public extension Api.help { - enum PromoData: TypeConstructorDescription { - case promoData(flags: Int32, expires: Int32, peer: Api.Peer?, psaType: String?, psaMessage: String?, pendingSuggestions: [String], dismissedSuggestions: [String], customPendingSuggestion: Api.PendingSuggestion?, chats: [Api.Chat], users: [Api.User]) - case promoDataEmpty(expires: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .promoData(let flags, let expires, let peer, let psaType, let psaMessage, let pendingSuggestions, let dismissedSuggestions, let customPendingSuggestion, let chats, let users): - if boxed { - buffer.appendInt32(145021050) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(expires, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {peer!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(psaType!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(psaMessage!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(pendingSuggestions.count)) - for item in pendingSuggestions { - serializeString(item, buffer: buffer, boxed: false) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(dismissedSuggestions.count)) - for item in dismissedSuggestions { - serializeString(item, buffer: buffer, boxed: false) - } - if Int(flags) & Int(1 << 4) != 0 {customPendingSuggestion!.serialize(buffer, true)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .promoDataEmpty(let expires): - if boxed { - buffer.appendInt32(-1728664459) - } - serializeInt32(expires, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .promoData(let flags, let expires, let peer, let psaType, let psaMessage, let pendingSuggestions, let dismissedSuggestions, let customPendingSuggestion, let chats, let users): - return ("promoData", [("flags", flags as Any), ("expires", expires as Any), ("peer", peer as Any), ("psaType", psaType as Any), ("psaMessage", psaMessage as Any), ("pendingSuggestions", pendingSuggestions as Any), ("dismissedSuggestions", dismissedSuggestions as Any), ("customPendingSuggestion", customPendingSuggestion as Any), ("chats", chats as Any), ("users", users as Any)]) - case .promoDataEmpty(let expires): - return ("promoDataEmpty", [("expires", expires as Any)]) - } - } - - public static func parse_promoData(_ reader: BufferReader) -> PromoData? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Api.Peer? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Peer - } } - var _4: String? - if Int(_1!) & Int(1 << 1) != 0 {_4 = parseString(reader) } - var _5: String? - if Int(_1!) & Int(1 << 2) != 0 {_5 = parseString(reader) } - var _6: [String]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) + case adminLogResults(Cons_adminLogResults) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .adminLogResults(let _data): + if boxed { + buffer.appendInt32(-309659827) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.events.count)) + for item in _data.events { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break } - var _7: [String]? - if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) - } - var _8: Api.PendingSuggestion? - if Int(_1!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.PendingSuggestion - } } - var _9: [Api.Chat]? - if let _ = reader.readInt32() { - _9 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _10: [Api.User]? - if let _ = reader.readInt32() { - _10 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 3) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 2) == 0) || _5 != nil - let _c6 = _6 != nil - let _c7 = _7 != nil - let _c8 = (Int(_1!) & Int(1 << 4) == 0) || _8 != nil - let _c9 = _9 != nil - let _c10 = _10 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - return Api.help.PromoData.promoData(flags: _1!, expires: _2!, peer: _3, psaType: _4, psaMessage: _5, pendingSuggestions: _6!, dismissedSuggestions: _7!, customPendingSuggestion: _8, chats: _9!, users: _10!) } - public static func parse_promoDataEmpty(_ reader: BufferReader) -> PromoData? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.help.PromoData.promoDataEmpty(expires: _1!) + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .adminLogResults(let _data): + return ("adminLogResults", [("events", _data.events as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } } - - } -} -public extension Api.help { - enum RecentMeUrls: TypeConstructorDescription { - case recentMeUrls(urls: [Api.RecentMeUrl], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .recentMeUrls(let urls, let chats, let users): - if boxed { - buffer.appendInt32(235081943) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(urls.count)) - for item in urls { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .recentMeUrls(let urls, let chats, let users): - return ("recentMeUrls", [("urls", urls as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_recentMeUrls(_ reader: BufferReader) -> RecentMeUrls? { - var _1: [Api.RecentMeUrl]? + + public static func parse_adminLogResults(_ reader: BufferReader) -> AdminLogResults? { + var _1: [Api.ChannelAdminLogEvent]? if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.RecentMeUrl.self) + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ChannelAdminLogEvent.self) } var _2: [Api.Chat]? if let _ = reader.readInt32() { @@ -860,449 +235,1482 @@ public extension Api.help { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.help.RecentMeUrls.recentMeUrls(urls: _1!, chats: _2!, users: _3!) + if _c1 && _c2 && _c3 { + return Api.channels.AdminLogResults.adminLogResults(Cons_adminLogResults(events: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } } - } } -public extension Api.help { - enum Support: TypeConstructorDescription { - case support(phoneNumber: String, user: Api.User) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .support(let phoneNumber, let user): - if boxed { - buffer.appendInt32(398898678) - } - serializeString(phoneNumber, buffer: buffer, boxed: false) - user.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .support(let phoneNumber, let user): - return ("support", [("phoneNumber", phoneNumber as Any), ("user", user as Any)]) - } - } - - public static func parse_support(_ reader: BufferReader) -> Support? { - var _1: String? - _1 = parseString(reader) - var _2: Api.User? +public extension Api.channels { + enum ChannelParticipant: TypeConstructorDescription { + public class Cons_channelParticipant { + public var participant: Api.ChannelParticipant + public var chats: [Api.Chat] + public var users: [Api.User] + public init(participant: Api.ChannelParticipant, chats: [Api.Chat], users: [Api.User]) { + self.participant = participant + self.chats = chats + self.users = users + } + } + case channelParticipant(Cons_channelParticipant) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .channelParticipant(let _data): + if boxed { + buffer.appendInt32(-541588713) + } + _data.participant.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .channelParticipant(let _data): + return ("channelParticipant", [("participant", _data.participant as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_channelParticipant(_ reader: BufferReader) -> ChannelParticipant? { + var _1: Api.ChannelParticipant? if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.User + _1 = Api.parse(reader, signature: signature) as? Api.ChannelParticipant + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.help.Support.support(phoneNumber: _1!, user: _2!) + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.channels.ChannelParticipant.channelParticipant(Cons_channelParticipant(participant: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } } - } } -public extension Api.help { - enum SupportName: TypeConstructorDescription { - case supportName(name: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .supportName(let name): - if boxed { - buffer.appendInt32(-1945767479) - } - serializeString(name, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .supportName(let name): - return ("supportName", [("name", name as Any)]) - } - } - - public static func parse_supportName(_ reader: BufferReader) -> SupportName? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.help.SupportName.supportName(name: _1!) +public extension Api.channels { + enum ChannelParticipants: TypeConstructorDescription { + public class Cons_channelParticipants { + public var count: Int32 + public var participants: [Api.ChannelParticipant] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(count: Int32, participants: [Api.ChannelParticipant], chats: [Api.Chat], users: [Api.User]) { + self.count = count + self.participants = participants + self.chats = chats + self.users = users + } } - - } -} -public extension Api.help { - enum TermsOfService: TypeConstructorDescription { - case termsOfService(flags: Int32, id: Api.DataJSON, text: String, entities: [Api.MessageEntity], minAgeConfirm: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .termsOfService(let flags, let id, let text, let entities, let minAgeConfirm): - if boxed { - buffer.appendInt32(2013922064) - } - serializeInt32(flags, buffer: buffer, boxed: false) - id.serialize(buffer, true) - serializeString(text, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities.count)) - for item in entities { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(minAgeConfirm!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .termsOfService(let flags, let id, let text, let entities, let minAgeConfirm): - return ("termsOfService", [("flags", flags as Any), ("id", id as Any), ("text", text as Any), ("entities", entities as Any), ("minAgeConfirm", minAgeConfirm as Any)]) - } - } - - public static func parse_termsOfService(_ reader: BufferReader) -> TermsOfService? { + case channelParticipants(Cons_channelParticipants) + case channelParticipantsNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .channelParticipants(let _data): + if boxed { + buffer.appendInt32(-1699676497) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.participants.count)) + for item in _data.participants { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .channelParticipantsNotModified: + if boxed { + buffer.appendInt32(-266911767) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .channelParticipants(let _data): + return ("channelParticipants", [("count", _data.count as Any), ("participants", _data.participants as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + case .channelParticipantsNotModified: + return ("channelParticipantsNotModified", []) + } + } + + public static func parse_channelParticipants(_ reader: BufferReader) -> ChannelParticipants? { var _1: Int32? _1 = reader.readInt32() - var _2: Api.DataJSON? + var _2: [Api.ChannelParticipant]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ChannelParticipant.self) + } + var _3: [Api.Chat]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _4: [Api.User]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.channels.ChannelParticipants.channelParticipants(Cons_channelParticipants(count: _1!, participants: _2!, chats: _3!, users: _4!)) + } + else { + return nil + } + } + public static func parse_channelParticipantsNotModified(_ reader: BufferReader) -> ChannelParticipants? { + return Api.channels.ChannelParticipants.channelParticipantsNotModified + } + } +} +public extension Api.channels { + enum SendAsPeers: TypeConstructorDescription { + public class Cons_sendAsPeers { + public var peers: [Api.SendAsPeer] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(peers: [Api.SendAsPeer], chats: [Api.Chat], users: [Api.User]) { + self.peers = peers + self.chats = chats + self.users = users + } + } + case sendAsPeers(Cons_sendAsPeers) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .sendAsPeers(let _data): + if boxed { + buffer.appendInt32(-191450938) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.peers.count)) + for item in _data.peers { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .sendAsPeers(let _data): + return ("sendAsPeers", [("peers", _data.peers as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_sendAsPeers(_ reader: BufferReader) -> SendAsPeers? { + var _1: [Api.SendAsPeer]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SendAsPeer.self) + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.channels.SendAsPeers.sendAsPeers(Cons_sendAsPeers(peers: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.channels { + enum SponsoredMessageReportResult: TypeConstructorDescription { + public class Cons_sponsoredMessageReportResultChooseOption { + public var title: String + public var options: [Api.SponsoredMessageReportOption] + public init(title: String, options: [Api.SponsoredMessageReportOption]) { + self.title = title + self.options = options + } + } + case sponsoredMessageReportResultAdsHidden + case sponsoredMessageReportResultChooseOption(Cons_sponsoredMessageReportResultChooseOption) + case sponsoredMessageReportResultReported + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .sponsoredMessageReportResultAdsHidden: + if boxed { + buffer.appendInt32(1044107055) + } + break + case .sponsoredMessageReportResultChooseOption(let _data): + if boxed { + buffer.appendInt32(-2073059774) + } + serializeString(_data.title, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.options.count)) + for item in _data.options { + item.serialize(buffer, true) + } + break + case .sponsoredMessageReportResultReported: + if boxed { + buffer.appendInt32(-1384544183) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .sponsoredMessageReportResultAdsHidden: + return ("sponsoredMessageReportResultAdsHidden", []) + case .sponsoredMessageReportResultChooseOption(let _data): + return ("sponsoredMessageReportResultChooseOption", [("title", _data.title as Any), ("options", _data.options as Any)]) + case .sponsoredMessageReportResultReported: + return ("sponsoredMessageReportResultReported", []) + } + } + + public static func parse_sponsoredMessageReportResultAdsHidden(_ reader: BufferReader) -> SponsoredMessageReportResult? { + return Api.channels.SponsoredMessageReportResult.sponsoredMessageReportResultAdsHidden + } + public static func parse_sponsoredMessageReportResultChooseOption(_ reader: BufferReader) -> SponsoredMessageReportResult? { + var _1: String? + _1 = parseString(reader) + var _2: [Api.SponsoredMessageReportOption]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SponsoredMessageReportOption.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.channels.SponsoredMessageReportResult.sponsoredMessageReportResultChooseOption(Cons_sponsoredMessageReportResultChooseOption(title: _1!, options: _2!)) + } + else { + return nil + } + } + public static func parse_sponsoredMessageReportResultReported(_ reader: BufferReader) -> SponsoredMessageReportResult? { + return Api.channels.SponsoredMessageReportResult.sponsoredMessageReportResultReported + } + } +} +public extension Api.chatlists { + enum ChatlistInvite: TypeConstructorDescription { + public class Cons_chatlistInvite { + public var flags: Int32 + public var title: Api.TextWithEntities + public var emoticon: String? + public var peers: [Api.Peer] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, title: Api.TextWithEntities, emoticon: String?, peers: [Api.Peer], chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.title = title + self.emoticon = emoticon + self.peers = peers + self.chats = chats + self.users = users + } + } + public class Cons_chatlistInviteAlready { + public var filterId: Int32 + public var missingPeers: [Api.Peer] + public var alreadyPeers: [Api.Peer] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(filterId: Int32, missingPeers: [Api.Peer], alreadyPeers: [Api.Peer], chats: [Api.Chat], users: [Api.User]) { + self.filterId = filterId + self.missingPeers = missingPeers + self.alreadyPeers = alreadyPeers + self.chats = chats + self.users = users + } + } + case chatlistInvite(Cons_chatlistInvite) + case chatlistInviteAlready(Cons_chatlistInviteAlready) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatlistInvite(let _data): + if boxed { + buffer.appendInt32(-250687953) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.title.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.emoticon!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.peers.count)) + for item in _data.peers { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .chatlistInviteAlready(let _data): + if boxed { + buffer.appendInt32(-91752871) + } + serializeInt32(_data.filterId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.missingPeers.count)) + for item in _data.missingPeers { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.alreadyPeers.count)) + for item in _data.alreadyPeers { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatlistInvite(let _data): + return ("chatlistInvite", [("flags", _data.flags as Any), ("title", _data.title as Any), ("emoticon", _data.emoticon as Any), ("peers", _data.peers as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + case .chatlistInviteAlready(let _data): + return ("chatlistInviteAlready", [("filterId", _data.filterId as Any), ("missingPeers", _data.missingPeers as Any), ("alreadyPeers", _data.alreadyPeers as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_chatlistInvite(_ reader: BufferReader) -> ChatlistInvite? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.TextWithEntities? if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.DataJSON + _2 = Api.parse(reader, signature: signature) as? Api.TextWithEntities } var _3: String? - _3 = parseString(reader) - var _4: [Api.MessageEntity]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + if Int(_1!) & Int(1 << 0) != 0 { + _3 = parseString(reader) + } + var _4: [Api.Peer]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) + } + var _5: [Api.Chat]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _6: [Api.User]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.chatlists.ChatlistInvite.chatlistInvite(Cons_chatlistInvite(flags: _1!, title: _2!, emoticon: _3, peers: _4!, chats: _5!, users: _6!)) + } + else { + return nil + } + } + public static func parse_chatlistInviteAlready(_ reader: BufferReader) -> ChatlistInvite? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.Peer]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) + } + var _3: [Api.Peer]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) + } + var _4: [Api.Chat]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _5: [Api.User]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } - var _5: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_5 = reader.readInt32() } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.help.TermsOfService.termsOfService(flags: _1!, id: _2!, text: _3!, entities: _4!, minAgeConfirm: _5) + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.chatlists.ChatlistInvite.chatlistInviteAlready(Cons_chatlistInviteAlready(filterId: _1!, missingPeers: _2!, alreadyPeers: _3!, chats: _4!, users: _5!)) + } + else { + return nil + } } - } } -public extension Api.help { - enum TermsOfServiceUpdate: TypeConstructorDescription { - case termsOfServiceUpdate(expires: Int32, termsOfService: Api.help.TermsOfService) - case termsOfServiceUpdateEmpty(expires: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .termsOfServiceUpdate(let expires, let termsOfService): - if boxed { - buffer.appendInt32(686618977) - } - serializeInt32(expires, buffer: buffer, boxed: false) - termsOfService.serialize(buffer, true) - break - case .termsOfServiceUpdateEmpty(let expires): - if boxed { - buffer.appendInt32(-483352705) - } - serializeInt32(expires, buffer: buffer, boxed: false) - break +public extension Api.chatlists { + enum ChatlistUpdates: TypeConstructorDescription { + public class Cons_chatlistUpdates { + public var missingPeers: [Api.Peer] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(missingPeers: [Api.Peer], chats: [Api.Chat], users: [Api.User]) { + self.missingPeers = missingPeers + self.chats = chats + self.users = users + } + } + case chatlistUpdates(Cons_chatlistUpdates) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatlistUpdates(let _data): + if boxed { + buffer.appendInt32(-1816295539) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.missingPeers.count)) + for item in _data.missingPeers { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatlistUpdates(let _data): + return ("chatlistUpdates", [("missingPeers", _data.missingPeers as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_chatlistUpdates(_ reader: BufferReader) -> ChatlistUpdates? { + var _1: [Api.Peer]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.chatlists.ChatlistUpdates.chatlistUpdates(Cons_chatlistUpdates(missingPeers: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } + } } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .termsOfServiceUpdate(let expires, let termsOfService): - return ("termsOfServiceUpdate", [("expires", expires as Any), ("termsOfService", termsOfService as Any)]) - case .termsOfServiceUpdateEmpty(let expires): - return ("termsOfServiceUpdateEmpty", [("expires", expires as Any)]) - } - } - - public static func parse_termsOfServiceUpdate(_ reader: BufferReader) -> TermsOfServiceUpdate? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.help.TermsOfService? +} +public extension Api.chatlists { + enum ExportedChatlistInvite: TypeConstructorDescription { + public class Cons_exportedChatlistInvite { + public var filter: Api.DialogFilter + public var invite: Api.ExportedChatlistInvite + public init(filter: Api.DialogFilter, invite: Api.ExportedChatlistInvite) { + self.filter = filter + self.invite = invite + } + } + case exportedChatlistInvite(Cons_exportedChatlistInvite) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .exportedChatlistInvite(let _data): + if boxed { + buffer.appendInt32(283567014) + } + _data.filter.serialize(buffer, true) + _data.invite.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .exportedChatlistInvite(let _data): + return ("exportedChatlistInvite", [("filter", _data.filter as Any), ("invite", _data.invite as Any)]) + } + } + + public static func parse_exportedChatlistInvite(_ reader: BufferReader) -> ExportedChatlistInvite? { + var _1: Api.DialogFilter? if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.help.TermsOfService + _1 = Api.parse(reader, signature: signature) as? Api.DialogFilter + } + var _2: Api.ExportedChatlistInvite? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.ExportedChatlistInvite } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.help.TermsOfServiceUpdate.termsOfServiceUpdate(expires: _1!, termsOfService: _2!) + if _c1 && _c2 { + return Api.chatlists.ExportedChatlistInvite.exportedChatlistInvite(Cons_exportedChatlistInvite(filter: _1!, invite: _2!)) + } + else { + return nil + } } - public static func parse_termsOfServiceUpdateEmpty(_ reader: BufferReader) -> TermsOfServiceUpdate? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.help.TermsOfServiceUpdate.termsOfServiceUpdateEmpty(expires: _1!) - } - } } -public extension Api.help { - enum TimezonesList: TypeConstructorDescription { - case timezonesList(timezones: [Api.Timezone], hash: Int32) - case timezonesListNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .timezonesList(let timezones, let hash): - if boxed { - buffer.appendInt32(2071260529) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(timezones.count)) - for item in timezones { - item.serialize(buffer, true) - } - serializeInt32(hash, buffer: buffer, boxed: false) - break - case .timezonesListNotModified: - if boxed { - buffer.appendInt32(-1761146676) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .timezonesList(let timezones, let hash): - return ("timezonesList", [("timezones", timezones as Any), ("hash", hash as Any)]) - case .timezonesListNotModified: - return ("timezonesListNotModified", []) - } - } - - public static func parse_timezonesList(_ reader: BufferReader) -> TimezonesList? { - var _1: [Api.Timezone]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Timezone.self) +public extension Api.chatlists { + enum ExportedInvites: TypeConstructorDescription { + public class Cons_exportedInvites { + public var invites: [Api.ExportedChatlistInvite] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(invites: [Api.ExportedChatlistInvite], chats: [Api.Chat], users: [Api.User]) { + self.invites = invites + self.chats = chats + self.users = users } - var _2: Int32? - _2 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.help.TimezonesList.timezonesList(timezones: _1!, hash: _2!) } - public static func parse_timezonesListNotModified(_ reader: BufferReader) -> TimezonesList? { - return Api.help.TimezonesList.timezonesListNotModified - } - - } -} -public extension Api.help { - enum UserInfo: TypeConstructorDescription { - case userInfo(message: String, entities: [Api.MessageEntity], author: String, date: Int32) - case userInfoEmpty - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .userInfo(let message, let entities, let author, let date): - if boxed { - buffer.appendInt32(32192344) - } - serializeString(message, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities.count)) - for item in entities { - item.serialize(buffer, true) - } - serializeString(author, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - break - case .userInfoEmpty: - if boxed { - buffer.appendInt32(-206688531) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .userInfo(let message, let entities, let author, let date): - return ("userInfo", [("message", message as Any), ("entities", entities as Any), ("author", author as Any), ("date", date as Any)]) - case .userInfoEmpty: - return ("userInfoEmpty", []) - } - } - - public static func parse_userInfo(_ reader: BufferReader) -> UserInfo? { - var _1: String? - _1 = parseString(reader) - var _2: [Api.MessageEntity]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + case exportedInvites(Cons_exportedInvites) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .exportedInvites(let _data): + if boxed { + buffer.appendInt32(279670215) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.invites.count)) + for item in _data.invites { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .exportedInvites(let _data): + return ("exportedInvites", [("invites", _data.invites as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_exportedInvites(_ reader: BufferReader) -> ExportedInvites? { + var _1: [Api.ExportedChatlistInvite]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ExportedChatlistInvite.self) + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } - var _3: String? - _3 = parseString(reader) - var _4: Int32? - _4 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.help.UserInfo.userInfo(message: _1!, entities: _2!, author: _3!, date: _4!) + if _c1 && _c2 && _c3 { + return Api.chatlists.ExportedInvites.exportedInvites(Cons_exportedInvites(invites: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } } - public static func parse_userInfoEmpty(_ reader: BufferReader) -> UserInfo? { - return Api.help.UserInfo.userInfoEmpty - } - } } -public extension Api.messages { - enum AffectedFoundMessages: TypeConstructorDescription { - case affectedFoundMessages(pts: Int32, ptsCount: Int32, offset: Int32, messages: [Int32]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .affectedFoundMessages(let pts, let ptsCount, let offset, let messages): - if boxed { - buffer.appendInt32(-275956116) - } - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - serializeInt32(offset, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - serializeInt32(item, buffer: buffer, boxed: false) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .affectedFoundMessages(let pts, let ptsCount, let offset, let messages): - return ("affectedFoundMessages", [("pts", pts as Any), ("ptsCount", ptsCount as Any), ("offset", offset as Any), ("messages", messages as Any)]) - } - } - - public static func parse_affectedFoundMessages(_ reader: BufferReader) -> AffectedFoundMessages? { +public extension Api.contacts { + enum Blocked: TypeConstructorDescription { + public class Cons_blocked { + public var blocked: [Api.PeerBlocked] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(blocked: [Api.PeerBlocked], chats: [Api.Chat], users: [Api.User]) { + self.blocked = blocked + self.chats = chats + self.users = users + } + } + public class Cons_blockedSlice { + public var count: Int32 + public var blocked: [Api.PeerBlocked] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(count: Int32, blocked: [Api.PeerBlocked], chats: [Api.Chat], users: [Api.User]) { + self.count = count + self.blocked = blocked + self.chats = chats + self.users = users + } + } + case blocked(Cons_blocked) + case blockedSlice(Cons_blockedSlice) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .blocked(let _data): + if boxed { + buffer.appendInt32(182326673) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.blocked.count)) + for item in _data.blocked { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .blockedSlice(let _data): + if boxed { + buffer.appendInt32(-513392236) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.blocked.count)) + for item in _data.blocked { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .blocked(let _data): + return ("blocked", [("blocked", _data.blocked as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + case .blockedSlice(let _data): + return ("blockedSlice", [("count", _data.count as Any), ("blocked", _data.blocked as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_blocked(_ reader: BufferReader) -> Blocked? { + var _1: [Api.PeerBlocked]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PeerBlocked.self) + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.contacts.Blocked.blocked(Cons_blocked(blocked: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } + } + public static func parse_blockedSlice(_ reader: BufferReader) -> Blocked? { var _1: Int32? _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - var _4: [Int32]? + var _2: [Api.PeerBlocked]? if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PeerBlocked.self) + } + var _3: [Api.Chat]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _4: [Api.User]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.messages.AffectedFoundMessages.affectedFoundMessages(pts: _1!, ptsCount: _2!, offset: _3!, messages: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.contacts.Blocked.blockedSlice(Cons_blockedSlice(count: _1!, blocked: _2!, chats: _3!, users: _4!)) + } + else { + return nil + } } - } } -public extension Api.messages { - enum AffectedHistory: TypeConstructorDescription { - case affectedHistory(pts: Int32, ptsCount: Int32, offset: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .affectedHistory(let pts, let ptsCount, let offset): - if boxed { - buffer.appendInt32(-1269012015) - } - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - serializeInt32(offset, buffer: buffer, boxed: false) - break +public extension Api.contacts { + enum ContactBirthdays: TypeConstructorDescription { + public class Cons_contactBirthdays { + public var contacts: [Api.ContactBirthday] + public var users: [Api.User] + public init(contacts: [Api.ContactBirthday], users: [Api.User]) { + self.contacts = contacts + self.users = users + } + } + case contactBirthdays(Cons_contactBirthdays) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .contactBirthdays(let _data): + if boxed { + buffer.appendInt32(290452237) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.contacts.count)) + for item in _data.contacts { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .contactBirthdays(let _data): + return ("contactBirthdays", [("contacts", _data.contacts as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_contactBirthdays(_ reader: BufferReader) -> ContactBirthdays? { + var _1: [Api.ContactBirthday]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ContactBirthday.self) + } + var _2: [Api.User]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.contacts.ContactBirthdays.contactBirthdays(Cons_contactBirthdays(contacts: _1!, users: _2!)) + } + else { + return nil + } + } } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .affectedHistory(let pts, let ptsCount, let offset): - return ("affectedHistory", [("pts", pts as Any), ("ptsCount", ptsCount as Any), ("offset", offset as Any)]) - } - } - - public static func parse_affectedHistory(_ reader: BufferReader) -> AffectedHistory? { - var _1: Int32? - _1 = reader.readInt32() +} +public extension Api.contacts { + enum Contacts: TypeConstructorDescription { + public class Cons_contacts { + public var contacts: [Api.Contact] + public var savedCount: Int32 + public var users: [Api.User] + public init(contacts: [Api.Contact], savedCount: Int32, users: [Api.User]) { + self.contacts = contacts + self.savedCount = savedCount + self.users = users + } + } + case contacts(Cons_contacts) + case contactsNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .contacts(let _data): + if boxed { + buffer.appendInt32(-353862078) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.contacts.count)) + for item in _data.contacts { + item.serialize(buffer, true) + } + serializeInt32(_data.savedCount, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .contactsNotModified: + if boxed { + buffer.appendInt32(-1219778094) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .contacts(let _data): + return ("contacts", [("contacts", _data.contacts as Any), ("savedCount", _data.savedCount as Any), ("users", _data.users as Any)]) + case .contactsNotModified: + return ("contactsNotModified", []) + } + } + + public static func parse_contacts(_ reader: BufferReader) -> Contacts? { + var _1: [Api.Contact]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Contact.self) + } var _2: Int32? _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.messages.AffectedHistory.affectedHistory(pts: _1!, ptsCount: _2!, offset: _3!) + if _c1 && _c2 && _c3 { + return Api.contacts.Contacts.contacts(Cons_contacts(contacts: _1!, savedCount: _2!, users: _3!)) + } + else { + return nil + } + } + public static func parse_contactsNotModified(_ reader: BufferReader) -> Contacts? { + return Api.contacts.Contacts.contactsNotModified } - } } -public extension Api.messages { - enum AffectedMessages: TypeConstructorDescription { - case affectedMessages(pts: Int32, ptsCount: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .affectedMessages(let pts, let ptsCount): - if boxed { - buffer.appendInt32(-2066640507) - } - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(ptsCount, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .affectedMessages(let pts, let ptsCount): - return ("affectedMessages", [("pts", pts as Any), ("ptsCount", ptsCount as Any)]) - } - } - - public static func parse_affectedMessages(_ reader: BufferReader) -> AffectedMessages? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() +public extension Api.contacts { + enum Found: TypeConstructorDescription { + public class Cons_found { + public var myResults: [Api.Peer] + public var results: [Api.Peer] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(myResults: [Api.Peer], results: [Api.Peer], chats: [Api.Chat], users: [Api.User]) { + self.myResults = myResults + self.results = results + self.chats = chats + self.users = users + } + } + case found(Cons_found) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .found(let _data): + if boxed { + buffer.appendInt32(-1290580579) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.myResults.count)) + for item in _data.myResults { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.results.count)) + for item in _data.results { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .found(let _data): + return ("found", [("myResults", _data.myResults as Any), ("results", _data.results as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_found(_ reader: BufferReader) -> Found? { + var _1: [Api.Peer]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) + } + var _2: [Api.Peer]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) + } + var _3: [Api.Chat]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _4: [Api.User]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.AffectedMessages.affectedMessages(pts: _1!, ptsCount: _2!) + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.contacts.Found.found(Cons_found(myResults: _1!, results: _2!, chats: _3!, users: _4!)) + } + else { + return nil + } + } + } +} +public extension Api.contacts { + enum ImportedContacts: TypeConstructorDescription { + public class Cons_importedContacts { + public var imported: [Api.ImportedContact] + public var popularInvites: [Api.PopularContact] + public var retryContacts: [Int64] + public var users: [Api.User] + public init(imported: [Api.ImportedContact], popularInvites: [Api.PopularContact], retryContacts: [Int64], users: [Api.User]) { + self.imported = imported + self.popularInvites = popularInvites + self.retryContacts = retryContacts + self.users = users + } + } + case importedContacts(Cons_importedContacts) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .importedContacts(let _data): + if boxed { + buffer.appendInt32(2010127419) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.imported.count)) + for item in _data.imported { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.popularInvites.count)) + for item in _data.popularInvites { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.retryContacts.count)) + for item in _data.retryContacts { + serializeInt64(item, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .importedContacts(let _data): + return ("importedContacts", [("imported", _data.imported as Any), ("popularInvites", _data.popularInvites as Any), ("retryContacts", _data.retryContacts as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_importedContacts(_ reader: BufferReader) -> ImportedContacts? { + var _1: [Api.ImportedContact]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ImportedContact.self) + } + var _2: [Api.PopularContact]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PopularContact.self) + } + var _3: [Int64]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) + } + var _4: [Api.User]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.contacts.ImportedContacts.importedContacts(Cons_importedContacts(imported: _1!, popularInvites: _2!, retryContacts: _3!, users: _4!)) + } + else { + return nil + } + } + } +} +public extension Api.contacts { + enum ResolvedPeer: TypeConstructorDescription { + public class Cons_resolvedPeer { + public var peer: Api.Peer + public var chats: [Api.Chat] + public var users: [Api.User] + public init(peer: Api.Peer, chats: [Api.Chat], users: [Api.User]) { + self.peer = peer + self.chats = chats + self.users = users + } + } + case resolvedPeer(Cons_resolvedPeer) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .resolvedPeer(let _data): + if boxed { + buffer.appendInt32(2131196633) + } + _data.peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .resolvedPeer(let _data): + return ("resolvedPeer", [("peer", _data.peer as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_resolvedPeer(_ reader: BufferReader) -> ResolvedPeer? { + var _1: Api.Peer? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Peer + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.contacts.ResolvedPeer.resolvedPeer(Cons_resolvedPeer(peer: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.contacts { + enum SponsoredPeers: TypeConstructorDescription { + public class Cons_sponsoredPeers { + public var peers: [Api.SponsoredPeer] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(peers: [Api.SponsoredPeer], chats: [Api.Chat], users: [Api.User]) { + self.peers = peers + self.chats = chats + self.users = users + } + } + case sponsoredPeers(Cons_sponsoredPeers) + case sponsoredPeersEmpty + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .sponsoredPeers(let _data): + if boxed { + buffer.appendInt32(-352114556) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.peers.count)) + for item in _data.peers { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .sponsoredPeersEmpty: + if boxed { + buffer.appendInt32(-365775695) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .sponsoredPeers(let _data): + return ("sponsoredPeers", [("peers", _data.peers as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + case .sponsoredPeersEmpty: + return ("sponsoredPeersEmpty", []) + } + } + + public static func parse_sponsoredPeers(_ reader: BufferReader) -> SponsoredPeers? { + var _1: [Api.SponsoredPeer]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SponsoredPeer.self) + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.contacts.SponsoredPeers.sponsoredPeers(Cons_sponsoredPeers(peers: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } + } + public static func parse_sponsoredPeersEmpty(_ reader: BufferReader) -> SponsoredPeers? { + return Api.contacts.SponsoredPeers.sponsoredPeersEmpty + } + } +} +public extension Api.contacts { + enum TopPeers: TypeConstructorDescription { + public class Cons_topPeers { + public var categories: [Api.TopPeerCategoryPeers] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(categories: [Api.TopPeerCategoryPeers], chats: [Api.Chat], users: [Api.User]) { + self.categories = categories + self.chats = chats + self.users = users + } + } + case topPeers(Cons_topPeers) + case topPeersDisabled + case topPeersNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .topPeers(let _data): + if boxed { + buffer.appendInt32(1891070632) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.categories.count)) + for item in _data.categories { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .topPeersDisabled: + if boxed { + buffer.appendInt32(-1255369827) + } + break + case .topPeersNotModified: + if boxed { + buffer.appendInt32(-567906571) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .topPeers(let _data): + return ("topPeers", [("categories", _data.categories as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + case .topPeersDisabled: + return ("topPeersDisabled", []) + case .topPeersNotModified: + return ("topPeersNotModified", []) + } + } + + public static func parse_topPeers(_ reader: BufferReader) -> TopPeers? { + var _1: [Api.TopPeerCategoryPeers]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.TopPeerCategoryPeers.self) + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.contacts.TopPeers.topPeers(Cons_topPeers(categories: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } + } + public static func parse_topPeersDisabled(_ reader: BufferReader) -> TopPeers? { + return Api.contacts.TopPeers.topPeersDisabled + } + public static func parse_topPeersNotModified(_ reader: BufferReader) -> TopPeers? { + return Api.contacts.TopPeers.topPeersNotModified + } + } +} +public extension Api.fragment { + enum CollectibleInfo: TypeConstructorDescription { + public class Cons_collectibleInfo { + public var purchaseDate: Int32 + public var currency: String + public var amount: Int64 + public var cryptoCurrency: String + public var cryptoAmount: Int64 + public var url: String + public init(purchaseDate: Int32, currency: String, amount: Int64, cryptoCurrency: String, cryptoAmount: Int64, url: String) { + self.purchaseDate = purchaseDate + self.currency = currency + self.amount = amount + self.cryptoCurrency = cryptoCurrency + self.cryptoAmount = cryptoAmount + self.url = url + } + } + case collectibleInfo(Cons_collectibleInfo) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .collectibleInfo(let _data): + if boxed { + buffer.appendInt32(1857945489) + } + serializeInt32(_data.purchaseDate, buffer: buffer, boxed: false) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.amount, buffer: buffer, boxed: false) + serializeString(_data.cryptoCurrency, buffer: buffer, boxed: false) + serializeInt64(_data.cryptoAmount, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .collectibleInfo(let _data): + return ("collectibleInfo", [("purchaseDate", _data.purchaseDate as Any), ("currency", _data.currency as Any), ("amount", _data.amount as Any), ("cryptoCurrency", _data.cryptoCurrency as Any), ("cryptoAmount", _data.cryptoAmount as Any), ("url", _data.url as Any)]) + } + } + + public static func parse_collectibleInfo(_ reader: BufferReader) -> CollectibleInfo? { + var _1: Int32? + _1 = reader.readInt32() + var _2: String? + _2 = parseString(reader) + var _3: Int64? + _3 = reader.readInt64() + var _4: String? + _4 = parseString(reader) + var _5: Int64? + _5 = reader.readInt64() + var _6: String? + _6 = parseString(reader) + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.fragment.CollectibleInfo.collectibleInfo(Cons_collectibleInfo(purchaseDate: _1!, currency: _2!, amount: _3!, cryptoCurrency: _4!, cryptoAmount: _5!, url: _6!)) + } + else { + return nil + } + } + } +} +public extension Api.help { + enum AppConfig: TypeConstructorDescription { + public class Cons_appConfig { + public var hash: Int32 + public var config: Api.JSONValue + public init(hash: Int32, config: Api.JSONValue) { + self.hash = hash + self.config = config + } + } + case appConfig(Cons_appConfig) + case appConfigNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .appConfig(let _data): + if boxed { + buffer.appendInt32(-585598930) + } + serializeInt32(_data.hash, buffer: buffer, boxed: false) + _data.config.serialize(buffer, true) + break + case .appConfigNotModified: + if boxed { + buffer.appendInt32(2094949405) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .appConfig(let _data): + return ("appConfig", [("hash", _data.hash as Any), ("config", _data.config as Any)]) + case .appConfigNotModified: + return ("appConfigNotModified", []) + } + } + + public static func parse_appConfig(_ reader: BufferReader) -> AppConfig? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.JSONValue? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.JSONValue + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.help.AppConfig.appConfig(Cons_appConfig(hash: _1!, config: _2!)) + } + else { + return nil + } + } + public static func parse_appConfigNotModified(_ reader: BufferReader) -> AppConfig? { + return Api.help.AppConfig.appConfigNotModified } - } } diff --git a/submodules/TelegramApi/Sources/Api33.swift b/submodules/TelegramApi/Sources/Api33.swift index 98c550df..c67b56a5 100644 --- a/submodules/TelegramApi/Sources/Api33.swift +++ b/submodules/TelegramApi/Sources/Api33.swift @@ -1,1326 +1,1651 @@ -public extension Api.messages { - enum AllStickers: TypeConstructorDescription { - case allStickers(hash: Int64, sets: [Api.StickerSet]) - case allStickersNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .allStickers(let hash, let sets): - if boxed { - buffer.appendInt32(-843329861) - } - serializeInt64(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(sets.count)) - for item in sets { - item.serialize(buffer, true) - } - break - case .allStickersNotModified: - if boxed { - buffer.appendInt32(-395967805) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .allStickers(let hash, let sets): - return ("allStickers", [("hash", hash as Any), ("sets", sets as Any)]) - case .allStickersNotModified: - return ("allStickersNotModified", []) - } - } - - public static func parse_allStickers(_ reader: BufferReader) -> AllStickers? { - var _1: Int64? - _1 = reader.readInt64() - var _2: [Api.StickerSet]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerSet.self) +public extension Api.help { + enum AppUpdate: TypeConstructorDescription { + public class Cons_appUpdate { + public var flags: Int32 + public var id: Int32 + public var version: String + public var text: String + public var entities: [Api.MessageEntity] + public var document: Api.Document? + public var url: String? + public var sticker: Api.Document? + public init(flags: Int32, id: Int32, version: String, text: String, entities: [Api.MessageEntity], document: Api.Document?, url: String?, sticker: Api.Document?) { + self.flags = flags + self.id = id + self.version = version + self.text = text + self.entities = entities + self.document = document + self.url = url + self.sticker = sticker } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.AllStickers.allStickers(hash: _1!, sets: _2!) } - public static func parse_allStickersNotModified(_ reader: BufferReader) -> AllStickers? { - return Api.messages.AllStickers.allStickersNotModified + case appUpdate(Cons_appUpdate) + case noAppUpdate + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .appUpdate(let _data): + if boxed { + buffer.appendInt32(-860107216) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeString(_data.version, buffer: buffer, boxed: false) + serializeString(_data.text, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities.count)) + for item in _data.entities { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.document!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.url!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.sticker!.serialize(buffer, true) + } + break + case .noAppUpdate: + if boxed { + buffer.appendInt32(-1000708810) + } + break + } } - - } -} -public extension Api.messages { - enum ArchivedStickers: TypeConstructorDescription { - case archivedStickers(count: Int32, sets: [Api.StickerSetCovered]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .archivedStickers(let count, let sets): - if boxed { - buffer.appendInt32(1338747336) - } - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(sets.count)) - for item in sets { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .archivedStickers(let count, let sets): - return ("archivedStickers", [("count", count as Any), ("sets", sets as Any)]) - } - } - - public static func parse_archivedStickers(_ reader: BufferReader) -> ArchivedStickers? { + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .appUpdate(let _data): + return ("appUpdate", [("flags", _data.flags as Any), ("id", _data.id as Any), ("version", _data.version as Any), ("text", _data.text as Any), ("entities", _data.entities as Any), ("document", _data.document as Any), ("url", _data.url as Any), ("sticker", _data.sticker as Any)]) + case .noAppUpdate: + return ("noAppUpdate", []) + } + } + + public static func parse_appUpdate(_ reader: BufferReader) -> AppUpdate? { var _1: Int32? _1 = reader.readInt32() - var _2: [Api.StickerSetCovered]? + var _2: Int32? + _2 = reader.readInt32() + var _3: String? + _3 = parseString(reader) + var _4: String? + _4 = parseString(reader) + var _5: [Api.MessageEntity]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerSetCovered.self) + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.ArchivedStickers.archivedStickers(count: _1!, sets: _2!) - } - - } -} -public extension Api.messages { - enum AvailableEffects: TypeConstructorDescription { - case availableEffects(hash: Int32, effects: [Api.AvailableEffect], documents: [Api.Document]) - case availableEffectsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .availableEffects(let hash, let effects, let documents): - if boxed { - buffer.appendInt32(-1109696146) - } - serializeInt32(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(effects.count)) - for item in effects { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(documents.count)) - for item in documents { - item.serialize(buffer, true) - } - break - case .availableEffectsNotModified: - if boxed { - buffer.appendInt32(-772957605) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .availableEffects(let hash, let effects, let documents): - return ("availableEffects", [("hash", hash as Any), ("effects", effects as Any), ("documents", documents as Any)]) - case .availableEffectsNotModified: - return ("availableEffectsNotModified", []) - } - } - - public static func parse_availableEffects(_ reader: BufferReader) -> AvailableEffects? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.AvailableEffect]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.AvailableEffect.self) + var _6: Api.Document? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.Document + } } - var _3: [Api.Document]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + var _7: String? + if Int(_1!) & Int(1 << 2) != 0 { + _7 = parseString(reader) + } + var _8: Api.Document? + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.Document + } } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.messages.AvailableEffects.availableEffects(hash: _1!, effects: _2!, documents: _3!) - } - public static func parse_availableEffectsNotModified(_ reader: BufferReader) -> AvailableEffects? { - return Api.messages.AvailableEffects.availableEffectsNotModified - } - - } -} -public extension Api.messages { - enum AvailableReactions: TypeConstructorDescription { - case availableReactions(hash: Int32, reactions: [Api.AvailableReaction]) - case availableReactionsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .availableReactions(let hash, let reactions): - if boxed { - buffer.appendInt32(1989032621) - } - serializeInt32(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(reactions.count)) - for item in reactions { - item.serialize(buffer, true) - } - break - case .availableReactionsNotModified: - if boxed { - buffer.appendInt32(-1626924713) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .availableReactions(let hash, let reactions): - return ("availableReactions", [("hash", hash as Any), ("reactions", reactions as Any)]) - case .availableReactionsNotModified: - return ("availableReactionsNotModified", []) - } - } - - public static func parse_availableReactions(_ reader: BufferReader) -> AvailableReactions? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.AvailableReaction]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.AvailableReaction.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.AvailableReactions.availableReactions(hash: _1!, reactions: _2!) - } - public static func parse_availableReactionsNotModified(_ reader: BufferReader) -> AvailableReactions? { - return Api.messages.AvailableReactions.availableReactionsNotModified - } - - } -} -public extension Api.messages { - enum BotApp: TypeConstructorDescription { - case botApp(flags: Int32, app: Api.BotApp) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botApp(let flags, let app): - if boxed { - buffer.appendInt32(-347034123) - } - serializeInt32(flags, buffer: buffer, boxed: false) - app.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botApp(let flags, let app): - return ("botApp", [("flags", flags as Any), ("app", app as Any)]) - } - } - - public static func parse_botApp(_ reader: BufferReader) -> BotApp? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.BotApp? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.BotApp - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.BotApp.botApp(flags: _1!, app: _2!) - } - - } -} -public extension Api.messages { - enum BotCallbackAnswer: TypeConstructorDescription { - case botCallbackAnswer(flags: Int32, message: String?, url: String?, cacheTime: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botCallbackAnswer(let flags, let message, let url, let cacheTime): - if boxed { - buffer.appendInt32(911761060) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(message!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(url!, buffer: buffer, boxed: false)} - serializeInt32(cacheTime, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botCallbackAnswer(let flags, let message, let url, let cacheTime): - return ("botCallbackAnswer", [("flags", flags as Any), ("message", message as Any), ("url", url as Any), ("cacheTime", cacheTime as Any)]) - } - } - - public static func parse_botCallbackAnswer(_ reader: BufferReader) -> BotCallbackAnswer? { - var _1: Int32? - _1 = reader.readInt32() - var _2: String? - if Int(_1!) & Int(1 << 0) != 0 {_2 = parseString(reader) } - var _3: String? - if Int(_1!) & Int(1 << 2) != 0 {_3 = parseString(reader) } - var _4: Int32? - _4 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - let _c3 = (Int(_1!) & Int(1 << 2) == 0) || _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.messages.BotCallbackAnswer.botCallbackAnswer(flags: _1!, message: _2, url: _3, cacheTime: _4!) + let _c5 = _5 != nil + let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil + let _c7 = (Int(_1!) & Int(1 << 2) == 0) || _7 != nil + let _c8 = (Int(_1!) & Int(1 << 3) == 0) || _8 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.help.AppUpdate.appUpdate(Cons_appUpdate(flags: _1!, id: _2!, version: _3!, text: _4!, entities: _5!, document: _6, url: _7, sticker: _8)) + } + else { + return nil + } + } + public static func parse_noAppUpdate(_ reader: BufferReader) -> AppUpdate? { + return Api.help.AppUpdate.noAppUpdate } - } } -public extension Api.messages { - enum BotPreparedInlineMessage: TypeConstructorDescription { - case botPreparedInlineMessage(id: String, expireDate: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botPreparedInlineMessage(let id, let expireDate): - if boxed { - buffer.appendInt32(-1899035375) - } - serializeString(id, buffer: buffer, boxed: false) - serializeInt32(expireDate, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botPreparedInlineMessage(let id, let expireDate): - return ("botPreparedInlineMessage", [("id", id as Any), ("expireDate", expireDate as Any)]) - } - } - - public static func parse_botPreparedInlineMessage(_ reader: BufferReader) -> BotPreparedInlineMessage? { - var _1: String? - _1 = parseString(reader) +public extension Api.help { + enum CountriesList: TypeConstructorDescription { + public class Cons_countriesList { + public var countries: [Api.help.Country] + public var hash: Int32 + public init(countries: [Api.help.Country], hash: Int32) { + self.countries = countries + self.hash = hash + } + } + case countriesList(Cons_countriesList) + case countriesListNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .countriesList(let _data): + if boxed { + buffer.appendInt32(-2016381538) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.countries.count)) + for item in _data.countries { + item.serialize(buffer, true) + } + serializeInt32(_data.hash, buffer: buffer, boxed: false) + break + case .countriesListNotModified: + if boxed { + buffer.appendInt32(-1815339214) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .countriesList(let _data): + return ("countriesList", [("countries", _data.countries as Any), ("hash", _data.hash as Any)]) + case .countriesListNotModified: + return ("countriesListNotModified", []) + } + } + + public static func parse_countriesList(_ reader: BufferReader) -> CountriesList? { + var _1: [Api.help.Country]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.help.Country.self) + } var _2: Int32? _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.BotPreparedInlineMessage.botPreparedInlineMessage(id: _1!, expireDate: _2!) + if _c1 && _c2 { + return Api.help.CountriesList.countriesList(Cons_countriesList(countries: _1!, hash: _2!)) + } + else { + return nil + } + } + public static func parse_countriesListNotModified(_ reader: BufferReader) -> CountriesList? { + return Api.help.CountriesList.countriesListNotModified } - } } -public extension Api.messages { - enum BotResults: TypeConstructorDescription { - case botResults(flags: Int32, queryId: Int64, nextOffset: String?, switchPm: Api.InlineBotSwitchPM?, switchWebview: Api.InlineBotWebView?, results: [Api.BotInlineResult], cacheTime: Int32, users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .botResults(let flags, let queryId, let nextOffset, let switchPm, let switchWebview, let results, let cacheTime, let users): - if boxed { - buffer.appendInt32(-534646026) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(queryId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeString(nextOffset!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {switchPm!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {switchWebview!.serialize(buffer, true)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(results.count)) - for item in results { - item.serialize(buffer, true) - } - serializeInt32(cacheTime, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .botResults(let flags, let queryId, let nextOffset, let switchPm, let switchWebview, let results, let cacheTime, let users): - return ("botResults", [("flags", flags as Any), ("queryId", queryId as Any), ("nextOffset", nextOffset as Any), ("switchPm", switchPm as Any), ("switchWebview", switchWebview as Any), ("results", results as Any), ("cacheTime", cacheTime as Any), ("users", users as Any)]) - } - } - - public static func parse_botResults(_ reader: BufferReader) -> BotResults? { +public extension Api.help { + enum Country: TypeConstructorDescription { + public class Cons_country { + public var flags: Int32 + public var iso2: String + public var defaultName: String + public var name: String? + public var countryCodes: [Api.help.CountryCode] + public init(flags: Int32, iso2: String, defaultName: String, name: String?, countryCodes: [Api.help.CountryCode]) { + self.flags = flags + self.iso2 = iso2 + self.defaultName = defaultName + self.name = name + self.countryCodes = countryCodes + } + } + case country(Cons_country) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .country(let _data): + if boxed { + buffer.appendInt32(-1014526429) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.iso2, buffer: buffer, boxed: false) + serializeString(_data.defaultName, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.name!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.countryCodes.count)) + for item in _data.countryCodes { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .country(let _data): + return ("country", [("flags", _data.flags as Any), ("iso2", _data.iso2 as Any), ("defaultName", _data.defaultName as Any), ("name", _data.name as Any), ("countryCodes", _data.countryCodes as Any)]) + } + } + + public static func parse_country(_ reader: BufferReader) -> Country? { var _1: Int32? _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() + var _2: String? + _2 = parseString(reader) var _3: String? - if Int(_1!) & Int(1 << 1) != 0 {_3 = parseString(reader) } - var _4: Api.InlineBotSwitchPM? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.InlineBotSwitchPM - } } - var _5: Api.InlineBotWebView? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.InlineBotWebView - } } - var _6: [Api.BotInlineResult]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.BotInlineResult.self) + _3 = parseString(reader) + var _4: String? + if Int(_1!) & Int(1 << 1) != 0 { + _4 = parseString(reader) } - var _7: Int32? - _7 = reader.readInt32() - var _8: [Api.User]? + var _5: [Api.help.CountryCode]? if let _ = reader.readInt32() { - _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.help.CountryCode.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.help.Country.country(Cons_country(flags: _1!, iso2: _2!, defaultName: _3!, name: _4, countryCodes: _5!)) + } + else { + return nil + } + } + } +} +public extension Api.help { + enum CountryCode: TypeConstructorDescription { + public class Cons_countryCode { + public var flags: Int32 + public var countryCode: String + public var prefixes: [String]? + public var patterns: [String]? + public init(flags: Int32, countryCode: String, prefixes: [String]?, patterns: [String]?) { + self.flags = flags + self.countryCode = countryCode + self.prefixes = prefixes + self.patterns = patterns + } + } + case countryCode(Cons_countryCode) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .countryCode(let _data): + if boxed { + buffer.appendInt32(1107543535) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.countryCode, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.prefixes!.count)) + for item in _data.prefixes! { + serializeString(item, buffer: buffer, boxed: false) + } + } + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.patterns!.count)) + for item in _data.patterns! { + serializeString(item, buffer: buffer, boxed: false) + } + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .countryCode(let _data): + return ("countryCode", [("flags", _data.flags as Any), ("countryCode", _data.countryCode as Any), ("prefixes", _data.prefixes as Any), ("patterns", _data.patterns as Any)]) + } + } + + public static func parse_countryCode(_ reader: BufferReader) -> CountryCode? { + var _1: Int32? + _1 = reader.readInt32() + var _2: String? + _2 = parseString(reader) + var _3: [String]? + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) + } + } + var _4: [String]? + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) + } + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.help.CountryCode.countryCode(Cons_countryCode(flags: _1!, countryCode: _2!, prefixes: _3, patterns: _4)) + } + else { + return nil + } + } + } +} +public extension Api.help { + enum DeepLinkInfo: TypeConstructorDescription { + public class Cons_deepLinkInfo { + public var flags: Int32 + public var message: String + public var entities: [Api.MessageEntity]? + public init(flags: Int32, message: String, entities: [Api.MessageEntity]?) { + self.flags = flags + self.message = message + self.entities = entities + } + } + case deepLinkInfo(Cons_deepLinkInfo) + case deepLinkInfoEmpty + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .deepLinkInfo(let _data): + if boxed { + buffer.appendInt32(1783556146) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.message, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { + item.serialize(buffer, true) + } + } + break + case .deepLinkInfoEmpty: + if boxed { + buffer.appendInt32(1722786150) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .deepLinkInfo(let _data): + return ("deepLinkInfo", [("flags", _data.flags as Any), ("message", _data.message as Any), ("entities", _data.entities as Any)]) + case .deepLinkInfoEmpty: + return ("deepLinkInfoEmpty", []) + } + } + + public static func parse_deepLinkInfo(_ reader: BufferReader) -> DeepLinkInfo? { + var _1: Int32? + _1 = reader.readInt32() + var _2: String? + _2 = parseString(reader) + var _3: [Api.MessageEntity]? + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil + if _c1 && _c2 && _c3 { + return Api.help.DeepLinkInfo.deepLinkInfo(Cons_deepLinkInfo(flags: _1!, message: _2!, entities: _3)) + } + else { + return nil + } + } + public static func parse_deepLinkInfoEmpty(_ reader: BufferReader) -> DeepLinkInfo? { + return Api.help.DeepLinkInfo.deepLinkInfoEmpty + } + } +} +public extension Api.help { + enum InviteText: TypeConstructorDescription { + public class Cons_inviteText { + public var message: String + public init(message: String) { + self.message = message + } + } + case inviteText(Cons_inviteText) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inviteText(let _data): + if boxed { + buffer.appendInt32(415997816) + } + serializeString(_data.message, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inviteText(let _data): + return ("inviteText", [("message", _data.message as Any)]) + } + } + + public static func parse_inviteText(_ reader: BufferReader) -> InviteText? { + var _1: String? + _1 = parseString(reader) + let _c1 = _1 != nil + if _c1 { + return Api.help.InviteText.inviteText(Cons_inviteText(message: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.help { + enum PassportConfig: TypeConstructorDescription { + public class Cons_passportConfig { + public var hash: Int32 + public var countriesLangs: Api.DataJSON + public init(hash: Int32, countriesLangs: Api.DataJSON) { + self.hash = hash + self.countriesLangs = countriesLangs + } + } + case passportConfig(Cons_passportConfig) + case passportConfigNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .passportConfig(let _data): + if boxed { + buffer.appendInt32(-1600596305) + } + serializeInt32(_data.hash, buffer: buffer, boxed: false) + _data.countriesLangs.serialize(buffer, true) + break + case .passportConfigNotModified: + if boxed { + buffer.appendInt32(-1078332329) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .passportConfig(let _data): + return ("passportConfig", [("hash", _data.hash as Any), ("countriesLangs", _data.countriesLangs as Any)]) + case .passportConfigNotModified: + return ("passportConfigNotModified", []) + } + } + + public static func parse_passportConfig(_ reader: BufferReader) -> PassportConfig? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.DataJSON? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.DataJSON + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.help.PassportConfig.passportConfig(Cons_passportConfig(hash: _1!, countriesLangs: _2!)) + } + else { + return nil + } + } + public static func parse_passportConfigNotModified(_ reader: BufferReader) -> PassportConfig? { + return Api.help.PassportConfig.passportConfigNotModified + } + } +} +public extension Api.help { + enum PeerColorOption: TypeConstructorDescription { + public class Cons_peerColorOption { + public var flags: Int32 + public var colorId: Int32 + public var colors: Api.help.PeerColorSet? + public var darkColors: Api.help.PeerColorSet? + public var channelMinLevel: Int32? + public var groupMinLevel: Int32? + public init(flags: Int32, colorId: Int32, colors: Api.help.PeerColorSet?, darkColors: Api.help.PeerColorSet?, channelMinLevel: Int32?, groupMinLevel: Int32?) { + self.flags = flags + self.colorId = colorId + self.colors = colors + self.darkColors = darkColors + self.channelMinLevel = channelMinLevel + self.groupMinLevel = groupMinLevel + } + } + case peerColorOption(Cons_peerColorOption) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .peerColorOption(let _data): + if boxed { + buffer.appendInt32(-1377014082) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.colorId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.colors!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.darkColors!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.channelMinLevel!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.groupMinLevel!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .peerColorOption(let _data): + return ("peerColorOption", [("flags", _data.flags as Any), ("colorId", _data.colorId as Any), ("colors", _data.colors as Any), ("darkColors", _data.darkColors as Any), ("channelMinLevel", _data.channelMinLevel as Any), ("groupMinLevel", _data.groupMinLevel as Any)]) + } + } + + public static func parse_peerColorOption(_ reader: BufferReader) -> PeerColorOption? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Api.help.PeerColorSet? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.help.PeerColorSet + } + } + var _4: Api.help.PeerColorSet? + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.help.PeerColorSet + } + } + var _5: Int32? + if Int(_1!) & Int(1 << 3) != 0 { + _5 = reader.readInt32() + } + var _6: Int32? + if Int(_1!) & Int(1 << 4) != 0 { + _6 = reader.readInt32() } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 3) == 0) || _5 != nil - let _c6 = _6 != nil - let _c7 = _7 != nil - let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.messages.BotResults.botResults(flags: _1!, queryId: _2!, nextOffset: _3, switchPm: _4, switchWebview: _5, results: _6!, cacheTime: _7!, users: _8!) + let _c6 = (Int(_1!) & Int(1 << 4) == 0) || _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.help.PeerColorOption.peerColorOption(Cons_peerColorOption(flags: _1!, colorId: _2!, colors: _3, darkColors: _4, channelMinLevel: _5, groupMinLevel: _6)) + } + else { + return nil + } } - } } -public extension Api.messages { - enum ChatAdminsWithInvites: TypeConstructorDescription { - case chatAdminsWithInvites(admins: [Api.ChatAdminWithInvites], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatAdminsWithInvites(let admins, let users): - if boxed { - buffer.appendInt32(-1231326505) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(admins.count)) - for item in admins { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatAdminsWithInvites(let admins, let users): - return ("chatAdminsWithInvites", [("admins", admins as Any), ("users", users as Any)]) - } - } - - public static func parse_chatAdminsWithInvites(_ reader: BufferReader) -> ChatAdminsWithInvites? { - var _1: [Api.ChatAdminWithInvites]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ChatAdminWithInvites.self) +public extension Api.help { + enum PeerColorSet: TypeConstructorDescription { + public class Cons_peerColorProfileSet { + public var paletteColors: [Int32] + public var bgColors: [Int32] + public var storyColors: [Int32] + public init(paletteColors: [Int32], bgColors: [Int32], storyColors: [Int32]) { + self.paletteColors = paletteColors + self.bgColors = bgColors + self.storyColors = storyColors } - var _2: [Api.User]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.ChatAdminsWithInvites.chatAdminsWithInvites(admins: _1!, users: _2!) } - - } -} -public extension Api.messages { - enum ChatFull: TypeConstructorDescription { - case chatFull(fullChat: Api.ChatFull, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatFull(let fullChat, let chats, let users): - if boxed { - buffer.appendInt32(-438840932) - } - fullChat.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatFull(let fullChat, let chats, let users): - return ("chatFull", [("fullChat", fullChat as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_chatFull(_ reader: BufferReader) -> ChatFull? { - var _1: Api.ChatFull? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.ChatFull + public class Cons_peerColorSet { + public var colors: [Int32] + public init(colors: [Int32]) { + self.colors = colors } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + case peerColorProfileSet(Cons_peerColorProfileSet) + case peerColorSet(Cons_peerColorSet) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .peerColorProfileSet(let _data): + if boxed { + buffer.appendInt32(1987928555) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.paletteColors.count)) + for item in _data.paletteColors { + serializeInt32(item, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.bgColors.count)) + for item in _data.bgColors { + serializeInt32(item, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.storyColors.count)) + for item in _data.storyColors { + serializeInt32(item, buffer: buffer, boxed: false) + } + break + case .peerColorSet(let _data): + if boxed { + buffer.appendInt32(639736408) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.colors.count)) + for item in _data.colors { + serializeInt32(item, buffer: buffer, boxed: false) + } + break } - var _3: [Api.User]? + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .peerColorProfileSet(let _data): + return ("peerColorProfileSet", [("paletteColors", _data.paletteColors as Any), ("bgColors", _data.bgColors as Any), ("storyColors", _data.storyColors as Any)]) + case .peerColorSet(let _data): + return ("peerColorSet", [("colors", _data.colors as Any)]) + } + } + + public static func parse_peerColorProfileSet(_ reader: BufferReader) -> PeerColorSet? { + var _1: [Int32]? if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + _1 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + var _2: [Int32]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + var _3: [Int32]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.messages.ChatFull.chatFull(fullChat: _1!, chats: _2!, users: _3!) + if _c1 && _c2 && _c3 { + return Api.help.PeerColorSet.peerColorProfileSet(Cons_peerColorProfileSet(paletteColors: _1!, bgColors: _2!, storyColors: _3!)) + } + else { + return nil + } + } + public static func parse_peerColorSet(_ reader: BufferReader) -> PeerColorSet? { + var _1: [Int32]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + let _c1 = _1 != nil + if _c1 { + return Api.help.PeerColorSet.peerColorSet(Cons_peerColorSet(colors: _1!)) + } + else { + return nil + } } - } } -public extension Api.messages { - enum ChatInviteImporters: TypeConstructorDescription { - case chatInviteImporters(count: Int32, importers: [Api.ChatInviteImporter], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatInviteImporters(let count, let importers, let users): - if boxed { - buffer.appendInt32(-2118733814) - } - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(importers.count)) - for item in importers { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatInviteImporters(let count, let importers, let users): - return ("chatInviteImporters", [("count", count as Any), ("importers", importers as Any), ("users", users as Any)]) - } - } - - public static func parse_chatInviteImporters(_ reader: BufferReader) -> ChatInviteImporters? { +public extension Api.help { + enum PeerColors: TypeConstructorDescription { + public class Cons_peerColors { + public var hash: Int32 + public var colors: [Api.help.PeerColorOption] + public init(hash: Int32, colors: [Api.help.PeerColorOption]) { + self.hash = hash + self.colors = colors + } + } + case peerColors(Cons_peerColors) + case peerColorsNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .peerColors(let _data): + if boxed { + buffer.appendInt32(16313608) + } + serializeInt32(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.colors.count)) + for item in _data.colors { + item.serialize(buffer, true) + } + break + case .peerColorsNotModified: + if boxed { + buffer.appendInt32(732034510) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .peerColors(let _data): + return ("peerColors", [("hash", _data.hash as Any), ("colors", _data.colors as Any)]) + case .peerColorsNotModified: + return ("peerColorsNotModified", []) + } + } + + public static func parse_peerColors(_ reader: BufferReader) -> PeerColors? { var _1: Int32? _1 = reader.readInt32() - var _2: [Api.ChatInviteImporter]? + var _2: [Api.help.PeerColorOption]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ChatInviteImporter.self) - } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.help.PeerColorOption.self) } let _c1 = _1 != nil let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.messages.ChatInviteImporters.chatInviteImporters(count: _1!, importers: _2!, users: _3!) + if _c1 && _c2 { + return Api.help.PeerColors.peerColors(Cons_peerColors(hash: _1!, colors: _2!)) + } + else { + return nil + } + } + public static func parse_peerColorsNotModified(_ reader: BufferReader) -> PeerColors? { + return Api.help.PeerColors.peerColorsNotModified } - } } -public extension Api.messages { - enum Chats: TypeConstructorDescription { - case chats(chats: [Api.Chat]) - case chatsSlice(count: Int32, chats: [Api.Chat]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chats(let chats): - if boxed { - buffer.appendInt32(1694474197) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - break - case .chatsSlice(let count, let chats): - if boxed { - buffer.appendInt32(-1663561404) - } - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chats(let chats): - return ("chats", [("chats", chats as Any)]) - case .chatsSlice(let count, let chats): - return ("chatsSlice", [("count", count as Any), ("chats", chats as Any)]) - } - } - - public static func parse_chats(_ reader: BufferReader) -> Chats? { - var _1: [Api.Chat]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) +public extension Api.help { + enum PremiumPromo: TypeConstructorDescription { + public class Cons_premiumPromo { + public var statusText: String + public var statusEntities: [Api.MessageEntity] + public var videoSections: [String] + public var videos: [Api.Document] + public var periodOptions: [Api.PremiumSubscriptionOption] + public var users: [Api.User] + public init(statusText: String, statusEntities: [Api.MessageEntity], videoSections: [String], videos: [Api.Document], periodOptions: [Api.PremiumSubscriptionOption], users: [Api.User]) { + self.statusText = statusText + self.statusEntities = statusEntities + self.videoSections = videoSections + self.videos = videos + self.periodOptions = periodOptions + self.users = users } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.messages.Chats.chats(chats: _1!) } - public static func parse_chatsSlice(_ reader: BufferReader) -> Chats? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + case premiumPromo(Cons_premiumPromo) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .premiumPromo(let _data): + if boxed { + buffer.appendInt32(1395946908) + } + serializeString(_data.statusText, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.statusEntities.count)) + for item in _data.statusEntities { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.videoSections.count)) + for item in _data.videoSections { + serializeString(item, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.videos.count)) + for item in _data.videos { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.periodOptions.count)) + for item in _data.periodOptions { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.Chats.chatsSlice(count: _1!, chats: _2!) } - - } -} -public extension Api.messages { - enum CheckedHistoryImportPeer: TypeConstructorDescription { - case checkedHistoryImportPeer(confirmText: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .checkedHistoryImportPeer(let confirmText): - if boxed { - buffer.appendInt32(-1571952873) - } - serializeString(confirmText, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .checkedHistoryImportPeer(let confirmText): - return ("checkedHistoryImportPeer", [("confirmText", confirmText as Any)]) - } - } - - public static func parse_checkedHistoryImportPeer(_ reader: BufferReader) -> CheckedHistoryImportPeer? { + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .premiumPromo(let _data): + return ("premiumPromo", [("statusText", _data.statusText as Any), ("statusEntities", _data.statusEntities as Any), ("videoSections", _data.videoSections as Any), ("videos", _data.videos as Any), ("periodOptions", _data.periodOptions as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_premiumPromo(_ reader: BufferReader) -> PremiumPromo? { var _1: String? _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.messages.CheckedHistoryImportPeer.checkedHistoryImportPeer(confirmText: _1!) - } - - } -} -public extension Api.messages { - enum DhConfig: TypeConstructorDescription { - case dhConfig(g: Int32, p: Buffer, version: Int32, random: Buffer) - case dhConfigNotModified(random: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .dhConfig(let g, let p, let version, let random): - if boxed { - buffer.appendInt32(740433629) - } - serializeInt32(g, buffer: buffer, boxed: false) - serializeBytes(p, buffer: buffer, boxed: false) - serializeInt32(version, buffer: buffer, boxed: false) - serializeBytes(random, buffer: buffer, boxed: false) - break - case .dhConfigNotModified(let random): - if boxed { - buffer.appendInt32(-1058912715) - } - serializeBytes(random, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .dhConfig(let g, let p, let version, let random): - return ("dhConfig", [("g", g as Any), ("p", p as Any), ("version", version as Any), ("random", random as Any)]) - case .dhConfigNotModified(let random): - return ("dhConfigNotModified", [("random", random as Any)]) - } - } - - public static func parse_dhConfig(_ reader: BufferReader) -> DhConfig? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Buffer? - _2 = parseBytes(reader) - var _3: Int32? - _3 = reader.readInt32() - var _4: Buffer? - _4 = parseBytes(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.messages.DhConfig.dhConfig(g: _1!, p: _2!, version: _3!, random: _4!) - } - public static func parse_dhConfigNotModified(_ reader: BufferReader) -> DhConfig? { - var _1: Buffer? - _1 = parseBytes(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.messages.DhConfig.dhConfigNotModified(random: _1!) - } - - } -} -public extension Api.messages { - enum DialogFilters: TypeConstructorDescription { - case dialogFilters(flags: Int32, filters: [Api.DialogFilter]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .dialogFilters(let flags, let filters): - if boxed { - buffer.appendInt32(718878489) - } - serializeInt32(flags, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(filters.count)) - for item in filters { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .dialogFilters(let flags, let filters): - return ("dialogFilters", [("flags", flags as Any), ("filters", filters as Any)]) - } - } - - public static func parse_dialogFilters(_ reader: BufferReader) -> DialogFilters? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.DialogFilter]? + var _2: [Api.MessageEntity]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.DialogFilter.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.DialogFilters.dialogFilters(flags: _1!, filters: _2!) - } - - } -} -public extension Api.messages { - enum Dialogs: TypeConstructorDescription { - case dialogs(dialogs: [Api.Dialog], messages: [Api.Message], chats: [Api.Chat], users: [Api.User]) - case dialogsNotModified(count: Int32) - case dialogsSlice(count: Int32, dialogs: [Api.Dialog], messages: [Api.Message], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .dialogs(let dialogs, let messages, let chats, let users): - if boxed { - buffer.appendInt32(364538944) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(dialogs.count)) - for item in dialogs { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .dialogsNotModified(let count): - if boxed { - buffer.appendInt32(-253500010) - } - serializeInt32(count, buffer: buffer, boxed: false) - break - case .dialogsSlice(let count, let dialogs, let messages, let chats, let users): - if boxed { - buffer.appendInt32(1910543603) - } - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(dialogs.count)) - for item in dialogs { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .dialogs(let dialogs, let messages, let chats, let users): - return ("dialogs", [("dialogs", dialogs as Any), ("messages", messages as Any), ("chats", chats as Any), ("users", users as Any)]) - case .dialogsNotModified(let count): - return ("dialogsNotModified", [("count", count as Any)]) - case .dialogsSlice(let count, let dialogs, let messages, let chats, let users): - return ("dialogsSlice", [("count", count as Any), ("dialogs", dialogs as Any), ("messages", messages as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_dialogs(_ reader: BufferReader) -> Dialogs? { - var _1: [Api.Dialog]? + var _3: [String]? if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Dialog.self) + _3 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) } - var _2: [Api.Message]? + var _4: [Api.Document]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) } - var _3: [Api.Chat]? + var _5: [Api.PremiumSubscriptionOption]? if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PremiumSubscriptionOption.self) } - var _4: [Api.User]? + var _6: [Api.User]? if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.messages.Dialogs.dialogs(dialogs: _1!, messages: _2!, chats: _3!, users: _4!) - } - public static func parse_dialogsNotModified(_ reader: BufferReader) -> Dialogs? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.messages.Dialogs.dialogsNotModified(count: _1!) - } - public static func parse_dialogsSlice(_ reader: BufferReader) -> Dialogs? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.Dialog]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Dialog.self) - } - var _3: [Api.Message]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) - } - var _4: [Api.Chat]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _5: [Api.User]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.messages.Dialogs.dialogsSlice(count: _1!, dialogs: _2!, messages: _3!, chats: _4!, users: _5!) + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.help.PremiumPromo.premiumPromo(Cons_premiumPromo(statusText: _1!, statusEntities: _2!, videoSections: _3!, videos: _4!, periodOptions: _5!, users: _6!)) + } + else { + return nil + } } - } } -public extension Api.messages { - enum DiscussionMessage: TypeConstructorDescription { - case discussionMessage(flags: Int32, messages: [Api.Message], maxId: Int32?, readInboxMaxId: Int32?, readOutboxMaxId: Int32?, unreadCount: Int32, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .discussionMessage(let flags, let messages, let maxId, let readInboxMaxId, let readOutboxMaxId, let unreadCount, let chats, let users): - if boxed { - buffer.appendInt32(-1506535550) - } - serializeInt32(flags, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(maxId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(readInboxMaxId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(readOutboxMaxId!, buffer: buffer, boxed: false)} - serializeInt32(unreadCount, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .discussionMessage(let flags, let messages, let maxId, let readInboxMaxId, let readOutboxMaxId, let unreadCount, let chats, let users): - return ("discussionMessage", [("flags", flags as Any), ("messages", messages as Any), ("maxId", maxId as Any), ("readInboxMaxId", readInboxMaxId as Any), ("readOutboxMaxId", readOutboxMaxId as Any), ("unreadCount", unreadCount as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_discussionMessage(_ reader: BufferReader) -> DiscussionMessage? { +public extension Api.help { + enum PromoData: TypeConstructorDescription { + public class Cons_promoData { + public var flags: Int32 + public var expires: Int32 + public var peer: Api.Peer? + public var psaType: String? + public var psaMessage: String? + public var pendingSuggestions: [String] + public var dismissedSuggestions: [String] + public var customPendingSuggestion: Api.PendingSuggestion? + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, expires: Int32, peer: Api.Peer?, psaType: String?, psaMessage: String?, pendingSuggestions: [String], dismissedSuggestions: [String], customPendingSuggestion: Api.PendingSuggestion?, chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.expires = expires + self.peer = peer + self.psaType = psaType + self.psaMessage = psaMessage + self.pendingSuggestions = pendingSuggestions + self.dismissedSuggestions = dismissedSuggestions + self.customPendingSuggestion = customPendingSuggestion + self.chats = chats + self.users = users + } + } + public class Cons_promoDataEmpty { + public var expires: Int32 + public init(expires: Int32) { + self.expires = expires + } + } + case promoData(Cons_promoData) + case promoDataEmpty(Cons_promoDataEmpty) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .promoData(let _data): + if boxed { + buffer.appendInt32(145021050) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.expires, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.peer!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.psaType!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.psaMessage!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.pendingSuggestions.count)) + for item in _data.pendingSuggestions { + serializeString(item, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.dismissedSuggestions.count)) + for item in _data.dismissedSuggestions { + serializeString(item, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + _data.customPendingSuggestion!.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .promoDataEmpty(let _data): + if boxed { + buffer.appendInt32(-1728664459) + } + serializeInt32(_data.expires, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .promoData(let _data): + return ("promoData", [("flags", _data.flags as Any), ("expires", _data.expires as Any), ("peer", _data.peer as Any), ("psaType", _data.psaType as Any), ("psaMessage", _data.psaMessage as Any), ("pendingSuggestions", _data.pendingSuggestions as Any), ("dismissedSuggestions", _data.dismissedSuggestions as Any), ("customPendingSuggestion", _data.customPendingSuggestion as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + case .promoDataEmpty(let _data): + return ("promoDataEmpty", [("expires", _data.expires as Any)]) + } + } + + public static func parse_promoData(_ reader: BufferReader) -> PromoData? { var _1: Int32? _1 = reader.readInt32() - var _2: [Api.Message]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) + var _2: Int32? + _2 = reader.readInt32() + var _3: Api.Peer? + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Peer + } } - var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } - var _4: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_4 = reader.readInt32() } - var _5: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_5 = reader.readInt32() } - var _6: Int32? - _6 = reader.readInt32() - var _7: [Api.Chat]? - if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + var _4: String? + if Int(_1!) & Int(1 << 1) != 0 { + _4 = parseString(reader) } - var _8: [Api.User]? + var _5: String? + if Int(_1!) & Int(1 << 2) != 0 { + _5 = parseString(reader) + } + var _6: [String]? if let _ = reader.readInt32() { - _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + _6 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) + } + var _7: [String]? + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) + } + var _8: Api.PendingSuggestion? + if Int(_1!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.PendingSuggestion + } + } + var _9: [Api.Chat]? + if let _ = reader.readInt32() { + _9 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _10: [Api.User]? + if let _ = reader.readInt32() { + _10 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } let _c1 = _1 != nil let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + let _c3 = (Int(_1!) & Int(1 << 3) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 2) == 0) || _5 != nil let _c6 = _6 != nil let _c7 = _7 != nil - let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.messages.DiscussionMessage.discussionMessage(flags: _1!, messages: _2!, maxId: _3, readInboxMaxId: _4, readOutboxMaxId: _5, unreadCount: _6!, chats: _7!, users: _8!) + let _c8 = (Int(_1!) & Int(1 << 4) == 0) || _8 != nil + let _c9 = _9 != nil + let _c10 = _10 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 { + return Api.help.PromoData.promoData(Cons_promoData(flags: _1!, expires: _2!, peer: _3, psaType: _4, psaMessage: _5, pendingSuggestions: _6!, dismissedSuggestions: _7!, customPendingSuggestion: _8, chats: _9!, users: _10!)) + } + else { + return nil + } } - - } -} -public extension Api.messages { - enum EmojiGameInfo: TypeConstructorDescription { - case emojiGameDiceInfo(flags: Int32, gameHash: String, prevStake: Int64, currentStreak: Int32, params: [Int32], playsLeft: Int32?) - case emojiGameUnavailable - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .emojiGameDiceInfo(let flags, let gameHash, let prevStake, let currentStreak, let params, let playsLeft): - if boxed { - buffer.appendInt32(1155883043) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(gameHash, buffer: buffer, boxed: false) - serializeInt64(prevStake, buffer: buffer, boxed: false) - serializeInt32(currentStreak, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(params.count)) - for item in params { - serializeInt32(item, buffer: buffer, boxed: false) - } - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(playsLeft!, buffer: buffer, boxed: false)} - break - case .emojiGameUnavailable: - if boxed { - buffer.appendInt32(1508266805) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .emojiGameDiceInfo(let flags, let gameHash, let prevStake, let currentStreak, let params, let playsLeft): - return ("emojiGameDiceInfo", [("flags", flags as Any), ("gameHash", gameHash as Any), ("prevStake", prevStake as Any), ("currentStreak", currentStreak as Any), ("params", params as Any), ("playsLeft", playsLeft as Any)]) - case .emojiGameUnavailable: - return ("emojiGameUnavailable", []) - } - } - - public static func parse_emojiGameDiceInfo(_ reader: BufferReader) -> EmojiGameInfo? { + public static func parse_promoDataEmpty(_ reader: BufferReader) -> PromoData? { var _1: Int32? _1 = reader.readInt32() - var _2: String? - _2 = parseString(reader) - var _3: Int64? - _3 = reader.readInt64() - var _4: Int32? - _4 = reader.readInt32() - var _5: [Int32]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + let _c1 = _1 != nil + if _c1 { + return Api.help.PromoData.promoDataEmpty(Cons_promoDataEmpty(expires: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.help { + enum RecentMeUrls: TypeConstructorDescription { + public class Cons_recentMeUrls { + public var urls: [Api.RecentMeUrl] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(urls: [Api.RecentMeUrl], chats: [Api.Chat], users: [Api.User]) { + self.urls = urls + self.chats = chats + self.users = users + } + } + case recentMeUrls(Cons_recentMeUrls) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .recentMeUrls(let _data): + if boxed { + buffer.appendInt32(235081943) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.urls.count)) + for item in _data.urls { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .recentMeUrls(let _data): + return ("recentMeUrls", [("urls", _data.urls as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_recentMeUrls(_ reader: BufferReader) -> RecentMeUrls? { + var _1: [Api.RecentMeUrl]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.RecentMeUrl.self) + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.help.RecentMeUrls.recentMeUrls(Cons_recentMeUrls(urls: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.help { + enum Support: TypeConstructorDescription { + public class Cons_support { + public var phoneNumber: String + public var user: Api.User + public init(phoneNumber: String, user: Api.User) { + self.phoneNumber = phoneNumber + self.user = user + } + } + case support(Cons_support) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .support(let _data): + if boxed { + buffer.appendInt32(398898678) + } + serializeString(_data.phoneNumber, buffer: buffer, boxed: false) + _data.user.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .support(let _data): + return ("support", [("phoneNumber", _data.phoneNumber as Any), ("user", _data.user as Any)]) + } + } + + public static func parse_support(_ reader: BufferReader) -> Support? { + var _1: String? + _1 = parseString(reader) + var _2: Api.User? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.User + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.help.Support.support(Cons_support(phoneNumber: _1!, user: _2!)) + } + else { + return nil + } + } + } +} +public extension Api.help { + enum SupportName: TypeConstructorDescription { + public class Cons_supportName { + public var name: String + public init(name: String) { + self.name = name + } + } + case supportName(Cons_supportName) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .supportName(let _data): + if boxed { + buffer.appendInt32(-1945767479) + } + serializeString(_data.name, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .supportName(let _data): + return ("supportName", [("name", _data.name as Any)]) + } + } + + public static func parse_supportName(_ reader: BufferReader) -> SupportName? { + var _1: String? + _1 = parseString(reader) + let _c1 = _1 != nil + if _c1 { + return Api.help.SupportName.supportName(Cons_supportName(name: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.help { + enum TermsOfService: TypeConstructorDescription { + public class Cons_termsOfService { + public var flags: Int32 + public var id: Api.DataJSON + public var text: String + public var entities: [Api.MessageEntity] + public var minAgeConfirm: Int32? + public init(flags: Int32, id: Api.DataJSON, text: String, entities: [Api.MessageEntity], minAgeConfirm: Int32?) { + self.flags = flags + self.id = id + self.text = text + self.entities = entities + self.minAgeConfirm = minAgeConfirm + } + } + case termsOfService(Cons_termsOfService) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .termsOfService(let _data): + if boxed { + buffer.appendInt32(2013922064) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.id.serialize(buffer, true) + serializeString(_data.text, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities.count)) + for item in _data.entities { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.minAgeConfirm!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .termsOfService(let _data): + return ("termsOfService", [("flags", _data.flags as Any), ("id", _data.id as Any), ("text", _data.text as Any), ("entities", _data.entities as Any), ("minAgeConfirm", _data.minAgeConfirm as Any)]) + } + } + + public static func parse_termsOfService(_ reader: BufferReader) -> TermsOfService? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.DataJSON? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.DataJSON + } + var _3: String? + _3 = parseString(reader) + var _4: [Api.MessageEntity]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + var _5: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _5 = reader.readInt32() } - var _6: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_6 = reader.readInt32() } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.messages.EmojiGameInfo.emojiGameDiceInfo(flags: _1!, gameHash: _2!, prevStake: _3!, currentStreak: _4!, params: _5!, playsLeft: _6) + let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.help.TermsOfService.termsOfService(Cons_termsOfService(flags: _1!, id: _2!, text: _3!, entities: _4!, minAgeConfirm: _5)) + } + else { + return nil + } } - public static func parse_emojiGameUnavailable(_ reader: BufferReader) -> EmojiGameInfo? { - return Api.messages.EmojiGameInfo.emojiGameUnavailable - } - } } -public extension Api.messages { - enum EmojiGameOutcome: TypeConstructorDescription { - case emojiGameOutcome(seed: Buffer, stakeTonAmount: Int64, tonAmount: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .emojiGameOutcome(let seed, let stakeTonAmount, let tonAmount): - if boxed { - buffer.appendInt32(-634726841) - } - serializeBytes(seed, buffer: buffer, boxed: false) - serializeInt64(stakeTonAmount, buffer: buffer, boxed: false) - serializeInt64(tonAmount, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .emojiGameOutcome(let seed, let stakeTonAmount, let tonAmount): - return ("emojiGameOutcome", [("seed", seed as Any), ("stakeTonAmount", stakeTonAmount as Any), ("tonAmount", tonAmount as Any)]) - } - } - - public static func parse_emojiGameOutcome(_ reader: BufferReader) -> EmojiGameOutcome? { - var _1: Buffer? - _1 = parseBytes(reader) - var _2: Int64? - _2 = reader.readInt64() - var _3: Int64? - _3 = reader.readInt64() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.messages.EmojiGameOutcome.emojiGameOutcome(seed: _1!, stakeTonAmount: _2!, tonAmount: _3!) +public extension Api.help { + enum TermsOfServiceUpdate: TypeConstructorDescription { + public class Cons_termsOfServiceUpdate { + public var expires: Int32 + public var termsOfService: Api.help.TermsOfService + public init(expires: Int32, termsOfService: Api.help.TermsOfService) { + self.expires = expires + self.termsOfService = termsOfService + } } - - } -} -public extension Api.messages { - enum EmojiGroups: TypeConstructorDescription { - case emojiGroups(hash: Int32, groups: [Api.EmojiGroup]) - case emojiGroupsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .emojiGroups(let hash, let groups): - if boxed { - buffer.appendInt32(-2011186869) - } - serializeInt32(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(groups.count)) - for item in groups { - item.serialize(buffer, true) - } - break - case .emojiGroupsNotModified: - if boxed { - buffer.appendInt32(1874111879) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .emojiGroups(let hash, let groups): - return ("emojiGroups", [("hash", hash as Any), ("groups", groups as Any)]) - case .emojiGroupsNotModified: - return ("emojiGroupsNotModified", []) - } - } - - public static func parse_emojiGroups(_ reader: BufferReader) -> EmojiGroups? { + public class Cons_termsOfServiceUpdateEmpty { + public var expires: Int32 + public init(expires: Int32) { + self.expires = expires + } + } + case termsOfServiceUpdate(Cons_termsOfServiceUpdate) + case termsOfServiceUpdateEmpty(Cons_termsOfServiceUpdateEmpty) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .termsOfServiceUpdate(let _data): + if boxed { + buffer.appendInt32(686618977) + } + serializeInt32(_data.expires, buffer: buffer, boxed: false) + _data.termsOfService.serialize(buffer, true) + break + case .termsOfServiceUpdateEmpty(let _data): + if boxed { + buffer.appendInt32(-483352705) + } + serializeInt32(_data.expires, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .termsOfServiceUpdate(let _data): + return ("termsOfServiceUpdate", [("expires", _data.expires as Any), ("termsOfService", _data.termsOfService as Any)]) + case .termsOfServiceUpdateEmpty(let _data): + return ("termsOfServiceUpdateEmpty", [("expires", _data.expires as Any)]) + } + } + + public static func parse_termsOfServiceUpdate(_ reader: BufferReader) -> TermsOfServiceUpdate? { var _1: Int32? _1 = reader.readInt32() - var _2: [Api.EmojiGroup]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.EmojiGroup.self) + var _2: Api.help.TermsOfService? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.help.TermsOfService } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.EmojiGroups.emojiGroups(hash: _1!, groups: _2!) + if _c1 && _c2 { + return Api.help.TermsOfServiceUpdate.termsOfServiceUpdate(Cons_termsOfServiceUpdate(expires: _1!, termsOfService: _2!)) + } + else { + return nil + } } - public static func parse_emojiGroupsNotModified(_ reader: BufferReader) -> EmojiGroups? { - return Api.messages.EmojiGroups.emojiGroupsNotModified - } - - } -} -public extension Api.messages { - enum ExportedChatInvite: TypeConstructorDescription { - case exportedChatInvite(invite: Api.ExportedChatInvite, users: [Api.User]) - case exportedChatInviteReplaced(invite: Api.ExportedChatInvite, newInvite: Api.ExportedChatInvite, users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .exportedChatInvite(let invite, let users): - if boxed { - buffer.appendInt32(410107472) - } - invite.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .exportedChatInviteReplaced(let invite, let newInvite, let users): - if boxed { - buffer.appendInt32(572915951) - } - invite.serialize(buffer, true) - newInvite.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .exportedChatInvite(let invite, let users): - return ("exportedChatInvite", [("invite", invite as Any), ("users", users as Any)]) - case .exportedChatInviteReplaced(let invite, let newInvite, let users): - return ("exportedChatInviteReplaced", [("invite", invite as Any), ("newInvite", newInvite as Any), ("users", users as Any)]) - } - } - - public static func parse_exportedChatInvite(_ reader: BufferReader) -> ExportedChatInvite? { - var _1: Api.ExportedChatInvite? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite - } - var _2: [Api.User]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.ExportedChatInvite.exportedChatInvite(invite: _1!, users: _2!) - } - public static func parse_exportedChatInviteReplaced(_ reader: BufferReader) -> ExportedChatInvite? { - var _1: Api.ExportedChatInvite? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite - } - var _2: Api.ExportedChatInvite? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite - } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.messages.ExportedChatInvite.exportedChatInviteReplaced(invite: _1!, newInvite: _2!, users: _3!) - } - - } -} -public extension Api.messages { - enum ExportedChatInvites: TypeConstructorDescription { - case exportedChatInvites(count: Int32, invites: [Api.ExportedChatInvite], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .exportedChatInvites(let count, let invites, let users): - if boxed { - buffer.appendInt32(-1111085620) - } - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(invites.count)) - for item in invites { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .exportedChatInvites(let count, let invites, let users): - return ("exportedChatInvites", [("count", count as Any), ("invites", invites as Any), ("users", users as Any)]) - } - } - - public static func parse_exportedChatInvites(_ reader: BufferReader) -> ExportedChatInvites? { + public static func parse_termsOfServiceUpdateEmpty(_ reader: BufferReader) -> TermsOfServiceUpdate? { var _1: Int32? _1 = reader.readInt32() - var _2: [Api.ExportedChatInvite]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ExportedChatInvite.self) + let _c1 = _1 != nil + if _c1 { + return Api.help.TermsOfServiceUpdate.termsOfServiceUpdateEmpty(Cons_termsOfServiceUpdateEmpty(expires: _1!)) } - var _3: [Api.User]? + else { + return nil + } + } + } +} +public extension Api.help { + enum TimezonesList: TypeConstructorDescription { + public class Cons_timezonesList { + public var timezones: [Api.Timezone] + public var hash: Int32 + public init(timezones: [Api.Timezone], hash: Int32) { + self.timezones = timezones + self.hash = hash + } + } + case timezonesList(Cons_timezonesList) + case timezonesListNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .timezonesList(let _data): + if boxed { + buffer.appendInt32(2071260529) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.timezones.count)) + for item in _data.timezones { + item.serialize(buffer, true) + } + serializeInt32(_data.hash, buffer: buffer, boxed: false) + break + case .timezonesListNotModified: + if boxed { + buffer.appendInt32(-1761146676) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .timezonesList(let _data): + return ("timezonesList", [("timezones", _data.timezones as Any), ("hash", _data.hash as Any)]) + case .timezonesListNotModified: + return ("timezonesListNotModified", []) + } + } + + public static func parse_timezonesList(_ reader: BufferReader) -> TimezonesList? { + var _1: [Api.Timezone]? if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Timezone.self) + } + var _2: Int32? + _2 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.help.TimezonesList.timezonesList(Cons_timezonesList(timezones: _1!, hash: _2!)) + } + else { + return nil + } + } + public static func parse_timezonesListNotModified(_ reader: BufferReader) -> TimezonesList? { + return Api.help.TimezonesList.timezonesListNotModified + } + } +} +public extension Api.help { + enum UserInfo: TypeConstructorDescription { + public class Cons_userInfo { + public var message: String + public var entities: [Api.MessageEntity] + public var author: String + public var date: Int32 + public init(message: String, entities: [Api.MessageEntity], author: String, date: Int32) { + self.message = message + self.entities = entities + self.author = author + self.date = date + } + } + case userInfo(Cons_userInfo) + case userInfoEmpty + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .userInfo(let _data): + if boxed { + buffer.appendInt32(32192344) + } + serializeString(_data.message, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities.count)) + for item in _data.entities { + item.serialize(buffer, true) + } + serializeString(_data.author, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + case .userInfoEmpty: + if boxed { + buffer.appendInt32(-206688531) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .userInfo(let _data): + return ("userInfo", [("message", _data.message as Any), ("entities", _data.entities as Any), ("author", _data.author as Any), ("date", _data.date as Any)]) + case .userInfoEmpty: + return ("userInfoEmpty", []) + } + } + + public static func parse_userInfo(_ reader: BufferReader) -> UserInfo? { + var _1: String? + _1 = parseString(reader) + var _2: [Api.MessageEntity]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + var _3: String? + _3 = parseString(reader) + var _4: Int32? + _4 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.help.UserInfo.userInfo(Cons_userInfo(message: _1!, entities: _2!, author: _3!, date: _4!)) + } + else { + return nil + } + } + public static func parse_userInfoEmpty(_ reader: BufferReader) -> UserInfo? { + return Api.help.UserInfo.userInfoEmpty + } + } +} +public extension Api.messages { + enum AffectedFoundMessages: TypeConstructorDescription { + public class Cons_affectedFoundMessages { + public var pts: Int32 + public var ptsCount: Int32 + public var offset: Int32 + public var messages: [Int32] + public init(pts: Int32, ptsCount: Int32, offset: Int32, messages: [Int32]) { + self.pts = pts + self.ptsCount = ptsCount + self.offset = offset + self.messages = messages + } + } + case affectedFoundMessages(Cons_affectedFoundMessages) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .affectedFoundMessages(let _data): + if boxed { + buffer.appendInt32(-275956116) + } + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + serializeInt32(_data.offset, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + serializeInt32(item, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .affectedFoundMessages(let _data): + return ("affectedFoundMessages", [("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any), ("offset", _data.offset as Any), ("messages", _data.messages as Any)]) + } + } + + public static func parse_affectedFoundMessages(_ reader: BufferReader) -> AffectedFoundMessages? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + var _4: [Int32]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.messages.ExportedChatInvites.exportedChatInvites(count: _1!, invites: _2!, users: _3!) + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.messages.AffectedFoundMessages.affectedFoundMessages(Cons_affectedFoundMessages(pts: _1!, ptsCount: _2!, offset: _3!, messages: _4!)) + } + else { + return nil + } + } + } +} +public extension Api.messages { + enum AffectedHistory: TypeConstructorDescription { + public class Cons_affectedHistory { + public var pts: Int32 + public var ptsCount: Int32 + public var offset: Int32 + public init(pts: Int32, ptsCount: Int32, offset: Int32) { + self.pts = pts + self.ptsCount = ptsCount + self.offset = offset + } + } + case affectedHistory(Cons_affectedHistory) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .affectedHistory(let _data): + if boxed { + buffer.appendInt32(-1269012015) + } + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + serializeInt32(_data.offset, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .affectedHistory(let _data): + return ("affectedHistory", [("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any), ("offset", _data.offset as Any)]) + } + } + + public static func parse_affectedHistory(_ reader: BufferReader) -> AffectedHistory? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.messages.AffectedHistory.affectedHistory(Cons_affectedHistory(pts: _1!, ptsCount: _2!, offset: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.messages { + enum AffectedMessages: TypeConstructorDescription { + public class Cons_affectedMessages { + public var pts: Int32 + public var ptsCount: Int32 + public init(pts: Int32, ptsCount: Int32) { + self.pts = pts + self.ptsCount = ptsCount + } + } + case affectedMessages(Cons_affectedMessages) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .affectedMessages(let _data): + if boxed { + buffer.appendInt32(-2066640507) + } + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.ptsCount, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .affectedMessages(let _data): + return ("affectedMessages", [("pts", _data.pts as Any), ("ptsCount", _data.ptsCount as Any)]) + } + } + + public static func parse_affectedMessages(_ reader: BufferReader) -> AffectedMessages? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.AffectedMessages.affectedMessages(Cons_affectedMessages(pts: _1!, ptsCount: _2!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api34.swift b/submodules/TelegramApi/Sources/Api34.swift index 23900f23..fbe1750d 100644 --- a/submodules/TelegramApi/Sources/Api34.swift +++ b/submodules/TelegramApi/Sources/Api34.swift @@ -1,50 +1,176 @@ public extension Api.messages { - enum FavedStickers: TypeConstructorDescription { - case favedStickers(hash: Int64, packs: [Api.StickerPack], stickers: [Api.Document]) - case favedStickersNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .favedStickers(let hash, let packs, let stickers): - if boxed { - buffer.appendInt32(750063767) - } - serializeInt64(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(packs.count)) - for item in packs { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stickers.count)) - for item in stickers { - item.serialize(buffer, true) - } - break - case .favedStickersNotModified: - if boxed { - buffer.appendInt32(-1634752813) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .favedStickers(let hash, let packs, let stickers): - return ("favedStickers", [("hash", hash as Any), ("packs", packs as Any), ("stickers", stickers as Any)]) - case .favedStickersNotModified: - return ("favedStickersNotModified", []) - } - } - - public static func parse_favedStickers(_ reader: BufferReader) -> FavedStickers? { + enum AllStickers: TypeConstructorDescription { + public class Cons_allStickers { + public var hash: Int64 + public var sets: [Api.StickerSet] + public init(hash: Int64, sets: [Api.StickerSet]) { + self.hash = hash + self.sets = sets + } + } + case allStickers(Cons_allStickers) + case allStickersNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .allStickers(let _data): + if boxed { + buffer.appendInt32(-843329861) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.sets.count)) + for item in _data.sets { + item.serialize(buffer, true) + } + break + case .allStickersNotModified: + if boxed { + buffer.appendInt32(-395967805) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .allStickers(let _data): + return ("allStickers", [("hash", _data.hash as Any), ("sets", _data.sets as Any)]) + case .allStickersNotModified: + return ("allStickersNotModified", []) + } + } + + public static func parse_allStickers(_ reader: BufferReader) -> AllStickers? { var _1: Int64? _1 = reader.readInt64() - var _2: [Api.StickerPack]? + var _2: [Api.StickerSet]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerPack.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerSet.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.AllStickers.allStickers(Cons_allStickers(hash: _1!, sets: _2!)) + } + else { + return nil + } + } + public static func parse_allStickersNotModified(_ reader: BufferReader) -> AllStickers? { + return Api.messages.AllStickers.allStickersNotModified + } + } +} +public extension Api.messages { + enum ArchivedStickers: TypeConstructorDescription { + public class Cons_archivedStickers { + public var count: Int32 + public var sets: [Api.StickerSetCovered] + public init(count: Int32, sets: [Api.StickerSetCovered]) { + self.count = count + self.sets = sets + } + } + case archivedStickers(Cons_archivedStickers) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .archivedStickers(let _data): + if boxed { + buffer.appendInt32(1338747336) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.sets.count)) + for item in _data.sets { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .archivedStickers(let _data): + return ("archivedStickers", [("count", _data.count as Any), ("sets", _data.sets as Any)]) + } + } + + public static func parse_archivedStickers(_ reader: BufferReader) -> ArchivedStickers? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.StickerSetCovered]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerSetCovered.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.ArchivedStickers.archivedStickers(Cons_archivedStickers(count: _1!, sets: _2!)) + } + else { + return nil + } + } + } +} +public extension Api.messages { + enum AvailableEffects: TypeConstructorDescription { + public class Cons_availableEffects { + public var hash: Int32 + public var effects: [Api.AvailableEffect] + public var documents: [Api.Document] + public init(hash: Int32, effects: [Api.AvailableEffect], documents: [Api.Document]) { + self.hash = hash + self.effects = effects + self.documents = documents + } + } + case availableEffects(Cons_availableEffects) + case availableEffectsNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .availableEffects(let _data): + if boxed { + buffer.appendInt32(-1109696146) + } + serializeInt32(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.effects.count)) + for item in _data.effects { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.documents.count)) + for item in _data.documents { + item.serialize(buffer, true) + } + break + case .availableEffectsNotModified: + if boxed { + buffer.appendInt32(-772957605) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .availableEffects(let _data): + return ("availableEffects", [("hash", _data.hash as Any), ("effects", _data.effects as Any), ("documents", _data.documents as Any)]) + case .availableEffectsNotModified: + return ("availableEffectsNotModified", []) + } + } + + public static func parse_availableEffects(_ reader: BufferReader) -> AvailableEffects? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.AvailableEffect]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.AvailableEffect.self) } var _3: [Api.Document]? if let _ = reader.readInt32() { @@ -53,347 +179,399 @@ public extension Api.messages { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.messages.FavedStickers.favedStickers(hash: _1!, packs: _2!, stickers: _3!) + if _c1 && _c2 && _c3 { + return Api.messages.AvailableEffects.availableEffects(Cons_availableEffects(hash: _1!, effects: _2!, documents: _3!)) + } + else { + return nil + } } - public static func parse_favedStickersNotModified(_ reader: BufferReader) -> FavedStickers? { - return Api.messages.FavedStickers.favedStickersNotModified + public static func parse_availableEffectsNotModified(_ reader: BufferReader) -> AvailableEffects? { + return Api.messages.AvailableEffects.availableEffectsNotModified } - } } public extension Api.messages { - enum FeaturedStickers: TypeConstructorDescription { - case featuredStickers(flags: Int32, hash: Int64, count: Int32, sets: [Api.StickerSetCovered], unread: [Int64]) - case featuredStickersNotModified(count: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .featuredStickers(let flags, let hash, let count, let sets, let unread): - if boxed { - buffer.appendInt32(-1103615738) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(sets.count)) - for item in sets { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(unread.count)) - for item in unread { - serializeInt64(item, buffer: buffer, boxed: false) - } - break - case .featuredStickersNotModified(let count): - if boxed { - buffer.appendInt32(-958657434) - } - serializeInt32(count, buffer: buffer, boxed: false) - break + enum AvailableReactions: TypeConstructorDescription { + public class Cons_availableReactions { + public var hash: Int32 + public var reactions: [Api.AvailableReaction] + public init(hash: Int32, reactions: [Api.AvailableReaction]) { + self.hash = hash + self.reactions = reactions + } + } + case availableReactions(Cons_availableReactions) + case availableReactionsNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .availableReactions(let _data): + if boxed { + buffer.appendInt32(1989032621) + } + serializeInt32(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.reactions.count)) + for item in _data.reactions { + item.serialize(buffer, true) + } + break + case .availableReactionsNotModified: + if boxed { + buffer.appendInt32(-1626924713) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .availableReactions(let _data): + return ("availableReactions", [("hash", _data.hash as Any), ("reactions", _data.reactions as Any)]) + case .availableReactionsNotModified: + return ("availableReactionsNotModified", []) + } + } + + public static func parse_availableReactions(_ reader: BufferReader) -> AvailableReactions? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.AvailableReaction]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.AvailableReaction.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.AvailableReactions.availableReactions(Cons_availableReactions(hash: _1!, reactions: _2!)) + } + else { + return nil + } + } + public static func parse_availableReactionsNotModified(_ reader: BufferReader) -> AvailableReactions? { + return Api.messages.AvailableReactions.availableReactionsNotModified + } } +} +public extension Api.messages { + enum BotApp: TypeConstructorDescription { + public class Cons_botApp { + public var flags: Int32 + public var app: Api.BotApp + public init(flags: Int32, app: Api.BotApp) { + self.flags = flags + self.app = app + } + } + case botApp(Cons_botApp) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botApp(let _data): + if boxed { + buffer.appendInt32(-347034123) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.app.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botApp(let _data): + return ("botApp", [("flags", _data.flags as Any), ("app", _data.app as Any)]) + } + } + + public static func parse_botApp(_ reader: BufferReader) -> BotApp? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.BotApp? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.BotApp + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.BotApp.botApp(Cons_botApp(flags: _1!, app: _2!)) + } + else { + return nil + } + } } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .featuredStickers(let flags, let hash, let count, let sets, let unread): - return ("featuredStickers", [("flags", flags as Any), ("hash", hash as Any), ("count", count as Any), ("sets", sets as Any), ("unread", unread as Any)]) - case .featuredStickersNotModified(let count): - return ("featuredStickersNotModified", [("count", count as Any)]) +} +public extension Api.messages { + enum BotCallbackAnswer: TypeConstructorDescription { + public class Cons_botCallbackAnswer { + public var flags: Int32 + public var message: String? + public var url: String? + public var cacheTime: Int32 + public init(flags: Int32, message: String?, url: String?, cacheTime: Int32) { + self.flags = flags + self.message = message + self.url = url + self.cacheTime = cacheTime + } + } + case botCallbackAnswer(Cons_botCallbackAnswer) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botCallbackAnswer(let _data): + if boxed { + buffer.appendInt32(911761060) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.message!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.url!, buffer: buffer, boxed: false) + } + serializeInt32(_data.cacheTime, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botCallbackAnswer(let _data): + return ("botCallbackAnswer", [("flags", _data.flags as Any), ("message", _data.message as Any), ("url", _data.url as Any), ("cacheTime", _data.cacheTime as Any)]) + } + } + + public static func parse_botCallbackAnswer(_ reader: BufferReader) -> BotCallbackAnswer? { + var _1: Int32? + _1 = reader.readInt32() + var _2: String? + if Int(_1!) & Int(1 << 0) != 0 { + _2 = parseString(reader) + } + var _3: String? + if Int(_1!) & Int(1 << 2) != 0 { + _3 = parseString(reader) + } + var _4: Int32? + _4 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + let _c3 = (Int(_1!) & Int(1 << 2) == 0) || _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.messages.BotCallbackAnswer.botCallbackAnswer(Cons_botCallbackAnswer(flags: _1!, message: _2, url: _3, cacheTime: _4!)) + } + else { + return nil + } + } } +} +public extension Api.messages { + enum BotPreparedInlineMessage: TypeConstructorDescription { + public class Cons_botPreparedInlineMessage { + public var id: String + public var expireDate: Int32 + public init(id: String, expireDate: Int32) { + self.id = id + self.expireDate = expireDate + } + } + case botPreparedInlineMessage(Cons_botPreparedInlineMessage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botPreparedInlineMessage(let _data): + if boxed { + buffer.appendInt32(-1899035375) + } + serializeString(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.expireDate, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botPreparedInlineMessage(let _data): + return ("botPreparedInlineMessage", [("id", _data.id as Any), ("expireDate", _data.expireDate as Any)]) + } + } + + public static func parse_botPreparedInlineMessage(_ reader: BufferReader) -> BotPreparedInlineMessage? { + var _1: String? + _1 = parseString(reader) + var _2: Int32? + _2 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.BotPreparedInlineMessage.botPreparedInlineMessage(Cons_botPreparedInlineMessage(id: _1!, expireDate: _2!)) + } + else { + return nil + } + } } - - public static func parse_featuredStickers(_ reader: BufferReader) -> FeaturedStickers? { +} +public extension Api.messages { + enum BotResults: TypeConstructorDescription { + public class Cons_botResults { + public var flags: Int32 + public var queryId: Int64 + public var nextOffset: String? + public var switchPm: Api.InlineBotSwitchPM? + public var switchWebview: Api.InlineBotWebView? + public var results: [Api.BotInlineResult] + public var cacheTime: Int32 + public var users: [Api.User] + public init(flags: Int32, queryId: Int64, nextOffset: String?, switchPm: Api.InlineBotSwitchPM?, switchWebview: Api.InlineBotWebView?, results: [Api.BotInlineResult], cacheTime: Int32, users: [Api.User]) { + self.flags = flags + self.queryId = queryId + self.nextOffset = nextOffset + self.switchPm = switchPm + self.switchWebview = switchWebview + self.results = results + self.cacheTime = cacheTime + self.users = users + } + } + case botResults(Cons_botResults) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .botResults(let _data): + if boxed { + buffer.appendInt32(-534646026) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.queryId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.nextOffset!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.switchPm!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.switchWebview!.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.results.count)) + for item in _data.results { + item.serialize(buffer, true) + } + serializeInt32(_data.cacheTime, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .botResults(let _data): + return ("botResults", [("flags", _data.flags as Any), ("queryId", _data.queryId as Any), ("nextOffset", _data.nextOffset as Any), ("switchPm", _data.switchPm as Any), ("switchWebview", _data.switchWebview as Any), ("results", _data.results as Any), ("cacheTime", _data.cacheTime as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_botResults(_ reader: BufferReader) -> BotResults? { var _1: Int32? _1 = reader.readInt32() var _2: Int64? _2 = reader.readInt64() - var _3: Int32? - _3 = reader.readInt32() - var _4: [Api.StickerSetCovered]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerSetCovered.self) + var _3: String? + if Int(_1!) & Int(1 << 1) != 0 { + _3 = parseString(reader) } - var _5: [Int64]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) + var _4: Api.InlineBotSwitchPM? + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.InlineBotSwitchPM + } } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.messages.FeaturedStickers.featuredStickers(flags: _1!, hash: _2!, count: _3!, sets: _4!, unread: _5!) - } - public static func parse_featuredStickersNotModified(_ reader: BufferReader) -> FeaturedStickers? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.messages.FeaturedStickers.featuredStickersNotModified(count: _1!) - } - - } -} -public extension Api.messages { - enum ForumTopics: TypeConstructorDescription { - case forumTopics(flags: Int32, count: Int32, topics: [Api.ForumTopic], messages: [Api.Message], chats: [Api.Chat], users: [Api.User], pts: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .forumTopics(let flags, let count, let topics, let messages, let chats, let users, let pts): - if boxed { - buffer.appendInt32(913709011) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(topics.count)) - for item in topics { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - serializeInt32(pts, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .forumTopics(let flags, let count, let topics, let messages, let chats, let users, let pts): - return ("forumTopics", [("flags", flags as Any), ("count", count as Any), ("topics", topics as Any), ("messages", messages as Any), ("chats", chats as Any), ("users", users as Any), ("pts", pts as Any)]) - } - } - - public static func parse_forumTopics(_ reader: BufferReader) -> ForumTopics? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: [Api.ForumTopic]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ForumTopic.self) + var _5: Api.InlineBotWebView? + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.InlineBotWebView + } } - var _4: [Api.Message]? + var _6: [Api.BotInlineResult]? if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) - } - var _5: [Api.Chat]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _6: [Api.User]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.BotInlineResult.self) } var _7: Int32? _7 = reader.readInt32() + var _8: [Api.User]? + if let _ = reader.readInt32() { + _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } let _c1 = _1 != nil let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil + let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil + let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil + let _c5 = (Int(_1!) & Int(1 << 3) == 0) || _5 != nil let _c6 = _6 != nil let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.messages.ForumTopics.forumTopics(flags: _1!, count: _2!, topics: _3!, messages: _4!, chats: _5!, users: _6!, pts: _7!) - } - - } -} -public extension Api.messages { - enum FoundStickerSets: TypeConstructorDescription { - case foundStickerSets(hash: Int64, sets: [Api.StickerSetCovered]) - case foundStickerSetsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .foundStickerSets(let hash, let sets): - if boxed { - buffer.appendInt32(-1963942446) - } - serializeInt64(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(sets.count)) - for item in sets { - item.serialize(buffer, true) - } - break - case .foundStickerSetsNotModified: - if boxed { - buffer.appendInt32(223655517) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .foundStickerSets(let hash, let sets): - return ("foundStickerSets", [("hash", hash as Any), ("sets", sets as Any)]) - case .foundStickerSetsNotModified: - return ("foundStickerSetsNotModified", []) - } - } - - public static func parse_foundStickerSets(_ reader: BufferReader) -> FoundStickerSets? { - var _1: Int64? - _1 = reader.readInt64() - var _2: [Api.StickerSetCovered]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerSetCovered.self) + let _c8 = _8 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.messages.BotResults.botResults(Cons_botResults(flags: _1!, queryId: _2!, nextOffset: _3, switchPm: _4, switchWebview: _5, results: _6!, cacheTime: _7!, users: _8!)) } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.FoundStickerSets.foundStickerSets(hash: _1!, sets: _2!) - } - public static func parse_foundStickerSetsNotModified(_ reader: BufferReader) -> FoundStickerSets? { - return Api.messages.FoundStickerSets.foundStickerSetsNotModified - } - - } -} -public extension Api.messages { - enum FoundStickers: TypeConstructorDescription { - case foundStickers(flags: Int32, nextOffset: Int32?, hash: Int64, stickers: [Api.Document]) - case foundStickersNotModified(flags: Int32, nextOffset: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .foundStickers(let flags, let nextOffset, let hash, let stickers): - if boxed { - buffer.appendInt32(-2100698480) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(nextOffset!, buffer: buffer, boxed: false)} - serializeInt64(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stickers.count)) - for item in stickers { - item.serialize(buffer, true) - } - break - case .foundStickersNotModified(let flags, let nextOffset): - if boxed { - buffer.appendInt32(1611711796) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(nextOffset!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .foundStickers(let flags, let nextOffset, let hash, let stickers): - return ("foundStickers", [("flags", flags as Any), ("nextOffset", nextOffset as Any), ("hash", hash as Any), ("stickers", stickers as Any)]) - case .foundStickersNotModified(let flags, let nextOffset): - return ("foundStickersNotModified", [("flags", flags as Any), ("nextOffset", nextOffset as Any)]) - } - } - - public static func parse_foundStickers(_ reader: BufferReader) -> FoundStickers? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt32() } - var _3: Int64? - _3 = reader.readInt64() - var _4: [Api.Document]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + else { + return nil } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.messages.FoundStickers.foundStickers(flags: _1!, nextOffset: _2, hash: _3!, stickers: _4!) } - public static func parse_foundStickersNotModified(_ reader: BufferReader) -> FoundStickers? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt32() } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.FoundStickers.foundStickersNotModified(flags: _1!, nextOffset: _2) - } - } } public extension Api.messages { - enum HighScores: TypeConstructorDescription { - case highScores(scores: [Api.HighScore], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .highScores(let scores, let users): - if boxed { - buffer.appendInt32(-1707344487) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(scores.count)) - for item in scores { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .highScores(let scores, let users): - return ("highScores", [("scores", scores as Any), ("users", users as Any)]) - } - } - - public static func parse_highScores(_ reader: BufferReader) -> HighScores? { - var _1: [Api.HighScore]? + enum ChatAdminsWithInvites: TypeConstructorDescription { + public class Cons_chatAdminsWithInvites { + public var admins: [Api.ChatAdminWithInvites] + public var users: [Api.User] + public init(admins: [Api.ChatAdminWithInvites], users: [Api.User]) { + self.admins = admins + self.users = users + } + } + case chatAdminsWithInvites(Cons_chatAdminsWithInvites) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatAdminsWithInvites(let _data): + if boxed { + buffer.appendInt32(-1231326505) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.admins.count)) + for item in _data.admins { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatAdminsWithInvites(let _data): + return ("chatAdminsWithInvites", [("admins", _data.admins as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_chatAdminsWithInvites(_ reader: BufferReader) -> ChatAdminsWithInvites? { + var _1: [Api.ChatAdminWithInvites]? if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.HighScore.self) + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ChatAdminWithInvites.self) } var _2: [Api.User]? if let _ = reader.readInt32() { @@ -401,334 +579,61 @@ public extension Api.messages { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.HighScores.highScores(scores: _1!, users: _2!) - } - - } -} -public extension Api.messages { - enum HistoryImport: TypeConstructorDescription { - case historyImport(id: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .historyImport(let id): - if boxed { - buffer.appendInt32(375566091) - } - serializeInt64(id, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .historyImport(let id): - return ("historyImport", [("id", id as Any)]) - } - } - - public static func parse_historyImport(_ reader: BufferReader) -> HistoryImport? { - var _1: Int64? - _1 = reader.readInt64() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.messages.HistoryImport.historyImport(id: _1!) - } - - } -} -public extension Api.messages { - enum HistoryImportParsed: TypeConstructorDescription { - case historyImportParsed(flags: Int32, title: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .historyImportParsed(let flags, let title): - if boxed { - buffer.appendInt32(1578088377) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .historyImportParsed(let flags, let title): - return ("historyImportParsed", [("flags", flags as Any), ("title", title as Any)]) - } - } - - public static func parse_historyImportParsed(_ reader: BufferReader) -> HistoryImportParsed? { - var _1: Int32? - _1 = reader.readInt32() - var _2: String? - if Int(_1!) & Int(1 << 2) != 0 {_2 = parseString(reader) } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 2) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.HistoryImportParsed.historyImportParsed(flags: _1!, title: _2) - } - - } -} -public extension Api.messages { - enum InactiveChats: TypeConstructorDescription { - case inactiveChats(dates: [Int32], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inactiveChats(let dates, let chats, let users): - if boxed { - buffer.appendInt32(-1456996667) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(dates.count)) - for item in dates { - serializeInt32(item, buffer: buffer, boxed: false) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inactiveChats(let dates, let chats, let users): - return ("inactiveChats", [("dates", dates as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_inactiveChats(_ reader: BufferReader) -> InactiveChats? { - var _1: [Int32]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + if _c1 && _c2 { + return Api.messages.ChatAdminsWithInvites.chatAdminsWithInvites(Cons_chatAdminsWithInvites(admins: _1!, users: _2!)) } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + else { + return nil } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.messages.InactiveChats.inactiveChats(dates: _1!, chats: _2!, users: _3!) } - } } public extension Api.messages { - indirect enum InvitedUsers: TypeConstructorDescription { - case invitedUsers(updates: Api.Updates, missingInvitees: [Api.MissingInvitee]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .invitedUsers(let updates, let missingInvitees): - if boxed { - buffer.appendInt32(2136862630) - } - updates.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(missingInvitees.count)) - for item in missingInvitees { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .invitedUsers(let updates, let missingInvitees): - return ("invitedUsers", [("updates", updates as Any), ("missingInvitees", missingInvitees as Any)]) - } - } - - public static func parse_invitedUsers(_ reader: BufferReader) -> InvitedUsers? { - var _1: Api.Updates? + enum ChatFull: TypeConstructorDescription { + public class Cons_chatFull { + public var fullChat: Api.ChatFull + public var chats: [Api.Chat] + public var users: [Api.User] + public init(fullChat: Api.ChatFull, chats: [Api.Chat], users: [Api.User]) { + self.fullChat = fullChat + self.chats = chats + self.users = users + } + } + case chatFull(Cons_chatFull) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatFull(let _data): + if boxed { + buffer.appendInt32(-438840932) + } + _data.fullChat.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatFull(let _data): + return ("chatFull", [("fullChat", _data.fullChat as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_chatFull(_ reader: BufferReader) -> ChatFull? { + var _1: Api.ChatFull? if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Updates - } - var _2: [Api.MissingInvitee]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MissingInvitee.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.InvitedUsers.invitedUsers(updates: _1!, missingInvitees: _2!) - } - - } -} -public extension Api.messages { - enum MessageEditData: TypeConstructorDescription { - case messageEditData(flags: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messageEditData(let flags): - if boxed { - buffer.appendInt32(649453030) - } - serializeInt32(flags, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messageEditData(let flags): - return ("messageEditData", [("flags", flags as Any)]) - } - } - - public static func parse_messageEditData(_ reader: BufferReader) -> MessageEditData? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.messages.MessageEditData.messageEditData(flags: _1!) - } - - } -} -public extension Api.messages { - enum MessageReactionsList: TypeConstructorDescription { - case messageReactionsList(flags: Int32, count: Int32, reactions: [Api.MessagePeerReaction], chats: [Api.Chat], users: [Api.User], nextOffset: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messageReactionsList(let flags, let count, let reactions, let chats, let users, let nextOffset): - if boxed { - buffer.appendInt32(834488621) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(reactions.count)) - for item in reactions { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 0) != 0 {serializeString(nextOffset!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messageReactionsList(let flags, let count, let reactions, let chats, let users, let nextOffset): - return ("messageReactionsList", [("flags", flags as Any), ("count", count as Any), ("reactions", reactions as Any), ("chats", chats as Any), ("users", users as Any), ("nextOffset", nextOffset as Any)]) - } - } - - public static func parse_messageReactionsList(_ reader: BufferReader) -> MessageReactionsList? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: [Api.MessagePeerReaction]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessagePeerReaction.self) - } - var _4: [Api.Chat]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _5: [Api.User]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - var _6: String? - if Int(_1!) & Int(1 << 0) != 0 {_6 = parseString(reader) } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.messages.MessageReactionsList.messageReactionsList(flags: _1!, count: _2!, reactions: _3!, chats: _4!, users: _5!, nextOffset: _6) - } - - } -} -public extension Api.messages { - enum MessageViews: TypeConstructorDescription { - case messageViews(views: [Api.MessageViews], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messageViews(let views, let chats, let users): - if boxed { - buffer.appendInt32(-1228606141) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(views.count)) - for item in views { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messageViews(let views, let chats, let users): - return ("messageViews", [("views", views as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_messageViews(_ reader: BufferReader) -> MessageViews? { - var _1: [Api.MessageViews]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageViews.self) + _1 = Api.parse(reader, signature: signature) as? Api.ChatFull } var _2: [Api.Chat]? if let _ = reader.readInt32() { @@ -741,344 +646,456 @@ public extension Api.messages { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.messages.MessageViews.messageViews(views: _1!, chats: _2!, users: _3!) + if _c1 && _c2 && _c3 { + return Api.messages.ChatFull.chatFull(Cons_chatFull(fullChat: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } } - } } public extension Api.messages { - enum Messages: TypeConstructorDescription { - case channelMessages(flags: Int32, pts: Int32, count: Int32, offsetIdOffset: Int32?, messages: [Api.Message], topics: [Api.ForumTopic], chats: [Api.Chat], users: [Api.User]) - case messages(messages: [Api.Message], topics: [Api.ForumTopic], chats: [Api.Chat], users: [Api.User]) - case messagesNotModified(count: Int32) - case messagesSlice(flags: Int32, count: Int32, nextRate: Int32?, offsetIdOffset: Int32?, searchFlood: Api.SearchPostsFlood?, messages: [Api.Message], topics: [Api.ForumTopic], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .channelMessages(let flags, let pts, let count, let offsetIdOffset, let messages, let topics, let chats, let users): - if boxed { - buffer.appendInt32(-948520370) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(offsetIdOffset!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(topics.count)) - for item in topics { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .messages(let messages, let topics, let chats, let users): - if boxed { - buffer.appendInt32(494135274) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(topics.count)) - for item in topics { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .messagesNotModified(let count): - if boxed { - buffer.appendInt32(1951620897) - } - serializeInt32(count, buffer: buffer, boxed: false) - break - case .messagesSlice(let flags, let count, let nextRate, let offsetIdOffset, let searchFlood, let messages, let topics, let chats, let users): - if boxed { - buffer.appendInt32(1595959062) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(nextRate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(offsetIdOffset!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {searchFlood!.serialize(buffer, true)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(topics.count)) - for item in topics { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .channelMessages(let flags, let pts, let count, let offsetIdOffset, let messages, let topics, let chats, let users): - return ("channelMessages", [("flags", flags as Any), ("pts", pts as Any), ("count", count as Any), ("offsetIdOffset", offsetIdOffset as Any), ("messages", messages as Any), ("topics", topics as Any), ("chats", chats as Any), ("users", users as Any)]) - case .messages(let messages, let topics, let chats, let users): - return ("messages", [("messages", messages as Any), ("topics", topics as Any), ("chats", chats as Any), ("users", users as Any)]) - case .messagesNotModified(let count): - return ("messagesNotModified", [("count", count as Any)]) - case .messagesSlice(let flags, let count, let nextRate, let offsetIdOffset, let searchFlood, let messages, let topics, let chats, let users): - return ("messagesSlice", [("flags", flags as Any), ("count", count as Any), ("nextRate", nextRate as Any), ("offsetIdOffset", offsetIdOffset as Any), ("searchFlood", searchFlood as Any), ("messages", messages as Any), ("topics", topics as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_channelMessages(_ reader: BufferReader) -> Messages? { + enum ChatInviteImporters: TypeConstructorDescription { + public class Cons_chatInviteImporters { + public var count: Int32 + public var importers: [Api.ChatInviteImporter] + public var users: [Api.User] + public init(count: Int32, importers: [Api.ChatInviteImporter], users: [Api.User]) { + self.count = count + self.importers = importers + self.users = users + } + } + case chatInviteImporters(Cons_chatInviteImporters) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatInviteImporters(let _data): + if boxed { + buffer.appendInt32(-2118733814) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.importers.count)) + for item in _data.importers { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatInviteImporters(let _data): + return ("chatInviteImporters", [("count", _data.count as Any), ("importers", _data.importers as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_chatInviteImporters(_ reader: BufferReader) -> ChatInviteImporters? { var _1: Int32? _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() + var _2: [Api.ChatInviteImporter]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ChatInviteImporter.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.messages.ChatInviteImporters.chatInviteImporters(Cons_chatInviteImporters(count: _1!, importers: _2!, users: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.messages { + enum Chats: TypeConstructorDescription { + public class Cons_chats { + public var chats: [Api.Chat] + public init(chats: [Api.Chat]) { + self.chats = chats + } + } + public class Cons_chatsSlice { + public var count: Int32 + public var chats: [Api.Chat] + public init(count: Int32, chats: [Api.Chat]) { + self.count = count + self.chats = chats + } + } + case chats(Cons_chats) + case chatsSlice(Cons_chatsSlice) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chats(let _data): + if boxed { + buffer.appendInt32(1694474197) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + break + case .chatsSlice(let _data): + if boxed { + buffer.appendInt32(-1663561404) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chats(let _data): + return ("chats", [("chats", _data.chats as Any)]) + case .chatsSlice(let _data): + return ("chatsSlice", [("count", _data.count as Any), ("chats", _data.chats as Any)]) + } + } + + public static func parse_chats(_ reader: BufferReader) -> Chats? { + var _1: [Api.Chat]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + let _c1 = _1 != nil + if _c1 { + return Api.messages.Chats.chats(Cons_chats(chats: _1!)) + } + else { + return nil + } + } + public static func parse_chatsSlice(_ reader: BufferReader) -> Chats? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.Chats.chatsSlice(Cons_chatsSlice(count: _1!, chats: _2!)) + } + else { + return nil + } + } + } +} +public extension Api.messages { + enum CheckedHistoryImportPeer: TypeConstructorDescription { + public class Cons_checkedHistoryImportPeer { + public var confirmText: String + public init(confirmText: String) { + self.confirmText = confirmText + } + } + case checkedHistoryImportPeer(Cons_checkedHistoryImportPeer) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .checkedHistoryImportPeer(let _data): + if boxed { + buffer.appendInt32(-1571952873) + } + serializeString(_data.confirmText, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .checkedHistoryImportPeer(let _data): + return ("checkedHistoryImportPeer", [("confirmText", _data.confirmText as Any)]) + } + } + + public static func parse_checkedHistoryImportPeer(_ reader: BufferReader) -> CheckedHistoryImportPeer? { + var _1: String? + _1 = parseString(reader) + let _c1 = _1 != nil + if _c1 { + return Api.messages.CheckedHistoryImportPeer.checkedHistoryImportPeer(Cons_checkedHistoryImportPeer(confirmText: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.messages { + enum DhConfig: TypeConstructorDescription { + public class Cons_dhConfig { + public var g: Int32 + public var p: Buffer + public var version: Int32 + public var random: Buffer + public init(g: Int32, p: Buffer, version: Int32, random: Buffer) { + self.g = g + self.p = p + self.version = version + self.random = random + } + } + public class Cons_dhConfigNotModified { + public var random: Buffer + public init(random: Buffer) { + self.random = random + } + } + case dhConfig(Cons_dhConfig) + case dhConfigNotModified(Cons_dhConfigNotModified) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .dhConfig(let _data): + if boxed { + buffer.appendInt32(740433629) + } + serializeInt32(_data.g, buffer: buffer, boxed: false) + serializeBytes(_data.p, buffer: buffer, boxed: false) + serializeInt32(_data.version, buffer: buffer, boxed: false) + serializeBytes(_data.random, buffer: buffer, boxed: false) + break + case .dhConfigNotModified(let _data): + if boxed { + buffer.appendInt32(-1058912715) + } + serializeBytes(_data.random, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .dhConfig(let _data): + return ("dhConfig", [("g", _data.g as Any), ("p", _data.p as Any), ("version", _data.version as Any), ("random", _data.random as Any)]) + case .dhConfigNotModified(let _data): + return ("dhConfigNotModified", [("random", _data.random as Any)]) + } + } + + public static func parse_dhConfig(_ reader: BufferReader) -> DhConfig? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Buffer? + _2 = parseBytes(reader) var _3: Int32? _3 = reader.readInt32() - var _4: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_4 = reader.readInt32() } - var _5: [Api.Message]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) - } - var _6: [Api.ForumTopic]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ForumTopic.self) - } - var _7: [Api.Chat]? - if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _8: [Api.User]? - if let _ = reader.readInt32() { - _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - let _c7 = _7 != nil - let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.messages.Messages.channelMessages(flags: _1!, pts: _2!, count: _3!, offsetIdOffset: _4, messages: _5!, topics: _6!, chats: _7!, users: _8!) - } - public static func parse_messages(_ reader: BufferReader) -> Messages? { - var _1: [Api.Message]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) - } - var _2: [Api.ForumTopic]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ForumTopic.self) - } - var _3: [Api.Chat]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _4: [Api.User]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } + var _4: Buffer? + _4 = parseBytes(reader) let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.messages.Messages.messages(messages: _1!, topics: _2!, chats: _3!, users: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.messages.DhConfig.dhConfig(Cons_dhConfig(g: _1!, p: _2!, version: _3!, random: _4!)) + } + else { + return nil + } } - public static func parse_messagesNotModified(_ reader: BufferReader) -> Messages? { - var _1: Int32? - _1 = reader.readInt32() + public static func parse_dhConfigNotModified(_ reader: BufferReader) -> DhConfig? { + var _1: Buffer? + _1 = parseBytes(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.messages.Messages.messagesNotModified(count: _1!) + if _c1 { + return Api.messages.DhConfig.dhConfigNotModified(Cons_dhConfigNotModified(random: _1!)) + } + else { + return nil + } } - public static func parse_messagesSlice(_ reader: BufferReader) -> Messages? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } - var _4: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_4 = reader.readInt32() } - var _5: Api.SearchPostsFlood? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.SearchPostsFlood - } } - var _6: [Api.Message]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) - } - var _7: [Api.ForumTopic]? - if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ForumTopic.self) - } - var _8: [Api.Chat]? - if let _ = reader.readInt32() { - _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _9: [Api.User]? - if let _ = reader.readInt32() { - _9 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 3) == 0) || _5 != nil - let _c6 = _6 != nil - let _c7 = _7 != nil - let _c8 = _8 != nil - let _c9 = _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.messages.Messages.messagesSlice(flags: _1!, count: _2!, nextRate: _3, offsetIdOffset: _4, searchFlood: _5, messages: _6!, topics: _7!, chats: _8!, users: _9!) - } - } } public extension Api.messages { - enum MyStickers: TypeConstructorDescription { - case myStickers(count: Int32, sets: [Api.StickerSetCovered]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .myStickers(let count, let sets): - if boxed { - buffer.appendInt32(-83926371) - } - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(sets.count)) - for item in sets { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .myStickers(let count, let sets): - return ("myStickers", [("count", count as Any), ("sets", sets as Any)]) - } - } - - public static func parse_myStickers(_ reader: BufferReader) -> MyStickers? { + enum DialogFilters: TypeConstructorDescription { + public class Cons_dialogFilters { + public var flags: Int32 + public var filters: [Api.DialogFilter] + public init(flags: Int32, filters: [Api.DialogFilter]) { + self.flags = flags + self.filters = filters + } + } + case dialogFilters(Cons_dialogFilters) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .dialogFilters(let _data): + if boxed { + buffer.appendInt32(718878489) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.filters.count)) + for item in _data.filters { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .dialogFilters(let _data): + return ("dialogFilters", [("flags", _data.flags as Any), ("filters", _data.filters as Any)]) + } + } + + public static func parse_dialogFilters(_ reader: BufferReader) -> DialogFilters? { var _1: Int32? _1 = reader.readInt32() - var _2: [Api.StickerSetCovered]? + var _2: [Api.DialogFilter]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerSetCovered.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.DialogFilter.self) } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.MyStickers.myStickers(count: _1!, sets: _2!) + if _c1 && _c2 { + return Api.messages.DialogFilters.dialogFilters(Cons_dialogFilters(flags: _1!, filters: _2!)) + } + else { + return nil + } } - } } public extension Api.messages { - enum PeerDialogs: TypeConstructorDescription { - case peerDialogs(dialogs: [Api.Dialog], messages: [Api.Message], chats: [Api.Chat], users: [Api.User], state: Api.updates.State) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .peerDialogs(let dialogs, let messages, let chats, let users, let state): - if boxed { - buffer.appendInt32(863093588) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(dialogs.count)) - for item in dialogs { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - state.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .peerDialogs(let dialogs, let messages, let chats, let users, let state): - return ("peerDialogs", [("dialogs", dialogs as Any), ("messages", messages as Any), ("chats", chats as Any), ("users", users as Any), ("state", state as Any)]) - } - } - - public static func parse_peerDialogs(_ reader: BufferReader) -> PeerDialogs? { + enum Dialogs: TypeConstructorDescription { + public class Cons_dialogs { + public var dialogs: [Api.Dialog] + public var messages: [Api.Message] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(dialogs: [Api.Dialog], messages: [Api.Message], chats: [Api.Chat], users: [Api.User]) { + self.dialogs = dialogs + self.messages = messages + self.chats = chats + self.users = users + } + } + public class Cons_dialogsNotModified { + public var count: Int32 + public init(count: Int32) { + self.count = count + } + } + public class Cons_dialogsSlice { + public var count: Int32 + public var dialogs: [Api.Dialog] + public var messages: [Api.Message] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(count: Int32, dialogs: [Api.Dialog], messages: [Api.Message], chats: [Api.Chat], users: [Api.User]) { + self.count = count + self.dialogs = dialogs + self.messages = messages + self.chats = chats + self.users = users + } + } + case dialogs(Cons_dialogs) + case dialogsNotModified(Cons_dialogsNotModified) + case dialogsSlice(Cons_dialogsSlice) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .dialogs(let _data): + if boxed { + buffer.appendInt32(364538944) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.dialogs.count)) + for item in _data.dialogs { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .dialogsNotModified(let _data): + if boxed { + buffer.appendInt32(-253500010) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + break + case .dialogsSlice(let _data): + if boxed { + buffer.appendInt32(1910543603) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.dialogs.count)) + for item in _data.dialogs { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .dialogs(let _data): + return ("dialogs", [("dialogs", _data.dialogs as Any), ("messages", _data.messages as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + case .dialogsNotModified(let _data): + return ("dialogsNotModified", [("count", _data.count as Any)]) + case .dialogsSlice(let _data): + return ("dialogsSlice", [("count", _data.count as Any), ("dialogs", _data.dialogs as Any), ("messages", _data.messages as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_dialogs(_ reader: BufferReader) -> Dialogs? { var _1: [Api.Dialog]? if let _ = reader.readInt32() { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Dialog.self) @@ -1095,481 +1112,34 @@ public extension Api.messages { if let _ = reader.readInt32() { _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } - var _5: Api.updates.State? - if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.updates.State - } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.messages.PeerDialogs.peerDialogs(dialogs: _1!, messages: _2!, chats: _3!, users: _4!, state: _5!) + if _c1 && _c2 && _c3 && _c4 { + return Api.messages.Dialogs.dialogs(Cons_dialogs(dialogs: _1!, messages: _2!, chats: _3!, users: _4!)) + } + else { + return nil + } } - - } -} -public extension Api.messages { - enum PeerSettings: TypeConstructorDescription { - case peerSettings(settings: Api.PeerSettings, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .peerSettings(let settings, let chats, let users): - if boxed { - buffer.appendInt32(1753266509) - } - settings.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .peerSettings(let settings, let chats, let users): - return ("peerSettings", [("settings", settings as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_peerSettings(_ reader: BufferReader) -> PeerSettings? { - var _1: Api.PeerSettings? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.PeerSettings - } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.messages.PeerSettings.peerSettings(settings: _1!, chats: _2!, users: _3!) - } - - } -} -public extension Api.messages { - enum PreparedInlineMessage: TypeConstructorDescription { - case preparedInlineMessage(queryId: Int64, result: Api.BotInlineResult, peerTypes: [Api.InlineQueryPeerType], cacheTime: Int32, users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .preparedInlineMessage(let queryId, let result, let peerTypes, let cacheTime, let users): - if boxed { - buffer.appendInt32(-11046771) - } - serializeInt64(queryId, buffer: buffer, boxed: false) - result.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peerTypes.count)) - for item in peerTypes { - item.serialize(buffer, true) - } - serializeInt32(cacheTime, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .preparedInlineMessage(let queryId, let result, let peerTypes, let cacheTime, let users): - return ("preparedInlineMessage", [("queryId", queryId as Any), ("result", result as Any), ("peerTypes", peerTypes as Any), ("cacheTime", cacheTime as Any), ("users", users as Any)]) - } - } - - public static func parse_preparedInlineMessage(_ reader: BufferReader) -> PreparedInlineMessage? { - var _1: Int64? - _1 = reader.readInt64() - var _2: Api.BotInlineResult? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.BotInlineResult - } - var _3: [Api.InlineQueryPeerType]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InlineQueryPeerType.self) - } - var _4: Int32? - _4 = reader.readInt32() - var _5: [Api.User]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.messages.PreparedInlineMessage.preparedInlineMessage(queryId: _1!, result: _2!, peerTypes: _3!, cacheTime: _4!, users: _5!) - } - - } -} -public extension Api.messages { - enum QuickReplies: TypeConstructorDescription { - case quickReplies(quickReplies: [Api.QuickReply], messages: [Api.Message], chats: [Api.Chat], users: [Api.User]) - case quickRepliesNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .quickReplies(let quickReplies, let messages, let chats, let users): - if boxed { - buffer.appendInt32(-963811691) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(quickReplies.count)) - for item in quickReplies { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .quickRepliesNotModified: - if boxed { - buffer.appendInt32(1603398491) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .quickReplies(let quickReplies, let messages, let chats, let users): - return ("quickReplies", [("quickReplies", quickReplies as Any), ("messages", messages as Any), ("chats", chats as Any), ("users", users as Any)]) - case .quickRepliesNotModified: - return ("quickRepliesNotModified", []) - } - } - - public static func parse_quickReplies(_ reader: BufferReader) -> QuickReplies? { - var _1: [Api.QuickReply]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.QuickReply.self) - } - var _2: [Api.Message]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) - } - var _3: [Api.Chat]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _4: [Api.User]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.messages.QuickReplies.quickReplies(quickReplies: _1!, messages: _2!, chats: _3!, users: _4!) - } - public static func parse_quickRepliesNotModified(_ reader: BufferReader) -> QuickReplies? { - return Api.messages.QuickReplies.quickRepliesNotModified - } - - } -} -public extension Api.messages { - enum Reactions: TypeConstructorDescription { - case reactions(hash: Int64, reactions: [Api.Reaction]) - case reactionsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .reactions(let hash, let reactions): - if boxed { - buffer.appendInt32(-352454890) - } - serializeInt64(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(reactions.count)) - for item in reactions { - item.serialize(buffer, true) - } - break - case .reactionsNotModified: - if boxed { - buffer.appendInt32(-1334846497) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .reactions(let hash, let reactions): - return ("reactions", [("hash", hash as Any), ("reactions", reactions as Any)]) - case .reactionsNotModified: - return ("reactionsNotModified", []) - } - } - - public static func parse_reactions(_ reader: BufferReader) -> Reactions? { - var _1: Int64? - _1 = reader.readInt64() - var _2: [Api.Reaction]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Reaction.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.Reactions.reactions(hash: _1!, reactions: _2!) - } - public static func parse_reactionsNotModified(_ reader: BufferReader) -> Reactions? { - return Api.messages.Reactions.reactionsNotModified - } - - } -} -public extension Api.messages { - enum RecentStickers: TypeConstructorDescription { - case recentStickers(hash: Int64, packs: [Api.StickerPack], stickers: [Api.Document], dates: [Int32]) - case recentStickersNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .recentStickers(let hash, let packs, let stickers, let dates): - if boxed { - buffer.appendInt32(-1999405994) - } - serializeInt64(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(packs.count)) - for item in packs { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stickers.count)) - for item in stickers { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(dates.count)) - for item in dates { - serializeInt32(item, buffer: buffer, boxed: false) - } - break - case .recentStickersNotModified: - if boxed { - buffer.appendInt32(186120336) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .recentStickers(let hash, let packs, let stickers, let dates): - return ("recentStickers", [("hash", hash as Any), ("packs", packs as Any), ("stickers", stickers as Any), ("dates", dates as Any)]) - case .recentStickersNotModified: - return ("recentStickersNotModified", []) - } - } - - public static func parse_recentStickers(_ reader: BufferReader) -> RecentStickers? { - var _1: Int64? - _1 = reader.readInt64() - var _2: [Api.StickerPack]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerPack.self) - } - var _3: [Api.Document]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) - } - var _4: [Int32]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.messages.RecentStickers.recentStickers(hash: _1!, packs: _2!, stickers: _3!, dates: _4!) - } - public static func parse_recentStickersNotModified(_ reader: BufferReader) -> RecentStickers? { - return Api.messages.RecentStickers.recentStickersNotModified - } - - } -} -public extension Api.messages { - enum SavedDialogs: TypeConstructorDescription { - case savedDialogs(dialogs: [Api.SavedDialog], messages: [Api.Message], chats: [Api.Chat], users: [Api.User]) - case savedDialogsNotModified(count: Int32) - case savedDialogsSlice(count: Int32, dialogs: [Api.SavedDialog], messages: [Api.Message], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .savedDialogs(let dialogs, let messages, let chats, let users): - if boxed { - buffer.appendInt32(-130358751) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(dialogs.count)) - for item in dialogs { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .savedDialogsNotModified(let count): - if boxed { - buffer.appendInt32(-1071681560) - } - serializeInt32(count, buffer: buffer, boxed: false) - break - case .savedDialogsSlice(let count, let dialogs, let messages, let chats, let users): - if boxed { - buffer.appendInt32(1153080793) - } - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(dialogs.count)) - for item in dialogs { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .savedDialogs(let dialogs, let messages, let chats, let users): - return ("savedDialogs", [("dialogs", dialogs as Any), ("messages", messages as Any), ("chats", chats as Any), ("users", users as Any)]) - case .savedDialogsNotModified(let count): - return ("savedDialogsNotModified", [("count", count as Any)]) - case .savedDialogsSlice(let count, let dialogs, let messages, let chats, let users): - return ("savedDialogsSlice", [("count", count as Any), ("dialogs", dialogs as Any), ("messages", messages as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_savedDialogs(_ reader: BufferReader) -> SavedDialogs? { - var _1: [Api.SavedDialog]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SavedDialog.self) - } - var _2: [Api.Message]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) - } - var _3: [Api.Chat]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _4: [Api.User]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.messages.SavedDialogs.savedDialogs(dialogs: _1!, messages: _2!, chats: _3!, users: _4!) - } - public static func parse_savedDialogsNotModified(_ reader: BufferReader) -> SavedDialogs? { + public static func parse_dialogsNotModified(_ reader: BufferReader) -> Dialogs? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.messages.SavedDialogs.savedDialogsNotModified(count: _1!) + if _c1 { + return Api.messages.Dialogs.dialogsNotModified(Cons_dialogsNotModified(count: _1!)) + } + else { + return nil + } } - public static func parse_savedDialogsSlice(_ reader: BufferReader) -> SavedDialogs? { + public static func parse_dialogsSlice(_ reader: BufferReader) -> Dialogs? { var _1: Int32? _1 = reader.readInt32() - var _2: [Api.SavedDialog]? + var _2: [Api.Dialog]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SavedDialog.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Dialog.self) } var _3: [Api.Message]? if let _ = reader.readInt32() { @@ -1588,13 +1158,502 @@ public extension Api.messages { let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.messages.SavedDialogs.savedDialogsSlice(count: _1!, dialogs: _2!, messages: _3!, chats: _4!, users: _5!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.messages.Dialogs.dialogsSlice(Cons_dialogsSlice(count: _1!, dialogs: _2!, messages: _3!, chats: _4!, users: _5!)) + } + else { + return nil + } + } + } +} +public extension Api.messages { + enum DiscussionMessage: TypeConstructorDescription { + public class Cons_discussionMessage { + public var flags: Int32 + public var messages: [Api.Message] + public var maxId: Int32? + public var readInboxMaxId: Int32? + public var readOutboxMaxId: Int32? + public var unreadCount: Int32 + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, messages: [Api.Message], maxId: Int32?, readInboxMaxId: Int32?, readOutboxMaxId: Int32?, unreadCount: Int32, chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.messages = messages + self.maxId = maxId + self.readInboxMaxId = readInboxMaxId + self.readOutboxMaxId = readOutboxMaxId + self.unreadCount = unreadCount + self.chats = chats + self.users = users + } + } + case discussionMessage(Cons_discussionMessage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .discussionMessage(let _data): + if boxed { + buffer.appendInt32(-1506535550) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.maxId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.readInboxMaxId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.readOutboxMaxId!, buffer: buffer, boxed: false) + } + serializeInt32(_data.unreadCount, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .discussionMessage(let _data): + return ("discussionMessage", [("flags", _data.flags as Any), ("messages", _data.messages as Any), ("maxId", _data.maxId as Any), ("readInboxMaxId", _data.readInboxMaxId as Any), ("readOutboxMaxId", _data.readOutboxMaxId as Any), ("unreadCount", _data.unreadCount as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_discussionMessage(_ reader: BufferReader) -> DiscussionMessage? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.Message]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) + } + var _3: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } + var _4: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _4 = reader.readInt32() + } + var _5: Int32? + if Int(_1!) & Int(1 << 2) != 0 { + _5 = reader.readInt32() + } + var _6: Int32? + _6 = reader.readInt32() + var _7: [Api.Chat]? + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _8: [Api.User]? + if let _ = reader.readInt32() { + _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil + let _c5 = (Int(_1!) & Int(1 << 2) == 0) || _5 != nil + let _c6 = _6 != nil + let _c7 = _7 != nil + let _c8 = _8 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.messages.DiscussionMessage.discussionMessage(Cons_discussionMessage(flags: _1!, messages: _2!, maxId: _3, readInboxMaxId: _4, readOutboxMaxId: _5, unreadCount: _6!, chats: _7!, users: _8!)) + } + else { + return nil + } + } + } +} +public extension Api.messages { + enum EmojiGameInfo: TypeConstructorDescription { + public class Cons_emojiGameDiceInfo { + public var flags: Int32 + public var gameHash: String + public var prevStake: Int64 + public var currentStreak: Int32 + public var params: [Int32] + public var playsLeft: Int32? + public init(flags: Int32, gameHash: String, prevStake: Int64, currentStreak: Int32, params: [Int32], playsLeft: Int32?) { + self.flags = flags + self.gameHash = gameHash + self.prevStake = prevStake + self.currentStreak = currentStreak + self.params = params + self.playsLeft = playsLeft + } + } + case emojiGameDiceInfo(Cons_emojiGameDiceInfo) + case emojiGameUnavailable + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .emojiGameDiceInfo(let _data): + if boxed { + buffer.appendInt32(1155883043) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.gameHash, buffer: buffer, boxed: false) + serializeInt64(_data.prevStake, buffer: buffer, boxed: false) + serializeInt32(_data.currentStreak, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.params.count)) + for item in _data.params { + serializeInt32(item, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.playsLeft!, buffer: buffer, boxed: false) + } + break + case .emojiGameUnavailable: + if boxed { + buffer.appendInt32(1508266805) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .emojiGameDiceInfo(let _data): + return ("emojiGameDiceInfo", [("flags", _data.flags as Any), ("gameHash", _data.gameHash as Any), ("prevStake", _data.prevStake as Any), ("currentStreak", _data.currentStreak as Any), ("params", _data.params as Any), ("playsLeft", _data.playsLeft as Any)]) + case .emojiGameUnavailable: + return ("emojiGameUnavailable", []) + } + } + + public static func parse_emojiGameDiceInfo(_ reader: BufferReader) -> EmojiGameInfo? { + var _1: Int32? + _1 = reader.readInt32() + var _2: String? + _2 = parseString(reader) + var _3: Int64? + _3 = reader.readInt64() + var _4: Int32? + _4 = reader.readInt32() + var _5: [Int32]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + var _6: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _6 = reader.readInt32() + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.messages.EmojiGameInfo.emojiGameDiceInfo(Cons_emojiGameDiceInfo(flags: _1!, gameHash: _2!, prevStake: _3!, currentStreak: _4!, params: _5!, playsLeft: _6)) + } + else { + return nil + } + } + public static func parse_emojiGameUnavailable(_ reader: BufferReader) -> EmojiGameInfo? { + return Api.messages.EmojiGameInfo.emojiGameUnavailable + } + } +} +public extension Api.messages { + enum EmojiGameOutcome: TypeConstructorDescription { + public class Cons_emojiGameOutcome { + public var seed: Buffer + public var stakeTonAmount: Int64 + public var tonAmount: Int64 + public init(seed: Buffer, stakeTonAmount: Int64, tonAmount: Int64) { + self.seed = seed + self.stakeTonAmount = stakeTonAmount + self.tonAmount = tonAmount + } + } + case emojiGameOutcome(Cons_emojiGameOutcome) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .emojiGameOutcome(let _data): + if boxed { + buffer.appendInt32(-634726841) + } + serializeBytes(_data.seed, buffer: buffer, boxed: false) + serializeInt64(_data.stakeTonAmount, buffer: buffer, boxed: false) + serializeInt64(_data.tonAmount, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .emojiGameOutcome(let _data): + return ("emojiGameOutcome", [("seed", _data.seed as Any), ("stakeTonAmount", _data.stakeTonAmount as Any), ("tonAmount", _data.tonAmount as Any)]) + } + } + + public static func parse_emojiGameOutcome(_ reader: BufferReader) -> EmojiGameOutcome? { + var _1: Buffer? + _1 = parseBytes(reader) + var _2: Int64? + _2 = reader.readInt64() + var _3: Int64? + _3 = reader.readInt64() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.messages.EmojiGameOutcome.emojiGameOutcome(Cons_emojiGameOutcome(seed: _1!, stakeTonAmount: _2!, tonAmount: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.messages { + enum EmojiGroups: TypeConstructorDescription { + public class Cons_emojiGroups { + public var hash: Int32 + public var groups: [Api.EmojiGroup] + public init(hash: Int32, groups: [Api.EmojiGroup]) { + self.hash = hash + self.groups = groups + } + } + case emojiGroups(Cons_emojiGroups) + case emojiGroupsNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .emojiGroups(let _data): + if boxed { + buffer.appendInt32(-2011186869) + } + serializeInt32(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.groups.count)) + for item in _data.groups { + item.serialize(buffer, true) + } + break + case .emojiGroupsNotModified: + if boxed { + buffer.appendInt32(1874111879) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .emojiGroups(let _data): + return ("emojiGroups", [("hash", _data.hash as Any), ("groups", _data.groups as Any)]) + case .emojiGroupsNotModified: + return ("emojiGroupsNotModified", []) + } + } + + public static func parse_emojiGroups(_ reader: BufferReader) -> EmojiGroups? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.EmojiGroup]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.EmojiGroup.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.EmojiGroups.emojiGroups(Cons_emojiGroups(hash: _1!, groups: _2!)) + } + else { + return nil + } + } + public static func parse_emojiGroupsNotModified(_ reader: BufferReader) -> EmojiGroups? { + return Api.messages.EmojiGroups.emojiGroupsNotModified + } + } +} +public extension Api.messages { + enum ExportedChatInvite: TypeConstructorDescription { + public class Cons_exportedChatInvite { + public var invite: Api.ExportedChatInvite + public var users: [Api.User] + public init(invite: Api.ExportedChatInvite, users: [Api.User]) { + self.invite = invite + self.users = users + } + } + public class Cons_exportedChatInviteReplaced { + public var invite: Api.ExportedChatInvite + public var newInvite: Api.ExportedChatInvite + public var users: [Api.User] + public init(invite: Api.ExportedChatInvite, newInvite: Api.ExportedChatInvite, users: [Api.User]) { + self.invite = invite + self.newInvite = newInvite + self.users = users + } + } + case exportedChatInvite(Cons_exportedChatInvite) + case exportedChatInviteReplaced(Cons_exportedChatInviteReplaced) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .exportedChatInvite(let _data): + if boxed { + buffer.appendInt32(410107472) + } + _data.invite.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .exportedChatInviteReplaced(let _data): + if boxed { + buffer.appendInt32(572915951) + } + _data.invite.serialize(buffer, true) + _data.newInvite.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .exportedChatInvite(let _data): + return ("exportedChatInvite", [("invite", _data.invite as Any), ("users", _data.users as Any)]) + case .exportedChatInviteReplaced(let _data): + return ("exportedChatInviteReplaced", [("invite", _data.invite as Any), ("newInvite", _data.newInvite as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_exportedChatInvite(_ reader: BufferReader) -> ExportedChatInvite? { + var _1: Api.ExportedChatInvite? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite + } + var _2: [Api.User]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.ExportedChatInvite.exportedChatInvite(Cons_exportedChatInvite(invite: _1!, users: _2!)) + } + else { + return nil + } + } + public static func parse_exportedChatInviteReplaced(_ reader: BufferReader) -> ExportedChatInvite? { + var _1: Api.ExportedChatInvite? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite + } + var _2: Api.ExportedChatInvite? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.messages.ExportedChatInvite.exportedChatInviteReplaced(Cons_exportedChatInviteReplaced(invite: _1!, newInvite: _2!, users: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.messages { + enum ExportedChatInvites: TypeConstructorDescription { + public class Cons_exportedChatInvites { + public var count: Int32 + public var invites: [Api.ExportedChatInvite] + public var users: [Api.User] + public init(count: Int32, invites: [Api.ExportedChatInvite], users: [Api.User]) { + self.count = count + self.invites = invites + self.users = users + } + } + case exportedChatInvites(Cons_exportedChatInvites) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .exportedChatInvites(let _data): + if boxed { + buffer.appendInt32(-1111085620) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.invites.count)) + for item in _data.invites { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .exportedChatInvites(let _data): + return ("exportedChatInvites", [("count", _data.count as Any), ("invites", _data.invites as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_exportedChatInvites(_ reader: BufferReader) -> ExportedChatInvites? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.ExportedChatInvite]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ExportedChatInvite.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.messages.ExportedChatInvites.exportedChatInvites(Cons_exportedChatInvites(count: _1!, invites: _2!, users: _3!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api35.swift b/submodules/TelegramApi/Sources/Api35.swift index 0898d641..d45e694a 100644 --- a/submodules/TelegramApi/Sources/Api35.swift +++ b/submodules/TelegramApi/Sources/Api35.swift @@ -1,764 +1,835 @@ public extension Api.messages { - enum SavedGifs: TypeConstructorDescription { - case savedGifs(hash: Int64, gifs: [Api.Document]) - case savedGifsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .savedGifs(let hash, let gifs): - if boxed { - buffer.appendInt32(-2069878259) - } - serializeInt64(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(gifs.count)) - for item in gifs { - item.serialize(buffer, true) - } - break - case .savedGifsNotModified: - if boxed { - buffer.appendInt32(-402498398) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .savedGifs(let hash, let gifs): - return ("savedGifs", [("hash", hash as Any), ("gifs", gifs as Any)]) - case .savedGifsNotModified: - return ("savedGifsNotModified", []) - } - } - - public static func parse_savedGifs(_ reader: BufferReader) -> SavedGifs? { + enum FavedStickers: TypeConstructorDescription { + public class Cons_favedStickers { + public var hash: Int64 + public var packs: [Api.StickerPack] + public var stickers: [Api.Document] + public init(hash: Int64, packs: [Api.StickerPack], stickers: [Api.Document]) { + self.hash = hash + self.packs = packs + self.stickers = stickers + } + } + case favedStickers(Cons_favedStickers) + case favedStickersNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .favedStickers(let _data): + if boxed { + buffer.appendInt32(750063767) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.packs.count)) + for item in _data.packs { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.stickers.count)) + for item in _data.stickers { + item.serialize(buffer, true) + } + break + case .favedStickersNotModified: + if boxed { + buffer.appendInt32(-1634752813) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .favedStickers(let _data): + return ("favedStickers", [("hash", _data.hash as Any), ("packs", _data.packs as Any), ("stickers", _data.stickers as Any)]) + case .favedStickersNotModified: + return ("favedStickersNotModified", []) + } + } + + public static func parse_favedStickers(_ reader: BufferReader) -> FavedStickers? { var _1: Int64? _1 = reader.readInt64() - var _2: [Api.Document]? + var _2: [Api.StickerPack]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerPack.self) } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.SavedGifs.savedGifs(hash: _1!, gifs: _2!) - } - public static func parse_savedGifsNotModified(_ reader: BufferReader) -> SavedGifs? { - return Api.messages.SavedGifs.savedGifsNotModified - } - - } -} -public extension Api.messages { - enum SavedReactionTags: TypeConstructorDescription { - case savedReactionTags(tags: [Api.SavedReactionTag], hash: Int64) - case savedReactionTagsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .savedReactionTags(let tags, let hash): - if boxed { - buffer.appendInt32(844731658) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(tags.count)) - for item in tags { - item.serialize(buffer, true) - } - serializeInt64(hash, buffer: buffer, boxed: false) - break - case .savedReactionTagsNotModified: - if boxed { - buffer.appendInt32(-2003084817) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .savedReactionTags(let tags, let hash): - return ("savedReactionTags", [("tags", tags as Any), ("hash", hash as Any)]) - case .savedReactionTagsNotModified: - return ("savedReactionTagsNotModified", []) - } - } - - public static func parse_savedReactionTags(_ reader: BufferReader) -> SavedReactionTags? { - var _1: [Api.SavedReactionTag]? + var _3: [Api.Document]? if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SavedReactionTag.self) + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) } - var _2: Int64? - _2 = reader.readInt64() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.SavedReactionTags.savedReactionTags(tags: _1!, hash: _2!) - } - public static func parse_savedReactionTagsNotModified(_ reader: BufferReader) -> SavedReactionTags? { - return Api.messages.SavedReactionTags.savedReactionTagsNotModified - } - - } -} -public extension Api.messages { - enum SearchCounter: TypeConstructorDescription { - case searchCounter(flags: Int32, filter: Api.MessagesFilter, count: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .searchCounter(let flags, let filter, let count): - if boxed { - buffer.appendInt32(-398136321) - } - serializeInt32(flags, buffer: buffer, boxed: false) - filter.serialize(buffer, true) - serializeInt32(count, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .searchCounter(let flags, let filter, let count): - return ("searchCounter", [("flags", flags as Any), ("filter", filter as Any), ("count", count as Any)]) - } - } - - public static func parse_searchCounter(_ reader: BufferReader) -> SearchCounter? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.MessagesFilter? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.MessagesFilter - } - var _3: Int32? - _3 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.messages.SearchCounter.searchCounter(flags: _1!, filter: _2!, count: _3!) + if _c1 && _c2 && _c3 { + return Api.messages.FavedStickers.favedStickers(Cons_favedStickers(hash: _1!, packs: _2!, stickers: _3!)) + } + else { + return nil + } + } + public static func parse_favedStickersNotModified(_ reader: BufferReader) -> FavedStickers? { + return Api.messages.FavedStickers.favedStickersNotModified } - } } public extension Api.messages { - enum SearchResultsCalendar: TypeConstructorDescription { - case searchResultsCalendar(flags: Int32, count: Int32, minDate: Int32, minMsgId: Int32, offsetIdOffset: Int32?, periods: [Api.SearchResultsCalendarPeriod], messages: [Api.Message], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .searchResultsCalendar(let flags, let count, let minDate, let minMsgId, let offsetIdOffset, let periods, let messages, let chats, let users): - if boxed { - buffer.appendInt32(343859772) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - serializeInt32(minDate, buffer: buffer, boxed: false) - serializeInt32(minMsgId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(offsetIdOffset!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(periods.count)) - for item in periods { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .searchResultsCalendar(let flags, let count, let minDate, let minMsgId, let offsetIdOffset, let periods, let messages, let chats, let users): - return ("searchResultsCalendar", [("flags", flags as Any), ("count", count as Any), ("minDate", minDate as Any), ("minMsgId", minMsgId as Any), ("offsetIdOffset", offsetIdOffset as Any), ("periods", periods as Any), ("messages", messages as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_searchResultsCalendar(_ reader: BufferReader) -> SearchResultsCalendar? { + enum FeaturedStickers: TypeConstructorDescription { + public class Cons_featuredStickers { + public var flags: Int32 + public var hash: Int64 + public var count: Int32 + public var sets: [Api.StickerSetCovered] + public var unread: [Int64] + public init(flags: Int32, hash: Int64, count: Int32, sets: [Api.StickerSetCovered], unread: [Int64]) { + self.flags = flags + self.hash = hash + self.count = count + self.sets = sets + self.unread = unread + } + } + public class Cons_featuredStickersNotModified { + public var count: Int32 + public init(count: Int32) { + self.count = count + } + } + case featuredStickers(Cons_featuredStickers) + case featuredStickersNotModified(Cons_featuredStickersNotModified) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .featuredStickers(let _data): + if boxed { + buffer.appendInt32(-1103615738) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.hash, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.sets.count)) + for item in _data.sets { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.unread.count)) + for item in _data.unread { + serializeInt64(item, buffer: buffer, boxed: false) + } + break + case .featuredStickersNotModified(let _data): + if boxed { + buffer.appendInt32(-958657434) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .featuredStickers(let _data): + return ("featuredStickers", [("flags", _data.flags as Any), ("hash", _data.hash as Any), ("count", _data.count as Any), ("sets", _data.sets as Any), ("unread", _data.unread as Any)]) + case .featuredStickersNotModified(let _data): + return ("featuredStickersNotModified", [("count", _data.count as Any)]) + } + } + + public static func parse_featuredStickers(_ reader: BufferReader) -> FeaturedStickers? { var _1: Int32? _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() var _3: Int32? _3 = reader.readInt32() - var _4: Int32? - _4 = reader.readInt32() - var _5: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_5 = reader.readInt32() } - var _6: [Api.SearchResultsCalendarPeriod]? + var _4: [Api.StickerSetCovered]? if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SearchResultsCalendarPeriod.self) + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerSetCovered.self) } - var _7: [Api.Message]? + var _5: [Int64]? if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) - } - var _8: [Api.Chat]? - if let _ = reader.readInt32() { - _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _9: [Api.User]? - if let _ = reader.readInt32() { - _9 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + _5 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - let _c6 = _6 != nil - let _c7 = _7 != nil - let _c8 = _8 != nil - let _c9 = _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.messages.SearchResultsCalendar.searchResultsCalendar(flags: _1!, count: _2!, minDate: _3!, minMsgId: _4!, offsetIdOffset: _5, periods: _6!, messages: _7!, chats: _8!, users: _9!) - } - - } -} -public extension Api.messages { - enum SearchResultsPositions: TypeConstructorDescription { - case searchResultsPositions(count: Int32, positions: [Api.SearchResultsPosition]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .searchResultsPositions(let count, let positions): - if boxed { - buffer.appendInt32(1404185519) - } - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(positions.count)) - for item in positions { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .searchResultsPositions(let count, let positions): - return ("searchResultsPositions", [("count", count as Any), ("positions", positions as Any)]) - } - } - - public static func parse_searchResultsPositions(_ reader: BufferReader) -> SearchResultsPositions? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.SearchResultsPosition]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SearchResultsPosition.self) + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.messages.FeaturedStickers.featuredStickers(Cons_featuredStickers(flags: _1!, hash: _2!, count: _3!, sets: _4!, unread: _5!)) } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.SearchResultsPositions.searchResultsPositions(count: _1!, positions: _2!) - } - - } -} -public extension Api.messages { - enum SentEncryptedMessage: TypeConstructorDescription { - case sentEncryptedFile(date: Int32, file: Api.EncryptedFile) - case sentEncryptedMessage(date: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .sentEncryptedFile(let date, let file): - if boxed { - buffer.appendInt32(-1802240206) - } - serializeInt32(date, buffer: buffer, boxed: false) - file.serialize(buffer, true) - break - case .sentEncryptedMessage(let date): - if boxed { - buffer.appendInt32(1443858741) - } - serializeInt32(date, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .sentEncryptedFile(let date, let file): - return ("sentEncryptedFile", [("date", date as Any), ("file", file as Any)]) - case .sentEncryptedMessage(let date): - return ("sentEncryptedMessage", [("date", date as Any)]) - } - } - - public static func parse_sentEncryptedFile(_ reader: BufferReader) -> SentEncryptedMessage? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.EncryptedFile? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.EncryptedFile + else { + return nil } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.SentEncryptedMessage.sentEncryptedFile(date: _1!, file: _2!) } - public static func parse_sentEncryptedMessage(_ reader: BufferReader) -> SentEncryptedMessage? { + public static func parse_featuredStickersNotModified(_ reader: BufferReader) -> FeaturedStickers? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.messages.SentEncryptedMessage.sentEncryptedMessage(date: _1!) + if _c1 { + return Api.messages.FeaturedStickers.featuredStickersNotModified(Cons_featuredStickersNotModified(count: _1!)) + } + else { + return nil + } } - } } public extension Api.messages { - enum SponsoredMessages: TypeConstructorDescription { - case sponsoredMessages(flags: Int32, postsBetween: Int32?, startDelay: Int32?, betweenDelay: Int32?, messages: [Api.SponsoredMessage], chats: [Api.Chat], users: [Api.User]) - case sponsoredMessagesEmpty - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .sponsoredMessages(let flags, let postsBetween, let startDelay, let betweenDelay, let messages, let chats, let users): - if boxed { - buffer.appendInt32(-2464403) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(postsBetween!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(startDelay!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(betweenDelay!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .sponsoredMessagesEmpty: - if boxed { - buffer.appendInt32(406407439) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .sponsoredMessages(let flags, let postsBetween, let startDelay, let betweenDelay, let messages, let chats, let users): - return ("sponsoredMessages", [("flags", flags as Any), ("postsBetween", postsBetween as Any), ("startDelay", startDelay as Any), ("betweenDelay", betweenDelay as Any), ("messages", messages as Any), ("chats", chats as Any), ("users", users as Any)]) - case .sponsoredMessagesEmpty: - return ("sponsoredMessagesEmpty", []) - } - } - - public static func parse_sponsoredMessages(_ reader: BufferReader) -> SponsoredMessages? { + enum ForumTopics: TypeConstructorDescription { + public class Cons_forumTopics { + public var flags: Int32 + public var count: Int32 + public var topics: [Api.ForumTopic] + public var messages: [Api.Message] + public var chats: [Api.Chat] + public var users: [Api.User] + public var pts: Int32 + public init(flags: Int32, count: Int32, topics: [Api.ForumTopic], messages: [Api.Message], chats: [Api.Chat], users: [Api.User], pts: Int32) { + self.flags = flags + self.count = count + self.topics = topics + self.messages = messages + self.chats = chats + self.users = users + self.pts = pts + } + } + case forumTopics(Cons_forumTopics) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .forumTopics(let _data): + if boxed { + buffer.appendInt32(913709011) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.topics.count)) + for item in _data.topics { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + serializeInt32(_data.pts, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .forumTopics(let _data): + return ("forumTopics", [("flags", _data.flags as Any), ("count", _data.count as Any), ("topics", _data.topics as Any), ("messages", _data.messages as Any), ("chats", _data.chats as Any), ("users", _data.users as Any), ("pts", _data.pts as Any)]) + } + } + + public static func parse_forumTopics(_ reader: BufferReader) -> ForumTopics? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt32() } - var _3: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_3 = reader.readInt32() } - var _4: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_4 = reader.readInt32() } - var _5: [Api.SponsoredMessage]? + _2 = reader.readInt32() + var _3: [Api.ForumTopic]? if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SponsoredMessage.self) + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ForumTopic.self) } - var _6: [Api.Chat]? + var _4: [Api.Message]? if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) } - var _7: [Api.User]? + var _5: [Api.Chat]? if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) } + var _6: [Api.User]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + var _7: Int32? + _7 = reader.readInt32() let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = _6 != nil let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.messages.SponsoredMessages.sponsoredMessages(flags: _1!, postsBetween: _2, startDelay: _3, betweenDelay: _4, messages: _5!, chats: _6!, users: _7!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.messages.ForumTopics.forumTopics(Cons_forumTopics(flags: _1!, count: _2!, topics: _3!, messages: _4!, chats: _5!, users: _6!, pts: _7!)) + } + else { + return nil + } } - public static func parse_sponsoredMessagesEmpty(_ reader: BufferReader) -> SponsoredMessages? { - return Api.messages.SponsoredMessages.sponsoredMessagesEmpty - } - } } public extension Api.messages { - enum StickerSet: TypeConstructorDescription { - case stickerSet(set: Api.StickerSet, packs: [Api.StickerPack], keywords: [Api.StickerKeyword], documents: [Api.Document]) - case stickerSetNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .stickerSet(let set, let packs, let keywords, let documents): - if boxed { - buffer.appendInt32(1846886166) - } - set.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(packs.count)) - for item in packs { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(keywords.count)) - for item in keywords { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(documents.count)) - for item in documents { - item.serialize(buffer, true) - } - break - case .stickerSetNotModified: - if boxed { - buffer.appendInt32(-738646805) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .stickerSet(let set, let packs, let keywords, let documents): - return ("stickerSet", [("set", set as Any), ("packs", packs as Any), ("keywords", keywords as Any), ("documents", documents as Any)]) - case .stickerSetNotModified: - return ("stickerSetNotModified", []) - } - } - - public static func parse_stickerSet(_ reader: BufferReader) -> StickerSet? { - var _1: Api.StickerSet? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.StickerSet + enum FoundStickerSets: TypeConstructorDescription { + public class Cons_foundStickerSets { + public var hash: Int64 + public var sets: [Api.StickerSetCovered] + public init(hash: Int64, sets: [Api.StickerSetCovered]) { + self.hash = hash + self.sets = sets } - var _2: [Api.StickerPack]? + } + case foundStickerSets(Cons_foundStickerSets) + case foundStickerSetsNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .foundStickerSets(let _data): + if boxed { + buffer.appendInt32(-1963942446) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.sets.count)) + for item in _data.sets { + item.serialize(buffer, true) + } + break + case .foundStickerSetsNotModified: + if boxed { + buffer.appendInt32(223655517) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .foundStickerSets(let _data): + return ("foundStickerSets", [("hash", _data.hash as Any), ("sets", _data.sets as Any)]) + case .foundStickerSetsNotModified: + return ("foundStickerSetsNotModified", []) + } + } + + public static func parse_foundStickerSets(_ reader: BufferReader) -> FoundStickerSets? { + var _1: Int64? + _1 = reader.readInt64() + var _2: [Api.StickerSetCovered]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerPack.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerSetCovered.self) } - var _3: [Api.StickerKeyword]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerKeyword.self) + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.FoundStickerSets.foundStickerSets(Cons_foundStickerSets(hash: _1!, sets: _2!)) } + else { + return nil + } + } + public static func parse_foundStickerSetsNotModified(_ reader: BufferReader) -> FoundStickerSets? { + return Api.messages.FoundStickerSets.foundStickerSetsNotModified + } + } +} +public extension Api.messages { + enum FoundStickers: TypeConstructorDescription { + public class Cons_foundStickers { + public var flags: Int32 + public var nextOffset: Int32? + public var hash: Int64 + public var stickers: [Api.Document] + public init(flags: Int32, nextOffset: Int32?, hash: Int64, stickers: [Api.Document]) { + self.flags = flags + self.nextOffset = nextOffset + self.hash = hash + self.stickers = stickers + } + } + public class Cons_foundStickersNotModified { + public var flags: Int32 + public var nextOffset: Int32? + public init(flags: Int32, nextOffset: Int32?) { + self.flags = flags + self.nextOffset = nextOffset + } + } + case foundStickers(Cons_foundStickers) + case foundStickersNotModified(Cons_foundStickersNotModified) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .foundStickers(let _data): + if boxed { + buffer.appendInt32(-2100698480) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.nextOffset!, buffer: buffer, boxed: false) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.stickers.count)) + for item in _data.stickers { + item.serialize(buffer, true) + } + break + case .foundStickersNotModified(let _data): + if boxed { + buffer.appendInt32(1611711796) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.nextOffset!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .foundStickers(let _data): + return ("foundStickers", [("flags", _data.flags as Any), ("nextOffset", _data.nextOffset as Any), ("hash", _data.hash as Any), ("stickers", _data.stickers as Any)]) + case .foundStickersNotModified(let _data): + return ("foundStickersNotModified", [("flags", _data.flags as Any), ("nextOffset", _data.nextOffset as Any)]) + } + } + + public static func parse_foundStickers(_ reader: BufferReader) -> FoundStickers? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt32() + } + var _3: Int64? + _3 = reader.readInt64() var _4: [Api.Document]? if let _ = reader.readInt32() { _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) } let _c1 = _1 != nil - let _c2 = _2 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.messages.StickerSet.stickerSet(set: _1!, packs: _2!, keywords: _3!, documents: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.messages.FoundStickers.foundStickers(Cons_foundStickers(flags: _1!, nextOffset: _2, hash: _3!, stickers: _4!)) + } + else { + return nil + } } - public static func parse_stickerSetNotModified(_ reader: BufferReader) -> StickerSet? { - return Api.messages.StickerSet.stickerSetNotModified - } - - } -} -public extension Api.messages { - enum StickerSetInstallResult: TypeConstructorDescription { - case stickerSetInstallResultArchive(sets: [Api.StickerSetCovered]) - case stickerSetInstallResultSuccess - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .stickerSetInstallResultArchive(let sets): - if boxed { - buffer.appendInt32(904138920) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(sets.count)) - for item in sets { - item.serialize(buffer, true) - } - break - case .stickerSetInstallResultSuccess: - if boxed { - buffer.appendInt32(946083368) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .stickerSetInstallResultArchive(let sets): - return ("stickerSetInstallResultArchive", [("sets", sets as Any)]) - case .stickerSetInstallResultSuccess: - return ("stickerSetInstallResultSuccess", []) - } - } - - public static func parse_stickerSetInstallResultArchive(_ reader: BufferReader) -> StickerSetInstallResult? { - var _1: [Api.StickerSetCovered]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerSetCovered.self) + public static func parse_foundStickersNotModified(_ reader: BufferReader) -> FoundStickers? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt32() } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.messages.StickerSetInstallResult.stickerSetInstallResultArchive(sets: _1!) + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + if _c1 && _c2 { + return Api.messages.FoundStickers.foundStickersNotModified(Cons_foundStickersNotModified(flags: _1!, nextOffset: _2)) + } + else { + return nil + } } - public static func parse_stickerSetInstallResultSuccess(_ reader: BufferReader) -> StickerSetInstallResult? { - return Api.messages.StickerSetInstallResult.stickerSetInstallResultSuccess - } - } } public extension Api.messages { - enum Stickers: TypeConstructorDescription { - case stickers(hash: Int64, stickers: [Api.Document]) - case stickersNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .stickers(let hash, let stickers): - if boxed { - buffer.appendInt32(816245886) - } - serializeInt64(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stickers.count)) - for item in stickers { - item.serialize(buffer, true) - } - break - case .stickersNotModified: - if boxed { - buffer.appendInt32(-244016606) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .stickers(let hash, let stickers): - return ("stickers", [("hash", hash as Any), ("stickers", stickers as Any)]) - case .stickersNotModified: - return ("stickersNotModified", []) - } - } - - public static func parse_stickers(_ reader: BufferReader) -> Stickers? { - var _1: Int64? - _1 = reader.readInt64() - var _2: [Api.Document]? + enum HighScores: TypeConstructorDescription { + public class Cons_highScores { + public var scores: [Api.HighScore] + public var users: [Api.User] + public init(scores: [Api.HighScore], users: [Api.User]) { + self.scores = scores + self.users = users + } + } + case highScores(Cons_highScores) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .highScores(let _data): + if boxed { + buffer.appendInt32(-1707344487) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.scores.count)) + for item in _data.scores { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .highScores(let _data): + return ("highScores", [("scores", _data.scores as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_highScores(_ reader: BufferReader) -> HighScores? { + var _1: [Api.HighScore]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.HighScore.self) + } + var _2: [Api.User]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.messages.Stickers.stickers(hash: _1!, stickers: _2!) + if _c1 && _c2 { + return Api.messages.HighScores.highScores(Cons_highScores(scores: _1!, users: _2!)) + } + else { + return nil + } } - public static func parse_stickersNotModified(_ reader: BufferReader) -> Stickers? { - return Api.messages.Stickers.stickersNotModified - } - } } public extension Api.messages { - enum TranscribedAudio: TypeConstructorDescription { - case transcribedAudio(flags: Int32, transcriptionId: Int64, text: String, trialRemainsNum: Int32?, trialRemainsUntilDate: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .transcribedAudio(let flags, let transcriptionId, let text, let trialRemainsNum, let trialRemainsUntilDate): - if boxed { - buffer.appendInt32(-809903785) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(transcriptionId, buffer: buffer, boxed: false) - serializeString(text, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(trialRemainsNum!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(trialRemainsUntilDate!, buffer: buffer, boxed: false)} - break + enum HistoryImport: TypeConstructorDescription { + public class Cons_historyImport { + public var id: Int64 + public init(id: Int64) { + self.id = id + } + } + case historyImport(Cons_historyImport) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .historyImport(let _data): + if boxed { + buffer.appendInt32(375566091) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .historyImport(let _data): + return ("historyImport", [("id", _data.id as Any)]) + } + } + + public static func parse_historyImport(_ reader: BufferReader) -> HistoryImport? { + var _1: Int64? + _1 = reader.readInt64() + let _c1 = _1 != nil + if _c1 { + return Api.messages.HistoryImport.historyImport(Cons_historyImport(id: _1!)) + } + else { + return nil + } + } } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .transcribedAudio(let flags, let transcriptionId, let text, let trialRemainsNum, let trialRemainsUntilDate): - return ("transcribedAudio", [("flags", flags as Any), ("transcriptionId", transcriptionId as Any), ("text", text as Any), ("trialRemainsNum", trialRemainsNum as Any), ("trialRemainsUntilDate", trialRemainsUntilDate as Any)]) - } - } - - public static func parse_transcribedAudio(_ reader: BufferReader) -> TranscribedAudio? { +} +public extension Api.messages { + enum HistoryImportParsed: TypeConstructorDescription { + public class Cons_historyImportParsed { + public var flags: Int32 + public var title: String? + public init(flags: Int32, title: String?) { + self.flags = flags + self.title = title + } + } + case historyImportParsed(Cons_historyImportParsed) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .historyImportParsed(let _data): + if boxed { + buffer.appendInt32(1578088377) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .historyImportParsed(let _data): + return ("historyImportParsed", [("flags", _data.flags as Any), ("title", _data.title as Any)]) + } + } + + public static func parse_historyImportParsed(_ reader: BufferReader) -> HistoryImportParsed? { var _1: Int32? _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: String? - _3 = parseString(reader) - var _4: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_4 = reader.readInt32() } - var _5: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_5 = reader.readInt32() } + var _2: String? + if Int(_1!) & Int(1 << 2) != 0 { + _2 = parseString(reader) + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 2) == 0) || _2 != nil + if _c1 && _c2 { + return Api.messages.HistoryImportParsed.historyImportParsed(Cons_historyImportParsed(flags: _1!, title: _2)) + } + else { + return nil + } + } + } +} +public extension Api.messages { + enum InactiveChats: TypeConstructorDescription { + public class Cons_inactiveChats { + public var dates: [Int32] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(dates: [Int32], chats: [Api.Chat], users: [Api.User]) { + self.dates = dates + self.chats = chats + self.users = users + } + } + case inactiveChats(Cons_inactiveChats) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inactiveChats(let _data): + if boxed { + buffer.appendInt32(-1456996667) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.dates.count)) + for item in _data.dates { + serializeInt32(item, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inactiveChats(let _data): + return ("inactiveChats", [("dates", _data.dates as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_inactiveChats(_ reader: BufferReader) -> InactiveChats? { + var _1: [Int32]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.messages.TranscribedAudio.transcribedAudio(flags: _1!, transcriptionId: _2!, text: _3!, trialRemainsNum: _4, trialRemainsUntilDate: _5) + if _c1 && _c2 && _c3 { + return Api.messages.InactiveChats.inactiveChats(Cons_inactiveChats(dates: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } } - } } public extension Api.messages { - enum TranslatedText: TypeConstructorDescription { - case translateResult(result: [Api.TextWithEntities]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .translateResult(let result): - if boxed { - buffer.appendInt32(870003448) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(result.count)) - for item in result { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .translateResult(let result): - return ("translateResult", [("result", result as Any)]) - } - } - - public static func parse_translateResult(_ reader: BufferReader) -> TranslatedText? { - var _1: [Api.TextWithEntities]? + indirect enum InvitedUsers: TypeConstructorDescription { + public class Cons_invitedUsers { + public var updates: Api.Updates + public var missingInvitees: [Api.MissingInvitee] + public init(updates: Api.Updates, missingInvitees: [Api.MissingInvitee]) { + self.updates = updates + self.missingInvitees = missingInvitees + } + } + case invitedUsers(Cons_invitedUsers) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .invitedUsers(let _data): + if boxed { + buffer.appendInt32(2136862630) + } + _data.updates.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.missingInvitees.count)) + for item in _data.missingInvitees { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .invitedUsers(let _data): + return ("invitedUsers", [("updates", _data.updates as Any), ("missingInvitees", _data.missingInvitees as Any)]) + } + } + + public static func parse_invitedUsers(_ reader: BufferReader) -> InvitedUsers? { + var _1: Api.Updates? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Updates + } + var _2: [Api.MissingInvitee]? if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.TextWithEntities.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MissingInvitee.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.messages.TranslatedText.translateResult(result: _1!) + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.InvitedUsers.invitedUsers(Cons_invitedUsers(updates: _1!, missingInvitees: _2!)) + } + else { + return nil + } } - } } public extension Api.messages { - enum VotesList: TypeConstructorDescription { - case votesList(flags: Int32, count: Int32, votes: [Api.MessagePeerVote], chats: [Api.Chat], users: [Api.User], nextOffset: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .votesList(let flags, let count, let votes, let chats, let users, let nextOffset): - if boxed { - buffer.appendInt32(1218005070) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(votes.count)) - for item in votes { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 0) != 0 {serializeString(nextOffset!, buffer: buffer, boxed: false)} - break + enum MessageEditData: TypeConstructorDescription { + public class Cons_messageEditData { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } + case messageEditData(Cons_messageEditData) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messageEditData(let _data): + if boxed { + buffer.appendInt32(649453030) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messageEditData(let _data): + return ("messageEditData", [("flags", _data.flags as Any)]) + } + } + + public static func parse_messageEditData(_ reader: BufferReader) -> MessageEditData? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.messages.MessageEditData.messageEditData(Cons_messageEditData(flags: _1!)) + } + else { + return nil + } + } } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .votesList(let flags, let count, let votes, let chats, let users, let nextOffset): - return ("votesList", [("flags", flags as Any), ("count", count as Any), ("votes", votes as Any), ("chats", chats as Any), ("users", users as Any), ("nextOffset", nextOffset as Any)]) - } - } - - public static func parse_votesList(_ reader: BufferReader) -> VotesList? { +} +public extension Api.messages { + enum MessageReactionsList: TypeConstructorDescription { + public class Cons_messageReactionsList { + public var flags: Int32 + public var count: Int32 + public var reactions: [Api.MessagePeerReaction] + public var chats: [Api.Chat] + public var users: [Api.User] + public var nextOffset: String? + public init(flags: Int32, count: Int32, reactions: [Api.MessagePeerReaction], chats: [Api.Chat], users: [Api.User], nextOffset: String?) { + self.flags = flags + self.count = count + self.reactions = reactions + self.chats = chats + self.users = users + self.nextOffset = nextOffset + } + } + case messageReactionsList(Cons_messageReactionsList) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messageReactionsList(let _data): + if boxed { + buffer.appendInt32(834488621) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.reactions.count)) + for item in _data.reactions { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.nextOffset!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messageReactionsList(let _data): + return ("messageReactionsList", [("flags", _data.flags as Any), ("count", _data.count as Any), ("reactions", _data.reactions as Any), ("chats", _data.chats as Any), ("users", _data.users as Any), ("nextOffset", _data.nextOffset as Any)]) + } + } + + public static func parse_messageReactionsList(_ reader: BufferReader) -> MessageReactionsList? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? _2 = reader.readInt32() - var _3: [Api.MessagePeerVote]? + var _3: [Api.MessagePeerReaction]? if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessagePeerVote.self) + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessagePeerReaction.self) } var _4: [Api.Chat]? if let _ = reader.readInt32() { @@ -769,60 +840,74 @@ public extension Api.messages { _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } var _6: String? - if Int(_1!) & Int(1 << 0) != 0 {_6 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _6 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.messages.VotesList.votesList(flags: _1!, count: _2!, votes: _3!, chats: _4!, users: _5!, nextOffset: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.messages.MessageReactionsList.messageReactionsList(Cons_messageReactionsList(flags: _1!, count: _2!, reactions: _3!, chats: _4!, users: _5!, nextOffset: _6)) + } + else { + return nil + } } - } } public extension Api.messages { - enum WebPage: TypeConstructorDescription { - case webPage(webpage: Api.WebPage, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .webPage(let webpage, let chats, let users): - if boxed { - buffer.appendInt32(-44166467) - } - webpage.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .webPage(let webpage, let chats, let users): - return ("webPage", [("webpage", webpage as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_webPage(_ reader: BufferReader) -> WebPage? { - var _1: Api.WebPage? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.WebPage + enum MessageViews: TypeConstructorDescription { + public class Cons_messageViews { + public var views: [Api.MessageViews] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(views: [Api.MessageViews], chats: [Api.Chat], users: [Api.User]) { + self.views = views + self.chats = chats + self.users = users + } + } + case messageViews(Cons_messageViews) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messageViews(let _data): + if boxed { + buffer.appendInt32(-1228606141) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.views.count)) + for item in _data.views { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messageViews(let _data): + return ("messageViews", [("views", _data.views as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_messageViews(_ reader: BufferReader) -> MessageViews? { + var _1: [Api.MessageViews]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageViews.self) } var _2: [Api.Chat]? if let _ = reader.readInt32() { @@ -835,214 +920,306 @@ public extension Api.messages { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.messages.WebPage.webPage(webpage: _1!, chats: _2!, users: _3!) + if _c1 && _c2 && _c3 { + return Api.messages.MessageViews.messageViews(Cons_messageViews(views: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } } - } } public extension Api.messages { - indirect enum WebPagePreview: TypeConstructorDescription { - case webPagePreview(media: Api.MessageMedia, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .webPagePreview(let media, let chats, let users): - if boxed { - buffer.appendInt32(-1936029524) - } - media.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .webPagePreview(let media, let chats, let users): - return ("webPagePreview", [("media", media as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_webPagePreview(_ reader: BufferReader) -> WebPagePreview? { - var _1: Api.MessageMedia? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.MessageMedia + enum Messages: TypeConstructorDescription { + public class Cons_channelMessages { + public var flags: Int32 + public var pts: Int32 + public var count: Int32 + public var offsetIdOffset: Int32? + public var messages: [Api.Message] + public var topics: [Api.ForumTopic] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, pts: Int32, count: Int32, offsetIdOffset: Int32?, messages: [Api.Message], topics: [Api.ForumTopic], chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.pts = pts + self.count = count + self.offsetIdOffset = offsetIdOffset + self.messages = messages + self.topics = topics + self.chats = chats + self.users = users } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.messages.WebPagePreview.webPagePreview(media: _1!, chats: _2!, users: _3!) } - - } -} -public extension Api.payments { - enum BankCardData: TypeConstructorDescription { - case bankCardData(title: String, openUrls: [Api.BankCardOpenUrl]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .bankCardData(let title, let openUrls): - if boxed { - buffer.appendInt32(1042605427) - } - serializeString(title, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(openUrls.count)) - for item in openUrls { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .bankCardData(let title, let openUrls): - return ("bankCardData", [("title", title as Any), ("openUrls", openUrls as Any)]) - } - } - - public static func parse_bankCardData(_ reader: BufferReader) -> BankCardData? { - var _1: String? - _1 = parseString(reader) - var _2: [Api.BankCardOpenUrl]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.BankCardOpenUrl.self) + public class Cons_messages { + public var messages: [Api.Message] + public var topics: [Api.ForumTopic] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(messages: [Api.Message], topics: [Api.ForumTopic], chats: [Api.Chat], users: [Api.User]) { + self.messages = messages + self.topics = topics + self.chats = chats + self.users = users } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.payments.BankCardData.bankCardData(title: _1!, openUrls: _2!) } - - } -} -public extension Api.payments { - enum CheckCanSendGiftResult: TypeConstructorDescription { - case checkCanSendGiftResultFail(reason: Api.TextWithEntities) - case checkCanSendGiftResultOk - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .checkCanSendGiftResultFail(let reason): - if boxed { - buffer.appendInt32(-706379148) - } - reason.serialize(buffer, true) - break - case .checkCanSendGiftResultOk: - if boxed { - buffer.appendInt32(927967149) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .checkCanSendGiftResultFail(let reason): - return ("checkCanSendGiftResultFail", [("reason", reason as Any)]) - case .checkCanSendGiftResultOk: - return ("checkCanSendGiftResultOk", []) - } - } - - public static func parse_checkCanSendGiftResultFail(_ reader: BufferReader) -> CheckCanSendGiftResult? { - var _1: Api.TextWithEntities? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.TextWithEntities + public class Cons_messagesNotModified { + public var count: Int32 + public init(count: Int32) { + self.count = count } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.payments.CheckCanSendGiftResult.checkCanSendGiftResultFail(reason: _1!) } - public static func parse_checkCanSendGiftResultOk(_ reader: BufferReader) -> CheckCanSendGiftResult? { - return Api.payments.CheckCanSendGiftResult.checkCanSendGiftResultOk + public class Cons_messagesSlice { + public var flags: Int32 + public var count: Int32 + public var nextRate: Int32? + public var offsetIdOffset: Int32? + public var searchFlood: Api.SearchPostsFlood? + public var messages: [Api.Message] + public var topics: [Api.ForumTopic] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, count: Int32, nextRate: Int32?, offsetIdOffset: Int32?, searchFlood: Api.SearchPostsFlood?, messages: [Api.Message], topics: [Api.ForumTopic], chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.count = count + self.nextRate = nextRate + self.offsetIdOffset = offsetIdOffset + self.searchFlood = searchFlood + self.messages = messages + self.topics = topics + self.chats = chats + self.users = users + } } - - } -} -public extension Api.payments { - enum CheckedGiftCode: TypeConstructorDescription { - case checkedGiftCode(flags: Int32, fromId: Api.Peer?, giveawayMsgId: Int32?, toId: Int64?, date: Int32, days: Int32, usedDate: Int32?, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .checkedGiftCode(let flags, let fromId, let giveawayMsgId, let toId, let date, let days, let usedDate, let chats, let users): - if boxed { - buffer.appendInt32(-342343793) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {fromId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(giveawayMsgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(toId!, buffer: buffer, boxed: false)} - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt32(days, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(usedDate!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .checkedGiftCode(let flags, let fromId, let giveawayMsgId, let toId, let date, let days, let usedDate, let chats, let users): - return ("checkedGiftCode", [("flags", flags as Any), ("fromId", fromId as Any), ("giveawayMsgId", giveawayMsgId as Any), ("toId", toId as Any), ("date", date as Any), ("days", days as Any), ("usedDate", usedDate as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_checkedGiftCode(_ reader: BufferReader) -> CheckedGiftCode? { + case channelMessages(Cons_channelMessages) + case messages(Cons_messages) + case messagesNotModified(Cons_messagesNotModified) + case messagesSlice(Cons_messagesSlice) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .channelMessages(let _data): + if boxed { + buffer.appendInt32(-948520370) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.offsetIdOffset!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.topics.count)) + for item in _data.topics { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .messages(let _data): + if boxed { + buffer.appendInt32(494135274) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.topics.count)) + for item in _data.topics { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .messagesNotModified(let _data): + if boxed { + buffer.appendInt32(1951620897) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + break + case .messagesSlice(let _data): + if boxed { + buffer.appendInt32(1595959062) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.nextRate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.offsetIdOffset!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.searchFlood!.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.topics.count)) + for item in _data.topics { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .channelMessages(let _data): + return ("channelMessages", [("flags", _data.flags as Any), ("pts", _data.pts as Any), ("count", _data.count as Any), ("offsetIdOffset", _data.offsetIdOffset as Any), ("messages", _data.messages as Any), ("topics", _data.topics as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + case .messages(let _data): + return ("messages", [("messages", _data.messages as Any), ("topics", _data.topics as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + case .messagesNotModified(let _data): + return ("messagesNotModified", [("count", _data.count as Any)]) + case .messagesSlice(let _data): + return ("messagesSlice", [("flags", _data.flags as Any), ("count", _data.count as Any), ("nextRate", _data.nextRate as Any), ("offsetIdOffset", _data.offsetIdOffset as Any), ("searchFlood", _data.searchFlood as Any), ("messages", _data.messages as Any), ("topics", _data.topics as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_channelMessages(_ reader: BufferReader) -> Messages? { var _1: Int32? _1 = reader.readInt32() - var _2: Api.Peer? - if Int(_1!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } } + var _2: Int32? + _2 = reader.readInt32() var _3: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_3 = reader.readInt32() } - var _4: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_4 = reader.readInt64() } - var _5: Int32? - _5 = reader.readInt32() - var _6: Int32? - _6 = reader.readInt32() - var _7: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_7 = reader.readInt32() } + _3 = reader.readInt32() + var _4: Int32? + if Int(_1!) & Int(1 << 2) != 0 { + _4 = reader.readInt32() + } + var _5: [Api.Message]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) + } + var _6: [Api.ForumTopic]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ForumTopic.self) + } + var _7: [Api.Chat]? + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _8: [Api.User]? + if let _ = reader.readInt32() { + _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + let _c7 = _7 != nil + let _c8 = _8 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.messages.Messages.channelMessages(Cons_channelMessages(flags: _1!, pts: _2!, count: _3!, offsetIdOffset: _4, messages: _5!, topics: _6!, chats: _7!, users: _8!)) + } + else { + return nil + } + } + public static func parse_messages(_ reader: BufferReader) -> Messages? { + var _1: [Api.Message]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) + } + var _2: [Api.ForumTopic]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ForumTopic.self) + } + var _3: [Api.Chat]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _4: [Api.User]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.messages.Messages.messages(Cons_messages(messages: _1!, topics: _2!, chats: _3!, users: _4!)) + } + else { + return nil + } + } + public static func parse_messagesNotModified(_ reader: BufferReader) -> Messages? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.messages.Messages.messagesNotModified(Cons_messagesNotModified(count: _1!)) + } + else { + return nil + } + } + public static func parse_messagesSlice(_ reader: BufferReader) -> Messages? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } + var _4: Int32? + if Int(_1!) & Int(1 << 2) != 0 { + _4 = reader.readInt32() + } + var _5: Api.SearchPostsFlood? + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.SearchPostsFlood + } + } + var _6: [Api.Message]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) + } + var _7: [Api.ForumTopic]? + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ForumTopic.self) + } var _8: [Api.Chat]? if let _ = reader.readInt32() { _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) @@ -1052,66 +1229,217 @@ public extension Api.payments { _9 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 4) == 0) || _2 != nil - let _c3 = (Int(_1!) & Int(1 << 3) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - let _c5 = _5 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil + let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil + let _c5 = (Int(_1!) & Int(1 << 3) == 0) || _5 != nil let _c6 = _6 != nil - let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil + let _c7 = _7 != nil let _c8 = _8 != nil let _c9 = _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.payments.CheckedGiftCode.checkedGiftCode(flags: _1!, fromId: _2, giveawayMsgId: _3, toId: _4, date: _5!, days: _6!, usedDate: _7, chats: _8!, users: _9!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.messages.Messages.messagesSlice(Cons_messagesSlice(flags: _1!, count: _2!, nextRate: _3, offsetIdOffset: _4, searchFlood: _5, messages: _6!, topics: _7!, chats: _8!, users: _9!)) + } + else { + return nil + } } - } } -public extension Api.payments { - enum ConnectedStarRefBots: TypeConstructorDescription { - case connectedStarRefBots(count: Int32, connectedBots: [Api.ConnectedBotStarRef], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .connectedStarRefBots(let count, let connectedBots, let users): - if boxed { - buffer.appendInt32(-1730811363) - } - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(connectedBots.count)) - for item in connectedBots { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .connectedStarRefBots(let count, let connectedBots, let users): - return ("connectedStarRefBots", [("count", count as Any), ("connectedBots", connectedBots as Any), ("users", users as Any)]) - } - } - - public static func parse_connectedStarRefBots(_ reader: BufferReader) -> ConnectedStarRefBots? { +public extension Api.messages { + enum MyStickers: TypeConstructorDescription { + public class Cons_myStickers { + public var count: Int32 + public var sets: [Api.StickerSetCovered] + public init(count: Int32, sets: [Api.StickerSetCovered]) { + self.count = count + self.sets = sets + } + } + case myStickers(Cons_myStickers) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .myStickers(let _data): + if boxed { + buffer.appendInt32(-83926371) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.sets.count)) + for item in _data.sets { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .myStickers(let _data): + return ("myStickers", [("count", _data.count as Any), ("sets", _data.sets as Any)]) + } + } + + public static func parse_myStickers(_ reader: BufferReader) -> MyStickers? { var _1: Int32? _1 = reader.readInt32() - var _2: [Api.ConnectedBotStarRef]? + var _2: [Api.StickerSetCovered]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ConnectedBotStarRef.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerSetCovered.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.MyStickers.myStickers(Cons_myStickers(count: _1!, sets: _2!)) + } + else { + return nil + } + } + } +} +public extension Api.messages { + enum PeerDialogs: TypeConstructorDescription { + public class Cons_peerDialogs { + public var dialogs: [Api.Dialog] + public var messages: [Api.Message] + public var chats: [Api.Chat] + public var users: [Api.User] + public var state: Api.updates.State + public init(dialogs: [Api.Dialog], messages: [Api.Message], chats: [Api.Chat], users: [Api.User], state: Api.updates.State) { + self.dialogs = dialogs + self.messages = messages + self.chats = chats + self.users = users + self.state = state + } + } + case peerDialogs(Cons_peerDialogs) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .peerDialogs(let _data): + if boxed { + buffer.appendInt32(863093588) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.dialogs.count)) + for item in _data.dialogs { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + _data.state.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .peerDialogs(let _data): + return ("peerDialogs", [("dialogs", _data.dialogs as Any), ("messages", _data.messages as Any), ("chats", _data.chats as Any), ("users", _data.users as Any), ("state", _data.state as Any)]) + } + } + + public static func parse_peerDialogs(_ reader: BufferReader) -> PeerDialogs? { + var _1: [Api.Dialog]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Dialog.self) + } + var _2: [Api.Message]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) + } + var _3: [Api.Chat]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _4: [Api.User]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + var _5: Api.updates.State? + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.updates.State + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.messages.PeerDialogs.peerDialogs(Cons_peerDialogs(dialogs: _1!, messages: _2!, chats: _3!, users: _4!, state: _5!)) + } + else { + return nil + } + } + } +} +public extension Api.messages { + enum PeerSettings: TypeConstructorDescription { + public class Cons_peerSettings { + public var settings: Api.PeerSettings + public var chats: [Api.Chat] + public var users: [Api.User] + public init(settings: Api.PeerSettings, chats: [Api.Chat], users: [Api.User]) { + self.settings = settings + self.chats = chats + self.users = users + } + } + case peerSettings(Cons_peerSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .peerSettings(let _data): + if boxed { + buffer.appendInt32(1753266509) + } + _data.settings.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .peerSettings(let _data): + return ("peerSettings", [("settings", _data.settings as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_peerSettings(_ reader: BufferReader) -> PeerSettings? { + var _1: Api.PeerSettings? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.PeerSettings + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) } var _3: [Api.User]? if let _ = reader.readInt32() { @@ -1120,353 +1448,520 @@ public extension Api.payments { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.payments.ConnectedStarRefBots.connectedStarRefBots(count: _1!, connectedBots: _2!, users: _3!) - } - - } -} -public extension Api.payments { - enum ExportedInvoice: TypeConstructorDescription { - case exportedInvoice(url: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .exportedInvoice(let url): - if boxed { - buffer.appendInt32(-1362048039) - } - serializeString(url, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .exportedInvoice(let url): - return ("exportedInvoice", [("url", url as Any)]) - } - } - - public static func parse_exportedInvoice(_ reader: BufferReader) -> ExportedInvoice? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.payments.ExportedInvoice.exportedInvoice(url: _1!) - } - - } -} -public extension Api.payments { - enum GiveawayInfo: TypeConstructorDescription { - case giveawayInfo(flags: Int32, startDate: Int32, joinedTooEarlyDate: Int32?, adminDisallowedChatId: Int64?, disallowedCountry: String?) - case giveawayInfoResults(flags: Int32, startDate: Int32, giftCodeSlug: String?, starsPrize: Int64?, finishDate: Int32, winnersCount: Int32, activatedCount: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .giveawayInfo(let flags, let startDate, let joinedTooEarlyDate, let adminDisallowedChatId, let disallowedCountry): - if boxed { - buffer.appendInt32(1130879648) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(startDate, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(joinedTooEarlyDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt64(adminDisallowedChatId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeString(disallowedCountry!, buffer: buffer, boxed: false)} - break - case .giveawayInfoResults(let flags, let startDate, let giftCodeSlug, let starsPrize, let finishDate, let winnersCount, let activatedCount): - if boxed { - buffer.appendInt32(-512366993) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(startDate, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {serializeString(giftCodeSlug!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt64(starsPrize!, buffer: buffer, boxed: false)} - serializeInt32(finishDate, buffer: buffer, boxed: false) - serializeInt32(winnersCount, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(activatedCount!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .giveawayInfo(let flags, let startDate, let joinedTooEarlyDate, let adminDisallowedChatId, let disallowedCountry): - return ("giveawayInfo", [("flags", flags as Any), ("startDate", startDate as Any), ("joinedTooEarlyDate", joinedTooEarlyDate as Any), ("adminDisallowedChatId", adminDisallowedChatId as Any), ("disallowedCountry", disallowedCountry as Any)]) - case .giveawayInfoResults(let flags, let startDate, let giftCodeSlug, let starsPrize, let finishDate, let winnersCount, let activatedCount): - return ("giveawayInfoResults", [("flags", flags as Any), ("startDate", startDate as Any), ("giftCodeSlug", giftCodeSlug as Any), ("starsPrize", starsPrize as Any), ("finishDate", finishDate as Any), ("winnersCount", winnersCount as Any), ("activatedCount", activatedCount as Any)]) - } - } - - public static func parse_giveawayInfo(_ reader: BufferReader) -> GiveawayInfo? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_3 = reader.readInt32() } - var _4: Int64? - if Int(_1!) & Int(1 << 2) != 0 {_4 = reader.readInt64() } - var _5: String? - if Int(_1!) & Int(1 << 4) != 0 {_5 = parseString(reader) } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 4) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.payments.GiveawayInfo.giveawayInfo(flags: _1!, startDate: _2!, joinedTooEarlyDate: _3, adminDisallowedChatId: _4, disallowedCountry: _5) - } - public static func parse_giveawayInfoResults(_ reader: BufferReader) -> GiveawayInfo? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: String? - if Int(_1!) & Int(1 << 3) != 0 {_3 = parseString(reader) } - var _4: Int64? - if Int(_1!) & Int(1 << 4) != 0 {_4 = reader.readInt64() } - var _5: Int32? - _5 = reader.readInt32() - var _6: Int32? - _6 = reader.readInt32() - var _7: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_7 = reader.readInt32() } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 3) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 4) == 0) || _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - let _c7 = (Int(_1!) & Int(1 << 2) == 0) || _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.payments.GiveawayInfo.giveawayInfoResults(flags: _1!, startDate: _2!, giftCodeSlug: _3, starsPrize: _4, finishDate: _5!, winnersCount: _6!, activatedCount: _7) - } - - } -} -public extension Api.payments { - enum PaymentForm: TypeConstructorDescription { - case paymentForm(flags: Int32, formId: Int64, botId: Int64, title: String, description: String, photo: Api.WebDocument?, invoice: Api.Invoice, providerId: Int64, url: String, nativeProvider: String?, nativeParams: Api.DataJSON?, additionalMethods: [Api.PaymentFormMethod]?, savedInfo: Api.PaymentRequestedInfo?, savedCredentials: [Api.PaymentSavedCredentials]?, users: [Api.User]) - case paymentFormStarGift(formId: Int64, invoice: Api.Invoice) - case paymentFormStars(flags: Int32, formId: Int64, botId: Int64, title: String, description: String, photo: Api.WebDocument?, invoice: Api.Invoice, users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .paymentForm(let flags, let formId, let botId, let title, let description, let photo, let invoice, let providerId, let url, let nativeProvider, let nativeParams, let additionalMethods, let savedInfo, let savedCredentials, let users): - if boxed { - buffer.appendInt32(-1610250415) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(formId, buffer: buffer, boxed: false) - serializeInt64(botId, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(description, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 5) != 0 {photo!.serialize(buffer, true)} - invoice.serialize(buffer, true) - serializeInt64(providerId, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {serializeString(nativeProvider!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {nativeParams!.serialize(buffer, true)} - if Int(flags) & Int(1 << 6) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(additionalMethods!.count)) - for item in additionalMethods! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 0) != 0 {savedInfo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(savedCredentials!.count)) - for item in savedCredentials! { - item.serialize(buffer, true) - }} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .paymentFormStarGift(let formId, let invoice): - if boxed { - buffer.appendInt32(-1272590367) - } - serializeInt64(formId, buffer: buffer, boxed: false) - invoice.serialize(buffer, true) - break - case .paymentFormStars(let flags, let formId, let botId, let title, let description, let photo, let invoice, let users): - if boxed { - buffer.appendInt32(2079764828) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(formId, buffer: buffer, boxed: false) - serializeInt64(botId, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(description, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 5) != 0 {photo!.serialize(buffer, true)} - invoice.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .paymentForm(let flags, let formId, let botId, let title, let description, let photo, let invoice, let providerId, let url, let nativeProvider, let nativeParams, let additionalMethods, let savedInfo, let savedCredentials, let users): - return ("paymentForm", [("flags", flags as Any), ("formId", formId as Any), ("botId", botId as Any), ("title", title as Any), ("description", description as Any), ("photo", photo as Any), ("invoice", invoice as Any), ("providerId", providerId as Any), ("url", url as Any), ("nativeProvider", nativeProvider as Any), ("nativeParams", nativeParams as Any), ("additionalMethods", additionalMethods as Any), ("savedInfo", savedInfo as Any), ("savedCredentials", savedCredentials as Any), ("users", users as Any)]) - case .paymentFormStarGift(let formId, let invoice): - return ("paymentFormStarGift", [("formId", formId as Any), ("invoice", invoice as Any)]) - case .paymentFormStars(let flags, let formId, let botId, let title, let description, let photo, let invoice, let users): - return ("paymentFormStars", [("flags", flags as Any), ("formId", formId as Any), ("botId", botId as Any), ("title", title as Any), ("description", description as Any), ("photo", photo as Any), ("invoice", invoice as Any), ("users", users as Any)]) - } - } - - public static func parse_paymentForm(_ reader: BufferReader) -> PaymentForm? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int64? - _3 = reader.readInt64() - var _4: String? - _4 = parseString(reader) - var _5: String? - _5 = parseString(reader) - var _6: Api.WebDocument? - if Int(_1!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.WebDocument - } } - var _7: Api.Invoice? - if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.Invoice + if _c1 && _c2 && _c3 { + return Api.messages.PeerSettings.peerSettings(Cons_peerSettings(settings: _1!, chats: _2!, users: _3!)) } - var _8: Int64? - _8 = reader.readInt64() - var _9: String? - _9 = parseString(reader) - var _10: String? - if Int(_1!) & Int(1 << 4) != 0 {_10 = parseString(reader) } - var _11: Api.DataJSON? - if Int(_1!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _11 = Api.parse(reader, signature: signature) as? Api.DataJSON - } } - var _12: [Api.PaymentFormMethod]? - if Int(_1!) & Int(1 << 6) != 0 {if let _ = reader.readInt32() { - _12 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PaymentFormMethod.self) - } } - var _13: Api.PaymentRequestedInfo? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _13 = Api.parse(reader, signature: signature) as? Api.PaymentRequestedInfo - } } - var _14: [Api.PaymentSavedCredentials]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _14 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PaymentSavedCredentials.self) - } } - var _15: [Api.User]? - if let _ = reader.readInt32() { - _15 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + else { + return nil } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 5) == 0) || _6 != nil - let _c7 = _7 != nil - let _c8 = _8 != nil - let _c9 = _9 != nil - let _c10 = (Int(_1!) & Int(1 << 4) == 0) || _10 != nil - let _c11 = (Int(_1!) & Int(1 << 4) == 0) || _11 != nil - let _c12 = (Int(_1!) & Int(1 << 6) == 0) || _12 != nil - let _c13 = (Int(_1!) & Int(1 << 0) == 0) || _13 != nil - let _c14 = (Int(_1!) & Int(1 << 1) == 0) || _14 != nil - let _c15 = _15 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - return Api.payments.PaymentForm.paymentForm(flags: _1!, formId: _2!, botId: _3!, title: _4!, description: _5!, photo: _6, invoice: _7!, providerId: _8!, url: _9!, nativeProvider: _10, nativeParams: _11, additionalMethods: _12, savedInfo: _13, savedCredentials: _14, users: _15!) } - public static func parse_paymentFormStarGift(_ reader: BufferReader) -> PaymentForm? { + } +} +public extension Api.messages { + enum PreparedInlineMessage: TypeConstructorDescription { + public class Cons_preparedInlineMessage { + public var queryId: Int64 + public var result: Api.BotInlineResult + public var peerTypes: [Api.InlineQueryPeerType] + public var cacheTime: Int32 + public var users: [Api.User] + public init(queryId: Int64, result: Api.BotInlineResult, peerTypes: [Api.InlineQueryPeerType], cacheTime: Int32, users: [Api.User]) { + self.queryId = queryId + self.result = result + self.peerTypes = peerTypes + self.cacheTime = cacheTime + self.users = users + } + } + case preparedInlineMessage(Cons_preparedInlineMessage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .preparedInlineMessage(let _data): + if boxed { + buffer.appendInt32(-11046771) + } + serializeInt64(_data.queryId, buffer: buffer, boxed: false) + _data.result.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.peerTypes.count)) + for item in _data.peerTypes { + item.serialize(buffer, true) + } + serializeInt32(_data.cacheTime, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .preparedInlineMessage(let _data): + return ("preparedInlineMessage", [("queryId", _data.queryId as Any), ("result", _data.result as Any), ("peerTypes", _data.peerTypes as Any), ("cacheTime", _data.cacheTime as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_preparedInlineMessage(_ reader: BufferReader) -> PreparedInlineMessage? { var _1: Int64? _1 = reader.readInt64() - var _2: Api.Invoice? + var _2: Api.BotInlineResult? if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Invoice + _2 = Api.parse(reader, signature: signature) as? Api.BotInlineResult } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.payments.PaymentForm.paymentFormStarGift(formId: _1!, invoice: _2!) - } - public static func parse_paymentFormStars(_ reader: BufferReader) -> PaymentForm? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int64? - _2 = reader.readInt64() - var _3: Int64? - _3 = reader.readInt64() - var _4: String? - _4 = parseString(reader) - var _5: String? - _5 = parseString(reader) - var _6: Api.WebDocument? - if Int(_1!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.WebDocument - } } - var _7: Api.Invoice? - if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.Invoice - } - var _8: [Api.User]? + var _3: [Api.InlineQueryPeerType]? if let _ = reader.readInt32() { - _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InlineQueryPeerType.self) + } + var _4: Int32? + _4 = reader.readInt32() + var _5: [Api.User]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 5) == 0) || _6 != nil - let _c7 = _7 != nil - let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.payments.PaymentForm.paymentFormStars(flags: _1!, formId: _2!, botId: _3!, title: _4!, description: _5!, photo: _6, invoice: _7!, users: _8!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.messages.PreparedInlineMessage.preparedInlineMessage(Cons_preparedInlineMessage(queryId: _1!, result: _2!, peerTypes: _3!, cacheTime: _4!, users: _5!)) + } + else { + return nil + } + } + } +} +public extension Api.messages { + enum QuickReplies: TypeConstructorDescription { + public class Cons_quickReplies { + public var quickReplies: [Api.QuickReply] + public var messages: [Api.Message] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(quickReplies: [Api.QuickReply], messages: [Api.Message], chats: [Api.Chat], users: [Api.User]) { + self.quickReplies = quickReplies + self.messages = messages + self.chats = chats + self.users = users + } + } + case quickReplies(Cons_quickReplies) + case quickRepliesNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .quickReplies(let _data): + if boxed { + buffer.appendInt32(-963811691) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.quickReplies.count)) + for item in _data.quickReplies { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .quickRepliesNotModified: + if boxed { + buffer.appendInt32(1603398491) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .quickReplies(let _data): + return ("quickReplies", [("quickReplies", _data.quickReplies as Any), ("messages", _data.messages as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + case .quickRepliesNotModified: + return ("quickRepliesNotModified", []) + } + } + + public static func parse_quickReplies(_ reader: BufferReader) -> QuickReplies? { + var _1: [Api.QuickReply]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.QuickReply.self) + } + var _2: [Api.Message]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) + } + var _3: [Api.Chat]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _4: [Api.User]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.messages.QuickReplies.quickReplies(Cons_quickReplies(quickReplies: _1!, messages: _2!, chats: _3!, users: _4!)) + } + else { + return nil + } + } + public static func parse_quickRepliesNotModified(_ reader: BufferReader) -> QuickReplies? { + return Api.messages.QuickReplies.quickRepliesNotModified + } + } +} +public extension Api.messages { + enum Reactions: TypeConstructorDescription { + public class Cons_reactions { + public var hash: Int64 + public var reactions: [Api.Reaction] + public init(hash: Int64, reactions: [Api.Reaction]) { + self.hash = hash + self.reactions = reactions + } + } + case reactions(Cons_reactions) + case reactionsNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .reactions(let _data): + if boxed { + buffer.appendInt32(-352454890) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.reactions.count)) + for item in _data.reactions { + item.serialize(buffer, true) + } + break + case .reactionsNotModified: + if boxed { + buffer.appendInt32(-1334846497) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .reactions(let _data): + return ("reactions", [("hash", _data.hash as Any), ("reactions", _data.reactions as Any)]) + case .reactionsNotModified: + return ("reactionsNotModified", []) + } + } + + public static func parse_reactions(_ reader: BufferReader) -> Reactions? { + var _1: Int64? + _1 = reader.readInt64() + var _2: [Api.Reaction]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Reaction.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.Reactions.reactions(Cons_reactions(hash: _1!, reactions: _2!)) + } + else { + return nil + } + } + public static func parse_reactionsNotModified(_ reader: BufferReader) -> Reactions? { + return Api.messages.Reactions.reactionsNotModified + } + } +} +public extension Api.messages { + enum RecentStickers: TypeConstructorDescription { + public class Cons_recentStickers { + public var hash: Int64 + public var packs: [Api.StickerPack] + public var stickers: [Api.Document] + public var dates: [Int32] + public init(hash: Int64, packs: [Api.StickerPack], stickers: [Api.Document], dates: [Int32]) { + self.hash = hash + self.packs = packs + self.stickers = stickers + self.dates = dates + } + } + case recentStickers(Cons_recentStickers) + case recentStickersNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .recentStickers(let _data): + if boxed { + buffer.appendInt32(-1999405994) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.packs.count)) + for item in _data.packs { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.stickers.count)) + for item in _data.stickers { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.dates.count)) + for item in _data.dates { + serializeInt32(item, buffer: buffer, boxed: false) + } + break + case .recentStickersNotModified: + if boxed { + buffer.appendInt32(186120336) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .recentStickers(let _data): + return ("recentStickers", [("hash", _data.hash as Any), ("packs", _data.packs as Any), ("stickers", _data.stickers as Any), ("dates", _data.dates as Any)]) + case .recentStickersNotModified: + return ("recentStickersNotModified", []) + } + } + + public static func parse_recentStickers(_ reader: BufferReader) -> RecentStickers? { + var _1: Int64? + _1 = reader.readInt64() + var _2: [Api.StickerPack]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerPack.self) + } + var _3: [Api.Document]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + } + var _4: [Int32]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.messages.RecentStickers.recentStickers(Cons_recentStickers(hash: _1!, packs: _2!, stickers: _3!, dates: _4!)) + } + else { + return nil + } + } + public static func parse_recentStickersNotModified(_ reader: BufferReader) -> RecentStickers? { + return Api.messages.RecentStickers.recentStickersNotModified + } + } +} +public extension Api.messages { + enum SavedDialogs: TypeConstructorDescription { + public class Cons_savedDialogs { + public var dialogs: [Api.SavedDialog] + public var messages: [Api.Message] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(dialogs: [Api.SavedDialog], messages: [Api.Message], chats: [Api.Chat], users: [Api.User]) { + self.dialogs = dialogs + self.messages = messages + self.chats = chats + self.users = users + } + } + public class Cons_savedDialogsNotModified { + public var count: Int32 + public init(count: Int32) { + self.count = count + } + } + public class Cons_savedDialogsSlice { + public var count: Int32 + public var dialogs: [Api.SavedDialog] + public var messages: [Api.Message] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(count: Int32, dialogs: [Api.SavedDialog], messages: [Api.Message], chats: [Api.Chat], users: [Api.User]) { + self.count = count + self.dialogs = dialogs + self.messages = messages + self.chats = chats + self.users = users + } + } + case savedDialogs(Cons_savedDialogs) + case savedDialogsNotModified(Cons_savedDialogsNotModified) + case savedDialogsSlice(Cons_savedDialogsSlice) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .savedDialogs(let _data): + if boxed { + buffer.appendInt32(-130358751) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.dialogs.count)) + for item in _data.dialogs { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .savedDialogsNotModified(let _data): + if boxed { + buffer.appendInt32(-1071681560) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + break + case .savedDialogsSlice(let _data): + if boxed { + buffer.appendInt32(1153080793) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.dialogs.count)) + for item in _data.dialogs { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .savedDialogs(let _data): + return ("savedDialogs", [("dialogs", _data.dialogs as Any), ("messages", _data.messages as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + case .savedDialogsNotModified(let _data): + return ("savedDialogsNotModified", [("count", _data.count as Any)]) + case .savedDialogsSlice(let _data): + return ("savedDialogsSlice", [("count", _data.count as Any), ("dialogs", _data.dialogs as Any), ("messages", _data.messages as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_savedDialogs(_ reader: BufferReader) -> SavedDialogs? { + var _1: [Api.SavedDialog]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SavedDialog.self) + } + var _2: [Api.Message]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) + } + var _3: [Api.Chat]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _4: [Api.User]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.messages.SavedDialogs.savedDialogs(Cons_savedDialogs(dialogs: _1!, messages: _2!, chats: _3!, users: _4!)) + } + else { + return nil + } + } + public static func parse_savedDialogsNotModified(_ reader: BufferReader) -> SavedDialogs? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.messages.SavedDialogs.savedDialogsNotModified(Cons_savedDialogsNotModified(count: _1!)) + } + else { + return nil + } + } + public static func parse_savedDialogsSlice(_ reader: BufferReader) -> SavedDialogs? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.SavedDialog]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SavedDialog.self) + } + var _3: [Api.Message]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) + } + var _4: [Api.Chat]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _5: [Api.User]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.messages.SavedDialogs.savedDialogsSlice(Cons_savedDialogsSlice(count: _1!, dialogs: _2!, messages: _3!, chats: _4!, users: _5!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api36.swift b/submodules/TelegramApi/Sources/Api36.swift index 1bad226d..21d07ed3 100644 --- a/submodules/TelegramApi/Sources/Api36.swift +++ b/submodules/TelegramApi/Sources/Api36.swift @@ -1,1121 +1,277 @@ -public extension Api.payments { - enum PaymentReceipt: TypeConstructorDescription { - case paymentReceipt(flags: Int32, date: Int32, botId: Int64, providerId: Int64, title: String, description: String, photo: Api.WebDocument?, invoice: Api.Invoice, info: Api.PaymentRequestedInfo?, shipping: Api.ShippingOption?, tipAmount: Int64?, currency: String, totalAmount: Int64, credentialsTitle: String, users: [Api.User]) - case paymentReceiptStars(flags: Int32, date: Int32, botId: Int64, title: String, description: String, photo: Api.WebDocument?, invoice: Api.Invoice, currency: String, totalAmount: Int64, transactionId: String, users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .paymentReceipt(let flags, let date, let botId, let providerId, let title, let description, let photo, let invoice, let info, let shipping, let tipAmount, let currency, let totalAmount, let credentialsTitle, let users): - if boxed { - buffer.appendInt32(1891958275) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(botId, buffer: buffer, boxed: false) - serializeInt64(providerId, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(description, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {photo!.serialize(buffer, true)} - invoice.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {info!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {shipping!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt64(tipAmount!, buffer: buffer, boxed: false)} - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(totalAmount, buffer: buffer, boxed: false) - serializeString(credentialsTitle, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .paymentReceiptStars(let flags, let date, let botId, let title, let description, let photo, let invoice, let currency, let totalAmount, let transactionId, let users): - if boxed { - buffer.appendInt32(-625215430) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(botId, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(description, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {photo!.serialize(buffer, true)} - invoice.serialize(buffer, true) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(totalAmount, buffer: buffer, boxed: false) - serializeString(transactionId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break +public extension Api.messages { + enum SavedGifs: TypeConstructorDescription { + public class Cons_savedGifs { + public var hash: Int64 + public var gifs: [Api.Document] + public init(hash: Int64, gifs: [Api.Document]) { + self.hash = hash + self.gifs = gifs + } + } + case savedGifs(Cons_savedGifs) + case savedGifsNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .savedGifs(let _data): + if boxed { + buffer.appendInt32(-2069878259) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.gifs.count)) + for item in _data.gifs { + item.serialize(buffer, true) + } + break + case .savedGifsNotModified: + if boxed { + buffer.appendInt32(-402498398) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .savedGifs(let _data): + return ("savedGifs", [("hash", _data.hash as Any), ("gifs", _data.gifs as Any)]) + case .savedGifsNotModified: + return ("savedGifsNotModified", []) + } + } + + public static func parse_savedGifs(_ reader: BufferReader) -> SavedGifs? { + var _1: Int64? + _1 = reader.readInt64() + var _2: [Api.Document]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.SavedGifs.savedGifs(Cons_savedGifs(hash: _1!, gifs: _2!)) + } + else { + return nil + } + } + public static func parse_savedGifsNotModified(_ reader: BufferReader) -> SavedGifs? { + return Api.messages.SavedGifs.savedGifsNotModified + } } +} +public extension Api.messages { + enum SavedReactionTags: TypeConstructorDescription { + public class Cons_savedReactionTags { + public var tags: [Api.SavedReactionTag] + public var hash: Int64 + public init(tags: [Api.SavedReactionTag], hash: Int64) { + self.tags = tags + self.hash = hash + } + } + case savedReactionTags(Cons_savedReactionTags) + case savedReactionTagsNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .savedReactionTags(let _data): + if boxed { + buffer.appendInt32(844731658) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.tags.count)) + for item in _data.tags { + item.serialize(buffer, true) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + break + case .savedReactionTagsNotModified: + if boxed { + buffer.appendInt32(-2003084817) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .savedReactionTags(let _data): + return ("savedReactionTags", [("tags", _data.tags as Any), ("hash", _data.hash as Any)]) + case .savedReactionTagsNotModified: + return ("savedReactionTagsNotModified", []) + } + } + + public static func parse_savedReactionTags(_ reader: BufferReader) -> SavedReactionTags? { + var _1: [Api.SavedReactionTag]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SavedReactionTag.self) + } + var _2: Int64? + _2 = reader.readInt64() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.SavedReactionTags.savedReactionTags(Cons_savedReactionTags(tags: _1!, hash: _2!)) + } + else { + return nil + } + } + public static func parse_savedReactionTagsNotModified(_ reader: BufferReader) -> SavedReactionTags? { + return Api.messages.SavedReactionTags.savedReactionTagsNotModified + } } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .paymentReceipt(let flags, let date, let botId, let providerId, let title, let description, let photo, let invoice, let info, let shipping, let tipAmount, let currency, let totalAmount, let credentialsTitle, let users): - return ("paymentReceipt", [("flags", flags as Any), ("date", date as Any), ("botId", botId as Any), ("providerId", providerId as Any), ("title", title as Any), ("description", description as Any), ("photo", photo as Any), ("invoice", invoice as Any), ("info", info as Any), ("shipping", shipping as Any), ("tipAmount", tipAmount as Any), ("currency", currency as Any), ("totalAmount", totalAmount as Any), ("credentialsTitle", credentialsTitle as Any), ("users", users as Any)]) - case .paymentReceiptStars(let flags, let date, let botId, let title, let description, let photo, let invoice, let currency, let totalAmount, let transactionId, let users): - return ("paymentReceiptStars", [("flags", flags as Any), ("date", date as Any), ("botId", botId as Any), ("title", title as Any), ("description", description as Any), ("photo", photo as Any), ("invoice", invoice as Any), ("currency", currency as Any), ("totalAmount", totalAmount as Any), ("transactionId", transactionId as Any), ("users", users as Any)]) +} +public extension Api.messages { + enum SearchCounter: TypeConstructorDescription { + public class Cons_searchCounter { + public var flags: Int32 + public var filter: Api.MessagesFilter + public var count: Int32 + public init(flags: Int32, filter: Api.MessagesFilter, count: Int32) { + self.flags = flags + self.filter = filter + self.count = count + } + } + case searchCounter(Cons_searchCounter) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .searchCounter(let _data): + if boxed { + buffer.appendInt32(-398136321) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.filter.serialize(buffer, true) + serializeInt32(_data.count, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .searchCounter(let _data): + return ("searchCounter", [("flags", _data.flags as Any), ("filter", _data.filter as Any), ("count", _data.count as Any)]) + } + } + + public static func parse_searchCounter(_ reader: BufferReader) -> SearchCounter? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.MessagesFilter? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.MessagesFilter + } + var _3: Int32? + _3 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.messages.SearchCounter.searchCounter(Cons_searchCounter(flags: _1!, filter: _2!, count: _3!)) + } + else { + return nil + } + } } - } - - public static func parse_paymentReceipt(_ reader: BufferReader) -> PaymentReceipt? { +} +public extension Api.messages { + enum SearchResultsCalendar: TypeConstructorDescription { + public class Cons_searchResultsCalendar { + public var flags: Int32 + public var count: Int32 + public var minDate: Int32 + public var minMsgId: Int32 + public var offsetIdOffset: Int32? + public var periods: [Api.SearchResultsCalendarPeriod] + public var messages: [Api.Message] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, count: Int32, minDate: Int32, minMsgId: Int32, offsetIdOffset: Int32?, periods: [Api.SearchResultsCalendarPeriod], messages: [Api.Message], chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.count = count + self.minDate = minDate + self.minMsgId = minMsgId + self.offsetIdOffset = offsetIdOffset + self.periods = periods + self.messages = messages + self.chats = chats + self.users = users + } + } + case searchResultsCalendar(Cons_searchResultsCalendar) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .searchResultsCalendar(let _data): + if boxed { + buffer.appendInt32(343859772) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + serializeInt32(_data.minDate, buffer: buffer, boxed: false) + serializeInt32(_data.minMsgId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.offsetIdOffset!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.periods.count)) + for item in _data.periods { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .searchResultsCalendar(let _data): + return ("searchResultsCalendar", [("flags", _data.flags as Any), ("count", _data.count as Any), ("minDate", _data.minDate as Any), ("minMsgId", _data.minMsgId as Any), ("offsetIdOffset", _data.offsetIdOffset as Any), ("periods", _data.periods as Any), ("messages", _data.messages as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_searchResultsCalendar(_ reader: BufferReader) -> SearchResultsCalendar? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? _2 = reader.readInt32() - var _3: Int64? - _3 = reader.readInt64() - var _4: Int64? - _4 = reader.readInt64() - var _5: String? - _5 = parseString(reader) - var _6: String? - _6 = parseString(reader) - var _7: Api.WebDocument? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.WebDocument - } } - var _8: Api.Invoice? - if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.Invoice - } - var _9: Api.PaymentRequestedInfo? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.PaymentRequestedInfo - } } - var _10: Api.ShippingOption? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _10 = Api.parse(reader, signature: signature) as? Api.ShippingOption - } } - var _11: Int64? - if Int(_1!) & Int(1 << 3) != 0 {_11 = reader.readInt64() } - var _12: String? - _12 = parseString(reader) - var _13: Int64? - _13 = reader.readInt64() - var _14: String? - _14 = parseString(reader) - var _15: [Api.User]? - if let _ = reader.readInt32() { - _15 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - let _c7 = (Int(_1!) & Int(1 << 2) == 0) || _7 != nil - let _c8 = _8 != nil - let _c9 = (Int(_1!) & Int(1 << 0) == 0) || _9 != nil - let _c10 = (Int(_1!) & Int(1 << 1) == 0) || _10 != nil - let _c11 = (Int(_1!) & Int(1 << 3) == 0) || _11 != nil - let _c12 = _12 != nil - let _c13 = _13 != nil - let _c14 = _14 != nil - let _c15 = _15 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - return Api.payments.PaymentReceipt.paymentReceipt(flags: _1!, date: _2!, botId: _3!, providerId: _4!, title: _5!, description: _6!, photo: _7, invoice: _8!, info: _9, shipping: _10, tipAmount: _11, currency: _12!, totalAmount: _13!, credentialsTitle: _14!, users: _15!) - } - public static func parse_paymentReceiptStars(_ reader: BufferReader) -> PaymentReceipt? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int64? - _3 = reader.readInt64() - var _4: String? - _4 = parseString(reader) - var _5: String? - _5 = parseString(reader) - var _6: Api.WebDocument? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.WebDocument - } } - var _7: Api.Invoice? - if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.Invoice - } - var _8: String? - _8 = parseString(reader) - var _9: Int64? - _9 = reader.readInt64() - var _10: String? - _10 = parseString(reader) - var _11: [Api.User]? - if let _ = reader.readInt32() { - _11 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil - let _c7 = _7 != nil - let _c8 = _8 != nil - let _c9 = _9 != nil - let _c10 = _10 != nil - let _c11 = _11 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - return Api.payments.PaymentReceipt.paymentReceiptStars(flags: _1!, date: _2!, botId: _3!, title: _4!, description: _5!, photo: _6, invoice: _7!, currency: _8!, totalAmount: _9!, transactionId: _10!, users: _11!) - } - - } -} -public extension Api.payments { - indirect enum PaymentResult: TypeConstructorDescription { - case paymentResult(updates: Api.Updates) - case paymentVerificationNeeded(url: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .paymentResult(let updates): - if boxed { - buffer.appendInt32(1314881805) - } - updates.serialize(buffer, true) - break - case .paymentVerificationNeeded(let url): - if boxed { - buffer.appendInt32(-666824391) - } - serializeString(url, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .paymentResult(let updates): - return ("paymentResult", [("updates", updates as Any)]) - case .paymentVerificationNeeded(let url): - return ("paymentVerificationNeeded", [("url", url as Any)]) - } - } - - public static func parse_paymentResult(_ reader: BufferReader) -> PaymentResult? { - var _1: Api.Updates? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Updates - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.payments.PaymentResult.paymentResult(updates: _1!) - } - public static func parse_paymentVerificationNeeded(_ reader: BufferReader) -> PaymentResult? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.payments.PaymentResult.paymentVerificationNeeded(url: _1!) - } - - } -} -public extension Api.payments { - enum ResaleStarGifts: TypeConstructorDescription { - case resaleStarGifts(flags: Int32, count: Int32, gifts: [Api.StarGift], nextOffset: String?, attributes: [Api.StarGiftAttribute]?, attributesHash: Int64?, chats: [Api.Chat], counters: [Api.StarGiftAttributeCounter]?, users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .resaleStarGifts(let flags, let count, let gifts, let nextOffset, let attributes, let attributesHash, let chats, let counters, let users): - if boxed { - buffer.appendInt32(-1803939105) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(gifts.count)) - for item in gifts { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 0) != 0 {serializeString(nextOffset!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(attributes!.count)) - for item in attributes! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 1) != 0 {serializeInt64(attributesHash!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 2) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(counters!.count)) - for item in counters! { - item.serialize(buffer, true) - }} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .resaleStarGifts(let flags, let count, let gifts, let nextOffset, let attributes, let attributesHash, let chats, let counters, let users): - return ("resaleStarGifts", [("flags", flags as Any), ("count", count as Any), ("gifts", gifts as Any), ("nextOffset", nextOffset as Any), ("attributes", attributes as Any), ("attributesHash", attributesHash as Any), ("chats", chats as Any), ("counters", counters as Any), ("users", users as Any)]) - } - } - - public static func parse_resaleStarGifts(_ reader: BufferReader) -> ResaleStarGifts? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: [Api.StarGift]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGift.self) - } - var _4: String? - if Int(_1!) & Int(1 << 0) != 0 {_4 = parseString(reader) } - var _5: [Api.StarGiftAttribute]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftAttribute.self) - } } - var _6: Int64? - if Int(_1!) & Int(1 << 1) != 0 {_6 = reader.readInt64() } - var _7: [Api.Chat]? - if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _8: [Api.StarGiftAttributeCounter]? - if Int(_1!) & Int(1 << 2) != 0 {if let _ = reader.readInt32() { - _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftAttributeCounter.self) - } } - var _9: [Api.User]? - if let _ = reader.readInt32() { - _9 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil - let _c7 = _7 != nil - let _c8 = (Int(_1!) & Int(1 << 2) == 0) || _8 != nil - let _c9 = _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.payments.ResaleStarGifts.resaleStarGifts(flags: _1!, count: _2!, gifts: _3!, nextOffset: _4, attributes: _5, attributesHash: _6, chats: _7!, counters: _8, users: _9!) - } - - } -} -public extension Api.payments { - enum SavedInfo: TypeConstructorDescription { - case savedInfo(flags: Int32, savedInfo: Api.PaymentRequestedInfo?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .savedInfo(let flags, let savedInfo): - if boxed { - buffer.appendInt32(-74456004) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {savedInfo!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .savedInfo(let flags, let savedInfo): - return ("savedInfo", [("flags", flags as Any), ("savedInfo", savedInfo as Any)]) - } - } - - public static func parse_savedInfo(_ reader: BufferReader) -> SavedInfo? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.PaymentRequestedInfo? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.PaymentRequestedInfo - } } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.payments.SavedInfo.savedInfo(flags: _1!, savedInfo: _2) - } - - } -} -public extension Api.payments { - enum SavedStarGifts: TypeConstructorDescription { - case savedStarGifts(flags: Int32, count: Int32, chatNotificationsEnabled: Api.Bool?, gifts: [Api.SavedStarGift], nextOffset: String?, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .savedStarGifts(let flags, let count, let chatNotificationsEnabled, let gifts, let nextOffset, let chats, let users): - if boxed { - buffer.appendInt32(-1779201615) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {chatNotificationsEnabled!.serialize(buffer, true)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(gifts.count)) - for item in gifts { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 0) != 0 {serializeString(nextOffset!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .savedStarGifts(let flags, let count, let chatNotificationsEnabled, let gifts, let nextOffset, let chats, let users): - return ("savedStarGifts", [("flags", flags as Any), ("count", count as Any), ("chatNotificationsEnabled", chatNotificationsEnabled as Any), ("gifts", gifts as Any), ("nextOffset", nextOffset as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_savedStarGifts(_ reader: BufferReader) -> SavedStarGifts? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Api.Bool? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Bool - } } - var _4: [Api.SavedStarGift]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SavedStarGift.self) - } - var _5: String? - if Int(_1!) & Int(1 << 0) != 0 {_5 = parseString(reader) } - var _6: [Api.Chat]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _7: [Api.User]? - if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - let _c4 = _4 != nil - let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil - let _c6 = _6 != nil - let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.payments.SavedStarGifts.savedStarGifts(flags: _1!, count: _2!, chatNotificationsEnabled: _3, gifts: _4!, nextOffset: _5, chats: _6!, users: _7!) - } - - } -} -public extension Api.payments { - enum StarGiftActiveAuctions: TypeConstructorDescription { - case starGiftActiveAuctions(auctions: [Api.StarGiftActiveAuctionState], users: [Api.User], chats: [Api.Chat]) - case starGiftActiveAuctionsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftActiveAuctions(let auctions, let users, let chats): - if boxed { - buffer.appendInt32(-1359565892) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(auctions.count)) - for item in auctions { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - break - case .starGiftActiveAuctionsNotModified: - if boxed { - buffer.appendInt32(-617358640) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftActiveAuctions(let auctions, let users, let chats): - return ("starGiftActiveAuctions", [("auctions", auctions as Any), ("users", users as Any), ("chats", chats as Any)]) - case .starGiftActiveAuctionsNotModified: - return ("starGiftActiveAuctionsNotModified", []) - } - } - - public static func parse_starGiftActiveAuctions(_ reader: BufferReader) -> StarGiftActiveAuctions? { - var _1: [Api.StarGiftActiveAuctionState]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftActiveAuctionState.self) - } - var _2: [Api.User]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - var _3: [Api.Chat]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.payments.StarGiftActiveAuctions.starGiftActiveAuctions(auctions: _1!, users: _2!, chats: _3!) - } - public static func parse_starGiftActiveAuctionsNotModified(_ reader: BufferReader) -> StarGiftActiveAuctions? { - return Api.payments.StarGiftActiveAuctions.starGiftActiveAuctionsNotModified - } - - } -} -public extension Api.payments { - enum StarGiftAuctionAcquiredGifts: TypeConstructorDescription { - case starGiftAuctionAcquiredGifts(gifts: [Api.StarGiftAuctionAcquiredGift], users: [Api.User], chats: [Api.Chat]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftAuctionAcquiredGifts(let gifts, let users, let chats): - if boxed { - buffer.appendInt32(2103169520) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(gifts.count)) - for item in gifts { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftAuctionAcquiredGifts(let gifts, let users, let chats): - return ("starGiftAuctionAcquiredGifts", [("gifts", gifts as Any), ("users", users as Any), ("chats", chats as Any)]) - } - } - - public static func parse_starGiftAuctionAcquiredGifts(_ reader: BufferReader) -> StarGiftAuctionAcquiredGifts? { - var _1: [Api.StarGiftAuctionAcquiredGift]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftAuctionAcquiredGift.self) - } - var _2: [Api.User]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - var _3: [Api.Chat]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.payments.StarGiftAuctionAcquiredGifts.starGiftAuctionAcquiredGifts(gifts: _1!, users: _2!, chats: _3!) - } - - } -} -public extension Api.payments { - enum StarGiftAuctionState: TypeConstructorDescription { - case starGiftAuctionState(gift: Api.StarGift, state: Api.StarGiftAuctionState, userState: Api.StarGiftAuctionUserState, timeout: Int32, users: [Api.User], chats: [Api.Chat]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftAuctionState(let gift, let state, let userState, let timeout, let users, let chats): - if boxed { - buffer.appendInt32(1798960364) - } - gift.serialize(buffer, true) - state.serialize(buffer, true) - userState.serialize(buffer, true) - serializeInt32(timeout, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftAuctionState(let gift, let state, let userState, let timeout, let users, let chats): - return ("starGiftAuctionState", [("gift", gift as Any), ("state", state as Any), ("userState", userState as Any), ("timeout", timeout as Any), ("users", users as Any), ("chats", chats as Any)]) - } - } - - public static func parse_starGiftAuctionState(_ reader: BufferReader) -> StarGiftAuctionState? { - var _1: Api.StarGift? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.StarGift - } - var _2: Api.StarGiftAuctionState? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.StarGiftAuctionState - } - var _3: Api.StarGiftAuctionUserState? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.StarGiftAuctionUserState - } + var _3: Int32? + _3 = reader.readInt32() var _4: Int32? _4 = reader.readInt32() - var _5: [Api.User]? + var _5: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _5 = reader.readInt32() + } + var _6: [Api.SearchResultsCalendarPeriod]? if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SearchResultsCalendarPeriod.self) } - var _6: [Api.Chat]? + var _7: [Api.Message]? if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.payments.StarGiftAuctionState.starGiftAuctionState(gift: _1!, state: _2!, userState: _3!, timeout: _4!, users: _5!, chats: _6!) - } - - } -} -public extension Api.payments { - enum StarGiftCollections: TypeConstructorDescription { - case starGiftCollections(collections: [Api.StarGiftCollection]) - case starGiftCollectionsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftCollections(let collections): - if boxed { - buffer.appendInt32(-1977011469) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(collections.count)) - for item in collections { - item.serialize(buffer, true) - } - break - case .starGiftCollectionsNotModified: - if boxed { - buffer.appendInt32(-1598402793) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftCollections(let collections): - return ("starGiftCollections", [("collections", collections as Any)]) - case .starGiftCollectionsNotModified: - return ("starGiftCollectionsNotModified", []) - } - } - - public static func parse_starGiftCollections(_ reader: BufferReader) -> StarGiftCollections? { - var _1: [Api.StarGiftCollection]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftCollection.self) - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.payments.StarGiftCollections.starGiftCollections(collections: _1!) - } - public static func parse_starGiftCollectionsNotModified(_ reader: BufferReader) -> StarGiftCollections? { - return Api.payments.StarGiftCollections.starGiftCollectionsNotModified - } - - } -} -public extension Api.payments { - enum StarGiftUpgradeAttributes: TypeConstructorDescription { - case starGiftUpgradeAttributes(attributes: [Api.StarGiftAttribute]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftUpgradeAttributes(let attributes): - if boxed { - buffer.appendInt32(1187439471) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(attributes.count)) - for item in attributes { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftUpgradeAttributes(let attributes): - return ("starGiftUpgradeAttributes", [("attributes", attributes as Any)]) - } - } - - public static func parse_starGiftUpgradeAttributes(_ reader: BufferReader) -> StarGiftUpgradeAttributes? { - var _1: [Api.StarGiftAttribute]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftAttribute.self) - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.payments.StarGiftUpgradeAttributes.starGiftUpgradeAttributes(attributes: _1!) - } - - } -} -public extension Api.payments { - enum StarGiftUpgradePreview: TypeConstructorDescription { - case starGiftUpgradePreview(sampleAttributes: [Api.StarGiftAttribute], prices: [Api.StarGiftUpgradePrice], nextPrices: [Api.StarGiftUpgradePrice]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftUpgradePreview(let sampleAttributes, let prices, let nextPrices): - if boxed { - buffer.appendInt32(1038213101) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(sampleAttributes.count)) - for item in sampleAttributes { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(prices.count)) - for item in prices { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(nextPrices.count)) - for item in nextPrices { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftUpgradePreview(let sampleAttributes, let prices, let nextPrices): - return ("starGiftUpgradePreview", [("sampleAttributes", sampleAttributes as Any), ("prices", prices as Any), ("nextPrices", nextPrices as Any)]) - } - } - - public static func parse_starGiftUpgradePreview(_ reader: BufferReader) -> StarGiftUpgradePreview? { - var _1: [Api.StarGiftAttribute]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftAttribute.self) - } - var _2: [Api.StarGiftUpgradePrice]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftUpgradePrice.self) - } - var _3: [Api.StarGiftUpgradePrice]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftUpgradePrice.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.payments.StarGiftUpgradePreview.starGiftUpgradePreview(sampleAttributes: _1!, prices: _2!, nextPrices: _3!) - } - - } -} -public extension Api.payments { - enum StarGiftWithdrawalUrl: TypeConstructorDescription { - case starGiftWithdrawalUrl(url: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGiftWithdrawalUrl(let url): - if boxed { - buffer.appendInt32(-2069218660) - } - serializeString(url, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGiftWithdrawalUrl(let url): - return ("starGiftWithdrawalUrl", [("url", url as Any)]) - } - } - - public static func parse_starGiftWithdrawalUrl(_ reader: BufferReader) -> StarGiftWithdrawalUrl? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.payments.StarGiftWithdrawalUrl.starGiftWithdrawalUrl(url: _1!) - } - - } -} -public extension Api.payments { - enum StarGifts: TypeConstructorDescription { - case starGifts(hash: Int32, gifts: [Api.StarGift], chats: [Api.Chat], users: [Api.User]) - case starGiftsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starGifts(let hash, let gifts, let chats, let users): - if boxed { - buffer.appendInt32(785918357) - } - serializeInt32(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(gifts.count)) - for item in gifts { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .starGiftsNotModified: - if boxed { - buffer.appendInt32(-1551326360) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starGifts(let hash, let gifts, let chats, let users): - return ("starGifts", [("hash", hash as Any), ("gifts", gifts as Any), ("chats", chats as Any), ("users", users as Any)]) - case .starGiftsNotModified: - return ("starGiftsNotModified", []) - } - } - - public static func parse_starGifts(_ reader: BufferReader) -> StarGifts? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.StarGift]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGift.self) - } - var _3: [Api.Chat]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _4: [Api.User]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.payments.StarGifts.starGifts(hash: _1!, gifts: _2!, chats: _3!, users: _4!) - } - public static func parse_starGiftsNotModified(_ reader: BufferReader) -> StarGifts? { - return Api.payments.StarGifts.starGiftsNotModified - } - - } -} -public extension Api.payments { - enum StarsRevenueAdsAccountUrl: TypeConstructorDescription { - case starsRevenueAdsAccountUrl(url: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starsRevenueAdsAccountUrl(let url): - if boxed { - buffer.appendInt32(961445665) - } - serializeString(url, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starsRevenueAdsAccountUrl(let url): - return ("starsRevenueAdsAccountUrl", [("url", url as Any)]) - } - } - - public static func parse_starsRevenueAdsAccountUrl(_ reader: BufferReader) -> StarsRevenueAdsAccountUrl? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.payments.StarsRevenueAdsAccountUrl.starsRevenueAdsAccountUrl(url: _1!) - } - - } -} -public extension Api.payments { - enum StarsRevenueStats: TypeConstructorDescription { - case starsRevenueStats(flags: Int32, topHoursGraph: Api.StatsGraph?, revenueGraph: Api.StatsGraph, status: Api.StarsRevenueStatus, usdRate: Double) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starsRevenueStats(let flags, let topHoursGraph, let revenueGraph, let status, let usdRate): - if boxed { - buffer.appendInt32(1814066038) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {topHoursGraph!.serialize(buffer, true)} - revenueGraph.serialize(buffer, true) - status.serialize(buffer, true) - serializeDouble(usdRate, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starsRevenueStats(let flags, let topHoursGraph, let revenueGraph, let status, let usdRate): - return ("starsRevenueStats", [("flags", flags as Any), ("topHoursGraph", topHoursGraph as Any), ("revenueGraph", revenueGraph as Any), ("status", status as Any), ("usdRate", usdRate as Any)]) - } - } - - public static func parse_starsRevenueStats(_ reader: BufferReader) -> StarsRevenueStats? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.StatsGraph? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } } - var _3: Api.StatsGraph? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _4: Api.StarsRevenueStatus? - if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.StarsRevenueStatus - } - var _5: Double? - _5 = reader.readDouble() - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.payments.StarsRevenueStats.starsRevenueStats(flags: _1!, topHoursGraph: _2, revenueGraph: _3!, status: _4!, usdRate: _5!) - } - - } -} -public extension Api.payments { - enum StarsRevenueWithdrawalUrl: TypeConstructorDescription { - case starsRevenueWithdrawalUrl(url: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starsRevenueWithdrawalUrl(let url): - if boxed { - buffer.appendInt32(497778871) - } - serializeString(url, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starsRevenueWithdrawalUrl(let url): - return ("starsRevenueWithdrawalUrl", [("url", url as Any)]) - } - } - - public static func parse_starsRevenueWithdrawalUrl(_ reader: BufferReader) -> StarsRevenueWithdrawalUrl? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.payments.StarsRevenueWithdrawalUrl.starsRevenueWithdrawalUrl(url: _1!) - } - - } -} -public extension Api.payments { - enum StarsStatus: TypeConstructorDescription { - case starsStatus(flags: Int32, balance: Api.StarsAmount, subscriptions: [Api.StarsSubscription]?, subscriptionsNextOffset: String?, subscriptionsMissingBalance: Int64?, history: [Api.StarsTransaction]?, nextOffset: String?, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .starsStatus(let flags, let balance, let subscriptions, let subscriptionsNextOffset, let subscriptionsMissingBalance, let history, let nextOffset, let chats, let users): - if boxed { - buffer.appendInt32(1822222573) - } - serializeInt32(flags, buffer: buffer, boxed: false) - balance.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(subscriptions!.count)) - for item in subscriptions! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 2) != 0 {serializeString(subscriptionsNextOffset!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt64(subscriptionsMissingBalance!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(history!.count)) - for item in history! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 0) != 0 {serializeString(nextOffset!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .starsStatus(let flags, let balance, let subscriptions, let subscriptionsNextOffset, let subscriptionsMissingBalance, let history, let nextOffset, let chats, let users): - return ("starsStatus", [("flags", flags as Any), ("balance", balance as Any), ("subscriptions", subscriptions as Any), ("subscriptionsNextOffset", subscriptionsNextOffset as Any), ("subscriptionsMissingBalance", subscriptionsMissingBalance as Any), ("history", history as Any), ("nextOffset", nextOffset as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_starsStatus(_ reader: BufferReader) -> StarsStatus? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Api.StarsAmount? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.StarsAmount - } - var _3: [Api.StarsSubscription]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarsSubscription.self) - } } - var _4: String? - if Int(_1!) & Int(1 << 2) != 0 {_4 = parseString(reader) } - var _5: Int64? - if Int(_1!) & Int(1 << 4) != 0 {_5 = reader.readInt64() } - var _6: [Api.StarsTransaction]? - if Int(_1!) & Int(1 << 3) != 0 {if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarsTransaction.self) - } } - var _7: String? - if Int(_1!) & Int(1 << 0) != 0 {_7 = parseString(reader) } var _8: [Api.Chat]? if let _ = reader.readInt32() { _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) @@ -1126,127 +282,739 @@ public extension Api.payments { } let _c1 = _1 != nil let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - let _c5 = (Int(_1!) & Int(1 << 4) == 0) || _5 != nil - let _c6 = (Int(_1!) & Int(1 << 3) == 0) || _6 != nil - let _c7 = (Int(_1!) & Int(1 << 0) == 0) || _7 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil + let _c6 = _6 != nil + let _c7 = _7 != nil let _c8 = _8 != nil let _c9 = _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.payments.StarsStatus.starsStatus(flags: _1!, balance: _2!, subscriptions: _3, subscriptionsNextOffset: _4, subscriptionsMissingBalance: _5, history: _6, nextOffset: _7, chats: _8!, users: _9!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.messages.SearchResultsCalendar.searchResultsCalendar(Cons_searchResultsCalendar(flags: _1!, count: _2!, minDate: _3!, minMsgId: _4!, offsetIdOffset: _5, periods: _6!, messages: _7!, chats: _8!, users: _9!)) + } + else { + return nil + } } - } } -public extension Api.payments { - enum SuggestedStarRefBots: TypeConstructorDescription { - case suggestedStarRefBots(flags: Int32, count: Int32, suggestedBots: [Api.StarRefProgram], users: [Api.User], nextOffset: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .suggestedStarRefBots(let flags, let count, let suggestedBots, let users, let nextOffset): - if boxed { - buffer.appendInt32(-1261053863) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(suggestedBots.count)) - for item in suggestedBots { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 0) != 0 {serializeString(nextOffset!, buffer: buffer, boxed: false)} - break +public extension Api.messages { + enum SearchResultsPositions: TypeConstructorDescription { + public class Cons_searchResultsPositions { + public var count: Int32 + public var positions: [Api.SearchResultsPosition] + public init(count: Int32, positions: [Api.SearchResultsPosition]) { + self.count = count + self.positions = positions + } + } + case searchResultsPositions(Cons_searchResultsPositions) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .searchResultsPositions(let _data): + if boxed { + buffer.appendInt32(1404185519) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.positions.count)) + for item in _data.positions { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .searchResultsPositions(let _data): + return ("searchResultsPositions", [("count", _data.count as Any), ("positions", _data.positions as Any)]) + } + } + + public static func parse_searchResultsPositions(_ reader: BufferReader) -> SearchResultsPositions? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.SearchResultsPosition]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SearchResultsPosition.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.SearchResultsPositions.searchResultsPositions(Cons_searchResultsPositions(count: _1!, positions: _2!)) + } + else { + return nil + } + } } +} +public extension Api.messages { + enum SentEncryptedMessage: TypeConstructorDescription { + public class Cons_sentEncryptedFile { + public var date: Int32 + public var file: Api.EncryptedFile + public init(date: Int32, file: Api.EncryptedFile) { + self.date = date + self.file = file + } + } + public class Cons_sentEncryptedMessage { + public var date: Int32 + public init(date: Int32) { + self.date = date + } + } + case sentEncryptedFile(Cons_sentEncryptedFile) + case sentEncryptedMessage(Cons_sentEncryptedMessage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .sentEncryptedFile(let _data): + if boxed { + buffer.appendInt32(-1802240206) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + _data.file.serialize(buffer, true) + break + case .sentEncryptedMessage(let _data): + if boxed { + buffer.appendInt32(1443858741) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .sentEncryptedFile(let _data): + return ("sentEncryptedFile", [("date", _data.date as Any), ("file", _data.file as Any)]) + case .sentEncryptedMessage(let _data): + return ("sentEncryptedMessage", [("date", _data.date as Any)]) + } + } + + public static func parse_sentEncryptedFile(_ reader: BufferReader) -> SentEncryptedMessage? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.EncryptedFile? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.EncryptedFile + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.SentEncryptedMessage.sentEncryptedFile(Cons_sentEncryptedFile(date: _1!, file: _2!)) + } + else { + return nil + } + } + public static func parse_sentEncryptedMessage(_ reader: BufferReader) -> SentEncryptedMessage? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.messages.SentEncryptedMessage.sentEncryptedMessage(Cons_sentEncryptedMessage(date: _1!)) + } + else { + return nil + } + } } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .suggestedStarRefBots(let flags, let count, let suggestedBots, let users, let nextOffset): - return ("suggestedStarRefBots", [("flags", flags as Any), ("count", count as Any), ("suggestedBots", suggestedBots as Any), ("users", users as Any), ("nextOffset", nextOffset as Any)]) - } - } - - public static func parse_suggestedStarRefBots(_ reader: BufferReader) -> SuggestedStarRefBots? { +} +public extension Api.messages { + enum SponsoredMessages: TypeConstructorDescription { + public class Cons_sponsoredMessages { + public var flags: Int32 + public var postsBetween: Int32? + public var startDelay: Int32? + public var betweenDelay: Int32? + public var messages: [Api.SponsoredMessage] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, postsBetween: Int32?, startDelay: Int32?, betweenDelay: Int32?, messages: [Api.SponsoredMessage], chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.postsBetween = postsBetween + self.startDelay = startDelay + self.betweenDelay = betweenDelay + self.messages = messages + self.chats = chats + self.users = users + } + } + case sponsoredMessages(Cons_sponsoredMessages) + case sponsoredMessagesEmpty + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .sponsoredMessages(let _data): + if boxed { + buffer.appendInt32(-2464403) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.postsBetween!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.startDelay!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.betweenDelay!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .sponsoredMessagesEmpty: + if boxed { + buffer.appendInt32(406407439) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .sponsoredMessages(let _data): + return ("sponsoredMessages", [("flags", _data.flags as Any), ("postsBetween", _data.postsBetween as Any), ("startDelay", _data.startDelay as Any), ("betweenDelay", _data.betweenDelay as Any), ("messages", _data.messages as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + case .sponsoredMessagesEmpty: + return ("sponsoredMessagesEmpty", []) + } + } + + public static func parse_sponsoredMessages(_ reader: BufferReader) -> SponsoredMessages? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? - _2 = reader.readInt32() - var _3: [Api.StarRefProgram]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarRefProgram.self) + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt32() } - var _4: [Api.User]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + var _3: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _3 = reader.readInt32() + } + var _4: Int32? + if Int(_1!) & Int(1 << 2) != 0 { + _4 = reader.readInt32() + } + var _5: [Api.SponsoredMessage]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SponsoredMessage.self) + } + var _6: [Api.Chat]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _7: [Api.User]? + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil + let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + let _c7 = _7 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.messages.SponsoredMessages.sponsoredMessages(Cons_sponsoredMessages(flags: _1!, postsBetween: _2, startDelay: _3, betweenDelay: _4, messages: _5!, chats: _6!, users: _7!)) + } + else { + return nil + } + } + public static func parse_sponsoredMessagesEmpty(_ reader: BufferReader) -> SponsoredMessages? { + return Api.messages.SponsoredMessages.sponsoredMessagesEmpty + } + } +} +public extension Api.messages { + enum StickerSet: TypeConstructorDescription { + public class Cons_stickerSet { + public var set: Api.StickerSet + public var packs: [Api.StickerPack] + public var keywords: [Api.StickerKeyword] + public var documents: [Api.Document] + public init(set: Api.StickerSet, packs: [Api.StickerPack], keywords: [Api.StickerKeyword], documents: [Api.Document]) { + self.set = set + self.packs = packs + self.keywords = keywords + self.documents = documents + } + } + case stickerSet(Cons_stickerSet) + case stickerSetNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .stickerSet(let _data): + if boxed { + buffer.appendInt32(1846886166) + } + _data.set.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.packs.count)) + for item in _data.packs { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.keywords.count)) + for item in _data.keywords { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.documents.count)) + for item in _data.documents { + item.serialize(buffer, true) + } + break + case .stickerSetNotModified: + if boxed { + buffer.appendInt32(-738646805) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .stickerSet(let _data): + return ("stickerSet", [("set", _data.set as Any), ("packs", _data.packs as Any), ("keywords", _data.keywords as Any), ("documents", _data.documents as Any)]) + case .stickerSetNotModified: + return ("stickerSetNotModified", []) + } + } + + public static func parse_stickerSet(_ reader: BufferReader) -> StickerSet? { + var _1: Api.StickerSet? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.StickerSet + } + var _2: [Api.StickerPack]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerPack.self) + } + var _3: [Api.StickerKeyword]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerKeyword.self) + } + var _4: [Api.Document]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) } - var _5: String? - if Int(_1!) & Int(1 << 0) != 0 {_5 = parseString(reader) } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.payments.SuggestedStarRefBots.suggestedStarRefBots(flags: _1!, count: _2!, suggestedBots: _3!, users: _4!, nextOffset: _5) + if _c1 && _c2 && _c3 && _c4 { + return Api.messages.StickerSet.stickerSet(Cons_stickerSet(set: _1!, packs: _2!, keywords: _3!, documents: _4!)) + } + else { + return nil + } + } + public static func parse_stickerSetNotModified(_ reader: BufferReader) -> StickerSet? { + return Api.messages.StickerSet.stickerSetNotModified } - } } -public extension Api.payments { - enum UniqueStarGift: TypeConstructorDescription { - case uniqueStarGift(gift: Api.StarGift, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .uniqueStarGift(let gift, let chats, let users): - if boxed { - buffer.appendInt32(1097619176) - } - gift.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break +public extension Api.messages { + enum StickerSetInstallResult: TypeConstructorDescription { + public class Cons_stickerSetInstallResultArchive { + public var sets: [Api.StickerSetCovered] + public init(sets: [Api.StickerSetCovered]) { + self.sets = sets + } + } + case stickerSetInstallResultArchive(Cons_stickerSetInstallResultArchive) + case stickerSetInstallResultSuccess + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .stickerSetInstallResultArchive(let _data): + if boxed { + buffer.appendInt32(904138920) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.sets.count)) + for item in _data.sets { + item.serialize(buffer, true) + } + break + case .stickerSetInstallResultSuccess: + if boxed { + buffer.appendInt32(946083368) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .stickerSetInstallResultArchive(let _data): + return ("stickerSetInstallResultArchive", [("sets", _data.sets as Any)]) + case .stickerSetInstallResultSuccess: + return ("stickerSetInstallResultSuccess", []) + } + } + + public static func parse_stickerSetInstallResultArchive(_ reader: BufferReader) -> StickerSetInstallResult? { + var _1: [Api.StickerSetCovered]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerSetCovered.self) + } + let _c1 = _1 != nil + if _c1 { + return Api.messages.StickerSetInstallResult.stickerSetInstallResultArchive(Cons_stickerSetInstallResultArchive(sets: _1!)) + } + else { + return nil + } + } + public static func parse_stickerSetInstallResultSuccess(_ reader: BufferReader) -> StickerSetInstallResult? { + return Api.messages.StickerSetInstallResult.stickerSetInstallResultSuccess + } } +} +public extension Api.messages { + enum Stickers: TypeConstructorDescription { + public class Cons_stickers { + public var hash: Int64 + public var stickers: [Api.Document] + public init(hash: Int64, stickers: [Api.Document]) { + self.hash = hash + self.stickers = stickers + } + } + case stickers(Cons_stickers) + case stickersNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .stickers(let _data): + if boxed { + buffer.appendInt32(816245886) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.stickers.count)) + for item in _data.stickers { + item.serialize(buffer, true) + } + break + case .stickersNotModified: + if boxed { + buffer.appendInt32(-244016606) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .stickers(let _data): + return ("stickers", [("hash", _data.hash as Any), ("stickers", _data.stickers as Any)]) + case .stickersNotModified: + return ("stickersNotModified", []) + } + } + + public static func parse_stickers(_ reader: BufferReader) -> Stickers? { + var _1: Int64? + _1 = reader.readInt64() + var _2: [Api.Document]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.messages.Stickers.stickers(Cons_stickers(hash: _1!, stickers: _2!)) + } + else { + return nil + } + } + public static func parse_stickersNotModified(_ reader: BufferReader) -> Stickers? { + return Api.messages.Stickers.stickersNotModified + } } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .uniqueStarGift(let gift, let chats, let users): - return ("uniqueStarGift", [("gift", gift as Any), ("chats", chats as Any), ("users", users as Any)]) +} +public extension Api.messages { + enum TranscribedAudio: TypeConstructorDescription { + public class Cons_transcribedAudio { + public var flags: Int32 + public var transcriptionId: Int64 + public var text: String + public var trialRemainsNum: Int32? + public var trialRemainsUntilDate: Int32? + public init(flags: Int32, transcriptionId: Int64, text: String, trialRemainsNum: Int32?, trialRemainsUntilDate: Int32?) { + self.flags = flags + self.transcriptionId = transcriptionId + self.text = text + self.trialRemainsNum = trialRemainsNum + self.trialRemainsUntilDate = trialRemainsUntilDate + } + } + case transcribedAudio(Cons_transcribedAudio) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .transcribedAudio(let _data): + if boxed { + buffer.appendInt32(-809903785) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.transcriptionId, buffer: buffer, boxed: false) + serializeString(_data.text, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.trialRemainsNum!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.trialRemainsUntilDate!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .transcribedAudio(let _data): + return ("transcribedAudio", [("flags", _data.flags as Any), ("transcriptionId", _data.transcriptionId as Any), ("text", _data.text as Any), ("trialRemainsNum", _data.trialRemainsNum as Any), ("trialRemainsUntilDate", _data.trialRemainsUntilDate as Any)]) + } + } + + public static func parse_transcribedAudio(_ reader: BufferReader) -> TranscribedAudio? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: String? + _3 = parseString(reader) + var _4: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _4 = reader.readInt32() + } + var _5: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _5 = reader.readInt32() + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil + let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.messages.TranscribedAudio.transcribedAudio(Cons_transcribedAudio(flags: _1!, transcriptionId: _2!, text: _3!, trialRemainsNum: _4, trialRemainsUntilDate: _5)) + } + else { + return nil + } + } } +} +public extension Api.messages { + enum TranslatedText: TypeConstructorDescription { + public class Cons_translateResult { + public var result: [Api.TextWithEntities] + public init(result: [Api.TextWithEntities]) { + self.result = result + } + } + case translateResult(Cons_translateResult) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .translateResult(let _data): + if boxed { + buffer.appendInt32(870003448) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.result.count)) + for item in _data.result { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .translateResult(let _data): + return ("translateResult", [("result", _data.result as Any)]) + } + } + + public static func parse_translateResult(_ reader: BufferReader) -> TranslatedText? { + var _1: [Api.TextWithEntities]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.TextWithEntities.self) + } + let _c1 = _1 != nil + if _c1 { + return Api.messages.TranslatedText.translateResult(Cons_translateResult(result: _1!)) + } + else { + return nil + } + } } - - public static func parse_uniqueStarGift(_ reader: BufferReader) -> UniqueStarGift? { - var _1: Api.StarGift? +} +public extension Api.messages { + enum VotesList: TypeConstructorDescription { + public class Cons_votesList { + public var flags: Int32 + public var count: Int32 + public var votes: [Api.MessagePeerVote] + public var chats: [Api.Chat] + public var users: [Api.User] + public var nextOffset: String? + public init(flags: Int32, count: Int32, votes: [Api.MessagePeerVote], chats: [Api.Chat], users: [Api.User], nextOffset: String?) { + self.flags = flags + self.count = count + self.votes = votes + self.chats = chats + self.users = users + self.nextOffset = nextOffset + } + } + case votesList(Cons_votesList) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .votesList(let _data): + if boxed { + buffer.appendInt32(1218005070) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.votes.count)) + for item in _data.votes { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.nextOffset!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .votesList(let _data): + return ("votesList", [("flags", _data.flags as Any), ("count", _data.count as Any), ("votes", _data.votes as Any), ("chats", _data.chats as Any), ("users", _data.users as Any), ("nextOffset", _data.nextOffset as Any)]) + } + } + + public static func parse_votesList(_ reader: BufferReader) -> VotesList? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: [Api.MessagePeerVote]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessagePeerVote.self) + } + var _4: [Api.Chat]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _5: [Api.User]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + var _6: String? + if Int(_1!) & Int(1 << 0) != 0 { + _6 = parseString(reader) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.messages.VotesList.votesList(Cons_votesList(flags: _1!, count: _2!, votes: _3!, chats: _4!, users: _5!, nextOffset: _6)) + } + else { + return nil + } + } + } +} +public extension Api.messages { + enum WebPage: TypeConstructorDescription { + public class Cons_webPage { + public var webpage: Api.WebPage + public var chats: [Api.Chat] + public var users: [Api.User] + public init(webpage: Api.WebPage, chats: [Api.Chat], users: [Api.User]) { + self.webpage = webpage + self.chats = chats + self.users = users + } + } + case webPage(Cons_webPage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .webPage(let _data): + if boxed { + buffer.appendInt32(-44166467) + } + _data.webpage.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .webPage(let _data): + return ("webPage", [("webpage", _data.webpage as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_webPage(_ reader: BufferReader) -> WebPage? { + var _1: Api.WebPage? if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.StarGift + _1 = Api.parse(reader, signature: signature) as? Api.WebPage } var _2: [Api.Chat]? if let _ = reader.readInt32() { @@ -1259,470 +1027,853 @@ public extension Api.payments { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.payments.UniqueStarGift.uniqueStarGift(gift: _1!, chats: _2!, users: _3!) + if _c1 && _c2 && _c3 { + return Api.messages.WebPage.webPage(Cons_webPage(webpage: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } } - } } -public extension Api.payments { - enum UniqueStarGiftValueInfo: TypeConstructorDescription { - case uniqueStarGiftValueInfo(flags: Int32, currency: String, value: Int64, initialSaleDate: Int32, initialSaleStars: Int64, initialSalePrice: Int64, lastSaleDate: Int32?, lastSalePrice: Int64?, floorPrice: Int64?, averagePrice: Int64?, listedCount: Int32?, fragmentListedCount: Int32?, fragmentListedUrl: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .uniqueStarGiftValueInfo(let flags, let currency, let value, let initialSaleDate, let initialSaleStars, let initialSalePrice, let lastSaleDate, let lastSalePrice, let floorPrice, let averagePrice, let listedCount, let fragmentListedCount, let fragmentListedUrl): - if boxed { - buffer.appendInt32(1362093126) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(currency, buffer: buffer, boxed: false) - serializeInt64(value, buffer: buffer, boxed: false) - serializeInt32(initialSaleDate, buffer: buffer, boxed: false) - serializeInt64(initialSaleStars, buffer: buffer, boxed: false) - serializeInt64(initialSalePrice, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(lastSaleDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(lastSalePrice!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt64(floorPrice!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt64(averagePrice!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(listedCount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeInt32(fragmentListedCount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeString(fragmentListedUrl!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .uniqueStarGiftValueInfo(let flags, let currency, let value, let initialSaleDate, let initialSaleStars, let initialSalePrice, let lastSaleDate, let lastSalePrice, let floorPrice, let averagePrice, let listedCount, let fragmentListedCount, let fragmentListedUrl): - return ("uniqueStarGiftValueInfo", [("flags", flags as Any), ("currency", currency as Any), ("value", value as Any), ("initialSaleDate", initialSaleDate as Any), ("initialSaleStars", initialSaleStars as Any), ("initialSalePrice", initialSalePrice as Any), ("lastSaleDate", lastSaleDate as Any), ("lastSalePrice", lastSalePrice as Any), ("floorPrice", floorPrice as Any), ("averagePrice", averagePrice as Any), ("listedCount", listedCount as Any), ("fragmentListedCount", fragmentListedCount as Any), ("fragmentListedUrl", fragmentListedUrl as Any)]) - } - } - - public static func parse_uniqueStarGiftValueInfo(_ reader: BufferReader) -> UniqueStarGiftValueInfo? { - var _1: Int32? - _1 = reader.readInt32() - var _2: String? - _2 = parseString(reader) - var _3: Int64? - _3 = reader.readInt64() - var _4: Int32? - _4 = reader.readInt32() - var _5: Int64? - _5 = reader.readInt64() - var _6: Int64? - _6 = reader.readInt64() - var _7: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_7 = reader.readInt32() } - var _8: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_8 = reader.readInt64() } - var _9: Int64? - if Int(_1!) & Int(1 << 2) != 0 {_9 = reader.readInt64() } - var _10: Int64? - if Int(_1!) & Int(1 << 3) != 0 {_10 = reader.readInt64() } - var _11: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_11 = reader.readInt32() } - var _12: Int32? - if Int(_1!) & Int(1 << 5) != 0 {_12 = reader.readInt32() } - var _13: String? - if Int(_1!) & Int(1 << 5) != 0 {_13 = parseString(reader) } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - let _c7 = (Int(_1!) & Int(1 << 0) == 0) || _7 != nil - let _c8 = (Int(_1!) & Int(1 << 0) == 0) || _8 != nil - let _c9 = (Int(_1!) & Int(1 << 2) == 0) || _9 != nil - let _c10 = (Int(_1!) & Int(1 << 3) == 0) || _10 != nil - let _c11 = (Int(_1!) & Int(1 << 4) == 0) || _11 != nil - let _c12 = (Int(_1!) & Int(1 << 5) == 0) || _12 != nil - let _c13 = (Int(_1!) & Int(1 << 5) == 0) || _13 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - return Api.payments.UniqueStarGiftValueInfo.uniqueStarGiftValueInfo(flags: _1!, currency: _2!, value: _3!, initialSaleDate: _4!, initialSaleStars: _5!, initialSalePrice: _6!, lastSaleDate: _7, lastSalePrice: _8, floorPrice: _9, averagePrice: _10, listedCount: _11, fragmentListedCount: _12, fragmentListedUrl: _13) +public extension Api.messages { + indirect enum WebPagePreview: TypeConstructorDescription { + public class Cons_webPagePreview { + public var media: Api.MessageMedia + public var chats: [Api.Chat] + public var users: [Api.User] + public init(media: Api.MessageMedia, chats: [Api.Chat], users: [Api.User]) { + self.media = media + self.chats = chats + self.users = users + } } - - } -} -public extension Api.payments { - enum ValidatedRequestedInfo: TypeConstructorDescription { - case validatedRequestedInfo(flags: Int32, id: String?, shippingOptions: [Api.ShippingOption]?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .validatedRequestedInfo(let flags, let id, let shippingOptions): - if boxed { - buffer.appendInt32(-784000893) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(id!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(shippingOptions!.count)) - for item in shippingOptions! { - item.serialize(buffer, true) - }} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .validatedRequestedInfo(let flags, let id, let shippingOptions): - return ("validatedRequestedInfo", [("flags", flags as Any), ("id", id as Any), ("shippingOptions", shippingOptions as Any)]) - } - } - - public static func parse_validatedRequestedInfo(_ reader: BufferReader) -> ValidatedRequestedInfo? { - var _1: Int32? - _1 = reader.readInt32() - var _2: String? - if Int(_1!) & Int(1 << 0) != 0 {_2 = parseString(reader) } - var _3: [Api.ShippingOption]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ShippingOption.self) - } } - let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.payments.ValidatedRequestedInfo.validatedRequestedInfo(flags: _1!, id: _2, shippingOptions: _3) + case webPagePreview(Cons_webPagePreview) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .webPagePreview(let _data): + if boxed { + buffer.appendInt32(-1936029524) + } + _data.media.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } } - - } -} -public extension Api.phone { - enum ExportedGroupCallInvite: TypeConstructorDescription { - case exportedGroupCallInvite(link: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .exportedGroupCallInvite(let link): - if boxed { - buffer.appendInt32(541839704) - } - serializeString(link, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .exportedGroupCallInvite(let link): - return ("exportedGroupCallInvite", [("link", link as Any)]) - } - } - - public static func parse_exportedGroupCallInvite(_ reader: BufferReader) -> ExportedGroupCallInvite? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.phone.ExportedGroupCallInvite.exportedGroupCallInvite(link: _1!) + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .webPagePreview(let _data): + return ("webPagePreview", [("media", _data.media as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } } - - } -} -public extension Api.phone { - enum GroupCall: TypeConstructorDescription { - case groupCall(call: Api.GroupCall, participants: [Api.GroupCallParticipant], participantsNextOffset: String, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .groupCall(let call, let participants, let participantsNextOffset, let chats, let users): - if boxed { - buffer.appendInt32(-1636664659) - } - call.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(participants.count)) - for item in participants { - item.serialize(buffer, true) - } - serializeString(participantsNextOffset, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .groupCall(let call, let participants, let participantsNextOffset, let chats, let users): - return ("groupCall", [("call", call as Any), ("participants", participants as Any), ("participantsNextOffset", participantsNextOffset as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_groupCall(_ reader: BufferReader) -> GroupCall? { - var _1: Api.GroupCall? + + public static func parse_webPagePreview(_ reader: BufferReader) -> WebPagePreview? { + var _1: Api.MessageMedia? if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.GroupCall + _1 = Api.parse(reader, signature: signature) as? Api.MessageMedia } - var _2: [Api.GroupCallParticipant]? + var _2: [Api.Chat]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.GroupCallParticipant.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) } - var _3: String? - _3 = parseString(reader) - var _4: [Api.Chat]? + var _3: [Api.User]? if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _5: [Api.User]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.phone.GroupCall.groupCall(call: _1!, participants: _2!, participantsNextOffset: _3!, chats: _4!, users: _5!) + if _c1 && _c2 && _c3 { + return Api.messages.WebPagePreview.webPagePreview(Cons_webPagePreview(media: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } } - } } -public extension Api.phone { - enum GroupCallStars: TypeConstructorDescription { - case groupCallStars(totalStars: Int64, topDonors: [Api.GroupCallDonor], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .groupCallStars(let totalStars, let topDonors, let chats, let users): - if boxed { - buffer.appendInt32(-1658995418) - } - serializeInt64(totalStars, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(topDonors.count)) - for item in topDonors { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .groupCallStars(let totalStars, let topDonors, let chats, let users): - return ("groupCallStars", [("totalStars", totalStars as Any), ("topDonors", topDonors as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_groupCallStars(_ reader: BufferReader) -> GroupCallStars? { - var _1: Int64? - _1 = reader.readInt64() - var _2: [Api.GroupCallDonor]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.GroupCallDonor.self) +public extension Api.payments { + enum BankCardData: TypeConstructorDescription { + public class Cons_bankCardData { + public var title: String + public var openUrls: [Api.BankCardOpenUrl] + public init(title: String, openUrls: [Api.BankCardOpenUrl]) { + self.title = title + self.openUrls = openUrls } - var _3: [Api.Chat]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _4: [Api.User]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.phone.GroupCallStars.groupCallStars(totalStars: _1!, topDonors: _2!, chats: _3!, users: _4!) } - - } -} -public extension Api.phone { - enum GroupCallStreamChannels: TypeConstructorDescription { - case groupCallStreamChannels(channels: [Api.GroupCallStreamChannel]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .groupCallStreamChannels(let channels): - if boxed { - buffer.appendInt32(-790330702) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(channels.count)) - for item in channels { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .groupCallStreamChannels(let channels): - return ("groupCallStreamChannels", [("channels", channels as Any)]) - } - } - - public static func parse_groupCallStreamChannels(_ reader: BufferReader) -> GroupCallStreamChannels? { - var _1: [Api.GroupCallStreamChannel]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.GroupCallStreamChannel.self) + case bankCardData(Cons_bankCardData) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .bankCardData(let _data): + if boxed { + buffer.appendInt32(1042605427) + } + serializeString(_data.title, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.openUrls.count)) + for item in _data.openUrls { + item.serialize(buffer, true) + } + break } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.phone.GroupCallStreamChannels.groupCallStreamChannels(channels: _1!) } - - } -} -public extension Api.phone { - enum GroupCallStreamRtmpUrl: TypeConstructorDescription { - case groupCallStreamRtmpUrl(url: String, key: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .groupCallStreamRtmpUrl(let url, let key): - if boxed { - buffer.appendInt32(767505458) - } - serializeString(url, buffer: buffer, boxed: false) - serializeString(key, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .groupCallStreamRtmpUrl(let url, let key): - return ("groupCallStreamRtmpUrl", [("url", url as Any), ("key", key as Any)]) - } - } - - public static func parse_groupCallStreamRtmpUrl(_ reader: BufferReader) -> GroupCallStreamRtmpUrl? { + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .bankCardData(let _data): + return ("bankCardData", [("title", _data.title as Any), ("openUrls", _data.openUrls as Any)]) + } + } + + public static func parse_bankCardData(_ reader: BufferReader) -> BankCardData? { var _1: String? _1 = parseString(reader) - var _2: String? - _2 = parseString(reader) + var _2: [Api.BankCardOpenUrl]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.BankCardOpenUrl.self) + } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.phone.GroupCallStreamRtmpUrl.groupCallStreamRtmpUrl(url: _1!, key: _2!) + if _c1 && _c2 { + return Api.payments.BankCardData.bankCardData(Cons_bankCardData(title: _1!, openUrls: _2!)) + } + else { + return nil + } } - } } -public extension Api.phone { - enum GroupParticipants: TypeConstructorDescription { - case groupParticipants(count: Int32, participants: [Api.GroupCallParticipant], nextOffset: String, chats: [Api.Chat], users: [Api.User], version: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .groupParticipants(let count, let participants, let nextOffset, let chats, let users, let version): - if boxed { - buffer.appendInt32(-193506890) - } - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(participants.count)) - for item in participants { - item.serialize(buffer, true) - } - serializeString(nextOffset, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - serializeInt32(version, buffer: buffer, boxed: false) - break +public extension Api.payments { + enum CheckCanSendGiftResult: TypeConstructorDescription { + public class Cons_checkCanSendGiftResultFail { + public var reason: Api.TextWithEntities + public init(reason: Api.TextWithEntities) { + self.reason = reason + } + } + case checkCanSendGiftResultFail(Cons_checkCanSendGiftResultFail) + case checkCanSendGiftResultOk + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .checkCanSendGiftResultFail(let _data): + if boxed { + buffer.appendInt32(-706379148) + } + _data.reason.serialize(buffer, true) + break + case .checkCanSendGiftResultOk: + if boxed { + buffer.appendInt32(927967149) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .checkCanSendGiftResultFail(let _data): + return ("checkCanSendGiftResultFail", [("reason", _data.reason as Any)]) + case .checkCanSendGiftResultOk: + return ("checkCanSendGiftResultOk", []) + } + } + + public static func parse_checkCanSendGiftResultFail(_ reader: BufferReader) -> CheckCanSendGiftResult? { + var _1: Api.TextWithEntities? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.TextWithEntities + } + let _c1 = _1 != nil + if _c1 { + return Api.payments.CheckCanSendGiftResult.checkCanSendGiftResultFail(Cons_checkCanSendGiftResultFail(reason: _1!)) + } + else { + return nil + } + } + public static func parse_checkCanSendGiftResultOk(_ reader: BufferReader) -> CheckCanSendGiftResult? { + return Api.payments.CheckCanSendGiftResult.checkCanSendGiftResultOk + } } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .groupParticipants(let count, let participants, let nextOffset, let chats, let users, let version): - return ("groupParticipants", [("count", count as Any), ("participants", participants as Any), ("nextOffset", nextOffset as Any), ("chats", chats as Any), ("users", users as Any), ("version", version as Any)]) - } - } - - public static func parse_groupParticipants(_ reader: BufferReader) -> GroupParticipants? { +} +public extension Api.payments { + enum CheckedGiftCode: TypeConstructorDescription { + public class Cons_checkedGiftCode { + public var flags: Int32 + public var fromId: Api.Peer? + public var giveawayMsgId: Int32? + public var toId: Int64? + public var date: Int32 + public var days: Int32 + public var usedDate: Int32? + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, fromId: Api.Peer?, giveawayMsgId: Int32?, toId: Int64?, date: Int32, days: Int32, usedDate: Int32?, chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.fromId = fromId + self.giveawayMsgId = giveawayMsgId + self.toId = toId + self.date = date + self.days = days + self.usedDate = usedDate + self.chats = chats + self.users = users + } + } + case checkedGiftCode(Cons_checkedGiftCode) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .checkedGiftCode(let _data): + if boxed { + buffer.appendInt32(-342343793) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 4) != 0 { + _data.fromId!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.giveawayMsgId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.toId!, buffer: buffer, boxed: false) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt32(_data.days, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.usedDate!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .checkedGiftCode(let _data): + return ("checkedGiftCode", [("flags", _data.flags as Any), ("fromId", _data.fromId as Any), ("giveawayMsgId", _data.giveawayMsgId as Any), ("toId", _data.toId as Any), ("date", _data.date as Any), ("days", _data.days as Any), ("usedDate", _data.usedDate as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_checkedGiftCode(_ reader: BufferReader) -> CheckedGiftCode? { var _1: Int32? _1 = reader.readInt32() - var _2: [Api.GroupCallParticipant]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.GroupCallParticipant.self) + var _2: Api.Peer? + if Int(_1!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } } - var _3: String? - _3 = parseString(reader) - var _4: [Api.Chat]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + var _3: Int32? + if Int(_1!) & Int(1 << 3) != 0 { + _3 = reader.readInt32() } - var _5: [Api.User]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + var _4: Int64? + if Int(_1!) & Int(1 << 0) != 0 { + _4 = reader.readInt64() } + var _5: Int32? + _5 = reader.readInt32() var _6: Int32? _6 = reader.readInt32() + var _7: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _7 = reader.readInt32() + } + var _8: [Api.Chat]? + if let _ = reader.readInt32() { + _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _9: [Api.User]? + if let _ = reader.readInt32() { + _9 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 4) == 0) || _2 != nil + let _c3 = (Int(_1!) & Int(1 << 3) == 0) || _3 != nil + let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil + let _c8 = _8 != nil + let _c9 = _9 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.payments.CheckedGiftCode.checkedGiftCode(Cons_checkedGiftCode(flags: _1!, fromId: _2, giveawayMsgId: _3, toId: _4, date: _5!, days: _6!, usedDate: _7, chats: _8!, users: _9!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum ConnectedStarRefBots: TypeConstructorDescription { + public class Cons_connectedStarRefBots { + public var count: Int32 + public var connectedBots: [Api.ConnectedBotStarRef] + public var users: [Api.User] + public init(count: Int32, connectedBots: [Api.ConnectedBotStarRef], users: [Api.User]) { + self.count = count + self.connectedBots = connectedBots + self.users = users + } + } + case connectedStarRefBots(Cons_connectedStarRefBots) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .connectedStarRefBots(let _data): + if boxed { + buffer.appendInt32(-1730811363) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.connectedBots.count)) + for item in _data.connectedBots { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .connectedStarRefBots(let _data): + return ("connectedStarRefBots", [("count", _data.count as Any), ("connectedBots", _data.connectedBots as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_connectedStarRefBots(_ reader: BufferReader) -> ConnectedStarRefBots? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.ConnectedBotStarRef]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ConnectedBotStarRef.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.payments.ConnectedStarRefBots.connectedStarRefBots(Cons_connectedStarRefBots(count: _1!, connectedBots: _2!, users: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum ExportedInvoice: TypeConstructorDescription { + public class Cons_exportedInvoice { + public var url: String + public init(url: String) { + self.url = url + } + } + case exportedInvoice(Cons_exportedInvoice) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .exportedInvoice(let _data): + if boxed { + buffer.appendInt32(-1362048039) + } + serializeString(_data.url, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .exportedInvoice(let _data): + return ("exportedInvoice", [("url", _data.url as Any)]) + } + } + + public static func parse_exportedInvoice(_ reader: BufferReader) -> ExportedInvoice? { + var _1: String? + _1 = parseString(reader) + let _c1 = _1 != nil + if _c1 { + return Api.payments.ExportedInvoice.exportedInvoice(Cons_exportedInvoice(url: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum GiveawayInfo: TypeConstructorDescription { + public class Cons_giveawayInfo { + public var flags: Int32 + public var startDate: Int32 + public var joinedTooEarlyDate: Int32? + public var adminDisallowedChatId: Int64? + public var disallowedCountry: String? + public init(flags: Int32, startDate: Int32, joinedTooEarlyDate: Int32?, adminDisallowedChatId: Int64?, disallowedCountry: String?) { + self.flags = flags + self.startDate = startDate + self.joinedTooEarlyDate = joinedTooEarlyDate + self.adminDisallowedChatId = adminDisallowedChatId + self.disallowedCountry = disallowedCountry + } + } + public class Cons_giveawayInfoResults { + public var flags: Int32 + public var startDate: Int32 + public var giftCodeSlug: String? + public var starsPrize: Int64? + public var finishDate: Int32 + public var winnersCount: Int32 + public var activatedCount: Int32? + public init(flags: Int32, startDate: Int32, giftCodeSlug: String?, starsPrize: Int64?, finishDate: Int32, winnersCount: Int32, activatedCount: Int32?) { + self.flags = flags + self.startDate = startDate + self.giftCodeSlug = giftCodeSlug + self.starsPrize = starsPrize + self.finishDate = finishDate + self.winnersCount = winnersCount + self.activatedCount = activatedCount + } + } + case giveawayInfo(Cons_giveawayInfo) + case giveawayInfoResults(Cons_giveawayInfoResults) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .giveawayInfo(let _data): + if boxed { + buffer.appendInt32(1130879648) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.startDate, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.joinedTooEarlyDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt64(_data.adminDisallowedChatId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeString(_data.disallowedCountry!, buffer: buffer, boxed: false) + } + break + case .giveawayInfoResults(let _data): + if boxed { + buffer.appendInt32(-512366993) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.startDate, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.giftCodeSlug!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt64(_data.starsPrize!, buffer: buffer, boxed: false) + } + serializeInt32(_data.finishDate, buffer: buffer, boxed: false) + serializeInt32(_data.winnersCount, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.activatedCount!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .giveawayInfo(let _data): + return ("giveawayInfo", [("flags", _data.flags as Any), ("startDate", _data.startDate as Any), ("joinedTooEarlyDate", _data.joinedTooEarlyDate as Any), ("adminDisallowedChatId", _data.adminDisallowedChatId as Any), ("disallowedCountry", _data.disallowedCountry as Any)]) + case .giveawayInfoResults(let _data): + return ("giveawayInfoResults", [("flags", _data.flags as Any), ("startDate", _data.startDate as Any), ("giftCodeSlug", _data.giftCodeSlug as Any), ("starsPrize", _data.starsPrize as Any), ("finishDate", _data.finishDate as Any), ("winnersCount", _data.winnersCount as Any), ("activatedCount", _data.activatedCount as Any)]) + } + } + + public static func parse_giveawayInfo(_ reader: BufferReader) -> GiveawayInfo? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _3 = reader.readInt32() + } + var _4: Int64? + if Int(_1!) & Int(1 << 2) != 0 { + _4 = reader.readInt64() + } + var _5: String? + if Int(_1!) & Int(1 << 4) != 0 { + _5 = parseString(reader) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil + let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil + let _c5 = (Int(_1!) & Int(1 << 4) == 0) || _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.payments.GiveawayInfo.giveawayInfo(Cons_giveawayInfo(flags: _1!, startDate: _2!, joinedTooEarlyDate: _3, adminDisallowedChatId: _4, disallowedCountry: _5)) + } + else { + return nil + } + } + public static func parse_giveawayInfoResults(_ reader: BufferReader) -> GiveawayInfo? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: String? + if Int(_1!) & Int(1 << 3) != 0 { + _3 = parseString(reader) + } + var _4: Int64? + if Int(_1!) & Int(1 << 4) != 0 { + _4 = reader.readInt64() + } + var _5: Int32? + _5 = reader.readInt32() + var _6: Int32? + _6 = reader.readInt32() + var _7: Int32? + if Int(_1!) & Int(1 << 2) != 0 { + _7 = reader.readInt32() + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 3) == 0) || _3 != nil + let _c4 = (Int(_1!) & Int(1 << 4) == 0) || _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + let _c7 = (Int(_1!) & Int(1 << 2) == 0) || _7 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.payments.GiveawayInfo.giveawayInfoResults(Cons_giveawayInfoResults(flags: _1!, startDate: _2!, giftCodeSlug: _3, starsPrize: _4, finishDate: _5!, winnersCount: _6!, activatedCount: _7)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum PaymentForm: TypeConstructorDescription { + public class Cons_paymentForm { + public var flags: Int32 + public var formId: Int64 + public var botId: Int64 + public var title: String + public var description: String + public var photo: Api.WebDocument? + public var invoice: Api.Invoice + public var providerId: Int64 + public var url: String + public var nativeProvider: String? + public var nativeParams: Api.DataJSON? + public var additionalMethods: [Api.PaymentFormMethod]? + public var savedInfo: Api.PaymentRequestedInfo? + public var savedCredentials: [Api.PaymentSavedCredentials]? + public var users: [Api.User] + public init(flags: Int32, formId: Int64, botId: Int64, title: String, description: String, photo: Api.WebDocument?, invoice: Api.Invoice, providerId: Int64, url: String, nativeProvider: String?, nativeParams: Api.DataJSON?, additionalMethods: [Api.PaymentFormMethod]?, savedInfo: Api.PaymentRequestedInfo?, savedCredentials: [Api.PaymentSavedCredentials]?, users: [Api.User]) { + self.flags = flags + self.formId = formId + self.botId = botId + self.title = title + self.description = description + self.photo = photo + self.invoice = invoice + self.providerId = providerId + self.url = url + self.nativeProvider = nativeProvider + self.nativeParams = nativeParams + self.additionalMethods = additionalMethods + self.savedInfo = savedInfo + self.savedCredentials = savedCredentials + self.users = users + } + } + public class Cons_paymentFormStarGift { + public var formId: Int64 + public var invoice: Api.Invoice + public init(formId: Int64, invoice: Api.Invoice) { + self.formId = formId + self.invoice = invoice + } + } + public class Cons_paymentFormStars { + public var flags: Int32 + public var formId: Int64 + public var botId: Int64 + public var title: String + public var description: String + public var photo: Api.WebDocument? + public var invoice: Api.Invoice + public var users: [Api.User] + public init(flags: Int32, formId: Int64, botId: Int64, title: String, description: String, photo: Api.WebDocument?, invoice: Api.Invoice, users: [Api.User]) { + self.flags = flags + self.formId = formId + self.botId = botId + self.title = title + self.description = description + self.photo = photo + self.invoice = invoice + self.users = users + } + } + case paymentForm(Cons_paymentForm) + case paymentFormStarGift(Cons_paymentFormStarGift) + case paymentFormStars(Cons_paymentFormStars) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .paymentForm(let _data): + if boxed { + buffer.appendInt32(-1610250415) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.formId, buffer: buffer, boxed: false) + serializeInt64(_data.botId, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.description, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 5) != 0 { + _data.photo!.serialize(buffer, true) + } + _data.invoice.serialize(buffer, true) + serializeInt64(_data.providerId, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeString(_data.nativeProvider!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + _data.nativeParams!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.additionalMethods!.count)) + for item in _data.additionalMethods! { + item.serialize(buffer, true) + } + } + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.savedInfo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.savedCredentials!.count)) + for item in _data.savedCredentials! { + item.serialize(buffer, true) + } + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .paymentFormStarGift(let _data): + if boxed { + buffer.appendInt32(-1272590367) + } + serializeInt64(_data.formId, buffer: buffer, boxed: false) + _data.invoice.serialize(buffer, true) + break + case .paymentFormStars(let _data): + if boxed { + buffer.appendInt32(2079764828) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.formId, buffer: buffer, boxed: false) + serializeInt64(_data.botId, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.description, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 5) != 0 { + _data.photo!.serialize(buffer, true) + } + _data.invoice.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .paymentForm(let _data): + return ("paymentForm", [("flags", _data.flags as Any), ("formId", _data.formId as Any), ("botId", _data.botId as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("photo", _data.photo as Any), ("invoice", _data.invoice as Any), ("providerId", _data.providerId as Any), ("url", _data.url as Any), ("nativeProvider", _data.nativeProvider as Any), ("nativeParams", _data.nativeParams as Any), ("additionalMethods", _data.additionalMethods as Any), ("savedInfo", _data.savedInfo as Any), ("savedCredentials", _data.savedCredentials as Any), ("users", _data.users as Any)]) + case .paymentFormStarGift(let _data): + return ("paymentFormStarGift", [("formId", _data.formId as Any), ("invoice", _data.invoice as Any)]) + case .paymentFormStars(let _data): + return ("paymentFormStars", [("flags", _data.flags as Any), ("formId", _data.formId as Any), ("botId", _data.botId as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("photo", _data.photo as Any), ("invoice", _data.invoice as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_paymentForm(_ reader: BufferReader) -> PaymentForm? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: Int64? + _3 = reader.readInt64() + var _4: String? + _4 = parseString(reader) + var _5: String? + _5 = parseString(reader) + var _6: Api.WebDocument? + if Int(_1!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.WebDocument + } + } + var _7: Api.Invoice? + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.Invoice + } + var _8: Int64? + _8 = reader.readInt64() + var _9: String? + _9 = parseString(reader) + var _10: String? + if Int(_1!) & Int(1 << 4) != 0 { + _10 = parseString(reader) + } + var _11: Api.DataJSON? + if Int(_1!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _11 = Api.parse(reader, signature: signature) as? Api.DataJSON + } + } + var _12: [Api.PaymentFormMethod]? + if Int(_1!) & Int(1 << 6) != 0 { + if let _ = reader.readInt32() { + _12 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PaymentFormMethod.self) + } + } + var _13: Api.PaymentRequestedInfo? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _13 = Api.parse(reader, signature: signature) as? Api.PaymentRequestedInfo + } + } + var _14: [Api.PaymentSavedCredentials]? + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _14 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PaymentSavedCredentials.self) + } + } + var _15: [Api.User]? + if let _ = reader.readInt32() { + _15 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.phone.GroupParticipants.groupParticipants(count: _1!, participants: _2!, nextOffset: _3!, chats: _4!, users: _5!, version: _6!) + let _c6 = (Int(_1!) & Int(1 << 5) == 0) || _6 != nil + let _c7 = _7 != nil + let _c8 = _8 != nil + let _c9 = _9 != nil + let _c10 = (Int(_1!) & Int(1 << 4) == 0) || _10 != nil + let _c11 = (Int(_1!) & Int(1 << 4) == 0) || _11 != nil + let _c12 = (Int(_1!) & Int(1 << 6) == 0) || _12 != nil + let _c13 = (Int(_1!) & Int(1 << 0) == 0) || _13 != nil + let _c14 = (Int(_1!) & Int(1 << 1) == 0) || _14 != nil + let _c15 = _15 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 { + return Api.payments.PaymentForm.paymentForm(Cons_paymentForm(flags: _1!, formId: _2!, botId: _3!, title: _4!, description: _5!, photo: _6, invoice: _7!, providerId: _8!, url: _9!, nativeProvider: _10, nativeParams: _11, additionalMethods: _12, savedInfo: _13, savedCredentials: _14, users: _15!)) + } + else { + return nil + } + } + public static func parse_paymentFormStarGift(_ reader: BufferReader) -> PaymentForm? { + var _1: Int64? + _1 = reader.readInt64() + var _2: Api.Invoice? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Invoice + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.payments.PaymentForm.paymentFormStarGift(Cons_paymentFormStarGift(formId: _1!, invoice: _2!)) + } + else { + return nil + } + } + public static func parse_paymentFormStars(_ reader: BufferReader) -> PaymentForm? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int64? + _2 = reader.readInt64() + var _3: Int64? + _3 = reader.readInt64() + var _4: String? + _4 = parseString(reader) + var _5: String? + _5 = parseString(reader) + var _6: Api.WebDocument? + if Int(_1!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.WebDocument + } + } + var _7: Api.Invoice? + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.Invoice + } + var _8: [Api.User]? + if let _ = reader.readInt32() { + _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = (Int(_1!) & Int(1 << 5) == 0) || _6 != nil + let _c7 = _7 != nil + let _c8 = _8 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.payments.PaymentForm.paymentFormStars(Cons_paymentFormStars(flags: _1!, formId: _2!, botId: _3!, title: _4!, description: _5!, photo: _6, invoice: _7!, users: _8!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api37.swift b/submodules/TelegramApi/Sources/Api37.swift index c9b4cfd1..083891d2 100644 --- a/submodules/TelegramApi/Sources/Api37.swift +++ b/submodules/TelegramApi/Sources/Api37.swift @@ -1,43 +1,1586 @@ -public extension Api.phone { - enum JoinAsPeers: TypeConstructorDescription { - case joinAsPeers(peers: [Api.Peer], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .joinAsPeers(let peers, let chats, let users): - if boxed { - buffer.appendInt32(-1343921601) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peers.count)) - for item in peers { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .joinAsPeers(let peers, let chats, let users): - return ("joinAsPeers", [("peers", peers as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_joinAsPeers(_ reader: BufferReader) -> JoinAsPeers? { - var _1: [Api.Peer]? +public extension Api.payments { + enum PaymentReceipt: TypeConstructorDescription { + public class Cons_paymentReceipt { + public var flags: Int32 + public var date: Int32 + public var botId: Int64 + public var providerId: Int64 + public var title: String + public var description: String + public var photo: Api.WebDocument? + public var invoice: Api.Invoice + public var info: Api.PaymentRequestedInfo? + public var shipping: Api.ShippingOption? + public var tipAmount: Int64? + public var currency: String + public var totalAmount: Int64 + public var credentialsTitle: String + public var users: [Api.User] + public init(flags: Int32, date: Int32, botId: Int64, providerId: Int64, title: String, description: String, photo: Api.WebDocument?, invoice: Api.Invoice, info: Api.PaymentRequestedInfo?, shipping: Api.ShippingOption?, tipAmount: Int64?, currency: String, totalAmount: Int64, credentialsTitle: String, users: [Api.User]) { + self.flags = flags + self.date = date + self.botId = botId + self.providerId = providerId + self.title = title + self.description = description + self.photo = photo + self.invoice = invoice + self.info = info + self.shipping = shipping + self.tipAmount = tipAmount + self.currency = currency + self.totalAmount = totalAmount + self.credentialsTitle = credentialsTitle + self.users = users + } + } + public class Cons_paymentReceiptStars { + public var flags: Int32 + public var date: Int32 + public var botId: Int64 + public var title: String + public var description: String + public var photo: Api.WebDocument? + public var invoice: Api.Invoice + public var currency: String + public var totalAmount: Int64 + public var transactionId: String + public var users: [Api.User] + public init(flags: Int32, date: Int32, botId: Int64, title: String, description: String, photo: Api.WebDocument?, invoice: Api.Invoice, currency: String, totalAmount: Int64, transactionId: String, users: [Api.User]) { + self.flags = flags + self.date = date + self.botId = botId + self.title = title + self.description = description + self.photo = photo + self.invoice = invoice + self.currency = currency + self.totalAmount = totalAmount + self.transactionId = transactionId + self.users = users + } + } + case paymentReceipt(Cons_paymentReceipt) + case paymentReceiptStars(Cons_paymentReceiptStars) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .paymentReceipt(let _data): + if boxed { + buffer.appendInt32(1891958275) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.botId, buffer: buffer, boxed: false) + serializeInt64(_data.providerId, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.description, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.photo!.serialize(buffer, true) + } + _data.invoice.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.info!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.shipping!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt64(_data.tipAmount!, buffer: buffer, boxed: false) + } + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.totalAmount, buffer: buffer, boxed: false) + serializeString(_data.credentialsTitle, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .paymentReceiptStars(let _data): + if boxed { + buffer.appendInt32(-625215430) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.botId, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.description, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.photo!.serialize(buffer, true) + } + _data.invoice.serialize(buffer, true) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.totalAmount, buffer: buffer, boxed: false) + serializeString(_data.transactionId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .paymentReceipt(let _data): + return ("paymentReceipt", [("flags", _data.flags as Any), ("date", _data.date as Any), ("botId", _data.botId as Any), ("providerId", _data.providerId as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("photo", _data.photo as Any), ("invoice", _data.invoice as Any), ("info", _data.info as Any), ("shipping", _data.shipping as Any), ("tipAmount", _data.tipAmount as Any), ("currency", _data.currency as Any), ("totalAmount", _data.totalAmount as Any), ("credentialsTitle", _data.credentialsTitle as Any), ("users", _data.users as Any)]) + case .paymentReceiptStars(let _data): + return ("paymentReceiptStars", [("flags", _data.flags as Any), ("date", _data.date as Any), ("botId", _data.botId as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("photo", _data.photo as Any), ("invoice", _data.invoice as Any), ("currency", _data.currency as Any), ("totalAmount", _data.totalAmount as Any), ("transactionId", _data.transactionId as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_paymentReceipt(_ reader: BufferReader) -> PaymentReceipt? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int64? + _3 = reader.readInt64() + var _4: Int64? + _4 = reader.readInt64() + var _5: String? + _5 = parseString(reader) + var _6: String? + _6 = parseString(reader) + var _7: Api.WebDocument? + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.WebDocument + } + } + var _8: Api.Invoice? + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.Invoice + } + var _9: Api.PaymentRequestedInfo? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.PaymentRequestedInfo + } + } + var _10: Api.ShippingOption? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _10 = Api.parse(reader, signature: signature) as? Api.ShippingOption + } + } + var _11: Int64? + if Int(_1!) & Int(1 << 3) != 0 { + _11 = reader.readInt64() + } + var _12: String? + _12 = parseString(reader) + var _13: Int64? + _13 = reader.readInt64() + var _14: String? + _14 = parseString(reader) + var _15: [Api.User]? if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) + _15 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + let _c7 = (Int(_1!) & Int(1 << 2) == 0) || _7 != nil + let _c8 = _8 != nil + let _c9 = (Int(_1!) & Int(1 << 0) == 0) || _9 != nil + let _c10 = (Int(_1!) & Int(1 << 1) == 0) || _10 != nil + let _c11 = (Int(_1!) & Int(1 << 3) == 0) || _11 != nil + let _c12 = _12 != nil + let _c13 = _13 != nil + let _c14 = _14 != nil + let _c15 = _15 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 { + return Api.payments.PaymentReceipt.paymentReceipt(Cons_paymentReceipt(flags: _1!, date: _2!, botId: _3!, providerId: _4!, title: _5!, description: _6!, photo: _7, invoice: _8!, info: _9, shipping: _10, tipAmount: _11, currency: _12!, totalAmount: _13!, credentialsTitle: _14!, users: _15!)) + } + else { + return nil + } + } + public static func parse_paymentReceiptStars(_ reader: BufferReader) -> PaymentReceipt? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int64? + _3 = reader.readInt64() + var _4: String? + _4 = parseString(reader) + var _5: String? + _5 = parseString(reader) + var _6: Api.WebDocument? + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.WebDocument + } + } + var _7: Api.Invoice? + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.Invoice + } + var _8: String? + _8 = parseString(reader) + var _9: Int64? + _9 = reader.readInt64() + var _10: String? + _10 = parseString(reader) + var _11: [Api.User]? + if let _ = reader.readInt32() { + _11 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil + let _c7 = _7 != nil + let _c8 = _8 != nil + let _c9 = _9 != nil + let _c10 = _10 != nil + let _c11 = _11 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 { + return Api.payments.PaymentReceipt.paymentReceiptStars(Cons_paymentReceiptStars(flags: _1!, date: _2!, botId: _3!, title: _4!, description: _5!, photo: _6, invoice: _7!, currency: _8!, totalAmount: _9!, transactionId: _10!, users: _11!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + indirect enum PaymentResult: TypeConstructorDescription { + public class Cons_paymentResult { + public var updates: Api.Updates + public init(updates: Api.Updates) { + self.updates = updates + } + } + public class Cons_paymentVerificationNeeded { + public var url: String + public init(url: String) { + self.url = url + } + } + case paymentResult(Cons_paymentResult) + case paymentVerificationNeeded(Cons_paymentVerificationNeeded) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .paymentResult(let _data): + if boxed { + buffer.appendInt32(1314881805) + } + _data.updates.serialize(buffer, true) + break + case .paymentVerificationNeeded(let _data): + if boxed { + buffer.appendInt32(-666824391) + } + serializeString(_data.url, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .paymentResult(let _data): + return ("paymentResult", [("updates", _data.updates as Any)]) + case .paymentVerificationNeeded(let _data): + return ("paymentVerificationNeeded", [("url", _data.url as Any)]) + } + } + + public static func parse_paymentResult(_ reader: BufferReader) -> PaymentResult? { + var _1: Api.Updates? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Updates + } + let _c1 = _1 != nil + if _c1 { + return Api.payments.PaymentResult.paymentResult(Cons_paymentResult(updates: _1!)) + } + else { + return nil + } + } + public static func parse_paymentVerificationNeeded(_ reader: BufferReader) -> PaymentResult? { + var _1: String? + _1 = parseString(reader) + let _c1 = _1 != nil + if _c1 { + return Api.payments.PaymentResult.paymentVerificationNeeded(Cons_paymentVerificationNeeded(url: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum ResaleStarGifts: TypeConstructorDescription { + public class Cons_resaleStarGifts { + public var flags: Int32 + public var count: Int32 + public var gifts: [Api.StarGift] + public var nextOffset: String? + public var attributes: [Api.StarGiftAttribute]? + public var attributesHash: Int64? + public var chats: [Api.Chat] + public var counters: [Api.StarGiftAttributeCounter]? + public var users: [Api.User] + public init(flags: Int32, count: Int32, gifts: [Api.StarGift], nextOffset: String?, attributes: [Api.StarGiftAttribute]?, attributesHash: Int64?, chats: [Api.Chat], counters: [Api.StarGiftAttributeCounter]?, users: [Api.User]) { + self.flags = flags + self.count = count + self.gifts = gifts + self.nextOffset = nextOffset + self.attributes = attributes + self.attributesHash = attributesHash + self.chats = chats + self.counters = counters + self.users = users + } + } + case resaleStarGifts(Cons_resaleStarGifts) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .resaleStarGifts(let _data): + if boxed { + buffer.appendInt32(-1803939105) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.gifts.count)) + for item in _data.gifts { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.nextOffset!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.attributes!.count)) + for item in _data.attributes! { + item.serialize(buffer, true) + } + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt64(_data.attributesHash!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.counters!.count)) + for item in _data.counters! { + item.serialize(buffer, true) + } + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .resaleStarGifts(let _data): + return ("resaleStarGifts", [("flags", _data.flags as Any), ("count", _data.count as Any), ("gifts", _data.gifts as Any), ("nextOffset", _data.nextOffset as Any), ("attributes", _data.attributes as Any), ("attributesHash", _data.attributesHash as Any), ("chats", _data.chats as Any), ("counters", _data.counters as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_resaleStarGifts(_ reader: BufferReader) -> ResaleStarGifts? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: [Api.StarGift]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGift.self) + } + var _4: String? + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) + } + var _5: [Api.StarGiftAttribute]? + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftAttribute.self) + } + } + var _6: Int64? + if Int(_1!) & Int(1 << 1) != 0 { + _6 = reader.readInt64() + } + var _7: [Api.Chat]? + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _8: [Api.StarGiftAttributeCounter]? + if Int(_1!) & Int(1 << 2) != 0 { + if let _ = reader.readInt32() { + _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftAttributeCounter.self) + } + } + var _9: [Api.User]? + if let _ = reader.readInt32() { + _9 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil + let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil + let _c6 = (Int(_1!) & Int(1 << 1) == 0) || _6 != nil + let _c7 = _7 != nil + let _c8 = (Int(_1!) & Int(1 << 2) == 0) || _8 != nil + let _c9 = _9 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.payments.ResaleStarGifts.resaleStarGifts(Cons_resaleStarGifts(flags: _1!, count: _2!, gifts: _3!, nextOffset: _4, attributes: _5, attributesHash: _6, chats: _7!, counters: _8, users: _9!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum SavedInfo: TypeConstructorDescription { + public class Cons_savedInfo { + public var flags: Int32 + public var savedInfo: Api.PaymentRequestedInfo? + public init(flags: Int32, savedInfo: Api.PaymentRequestedInfo?) { + self.flags = flags + self.savedInfo = savedInfo + } + } + case savedInfo(Cons_savedInfo) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .savedInfo(let _data): + if boxed { + buffer.appendInt32(-74456004) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.savedInfo!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .savedInfo(let _data): + return ("savedInfo", [("flags", _data.flags as Any), ("savedInfo", _data.savedInfo as Any)]) + } + } + + public static func parse_savedInfo(_ reader: BufferReader) -> SavedInfo? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.PaymentRequestedInfo? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.PaymentRequestedInfo + } + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + if _c1 && _c2 { + return Api.payments.SavedInfo.savedInfo(Cons_savedInfo(flags: _1!, savedInfo: _2)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum SavedStarGifts: TypeConstructorDescription { + public class Cons_savedStarGifts { + public var flags: Int32 + public var count: Int32 + public var chatNotificationsEnabled: Api.Bool? + public var gifts: [Api.SavedStarGift] + public var nextOffset: String? + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, count: Int32, chatNotificationsEnabled: Api.Bool?, gifts: [Api.SavedStarGift], nextOffset: String?, chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.count = count + self.chatNotificationsEnabled = chatNotificationsEnabled + self.gifts = gifts + self.nextOffset = nextOffset + self.chats = chats + self.users = users + } + } + case savedStarGifts(Cons_savedStarGifts) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .savedStarGifts(let _data): + if boxed { + buffer.appendInt32(-1779201615) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.chatNotificationsEnabled!.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.gifts.count)) + for item in _data.gifts { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.nextOffset!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .savedStarGifts(let _data): + return ("savedStarGifts", [("flags", _data.flags as Any), ("count", _data.count as Any), ("chatNotificationsEnabled", _data.chatNotificationsEnabled as Any), ("gifts", _data.gifts as Any), ("nextOffset", _data.nextOffset as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_savedStarGifts(_ reader: BufferReader) -> SavedStarGifts? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Api.Bool? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Bool + } + } + var _4: [Api.SavedStarGift]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.SavedStarGift.self) + } + var _5: String? + if Int(_1!) & Int(1 << 0) != 0 { + _5 = parseString(reader) + } + var _6: [Api.Chat]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _7: [Api.User]? + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil + let _c4 = _4 != nil + let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil + let _c6 = _6 != nil + let _c7 = _7 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.payments.SavedStarGifts.savedStarGifts(Cons_savedStarGifts(flags: _1!, count: _2!, chatNotificationsEnabled: _3, gifts: _4!, nextOffset: _5, chats: _6!, users: _7!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum StarGiftActiveAuctions: TypeConstructorDescription { + public class Cons_starGiftActiveAuctions { + public var auctions: [Api.StarGiftActiveAuctionState] + public var users: [Api.User] + public var chats: [Api.Chat] + public init(auctions: [Api.StarGiftActiveAuctionState], users: [Api.User], chats: [Api.Chat]) { + self.auctions = auctions + self.users = users + self.chats = chats + } + } + case starGiftActiveAuctions(Cons_starGiftActiveAuctions) + case starGiftActiveAuctionsNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftActiveAuctions(let _data): + if boxed { + buffer.appendInt32(-1359565892) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.auctions.count)) + for item in _data.auctions { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + break + case .starGiftActiveAuctionsNotModified: + if boxed { + buffer.appendInt32(-617358640) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftActiveAuctions(let _data): + return ("starGiftActiveAuctions", [("auctions", _data.auctions as Any), ("users", _data.users as Any), ("chats", _data.chats as Any)]) + case .starGiftActiveAuctionsNotModified: + return ("starGiftActiveAuctionsNotModified", []) + } + } + + public static func parse_starGiftActiveAuctions(_ reader: BufferReader) -> StarGiftActiveAuctions? { + var _1: [Api.StarGiftActiveAuctionState]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftActiveAuctionState.self) + } + var _2: [Api.User]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + var _3: [Api.Chat]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.payments.StarGiftActiveAuctions.starGiftActiveAuctions(Cons_starGiftActiveAuctions(auctions: _1!, users: _2!, chats: _3!)) + } + else { + return nil + } + } + public static func parse_starGiftActiveAuctionsNotModified(_ reader: BufferReader) -> StarGiftActiveAuctions? { + return Api.payments.StarGiftActiveAuctions.starGiftActiveAuctionsNotModified + } + } +} +public extension Api.payments { + enum StarGiftAuctionAcquiredGifts: TypeConstructorDescription { + public class Cons_starGiftAuctionAcquiredGifts { + public var gifts: [Api.StarGiftAuctionAcquiredGift] + public var users: [Api.User] + public var chats: [Api.Chat] + public init(gifts: [Api.StarGiftAuctionAcquiredGift], users: [Api.User], chats: [Api.Chat]) { + self.gifts = gifts + self.users = users + self.chats = chats + } + } + case starGiftAuctionAcquiredGifts(Cons_starGiftAuctionAcquiredGifts) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftAuctionAcquiredGifts(let _data): + if boxed { + buffer.appendInt32(2103169520) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.gifts.count)) + for item in _data.gifts { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftAuctionAcquiredGifts(let _data): + return ("starGiftAuctionAcquiredGifts", [("gifts", _data.gifts as Any), ("users", _data.users as Any), ("chats", _data.chats as Any)]) + } + } + + public static func parse_starGiftAuctionAcquiredGifts(_ reader: BufferReader) -> StarGiftAuctionAcquiredGifts? { + var _1: [Api.StarGiftAuctionAcquiredGift]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftAuctionAcquiredGift.self) + } + var _2: [Api.User]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + var _3: [Api.Chat]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.payments.StarGiftAuctionAcquiredGifts.starGiftAuctionAcquiredGifts(Cons_starGiftAuctionAcquiredGifts(gifts: _1!, users: _2!, chats: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum StarGiftAuctionState: TypeConstructorDescription { + public class Cons_starGiftAuctionState { + public var gift: Api.StarGift + public var state: Api.StarGiftAuctionState + public var userState: Api.StarGiftAuctionUserState + public var timeout: Int32 + public var users: [Api.User] + public var chats: [Api.Chat] + public init(gift: Api.StarGift, state: Api.StarGiftAuctionState, userState: Api.StarGiftAuctionUserState, timeout: Int32, users: [Api.User], chats: [Api.Chat]) { + self.gift = gift + self.state = state + self.userState = userState + self.timeout = timeout + self.users = users + self.chats = chats + } + } + case starGiftAuctionState(Cons_starGiftAuctionState) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftAuctionState(let _data): + if boxed { + buffer.appendInt32(1798960364) + } + _data.gift.serialize(buffer, true) + _data.state.serialize(buffer, true) + _data.userState.serialize(buffer, true) + serializeInt32(_data.timeout, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftAuctionState(let _data): + return ("starGiftAuctionState", [("gift", _data.gift as Any), ("state", _data.state as Any), ("userState", _data.userState as Any), ("timeout", _data.timeout as Any), ("users", _data.users as Any), ("chats", _data.chats as Any)]) + } + } + + public static func parse_starGiftAuctionState(_ reader: BufferReader) -> StarGiftAuctionState? { + var _1: Api.StarGift? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.StarGift + } + var _2: Api.StarGiftAuctionState? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.StarGiftAuctionState + } + var _3: Api.StarGiftAuctionUserState? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.StarGiftAuctionUserState + } + var _4: Int32? + _4 = reader.readInt32() + var _5: [Api.User]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + var _6: [Api.Chat]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.payments.StarGiftAuctionState.starGiftAuctionState(Cons_starGiftAuctionState(gift: _1!, state: _2!, userState: _3!, timeout: _4!, users: _5!, chats: _6!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum StarGiftCollections: TypeConstructorDescription { + public class Cons_starGiftCollections { + public var collections: [Api.StarGiftCollection] + public init(collections: [Api.StarGiftCollection]) { + self.collections = collections + } + } + case starGiftCollections(Cons_starGiftCollections) + case starGiftCollectionsNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftCollections(let _data): + if boxed { + buffer.appendInt32(-1977011469) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.collections.count)) + for item in _data.collections { + item.serialize(buffer, true) + } + break + case .starGiftCollectionsNotModified: + if boxed { + buffer.appendInt32(-1598402793) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftCollections(let _data): + return ("starGiftCollections", [("collections", _data.collections as Any)]) + case .starGiftCollectionsNotModified: + return ("starGiftCollectionsNotModified", []) + } + } + + public static func parse_starGiftCollections(_ reader: BufferReader) -> StarGiftCollections? { + var _1: [Api.StarGiftCollection]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftCollection.self) + } + let _c1 = _1 != nil + if _c1 { + return Api.payments.StarGiftCollections.starGiftCollections(Cons_starGiftCollections(collections: _1!)) + } + else { + return nil + } + } + public static func parse_starGiftCollectionsNotModified(_ reader: BufferReader) -> StarGiftCollections? { + return Api.payments.StarGiftCollections.starGiftCollectionsNotModified + } + } +} +public extension Api.payments { + enum StarGiftUpgradeAttributes: TypeConstructorDescription { + public class Cons_starGiftUpgradeAttributes { + public var attributes: [Api.StarGiftAttribute] + public init(attributes: [Api.StarGiftAttribute]) { + self.attributes = attributes + } + } + case starGiftUpgradeAttributes(Cons_starGiftUpgradeAttributes) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftUpgradeAttributes(let _data): + if boxed { + buffer.appendInt32(1187439471) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.attributes.count)) + for item in _data.attributes { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftUpgradeAttributes(let _data): + return ("starGiftUpgradeAttributes", [("attributes", _data.attributes as Any)]) + } + } + + public static func parse_starGiftUpgradeAttributes(_ reader: BufferReader) -> StarGiftUpgradeAttributes? { + var _1: [Api.StarGiftAttribute]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftAttribute.self) + } + let _c1 = _1 != nil + if _c1 { + return Api.payments.StarGiftUpgradeAttributes.starGiftUpgradeAttributes(Cons_starGiftUpgradeAttributes(attributes: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum StarGiftUpgradePreview: TypeConstructorDescription { + public class Cons_starGiftUpgradePreview { + public var sampleAttributes: [Api.StarGiftAttribute] + public var prices: [Api.StarGiftUpgradePrice] + public var nextPrices: [Api.StarGiftUpgradePrice] + public init(sampleAttributes: [Api.StarGiftAttribute], prices: [Api.StarGiftUpgradePrice], nextPrices: [Api.StarGiftUpgradePrice]) { + self.sampleAttributes = sampleAttributes + self.prices = prices + self.nextPrices = nextPrices + } + } + case starGiftUpgradePreview(Cons_starGiftUpgradePreview) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftUpgradePreview(let _data): + if boxed { + buffer.appendInt32(1038213101) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.sampleAttributes.count)) + for item in _data.sampleAttributes { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.prices.count)) + for item in _data.prices { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.nextPrices.count)) + for item in _data.nextPrices { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftUpgradePreview(let _data): + return ("starGiftUpgradePreview", [("sampleAttributes", _data.sampleAttributes as Any), ("prices", _data.prices as Any), ("nextPrices", _data.nextPrices as Any)]) + } + } + + public static func parse_starGiftUpgradePreview(_ reader: BufferReader) -> StarGiftUpgradePreview? { + var _1: [Api.StarGiftAttribute]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftAttribute.self) + } + var _2: [Api.StarGiftUpgradePrice]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftUpgradePrice.self) + } + var _3: [Api.StarGiftUpgradePrice]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGiftUpgradePrice.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.payments.StarGiftUpgradePreview.starGiftUpgradePreview(Cons_starGiftUpgradePreview(sampleAttributes: _1!, prices: _2!, nextPrices: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum StarGiftWithdrawalUrl: TypeConstructorDescription { + public class Cons_starGiftWithdrawalUrl { + public var url: String + public init(url: String) { + self.url = url + } + } + case starGiftWithdrawalUrl(Cons_starGiftWithdrawalUrl) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGiftWithdrawalUrl(let _data): + if boxed { + buffer.appendInt32(-2069218660) + } + serializeString(_data.url, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGiftWithdrawalUrl(let _data): + return ("starGiftWithdrawalUrl", [("url", _data.url as Any)]) + } + } + + public static func parse_starGiftWithdrawalUrl(_ reader: BufferReader) -> StarGiftWithdrawalUrl? { + var _1: String? + _1 = parseString(reader) + let _c1 = _1 != nil + if _c1 { + return Api.payments.StarGiftWithdrawalUrl.starGiftWithdrawalUrl(Cons_starGiftWithdrawalUrl(url: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum StarGifts: TypeConstructorDescription { + public class Cons_starGifts { + public var hash: Int32 + public var gifts: [Api.StarGift] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(hash: Int32, gifts: [Api.StarGift], chats: [Api.Chat], users: [Api.User]) { + self.hash = hash + self.gifts = gifts + self.chats = chats + self.users = users + } + } + case starGifts(Cons_starGifts) + case starGiftsNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starGifts(let _data): + if boxed { + buffer.appendInt32(785918357) + } + serializeInt32(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.gifts.count)) + for item in _data.gifts { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .starGiftsNotModified: + if boxed { + buffer.appendInt32(-1551326360) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starGifts(let _data): + return ("starGifts", [("hash", _data.hash as Any), ("gifts", _data.gifts as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + case .starGiftsNotModified: + return ("starGiftsNotModified", []) + } + } + + public static func parse_starGifts(_ reader: BufferReader) -> StarGifts? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.StarGift]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarGift.self) + } + var _3: [Api.Chat]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _4: [Api.User]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.payments.StarGifts.starGifts(Cons_starGifts(hash: _1!, gifts: _2!, chats: _3!, users: _4!)) + } + else { + return nil + } + } + public static func parse_starGiftsNotModified(_ reader: BufferReader) -> StarGifts? { + return Api.payments.StarGifts.starGiftsNotModified + } + } +} +public extension Api.payments { + enum StarsRevenueAdsAccountUrl: TypeConstructorDescription { + public class Cons_starsRevenueAdsAccountUrl { + public var url: String + public init(url: String) { + self.url = url + } + } + case starsRevenueAdsAccountUrl(Cons_starsRevenueAdsAccountUrl) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starsRevenueAdsAccountUrl(let _data): + if boxed { + buffer.appendInt32(961445665) + } + serializeString(_data.url, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starsRevenueAdsAccountUrl(let _data): + return ("starsRevenueAdsAccountUrl", [("url", _data.url as Any)]) + } + } + + public static func parse_starsRevenueAdsAccountUrl(_ reader: BufferReader) -> StarsRevenueAdsAccountUrl? { + var _1: String? + _1 = parseString(reader) + let _c1 = _1 != nil + if _c1 { + return Api.payments.StarsRevenueAdsAccountUrl.starsRevenueAdsAccountUrl(Cons_starsRevenueAdsAccountUrl(url: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum StarsRevenueStats: TypeConstructorDescription { + public class Cons_starsRevenueStats { + public var flags: Int32 + public var topHoursGraph: Api.StatsGraph? + public var revenueGraph: Api.StatsGraph + public var status: Api.StarsRevenueStatus + public var usdRate: Double + public init(flags: Int32, topHoursGraph: Api.StatsGraph?, revenueGraph: Api.StatsGraph, status: Api.StarsRevenueStatus, usdRate: Double) { + self.flags = flags + self.topHoursGraph = topHoursGraph + self.revenueGraph = revenueGraph + self.status = status + self.usdRate = usdRate + } + } + case starsRevenueStats(Cons_starsRevenueStats) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starsRevenueStats(let _data): + if boxed { + buffer.appendInt32(1814066038) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.topHoursGraph!.serialize(buffer, true) + } + _data.revenueGraph.serialize(buffer, true) + _data.status.serialize(buffer, true) + serializeDouble(_data.usdRate, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starsRevenueStats(let _data): + return ("starsRevenueStats", [("flags", _data.flags as Any), ("topHoursGraph", _data.topHoursGraph as Any), ("revenueGraph", _data.revenueGraph as Any), ("status", _data.status as Any), ("usdRate", _data.usdRate as Any)]) + } + } + + public static func parse_starsRevenueStats(_ reader: BufferReader) -> StarsRevenueStats? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.StatsGraph? + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + } + var _3: Api.StatsGraph? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _4: Api.StarsRevenueStatus? + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.StarsRevenueStatus + } + var _5: Double? + _5 = reader.readDouble() + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.payments.StarsRevenueStats.starsRevenueStats(Cons_starsRevenueStats(flags: _1!, topHoursGraph: _2, revenueGraph: _3!, status: _4!, usdRate: _5!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum StarsRevenueWithdrawalUrl: TypeConstructorDescription { + public class Cons_starsRevenueWithdrawalUrl { + public var url: String + public init(url: String) { + self.url = url + } + } + case starsRevenueWithdrawalUrl(Cons_starsRevenueWithdrawalUrl) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starsRevenueWithdrawalUrl(let _data): + if boxed { + buffer.appendInt32(497778871) + } + serializeString(_data.url, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starsRevenueWithdrawalUrl(let _data): + return ("starsRevenueWithdrawalUrl", [("url", _data.url as Any)]) + } + } + + public static func parse_starsRevenueWithdrawalUrl(_ reader: BufferReader) -> StarsRevenueWithdrawalUrl? { + var _1: String? + _1 = parseString(reader) + let _c1 = _1 != nil + if _c1 { + return Api.payments.StarsRevenueWithdrawalUrl.starsRevenueWithdrawalUrl(Cons_starsRevenueWithdrawalUrl(url: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum StarsStatus: TypeConstructorDescription { + public class Cons_starsStatus { + public var flags: Int32 + public var balance: Api.StarsAmount + public var subscriptions: [Api.StarsSubscription]? + public var subscriptionsNextOffset: String? + public var subscriptionsMissingBalance: Int64? + public var history: [Api.StarsTransaction]? + public var nextOffset: String? + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, balance: Api.StarsAmount, subscriptions: [Api.StarsSubscription]?, subscriptionsNextOffset: String?, subscriptionsMissingBalance: Int64?, history: [Api.StarsTransaction]?, nextOffset: String?, chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.balance = balance + self.subscriptions = subscriptions + self.subscriptionsNextOffset = subscriptionsNextOffset + self.subscriptionsMissingBalance = subscriptionsMissingBalance + self.history = history + self.nextOffset = nextOffset + self.chats = chats + self.users = users + } + } + case starsStatus(Cons_starsStatus) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .starsStatus(let _data): + if boxed { + buffer.appendInt32(1822222573) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.balance.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.subscriptions!.count)) + for item in _data.subscriptions! { + item.serialize(buffer, true) + } + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.subscriptionsNextOffset!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt64(_data.subscriptionsMissingBalance!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.history!.count)) + for item in _data.history! { + item.serialize(buffer, true) + } + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.nextOffset!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .starsStatus(let _data): + return ("starsStatus", [("flags", _data.flags as Any), ("balance", _data.balance as Any), ("subscriptions", _data.subscriptions as Any), ("subscriptionsNextOffset", _data.subscriptionsNextOffset as Any), ("subscriptionsMissingBalance", _data.subscriptionsMissingBalance as Any), ("history", _data.history as Any), ("nextOffset", _data.nextOffset as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_starsStatus(_ reader: BufferReader) -> StarsStatus? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Api.StarsAmount? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.StarsAmount + } + var _3: [Api.StarsSubscription]? + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarsSubscription.self) + } + } + var _4: String? + if Int(_1!) & Int(1 << 2) != 0 { + _4 = parseString(reader) + } + var _5: Int64? + if Int(_1!) & Int(1 << 4) != 0 { + _5 = reader.readInt64() + } + var _6: [Api.StarsTransaction]? + if Int(_1!) & Int(1 << 3) != 0 { + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarsTransaction.self) + } + } + var _7: String? + if Int(_1!) & Int(1 << 0) != 0 { + _7 = parseString(reader) + } + var _8: [Api.Chat]? + if let _ = reader.readInt32() { + _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _9: [Api.User]? + if let _ = reader.readInt32() { + _9 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil + let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil + let _c5 = (Int(_1!) & Int(1 << 4) == 0) || _5 != nil + let _c6 = (Int(_1!) & Int(1 << 3) == 0) || _6 != nil + let _c7 = (Int(_1!) & Int(1 << 0) == 0) || _7 != nil + let _c8 = _8 != nil + let _c9 = _9 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.payments.StarsStatus.starsStatus(Cons_starsStatus(flags: _1!, balance: _2!, subscriptions: _3, subscriptionsNextOffset: _4, subscriptionsMissingBalance: _5, history: _6, nextOffset: _7, chats: _8!, users: _9!)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum SuggestedStarRefBots: TypeConstructorDescription { + public class Cons_suggestedStarRefBots { + public var flags: Int32 + public var count: Int32 + public var suggestedBots: [Api.StarRefProgram] + public var users: [Api.User] + public var nextOffset: String? + public init(flags: Int32, count: Int32, suggestedBots: [Api.StarRefProgram], users: [Api.User], nextOffset: String?) { + self.flags = flags + self.count = count + self.suggestedBots = suggestedBots + self.users = users + self.nextOffset = nextOffset + } + } + case suggestedStarRefBots(Cons_suggestedStarRefBots) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .suggestedStarRefBots(let _data): + if boxed { + buffer.appendInt32(-1261053863) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.suggestedBots.count)) + for item in _data.suggestedBots { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.nextOffset!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .suggestedStarRefBots(let _data): + return ("suggestedStarRefBots", [("flags", _data.flags as Any), ("count", _data.count as Any), ("suggestedBots", _data.suggestedBots as Any), ("users", _data.users as Any), ("nextOffset", _data.nextOffset as Any)]) + } + } + + public static func parse_suggestedStarRefBots(_ reader: BufferReader) -> SuggestedStarRefBots? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: [Api.StarRefProgram]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarRefProgram.self) + } + var _4: [Api.User]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + var _5: String? + if Int(_1!) & Int(1 << 0) != 0 { + _5 = parseString(reader) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.payments.SuggestedStarRefBots.suggestedStarRefBots(Cons_suggestedStarRefBots(flags: _1!, count: _2!, suggestedBots: _3!, users: _4!, nextOffset: _5)) + } + else { + return nil + } + } + } +} +public extension Api.payments { + enum UniqueStarGift: TypeConstructorDescription { + public class Cons_uniqueStarGift { + public var gift: Api.StarGift + public var chats: [Api.Chat] + public var users: [Api.User] + public init(gift: Api.StarGift, chats: [Api.Chat], users: [Api.User]) { + self.gift = gift + self.chats = chats + self.users = users + } + } + case uniqueStarGift(Cons_uniqueStarGift) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .uniqueStarGift(let _data): + if boxed { + buffer.appendInt32(1097619176) + } + _data.gift.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .uniqueStarGift(let _data): + return ("uniqueStarGift", [("gift", _data.gift as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_uniqueStarGift(_ reader: BufferReader) -> UniqueStarGift? { + var _1: Api.StarGift? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.StarGift } var _2: [Api.Chat]? if let _ = reader.readInt32() { @@ -50,236 +1593,331 @@ public extension Api.phone { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.phone.JoinAsPeers.joinAsPeers(peers: _1!, chats: _2!, users: _3!) + if _c1 && _c2 && _c3 { + return Api.payments.UniqueStarGift.uniqueStarGift(Cons_uniqueStarGift(gift: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } } - } } -public extension Api.phone { - enum PhoneCall: TypeConstructorDescription { - case phoneCall(phoneCall: Api.PhoneCall, users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .phoneCall(let phoneCall, let users): - if boxed { - buffer.appendInt32(-326966976) - } - phoneCall.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .phoneCall(let phoneCall, let users): - return ("phoneCall", [("phoneCall", phoneCall as Any), ("users", users as Any)]) - } - } - - public static func parse_phoneCall(_ reader: BufferReader) -> PhoneCall? { - var _1: Api.PhoneCall? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.PhoneCall +public extension Api.payments { + enum UniqueStarGiftValueInfo: TypeConstructorDescription { + public class Cons_uniqueStarGiftValueInfo { + public var flags: Int32 + public var currency: String + public var value: Int64 + public var initialSaleDate: Int32 + public var initialSaleStars: Int64 + public var initialSalePrice: Int64 + public var lastSaleDate: Int32? + public var lastSalePrice: Int64? + public var floorPrice: Int64? + public var averagePrice: Int64? + public var listedCount: Int32? + public var fragmentListedCount: Int32? + public var fragmentListedUrl: String? + public init(flags: Int32, currency: String, value: Int64, initialSaleDate: Int32, initialSaleStars: Int64, initialSalePrice: Int64, lastSaleDate: Int32?, lastSalePrice: Int64?, floorPrice: Int64?, averagePrice: Int64?, listedCount: Int32?, fragmentListedCount: Int32?, fragmentListedUrl: String?) { + self.flags = flags + self.currency = currency + self.value = value + self.initialSaleDate = initialSaleDate + self.initialSaleStars = initialSaleStars + self.initialSalePrice = initialSalePrice + self.lastSaleDate = lastSaleDate + self.lastSalePrice = lastSalePrice + self.floorPrice = floorPrice + self.averagePrice = averagePrice + self.listedCount = listedCount + self.fragmentListedCount = fragmentListedCount + self.fragmentListedUrl = fragmentListedUrl } - var _2: [Api.User]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.phone.PhoneCall.phoneCall(phoneCall: _1!, users: _2!) } - - } -} -public extension Api.photos { - enum Photo: TypeConstructorDescription { - case photo(photo: Api.Photo, users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .photo(let photo, let users): - if boxed { - buffer.appendInt32(539045032) - } - photo.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .photo(let photo, let users): - return ("photo", [("photo", photo as Any), ("users", users as Any)]) - } - } - - public static func parse_photo(_ reader: BufferReader) -> Photo? { - var _1: Api.Photo? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.Photo + case uniqueStarGiftValueInfo(Cons_uniqueStarGiftValueInfo) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .uniqueStarGiftValueInfo(let _data): + if boxed { + buffer.appendInt32(1362093126) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.currency, buffer: buffer, boxed: false) + serializeInt64(_data.value, buffer: buffer, boxed: false) + serializeInt32(_data.initialSaleDate, buffer: buffer, boxed: false) + serializeInt64(_data.initialSaleStars, buffer: buffer, boxed: false) + serializeInt64(_data.initialSalePrice, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.lastSaleDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.lastSalePrice!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt64(_data.floorPrice!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt64(_data.averagePrice!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.listedCount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeInt32(_data.fragmentListedCount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeString(_data.fragmentListedUrl!, buffer: buffer, boxed: false) + } + break } - var _2: [Api.User]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.photos.Photo.photo(photo: _1!, users: _2!) } - - } -} -public extension Api.photos { - enum Photos: TypeConstructorDescription { - case photos(photos: [Api.Photo], users: [Api.User]) - case photosSlice(count: Int32, photos: [Api.Photo], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .photos(let photos, let users): - if boxed { - buffer.appendInt32(-1916114267) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(photos.count)) - for item in photos { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .photosSlice(let count, let photos, let users): - if boxed { - buffer.appendInt32(352657236) - } - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(photos.count)) - for item in photos { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .photos(let photos, let users): - return ("photos", [("photos", photos as Any), ("users", users as Any)]) - case .photosSlice(let count, let photos, let users): - return ("photosSlice", [("count", count as Any), ("photos", photos as Any), ("users", users as Any)]) - } - } - - public static func parse_photos(_ reader: BufferReader) -> Photos? { - var _1: [Api.Photo]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Photo.self) + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .uniqueStarGiftValueInfo(let _data): + return ("uniqueStarGiftValueInfo", [("flags", _data.flags as Any), ("currency", _data.currency as Any), ("value", _data.value as Any), ("initialSaleDate", _data.initialSaleDate as Any), ("initialSaleStars", _data.initialSaleStars as Any), ("initialSalePrice", _data.initialSalePrice as Any), ("lastSaleDate", _data.lastSaleDate as Any), ("lastSalePrice", _data.lastSalePrice as Any), ("floorPrice", _data.floorPrice as Any), ("averagePrice", _data.averagePrice as Any), ("listedCount", _data.listedCount as Any), ("fragmentListedCount", _data.fragmentListedCount as Any), ("fragmentListedUrl", _data.fragmentListedUrl as Any)]) } - var _2: [Api.User]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.photos.Photos.photos(photos: _1!, users: _2!) } - public static func parse_photosSlice(_ reader: BufferReader) -> Photos? { + + public static func parse_uniqueStarGiftValueInfo(_ reader: BufferReader) -> UniqueStarGiftValueInfo? { var _1: Int32? _1 = reader.readInt32() - var _2: [Api.Photo]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Photo.self) + var _2: String? + _2 = parseString(reader) + var _3: Int64? + _3 = reader.readInt64() + var _4: Int32? + _4 = reader.readInt32() + var _5: Int64? + _5 = reader.readInt64() + var _6: Int64? + _6 = reader.readInt64() + var _7: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _7 = reader.readInt32() } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + var _8: Int64? + if Int(_1!) & Int(1 << 0) != 0 { + _8 = reader.readInt64() + } + var _9: Int64? + if Int(_1!) & Int(1 << 2) != 0 { + _9 = reader.readInt64() + } + var _10: Int64? + if Int(_1!) & Int(1 << 3) != 0 { + _10 = reader.readInt64() + } + var _11: Int32? + if Int(_1!) & Int(1 << 4) != 0 { + _11 = reader.readInt32() + } + var _12: Int32? + if Int(_1!) & Int(1 << 5) != 0 { + _12 = reader.readInt32() + } + var _13: String? + if Int(_1!) & Int(1 << 5) != 0 { + _13 = parseString(reader) } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.photos.Photos.photosSlice(count: _1!, photos: _2!, users: _3!) + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + let _c7 = (Int(_1!) & Int(1 << 0) == 0) || _7 != nil + let _c8 = (Int(_1!) & Int(1 << 0) == 0) || _8 != nil + let _c9 = (Int(_1!) & Int(1 << 2) == 0) || _9 != nil + let _c10 = (Int(_1!) & Int(1 << 3) == 0) || _10 != nil + let _c11 = (Int(_1!) & Int(1 << 4) == 0) || _11 != nil + let _c12 = (Int(_1!) & Int(1 << 5) == 0) || _12 != nil + let _c13 = (Int(_1!) & Int(1 << 5) == 0) || _13 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 { + return Api.payments.UniqueStarGiftValueInfo.uniqueStarGiftValueInfo(Cons_uniqueStarGiftValueInfo(flags: _1!, currency: _2!, value: _3!, initialSaleDate: _4!, initialSaleStars: _5!, initialSalePrice: _6!, lastSaleDate: _7, lastSalePrice: _8, floorPrice: _9, averagePrice: _10, listedCount: _11, fragmentListedCount: _12, fragmentListedUrl: _13)) + } + else { + return nil + } } - } } -public extension Api.premium { - enum BoostsList: TypeConstructorDescription { - case boostsList(flags: Int32, count: Int32, boosts: [Api.Boost], nextOffset: String?, users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .boostsList(let flags, let count, let boosts, let nextOffset, let users): - if boxed { - buffer.appendInt32(-2030542532) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) +public extension Api.payments { + enum ValidatedRequestedInfo: TypeConstructorDescription { + public class Cons_validatedRequestedInfo { + public var flags: Int32 + public var id: String? + public var shippingOptions: [Api.ShippingOption]? + public init(flags: Int32, id: String?, shippingOptions: [Api.ShippingOption]?) { + self.flags = flags + self.id = id + self.shippingOptions = shippingOptions + } + } + case validatedRequestedInfo(Cons_validatedRequestedInfo) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .validatedRequestedInfo(let _data): + if boxed { + buffer.appendInt32(-784000893) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.id!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(boosts.count)) - for item in boosts { + buffer.appendInt32(Int32(_data.shippingOptions!.count)) + for item in _data.shippingOptions! { item.serialize(buffer, true) } - if Int(flags) & Int(1 << 0) != 0 {serializeString(nextOffset!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .boostsList(let flags, let count, let boosts, let nextOffset, let users): - return ("boostsList", [("flags", flags as Any), ("count", count as Any), ("boosts", boosts as Any), ("nextOffset", nextOffset as Any), ("users", users as Any)]) - } - } - - public static func parse_boostsList(_ reader: BufferReader) -> BoostsList? { + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .validatedRequestedInfo(let _data): + return ("validatedRequestedInfo", [("flags", _data.flags as Any), ("id", _data.id as Any), ("shippingOptions", _data.shippingOptions as Any)]) + } + } + + public static func parse_validatedRequestedInfo(_ reader: BufferReader) -> ValidatedRequestedInfo? { var _1: Int32? _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: [Api.Boost]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Boost.self) + var _2: String? + if Int(_1!) & Int(1 << 0) != 0 { + _2 = parseString(reader) + } + var _3: [Api.ShippingOption]? + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.ShippingOption.self) + } + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil + let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil + if _c1 && _c2 && _c3 { + return Api.payments.ValidatedRequestedInfo.validatedRequestedInfo(Cons_validatedRequestedInfo(flags: _1!, id: _2, shippingOptions: _3)) + } + else { + return nil + } + } + } +} +public extension Api.phone { + enum ExportedGroupCallInvite: TypeConstructorDescription { + public class Cons_exportedGroupCallInvite { + public var link: String + public init(link: String) { + self.link = link + } + } + case exportedGroupCallInvite(Cons_exportedGroupCallInvite) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .exportedGroupCallInvite(let _data): + if boxed { + buffer.appendInt32(541839704) + } + serializeString(_data.link, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .exportedGroupCallInvite(let _data): + return ("exportedGroupCallInvite", [("link", _data.link as Any)]) + } + } + + public static func parse_exportedGroupCallInvite(_ reader: BufferReader) -> ExportedGroupCallInvite? { + var _1: String? + _1 = parseString(reader) + let _c1 = _1 != nil + if _c1 { + return Api.phone.ExportedGroupCallInvite.exportedGroupCallInvite(Cons_exportedGroupCallInvite(link: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.phone { + enum GroupCall: TypeConstructorDescription { + public class Cons_groupCall { + public var call: Api.GroupCall + public var participants: [Api.GroupCallParticipant] + public var participantsNextOffset: String + public var chats: [Api.Chat] + public var users: [Api.User] + public init(call: Api.GroupCall, participants: [Api.GroupCallParticipant], participantsNextOffset: String, chats: [Api.Chat], users: [Api.User]) { + self.call = call + self.participants = participants + self.participantsNextOffset = participantsNextOffset + self.chats = chats + self.users = users + } + } + case groupCall(Cons_groupCall) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .groupCall(let _data): + if boxed { + buffer.appendInt32(-1636664659) + } + _data.call.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.participants.count)) + for item in _data.participants { + item.serialize(buffer, true) + } + serializeString(_data.participantsNextOffset, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .groupCall(let _data): + return ("groupCall", [("call", _data.call as Any), ("participants", _data.participants as Any), ("participantsNextOffset", _data.participantsNextOffset as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_groupCall(_ reader: BufferReader) -> GroupCall? { + var _1: Api.GroupCall? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.GroupCall + } + var _2: [Api.GroupCallParticipant]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.GroupCallParticipant.self) + } + var _3: String? + _3 = parseString(reader) + var _4: [Api.Chat]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) } - var _4: String? - if Int(_1!) & Int(1 << 0) != 0 {_4 = parseString(reader) } var _5: [Api.User]? if let _ = reader.readInt32() { _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) @@ -287,1214 +1925,274 @@ public extension Api.premium { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.premium.BoostsList.boostsList(flags: _1!, count: _2!, boosts: _3!, nextOffset: _4, users: _5!) - } - - } -} -public extension Api.premium { - enum BoostsStatus: TypeConstructorDescription { - case boostsStatus(flags: Int32, level: Int32, currentLevelBoosts: Int32, boosts: Int32, giftBoosts: Int32?, nextLevelBoosts: Int32?, premiumAudience: Api.StatsPercentValue?, boostUrl: String, prepaidGiveaways: [Api.PrepaidGiveaway]?, myBoostSlots: [Int32]?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .boostsStatus(let flags, let level, let currentLevelBoosts, let boosts, let giftBoosts, let nextLevelBoosts, let premiumAudience, let boostUrl, let prepaidGiveaways, let myBoostSlots): - if boxed { - buffer.appendInt32(1230586490) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(level, buffer: buffer, boxed: false) - serializeInt32(currentLevelBoosts, buffer: buffer, boxed: false) - serializeInt32(boosts, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(giftBoosts!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(nextLevelBoosts!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {premiumAudience!.serialize(buffer, true)} - serializeString(boostUrl, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(prepaidGiveaways!.count)) - for item in prepaidGiveaways! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 2) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(myBoostSlots!.count)) - for item in myBoostSlots! { - serializeInt32(item, buffer: buffer, boxed: false) - }} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .boostsStatus(let flags, let level, let currentLevelBoosts, let boosts, let giftBoosts, let nextLevelBoosts, let premiumAudience, let boostUrl, let prepaidGiveaways, let myBoostSlots): - return ("boostsStatus", [("flags", flags as Any), ("level", level as Any), ("currentLevelBoosts", currentLevelBoosts as Any), ("boosts", boosts as Any), ("giftBoosts", giftBoosts as Any), ("nextLevelBoosts", nextLevelBoosts as Any), ("premiumAudience", premiumAudience as Any), ("boostUrl", boostUrl as Any), ("prepaidGiveaways", prepaidGiveaways as Any), ("myBoostSlots", myBoostSlots as Any)]) - } - } - - public static func parse_boostsStatus(_ reader: BufferReader) -> BoostsStatus? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - var _4: Int32? - _4 = reader.readInt32() - var _5: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_5 = reader.readInt32() } - var _6: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_6 = reader.readInt32() } - var _7: Api.StatsPercentValue? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.StatsPercentValue - } } - var _8: String? - _8 = parseString(reader) - var _9: [Api.PrepaidGiveaway]? - if Int(_1!) & Int(1 << 3) != 0 {if let _ = reader.readInt32() { - _9 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PrepaidGiveaway.self) - } } - var _10: [Int32]? - if Int(_1!) & Int(1 << 2) != 0 {if let _ = reader.readInt32() { - _10 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = (Int(_1!) & Int(1 << 4) == 0) || _5 != nil - let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil - let _c8 = _8 != nil - let _c9 = (Int(_1!) & Int(1 << 3) == 0) || _9 != nil - let _c10 = (Int(_1!) & Int(1 << 2) == 0) || _10 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - return Api.premium.BoostsStatus.boostsStatus(flags: _1!, level: _2!, currentLevelBoosts: _3!, boosts: _4!, giftBoosts: _5, nextLevelBoosts: _6, premiumAudience: _7, boostUrl: _8!, prepaidGiveaways: _9, myBoostSlots: _10) - } - - } -} -public extension Api.premium { - enum MyBoosts: TypeConstructorDescription { - case myBoosts(myBoosts: [Api.MyBoost], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .myBoosts(let myBoosts, let chats, let users): - if boxed { - buffer.appendInt32(-1696454430) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(myBoosts.count)) - for item in myBoosts { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .myBoosts(let myBoosts, let chats, let users): - return ("myBoosts", [("myBoosts", myBoosts as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_myBoosts(_ reader: BufferReader) -> MyBoosts? { - var _1: [Api.MyBoost]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MyBoost.self) - } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.premium.MyBoosts.myBoosts(myBoosts: _1!, chats: _2!, users: _3!) - } - - } -} -public extension Api.smsjobs { - enum EligibilityToJoin: TypeConstructorDescription { - case eligibleToJoin(termsUrl: String, monthlySentSms: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .eligibleToJoin(let termsUrl, let monthlySentSms): - if boxed { - buffer.appendInt32(-594852657) - } - serializeString(termsUrl, buffer: buffer, boxed: false) - serializeInt32(monthlySentSms, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .eligibleToJoin(let termsUrl, let monthlySentSms): - return ("eligibleToJoin", [("termsUrl", termsUrl as Any), ("monthlySentSms", monthlySentSms as Any)]) - } - } - - public static func parse_eligibleToJoin(_ reader: BufferReader) -> EligibilityToJoin? { - var _1: String? - _1 = parseString(reader) - var _2: Int32? - _2 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.smsjobs.EligibilityToJoin.eligibleToJoin(termsUrl: _1!, monthlySentSms: _2!) - } - - } -} -public extension Api.smsjobs { - enum Status: TypeConstructorDescription { - case status(flags: Int32, recentSent: Int32, recentSince: Int32, recentRemains: Int32, totalSent: Int32, totalSince: Int32, lastGiftSlug: String?, termsUrl: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .status(let flags, let recentSent, let recentSince, let recentRemains, let totalSent, let totalSince, let lastGiftSlug, let termsUrl): - if boxed { - buffer.appendInt32(720277905) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(recentSent, buffer: buffer, boxed: false) - serializeInt32(recentSince, buffer: buffer, boxed: false) - serializeInt32(recentRemains, buffer: buffer, boxed: false) - serializeInt32(totalSent, buffer: buffer, boxed: false) - serializeInt32(totalSince, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeString(lastGiftSlug!, buffer: buffer, boxed: false)} - serializeString(termsUrl, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .status(let flags, let recentSent, let recentSince, let recentRemains, let totalSent, let totalSince, let lastGiftSlug, let termsUrl): - return ("status", [("flags", flags as Any), ("recentSent", recentSent as Any), ("recentSince", recentSince as Any), ("recentRemains", recentRemains as Any), ("totalSent", totalSent as Any), ("totalSince", totalSince as Any), ("lastGiftSlug", lastGiftSlug as Any), ("termsUrl", termsUrl as Any)]) - } - } - - public static func parse_status(_ reader: BufferReader) -> Status? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - var _4: Int32? - _4 = reader.readInt32() - var _5: Int32? - _5 = reader.readInt32() - var _6: Int32? - _6 = reader.readInt32() - var _7: String? - if Int(_1!) & Int(1 << 1) != 0 {_7 = parseString(reader) } - var _8: String? - _8 = parseString(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - let _c6 = _6 != nil - let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil - let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.smsjobs.Status.status(flags: _1!, recentSent: _2!, recentSince: _3!, recentRemains: _4!, totalSent: _5!, totalSince: _6!, lastGiftSlug: _7, termsUrl: _8!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.phone.GroupCall.groupCall(Cons_groupCall(call: _1!, participants: _2!, participantsNextOffset: _3!, chats: _4!, users: _5!)) + } + else { + return nil + } } - } } -public extension Api.stats { - enum BroadcastStats: TypeConstructorDescription { - case broadcastStats(period: Api.StatsDateRangeDays, followers: Api.StatsAbsValueAndPrev, viewsPerPost: Api.StatsAbsValueAndPrev, sharesPerPost: Api.StatsAbsValueAndPrev, reactionsPerPost: Api.StatsAbsValueAndPrev, viewsPerStory: Api.StatsAbsValueAndPrev, sharesPerStory: Api.StatsAbsValueAndPrev, reactionsPerStory: Api.StatsAbsValueAndPrev, enabledNotifications: Api.StatsPercentValue, growthGraph: Api.StatsGraph, followersGraph: Api.StatsGraph, muteGraph: Api.StatsGraph, topHoursGraph: Api.StatsGraph, interactionsGraph: Api.StatsGraph, ivInteractionsGraph: Api.StatsGraph, viewsBySourceGraph: Api.StatsGraph, newFollowersBySourceGraph: Api.StatsGraph, languagesGraph: Api.StatsGraph, reactionsByEmotionGraph: Api.StatsGraph, storyInteractionsGraph: Api.StatsGraph, storyReactionsByEmotionGraph: Api.StatsGraph, recentPostsInteractions: [Api.PostInteractionCounters]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .broadcastStats(let period, let followers, let viewsPerPost, let sharesPerPost, let reactionsPerPost, let viewsPerStory, let sharesPerStory, let reactionsPerStory, let enabledNotifications, let growthGraph, let followersGraph, let muteGraph, let topHoursGraph, let interactionsGraph, let ivInteractionsGraph, let viewsBySourceGraph, let newFollowersBySourceGraph, let languagesGraph, let reactionsByEmotionGraph, let storyInteractionsGraph, let storyReactionsByEmotionGraph, let recentPostsInteractions): - if boxed { - buffer.appendInt32(963421692) - } - period.serialize(buffer, true) - followers.serialize(buffer, true) - viewsPerPost.serialize(buffer, true) - sharesPerPost.serialize(buffer, true) - reactionsPerPost.serialize(buffer, true) - viewsPerStory.serialize(buffer, true) - sharesPerStory.serialize(buffer, true) - reactionsPerStory.serialize(buffer, true) - enabledNotifications.serialize(buffer, true) - growthGraph.serialize(buffer, true) - followersGraph.serialize(buffer, true) - muteGraph.serialize(buffer, true) - topHoursGraph.serialize(buffer, true) - interactionsGraph.serialize(buffer, true) - ivInteractionsGraph.serialize(buffer, true) - viewsBySourceGraph.serialize(buffer, true) - newFollowersBySourceGraph.serialize(buffer, true) - languagesGraph.serialize(buffer, true) - reactionsByEmotionGraph.serialize(buffer, true) - storyInteractionsGraph.serialize(buffer, true) - storyReactionsByEmotionGraph.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(recentPostsInteractions.count)) - for item in recentPostsInteractions { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .broadcastStats(let period, let followers, let viewsPerPost, let sharesPerPost, let reactionsPerPost, let viewsPerStory, let sharesPerStory, let reactionsPerStory, let enabledNotifications, let growthGraph, let followersGraph, let muteGraph, let topHoursGraph, let interactionsGraph, let ivInteractionsGraph, let viewsBySourceGraph, let newFollowersBySourceGraph, let languagesGraph, let reactionsByEmotionGraph, let storyInteractionsGraph, let storyReactionsByEmotionGraph, let recentPostsInteractions): - return ("broadcastStats", [("period", period as Any), ("followers", followers as Any), ("viewsPerPost", viewsPerPost as Any), ("sharesPerPost", sharesPerPost as Any), ("reactionsPerPost", reactionsPerPost as Any), ("viewsPerStory", viewsPerStory as Any), ("sharesPerStory", sharesPerStory as Any), ("reactionsPerStory", reactionsPerStory as Any), ("enabledNotifications", enabledNotifications as Any), ("growthGraph", growthGraph as Any), ("followersGraph", followersGraph as Any), ("muteGraph", muteGraph as Any), ("topHoursGraph", topHoursGraph as Any), ("interactionsGraph", interactionsGraph as Any), ("ivInteractionsGraph", ivInteractionsGraph as Any), ("viewsBySourceGraph", viewsBySourceGraph as Any), ("newFollowersBySourceGraph", newFollowersBySourceGraph as Any), ("languagesGraph", languagesGraph as Any), ("reactionsByEmotionGraph", reactionsByEmotionGraph as Any), ("storyInteractionsGraph", storyInteractionsGraph as Any), ("storyReactionsByEmotionGraph", storyReactionsByEmotionGraph as Any), ("recentPostsInteractions", recentPostsInteractions as Any)]) - } - } - - public static func parse_broadcastStats(_ reader: BufferReader) -> BroadcastStats? { - var _1: Api.StatsDateRangeDays? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.StatsDateRangeDays +public extension Api.phone { + enum GroupCallStars: TypeConstructorDescription { + public class Cons_groupCallStars { + public var totalStars: Int64 + public var topDonors: [Api.GroupCallDonor] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(totalStars: Int64, topDonors: [Api.GroupCallDonor], chats: [Api.Chat], users: [Api.User]) { + self.totalStars = totalStars + self.topDonors = topDonors + self.chats = chats + self.users = users } - var _2: Api.StatsAbsValueAndPrev? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev - } - var _3: Api.StatsAbsValueAndPrev? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev - } - var _4: Api.StatsAbsValueAndPrev? - if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev - } - var _5: Api.StatsAbsValueAndPrev? - if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev - } - var _6: Api.StatsAbsValueAndPrev? - if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev - } - var _7: Api.StatsAbsValueAndPrev? - if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev - } - var _8: Api.StatsAbsValueAndPrev? - if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev - } - var _9: Api.StatsPercentValue? - if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.StatsPercentValue - } - var _10: Api.StatsGraph? - if let signature = reader.readInt32() { - _10 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _11: Api.StatsGraph? - if let signature = reader.readInt32() { - _11 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _12: Api.StatsGraph? - if let signature = reader.readInt32() { - _12 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _13: Api.StatsGraph? - if let signature = reader.readInt32() { - _13 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _14: Api.StatsGraph? - if let signature = reader.readInt32() { - _14 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _15: Api.StatsGraph? - if let signature = reader.readInt32() { - _15 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _16: Api.StatsGraph? - if let signature = reader.readInt32() { - _16 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _17: Api.StatsGraph? - if let signature = reader.readInt32() { - _17 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _18: Api.StatsGraph? - if let signature = reader.readInt32() { - _18 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _19: Api.StatsGraph? - if let signature = reader.readInt32() { - _19 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _20: Api.StatsGraph? - if let signature = reader.readInt32() { - _20 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _21: Api.StatsGraph? - if let signature = reader.readInt32() { - _21 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _22: [Api.PostInteractionCounters]? - if let _ = reader.readInt32() { - _22 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PostInteractionCounters.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - let _c7 = _7 != nil - let _c8 = _8 != nil - let _c9 = _9 != nil - let _c10 = _10 != nil - let _c11 = _11 != nil - let _c12 = _12 != nil - let _c13 = _13 != nil - let _c14 = _14 != nil - let _c15 = _15 != nil - let _c16 = _16 != nil - let _c17 = _17 != nil - let _c18 = _18 != nil - let _c19 = _19 != nil - let _c20 = _20 != nil - let _c21 = _21 != nil - let _c22 = _22 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - if !_c16 { return nil } - if !_c17 { return nil } - if !_c18 { return nil } - if !_c19 { return nil } - if !_c20 { return nil } - if !_c21 { return nil } - if !_c22 { return nil } - return Api.stats.BroadcastStats.broadcastStats(period: _1!, followers: _2!, viewsPerPost: _3!, sharesPerPost: _4!, reactionsPerPost: _5!, viewsPerStory: _6!, sharesPerStory: _7!, reactionsPerStory: _8!, enabledNotifications: _9!, growthGraph: _10!, followersGraph: _11!, muteGraph: _12!, topHoursGraph: _13!, interactionsGraph: _14!, ivInteractionsGraph: _15!, viewsBySourceGraph: _16!, newFollowersBySourceGraph: _17!, languagesGraph: _18!, reactionsByEmotionGraph: _19!, storyInteractionsGraph: _20!, storyReactionsByEmotionGraph: _21!, recentPostsInteractions: _22!) } - - } -} -public extension Api.stats { - enum MegagroupStats: TypeConstructorDescription { - case megagroupStats(period: Api.StatsDateRangeDays, members: Api.StatsAbsValueAndPrev, messages: Api.StatsAbsValueAndPrev, viewers: Api.StatsAbsValueAndPrev, posters: Api.StatsAbsValueAndPrev, growthGraph: Api.StatsGraph, membersGraph: Api.StatsGraph, newMembersBySourceGraph: Api.StatsGraph, languagesGraph: Api.StatsGraph, messagesGraph: Api.StatsGraph, actionsGraph: Api.StatsGraph, topHoursGraph: Api.StatsGraph, weekdaysGraph: Api.StatsGraph, topPosters: [Api.StatsGroupTopPoster], topAdmins: [Api.StatsGroupTopAdmin], topInviters: [Api.StatsGroupTopInviter], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .megagroupStats(let period, let members, let messages, let viewers, let posters, let growthGraph, let membersGraph, let newMembersBySourceGraph, let languagesGraph, let messagesGraph, let actionsGraph, let topHoursGraph, let weekdaysGraph, let topPosters, let topAdmins, let topInviters, let users): - if boxed { - buffer.appendInt32(-276825834) - } - period.serialize(buffer, true) - members.serialize(buffer, true) - messages.serialize(buffer, true) - viewers.serialize(buffer, true) - posters.serialize(buffer, true) - growthGraph.serialize(buffer, true) - membersGraph.serialize(buffer, true) - newMembersBySourceGraph.serialize(buffer, true) - languagesGraph.serialize(buffer, true) - messagesGraph.serialize(buffer, true) - actionsGraph.serialize(buffer, true) - topHoursGraph.serialize(buffer, true) - weekdaysGraph.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(topPosters.count)) - for item in topPosters { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(topAdmins.count)) - for item in topAdmins { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(topInviters.count)) - for item in topInviters { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .megagroupStats(let period, let members, let messages, let viewers, let posters, let growthGraph, let membersGraph, let newMembersBySourceGraph, let languagesGraph, let messagesGraph, let actionsGraph, let topHoursGraph, let weekdaysGraph, let topPosters, let topAdmins, let topInviters, let users): - return ("megagroupStats", [("period", period as Any), ("members", members as Any), ("messages", messages as Any), ("viewers", viewers as Any), ("posters", posters as Any), ("growthGraph", growthGraph as Any), ("membersGraph", membersGraph as Any), ("newMembersBySourceGraph", newMembersBySourceGraph as Any), ("languagesGraph", languagesGraph as Any), ("messagesGraph", messagesGraph as Any), ("actionsGraph", actionsGraph as Any), ("topHoursGraph", topHoursGraph as Any), ("weekdaysGraph", weekdaysGraph as Any), ("topPosters", topPosters as Any), ("topAdmins", topAdmins as Any), ("topInviters", topInviters as Any), ("users", users as Any)]) - } - } - - public static func parse_megagroupStats(_ reader: BufferReader) -> MegagroupStats? { - var _1: Api.StatsDateRangeDays? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.StatsDateRangeDays + case groupCallStars(Cons_groupCallStars) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .groupCallStars(let _data): + if boxed { + buffer.appendInt32(-1658995418) + } + serializeInt64(_data.totalStars, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.topDonors.count)) + for item in _data.topDonors { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break } - var _2: Api.StatsAbsValueAndPrev? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev - } - var _3: Api.StatsAbsValueAndPrev? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev - } - var _4: Api.StatsAbsValueAndPrev? - if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev - } - var _5: Api.StatsAbsValueAndPrev? - if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev - } - var _6: Api.StatsGraph? - if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _7: Api.StatsGraph? - if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _8: Api.StatsGraph? - if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _9: Api.StatsGraph? - if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _10: Api.StatsGraph? - if let signature = reader.readInt32() { - _10 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _11: Api.StatsGraph? - if let signature = reader.readInt32() { - _11 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _12: Api.StatsGraph? - if let signature = reader.readInt32() { - _12 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _13: Api.StatsGraph? - if let signature = reader.readInt32() { - _13 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _14: [Api.StatsGroupTopPoster]? - if let _ = reader.readInt32() { - _14 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StatsGroupTopPoster.self) - } - var _15: [Api.StatsGroupTopAdmin]? - if let _ = reader.readInt32() { - _15 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StatsGroupTopAdmin.self) - } - var _16: [Api.StatsGroupTopInviter]? - if let _ = reader.readInt32() { - _16 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StatsGroupTopInviter.self) - } - var _17: [Api.User]? - if let _ = reader.readInt32() { - _17 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - let _c7 = _7 != nil - let _c8 = _8 != nil - let _c9 = _9 != nil - let _c10 = _10 != nil - let _c11 = _11 != nil - let _c12 = _12 != nil - let _c13 = _13 != nil - let _c14 = _14 != nil - let _c15 = _15 != nil - let _c16 = _16 != nil - let _c17 = _17 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - if !_c16 { return nil } - if !_c17 { return nil } - return Api.stats.MegagroupStats.megagroupStats(period: _1!, members: _2!, messages: _3!, viewers: _4!, posters: _5!, growthGraph: _6!, membersGraph: _7!, newMembersBySourceGraph: _8!, languagesGraph: _9!, messagesGraph: _10!, actionsGraph: _11!, topHoursGraph: _12!, weekdaysGraph: _13!, topPosters: _14!, topAdmins: _15!, topInviters: _16!, users: _17!) } - - } -} -public extension Api.stats { - enum MessageStats: TypeConstructorDescription { - case messageStats(viewsGraph: Api.StatsGraph, reactionsByEmotionGraph: Api.StatsGraph) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .messageStats(let viewsGraph, let reactionsByEmotionGraph): - if boxed { - buffer.appendInt32(2145983508) - } - viewsGraph.serialize(buffer, true) - reactionsByEmotionGraph.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .messageStats(let viewsGraph, let reactionsByEmotionGraph): - return ("messageStats", [("viewsGraph", viewsGraph as Any), ("reactionsByEmotionGraph", reactionsByEmotionGraph as Any)]) - } - } - - public static func parse_messageStats(_ reader: BufferReader) -> MessageStats? { - var _1: Api.StatsGraph? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.StatsGraph + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .groupCallStars(let _data): + return ("groupCallStars", [("totalStars", _data.totalStars as Any), ("topDonors", _data.topDonors as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) } - var _2: Api.StatsGraph? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.stats.MessageStats.messageStats(viewsGraph: _1!, reactionsByEmotionGraph: _2!) } - - } -} -public extension Api.stats { - enum PublicForwards: TypeConstructorDescription { - case publicForwards(flags: Int32, count: Int32, forwards: [Api.PublicForward], nextOffset: String?, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .publicForwards(let flags, let count, let forwards, let nextOffset, let chats, let users): - if boxed { - buffer.appendInt32(-1828487648) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(forwards.count)) - for item in forwards { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 0) != 0 {serializeString(nextOffset!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .publicForwards(let flags, let count, let forwards, let nextOffset, let chats, let users): - return ("publicForwards", [("flags", flags as Any), ("count", count as Any), ("forwards", forwards as Any), ("nextOffset", nextOffset as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_publicForwards(_ reader: BufferReader) -> PublicForwards? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: [Api.PublicForward]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PublicForward.self) - } - var _4: String? - if Int(_1!) & Int(1 << 0) != 0 {_4 = parseString(reader) } - var _5: [Api.Chat]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _6: [Api.User]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.stats.PublicForwards.publicForwards(flags: _1!, count: _2!, forwards: _3!, nextOffset: _4, chats: _5!, users: _6!) - } - - } -} -public extension Api.stats { - enum StoryStats: TypeConstructorDescription { - case storyStats(viewsGraph: Api.StatsGraph, reactionsByEmotionGraph: Api.StatsGraph) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .storyStats(let viewsGraph, let reactionsByEmotionGraph): - if boxed { - buffer.appendInt32(1355613820) - } - viewsGraph.serialize(buffer, true) - reactionsByEmotionGraph.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .storyStats(let viewsGraph, let reactionsByEmotionGraph): - return ("storyStats", [("viewsGraph", viewsGraph as Any), ("reactionsByEmotionGraph", reactionsByEmotionGraph as Any)]) - } - } - - public static func parse_storyStats(_ reader: BufferReader) -> StoryStats? { - var _1: Api.StatsGraph? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - var _2: Api.StatsGraph? - if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.stats.StoryStats.storyStats(viewsGraph: _1!, reactionsByEmotionGraph: _2!) - } - - } -} -public extension Api.stickers { - enum SuggestedShortName: TypeConstructorDescription { - case suggestedShortName(shortName: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .suggestedShortName(let shortName): - if boxed { - buffer.appendInt32(-2046910401) - } - serializeString(shortName, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .suggestedShortName(let shortName): - return ("suggestedShortName", [("shortName", shortName as Any)]) - } - } - - public static func parse_suggestedShortName(_ reader: BufferReader) -> SuggestedShortName? { - var _1: String? - _1 = parseString(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.stickers.SuggestedShortName.suggestedShortName(shortName: _1!) - } - - } -} -public extension Api.storage { - enum FileType: TypeConstructorDescription { - case fileGif - case fileJpeg - case fileMov - case fileMp3 - case fileMp4 - case filePartial - case filePdf - case filePng - case fileUnknown - case fileWebp - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .fileGif: - if boxed { - buffer.appendInt32(-891180321) - } - - break - case .fileJpeg: - if boxed { - buffer.appendInt32(8322574) - } - - break - case .fileMov: - if boxed { - buffer.appendInt32(1258941372) - } - - break - case .fileMp3: - if boxed { - buffer.appendInt32(1384777335) - } - - break - case .fileMp4: - if boxed { - buffer.appendInt32(-1278304028) - } - - break - case .filePartial: - if boxed { - buffer.appendInt32(1086091090) - } - - break - case .filePdf: - if boxed { - buffer.appendInt32(-1373745011) - } - - break - case .filePng: - if boxed { - buffer.appendInt32(172975040) - } - - break - case .fileUnknown: - if boxed { - buffer.appendInt32(-1432995067) - } - - break - case .fileWebp: - if boxed { - buffer.appendInt32(276907596) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .fileGif: - return ("fileGif", []) - case .fileJpeg: - return ("fileJpeg", []) - case .fileMov: - return ("fileMov", []) - case .fileMp3: - return ("fileMp3", []) - case .fileMp4: - return ("fileMp4", []) - case .filePartial: - return ("filePartial", []) - case .filePdf: - return ("filePdf", []) - case .filePng: - return ("filePng", []) - case .fileUnknown: - return ("fileUnknown", []) - case .fileWebp: - return ("fileWebp", []) - } - } - - public static func parse_fileGif(_ reader: BufferReader) -> FileType? { - return Api.storage.FileType.fileGif - } - public static func parse_fileJpeg(_ reader: BufferReader) -> FileType? { - return Api.storage.FileType.fileJpeg - } - public static func parse_fileMov(_ reader: BufferReader) -> FileType? { - return Api.storage.FileType.fileMov - } - public static func parse_fileMp3(_ reader: BufferReader) -> FileType? { - return Api.storage.FileType.fileMp3 - } - public static func parse_fileMp4(_ reader: BufferReader) -> FileType? { - return Api.storage.FileType.fileMp4 - } - public static func parse_filePartial(_ reader: BufferReader) -> FileType? { - return Api.storage.FileType.filePartial - } - public static func parse_filePdf(_ reader: BufferReader) -> FileType? { - return Api.storage.FileType.filePdf - } - public static func parse_filePng(_ reader: BufferReader) -> FileType? { - return Api.storage.FileType.filePng - } - public static func parse_fileUnknown(_ reader: BufferReader) -> FileType? { - return Api.storage.FileType.fileUnknown - } - public static func parse_fileWebp(_ reader: BufferReader) -> FileType? { - return Api.storage.FileType.fileWebp - } - - } -} -public extension Api.stories { - enum Albums: TypeConstructorDescription { - case albums(hash: Int64, albums: [Api.StoryAlbum]) - case albumsNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .albums(let hash, let albums): - if boxed { - buffer.appendInt32(-1013417414) - } - serializeInt64(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(albums.count)) - for item in albums { - item.serialize(buffer, true) - } - break - case .albumsNotModified: - if boxed { - buffer.appendInt32(1448008427) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .albums(let hash, let albums): - return ("albums", [("hash", hash as Any), ("albums", albums as Any)]) - case .albumsNotModified: - return ("albumsNotModified", []) - } - } - - public static func parse_albums(_ reader: BufferReader) -> Albums? { + + public static func parse_groupCallStars(_ reader: BufferReader) -> GroupCallStars? { var _1: Int64? _1 = reader.readInt64() - var _2: [Api.StoryAlbum]? + var _2: [Api.GroupCallDonor]? if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StoryAlbum.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.GroupCallDonor.self) + } + var _3: [Api.Chat]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _4: [Api.User]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.stories.Albums.albums(hash: _1!, albums: _2!) + let _c3 = _3 != nil + let _c4 = _4 != nil + if _c1 && _c2 && _c3 && _c4 { + return Api.phone.GroupCallStars.groupCallStars(Cons_groupCallStars(totalStars: _1!, topDonors: _2!, chats: _3!, users: _4!)) + } + else { + return nil + } } - public static func parse_albumsNotModified(_ reader: BufferReader) -> Albums? { - return Api.stories.Albums.albumsNotModified - } - } } -public extension Api.stories { - enum AllStories: TypeConstructorDescription { - case allStories(flags: Int32, count: Int32, state: String, peerStories: [Api.PeerStories], chats: [Api.Chat], users: [Api.User], stealthMode: Api.StoriesStealthMode) - case allStoriesNotModified(flags: Int32, state: String, stealthMode: Api.StoriesStealthMode) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .allStories(let flags, let count, let state, let peerStories, let chats, let users, let stealthMode): - if boxed { - buffer.appendInt32(1862033025) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - serializeString(state, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peerStories.count)) - for item in peerStories { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - stealthMode.serialize(buffer, true) - break - case .allStoriesNotModified(let flags, let state, let stealthMode): - if boxed { - buffer.appendInt32(291044926) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(state, buffer: buffer, boxed: false) - stealthMode.serialize(buffer, true) - break +public extension Api.phone { + enum GroupCallStreamChannels: TypeConstructorDescription { + public class Cons_groupCallStreamChannels { + public var channels: [Api.GroupCallStreamChannel] + public init(channels: [Api.GroupCallStreamChannel]) { + self.channels = channels + } + } + case groupCallStreamChannels(Cons_groupCallStreamChannels) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .groupCallStreamChannels(let _data): + if boxed { + buffer.appendInt32(-790330702) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.channels.count)) + for item in _data.channels { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .groupCallStreamChannels(let _data): + return ("groupCallStreamChannels", [("channels", _data.channels as Any)]) + } + } + + public static func parse_groupCallStreamChannels(_ reader: BufferReader) -> GroupCallStreamChannels? { + var _1: [Api.GroupCallStreamChannel]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.GroupCallStreamChannel.self) + } + let _c1 = _1 != nil + if _c1 { + return Api.phone.GroupCallStreamChannels.groupCallStreamChannels(Cons_groupCallStreamChannels(channels: _1!)) + } + else { + return nil + } + } } +} +public extension Api.phone { + enum GroupCallStreamRtmpUrl: TypeConstructorDescription { + public class Cons_groupCallStreamRtmpUrl { + public var url: String + public var key: String + public init(url: String, key: String) { + self.url = url + self.key = key + } + } + case groupCallStreamRtmpUrl(Cons_groupCallStreamRtmpUrl) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .groupCallStreamRtmpUrl(let _data): + if boxed { + buffer.appendInt32(767505458) + } + serializeString(_data.url, buffer: buffer, boxed: false) + serializeString(_data.key, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .groupCallStreamRtmpUrl(let _data): + return ("groupCallStreamRtmpUrl", [("url", _data.url as Any), ("key", _data.key as Any)]) + } + } + + public static func parse_groupCallStreamRtmpUrl(_ reader: BufferReader) -> GroupCallStreamRtmpUrl? { + var _1: String? + _1 = parseString(reader) + var _2: String? + _2 = parseString(reader) + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.phone.GroupCallStreamRtmpUrl.groupCallStreamRtmpUrl(Cons_groupCallStreamRtmpUrl(url: _1!, key: _2!)) + } + else { + return nil + } + } } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .allStories(let flags, let count, let state, let peerStories, let chats, let users, let stealthMode): - return ("allStories", [("flags", flags as Any), ("count", count as Any), ("state", state as Any), ("peerStories", peerStories as Any), ("chats", chats as Any), ("users", users as Any), ("stealthMode", stealthMode as Any)]) - case .allStoriesNotModified(let flags, let state, let stealthMode): - return ("allStoriesNotModified", [("flags", flags as Any), ("state", state as Any), ("stealthMode", stealthMode as Any)]) - } - } - - public static func parse_allStories(_ reader: BufferReader) -> AllStories? { +} +public extension Api.phone { + enum GroupParticipants: TypeConstructorDescription { + public class Cons_groupParticipants { + public var count: Int32 + public var participants: [Api.GroupCallParticipant] + public var nextOffset: String + public var chats: [Api.Chat] + public var users: [Api.User] + public var version: Int32 + public init(count: Int32, participants: [Api.GroupCallParticipant], nextOffset: String, chats: [Api.Chat], users: [Api.User], version: Int32) { + self.count = count + self.participants = participants + self.nextOffset = nextOffset + self.chats = chats + self.users = users + self.version = version + } + } + case groupParticipants(Cons_groupParticipants) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .groupParticipants(let _data): + if boxed { + buffer.appendInt32(-193506890) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.participants.count)) + for item in _data.participants { + item.serialize(buffer, true) + } + serializeString(_data.nextOffset, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + serializeInt32(_data.version, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .groupParticipants(let _data): + return ("groupParticipants", [("count", _data.count as Any), ("participants", _data.participants as Any), ("nextOffset", _data.nextOffset as Any), ("chats", _data.chats as Any), ("users", _data.users as Any), ("version", _data.version as Any)]) + } + } + + public static func parse_groupParticipants(_ reader: BufferReader) -> GroupParticipants? { var _1: Int32? _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() + var _2: [Api.GroupCallParticipant]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.GroupCallParticipant.self) + } var _3: String? _3 = parseString(reader) - var _4: [Api.PeerStories]? + var _4: [Api.Chat]? if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PeerStories.self) + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) } - var _5: [Api.Chat]? + var _5: [Api.User]? if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _6: [Api.User]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - var _7: Api.StoriesStealthMode? - if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.StoriesStealthMode + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } + var _6: Int32? + _6 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = _6 != nil - let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.stories.AllStories.allStories(flags: _1!, count: _2!, state: _3!, peerStories: _4!, chats: _5!, users: _6!, stealthMode: _7!) - } - public static func parse_allStoriesNotModified(_ reader: BufferReader) -> AllStories? { - var _1: Int32? - _1 = reader.readInt32() - var _2: String? - _2 = parseString(reader) - var _3: Api.StoriesStealthMode? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.StoriesStealthMode + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.phone.GroupParticipants.groupParticipants(Cons_groupParticipants(count: _1!, participants: _2!, nextOffset: _3!, chats: _4!, users: _5!, version: _6!)) + } + else { + return nil } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.stories.AllStories.allStoriesNotModified(flags: _1!, state: _2!, stealthMode: _3!) } - - } -} -public extension Api.stories { - enum CanSendStoryCount: TypeConstructorDescription { - case canSendStoryCount(countRemains: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .canSendStoryCount(let countRemains): - if boxed { - buffer.appendInt32(-1014513586) - } - serializeInt32(countRemains, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .canSendStoryCount(let countRemains): - return ("canSendStoryCount", [("countRemains", countRemains as Any)]) - } - } - - public static func parse_canSendStoryCount(_ reader: BufferReader) -> CanSendStoryCount? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.stories.CanSendStoryCount.canSendStoryCount(countRemains: _1!) - } - - } -} -public extension Api.stories { - enum FoundStories: TypeConstructorDescription { - case foundStories(flags: Int32, count: Int32, stories: [Api.FoundStory], nextOffset: String?, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .foundStories(let flags, let count, let stories, let nextOffset, let chats, let users): - if boxed { - buffer.appendInt32(-488736969) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stories.count)) - for item in stories { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 0) != 0 {serializeString(nextOffset!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .foundStories(let flags, let count, let stories, let nextOffset, let chats, let users): - return ("foundStories", [("flags", flags as Any), ("count", count as Any), ("stories", stories as Any), ("nextOffset", nextOffset as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_foundStories(_ reader: BufferReader) -> FoundStories? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: [Api.FoundStory]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.FoundStory.self) - } - var _4: String? - if Int(_1!) & Int(1 << 0) != 0 {_4 = parseString(reader) } - var _5: [Api.Chat]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _6: [Api.User]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.stories.FoundStories.foundStories(flags: _1!, count: _2!, stories: _3!, nextOffset: _4, chats: _5!, users: _6!) - } - } } diff --git a/submodules/TelegramApi/Sources/Api38.swift b/submodules/TelegramApi/Sources/Api38.swift index 68d4e320..17cdf6bb 100644 --- a/submodules/TelegramApi/Sources/Api38.swift +++ b/submodules/TelegramApi/Sources/Api38.swift @@ -1,39 +1,53 @@ -public extension Api.stories { - enum PeerStories: TypeConstructorDescription { - case peerStories(stories: Api.PeerStories, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .peerStories(let stories, let chats, let users): - if boxed { - buffer.appendInt32(-890861720) - } - stories.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .peerStories(let stories, let chats, let users): - return ("peerStories", [("stories", stories as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_peerStories(_ reader: BufferReader) -> PeerStories? { - var _1: Api.PeerStories? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.PeerStories +public extension Api.phone { + enum JoinAsPeers: TypeConstructorDescription { + public class Cons_joinAsPeers { + public var peers: [Api.Peer] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(peers: [Api.Peer], chats: [Api.Chat], users: [Api.User]) { + self.peers = peers + self.chats = chats + self.users = users + } + } + case joinAsPeers(Cons_joinAsPeers) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .joinAsPeers(let _data): + if boxed { + buffer.appendInt32(-1343921601) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.peers.count)) + for item in _data.peers { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .joinAsPeers(let _data): + return ("joinAsPeers", [("peers", _data.peers as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_joinAsPeers(_ reader: BufferReader) -> JoinAsPeers? { + var _1: [Api.Peer]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) } var _2: [Api.Chat]? if let _ = reader.readInt32() { @@ -46,70 +60,1172 @@ public extension Api.stories { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.stories.PeerStories.peerStories(stories: _1!, chats: _2!, users: _3!) + if _c1 && _c2 && _c3 { + return Api.phone.JoinAsPeers.joinAsPeers(Cons_joinAsPeers(peers: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } } - } } -public extension Api.stories { - enum Stories: TypeConstructorDescription { - case stories(flags: Int32, count: Int32, stories: [Api.StoryItem], pinnedToTop: [Int32]?, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .stories(let flags, let count, let stories, let pinnedToTop, let chats, let users): - if boxed { - buffer.appendInt32(1673780490) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stories.count)) - for item in stories { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(pinnedToTop!.count)) - for item in pinnedToTop! { - serializeInt32(item, buffer: buffer, boxed: false) - }} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break +public extension Api.phone { + enum PhoneCall: TypeConstructorDescription { + public class Cons_phoneCall { + public var phoneCall: Api.PhoneCall + public var users: [Api.User] + public init(phoneCall: Api.PhoneCall, users: [Api.User]) { + self.phoneCall = phoneCall + self.users = users + } + } + case phoneCall(Cons_phoneCall) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .phoneCall(let _data): + if boxed { + buffer.appendInt32(-326966976) + } + _data.phoneCall.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .phoneCall(let _data): + return ("phoneCall", [("phoneCall", _data.phoneCall as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_phoneCall(_ reader: BufferReader) -> PhoneCall? { + var _1: Api.PhoneCall? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.PhoneCall + } + var _2: [Api.User]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.phone.PhoneCall.phoneCall(Cons_phoneCall(phoneCall: _1!, users: _2!)) + } + else { + return nil + } + } } +} +public extension Api.photos { + enum Photo: TypeConstructorDescription { + public class Cons_photo { + public var photo: Api.Photo + public var users: [Api.User] + public init(photo: Api.Photo, users: [Api.User]) { + self.photo = photo + self.users = users + } + } + case photo(Cons_photo) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .photo(let _data): + if boxed { + buffer.appendInt32(539045032) + } + _data.photo.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .photo(let _data): + return ("photo", [("photo", _data.photo as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_photo(_ reader: BufferReader) -> Photo? { + var _1: Api.Photo? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.Photo + } + var _2: [Api.User]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.photos.Photo.photo(Cons_photo(photo: _1!, users: _2!)) + } + else { + return nil + } + } } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .stories(let flags, let count, let stories, let pinnedToTop, let chats, let users): - return ("stories", [("flags", flags as Any), ("count", count as Any), ("stories", stories as Any), ("pinnedToTop", pinnedToTop as Any), ("chats", chats as Any), ("users", users as Any)]) +} +public extension Api.photos { + enum Photos: TypeConstructorDescription { + public class Cons_photos { + public var photos: [Api.Photo] + public var users: [Api.User] + public init(photos: [Api.Photo], users: [Api.User]) { + self.photos = photos + self.users = users + } + } + public class Cons_photosSlice { + public var count: Int32 + public var photos: [Api.Photo] + public var users: [Api.User] + public init(count: Int32, photos: [Api.Photo], users: [Api.User]) { + self.count = count + self.photos = photos + self.users = users + } + } + case photos(Cons_photos) + case photosSlice(Cons_photosSlice) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .photos(let _data): + if boxed { + buffer.appendInt32(-1916114267) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.photos.count)) + for item in _data.photos { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .photosSlice(let _data): + if boxed { + buffer.appendInt32(352657236) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.photos.count)) + for item in _data.photos { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .photos(let _data): + return ("photos", [("photos", _data.photos as Any), ("users", _data.users as Any)]) + case .photosSlice(let _data): + return ("photosSlice", [("count", _data.count as Any), ("photos", _data.photos as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_photos(_ reader: BufferReader) -> Photos? { + var _1: [Api.Photo]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Photo.self) + } + var _2: [Api.User]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.photos.Photos.photos(Cons_photos(photos: _1!, users: _2!)) + } + else { + return nil + } + } + public static func parse_photosSlice(_ reader: BufferReader) -> Photos? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.Photo]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Photo.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.photos.Photos.photosSlice(Cons_photosSlice(count: _1!, photos: _2!, users: _3!)) + } + else { + return nil + } + } } - } - - public static func parse_stories(_ reader: BufferReader) -> Stories? { +} +public extension Api.premium { + enum BoostsList: TypeConstructorDescription { + public class Cons_boostsList { + public var flags: Int32 + public var count: Int32 + public var boosts: [Api.Boost] + public var nextOffset: String? + public var users: [Api.User] + public init(flags: Int32, count: Int32, boosts: [Api.Boost], nextOffset: String?, users: [Api.User]) { + self.flags = flags + self.count = count + self.boosts = boosts + self.nextOffset = nextOffset + self.users = users + } + } + case boostsList(Cons_boostsList) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .boostsList(let _data): + if boxed { + buffer.appendInt32(-2030542532) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.boosts.count)) + for item in _data.boosts { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.nextOffset!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .boostsList(let _data): + return ("boostsList", [("flags", _data.flags as Any), ("count", _data.count as Any), ("boosts", _data.boosts as Any), ("nextOffset", _data.nextOffset as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_boostsList(_ reader: BufferReader) -> BoostsList? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? _2 = reader.readInt32() - var _3: [Api.StoryItem]? + var _3: [Api.Boost]? if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StoryItem.self) + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Boost.self) + } + var _4: String? + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) + } + var _5: [Api.User]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.premium.BoostsList.boostsList(Cons_boostsList(flags: _1!, count: _2!, boosts: _3!, nextOffset: _4, users: _5!)) + } + else { + return nil + } + } + } +} +public extension Api.premium { + enum BoostsStatus: TypeConstructorDescription { + public class Cons_boostsStatus { + public var flags: Int32 + public var level: Int32 + public var currentLevelBoosts: Int32 + public var boosts: Int32 + public var giftBoosts: Int32? + public var nextLevelBoosts: Int32? + public var premiumAudience: Api.StatsPercentValue? + public var boostUrl: String + public var prepaidGiveaways: [Api.PrepaidGiveaway]? + public var myBoostSlots: [Int32]? + public init(flags: Int32, level: Int32, currentLevelBoosts: Int32, boosts: Int32, giftBoosts: Int32?, nextLevelBoosts: Int32?, premiumAudience: Api.StatsPercentValue?, boostUrl: String, prepaidGiveaways: [Api.PrepaidGiveaway]?, myBoostSlots: [Int32]?) { + self.flags = flags + self.level = level + self.currentLevelBoosts = currentLevelBoosts + self.boosts = boosts + self.giftBoosts = giftBoosts + self.nextLevelBoosts = nextLevelBoosts + self.premiumAudience = premiumAudience + self.boostUrl = boostUrl + self.prepaidGiveaways = prepaidGiveaways + self.myBoostSlots = myBoostSlots + } + } + case boostsStatus(Cons_boostsStatus) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .boostsStatus(let _data): + if boxed { + buffer.appendInt32(1230586490) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.level, buffer: buffer, boxed: false) + serializeInt32(_data.currentLevelBoosts, buffer: buffer, boxed: false) + serializeInt32(_data.boosts, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.giftBoosts!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.nextLevelBoosts!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.premiumAudience!.serialize(buffer, true) + } + serializeString(_data.boostUrl, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.prepaidGiveaways!.count)) + for item in _data.prepaidGiveaways! { + item.serialize(buffer, true) + } + } + if Int(_data.flags) & Int(1 << 2) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.myBoostSlots!.count)) + for item in _data.myBoostSlots! { + serializeInt32(item, buffer: buffer, boxed: false) + } + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .boostsStatus(let _data): + return ("boostsStatus", [("flags", _data.flags as Any), ("level", _data.level as Any), ("currentLevelBoosts", _data.currentLevelBoosts as Any), ("boosts", _data.boosts as Any), ("giftBoosts", _data.giftBoosts as Any), ("nextLevelBoosts", _data.nextLevelBoosts as Any), ("premiumAudience", _data.premiumAudience as Any), ("boostUrl", _data.boostUrl as Any), ("prepaidGiveaways", _data.prepaidGiveaways as Any), ("myBoostSlots", _data.myBoostSlots as Any)]) + } + } + + public static func parse_boostsStatus(_ reader: BufferReader) -> BoostsStatus? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + var _4: Int32? + _4 = reader.readInt32() + var _5: Int32? + if Int(_1!) & Int(1 << 4) != 0 { + _5 = reader.readInt32() + } + var _6: Int32? + if Int(_1!) & Int(1 << 0) != 0 { + _6 = reader.readInt32() + } + var _7: Api.StatsPercentValue? + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.StatsPercentValue + } + } + var _8: String? + _8 = parseString(reader) + var _9: [Api.PrepaidGiveaway]? + if Int(_1!) & Int(1 << 3) != 0 { + if let _ = reader.readInt32() { + _9 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PrepaidGiveaway.self) + } + } + var _10: [Int32]? + if Int(_1!) & Int(1 << 2) != 0 { + if let _ = reader.readInt32() { + _10 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = (Int(_1!) & Int(1 << 4) == 0) || _5 != nil + let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil + let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil + let _c8 = _8 != nil + let _c9 = (Int(_1!) & Int(1 << 3) == 0) || _9 != nil + let _c10 = (Int(_1!) & Int(1 << 2) == 0) || _10 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 { + return Api.premium.BoostsStatus.boostsStatus(Cons_boostsStatus(flags: _1!, level: _2!, currentLevelBoosts: _3!, boosts: _4!, giftBoosts: _5, nextLevelBoosts: _6, premiumAudience: _7, boostUrl: _8!, prepaidGiveaways: _9, myBoostSlots: _10)) + } + else { + return nil + } + } + } +} +public extension Api.premium { + enum MyBoosts: TypeConstructorDescription { + public class Cons_myBoosts { + public var myBoosts: [Api.MyBoost] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(myBoosts: [Api.MyBoost], chats: [Api.Chat], users: [Api.User]) { + self.myBoosts = myBoosts + self.chats = chats + self.users = users + } + } + case myBoosts(Cons_myBoosts) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .myBoosts(let _data): + if boxed { + buffer.appendInt32(-1696454430) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.myBoosts.count)) + for item in _data.myBoosts { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .myBoosts(let _data): + return ("myBoosts", [("myBoosts", _data.myBoosts as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_myBoosts(_ reader: BufferReader) -> MyBoosts? { + var _1: [Api.MyBoost]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MyBoost.self) + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.premium.MyBoosts.myBoosts(Cons_myBoosts(myBoosts: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.smsjobs { + enum EligibilityToJoin: TypeConstructorDescription { + public class Cons_eligibleToJoin { + public var termsUrl: String + public var monthlySentSms: Int32 + public init(termsUrl: String, monthlySentSms: Int32) { + self.termsUrl = termsUrl + self.monthlySentSms = monthlySentSms + } + } + case eligibleToJoin(Cons_eligibleToJoin) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .eligibleToJoin(let _data): + if boxed { + buffer.appendInt32(-594852657) + } + serializeString(_data.termsUrl, buffer: buffer, boxed: false) + serializeInt32(_data.monthlySentSms, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .eligibleToJoin(let _data): + return ("eligibleToJoin", [("termsUrl", _data.termsUrl as Any), ("monthlySentSms", _data.monthlySentSms as Any)]) + } + } + + public static func parse_eligibleToJoin(_ reader: BufferReader) -> EligibilityToJoin? { + var _1: String? + _1 = parseString(reader) + var _2: Int32? + _2 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.smsjobs.EligibilityToJoin.eligibleToJoin(Cons_eligibleToJoin(termsUrl: _1!, monthlySentSms: _2!)) + } + else { + return nil + } + } + } +} +public extension Api.smsjobs { + enum Status: TypeConstructorDescription { + public class Cons_status { + public var flags: Int32 + public var recentSent: Int32 + public var recentSince: Int32 + public var recentRemains: Int32 + public var totalSent: Int32 + public var totalSince: Int32 + public var lastGiftSlug: String? + public var termsUrl: String + public init(flags: Int32, recentSent: Int32, recentSince: Int32, recentRemains: Int32, totalSent: Int32, totalSince: Int32, lastGiftSlug: String?, termsUrl: String) { + self.flags = flags + self.recentSent = recentSent + self.recentSince = recentSince + self.recentRemains = recentRemains + self.totalSent = totalSent + self.totalSince = totalSince + self.lastGiftSlug = lastGiftSlug + self.termsUrl = termsUrl + } + } + case status(Cons_status) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .status(let _data): + if boxed { + buffer.appendInt32(720277905) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.recentSent, buffer: buffer, boxed: false) + serializeInt32(_data.recentSince, buffer: buffer, boxed: false) + serializeInt32(_data.recentRemains, buffer: buffer, boxed: false) + serializeInt32(_data.totalSent, buffer: buffer, boxed: false) + serializeInt32(_data.totalSince, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.lastGiftSlug!, buffer: buffer, boxed: false) + } + serializeString(_data.termsUrl, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .status(let _data): + return ("status", [("flags", _data.flags as Any), ("recentSent", _data.recentSent as Any), ("recentSince", _data.recentSince as Any), ("recentRemains", _data.recentRemains as Any), ("totalSent", _data.totalSent as Any), ("totalSince", _data.totalSince as Any), ("lastGiftSlug", _data.lastGiftSlug as Any), ("termsUrl", _data.termsUrl as Any)]) + } + } + + public static func parse_status(_ reader: BufferReader) -> Status? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + var _4: Int32? + _4 = reader.readInt32() + var _5: Int32? + _5 = reader.readInt32() + var _6: Int32? + _6 = reader.readInt32() + var _7: String? + if Int(_1!) & Int(1 << 1) != 0 { + _7 = parseString(reader) + } + var _8: String? + _8 = parseString(reader) + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + let _c7 = (Int(_1!) & Int(1 << 1) == 0) || _7 != nil + let _c8 = _8 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.smsjobs.Status.status(Cons_status(flags: _1!, recentSent: _2!, recentSince: _3!, recentRemains: _4!, totalSent: _5!, totalSince: _6!, lastGiftSlug: _7, termsUrl: _8!)) + } + else { + return nil + } + } + } +} +public extension Api.stats { + enum BroadcastStats: TypeConstructorDescription { + public class Cons_broadcastStats { + public var period: Api.StatsDateRangeDays + public var followers: Api.StatsAbsValueAndPrev + public var viewsPerPost: Api.StatsAbsValueAndPrev + public var sharesPerPost: Api.StatsAbsValueAndPrev + public var reactionsPerPost: Api.StatsAbsValueAndPrev + public var viewsPerStory: Api.StatsAbsValueAndPrev + public var sharesPerStory: Api.StatsAbsValueAndPrev + public var reactionsPerStory: Api.StatsAbsValueAndPrev + public var enabledNotifications: Api.StatsPercentValue + public var growthGraph: Api.StatsGraph + public var followersGraph: Api.StatsGraph + public var muteGraph: Api.StatsGraph + public var topHoursGraph: Api.StatsGraph + public var interactionsGraph: Api.StatsGraph + public var ivInteractionsGraph: Api.StatsGraph + public var viewsBySourceGraph: Api.StatsGraph + public var newFollowersBySourceGraph: Api.StatsGraph + public var languagesGraph: Api.StatsGraph + public var reactionsByEmotionGraph: Api.StatsGraph + public var storyInteractionsGraph: Api.StatsGraph + public var storyReactionsByEmotionGraph: Api.StatsGraph + public var recentPostsInteractions: [Api.PostInteractionCounters] + public init(period: Api.StatsDateRangeDays, followers: Api.StatsAbsValueAndPrev, viewsPerPost: Api.StatsAbsValueAndPrev, sharesPerPost: Api.StatsAbsValueAndPrev, reactionsPerPost: Api.StatsAbsValueAndPrev, viewsPerStory: Api.StatsAbsValueAndPrev, sharesPerStory: Api.StatsAbsValueAndPrev, reactionsPerStory: Api.StatsAbsValueAndPrev, enabledNotifications: Api.StatsPercentValue, growthGraph: Api.StatsGraph, followersGraph: Api.StatsGraph, muteGraph: Api.StatsGraph, topHoursGraph: Api.StatsGraph, interactionsGraph: Api.StatsGraph, ivInteractionsGraph: Api.StatsGraph, viewsBySourceGraph: Api.StatsGraph, newFollowersBySourceGraph: Api.StatsGraph, languagesGraph: Api.StatsGraph, reactionsByEmotionGraph: Api.StatsGraph, storyInteractionsGraph: Api.StatsGraph, storyReactionsByEmotionGraph: Api.StatsGraph, recentPostsInteractions: [Api.PostInteractionCounters]) { + self.period = period + self.followers = followers + self.viewsPerPost = viewsPerPost + self.sharesPerPost = sharesPerPost + self.reactionsPerPost = reactionsPerPost + self.viewsPerStory = viewsPerStory + self.sharesPerStory = sharesPerStory + self.reactionsPerStory = reactionsPerStory + self.enabledNotifications = enabledNotifications + self.growthGraph = growthGraph + self.followersGraph = followersGraph + self.muteGraph = muteGraph + self.topHoursGraph = topHoursGraph + self.interactionsGraph = interactionsGraph + self.ivInteractionsGraph = ivInteractionsGraph + self.viewsBySourceGraph = viewsBySourceGraph + self.newFollowersBySourceGraph = newFollowersBySourceGraph + self.languagesGraph = languagesGraph + self.reactionsByEmotionGraph = reactionsByEmotionGraph + self.storyInteractionsGraph = storyInteractionsGraph + self.storyReactionsByEmotionGraph = storyReactionsByEmotionGraph + self.recentPostsInteractions = recentPostsInteractions + } + } + case broadcastStats(Cons_broadcastStats) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .broadcastStats(let _data): + if boxed { + buffer.appendInt32(963421692) + } + _data.period.serialize(buffer, true) + _data.followers.serialize(buffer, true) + _data.viewsPerPost.serialize(buffer, true) + _data.sharesPerPost.serialize(buffer, true) + _data.reactionsPerPost.serialize(buffer, true) + _data.viewsPerStory.serialize(buffer, true) + _data.sharesPerStory.serialize(buffer, true) + _data.reactionsPerStory.serialize(buffer, true) + _data.enabledNotifications.serialize(buffer, true) + _data.growthGraph.serialize(buffer, true) + _data.followersGraph.serialize(buffer, true) + _data.muteGraph.serialize(buffer, true) + _data.topHoursGraph.serialize(buffer, true) + _data.interactionsGraph.serialize(buffer, true) + _data.ivInteractionsGraph.serialize(buffer, true) + _data.viewsBySourceGraph.serialize(buffer, true) + _data.newFollowersBySourceGraph.serialize(buffer, true) + _data.languagesGraph.serialize(buffer, true) + _data.reactionsByEmotionGraph.serialize(buffer, true) + _data.storyInteractionsGraph.serialize(buffer, true) + _data.storyReactionsByEmotionGraph.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.recentPostsInteractions.count)) + for item in _data.recentPostsInteractions { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .broadcastStats(let _data): + return ("broadcastStats", [("period", _data.period as Any), ("followers", _data.followers as Any), ("viewsPerPost", _data.viewsPerPost as Any), ("sharesPerPost", _data.sharesPerPost as Any), ("reactionsPerPost", _data.reactionsPerPost as Any), ("viewsPerStory", _data.viewsPerStory as Any), ("sharesPerStory", _data.sharesPerStory as Any), ("reactionsPerStory", _data.reactionsPerStory as Any), ("enabledNotifications", _data.enabledNotifications as Any), ("growthGraph", _data.growthGraph as Any), ("followersGraph", _data.followersGraph as Any), ("muteGraph", _data.muteGraph as Any), ("topHoursGraph", _data.topHoursGraph as Any), ("interactionsGraph", _data.interactionsGraph as Any), ("ivInteractionsGraph", _data.ivInteractionsGraph as Any), ("viewsBySourceGraph", _data.viewsBySourceGraph as Any), ("newFollowersBySourceGraph", _data.newFollowersBySourceGraph as Any), ("languagesGraph", _data.languagesGraph as Any), ("reactionsByEmotionGraph", _data.reactionsByEmotionGraph as Any), ("storyInteractionsGraph", _data.storyInteractionsGraph as Any), ("storyReactionsByEmotionGraph", _data.storyReactionsByEmotionGraph as Any), ("recentPostsInteractions", _data.recentPostsInteractions as Any)]) + } + } + + public static func parse_broadcastStats(_ reader: BufferReader) -> BroadcastStats? { + var _1: Api.StatsDateRangeDays? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.StatsDateRangeDays + } + var _2: Api.StatsAbsValueAndPrev? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev + } + var _3: Api.StatsAbsValueAndPrev? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev + } + var _4: Api.StatsAbsValueAndPrev? + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev + } + var _5: Api.StatsAbsValueAndPrev? + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev + } + var _6: Api.StatsAbsValueAndPrev? + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev + } + var _7: Api.StatsAbsValueAndPrev? + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev + } + var _8: Api.StatsAbsValueAndPrev? + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev + } + var _9: Api.StatsPercentValue? + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.StatsPercentValue + } + var _10: Api.StatsGraph? + if let signature = reader.readInt32() { + _10 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _11: Api.StatsGraph? + if let signature = reader.readInt32() { + _11 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _12: Api.StatsGraph? + if let signature = reader.readInt32() { + _12 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _13: Api.StatsGraph? + if let signature = reader.readInt32() { + _13 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _14: Api.StatsGraph? + if let signature = reader.readInt32() { + _14 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _15: Api.StatsGraph? + if let signature = reader.readInt32() { + _15 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _16: Api.StatsGraph? + if let signature = reader.readInt32() { + _16 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _17: Api.StatsGraph? + if let signature = reader.readInt32() { + _17 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _18: Api.StatsGraph? + if let signature = reader.readInt32() { + _18 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _19: Api.StatsGraph? + if let signature = reader.readInt32() { + _19 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _20: Api.StatsGraph? + if let signature = reader.readInt32() { + _20 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _21: Api.StatsGraph? + if let signature = reader.readInt32() { + _21 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _22: [Api.PostInteractionCounters]? + if let _ = reader.readInt32() { + _22 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PostInteractionCounters.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + let _c7 = _7 != nil + let _c8 = _8 != nil + let _c9 = _9 != nil + let _c10 = _10 != nil + let _c11 = _11 != nil + let _c12 = _12 != nil + let _c13 = _13 != nil + let _c14 = _14 != nil + let _c15 = _15 != nil + let _c16 = _16 != nil + let _c17 = _17 != nil + let _c18 = _18 != nil + let _c19 = _19 != nil + let _c20 = _20 != nil + let _c21 = _21 != nil + let _c22 = _22 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 && _c18 && _c19 && _c20 && _c21 && _c22 { + return Api.stats.BroadcastStats.broadcastStats(Cons_broadcastStats(period: _1!, followers: _2!, viewsPerPost: _3!, sharesPerPost: _4!, reactionsPerPost: _5!, viewsPerStory: _6!, sharesPerStory: _7!, reactionsPerStory: _8!, enabledNotifications: _9!, growthGraph: _10!, followersGraph: _11!, muteGraph: _12!, topHoursGraph: _13!, interactionsGraph: _14!, ivInteractionsGraph: _15!, viewsBySourceGraph: _16!, newFollowersBySourceGraph: _17!, languagesGraph: _18!, reactionsByEmotionGraph: _19!, storyInteractionsGraph: _20!, storyReactionsByEmotionGraph: _21!, recentPostsInteractions: _22!)) + } + else { + return nil + } + } + } +} +public extension Api.stats { + enum MegagroupStats: TypeConstructorDescription { + public class Cons_megagroupStats { + public var period: Api.StatsDateRangeDays + public var members: Api.StatsAbsValueAndPrev + public var messages: Api.StatsAbsValueAndPrev + public var viewers: Api.StatsAbsValueAndPrev + public var posters: Api.StatsAbsValueAndPrev + public var growthGraph: Api.StatsGraph + public var membersGraph: Api.StatsGraph + public var newMembersBySourceGraph: Api.StatsGraph + public var languagesGraph: Api.StatsGraph + public var messagesGraph: Api.StatsGraph + public var actionsGraph: Api.StatsGraph + public var topHoursGraph: Api.StatsGraph + public var weekdaysGraph: Api.StatsGraph + public var topPosters: [Api.StatsGroupTopPoster] + public var topAdmins: [Api.StatsGroupTopAdmin] + public var topInviters: [Api.StatsGroupTopInviter] + public var users: [Api.User] + public init(period: Api.StatsDateRangeDays, members: Api.StatsAbsValueAndPrev, messages: Api.StatsAbsValueAndPrev, viewers: Api.StatsAbsValueAndPrev, posters: Api.StatsAbsValueAndPrev, growthGraph: Api.StatsGraph, membersGraph: Api.StatsGraph, newMembersBySourceGraph: Api.StatsGraph, languagesGraph: Api.StatsGraph, messagesGraph: Api.StatsGraph, actionsGraph: Api.StatsGraph, topHoursGraph: Api.StatsGraph, weekdaysGraph: Api.StatsGraph, topPosters: [Api.StatsGroupTopPoster], topAdmins: [Api.StatsGroupTopAdmin], topInviters: [Api.StatsGroupTopInviter], users: [Api.User]) { + self.period = period + self.members = members + self.messages = messages + self.viewers = viewers + self.posters = posters + self.growthGraph = growthGraph + self.membersGraph = membersGraph + self.newMembersBySourceGraph = newMembersBySourceGraph + self.languagesGraph = languagesGraph + self.messagesGraph = messagesGraph + self.actionsGraph = actionsGraph + self.topHoursGraph = topHoursGraph + self.weekdaysGraph = weekdaysGraph + self.topPosters = topPosters + self.topAdmins = topAdmins + self.topInviters = topInviters + self.users = users + } + } + case megagroupStats(Cons_megagroupStats) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .megagroupStats(let _data): + if boxed { + buffer.appendInt32(-276825834) + } + _data.period.serialize(buffer, true) + _data.members.serialize(buffer, true) + _data.messages.serialize(buffer, true) + _data.viewers.serialize(buffer, true) + _data.posters.serialize(buffer, true) + _data.growthGraph.serialize(buffer, true) + _data.membersGraph.serialize(buffer, true) + _data.newMembersBySourceGraph.serialize(buffer, true) + _data.languagesGraph.serialize(buffer, true) + _data.messagesGraph.serialize(buffer, true) + _data.actionsGraph.serialize(buffer, true) + _data.topHoursGraph.serialize(buffer, true) + _data.weekdaysGraph.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.topPosters.count)) + for item in _data.topPosters { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.topAdmins.count)) + for item in _data.topAdmins { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.topInviters.count)) + for item in _data.topInviters { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .megagroupStats(let _data): + return ("megagroupStats", [("period", _data.period as Any), ("members", _data.members as Any), ("messages", _data.messages as Any), ("viewers", _data.viewers as Any), ("posters", _data.posters as Any), ("growthGraph", _data.growthGraph as Any), ("membersGraph", _data.membersGraph as Any), ("newMembersBySourceGraph", _data.newMembersBySourceGraph as Any), ("languagesGraph", _data.languagesGraph as Any), ("messagesGraph", _data.messagesGraph as Any), ("actionsGraph", _data.actionsGraph as Any), ("topHoursGraph", _data.topHoursGraph as Any), ("weekdaysGraph", _data.weekdaysGraph as Any), ("topPosters", _data.topPosters as Any), ("topAdmins", _data.topAdmins as Any), ("topInviters", _data.topInviters as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_megagroupStats(_ reader: BufferReader) -> MegagroupStats? { + var _1: Api.StatsDateRangeDays? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.StatsDateRangeDays + } + var _2: Api.StatsAbsValueAndPrev? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev + } + var _3: Api.StatsAbsValueAndPrev? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev + } + var _4: Api.StatsAbsValueAndPrev? + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev + } + var _5: Api.StatsAbsValueAndPrev? + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.StatsAbsValueAndPrev + } + var _6: Api.StatsGraph? + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _7: Api.StatsGraph? + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _8: Api.StatsGraph? + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _9: Api.StatsGraph? + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _10: Api.StatsGraph? + if let signature = reader.readInt32() { + _10 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _11: Api.StatsGraph? + if let signature = reader.readInt32() { + _11 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _12: Api.StatsGraph? + if let signature = reader.readInt32() { + _12 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _13: Api.StatsGraph? + if let signature = reader.readInt32() { + _13 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _14: [Api.StatsGroupTopPoster]? + if let _ = reader.readInt32() { + _14 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StatsGroupTopPoster.self) + } + var _15: [Api.StatsGroupTopAdmin]? + if let _ = reader.readInt32() { + _15 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StatsGroupTopAdmin.self) + } + var _16: [Api.StatsGroupTopInviter]? + if let _ = reader.readInt32() { + _16 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StatsGroupTopInviter.self) + } + var _17: [Api.User]? + if let _ = reader.readInt32() { + _17 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + let _c7 = _7 != nil + let _c8 = _8 != nil + let _c9 = _9 != nil + let _c10 = _10 != nil + let _c11 = _11 != nil + let _c12 = _12 != nil + let _c13 = _13 != nil + let _c14 = _14 != nil + let _c15 = _15 != nil + let _c16 = _16 != nil + let _c17 = _17 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 { + return Api.stats.MegagroupStats.megagroupStats(Cons_megagroupStats(period: _1!, members: _2!, messages: _3!, viewers: _4!, posters: _5!, growthGraph: _6!, membersGraph: _7!, newMembersBySourceGraph: _8!, languagesGraph: _9!, messagesGraph: _10!, actionsGraph: _11!, topHoursGraph: _12!, weekdaysGraph: _13!, topPosters: _14!, topAdmins: _15!, topInviters: _16!, users: _17!)) + } + else { + return nil + } + } + } +} +public extension Api.stats { + enum MessageStats: TypeConstructorDescription { + public class Cons_messageStats { + public var viewsGraph: Api.StatsGraph + public var reactionsByEmotionGraph: Api.StatsGraph + public init(viewsGraph: Api.StatsGraph, reactionsByEmotionGraph: Api.StatsGraph) { + self.viewsGraph = viewsGraph + self.reactionsByEmotionGraph = reactionsByEmotionGraph + } + } + case messageStats(Cons_messageStats) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .messageStats(let _data): + if boxed { + buffer.appendInt32(2145983508) + } + _data.viewsGraph.serialize(buffer, true) + _data.reactionsByEmotionGraph.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .messageStats(let _data): + return ("messageStats", [("viewsGraph", _data.viewsGraph as Any), ("reactionsByEmotionGraph", _data.reactionsByEmotionGraph as Any)]) + } + } + + public static func parse_messageStats(_ reader: BufferReader) -> MessageStats? { + var _1: Api.StatsGraph? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + var _2: Api.StatsGraph? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.stats.MessageStats.messageStats(Cons_messageStats(viewsGraph: _1!, reactionsByEmotionGraph: _2!)) + } + else { + return nil + } + } + } +} +public extension Api.stats { + enum PublicForwards: TypeConstructorDescription { + public class Cons_publicForwards { + public var flags: Int32 + public var count: Int32 + public var forwards: [Api.PublicForward] + public var nextOffset: String? + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, count: Int32, forwards: [Api.PublicForward], nextOffset: String?, chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.count = count + self.forwards = forwards + self.nextOffset = nextOffset + self.chats = chats + self.users = users + } + } + case publicForwards(Cons_publicForwards) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .publicForwards(let _data): + if boxed { + buffer.appendInt32(-1828487648) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.forwards.count)) + for item in _data.forwards { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.nextOffset!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .publicForwards(let _data): + return ("publicForwards", [("flags", _data.flags as Any), ("count", _data.count as Any), ("forwards", _data.forwards as Any), ("nextOffset", _data.nextOffset as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_publicForwards(_ reader: BufferReader) -> PublicForwards? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: [Api.PublicForward]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PublicForward.self) + } + var _4: String? + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) } - var _4: [Int32]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } } var _5: [Api.Chat]? if let _ = reader.readInt32() { _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) @@ -124,378 +1240,543 @@ public extension Api.stories { let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil let _c5 = _5 != nil let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.stories.Stories.stories(flags: _1!, count: _2!, stories: _3!, pinnedToTop: _4, chats: _5!, users: _6!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.stats.PublicForwards.publicForwards(Cons_publicForwards(flags: _1!, count: _2!, forwards: _3!, nextOffset: _4, chats: _5!, users: _6!)) + } + else { + return nil + } } - } } -public extension Api.stories { - enum StoryReactionsList: TypeConstructorDescription { - case storyReactionsList(flags: Int32, count: Int32, reactions: [Api.StoryReaction], chats: [Api.Chat], users: [Api.User], nextOffset: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .storyReactionsList(let flags, let count, let reactions, let chats, let users, let nextOffset): - if boxed { - buffer.appendInt32(-1436583780) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(reactions.count)) - for item in reactions { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 0) != 0 {serializeString(nextOffset!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .storyReactionsList(let flags, let count, let reactions, let chats, let users, let nextOffset): - return ("storyReactionsList", [("flags", flags as Any), ("count", count as Any), ("reactions", reactions as Any), ("chats", chats as Any), ("users", users as Any), ("nextOffset", nextOffset as Any)]) - } - } - - public static func parse_storyReactionsList(_ reader: BufferReader) -> StoryReactionsList? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: [Api.StoryReaction]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StoryReaction.self) +public extension Api.stats { + enum StoryStats: TypeConstructorDescription { + public class Cons_storyStats { + public var viewsGraph: Api.StatsGraph + public var reactionsByEmotionGraph: Api.StatsGraph + public init(viewsGraph: Api.StatsGraph, reactionsByEmotionGraph: Api.StatsGraph) { + self.viewsGraph = viewsGraph + self.reactionsByEmotionGraph = reactionsByEmotionGraph } - var _4: [Api.Chat]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _5: [Api.User]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - var _6: String? - if Int(_1!) & Int(1 << 0) != 0 {_6 = parseString(reader) } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.stories.StoryReactionsList.storyReactionsList(flags: _1!, count: _2!, reactions: _3!, chats: _4!, users: _5!, nextOffset: _6) } - - } -} -public extension Api.stories { - enum StoryViews: TypeConstructorDescription { - case storyViews(views: [Api.StoryViews], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .storyViews(let views, let users): - if boxed { - buffer.appendInt32(-560009955) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(views.count)) - for item in views { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .storyViews(let views, let users): - return ("storyViews", [("views", views as Any), ("users", users as Any)]) - } - } - - public static func parse_storyViews(_ reader: BufferReader) -> StoryViews? { - var _1: [Api.StoryViews]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StoryViews.self) + case storyStats(Cons_storyStats) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .storyStats(let _data): + if boxed { + buffer.appendInt32(1355613820) + } + _data.viewsGraph.serialize(buffer, true) + _data.reactionsByEmotionGraph.serialize(buffer, true) + break } - var _2: [Api.User]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.stories.StoryViews.storyViews(views: _1!, users: _2!) } - - } -} -public extension Api.stories { - enum StoryViewsList: TypeConstructorDescription { - case storyViewsList(flags: Int32, count: Int32, viewsCount: Int32, forwardsCount: Int32, reactionsCount: Int32, views: [Api.StoryView], chats: [Api.Chat], users: [Api.User], nextOffset: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .storyViewsList(let flags, let count, let viewsCount, let forwardsCount, let reactionsCount, let views, let chats, let users, let nextOffset): - if boxed { - buffer.appendInt32(1507299269) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - serializeInt32(viewsCount, buffer: buffer, boxed: false) - serializeInt32(forwardsCount, buffer: buffer, boxed: false) - serializeInt32(reactionsCount, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(views.count)) - for item in views { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 0) != 0 {serializeString(nextOffset!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .storyViewsList(let flags, let count, let viewsCount, let forwardsCount, let reactionsCount, let views, let chats, let users, let nextOffset): - return ("storyViewsList", [("flags", flags as Any), ("count", count as Any), ("viewsCount", viewsCount as Any), ("forwardsCount", forwardsCount as Any), ("reactionsCount", reactionsCount as Any), ("views", views as Any), ("chats", chats as Any), ("users", users as Any), ("nextOffset", nextOffset as Any)]) - } - } - - public static func parse_storyViewsList(_ reader: BufferReader) -> StoryViewsList? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - var _4: Int32? - _4 = reader.readInt32() - var _5: Int32? - _5 = reader.readInt32() - var _6: [Api.StoryView]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StoryView.self) + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .storyStats(let _data): + return ("storyStats", [("viewsGraph", _data.viewsGraph as Any), ("reactionsByEmotionGraph", _data.reactionsByEmotionGraph as Any)]) } - var _7: [Api.Chat]? - if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _8: [Api.User]? - if let _ = reader.readInt32() { - _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - var _9: String? - if Int(_1!) & Int(1 << 0) != 0 {_9 = parseString(reader) } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - let _c7 = _7 != nil - let _c8 = _8 != nil - let _c9 = (Int(_1!) & Int(1 << 0) == 0) || _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.stories.StoryViewsList.storyViewsList(flags: _1!, count: _2!, viewsCount: _3!, forwardsCount: _4!, reactionsCount: _5!, views: _6!, chats: _7!, users: _8!, nextOffset: _9) } - - } -} -public extension Api.updates { - indirect enum ChannelDifference: TypeConstructorDescription { - case channelDifference(flags: Int32, pts: Int32, timeout: Int32?, newMessages: [Api.Message], otherUpdates: [Api.Update], chats: [Api.Chat], users: [Api.User]) - case channelDifferenceEmpty(flags: Int32, pts: Int32, timeout: Int32?) - case channelDifferenceTooLong(flags: Int32, timeout: Int32?, dialog: Api.Dialog, messages: [Api.Message], chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .channelDifference(let flags, let pts, let timeout, let newMessages, let otherUpdates, let chats, let users): - if boxed { - buffer.appendInt32(543450958) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(pts, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(timeout!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(newMessages.count)) - for item in newMessages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(otherUpdates.count)) - for item in otherUpdates { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .channelDifferenceEmpty(let flags, let pts, let timeout): - if boxed { - buffer.appendInt32(1041346555) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(pts, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(timeout!, buffer: buffer, boxed: false)} - break - case .channelDifferenceTooLong(let flags, let timeout, let dialog, let messages, let chats, let users): - if boxed { - buffer.appendInt32(-1531132162) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(timeout!, buffer: buffer, boxed: false)} - dialog.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .channelDifference(let flags, let pts, let timeout, let newMessages, let otherUpdates, let chats, let users): - return ("channelDifference", [("flags", flags as Any), ("pts", pts as Any), ("timeout", timeout as Any), ("newMessages", newMessages as Any), ("otherUpdates", otherUpdates as Any), ("chats", chats as Any), ("users", users as Any)]) - case .channelDifferenceEmpty(let flags, let pts, let timeout): - return ("channelDifferenceEmpty", [("flags", flags as Any), ("pts", pts as Any), ("timeout", timeout as Any)]) - case .channelDifferenceTooLong(let flags, let timeout, let dialog, let messages, let chats, let users): - return ("channelDifferenceTooLong", [("flags", flags as Any), ("timeout", timeout as Any), ("dialog", dialog as Any), ("messages", messages as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_channelDifference(_ reader: BufferReader) -> ChannelDifference? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_3 = reader.readInt32() } - var _4: [Api.Message]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) - } - var _5: [Api.Update]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Update.self) - } - var _6: [Api.Chat]? - if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _7: [Api.User]? - if let _ = reader.readInt32() { - _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.updates.ChannelDifference.channelDifference(flags: _1!, pts: _2!, timeout: _3, newMessages: _4!, otherUpdates: _5!, chats: _6!, users: _7!) - } - public static func parse_channelDifferenceEmpty(_ reader: BufferReader) -> ChannelDifference? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_3 = reader.readInt32() } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.updates.ChannelDifference.channelDifferenceEmpty(flags: _1!, pts: _2!, timeout: _3) - } - public static func parse_channelDifferenceTooLong(_ reader: BufferReader) -> ChannelDifference? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_2 = reader.readInt32() } - var _3: Api.Dialog? + + public static func parse_storyStats(_ reader: BufferReader) -> StoryStats? { + var _1: Api.StatsGraph? if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.Dialog + _1 = Api.parse(reader, signature: signature) as? Api.StatsGraph } - var _4: [Api.Message]? + var _2: Api.StatsGraph? + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.stats.StoryStats.storyStats(Cons_storyStats(viewsGraph: _1!, reactionsByEmotionGraph: _2!)) + } + else { + return nil + } + } + } +} +public extension Api.stickers { + enum SuggestedShortName: TypeConstructorDescription { + public class Cons_suggestedShortName { + public var shortName: String + public init(shortName: String) { + self.shortName = shortName + } + } + case suggestedShortName(Cons_suggestedShortName) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .suggestedShortName(let _data): + if boxed { + buffer.appendInt32(-2046910401) + } + serializeString(_data.shortName, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .suggestedShortName(let _data): + return ("suggestedShortName", [("shortName", _data.shortName as Any)]) + } + } + + public static func parse_suggestedShortName(_ reader: BufferReader) -> SuggestedShortName? { + var _1: String? + _1 = parseString(reader) + let _c1 = _1 != nil + if _c1 { + return Api.stickers.SuggestedShortName.suggestedShortName(Cons_suggestedShortName(shortName: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.storage { + enum FileType: TypeConstructorDescription { + case fileGif + case fileJpeg + case fileMov + case fileMp3 + case fileMp4 + case filePartial + case filePdf + case filePng + case fileUnknown + case fileWebp + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .fileGif: + if boxed { + buffer.appendInt32(-891180321) + } + break + case .fileJpeg: + if boxed { + buffer.appendInt32(8322574) + } + break + case .fileMov: + if boxed { + buffer.appendInt32(1258941372) + } + break + case .fileMp3: + if boxed { + buffer.appendInt32(1384777335) + } + break + case .fileMp4: + if boxed { + buffer.appendInt32(-1278304028) + } + break + case .filePartial: + if boxed { + buffer.appendInt32(1086091090) + } + break + case .filePdf: + if boxed { + buffer.appendInt32(-1373745011) + } + break + case .filePng: + if boxed { + buffer.appendInt32(172975040) + } + break + case .fileUnknown: + if boxed { + buffer.appendInt32(-1432995067) + } + break + case .fileWebp: + if boxed { + buffer.appendInt32(276907596) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .fileGif: + return ("fileGif", []) + case .fileJpeg: + return ("fileJpeg", []) + case .fileMov: + return ("fileMov", []) + case .fileMp3: + return ("fileMp3", []) + case .fileMp4: + return ("fileMp4", []) + case .filePartial: + return ("filePartial", []) + case .filePdf: + return ("filePdf", []) + case .filePng: + return ("filePng", []) + case .fileUnknown: + return ("fileUnknown", []) + case .fileWebp: + return ("fileWebp", []) + } + } + + public static func parse_fileGif(_ reader: BufferReader) -> FileType? { + return Api.storage.FileType.fileGif + } + public static func parse_fileJpeg(_ reader: BufferReader) -> FileType? { + return Api.storage.FileType.fileJpeg + } + public static func parse_fileMov(_ reader: BufferReader) -> FileType? { + return Api.storage.FileType.fileMov + } + public static func parse_fileMp3(_ reader: BufferReader) -> FileType? { + return Api.storage.FileType.fileMp3 + } + public static func parse_fileMp4(_ reader: BufferReader) -> FileType? { + return Api.storage.FileType.fileMp4 + } + public static func parse_filePartial(_ reader: BufferReader) -> FileType? { + return Api.storage.FileType.filePartial + } + public static func parse_filePdf(_ reader: BufferReader) -> FileType? { + return Api.storage.FileType.filePdf + } + public static func parse_filePng(_ reader: BufferReader) -> FileType? { + return Api.storage.FileType.filePng + } + public static func parse_fileUnknown(_ reader: BufferReader) -> FileType? { + return Api.storage.FileType.fileUnknown + } + public static func parse_fileWebp(_ reader: BufferReader) -> FileType? { + return Api.storage.FileType.fileWebp + } + } +} +public extension Api.stories { + enum Albums: TypeConstructorDescription { + public class Cons_albums { + public var hash: Int64 + public var albums: [Api.StoryAlbum] + public init(hash: Int64, albums: [Api.StoryAlbum]) { + self.hash = hash + self.albums = albums + } + } + case albums(Cons_albums) + case albumsNotModified + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .albums(let _data): + if boxed { + buffer.appendInt32(-1013417414) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.albums.count)) + for item in _data.albums { + item.serialize(buffer, true) + } + break + case .albumsNotModified: + if boxed { + buffer.appendInt32(1448008427) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .albums(let _data): + return ("albums", [("hash", _data.hash as Any), ("albums", _data.albums as Any)]) + case .albumsNotModified: + return ("albumsNotModified", []) + } + } + + public static func parse_albums(_ reader: BufferReader) -> Albums? { + var _1: Int64? + _1 = reader.readInt64() + var _2: [Api.StoryAlbum]? if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StoryAlbum.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.stories.Albums.albums(Cons_albums(hash: _1!, albums: _2!)) + } + else { + return nil + } + } + public static func parse_albumsNotModified(_ reader: BufferReader) -> Albums? { + return Api.stories.Albums.albumsNotModified + } + } +} +public extension Api.stories { + enum AllStories: TypeConstructorDescription { + public class Cons_allStories { + public var flags: Int32 + public var count: Int32 + public var state: String + public var peerStories: [Api.PeerStories] + public var chats: [Api.Chat] + public var users: [Api.User] + public var stealthMode: Api.StoriesStealthMode + public init(flags: Int32, count: Int32, state: String, peerStories: [Api.PeerStories], chats: [Api.Chat], users: [Api.User], stealthMode: Api.StoriesStealthMode) { + self.flags = flags + self.count = count + self.state = state + self.peerStories = peerStories + self.chats = chats + self.users = users + self.stealthMode = stealthMode + } + } + public class Cons_allStoriesNotModified { + public var flags: Int32 + public var state: String + public var stealthMode: Api.StoriesStealthMode + public init(flags: Int32, state: String, stealthMode: Api.StoriesStealthMode) { + self.flags = flags + self.state = state + self.stealthMode = stealthMode + } + } + case allStories(Cons_allStories) + case allStoriesNotModified(Cons_allStoriesNotModified) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .allStories(let _data): + if boxed { + buffer.appendInt32(1862033025) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + serializeString(_data.state, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.peerStories.count)) + for item in _data.peerStories { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + _data.stealthMode.serialize(buffer, true) + break + case .allStoriesNotModified(let _data): + if boxed { + buffer.appendInt32(291044926) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.state, buffer: buffer, boxed: false) + _data.stealthMode.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .allStories(let _data): + return ("allStories", [("flags", _data.flags as Any), ("count", _data.count as Any), ("state", _data.state as Any), ("peerStories", _data.peerStories as Any), ("chats", _data.chats as Any), ("users", _data.users as Any), ("stealthMode", _data.stealthMode as Any)]) + case .allStoriesNotModified(let _data): + return ("allStoriesNotModified", [("flags", _data.flags as Any), ("state", _data.state as Any), ("stealthMode", _data.stealthMode as Any)]) + } + } + + public static func parse_allStories(_ reader: BufferReader) -> AllStories? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: String? + _3 = parseString(reader) + var _4: [Api.PeerStories]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PeerStories.self) + } + var _5: [Api.Chat]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _6: [Api.User]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + var _7: Api.StoriesStealthMode? + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.StoriesStealthMode + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + let _c7 = _7 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.stories.AllStories.allStories(Cons_allStories(flags: _1!, count: _2!, state: _3!, peerStories: _4!, chats: _5!, users: _6!, stealthMode: _7!)) + } + else { + return nil + } + } + public static func parse_allStoriesNotModified(_ reader: BufferReader) -> AllStories? { + var _1: Int32? + _1 = reader.readInt32() + var _2: String? + _2 = parseString(reader) + var _3: Api.StoriesStealthMode? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.StoriesStealthMode + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.stories.AllStories.allStoriesNotModified(Cons_allStoriesNotModified(flags: _1!, state: _2!, stealthMode: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.stories { + enum CanSendStoryCount: TypeConstructorDescription { + public class Cons_canSendStoryCount { + public var countRemains: Int32 + public init(countRemains: Int32) { + self.countRemains = countRemains + } + } + case canSendStoryCount(Cons_canSendStoryCount) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .canSendStoryCount(let _data): + if boxed { + buffer.appendInt32(-1014513586) + } + serializeInt32(_data.countRemains, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .canSendStoryCount(let _data): + return ("canSendStoryCount", [("countRemains", _data.countRemains as Any)]) + } + } + + public static func parse_canSendStoryCount(_ reader: BufferReader) -> CanSendStoryCount? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.stories.CanSendStoryCount.canSendStoryCount(Cons_canSendStoryCount(countRemains: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.stories { + enum FoundStories: TypeConstructorDescription { + public class Cons_foundStories { + public var flags: Int32 + public var count: Int32 + public var stories: [Api.FoundStory] + public var nextOffset: String? + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, count: Int32, stories: [Api.FoundStory], nextOffset: String?, chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.count = count + self.stories = stories + self.nextOffset = nextOffset + self.chats = chats + self.users = users + } + } + case foundStories(Cons_foundStories) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .foundStories(let _data): + if boxed { + buffer.appendInt32(-488736969) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.stories.count)) + for item in _data.stories { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.nextOffset!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .foundStories(let _data): + return ("foundStories", [("flags", _data.flags as Any), ("count", _data.count as Any), ("stories", _data.stories as Any), ("nextOffset", _data.nextOffset as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_foundStories(_ reader: BufferReader) -> FoundStories? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: [Api.FoundStory]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.FoundStory.self) + } + var _4: String? + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) } var _5: [Api.Chat]? if let _ = reader.readInt32() { @@ -506,638 +1787,17 @@ public extension Api.updates { _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) } let _c1 = _1 != nil - let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil + let _c2 = _2 != nil let _c3 = _3 != nil - let _c4 = _4 != nil + let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil let _c5 = _5 != nil let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.updates.ChannelDifference.channelDifferenceTooLong(flags: _1!, timeout: _2, dialog: _3!, messages: _4!, chats: _5!, users: _6!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.stories.FoundStories.foundStories(Cons_foundStories(flags: _1!, count: _2!, stories: _3!, nextOffset: _4, chats: _5!, users: _6!)) + } + else { + return nil + } } - - } -} -public extension Api.updates { - enum Difference: TypeConstructorDescription { - case difference(newMessages: [Api.Message], newEncryptedMessages: [Api.EncryptedMessage], otherUpdates: [Api.Update], chats: [Api.Chat], users: [Api.User], state: Api.updates.State) - case differenceEmpty(date: Int32, seq: Int32) - case differenceSlice(newMessages: [Api.Message], newEncryptedMessages: [Api.EncryptedMessage], otherUpdates: [Api.Update], chats: [Api.Chat], users: [Api.User], intermediateState: Api.updates.State) - case differenceTooLong(pts: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .difference(let newMessages, let newEncryptedMessages, let otherUpdates, let chats, let users, let state): - if boxed { - buffer.appendInt32(16030880) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(newMessages.count)) - for item in newMessages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(newEncryptedMessages.count)) - for item in newEncryptedMessages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(otherUpdates.count)) - for item in otherUpdates { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - state.serialize(buffer, true) - break - case .differenceEmpty(let date, let seq): - if boxed { - buffer.appendInt32(1567990072) - } - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt32(seq, buffer: buffer, boxed: false) - break - case .differenceSlice(let newMessages, let newEncryptedMessages, let otherUpdates, let chats, let users, let intermediateState): - if boxed { - buffer.appendInt32(-1459938943) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(newMessages.count)) - for item in newMessages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(newEncryptedMessages.count)) - for item in newEncryptedMessages { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(otherUpdates.count)) - for item in otherUpdates { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - intermediateState.serialize(buffer, true) - break - case .differenceTooLong(let pts): - if boxed { - buffer.appendInt32(1258196845) - } - serializeInt32(pts, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .difference(let newMessages, let newEncryptedMessages, let otherUpdates, let chats, let users, let state): - return ("difference", [("newMessages", newMessages as Any), ("newEncryptedMessages", newEncryptedMessages as Any), ("otherUpdates", otherUpdates as Any), ("chats", chats as Any), ("users", users as Any), ("state", state as Any)]) - case .differenceEmpty(let date, let seq): - return ("differenceEmpty", [("date", date as Any), ("seq", seq as Any)]) - case .differenceSlice(let newMessages, let newEncryptedMessages, let otherUpdates, let chats, let users, let intermediateState): - return ("differenceSlice", [("newMessages", newMessages as Any), ("newEncryptedMessages", newEncryptedMessages as Any), ("otherUpdates", otherUpdates as Any), ("chats", chats as Any), ("users", users as Any), ("intermediateState", intermediateState as Any)]) - case .differenceTooLong(let pts): - return ("differenceTooLong", [("pts", pts as Any)]) - } - } - - public static func parse_difference(_ reader: BufferReader) -> Difference? { - var _1: [Api.Message]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) - } - var _2: [Api.EncryptedMessage]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.EncryptedMessage.self) - } - var _3: [Api.Update]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Update.self) - } - var _4: [Api.Chat]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _5: [Api.User]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - var _6: Api.updates.State? - if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.updates.State - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.updates.Difference.difference(newMessages: _1!, newEncryptedMessages: _2!, otherUpdates: _3!, chats: _4!, users: _5!, state: _6!) - } - public static func parse_differenceEmpty(_ reader: BufferReader) -> Difference? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.updates.Difference.differenceEmpty(date: _1!, seq: _2!) - } - public static func parse_differenceSlice(_ reader: BufferReader) -> Difference? { - var _1: [Api.Message]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) - } - var _2: [Api.EncryptedMessage]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.EncryptedMessage.self) - } - var _3: [Api.Update]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Update.self) - } - var _4: [Api.Chat]? - if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _5: [Api.User]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - var _6: Api.updates.State? - if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.updates.State - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - let _c6 = _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.updates.Difference.differenceSlice(newMessages: _1!, newEncryptedMessages: _2!, otherUpdates: _3!, chats: _4!, users: _5!, intermediateState: _6!) - } - public static func parse_differenceTooLong(_ reader: BufferReader) -> Difference? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.updates.Difference.differenceTooLong(pts: _1!) - } - - } -} -public extension Api.updates { - enum State: TypeConstructorDescription { - case state(pts: Int32, qts: Int32, date: Int32, seq: Int32, unreadCount: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .state(let pts, let qts, let date, let seq, let unreadCount): - if boxed { - buffer.appendInt32(-1519637954) - } - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(qts, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt32(seq, buffer: buffer, boxed: false) - serializeInt32(unreadCount, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .state(let pts, let qts, let date, let seq, let unreadCount): - return ("state", [("pts", pts as Any), ("qts", qts as Any), ("date", date as Any), ("seq", seq as Any), ("unreadCount", unreadCount as Any)]) - } - } - - public static func parse_state(_ reader: BufferReader) -> State? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Int32? - _2 = reader.readInt32() - var _3: Int32? - _3 = reader.readInt32() - var _4: Int32? - _4 = reader.readInt32() - var _5: Int32? - _5 = reader.readInt32() - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.updates.State.state(pts: _1!, qts: _2!, date: _3!, seq: _4!, unreadCount: _5!) - } - - } -} -public extension Api.upload { - enum CdnFile: TypeConstructorDescription { - case cdnFile(bytes: Buffer) - case cdnFileReuploadNeeded(requestToken: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .cdnFile(let bytes): - if boxed { - buffer.appendInt32(-1449145777) - } - serializeBytes(bytes, buffer: buffer, boxed: false) - break - case .cdnFileReuploadNeeded(let requestToken): - if boxed { - buffer.appendInt32(-290921362) - } - serializeBytes(requestToken, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .cdnFile(let bytes): - return ("cdnFile", [("bytes", bytes as Any)]) - case .cdnFileReuploadNeeded(let requestToken): - return ("cdnFileReuploadNeeded", [("requestToken", requestToken as Any)]) - } - } - - public static func parse_cdnFile(_ reader: BufferReader) -> CdnFile? { - var _1: Buffer? - _1 = parseBytes(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.upload.CdnFile.cdnFile(bytes: _1!) - } - public static func parse_cdnFileReuploadNeeded(_ reader: BufferReader) -> CdnFile? { - var _1: Buffer? - _1 = parseBytes(reader) - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.upload.CdnFile.cdnFileReuploadNeeded(requestToken: _1!) - } - - } -} -public extension Api.upload { - enum File: TypeConstructorDescription { - case file(type: Api.storage.FileType, mtime: Int32, bytes: Buffer) - case fileCdnRedirect(dcId: Int32, fileToken: Buffer, encryptionKey: Buffer, encryptionIv: Buffer, fileHashes: [Api.FileHash]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .file(let type, let mtime, let bytes): - if boxed { - buffer.appendInt32(157948117) - } - type.serialize(buffer, true) - serializeInt32(mtime, buffer: buffer, boxed: false) - serializeBytes(bytes, buffer: buffer, boxed: false) - break - case .fileCdnRedirect(let dcId, let fileToken, let encryptionKey, let encryptionIv, let fileHashes): - if boxed { - buffer.appendInt32(-242427324) - } - serializeInt32(dcId, buffer: buffer, boxed: false) - serializeBytes(fileToken, buffer: buffer, boxed: false) - serializeBytes(encryptionKey, buffer: buffer, boxed: false) - serializeBytes(encryptionIv, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(fileHashes.count)) - for item in fileHashes { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .file(let type, let mtime, let bytes): - return ("file", [("type", type as Any), ("mtime", mtime as Any), ("bytes", bytes as Any)]) - case .fileCdnRedirect(let dcId, let fileToken, let encryptionKey, let encryptionIv, let fileHashes): - return ("fileCdnRedirect", [("dcId", dcId as Any), ("fileToken", fileToken as Any), ("encryptionKey", encryptionKey as Any), ("encryptionIv", encryptionIv as Any), ("fileHashes", fileHashes as Any)]) - } - } - - public static func parse_file(_ reader: BufferReader) -> File? { - var _1: Api.storage.FileType? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.storage.FileType - } - var _2: Int32? - _2 = reader.readInt32() - var _3: Buffer? - _3 = parseBytes(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.upload.File.file(type: _1!, mtime: _2!, bytes: _3!) - } - public static func parse_fileCdnRedirect(_ reader: BufferReader) -> File? { - var _1: Int32? - _1 = reader.readInt32() - var _2: Buffer? - _2 = parseBytes(reader) - var _3: Buffer? - _3 = parseBytes(reader) - var _4: Buffer? - _4 = parseBytes(reader) - var _5: [Api.FileHash]? - if let _ = reader.readInt32() { - _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.FileHash.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.upload.File.fileCdnRedirect(dcId: _1!, fileToken: _2!, encryptionKey: _3!, encryptionIv: _4!, fileHashes: _5!) - } - - } -} -public extension Api.upload { - enum WebFile: TypeConstructorDescription { - case webFile(size: Int32, mimeType: String, fileType: Api.storage.FileType, mtime: Int32, bytes: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .webFile(let size, let mimeType, let fileType, let mtime, let bytes): - if boxed { - buffer.appendInt32(568808380) - } - serializeInt32(size, buffer: buffer, boxed: false) - serializeString(mimeType, buffer: buffer, boxed: false) - fileType.serialize(buffer, true) - serializeInt32(mtime, buffer: buffer, boxed: false) - serializeBytes(bytes, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .webFile(let size, let mimeType, let fileType, let mtime, let bytes): - return ("webFile", [("size", size as Any), ("mimeType", mimeType as Any), ("fileType", fileType as Any), ("mtime", mtime as Any), ("bytes", bytes as Any)]) - } - } - - public static func parse_webFile(_ reader: BufferReader) -> WebFile? { - var _1: Int32? - _1 = reader.readInt32() - var _2: String? - _2 = parseString(reader) - var _3: Api.storage.FileType? - if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.storage.FileType - } - var _4: Int32? - _4 = reader.readInt32() - var _5: Buffer? - _5 = parseBytes(reader) - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - let _c4 = _4 != nil - let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.upload.WebFile.webFile(size: _1!, mimeType: _2!, fileType: _3!, mtime: _4!, bytes: _5!) - } - - } -} -public extension Api.users { - enum SavedMusic: TypeConstructorDescription { - case savedMusic(count: Int32, documents: [Api.Document]) - case savedMusicNotModified(count: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .savedMusic(let count, let documents): - if boxed { - buffer.appendInt32(883094167) - } - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(documents.count)) - for item in documents { - item.serialize(buffer, true) - } - break - case .savedMusicNotModified(let count): - if boxed { - buffer.appendInt32(-477656412) - } - serializeInt32(count, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .savedMusic(let count, let documents): - return ("savedMusic", [("count", count as Any), ("documents", documents as Any)]) - case .savedMusicNotModified(let count): - return ("savedMusicNotModified", [("count", count as Any)]) - } - } - - public static func parse_savedMusic(_ reader: BufferReader) -> SavedMusic? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.Document]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.users.SavedMusic.savedMusic(count: _1!, documents: _2!) - } - public static func parse_savedMusicNotModified(_ reader: BufferReader) -> SavedMusic? { - var _1: Int32? - _1 = reader.readInt32() - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.users.SavedMusic.savedMusicNotModified(count: _1!) - } - - } -} -public extension Api.users { - enum UserFull: TypeConstructorDescription { - case userFull(fullUser: Api.UserFull, chats: [Api.Chat], users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .userFull(let fullUser, let chats, let users): - if boxed { - buffer.appendInt32(997004590) - } - fullUser.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(chats.count)) - for item in chats { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .userFull(let fullUser, let chats, let users): - return ("userFull", [("fullUser", fullUser as Any), ("chats", chats as Any), ("users", users as Any)]) - } - } - - public static func parse_userFull(_ reader: BufferReader) -> UserFull? { - var _1: Api.UserFull? - if let signature = reader.readInt32() { - _1 = Api.parse(reader, signature: signature) as? Api.UserFull - } - var _2: [Api.Chat]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) - } - var _3: [Api.User]? - if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.users.UserFull.userFull(fullUser: _1!, chats: _2!, users: _3!) - } - - } -} -public extension Api.users { - enum Users: TypeConstructorDescription { - case users(users: [Api.User]) - case usersSlice(count: Int32, users: [Api.User]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .users(let users): - if boxed { - buffer.appendInt32(1658259128) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - case .usersSlice(let count, let users): - if boxed { - buffer.appendInt32(828000628) - } - serializeInt32(count, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .users(let users): - return ("users", [("users", users as Any)]) - case .usersSlice(let count, let users): - return ("usersSlice", [("count", count as Any), ("users", users as Any)]) - } - } - - public static func parse_users(_ reader: BufferReader) -> Users? { - var _1: [Api.User]? - if let _ = reader.readInt32() { - _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - if !_c1 { return nil } - return Api.users.Users.users(users: _1!) - } - public static func parse_usersSlice(_ reader: BufferReader) -> Users? { - var _1: Int32? - _1 = reader.readInt32() - var _2: [Api.User]? - if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - let _c1 = _1 != nil - let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.users.Users.usersSlice(count: _1!, users: _2!) - } - } } diff --git a/submodules/TelegramApi/Sources/Api39.swift b/submodules/TelegramApi/Sources/Api39.swift index c9e087f8..6a352c8b 100644 --- a/submodules/TelegramApi/Sources/Api39.swift +++ b/submodules/TelegramApi/Sources/Api39.swift @@ -1,12818 +1,1446 @@ -public extension Api.functions.account { - static func acceptAuthorization(botId: Int64, scope: String, publicKey: String, valueHashes: [Api.SecureValueHash], credentials: Api.SecureCredentialsEncrypted) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-202552205) - serializeInt64(botId, buffer: buffer, boxed: false) - serializeString(scope, buffer: buffer, boxed: false) - serializeString(publicKey, buffer: buffer, boxed: false) +public extension Api.stories { + enum PeerStories: TypeConstructorDescription { + public class Cons_peerStories { + public var stories: Api.PeerStories + public var chats: [Api.Chat] + public var users: [Api.User] + public init(stories: Api.PeerStories, chats: [Api.Chat], users: [Api.User]) { + self.stories = stories + self.chats = chats + self.users = users + } + } + case peerStories(Cons_peerStories) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .peerStories(let _data): + if boxed { + buffer.appendInt32(-890861720) + } + _data.stories.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .peerStories(let _data): + return ("peerStories", [("stories", _data.stories as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_peerStories(_ reader: BufferReader) -> PeerStories? { + var _1: Api.PeerStories? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.PeerStories + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.stories.PeerStories.peerStories(Cons_peerStories(stories: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.stories { + enum Stories: TypeConstructorDescription { + public class Cons_stories { + public var flags: Int32 + public var count: Int32 + public var stories: [Api.StoryItem] + public var pinnedToTop: [Int32]? + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, count: Int32, stories: [Api.StoryItem], pinnedToTop: [Int32]?, chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.count = count + self.stories = stories + self.pinnedToTop = pinnedToTop + self.chats = chats + self.users = users + } + } + case stories(Cons_stories) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .stories(let _data): + if boxed { + buffer.appendInt32(1673780490) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.stories.count)) + for item in _data.stories { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(valueHashes.count)) - for item in valueHashes { - item.serialize(buffer, true) - } - credentials.serialize(buffer, true) - return (FunctionDescription(name: "account.acceptAuthorization", parameters: [("botId", String(describing: botId)), ("scope", String(describing: scope)), ("publicKey", String(describing: publicKey)), ("valueHashes", String(describing: valueHashes)), ("credentials", String(describing: credentials))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func cancelPasswordEmail() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1043606090) - - return (FunctionDescription(name: "account.cancelPasswordEmail", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func changeAuthorizationSettings(flags: Int32, hash: Int64, encryptedRequestsDisabled: Api.Bool?, callRequestsDisabled: Api.Bool?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1089766498) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {encryptedRequestsDisabled!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {callRequestsDisabled!.serialize(buffer, true)} - return (FunctionDescription(name: "account.changeAuthorizationSettings", parameters: [("flags", String(describing: flags)), ("hash", String(describing: hash)), ("encryptedRequestsDisabled", String(describing: encryptedRequestsDisabled)), ("callRequestsDisabled", String(describing: callRequestsDisabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func changePhone(phoneNumber: String, phoneCodeHash: String, phoneCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1891839707) - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(phoneCodeHash, buffer: buffer, boxed: false) - serializeString(phoneCode, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.changePhone", parameters: [("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("phoneCode", String(describing: phoneCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.User? in - let reader = BufferReader(buffer) - var result: Api.User? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.User - } - return result - }) - } -} -public extension Api.functions.account { - static func checkUsername(username: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(655677548) - serializeString(username, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.checkUsername", parameters: [("username", String(describing: username))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func clearRecentEmojiStatuses() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(404757166) - - return (FunctionDescription(name: "account.clearRecentEmojiStatuses", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func confirmPasswordEmail(code: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1881204448) - serializeString(code, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.confirmPasswordEmail", parameters: [("code", String(describing: code))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func confirmPhone(phoneCodeHash: String, phoneCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1596029123) - serializeString(phoneCodeHash, buffer: buffer, boxed: false) - serializeString(phoneCode, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.confirmPhone", parameters: [("phoneCodeHash", String(describing: phoneCodeHash)), ("phoneCode", String(describing: phoneCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func createBusinessChatLink(link: Api.InputBusinessChatLink) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2007898482) - link.serialize(buffer, true) - return (FunctionDescription(name: "account.createBusinessChatLink", parameters: [("link", String(describing: link))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.BusinessChatLink? in - let reader = BufferReader(buffer) - var result: Api.BusinessChatLink? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.BusinessChatLink - } - return result - }) - } -} -public extension Api.functions.account { - static func createTheme(flags: Int32, slug: String, title: String, document: Api.InputDocument?, settings: [Api.InputThemeSettings]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1697530880) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(slug, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {document!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(settings!.count)) - for item in settings! { - item.serialize(buffer, true) - }} - return (FunctionDescription(name: "account.createTheme", parameters: [("flags", String(describing: flags)), ("slug", String(describing: slug)), ("title", String(describing: title)), ("document", String(describing: document)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Theme? in - let reader = BufferReader(buffer) - var result: Api.Theme? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Theme - } - return result - }) - } -} -public extension Api.functions.account { - static func declinePasswordReset() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1284770294) - - return (FunctionDescription(name: "account.declinePasswordReset", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func deleteAccount(flags: Int32, reason: String, password: Api.InputCheckPasswordSRP?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1564422284) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(reason, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {password!.serialize(buffer, true)} - return (FunctionDescription(name: "account.deleteAccount", parameters: [("flags", String(describing: flags)), ("reason", String(describing: reason)), ("password", String(describing: password))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func deleteAutoSaveExceptions() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1404829728) - - return (FunctionDescription(name: "account.deleteAutoSaveExceptions", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func deleteBusinessChatLink(slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1611085428) - serializeString(slug, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.deleteBusinessChatLink", parameters: [("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func deletePasskey(id: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-172665281) - serializeString(id, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.deletePasskey", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func deleteSecureValue(types: [Api.SecureValueType]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1199522741) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(types.count)) - for item in types { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "account.deleteSecureValue", parameters: [("types", String(describing: types))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func disablePeerConnectedBot(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1581481689) - peer.serialize(buffer, true) - return (FunctionDescription(name: "account.disablePeerConnectedBot", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func editBusinessChatLink(slug: String, link: Api.InputBusinessChatLink) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1942744913) - serializeString(slug, buffer: buffer, boxed: false) - link.serialize(buffer, true) - return (FunctionDescription(name: "account.editBusinessChatLink", parameters: [("slug", String(describing: slug)), ("link", String(describing: link))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.BusinessChatLink? in - let reader = BufferReader(buffer) - var result: Api.BusinessChatLink? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.BusinessChatLink - } - return result - }) - } -} -public extension Api.functions.account { - static func finishTakeoutSession(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(489050862) - serializeInt32(flags, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.finishTakeoutSession", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func getAccountTTL() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(150761757) - - return (FunctionDescription(name: "account.getAccountTTL", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.AccountDaysTTL? in - let reader = BufferReader(buffer) - var result: Api.AccountDaysTTL? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.AccountDaysTTL - } - return result - }) - } -} -public extension Api.functions.account { - static func getAllSecureValues() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.SecureValue]>) { - let buffer = Buffer() - buffer.appendInt32(-1299661699) - - return (FunctionDescription(name: "account.getAllSecureValues", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.SecureValue]? in - let reader = BufferReader(buffer) - var result: [Api.SecureValue]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureValue.self) - } - return result - }) - } -} -public extension Api.functions.account { - static func getAuthorizationForm(botId: Int64, scope: String, publicKey: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1456907910) - serializeInt64(botId, buffer: buffer, boxed: false) - serializeString(scope, buffer: buffer, boxed: false) - serializeString(publicKey, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getAuthorizationForm", parameters: [("botId", String(describing: botId)), ("scope", String(describing: scope)), ("publicKey", String(describing: publicKey))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.AuthorizationForm? in - let reader = BufferReader(buffer) - var result: Api.account.AuthorizationForm? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.AuthorizationForm - } - return result - }) - } -} -public extension Api.functions.account { - static func getAuthorizations() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-484392616) - - return (FunctionDescription(name: "account.getAuthorizations", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.Authorizations? in - let reader = BufferReader(buffer) - var result: Api.account.Authorizations? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.Authorizations - } - return result - }) - } -} -public extension Api.functions.account { - static func getAutoDownloadSettings() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1457130303) - - return (FunctionDescription(name: "account.getAutoDownloadSettings", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.AutoDownloadSettings? in - let reader = BufferReader(buffer) - var result: Api.account.AutoDownloadSettings? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.AutoDownloadSettings - } - return result - }) - } -} -public extension Api.functions.account { - static func getAutoSaveSettings() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1379156774) - - return (FunctionDescription(name: "account.getAutoSaveSettings", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.AutoSaveSettings? in - let reader = BufferReader(buffer) - var result: Api.account.AutoSaveSettings? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.AutoSaveSettings - } - return result - }) - } -} -public extension Api.functions.account { - static func getBotBusinessConnection(connectionId: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1990746736) - serializeString(connectionId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getBotBusinessConnection", parameters: [("connectionId", String(describing: connectionId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.account { - static func getBusinessChatLinks() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1869667809) - - return (FunctionDescription(name: "account.getBusinessChatLinks", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.BusinessChatLinks? in - let reader = BufferReader(buffer) - var result: Api.account.BusinessChatLinks? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.BusinessChatLinks - } - return result - }) - } -} -public extension Api.functions.account { - static func getChannelDefaultEmojiStatuses(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1999087573) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getChannelDefaultEmojiStatuses", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.EmojiStatuses? in - let reader = BufferReader(buffer) - var result: Api.account.EmojiStatuses? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.EmojiStatuses - } - return result - }) - } -} -public extension Api.functions.account { - static func getChannelRestrictedStatusEmojis(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(900325589) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getChannelRestrictedStatusEmojis", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiList? in - let reader = BufferReader(buffer) - var result: Api.EmojiList? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.EmojiList - } - return result - }) - } -} -public extension Api.functions.account { - static func getChatThemes(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-700916087) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getChatThemes", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.Themes? in - let reader = BufferReader(buffer) - var result: Api.account.Themes? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.Themes - } - return result - }) - } -} -public extension Api.functions.account { - static func getCollectibleEmojiStatuses(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(779830595) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getCollectibleEmojiStatuses", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.EmojiStatuses? in - let reader = BufferReader(buffer) - var result: Api.account.EmojiStatuses? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.EmojiStatuses - } - return result - }) - } -} -public extension Api.functions.account { - static func getConnectedBots() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1319421967) - - return (FunctionDescription(name: "account.getConnectedBots", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.ConnectedBots? in - let reader = BufferReader(buffer) - var result: Api.account.ConnectedBots? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.ConnectedBots - } - return result - }) - } -} -public extension Api.functions.account { - static func getContactSignUpNotification() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1626880216) - - return (FunctionDescription(name: "account.getContactSignUpNotification", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func getContentSettings() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1952756306) - - return (FunctionDescription(name: "account.getContentSettings", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.ContentSettings? in - let reader = BufferReader(buffer) - var result: Api.account.ContentSettings? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.ContentSettings - } - return result - }) - } -} -public extension Api.functions.account { - static func getDefaultBackgroundEmojis(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1509246514) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getDefaultBackgroundEmojis", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiList? in - let reader = BufferReader(buffer) - var result: Api.EmojiList? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.EmojiList - } - return result - }) - } -} -public extension Api.functions.account { - static func getDefaultEmojiStatuses(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-696962170) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getDefaultEmojiStatuses", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.EmojiStatuses? in - let reader = BufferReader(buffer) - var result: Api.account.EmojiStatuses? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.EmojiStatuses - } - return result - }) - } -} -public extension Api.functions.account { - static func getDefaultGroupPhotoEmojis(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1856479058) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getDefaultGroupPhotoEmojis", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiList? in - let reader = BufferReader(buffer) - var result: Api.EmojiList? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.EmojiList - } - return result - }) - } -} -public extension Api.functions.account { - static func getDefaultProfilePhotoEmojis(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-495647960) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getDefaultProfilePhotoEmojis", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiList? in - let reader = BufferReader(buffer) - var result: Api.EmojiList? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.EmojiList - } - return result - }) - } -} -public extension Api.functions.account { - static func getGlobalPrivacySettings() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-349483786) - - return (FunctionDescription(name: "account.getGlobalPrivacySettings", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.GlobalPrivacySettings? in - let reader = BufferReader(buffer) - var result: Api.GlobalPrivacySettings? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.GlobalPrivacySettings - } - return result - }) - } -} -public extension Api.functions.account { - static func getMultiWallPapers(wallpapers: [Api.InputWallPaper]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.WallPaper]>) { - let buffer = Buffer() - buffer.appendInt32(1705865692) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(wallpapers.count)) - for item in wallpapers { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "account.getMultiWallPapers", parameters: [("wallpapers", String(describing: wallpapers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.WallPaper]? in - let reader = BufferReader(buffer) - var result: [Api.WallPaper]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.WallPaper.self) - } - return result - }) - } -} -public extension Api.functions.account { - static func getNotifyExceptions(flags: Int32, peer: Api.InputNotifyPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1398240377) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {peer!.serialize(buffer, true)} - return (FunctionDescription(name: "account.getNotifyExceptions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.account { - static func getNotifySettings(peer: Api.InputNotifyPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(313765169) - peer.serialize(buffer, true) - return (FunctionDescription(name: "account.getNotifySettings", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.PeerNotifySettings? in - let reader = BufferReader(buffer) - var result: Api.PeerNotifySettings? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.PeerNotifySettings - } - return result - }) - } -} -public extension Api.functions.account { - static func getPaidMessagesRevenue(flags: Int32, parentPeer: Api.InputPeer?, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(431639143) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {parentPeer!.serialize(buffer, true)} - userId.serialize(buffer, true) - return (FunctionDescription(name: "account.getPaidMessagesRevenue", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.PaidMessagesRevenue? in - let reader = BufferReader(buffer) - var result: Api.account.PaidMessagesRevenue? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.PaidMessagesRevenue - } - return result - }) - } -} -public extension Api.functions.account { - static func getPasskeys() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-367063982) - - return (FunctionDescription(name: "account.getPasskeys", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.Passkeys? in - let reader = BufferReader(buffer) - var result: Api.account.Passkeys? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.Passkeys - } - return result - }) - } -} -public extension Api.functions.account { - static func getPassword() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1418342645) - - return (FunctionDescription(name: "account.getPassword", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.Password? in - let reader = BufferReader(buffer) - var result: Api.account.Password? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.Password - } - return result - }) - } -} -public extension Api.functions.account { - static func getPasswordSettings(password: Api.InputCheckPasswordSRP) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1663767815) - password.serialize(buffer, true) - return (FunctionDescription(name: "account.getPasswordSettings", parameters: [("password", String(describing: password))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.PasswordSettings? in - let reader = BufferReader(buffer) - var result: Api.account.PasswordSettings? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.PasswordSettings - } - return result - }) - } -} -public extension Api.functions.account { - static func getPrivacy(key: Api.InputPrivacyKey) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-623130288) - key.serialize(buffer, true) - return (FunctionDescription(name: "account.getPrivacy", parameters: [("key", String(describing: key))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.PrivacyRules? in - let reader = BufferReader(buffer) - var result: Api.account.PrivacyRules? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.PrivacyRules - } - return result - }) - } -} -public extension Api.functions.account { - static func getReactionsNotifySettings() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(115172684) - - return (FunctionDescription(name: "account.getReactionsNotifySettings", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ReactionsNotifySettings? in - let reader = BufferReader(buffer) - var result: Api.ReactionsNotifySettings? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.ReactionsNotifySettings - } - return result - }) - } -} -public extension Api.functions.account { - static func getRecentEmojiStatuses(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(257392901) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getRecentEmojiStatuses", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.EmojiStatuses? in - let reader = BufferReader(buffer) - var result: Api.account.EmojiStatuses? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.EmojiStatuses - } - return result - }) - } -} -public extension Api.functions.account { - static func getSavedMusicIds(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-526557265) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getSavedMusicIds", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.SavedMusicIds? in - let reader = BufferReader(buffer) - var result: Api.account.SavedMusicIds? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.SavedMusicIds - } - return result - }) - } -} -public extension Api.functions.account { - static func getSavedRingtones(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-510647672) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getSavedRingtones", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.SavedRingtones? in - let reader = BufferReader(buffer) - var result: Api.account.SavedRingtones? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.SavedRingtones - } - return result - }) - } -} -public extension Api.functions.account { - static func getSecureValue(types: [Api.SecureValueType]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.SecureValue]>) { - let buffer = Buffer() - buffer.appendInt32(1936088002) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(types.count)) - for item in types { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "account.getSecureValue", parameters: [("types", String(describing: types))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.SecureValue]? in - let reader = BufferReader(buffer) - var result: [Api.SecureValue]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureValue.self) - } - return result - }) - } -} -public extension Api.functions.account { - static func getTheme(format: String, theme: Api.InputTheme) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(978872812) - serializeString(format, buffer: buffer, boxed: false) - theme.serialize(buffer, true) - return (FunctionDescription(name: "account.getTheme", parameters: [("format", String(describing: format)), ("theme", String(describing: theme))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Theme? in - let reader = BufferReader(buffer) - var result: Api.Theme? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Theme - } - return result - }) - } -} -public extension Api.functions.account { - static func getThemes(format: String, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1913054296) - serializeString(format, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getThemes", parameters: [("format", String(describing: format)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.Themes? in - let reader = BufferReader(buffer) - var result: Api.account.Themes? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.Themes - } - return result - }) - } -} -public extension Api.functions.account { - static func getTmpPassword(password: Api.InputCheckPasswordSRP, period: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1151208273) - password.serialize(buffer, true) - serializeInt32(period, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getTmpPassword", parameters: [("password", String(describing: password)), ("period", String(describing: period))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.TmpPassword? in - let reader = BufferReader(buffer) - var result: Api.account.TmpPassword? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.TmpPassword - } - return result - }) - } -} -public extension Api.functions.account { - static func getUniqueGiftChatThemes(offset: String, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-466818615) - serializeString(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getUniqueGiftChatThemes", parameters: [("offset", String(describing: offset)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.ChatThemes? in - let reader = BufferReader(buffer) - var result: Api.account.ChatThemes? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.ChatThemes - } - return result - }) - } -} -public extension Api.functions.account { - static func getWallPaper(wallpaper: Api.InputWallPaper) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-57811990) - wallpaper.serialize(buffer, true) - return (FunctionDescription(name: "account.getWallPaper", parameters: [("wallpaper", String(describing: wallpaper))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.WallPaper? in - let reader = BufferReader(buffer) - var result: Api.WallPaper? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.WallPaper - } - return result - }) - } -} -public extension Api.functions.account { - static func getWallPapers(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(127302966) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.getWallPapers", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.WallPapers? in - let reader = BufferReader(buffer) - var result: Api.account.WallPapers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.WallPapers - } - return result - }) - } -} -public extension Api.functions.account { - static func getWebAuthorizations() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(405695855) - - return (FunctionDescription(name: "account.getWebAuthorizations", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.WebAuthorizations? in - let reader = BufferReader(buffer) - var result: Api.account.WebAuthorizations? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.WebAuthorizations - } - return result - }) - } -} -public extension Api.functions.account { - static func initPasskeyRegistration() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1117079528) - - return (FunctionDescription(name: "account.initPasskeyRegistration", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.PasskeyRegistrationOptions? in - let reader = BufferReader(buffer) - var result: Api.account.PasskeyRegistrationOptions? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.PasskeyRegistrationOptions - } - return result - }) - } -} -public extension Api.functions.account { - static func initTakeoutSession(flags: Int32, fileMaxSize: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1896617296) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 5) != 0 {serializeInt64(fileMaxSize!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "account.initTakeoutSession", parameters: [("flags", String(describing: flags)), ("fileMaxSize", String(describing: fileMaxSize))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.Takeout? in - let reader = BufferReader(buffer) - var result: Api.account.Takeout? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.Takeout - } - return result - }) - } -} -public extension Api.functions.account { - static func installTheme(flags: Int32, theme: Api.InputTheme?, format: String?, baseTheme: Api.BaseTheme?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-953697477) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {theme!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(format!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {baseTheme!.serialize(buffer, true)} - return (FunctionDescription(name: "account.installTheme", parameters: [("flags", String(describing: flags)), ("theme", String(describing: theme)), ("format", String(describing: format)), ("baseTheme", String(describing: baseTheme))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func installWallPaper(wallpaper: Api.InputWallPaper, settings: Api.WallPaperSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-18000023) - wallpaper.serialize(buffer, true) - settings.serialize(buffer, true) - return (FunctionDescription(name: "account.installWallPaper", parameters: [("wallpaper", String(describing: wallpaper)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func invalidateSignInCodes(codes: [String]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-896866118) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(codes.count)) - for item in codes { - serializeString(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "account.invalidateSignInCodes", parameters: [("codes", String(describing: codes))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func registerDevice(flags: Int32, tokenType: Int32, token: String, appSandbox: Api.Bool, secret: Buffer, otherUids: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-326762118) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(tokenType, buffer: buffer, boxed: false) - serializeString(token, buffer: buffer, boxed: false) - appSandbox.serialize(buffer, true) - serializeBytes(secret, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(otherUids.count)) - for item in otherUids { - serializeInt64(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "account.registerDevice", parameters: [("flags", String(describing: flags)), ("tokenType", String(describing: tokenType)), ("token", String(describing: token)), ("appSandbox", String(describing: appSandbox)), ("secret", String(describing: secret)), ("otherUids", String(describing: otherUids))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func registerPasskey(credential: Api.InputPasskeyCredential) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1437867990) - credential.serialize(buffer, true) - return (FunctionDescription(name: "account.registerPasskey", parameters: [("credential", String(describing: credential))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Passkey? in - let reader = BufferReader(buffer) - var result: Api.Passkey? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Passkey - } - return result - }) - } -} -public extension Api.functions.account { - static func reorderUsernames(order: [String]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-279966037) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order.count)) - for item in order { - serializeString(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "account.reorderUsernames", parameters: [("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func reportPeer(peer: Api.InputPeer, reason: Api.ReportReason, message: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-977650298) - peer.serialize(buffer, true) - reason.serialize(buffer, true) - serializeString(message, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.reportPeer", parameters: [("peer", String(describing: peer)), ("reason", String(describing: reason)), ("message", String(describing: message))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func reportProfilePhoto(peer: Api.InputPeer, photoId: Api.InputPhoto, reason: Api.ReportReason, message: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-91437323) - peer.serialize(buffer, true) - photoId.serialize(buffer, true) - reason.serialize(buffer, true) - serializeString(message, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.reportProfilePhoto", parameters: [("peer", String(describing: peer)), ("photoId", String(describing: photoId)), ("reason", String(describing: reason)), ("message", String(describing: message))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func resendPasswordEmail() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2055154197) - - return (FunctionDescription(name: "account.resendPasswordEmail", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func resetAuthorization(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-545786948) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.resetAuthorization", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func resetNotifySettings() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-612493497) - - return (FunctionDescription(name: "account.resetNotifySettings", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func resetPassword() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1828139493) - - return (FunctionDescription(name: "account.resetPassword", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.ResetPasswordResult? in - let reader = BufferReader(buffer) - var result: Api.account.ResetPasswordResult? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.ResetPasswordResult - } - return result - }) - } -} -public extension Api.functions.account { - static func resetWallPapers() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1153722364) - - return (FunctionDescription(name: "account.resetWallPapers", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func resetWebAuthorization(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(755087855) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.resetWebAuthorization", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func resetWebAuthorizations() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1747789204) - - return (FunctionDescription(name: "account.resetWebAuthorizations", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func resolveBusinessChatLink(slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1418913262) - serializeString(slug, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.resolveBusinessChatLink", parameters: [("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.ResolvedBusinessChatLinks? in - let reader = BufferReader(buffer) - var result: Api.account.ResolvedBusinessChatLinks? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.ResolvedBusinessChatLinks - } - return result - }) - } -} -public extension Api.functions.account { - static func saveAutoDownloadSettings(flags: Int32, settings: Api.AutoDownloadSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1995661875) - serializeInt32(flags, buffer: buffer, boxed: false) - settings.serialize(buffer, true) - return (FunctionDescription(name: "account.saveAutoDownloadSettings", parameters: [("flags", String(describing: flags)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func saveAutoSaveSettings(flags: Int32, peer: Api.InputPeer?, settings: Api.AutoSaveSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-694451359) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {peer!.serialize(buffer, true)} - settings.serialize(buffer, true) - return (FunctionDescription(name: "account.saveAutoSaveSettings", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func saveMusic(flags: Int32, id: Api.InputDocument, afterId: Api.InputDocument?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1301859671) - serializeInt32(flags, buffer: buffer, boxed: false) - id.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {afterId!.serialize(buffer, true)} - return (FunctionDescription(name: "account.saveMusic", parameters: [("flags", String(describing: flags)), ("id", String(describing: id)), ("afterId", String(describing: afterId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func saveRingtone(id: Api.InputDocument, unsave: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1038768899) - id.serialize(buffer, true) - unsave.serialize(buffer, true) - return (FunctionDescription(name: "account.saveRingtone", parameters: [("id", String(describing: id)), ("unsave", String(describing: unsave))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.SavedRingtone? in - let reader = BufferReader(buffer) - var result: Api.account.SavedRingtone? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.SavedRingtone - } - return result - }) - } -} -public extension Api.functions.account { - static func saveSecureValue(value: Api.InputSecureValue, secureSecretId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1986010339) - value.serialize(buffer, true) - serializeInt64(secureSecretId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.saveSecureValue", parameters: [("value", String(describing: value)), ("secureSecretId", String(describing: secureSecretId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.SecureValue? in - let reader = BufferReader(buffer) - var result: Api.SecureValue? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.SecureValue - } - return result - }) - } -} -public extension Api.functions.account { - static func saveTheme(theme: Api.InputTheme, unsave: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-229175188) - theme.serialize(buffer, true) - unsave.serialize(buffer, true) - return (FunctionDescription(name: "account.saveTheme", parameters: [("theme", String(describing: theme)), ("unsave", String(describing: unsave))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func saveWallPaper(wallpaper: Api.InputWallPaper, unsave: Api.Bool, settings: Api.WallPaperSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1817860919) - wallpaper.serialize(buffer, true) - unsave.serialize(buffer, true) - settings.serialize(buffer, true) - return (FunctionDescription(name: "account.saveWallPaper", parameters: [("wallpaper", String(describing: wallpaper)), ("unsave", String(describing: unsave)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func sendChangePhoneCode(phoneNumber: String, settings: Api.CodeSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2108208411) - serializeString(phoneNumber, buffer: buffer, boxed: false) - settings.serialize(buffer, true) - return (FunctionDescription(name: "account.sendChangePhoneCode", parameters: [("phoneNumber", String(describing: phoneNumber)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.SentCode? in - let reader = BufferReader(buffer) - var result: Api.auth.SentCode? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.SentCode - } - return result - }) - } -} -public extension Api.functions.account { - static func sendConfirmPhoneCode(hash: String, settings: Api.CodeSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(457157256) - serializeString(hash, buffer: buffer, boxed: false) - settings.serialize(buffer, true) - return (FunctionDescription(name: "account.sendConfirmPhoneCode", parameters: [("hash", String(describing: hash)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.SentCode? in - let reader = BufferReader(buffer) - var result: Api.auth.SentCode? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.SentCode - } - return result - }) - } -} -public extension Api.functions.account { - static func sendVerifyEmailCode(purpose: Api.EmailVerifyPurpose, email: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1730136133) - purpose.serialize(buffer, true) - serializeString(email, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.sendVerifyEmailCode", parameters: [("purpose", String(describing: purpose)), ("email", String(describing: email))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.SentEmailCode? in - let reader = BufferReader(buffer) - var result: Api.account.SentEmailCode? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.SentEmailCode - } - return result - }) - } -} -public extension Api.functions.account { - static func sendVerifyPhoneCode(phoneNumber: String, settings: Api.CodeSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1516022023) - serializeString(phoneNumber, buffer: buffer, boxed: false) - settings.serialize(buffer, true) - return (FunctionDescription(name: "account.sendVerifyPhoneCode", parameters: [("phoneNumber", String(describing: phoneNumber)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.SentCode? in - let reader = BufferReader(buffer) - var result: Api.auth.SentCode? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.SentCode - } - return result - }) - } -} -public extension Api.functions.account { - static func setAccountTTL(ttl: Api.AccountDaysTTL) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(608323678) - ttl.serialize(buffer, true) - return (FunctionDescription(name: "account.setAccountTTL", parameters: [("ttl", String(describing: ttl))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func setAuthorizationTTL(authorizationTtlDays: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1081501024) - serializeInt32(authorizationTtlDays, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.setAuthorizationTTL", parameters: [("authorizationTtlDays", String(describing: authorizationTtlDays))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func setContactSignUpNotification(silent: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-806076575) - silent.serialize(buffer, true) - return (FunctionDescription(name: "account.setContactSignUpNotification", parameters: [("silent", String(describing: silent))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func setContentSettings(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1250643605) - serializeInt32(flags, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.setContentSettings", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func setGlobalPrivacySettings(settings: Api.GlobalPrivacySettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(517647042) - settings.serialize(buffer, true) - return (FunctionDescription(name: "account.setGlobalPrivacySettings", parameters: [("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.GlobalPrivacySettings? in - let reader = BufferReader(buffer) - var result: Api.GlobalPrivacySettings? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.GlobalPrivacySettings - } - return result - }) - } -} -public extension Api.functions.account { - static func setMainProfileTab(tab: Api.ProfileTab) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1575909552) - tab.serialize(buffer, true) - return (FunctionDescription(name: "account.setMainProfileTab", parameters: [("tab", String(describing: tab))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func setPrivacy(key: Api.InputPrivacyKey, rules: [Api.InputPrivacyRule]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-906486552) - key.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(rules.count)) - for item in rules { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "account.setPrivacy", parameters: [("key", String(describing: key)), ("rules", String(describing: rules))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.PrivacyRules? in - let reader = BufferReader(buffer) - var result: Api.account.PrivacyRules? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.PrivacyRules - } - return result - }) - } -} -public extension Api.functions.account { - static func setReactionsNotifySettings(settings: Api.ReactionsNotifySettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(829220168) - settings.serialize(buffer, true) - return (FunctionDescription(name: "account.setReactionsNotifySettings", parameters: [("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ReactionsNotifySettings? in - let reader = BufferReader(buffer) - var result: Api.ReactionsNotifySettings? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.ReactionsNotifySettings - } - return result - }) - } -} -public extension Api.functions.account { - static func toggleConnectedBotPaused(peer: Api.InputPeer, paused: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1684934807) - peer.serialize(buffer, true) - paused.serialize(buffer, true) - return (FunctionDescription(name: "account.toggleConnectedBotPaused", parameters: [("peer", String(describing: peer)), ("paused", String(describing: paused))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func toggleNoPaidMessagesException(flags: Int32, parentPeer: Api.InputPeer?, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-30483850) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {parentPeer!.serialize(buffer, true)} - userId.serialize(buffer, true) - return (FunctionDescription(name: "account.toggleNoPaidMessagesException", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func toggleSponsoredMessages(enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1176919155) - enabled.serialize(buffer, true) - return (FunctionDescription(name: "account.toggleSponsoredMessages", parameters: [("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func toggleUsername(username: String, active: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1490465654) - serializeString(username, buffer: buffer, boxed: false) - active.serialize(buffer, true) - return (FunctionDescription(name: "account.toggleUsername", parameters: [("username", String(describing: username)), ("active", String(describing: active))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func unregisterDevice(tokenType: Int32, token: String, otherUids: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1779249670) - serializeInt32(tokenType, buffer: buffer, boxed: false) - serializeString(token, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(otherUids.count)) - for item in otherUids { - serializeInt64(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "account.unregisterDevice", parameters: [("tokenType", String(describing: tokenType)), ("token", String(describing: token)), ("otherUids", String(describing: otherUids))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func updateBirthday(flags: Int32, birthday: Api.Birthday?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-865203183) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {birthday!.serialize(buffer, true)} - return (FunctionDescription(name: "account.updateBirthday", parameters: [("flags", String(describing: flags)), ("birthday", String(describing: birthday))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func updateBusinessAwayMessage(flags: Int32, message: Api.InputBusinessAwayMessage?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1570078811) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {message!.serialize(buffer, true)} - return (FunctionDescription(name: "account.updateBusinessAwayMessage", parameters: [("flags", String(describing: flags)), ("message", String(describing: message))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func updateBusinessGreetingMessage(flags: Int32, message: Api.InputBusinessGreetingMessage?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1724755908) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {message!.serialize(buffer, true)} - return (FunctionDescription(name: "account.updateBusinessGreetingMessage", parameters: [("flags", String(describing: flags)), ("message", String(describing: message))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func updateBusinessIntro(flags: Int32, intro: Api.InputBusinessIntro?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1508585420) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {intro!.serialize(buffer, true)} - return (FunctionDescription(name: "account.updateBusinessIntro", parameters: [("flags", String(describing: flags)), ("intro", String(describing: intro))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func updateBusinessLocation(flags: Int32, geoPoint: Api.InputGeoPoint?, address: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1637149926) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {geoPoint!.serialize(buffer, true)} - if Int(flags) & Int(1 << 0) != 0 {serializeString(address!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "account.updateBusinessLocation", parameters: [("flags", String(describing: flags)), ("geoPoint", String(describing: geoPoint)), ("address", String(describing: address))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func updateBusinessWorkHours(flags: Int32, businessWorkHours: Api.BusinessWorkHours?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1258348646) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {businessWorkHours!.serialize(buffer, true)} - return (FunctionDescription(name: "account.updateBusinessWorkHours", parameters: [("flags", String(describing: flags)), ("businessWorkHours", String(describing: businessWorkHours))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func updateColor(flags: Int32, color: Api.PeerColor?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1749885262) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {color!.serialize(buffer, true)} - return (FunctionDescription(name: "account.updateColor", parameters: [("flags", String(describing: flags)), ("color", String(describing: color))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func updateConnectedBot(flags: Int32, rights: Api.BusinessBotRights?, bot: Api.InputUser, recipients: Api.InputBusinessBotRecipients) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1721797758) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {rights!.serialize(buffer, true)} - bot.serialize(buffer, true) - recipients.serialize(buffer, true) - return (FunctionDescription(name: "account.updateConnectedBot", parameters: [("flags", String(describing: flags)), ("rights", String(describing: rights)), ("bot", String(describing: bot)), ("recipients", String(describing: recipients))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.account { - static func updateDeviceLocked(period: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(954152242) - serializeInt32(period, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.updateDeviceLocked", parameters: [("period", String(describing: period))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func updateEmojiStatus(emojiStatus: Api.EmojiStatus) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-70001045) - emojiStatus.serialize(buffer, true) - return (FunctionDescription(name: "account.updateEmojiStatus", parameters: [("emojiStatus", String(describing: emojiStatus))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func updateNotifySettings(peer: Api.InputNotifyPeer, settings: Api.InputPeerNotifySettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2067899501) - peer.serialize(buffer, true) - settings.serialize(buffer, true) - return (FunctionDescription(name: "account.updateNotifySettings", parameters: [("peer", String(describing: peer)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func updatePasswordSettings(password: Api.InputCheckPasswordSRP, newSettings: Api.account.PasswordInputSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1516564433) - password.serialize(buffer, true) - newSettings.serialize(buffer, true) - return (FunctionDescription(name: "account.updatePasswordSettings", parameters: [("password", String(describing: password)), ("newSettings", String(describing: newSettings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func updatePersonalChannel(channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-649919008) - channel.serialize(buffer, true) - return (FunctionDescription(name: "account.updatePersonalChannel", parameters: [("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func updateProfile(flags: Int32, firstName: String?, lastName: String?, about: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2018596725) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(firstName!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(lastName!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(about!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "account.updateProfile", parameters: [("flags", String(describing: flags)), ("firstName", String(describing: firstName)), ("lastName", String(describing: lastName)), ("about", String(describing: about))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.User? in - let reader = BufferReader(buffer) - var result: Api.User? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.User - } - return result - }) - } -} -public extension Api.functions.account { - static func updateStatus(offline: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1713919532) - offline.serialize(buffer, true) - return (FunctionDescription(name: "account.updateStatus", parameters: [("offline", String(describing: offline))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.account { - static func updateTheme(flags: Int32, format: String, theme: Api.InputTheme, slug: String?, title: String?, document: Api.InputDocument?, settings: [Api.InputThemeSettings]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(737414348) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(format, buffer: buffer, boxed: false) - theme.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeString(slug!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {document!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(settings!.count)) - for item in settings! { - item.serialize(buffer, true) - }} - return (FunctionDescription(name: "account.updateTheme", parameters: [("flags", String(describing: flags)), ("format", String(describing: format)), ("theme", String(describing: theme)), ("slug", String(describing: slug)), ("title", String(describing: title)), ("document", String(describing: document)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Theme? in - let reader = BufferReader(buffer) - var result: Api.Theme? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Theme - } - return result - }) - } -} -public extension Api.functions.account { - static func updateUsername(username: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1040964988) - serializeString(username, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.updateUsername", parameters: [("username", String(describing: username))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.User? in - let reader = BufferReader(buffer) - var result: Api.User? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.User - } - return result - }) - } -} -public extension Api.functions.account { - static func uploadRingtone(file: Api.InputFile, fileName: String, mimeType: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2095414366) - file.serialize(buffer, true) - serializeString(fileName, buffer: buffer, boxed: false) - serializeString(mimeType, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.uploadRingtone", parameters: [("file", String(describing: file)), ("fileName", String(describing: fileName)), ("mimeType", String(describing: mimeType))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Document? in - let reader = BufferReader(buffer) - var result: Api.Document? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Document - } - return result - }) - } -} -public extension Api.functions.account { - static func uploadTheme(flags: Int32, file: Api.InputFile, thumb: Api.InputFile?, fileName: String, mimeType: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(473805619) - serializeInt32(flags, buffer: buffer, boxed: false) - file.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {thumb!.serialize(buffer, true)} - serializeString(fileName, buffer: buffer, boxed: false) - serializeString(mimeType, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.uploadTheme", parameters: [("flags", String(describing: flags)), ("file", String(describing: file)), ("thumb", String(describing: thumb)), ("fileName", String(describing: fileName)), ("mimeType", String(describing: mimeType))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Document? in - let reader = BufferReader(buffer) - var result: Api.Document? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Document - } - return result - }) - } -} -public extension Api.functions.account { - static func uploadWallPaper(flags: Int32, file: Api.InputFile, mimeType: String, settings: Api.WallPaperSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-476410109) - serializeInt32(flags, buffer: buffer, boxed: false) - file.serialize(buffer, true) - serializeString(mimeType, buffer: buffer, boxed: false) - settings.serialize(buffer, true) - return (FunctionDescription(name: "account.uploadWallPaper", parameters: [("flags", String(describing: flags)), ("file", String(describing: file)), ("mimeType", String(describing: mimeType)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.WallPaper? in - let reader = BufferReader(buffer) - var result: Api.WallPaper? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.WallPaper - } - return result - }) - } -} -public extension Api.functions.account { - static func verifyEmail(purpose: Api.EmailVerifyPurpose, verification: Api.EmailVerification) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(53322959) - purpose.serialize(buffer, true) - verification.serialize(buffer, true) - return (FunctionDescription(name: "account.verifyEmail", parameters: [("purpose", String(describing: purpose)), ("verification", String(describing: verification))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.EmailVerified? in - let reader = BufferReader(buffer) - var result: Api.account.EmailVerified? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.account.EmailVerified - } - return result - }) - } -} -public extension Api.functions.account { - static func verifyPhone(phoneNumber: String, phoneCodeHash: String, phoneCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1305716726) - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(phoneCodeHash, buffer: buffer, boxed: false) - serializeString(phoneCode, buffer: buffer, boxed: false) - return (FunctionDescription(name: "account.verifyPhone", parameters: [("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("phoneCode", String(describing: phoneCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.auth { - static func acceptLoginToken(token: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-392909491) - serializeBytes(token, buffer: buffer, boxed: false) - return (FunctionDescription(name: "auth.acceptLoginToken", parameters: [("token", String(describing: token))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Authorization? in - let reader = BufferReader(buffer) - var result: Api.Authorization? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Authorization - } - return result - }) - } -} -public extension Api.functions.auth { - static func bindTempAuthKey(permAuthKeyId: Int64, nonce: Int64, expiresAt: Int32, encryptedMessage: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-841733627) - serializeInt64(permAuthKeyId, buffer: buffer, boxed: false) - serializeInt64(nonce, buffer: buffer, boxed: false) - serializeInt32(expiresAt, buffer: buffer, boxed: false) - serializeBytes(encryptedMessage, buffer: buffer, boxed: false) - return (FunctionDescription(name: "auth.bindTempAuthKey", parameters: [("permAuthKeyId", String(describing: permAuthKeyId)), ("nonce", String(describing: nonce)), ("expiresAt", String(describing: expiresAt)), ("encryptedMessage", String(describing: encryptedMessage))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.auth { - static func cancelCode(phoneNumber: String, phoneCodeHash: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(520357240) - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(phoneCodeHash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "auth.cancelCode", parameters: [("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.auth { - static func checkPaidAuth(phoneNumber: String, phoneCodeHash: String, formId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1457889180) - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(phoneCodeHash, buffer: buffer, boxed: false) - serializeInt64(formId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "auth.checkPaidAuth", parameters: [("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("formId", String(describing: formId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.SentCode? in - let reader = BufferReader(buffer) - var result: Api.auth.SentCode? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.SentCode - } - return result - }) - } -} -public extension Api.functions.auth { - static func checkPassword(password: Api.InputCheckPasswordSRP) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-779399914) - password.serialize(buffer, true) - return (FunctionDescription(name: "auth.checkPassword", parameters: [("password", String(describing: password))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in - let reader = BufferReader(buffer) - var result: Api.auth.Authorization? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.Authorization - } - return result - }) - } -} -public extension Api.functions.auth { - static func checkRecoveryPassword(code: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(221691769) - serializeString(code, buffer: buffer, boxed: false) - return (FunctionDescription(name: "auth.checkRecoveryPassword", parameters: [("code", String(describing: code))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.auth { - static func dropTempAuthKeys(exceptAuthKeys: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1907842680) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(exceptAuthKeys.count)) - for item in exceptAuthKeys { - serializeInt64(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "auth.dropTempAuthKeys", parameters: [("exceptAuthKeys", String(describing: exceptAuthKeys))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.auth { - static func exportAuthorization(dcId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-440401971) - serializeInt32(dcId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "auth.exportAuthorization", parameters: [("dcId", String(describing: dcId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.ExportedAuthorization? in - let reader = BufferReader(buffer) - var result: Api.auth.ExportedAuthorization? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.ExportedAuthorization - } - return result - }) - } -} -public extension Api.functions.auth { - static func exportLoginToken(apiId: Int32, apiHash: String, exceptIds: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1210022402) - serializeInt32(apiId, buffer: buffer, boxed: false) - serializeString(apiHash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(exceptIds.count)) - for item in exceptIds { - serializeInt64(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "auth.exportLoginToken", parameters: [("apiId", String(describing: apiId)), ("apiHash", String(describing: apiHash)), ("exceptIds", String(describing: exceptIds))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.LoginToken? in - let reader = BufferReader(buffer) - var result: Api.auth.LoginToken? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.LoginToken - } - return result - }) - } -} -public extension Api.functions.auth { - static func finishPasskeyLogin(flags: Int32, credential: Api.InputPasskeyCredential, fromDcId: Int32?, fromAuthKeyId: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1739084537) - serializeInt32(flags, buffer: buffer, boxed: false) - credential.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(fromDcId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(fromAuthKeyId!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "auth.finishPasskeyLogin", parameters: [("flags", String(describing: flags)), ("credential", String(describing: credential)), ("fromDcId", String(describing: fromDcId)), ("fromAuthKeyId", String(describing: fromAuthKeyId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in - let reader = BufferReader(buffer) - var result: Api.auth.Authorization? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.Authorization - } - return result - }) - } -} -public extension Api.functions.auth { - static func importAuthorization(id: Int64, bytes: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1518699091) - serializeInt64(id, buffer: buffer, boxed: false) - serializeBytes(bytes, buffer: buffer, boxed: false) - return (FunctionDescription(name: "auth.importAuthorization", parameters: [("id", String(describing: id)), ("bytes", String(describing: bytes))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in - let reader = BufferReader(buffer) - var result: Api.auth.Authorization? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.Authorization - } - return result - }) - } -} -public extension Api.functions.auth { - static func importBotAuthorization(flags: Int32, apiId: Int32, apiHash: String, botAuthToken: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1738800940) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(apiId, buffer: buffer, boxed: false) - serializeString(apiHash, buffer: buffer, boxed: false) - serializeString(botAuthToken, buffer: buffer, boxed: false) - return (FunctionDescription(name: "auth.importBotAuthorization", parameters: [("flags", String(describing: flags)), ("apiId", String(describing: apiId)), ("apiHash", String(describing: apiHash)), ("botAuthToken", String(describing: botAuthToken))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in - let reader = BufferReader(buffer) - var result: Api.auth.Authorization? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.Authorization - } - return result - }) - } -} -public extension Api.functions.auth { - static func importLoginToken(token: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1783866140) - serializeBytes(token, buffer: buffer, boxed: false) - return (FunctionDescription(name: "auth.importLoginToken", parameters: [("token", String(describing: token))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.LoginToken? in - let reader = BufferReader(buffer) - var result: Api.auth.LoginToken? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.LoginToken - } - return result - }) - } -} -public extension Api.functions.auth { - static func importWebTokenAuthorization(apiId: Int32, apiHash: String, webAuthToken: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(767062953) - serializeInt32(apiId, buffer: buffer, boxed: false) - serializeString(apiHash, buffer: buffer, boxed: false) - serializeString(webAuthToken, buffer: buffer, boxed: false) - return (FunctionDescription(name: "auth.importWebTokenAuthorization", parameters: [("apiId", String(describing: apiId)), ("apiHash", String(describing: apiHash)), ("webAuthToken", String(describing: webAuthToken))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in - let reader = BufferReader(buffer) - var result: Api.auth.Authorization? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.Authorization - } - return result - }) - } -} -public extension Api.functions.auth { - static func initPasskeyLogin(apiId: Int32, apiHash: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1368051895) - serializeInt32(apiId, buffer: buffer, boxed: false) - serializeString(apiHash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "auth.initPasskeyLogin", parameters: [("apiId", String(describing: apiId)), ("apiHash", String(describing: apiHash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.PasskeyLoginOptions? in - let reader = BufferReader(buffer) - var result: Api.auth.PasskeyLoginOptions? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.PasskeyLoginOptions - } - return result - }) - } -} -public extension Api.functions.auth { - static func logOut() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1047706137) - - return (FunctionDescription(name: "auth.logOut", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.LoggedOut? in - let reader = BufferReader(buffer) - var result: Api.auth.LoggedOut? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.LoggedOut - } - return result - }) - } -} -public extension Api.functions.auth { - static func recoverPassword(flags: Int32, code: String, newSettings: Api.account.PasswordInputSettings?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(923364464) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(code, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {newSettings!.serialize(buffer, true)} - return (FunctionDescription(name: "auth.recoverPassword", parameters: [("flags", String(describing: flags)), ("code", String(describing: code)), ("newSettings", String(describing: newSettings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in - let reader = BufferReader(buffer) - var result: Api.auth.Authorization? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.Authorization - } - return result - }) - } -} -public extension Api.functions.auth { - static func reportMissingCode(phoneNumber: String, phoneCodeHash: String, mnc: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-878841866) - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(phoneCodeHash, buffer: buffer, boxed: false) - serializeString(mnc, buffer: buffer, boxed: false) - return (FunctionDescription(name: "auth.reportMissingCode", parameters: [("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("mnc", String(describing: mnc))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.auth { - static func requestFirebaseSms(flags: Int32, phoneNumber: String, phoneCodeHash: String, safetyNetToken: String?, playIntegrityToken: String?, iosPushSecret: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1908857314) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(phoneCodeHash, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(safetyNetToken!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(playIntegrityToken!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(iosPushSecret!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "auth.requestFirebaseSms", parameters: [("flags", String(describing: flags)), ("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("safetyNetToken", String(describing: safetyNetToken)), ("playIntegrityToken", String(describing: playIntegrityToken)), ("iosPushSecret", String(describing: iosPushSecret))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.auth { - static func requestPasswordRecovery() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-661144474) - - return (FunctionDescription(name: "auth.requestPasswordRecovery", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.PasswordRecovery? in - let reader = BufferReader(buffer) - var result: Api.auth.PasswordRecovery? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.PasswordRecovery - } - return result - }) - } -} -public extension Api.functions.auth { - static func resendCode(flags: Int32, phoneNumber: String, phoneCodeHash: String, reason: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-890997469) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(phoneCodeHash, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(reason!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "auth.resendCode", parameters: [("flags", String(describing: flags)), ("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("reason", String(describing: reason))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.SentCode? in - let reader = BufferReader(buffer) - var result: Api.auth.SentCode? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.SentCode - } - return result - }) - } -} -public extension Api.functions.auth { - static func resetAuthorizations() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1616179942) - - return (FunctionDescription(name: "auth.resetAuthorizations", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.auth { - static func resetLoginEmail(phoneNumber: String, phoneCodeHash: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2123760019) - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(phoneCodeHash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "auth.resetLoginEmail", parameters: [("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.SentCode? in - let reader = BufferReader(buffer) - var result: Api.auth.SentCode? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.SentCode - } - return result - }) - } -} -public extension Api.functions.auth { - static func sendCode(phoneNumber: String, apiId: Int32, apiHash: String, settings: Api.CodeSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1502141361) - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeInt32(apiId, buffer: buffer, boxed: false) - serializeString(apiHash, buffer: buffer, boxed: false) - settings.serialize(buffer, true) - return (FunctionDescription(name: "auth.sendCode", parameters: [("phoneNumber", String(describing: phoneNumber)), ("apiId", String(describing: apiId)), ("apiHash", String(describing: apiHash)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.SentCode? in - let reader = BufferReader(buffer) - var result: Api.auth.SentCode? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.SentCode - } - return result - }) - } -} -public extension Api.functions.auth { - static func signIn(flags: Int32, phoneNumber: String, phoneCodeHash: String, phoneCode: String?, emailVerification: Api.EmailVerification?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1923962543) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(phoneCodeHash, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(phoneCode!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {emailVerification!.serialize(buffer, true)} - return (FunctionDescription(name: "auth.signIn", parameters: [("flags", String(describing: flags)), ("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("phoneCode", String(describing: phoneCode)), ("emailVerification", String(describing: emailVerification))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in - let reader = BufferReader(buffer) - var result: Api.auth.Authorization? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.Authorization - } - return result - }) - } -} -public extension Api.functions.auth { - static func signUp(flags: Int32, phoneNumber: String, phoneCodeHash: String, firstName: String, lastName: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1429752041) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(phoneCodeHash, buffer: buffer, boxed: false) - serializeString(firstName, buffer: buffer, boxed: false) - serializeString(lastName, buffer: buffer, boxed: false) - return (FunctionDescription(name: "auth.signUp", parameters: [("flags", String(describing: flags)), ("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("firstName", String(describing: firstName)), ("lastName", String(describing: lastName))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in - let reader = BufferReader(buffer) - var result: Api.auth.Authorization? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.auth.Authorization - } - return result - }) - } -} -public extension Api.functions.bots { - static func addPreviewMedia(bot: Api.InputUser, langCode: String, media: Api.InputMedia) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(397326170) - bot.serialize(buffer, true) - serializeString(langCode, buffer: buffer, boxed: false) - media.serialize(buffer, true) - return (FunctionDescription(name: "bots.addPreviewMedia", parameters: [("bot", String(describing: bot)), ("langCode", String(describing: langCode)), ("media", String(describing: media))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.BotPreviewMedia? in - let reader = BufferReader(buffer) - var result: Api.BotPreviewMedia? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.BotPreviewMedia - } - return result - }) - } -} -public extension Api.functions.bots { - static func allowSendMessage(bot: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-248323089) - bot.serialize(buffer, true) - return (FunctionDescription(name: "bots.allowSendMessage", parameters: [("bot", String(describing: bot))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.bots { - static func answerWebhookJSONQuery(queryId: Int64, data: Api.DataJSON) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-434028723) - serializeInt64(queryId, buffer: buffer, boxed: false) - data.serialize(buffer, true) - return (FunctionDescription(name: "bots.answerWebhookJSONQuery", parameters: [("queryId", String(describing: queryId)), ("data", String(describing: data))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.bots { - static func canSendMessage(bot: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(324662502) - bot.serialize(buffer, true) - return (FunctionDescription(name: "bots.canSendMessage", parameters: [("bot", String(describing: bot))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.bots { - static func checkDownloadFileParams(bot: Api.InputUser, fileName: String, url: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1342666121) - bot.serialize(buffer, true) - serializeString(fileName, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - return (FunctionDescription(name: "bots.checkDownloadFileParams", parameters: [("bot", String(describing: bot)), ("fileName", String(describing: fileName)), ("url", String(describing: url))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.bots { - static func deletePreviewMedia(bot: Api.InputUser, langCode: String, media: [Api.InputMedia]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(755054003) - bot.serialize(buffer, true) - serializeString(langCode, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(media.count)) - for item in media { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "bots.deletePreviewMedia", parameters: [("bot", String(describing: bot)), ("langCode", String(describing: langCode)), ("media", String(describing: media))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.bots { - static func editPreviewMedia(bot: Api.InputUser, langCode: String, media: Api.InputMedia, newMedia: Api.InputMedia) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2061148049) - bot.serialize(buffer, true) - serializeString(langCode, buffer: buffer, boxed: false) - media.serialize(buffer, true) - newMedia.serialize(buffer, true) - return (FunctionDescription(name: "bots.editPreviewMedia", parameters: [("bot", String(describing: bot)), ("langCode", String(describing: langCode)), ("media", String(describing: media)), ("newMedia", String(describing: newMedia))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.BotPreviewMedia? in - let reader = BufferReader(buffer) - var result: Api.BotPreviewMedia? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.BotPreviewMedia - } - return result - }) - } -} -public extension Api.functions.bots { - static func getAdminedBots() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.User]>) { - let buffer = Buffer() - buffer.appendInt32(-1334764157) - - return (FunctionDescription(name: "bots.getAdminedBots", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.User]? in - let reader = BufferReader(buffer) - var result: [Api.User]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - return result - }) - } -} -public extension Api.functions.bots { - static func getBotCommands(scope: Api.BotCommandScope, langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.BotCommand]>) { - let buffer = Buffer() - buffer.appendInt32(-481554986) - scope.serialize(buffer, true) - serializeString(langCode, buffer: buffer, boxed: false) - return (FunctionDescription(name: "bots.getBotCommands", parameters: [("scope", String(describing: scope)), ("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.BotCommand]? in - let reader = BufferReader(buffer) - var result: [Api.BotCommand]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.BotCommand.self) - } - return result - }) - } -} -public extension Api.functions.bots { - static func getBotInfo(flags: Int32, bot: Api.InputUser?, langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-589753091) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {bot!.serialize(buffer, true)} - serializeString(langCode, buffer: buffer, boxed: false) - return (FunctionDescription(name: "bots.getBotInfo", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.bots.BotInfo? in - let reader = BufferReader(buffer) - var result: Api.bots.BotInfo? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.bots.BotInfo - } - return result - }) - } -} -public extension Api.functions.bots { - static func getBotMenuButton(userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1671369944) - userId.serialize(buffer, true) - return (FunctionDescription(name: "bots.getBotMenuButton", parameters: [("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.BotMenuButton? in - let reader = BufferReader(buffer) - var result: Api.BotMenuButton? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.BotMenuButton - } - return result - }) - } -} -public extension Api.functions.bots { - static func getBotRecommendations(bot: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1581840363) - bot.serialize(buffer, true) - return (FunctionDescription(name: "bots.getBotRecommendations", parameters: [("bot", String(describing: bot))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.users.Users? in - let reader = BufferReader(buffer) - var result: Api.users.Users? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.users.Users - } - return result - }) - } -} -public extension Api.functions.bots { - static func getPopularAppBots(offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1034878574) - serializeString(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "bots.getPopularAppBots", parameters: [("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.bots.PopularAppBots? in - let reader = BufferReader(buffer) - var result: Api.bots.PopularAppBots? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.bots.PopularAppBots - } - return result - }) - } -} -public extension Api.functions.bots { - static func getPreviewInfo(bot: Api.InputUser, langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1111143341) - bot.serialize(buffer, true) - serializeString(langCode, buffer: buffer, boxed: false) - return (FunctionDescription(name: "bots.getPreviewInfo", parameters: [("bot", String(describing: bot)), ("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.bots.PreviewInfo? in - let reader = BufferReader(buffer) - var result: Api.bots.PreviewInfo? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.bots.PreviewInfo - } - return result - }) - } -} -public extension Api.functions.bots { - static func getPreviewMedias(bot: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.BotPreviewMedia]>) { - let buffer = Buffer() - buffer.appendInt32(-1566222003) - bot.serialize(buffer, true) - return (FunctionDescription(name: "bots.getPreviewMedias", parameters: [("bot", String(describing: bot))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.BotPreviewMedia]? in - let reader = BufferReader(buffer) - var result: [Api.BotPreviewMedia]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.BotPreviewMedia.self) - } - return result - }) - } -} -public extension Api.functions.bots { - static func invokeWebViewCustomMethod(bot: Api.InputUser, customMethod: String, params: Api.DataJSON) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(142591463) - bot.serialize(buffer, true) - serializeString(customMethod, buffer: buffer, boxed: false) - params.serialize(buffer, true) - return (FunctionDescription(name: "bots.invokeWebViewCustomMethod", parameters: [("bot", String(describing: bot)), ("customMethod", String(describing: customMethod)), ("params", String(describing: params))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.DataJSON? in - let reader = BufferReader(buffer) - var result: Api.DataJSON? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.DataJSON - } - return result - }) - } -} -public extension Api.functions.bots { - static func reorderPreviewMedias(bot: Api.InputUser, langCode: String, order: [Api.InputMedia]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1238895702) - bot.serialize(buffer, true) - serializeString(langCode, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order.count)) - for item in order { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "bots.reorderPreviewMedias", parameters: [("bot", String(describing: bot)), ("langCode", String(describing: langCode)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.bots { - static func reorderUsernames(bot: Api.InputUser, order: [String]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1760972350) - bot.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order.count)) - for item in order { - serializeString(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "bots.reorderUsernames", parameters: [("bot", String(describing: bot)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.bots { - static func resetBotCommands(scope: Api.BotCommandScope, langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1032708345) - scope.serialize(buffer, true) - serializeString(langCode, buffer: buffer, boxed: false) - return (FunctionDescription(name: "bots.resetBotCommands", parameters: [("scope", String(describing: scope)), ("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.bots { - static func sendCustomRequest(customMethod: String, params: Api.DataJSON) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1440257555) - serializeString(customMethod, buffer: buffer, boxed: false) - params.serialize(buffer, true) - return (FunctionDescription(name: "bots.sendCustomRequest", parameters: [("customMethod", String(describing: customMethod)), ("params", String(describing: params))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.DataJSON? in - let reader = BufferReader(buffer) - var result: Api.DataJSON? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.DataJSON - } - return result - }) - } -} -public extension Api.functions.bots { - static func setBotBroadcastDefaultAdminRights(adminRights: Api.ChatAdminRights) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2021942497) - adminRights.serialize(buffer, true) - return (FunctionDescription(name: "bots.setBotBroadcastDefaultAdminRights", parameters: [("adminRights", String(describing: adminRights))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.bots { - static func setBotCommands(scope: Api.BotCommandScope, langCode: String, commands: [Api.BotCommand]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(85399130) - scope.serialize(buffer, true) - serializeString(langCode, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(commands.count)) - for item in commands { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "bots.setBotCommands", parameters: [("scope", String(describing: scope)), ("langCode", String(describing: langCode)), ("commands", String(describing: commands))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.bots { - static func setBotGroupDefaultAdminRights(adminRights: Api.ChatAdminRights) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1839281686) - adminRights.serialize(buffer, true) - return (FunctionDescription(name: "bots.setBotGroupDefaultAdminRights", parameters: [("adminRights", String(describing: adminRights))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.bots { - static func setBotInfo(flags: Int32, bot: Api.InputUser?, langCode: String, name: String?, about: String?, description: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(282013987) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {bot!.serialize(buffer, true)} - serializeString(langCode, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {serializeString(name!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeString(about!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(description!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "bots.setBotInfo", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("langCode", String(describing: langCode)), ("name", String(describing: name)), ("about", String(describing: about)), ("description", String(describing: description))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.bots { - static func setBotMenuButton(userId: Api.InputUser, button: Api.BotMenuButton) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1157944655) - userId.serialize(buffer, true) - button.serialize(buffer, true) - return (FunctionDescription(name: "bots.setBotMenuButton", parameters: [("userId", String(describing: userId)), ("button", String(describing: button))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.bots { - static func setCustomVerification(flags: Int32, bot: Api.InputUser?, peer: Api.InputPeer, customDescription: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1953898563) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {bot!.serialize(buffer, true)} - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {serializeString(customDescription!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "bots.setCustomVerification", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("peer", String(describing: peer)), ("customDescription", String(describing: customDescription))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.bots { - static func toggleUserEmojiStatusPermission(bot: Api.InputUser, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(115237778) - bot.serialize(buffer, true) - enabled.serialize(buffer, true) - return (FunctionDescription(name: "bots.toggleUserEmojiStatusPermission", parameters: [("bot", String(describing: bot)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.bots { - static func toggleUsername(bot: Api.InputUser, username: String, active: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(87861619) - bot.serialize(buffer, true) - serializeString(username, buffer: buffer, boxed: false) - active.serialize(buffer, true) - return (FunctionDescription(name: "bots.toggleUsername", parameters: [("bot", String(describing: bot)), ("username", String(describing: username)), ("active", String(describing: active))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.bots { - static func updateStarRefProgram(flags: Int32, bot: Api.InputUser, commissionPermille: Int32, durationMonths: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2005621427) - serializeInt32(flags, buffer: buffer, boxed: false) - bot.serialize(buffer, true) - serializeInt32(commissionPermille, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(durationMonths!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "bots.updateStarRefProgram", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("commissionPermille", String(describing: commissionPermille)), ("durationMonths", String(describing: durationMonths))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.StarRefProgram? in - let reader = BufferReader(buffer) - var result: Api.StarRefProgram? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.StarRefProgram - } - return result - }) - } -} -public extension Api.functions.bots { - static func updateUserEmojiStatus(userId: Api.InputUser, emojiStatus: Api.EmojiStatus) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-308334395) - userId.serialize(buffer, true) - emojiStatus.serialize(buffer, true) - return (FunctionDescription(name: "bots.updateUserEmojiStatus", parameters: [("userId", String(describing: userId)), ("emojiStatus", String(describing: emojiStatus))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.channels { - static func checkSearchPostsFlood(flags: Int32, query: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(576090389) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(query!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "channels.checkSearchPostsFlood", parameters: [("flags", String(describing: flags)), ("query", String(describing: query))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.SearchPostsFlood? in - let reader = BufferReader(buffer) - var result: Api.SearchPostsFlood? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.SearchPostsFlood - } - return result - }) - } -} -public extension Api.functions.channels { - static func checkUsername(channel: Api.InputChannel, username: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(283557164) - channel.serialize(buffer, true) - serializeString(username, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.checkUsername", parameters: [("channel", String(describing: channel)), ("username", String(describing: username))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.channels { - static func convertToGigagroup(channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(187239529) - channel.serialize(buffer, true) - return (FunctionDescription(name: "channels.convertToGigagroup", parameters: [("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func createChannel(flags: Int32, title: String, about: String, geoPoint: Api.InputGeoPoint?, address: String?, ttlPeriod: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1862244601) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(about, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {geoPoint!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(address!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(ttlPeriod!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "channels.createChannel", parameters: [("flags", String(describing: flags)), ("title", String(describing: title)), ("about", String(describing: about)), ("geoPoint", String(describing: geoPoint)), ("address", String(describing: address)), ("ttlPeriod", String(describing: ttlPeriod))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func deactivateAllUsernames(channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(170155475) - channel.serialize(buffer, true) - return (FunctionDescription(name: "channels.deactivateAllUsernames", parameters: [("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.channels { - static func deleteChannel(channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1072619549) - channel.serialize(buffer, true) - return (FunctionDescription(name: "channels.deleteChannel", parameters: [("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func deleteHistory(flags: Int32, channel: Api.InputChannel, maxId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1683319225) - serializeInt32(flags, buffer: buffer, boxed: false) - channel.serialize(buffer, true) - serializeInt32(maxId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.deleteHistory", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel)), ("maxId", String(describing: maxId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func deleteMessages(channel: Api.InputChannel, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2067661490) - channel.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { + buffer.appendInt32(Int32(_data.pinnedToTop!.count)) + for item in _data.pinnedToTop! { serializeInt32(item, buffer: buffer, boxed: false) } - return (FunctionDescription(name: "channels.deleteMessages", parameters: [("channel", String(describing: channel)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedMessages? in - let reader = BufferReader(buffer) - var result: Api.messages.AffectedMessages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AffectedMessages - } - return result - }) - } -} -public extension Api.functions.channels { - static func deleteParticipantHistory(channel: Api.InputChannel, participant: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(913655003) - channel.serialize(buffer, true) - participant.serialize(buffer, true) - return (FunctionDescription(name: "channels.deleteParticipantHistory", parameters: [("channel", String(describing: channel)), ("participant", String(describing: participant))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedHistory? in - let reader = BufferReader(buffer) - var result: Api.messages.AffectedHistory? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AffectedHistory - } - return result - }) - } -} -public extension Api.functions.channels { - static func editAdmin(channel: Api.InputChannel, userId: Api.InputUser, adminRights: Api.ChatAdminRights, rank: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-751007486) - channel.serialize(buffer, true) - userId.serialize(buffer, true) - adminRights.serialize(buffer, true) - serializeString(rank, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.editAdmin", parameters: [("channel", String(describing: channel)), ("userId", String(describing: userId)), ("adminRights", String(describing: adminRights)), ("rank", String(describing: rank))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func editBanned(channel: Api.InputChannel, participant: Api.InputPeer, bannedRights: Api.ChatBannedRights) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1763259007) - channel.serialize(buffer, true) - participant.serialize(buffer, true) - bannedRights.serialize(buffer, true) - return (FunctionDescription(name: "channels.editBanned", parameters: [("channel", String(describing: channel)), ("participant", String(describing: participant)), ("bannedRights", String(describing: bannedRights))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func editCreator(channel: Api.InputChannel, userId: Api.InputUser, password: Api.InputCheckPasswordSRP) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1892102881) - channel.serialize(buffer, true) - userId.serialize(buffer, true) - password.serialize(buffer, true) - return (FunctionDescription(name: "channels.editCreator", parameters: [("channel", String(describing: channel)), ("userId", String(describing: userId)), ("password", String(describing: password))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func editLocation(channel: Api.InputChannel, geoPoint: Api.InputGeoPoint, address: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1491484525) - channel.serialize(buffer, true) - geoPoint.serialize(buffer, true) - serializeString(address, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.editLocation", parameters: [("channel", String(describing: channel)), ("geoPoint", String(describing: geoPoint)), ("address", String(describing: address))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.channels { - static func editPhoto(channel: Api.InputChannel, photo: Api.InputChatPhoto) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-248621111) - channel.serialize(buffer, true) - photo.serialize(buffer, true) - return (FunctionDescription(name: "channels.editPhoto", parameters: [("channel", String(describing: channel)), ("photo", String(describing: photo))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func editTitle(channel: Api.InputChannel, title: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1450044624) - channel.serialize(buffer, true) - serializeString(title, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.editTitle", parameters: [("channel", String(describing: channel)), ("title", String(describing: title))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func exportMessageLink(flags: Int32, channel: Api.InputChannel, id: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-432034325) - serializeInt32(flags, buffer: buffer, boxed: false) - channel.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.exportMessageLink", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ExportedMessageLink? in - let reader = BufferReader(buffer) - var result: Api.ExportedMessageLink? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.ExportedMessageLink - } - return result - }) - } -} -public extension Api.functions.channels { - static func getAdminLog(flags: Int32, channel: Api.InputChannel, q: String, eventsFilter: Api.ChannelAdminLogEventsFilter?, admins: [Api.InputUser]?, maxId: Int64, minId: Int64, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(870184064) - serializeInt32(flags, buffer: buffer, boxed: false) - channel.serialize(buffer, true) - serializeString(q, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {eventsFilter!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(admins!.count)) - for item in admins! { - item.serialize(buffer, true) - }} - serializeInt64(maxId, buffer: buffer, boxed: false) - serializeInt64(minId, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.getAdminLog", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel)), ("q", String(describing: q)), ("eventsFilter", String(describing: eventsFilter)), ("admins", String(describing: admins)), ("maxId", String(describing: maxId)), ("minId", String(describing: minId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.channels.AdminLogResults? in - let reader = BufferReader(buffer) - var result: Api.channels.AdminLogResults? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.channels.AdminLogResults - } - return result - }) - } -} -public extension Api.functions.channels { - static func getAdminedPublicChannels(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-122669393) - serializeInt32(flags, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.getAdminedPublicChannels", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in - let reader = BufferReader(buffer) - var result: Api.messages.Chats? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Chats - } - return result - }) - } -} -public extension Api.functions.channels { - static func getChannelRecommendations(flags: Int32, channel: Api.InputChannel?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(631707458) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {channel!.serialize(buffer, true)} - return (FunctionDescription(name: "channels.getChannelRecommendations", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in - let reader = BufferReader(buffer) - var result: Api.messages.Chats? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Chats - } - return result - }) - } -} -public extension Api.functions.channels { - static func getChannels(id: [Api.InputChannel]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(176122811) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "channels.getChannels", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in - let reader = BufferReader(buffer) - var result: Api.messages.Chats? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Chats - } - return result - }) - } -} -public extension Api.functions.channels { - static func getFullChannel(channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(141781513) - channel.serialize(buffer, true) - return (FunctionDescription(name: "channels.getFullChannel", parameters: [("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ChatFull? in - let reader = BufferReader(buffer) - var result: Api.messages.ChatFull? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.ChatFull - } - return result - }) - } -} -public extension Api.functions.channels { - static func getGroupsForDiscussion() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-170208392) - - return (FunctionDescription(name: "channels.getGroupsForDiscussion", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in - let reader = BufferReader(buffer) - var result: Api.messages.Chats? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Chats - } - return result - }) - } -} -public extension Api.functions.channels { - static func getInactiveChannels() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(300429806) - - return (FunctionDescription(name: "channels.getInactiveChannels", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.InactiveChats? in - let reader = BufferReader(buffer) - var result: Api.messages.InactiveChats? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.InactiveChats - } - return result - }) - } -} -public extension Api.functions.channels { - static func getLeftChannels(offset: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2092831552) - serializeInt32(offset, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.getLeftChannels", parameters: [("offset", String(describing: offset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in - let reader = BufferReader(buffer) - var result: Api.messages.Chats? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Chats - } - return result - }) - } -} -public extension Api.functions.channels { - static func getMessageAuthor(channel: Api.InputChannel, id: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-320691994) - channel.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.getMessageAuthor", parameters: [("channel", String(describing: channel)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.User? in - let reader = BufferReader(buffer) - var result: Api.User? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.User - } - return result - }) - } -} -public extension Api.functions.channels { - static func getMessages(channel: Api.InputChannel, id: [Api.InputMessage]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1383294429) - channel.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "channels.getMessages", parameters: [("channel", String(describing: channel)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in - let reader = BufferReader(buffer) - var result: Api.messages.Messages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Messages - } - return result - }) - } -} -public extension Api.functions.channels { - static func getParticipant(channel: Api.InputChannel, participant: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1599378234) - channel.serialize(buffer, true) - participant.serialize(buffer, true) - return (FunctionDescription(name: "channels.getParticipant", parameters: [("channel", String(describing: channel)), ("participant", String(describing: participant))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.channels.ChannelParticipant? in - let reader = BufferReader(buffer) - var result: Api.channels.ChannelParticipant? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.channels.ChannelParticipant - } - return result - }) - } -} -public extension Api.functions.channels { - static func getParticipants(channel: Api.InputChannel, filter: Api.ChannelParticipantsFilter, offset: Int32, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2010044880) - channel.serialize(buffer, true) - filter.serialize(buffer, true) - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.getParticipants", parameters: [("channel", String(describing: channel)), ("filter", String(describing: filter)), ("offset", String(describing: offset)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.channels.ChannelParticipants? in - let reader = BufferReader(buffer) - var result: Api.channels.ChannelParticipants? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.channels.ChannelParticipants - } - return result - }) - } -} -public extension Api.functions.channels { - static func getSendAs(flags: Int32, peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-410672065) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - return (FunctionDescription(name: "channels.getSendAs", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.channels.SendAsPeers? in - let reader = BufferReader(buffer) - var result: Api.channels.SendAsPeers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.channels.SendAsPeers - } - return result - }) - } -} -public extension Api.functions.channels { - static func inviteToChannel(channel: Api.InputChannel, users: [Api.InputUser]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-907854508) - channel.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "channels.inviteToChannel", parameters: [("channel", String(describing: channel)), ("users", String(describing: users))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.InvitedUsers? in - let reader = BufferReader(buffer) - var result: Api.messages.InvitedUsers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.InvitedUsers - } - return result - }) - } -} -public extension Api.functions.channels { - static func joinChannel(channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(615851205) - channel.serialize(buffer, true) - return (FunctionDescription(name: "channels.joinChannel", parameters: [("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func leaveChannel(channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-130635115) - channel.serialize(buffer, true) - return (FunctionDescription(name: "channels.leaveChannel", parameters: [("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func readHistory(channel: Api.InputChannel, maxId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-871347913) - channel.serialize(buffer, true) - serializeInt32(maxId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.readHistory", parameters: [("channel", String(describing: channel)), ("maxId", String(describing: maxId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.channels { - static func readMessageContents(channel: Api.InputChannel, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-357180360) - channel.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "channels.readMessageContents", parameters: [("channel", String(describing: channel)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.channels { - static func reorderUsernames(channel: Api.InputChannel, order: [String]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1268978403) - channel.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order.count)) - for item in order { - serializeString(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "channels.reorderUsernames", parameters: [("channel", String(describing: channel)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.channels { - static func reportAntiSpamFalsePositive(channel: Api.InputChannel, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1471109485) - channel.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.reportAntiSpamFalsePositive", parameters: [("channel", String(describing: channel)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.channels { - static func reportSpam(channel: Api.InputChannel, participant: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-196443371) - channel.serialize(buffer, true) - participant.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "channels.reportSpam", parameters: [("channel", String(describing: channel)), ("participant", String(describing: participant)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.channels { - static func restrictSponsoredMessages(channel: Api.InputChannel, restricted: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1696000743) - channel.serialize(buffer, true) - restricted.serialize(buffer, true) - return (FunctionDescription(name: "channels.restrictSponsoredMessages", parameters: [("channel", String(describing: channel)), ("restricted", String(describing: restricted))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func searchPosts(flags: Int32, hashtag: String?, query: String?, offsetRate: Int32, offsetPeer: Api.InputPeer, offsetId: Int32, limit: Int32, allowPaidStars: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-221973939) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(hashtag!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(query!, buffer: buffer, boxed: false)} - serializeInt32(offsetRate, buffer: buffer, boxed: false) - offsetPeer.serialize(buffer, true) - serializeInt32(offsetId, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeInt64(allowPaidStars!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "channels.searchPosts", parameters: [("flags", String(describing: flags)), ("hashtag", String(describing: hashtag)), ("query", String(describing: query)), ("offsetRate", String(describing: offsetRate)), ("offsetPeer", String(describing: offsetPeer)), ("offsetId", String(describing: offsetId)), ("limit", String(describing: limit)), ("allowPaidStars", String(describing: allowPaidStars))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in - let reader = BufferReader(buffer) - var result: Api.messages.Messages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Messages - } - return result - }) - } -} -public extension Api.functions.channels { - static func setBoostsToUnblockRestrictions(channel: Api.InputChannel, boosts: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1388733202) - channel.serialize(buffer, true) - serializeInt32(boosts, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.setBoostsToUnblockRestrictions", parameters: [("channel", String(describing: channel)), ("boosts", String(describing: boosts))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func setDiscussionGroup(broadcast: Api.InputChannel, group: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1079520178) - broadcast.serialize(buffer, true) - group.serialize(buffer, true) - return (FunctionDescription(name: "channels.setDiscussionGroup", parameters: [("broadcast", String(describing: broadcast)), ("group", String(describing: group))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.channels { - static func setEmojiStickers(channel: Api.InputChannel, stickerset: Api.InputStickerSet) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1020866743) - channel.serialize(buffer, true) - stickerset.serialize(buffer, true) - return (FunctionDescription(name: "channels.setEmojiStickers", parameters: [("channel", String(describing: channel)), ("stickerset", String(describing: stickerset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.channels { - static func setMainProfileTab(channel: Api.InputChannel, tab: Api.ProfileTab) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(897842353) - channel.serialize(buffer, true) - tab.serialize(buffer, true) - return (FunctionDescription(name: "channels.setMainProfileTab", parameters: [("channel", String(describing: channel)), ("tab", String(describing: tab))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.channels { - static func setStickers(channel: Api.InputChannel, stickerset: Api.InputStickerSet) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-359881479) - channel.serialize(buffer, true) - stickerset.serialize(buffer, true) - return (FunctionDescription(name: "channels.setStickers", parameters: [("channel", String(describing: channel)), ("stickerset", String(describing: stickerset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.channels { - static func toggleAntiSpam(channel: Api.InputChannel, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1760814315) - channel.serialize(buffer, true) - enabled.serialize(buffer, true) - return (FunctionDescription(name: "channels.toggleAntiSpam", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func toggleAutotranslation(channel: Api.InputChannel, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(377471137) - channel.serialize(buffer, true) - enabled.serialize(buffer, true) - return (FunctionDescription(name: "channels.toggleAutotranslation", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func toggleForum(channel: Api.InputChannel, enabled: Api.Bool, tabs: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1073174324) - channel.serialize(buffer, true) - enabled.serialize(buffer, true) - tabs.serialize(buffer, true) - return (FunctionDescription(name: "channels.toggleForum", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled)), ("tabs", String(describing: tabs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func toggleJoinRequest(channel: Api.InputChannel, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1277789622) - channel.serialize(buffer, true) - enabled.serialize(buffer, true) - return (FunctionDescription(name: "channels.toggleJoinRequest", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func toggleJoinToSend(channel: Api.InputChannel, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-456419968) - channel.serialize(buffer, true) - enabled.serialize(buffer, true) - return (FunctionDescription(name: "channels.toggleJoinToSend", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func toggleParticipantsHidden(channel: Api.InputChannel, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1785624660) - channel.serialize(buffer, true) - enabled.serialize(buffer, true) - return (FunctionDescription(name: "channels.toggleParticipantsHidden", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func togglePreHistoryHidden(channel: Api.InputChannel, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-356796084) - channel.serialize(buffer, true) - enabled.serialize(buffer, true) - return (FunctionDescription(name: "channels.togglePreHistoryHidden", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func toggleSignatures(flags: Int32, channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1099781276) - serializeInt32(flags, buffer: buffer, boxed: false) - channel.serialize(buffer, true) - return (FunctionDescription(name: "channels.toggleSignatures", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func toggleSlowMode(channel: Api.InputChannel, seconds: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-304832784) - channel.serialize(buffer, true) - serializeInt32(seconds, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.toggleSlowMode", parameters: [("channel", String(describing: channel)), ("seconds", String(describing: seconds))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func toggleUsername(channel: Api.InputChannel, username: String, active: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1358053637) - channel.serialize(buffer, true) - serializeString(username, buffer: buffer, boxed: false) - active.serialize(buffer, true) - return (FunctionDescription(name: "channels.toggleUsername", parameters: [("channel", String(describing: channel)), ("username", String(describing: username)), ("active", String(describing: active))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.channels { - static func toggleViewForumAsMessages(channel: Api.InputChannel, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1757889771) - channel.serialize(buffer, true) - enabled.serialize(buffer, true) - return (FunctionDescription(name: "channels.toggleViewForumAsMessages", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func updateColor(flags: Int32, channel: Api.InputChannel, color: Int32?, backgroundEmojiId: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-659933583) - serializeInt32(flags, buffer: buffer, boxed: false) - channel.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(color!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(backgroundEmojiId!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "channels.updateColor", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel)), ("color", String(describing: color)), ("backgroundEmojiId", String(describing: backgroundEmojiId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func updateEmojiStatus(channel: Api.InputChannel, emojiStatus: Api.EmojiStatus) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-254548312) - channel.serialize(buffer, true) - emojiStatus.serialize(buffer, true) - return (FunctionDescription(name: "channels.updateEmojiStatus", parameters: [("channel", String(describing: channel)), ("emojiStatus", String(describing: emojiStatus))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func updatePaidMessagesPrice(flags: Int32, channel: Api.InputChannel, sendPaidMessagesStars: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1259483771) - serializeInt32(flags, buffer: buffer, boxed: false) - channel.serialize(buffer, true) - serializeInt64(sendPaidMessagesStars, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.updatePaidMessagesPrice", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel)), ("sendPaidMessagesStars", String(describing: sendPaidMessagesStars))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.channels { - static func updateUsername(channel: Api.InputChannel, username: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(890549214) - channel.serialize(buffer, true) - serializeString(username, buffer: buffer, boxed: false) - return (FunctionDescription(name: "channels.updateUsername", parameters: [("channel", String(describing: channel)), ("username", String(describing: username))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.chatlists { - static func checkChatlistInvite(slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1103171583) - serializeString(slug, buffer: buffer, boxed: false) - return (FunctionDescription(name: "chatlists.checkChatlistInvite", parameters: [("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.chatlists.ChatlistInvite? in - let reader = BufferReader(buffer) - var result: Api.chatlists.ChatlistInvite? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.chatlists.ChatlistInvite - } - return result - }) - } -} -public extension Api.functions.chatlists { - static func deleteExportedInvite(chatlist: Api.InputChatlist, slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1906072670) - chatlist.serialize(buffer, true) - serializeString(slug, buffer: buffer, boxed: false) - return (FunctionDescription(name: "chatlists.deleteExportedInvite", parameters: [("chatlist", String(describing: chatlist)), ("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.chatlists { - static func editExportedInvite(flags: Int32, chatlist: Api.InputChatlist, slug: String, title: String?, peers: [Api.InputPeer]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1698543165) - serializeInt32(flags, buffer: buffer, boxed: false) - chatlist.serialize(buffer, true) - serializeString(slug, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peers!.count)) - for item in peers! { - item.serialize(buffer, true) - }} - return (FunctionDescription(name: "chatlists.editExportedInvite", parameters: [("flags", String(describing: flags)), ("chatlist", String(describing: chatlist)), ("slug", String(describing: slug)), ("title", String(describing: title)), ("peers", String(describing: peers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ExportedChatlistInvite? in - let reader = BufferReader(buffer) - var result: Api.ExportedChatlistInvite? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.ExportedChatlistInvite - } - return result - }) - } -} -public extension Api.functions.chatlists { - static func exportChatlistInvite(chatlist: Api.InputChatlist, title: String, peers: [Api.InputPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2072885362) - chatlist.serialize(buffer, true) - serializeString(title, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peers.count)) - for item in peers { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "chatlists.exportChatlistInvite", parameters: [("chatlist", String(describing: chatlist)), ("title", String(describing: title)), ("peers", String(describing: peers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.chatlists.ExportedChatlistInvite? in - let reader = BufferReader(buffer) - var result: Api.chatlists.ExportedChatlistInvite? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.chatlists.ExportedChatlistInvite - } - return result - }) - } -} -public extension Api.functions.chatlists { - static func getChatlistUpdates(chatlist: Api.InputChatlist) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1992190687) - chatlist.serialize(buffer, true) - return (FunctionDescription(name: "chatlists.getChatlistUpdates", parameters: [("chatlist", String(describing: chatlist))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.chatlists.ChatlistUpdates? in - let reader = BufferReader(buffer) - var result: Api.chatlists.ChatlistUpdates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.chatlists.ChatlistUpdates - } - return result - }) - } -} -public extension Api.functions.chatlists { - static func getExportedInvites(chatlist: Api.InputChatlist) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-838608253) - chatlist.serialize(buffer, true) - return (FunctionDescription(name: "chatlists.getExportedInvites", parameters: [("chatlist", String(describing: chatlist))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.chatlists.ExportedInvites? in - let reader = BufferReader(buffer) - var result: Api.chatlists.ExportedInvites? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.chatlists.ExportedInvites - } - return result - }) - } -} -public extension Api.functions.chatlists { - static func getLeaveChatlistSuggestions(chatlist: Api.InputChatlist) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.Peer]>) { - let buffer = Buffer() - buffer.appendInt32(-37955820) - chatlist.serialize(buffer, true) - return (FunctionDescription(name: "chatlists.getLeaveChatlistSuggestions", parameters: [("chatlist", String(describing: chatlist))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.Peer]? in - let reader = BufferReader(buffer) - var result: [Api.Peer]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) - } - return result - }) - } -} -public extension Api.functions.chatlists { - static func hideChatlistUpdates(chatlist: Api.InputChatlist) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1726252795) - chatlist.serialize(buffer, true) - return (FunctionDescription(name: "chatlists.hideChatlistUpdates", parameters: [("chatlist", String(describing: chatlist))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.chatlists { - static func joinChatlistInvite(slug: String, peers: [Api.InputPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1498291302) - serializeString(slug, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peers.count)) - for item in peers { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "chatlists.joinChatlistInvite", parameters: [("slug", String(describing: slug)), ("peers", String(describing: peers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.chatlists { - static func joinChatlistUpdates(chatlist: Api.InputChatlist, peers: [Api.InputPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-527828747) - chatlist.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peers.count)) - for item in peers { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "chatlists.joinChatlistUpdates", parameters: [("chatlist", String(describing: chatlist)), ("peers", String(describing: peers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.chatlists { - static func leaveChatlist(chatlist: Api.InputChatlist, peers: [Api.InputPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1962598714) - chatlist.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peers.count)) - for item in peers { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "chatlists.leaveChatlist", parameters: [("chatlist", String(describing: chatlist)), ("peers", String(describing: peers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.contacts { - static func acceptContact(id: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-130964977) - id.serialize(buffer, true) - return (FunctionDescription(name: "contacts.acceptContact", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.contacts { - static func addContact(flags: Int32, id: Api.InputUser, firstName: String, lastName: String, phone: String, note: Api.TextWithEntities?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-642109868) - serializeInt32(flags, buffer: buffer, boxed: false) - id.serialize(buffer, true) - serializeString(firstName, buffer: buffer, boxed: false) - serializeString(lastName, buffer: buffer, boxed: false) - serializeString(phone, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {note!.serialize(buffer, true)} - return (FunctionDescription(name: "contacts.addContact", parameters: [("flags", String(describing: flags)), ("id", String(describing: id)), ("firstName", String(describing: firstName)), ("lastName", String(describing: lastName)), ("phone", String(describing: phone)), ("note", String(describing: note))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.contacts { - static func block(flags: Int32, id: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(774801204) - serializeInt32(flags, buffer: buffer, boxed: false) - id.serialize(buffer, true) - return (FunctionDescription(name: "contacts.block", parameters: [("flags", String(describing: flags)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.contacts { - static func blockFromReplies(flags: Int32, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(698914348) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(msgId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "contacts.blockFromReplies", parameters: [("flags", String(describing: flags)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.contacts { - static func deleteByPhones(phones: [String]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(269745566) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(phones.count)) - for item in phones { - serializeString(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "contacts.deleteByPhones", parameters: [("phones", String(describing: phones))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.contacts { - static func deleteContacts(id: [Api.InputUser]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(157945344) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "contacts.deleteContacts", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.contacts { - static func editCloseFriends(id: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1167653392) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt64(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "contacts.editCloseFriends", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.contacts { - static func exportContactToken() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-127582169) - - return (FunctionDescription(name: "contacts.exportContactToken", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ExportedContactToken? in - let reader = BufferReader(buffer) - var result: Api.ExportedContactToken? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.ExportedContactToken - } - return result - }) - } -} -public extension Api.functions.contacts { - static func getBirthdays() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-621959068) - - return (FunctionDescription(name: "contacts.getBirthdays", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.ContactBirthdays? in - let reader = BufferReader(buffer) - var result: Api.contacts.ContactBirthdays? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.contacts.ContactBirthdays - } - return result - }) - } -} -public extension Api.functions.contacts { - static func getBlocked(flags: Int32, offset: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1702457472) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "contacts.getBlocked", parameters: [("flags", String(describing: flags)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.Blocked? in - let reader = BufferReader(buffer) - var result: Api.contacts.Blocked? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.contacts.Blocked - } - return result - }) - } -} -public extension Api.functions.contacts { - static func getContactIDs(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Int32]>) { - let buffer = Buffer() - buffer.appendInt32(2061264541) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "contacts.getContactIDs", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Int32]? in - let reader = BufferReader(buffer) - var result: [Int32]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - return result - }) - } -} -public extension Api.functions.contacts { - static func getContacts(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1574346258) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "contacts.getContacts", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.Contacts? in - let reader = BufferReader(buffer) - var result: Api.contacts.Contacts? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.contacts.Contacts - } - return result - }) - } -} -public extension Api.functions.contacts { - static func getLocated(flags: Int32, geoPoint: Api.InputGeoPoint, selfExpires: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-750207932) - serializeInt32(flags, buffer: buffer, boxed: false) - geoPoint.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(selfExpires!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "contacts.getLocated", parameters: [("flags", String(describing: flags)), ("geoPoint", String(describing: geoPoint)), ("selfExpires", String(describing: selfExpires))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.contacts { - static func getSaved() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.SavedContact]>) { - let buffer = Buffer() - buffer.appendInt32(-2098076769) - - return (FunctionDescription(name: "contacts.getSaved", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.SavedContact]? in - let reader = BufferReader(buffer) - var result: [Api.SavedContact]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.SavedContact.self) - } - return result - }) - } -} -public extension Api.functions.contacts { - static func getSponsoredPeers(q: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1228356717) - serializeString(q, buffer: buffer, boxed: false) - return (FunctionDescription(name: "contacts.getSponsoredPeers", parameters: [("q", String(describing: q))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.SponsoredPeers? in - let reader = BufferReader(buffer) - var result: Api.contacts.SponsoredPeers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.contacts.SponsoredPeers - } - return result - }) - } -} -public extension Api.functions.contacts { - static func getStatuses() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.ContactStatus]>) { - let buffer = Buffer() - buffer.appendInt32(-995929106) - - return (FunctionDescription(name: "contacts.getStatuses", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.ContactStatus]? in - let reader = BufferReader(buffer) - var result: [Api.ContactStatus]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.ContactStatus.self) - } - return result - }) - } -} -public extension Api.functions.contacts { - static func getTopPeers(flags: Int32, offset: Int32, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1758168906) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "contacts.getTopPeers", parameters: [("flags", String(describing: flags)), ("offset", String(describing: offset)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.TopPeers? in - let reader = BufferReader(buffer) - var result: Api.contacts.TopPeers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.contacts.TopPeers - } - return result - }) - } -} -public extension Api.functions.contacts { - static func importContactToken(token: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(318789512) - serializeString(token, buffer: buffer, boxed: false) - return (FunctionDescription(name: "contacts.importContactToken", parameters: [("token", String(describing: token))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.User? in - let reader = BufferReader(buffer) - var result: Api.User? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.User - } - return result - }) - } -} -public extension Api.functions.contacts { - static func importContacts(contacts: [Api.InputContact]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(746589157) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(contacts.count)) - for item in contacts { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "contacts.importContacts", parameters: [("contacts", String(describing: contacts))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.ImportedContacts? in - let reader = BufferReader(buffer) - var result: Api.contacts.ImportedContacts? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.contacts.ImportedContacts - } - return result - }) - } -} -public extension Api.functions.contacts { - static func resetSaved() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2020263951) - - return (FunctionDescription(name: "contacts.resetSaved", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.contacts { - static func resetTopPeerRating(category: Api.TopPeerCategory, peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(451113900) - category.serialize(buffer, true) - peer.serialize(buffer, true) - return (FunctionDescription(name: "contacts.resetTopPeerRating", parameters: [("category", String(describing: category)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.contacts { - static func resolvePhone(phone: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1963375804) - serializeString(phone, buffer: buffer, boxed: false) - return (FunctionDescription(name: "contacts.resolvePhone", parameters: [("phone", String(describing: phone))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.ResolvedPeer? in - let reader = BufferReader(buffer) - var result: Api.contacts.ResolvedPeer? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.contacts.ResolvedPeer - } - return result - }) - } -} -public extension Api.functions.contacts { - static func resolveUsername(flags: Int32, username: String, referer: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1918565308) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(username, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(referer!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "contacts.resolveUsername", parameters: [("flags", String(describing: flags)), ("username", String(describing: username)), ("referer", String(describing: referer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.ResolvedPeer? in - let reader = BufferReader(buffer) - var result: Api.contacts.ResolvedPeer? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.contacts.ResolvedPeer - } - return result - }) - } -} -public extension Api.functions.contacts { - static func search(q: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(301470424) - serializeString(q, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "contacts.search", parameters: [("q", String(describing: q)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.Found? in - let reader = BufferReader(buffer) - var result: Api.contacts.Found? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.contacts.Found - } - return result - }) - } -} -public extension Api.functions.contacts { - static func setBlocked(flags: Int32, id: [Api.InputPeer], limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1798939530) - serializeInt32(flags, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - item.serialize(buffer, true) - } - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "contacts.setBlocked", parameters: [("flags", String(describing: flags)), ("id", String(describing: id)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.contacts { - static func toggleTopPeers(enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2062238246) - enabled.serialize(buffer, true) - return (FunctionDescription(name: "contacts.toggleTopPeers", parameters: [("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.contacts { - static func unblock(flags: Int32, id: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1252994264) - serializeInt32(flags, buffer: buffer, boxed: false) - id.serialize(buffer, true) - return (FunctionDescription(name: "contacts.unblock", parameters: [("flags", String(describing: flags)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.contacts { - static func updateContactNote(id: Api.InputUser, note: Api.TextWithEntities) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(329212923) - id.serialize(buffer, true) - note.serialize(buffer, true) - return (FunctionDescription(name: "contacts.updateContactNote", parameters: [("id", String(describing: id)), ("note", String(describing: note))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.folders { - static func editPeerFolders(folderPeers: [Api.InputFolderPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1749536939) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(folderPeers.count)) - for item in folderPeers { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "folders.editPeerFolders", parameters: [("folderPeers", String(describing: folderPeers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.fragment { - static func getCollectibleInfo(collectible: Api.InputCollectible) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1105295942) - collectible.serialize(buffer, true) - return (FunctionDescription(name: "fragment.getCollectibleInfo", parameters: [("collectible", String(describing: collectible))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.fragment.CollectibleInfo? in - let reader = BufferReader(buffer) - var result: Api.fragment.CollectibleInfo? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.fragment.CollectibleInfo - } - return result - }) - } -} -public extension Api.functions.help { - static func acceptTermsOfService(id: Api.DataJSON) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-294455398) - id.serialize(buffer, true) - return (FunctionDescription(name: "help.acceptTermsOfService", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.help { - static func dismissSuggestion(peer: Api.InputPeer, suggestion: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-183649631) - peer.serialize(buffer, true) - serializeString(suggestion, buffer: buffer, boxed: false) - return (FunctionDescription(name: "help.dismissSuggestion", parameters: [("peer", String(describing: peer)), ("suggestion", String(describing: suggestion))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.help { - static func editUserInfo(userId: Api.InputUser, message: String, entities: [Api.MessageEntity]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1723407216) - userId.serialize(buffer, true) - serializeString(message, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities.count)) - for item in entities { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "help.editUserInfo", parameters: [("userId", String(describing: userId)), ("message", String(describing: message)), ("entities", String(describing: entities))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.UserInfo? in - let reader = BufferReader(buffer) - var result: Api.help.UserInfo? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.UserInfo - } - return result - }) - } -} -public extension Api.functions.help { - static func getAppConfig(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1642330196) - serializeInt32(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "help.getAppConfig", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.AppConfig? in - let reader = BufferReader(buffer) - var result: Api.help.AppConfig? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.AppConfig - } - return result - }) - } -} -public extension Api.functions.help { - static func getAppUpdate(source: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1378703997) - serializeString(source, buffer: buffer, boxed: false) - return (FunctionDescription(name: "help.getAppUpdate", parameters: [("source", String(describing: source))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.AppUpdate? in - let reader = BufferReader(buffer) - var result: Api.help.AppUpdate? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.AppUpdate - } - return result - }) - } -} -public extension Api.functions.help { - static func getCdnConfig() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1375900482) - - return (FunctionDescription(name: "help.getCdnConfig", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.CdnConfig? in - let reader = BufferReader(buffer) - var result: Api.CdnConfig? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.CdnConfig - } - return result - }) - } -} -public extension Api.functions.help { - static func getConfig() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-990308245) - - return (FunctionDescription(name: "help.getConfig", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Config? in - let reader = BufferReader(buffer) - var result: Api.Config? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Config - } - return result - }) - } -} -public extension Api.functions.help { - static func getCountriesList(langCode: String, hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1935116200) - serializeString(langCode, buffer: buffer, boxed: false) - serializeInt32(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "help.getCountriesList", parameters: [("langCode", String(describing: langCode)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.CountriesList? in - let reader = BufferReader(buffer) - var result: Api.help.CountriesList? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.CountriesList - } - return result - }) - } -} -public extension Api.functions.help { - static func getDeepLinkInfo(path: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1072547679) - serializeString(path, buffer: buffer, boxed: false) - return (FunctionDescription(name: "help.getDeepLinkInfo", parameters: [("path", String(describing: path))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.DeepLinkInfo? in - let reader = BufferReader(buffer) - var result: Api.help.DeepLinkInfo? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.DeepLinkInfo - } - return result - }) - } -} -public extension Api.functions.help { - static func getInviteText() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1295590211) - - return (FunctionDescription(name: "help.getInviteText", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.InviteText? in - let reader = BufferReader(buffer) - var result: Api.help.InviteText? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.InviteText - } - return result - }) - } -} -public extension Api.functions.help { - static func getNearestDc() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(531836966) - - return (FunctionDescription(name: "help.getNearestDc", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.NearestDc? in - let reader = BufferReader(buffer) - var result: Api.NearestDc? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.NearestDc - } - return result - }) - } -} -public extension Api.functions.help { - static func getPassportConfig(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-966677240) - serializeInt32(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "help.getPassportConfig", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.PassportConfig? in - let reader = BufferReader(buffer) - var result: Api.help.PassportConfig? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.PassportConfig - } - return result - }) - } -} -public extension Api.functions.help { - static func getPeerColors(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-629083089) - serializeInt32(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "help.getPeerColors", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.PeerColors? in - let reader = BufferReader(buffer) - var result: Api.help.PeerColors? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.PeerColors - } - return result - }) - } -} -public extension Api.functions.help { - static func getPeerProfileColors(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1412453891) - serializeInt32(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "help.getPeerProfileColors", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.PeerColors? in - let reader = BufferReader(buffer) - var result: Api.help.PeerColors? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.PeerColors - } - return result - }) - } -} -public extension Api.functions.help { - static func getPremiumPromo() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1206152236) - - return (FunctionDescription(name: "help.getPremiumPromo", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.PremiumPromo? in - let reader = BufferReader(buffer) - var result: Api.help.PremiumPromo? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.PremiumPromo - } - return result - }) - } -} -public extension Api.functions.help { - static func getPromoData() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1063816159) - - return (FunctionDescription(name: "help.getPromoData", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.PromoData? in - let reader = BufferReader(buffer) - var result: Api.help.PromoData? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.PromoData - } - return result - }) - } -} -public extension Api.functions.help { - static func getRecentMeUrls(referer: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1036054804) - serializeString(referer, buffer: buffer, boxed: false) - return (FunctionDescription(name: "help.getRecentMeUrls", parameters: [("referer", String(describing: referer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.RecentMeUrls? in - let reader = BufferReader(buffer) - var result: Api.help.RecentMeUrls? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.RecentMeUrls - } - return result - }) - } -} -public extension Api.functions.help { - static func getSupport() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1663104819) - - return (FunctionDescription(name: "help.getSupport", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.Support? in - let reader = BufferReader(buffer) - var result: Api.help.Support? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.Support - } - return result - }) - } -} -public extension Api.functions.help { - static func getSupportName() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-748624084) - - return (FunctionDescription(name: "help.getSupportName", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.SupportName? in - let reader = BufferReader(buffer) - var result: Api.help.SupportName? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.SupportName - } - return result - }) - } -} -public extension Api.functions.help { - static func getTermsOfServiceUpdate() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(749019089) - - return (FunctionDescription(name: "help.getTermsOfServiceUpdate", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.TermsOfServiceUpdate? in - let reader = BufferReader(buffer) - var result: Api.help.TermsOfServiceUpdate? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.TermsOfServiceUpdate - } - return result - }) - } -} -public extension Api.functions.help { - static func getTimezonesList(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1236468288) - serializeInt32(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "help.getTimezonesList", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.TimezonesList? in - let reader = BufferReader(buffer) - var result: Api.help.TimezonesList? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.TimezonesList - } - return result - }) - } -} -public extension Api.functions.help { - static func getUserInfo(userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(59377875) - userId.serialize(buffer, true) - return (FunctionDescription(name: "help.getUserInfo", parameters: [("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.UserInfo? in - let reader = BufferReader(buffer) - var result: Api.help.UserInfo? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.help.UserInfo - } - return result - }) - } -} -public extension Api.functions.help { - static func hidePromoData(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(505748629) - peer.serialize(buffer, true) - return (FunctionDescription(name: "help.hidePromoData", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.help { - static func saveAppLog(events: [Api.InputAppEvent]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1862465352) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(events.count)) - for item in events { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "help.saveAppLog", parameters: [("events", String(describing: events))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.help { - static func setBotUpdatesStatus(pendingUpdatesCount: Int32, message: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-333262899) - serializeInt32(pendingUpdatesCount, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - return (FunctionDescription(name: "help.setBotUpdatesStatus", parameters: [("pendingUpdatesCount", String(describing: pendingUpdatesCount)), ("message", String(describing: message))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.help { - static func test() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1058929929) - - return (FunctionDescription(name: "help.test", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.langpack { - static func getDifference(langPack: String, langCode: String, fromVersion: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-845657435) - serializeString(langPack, buffer: buffer, boxed: false) - serializeString(langCode, buffer: buffer, boxed: false) - serializeInt32(fromVersion, buffer: buffer, boxed: false) - return (FunctionDescription(name: "langpack.getDifference", parameters: [("langPack", String(describing: langPack)), ("langCode", String(describing: langCode)), ("fromVersion", String(describing: fromVersion))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.LangPackDifference? in - let reader = BufferReader(buffer) - var result: Api.LangPackDifference? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.LangPackDifference - } - return result - }) - } -} -public extension Api.functions.langpack { - static func getLangPack(langPack: String, langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-219008246) - serializeString(langPack, buffer: buffer, boxed: false) - serializeString(langCode, buffer: buffer, boxed: false) - return (FunctionDescription(name: "langpack.getLangPack", parameters: [("langPack", String(describing: langPack)), ("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.LangPackDifference? in - let reader = BufferReader(buffer) - var result: Api.LangPackDifference? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.LangPackDifference - } - return result - }) - } -} -public extension Api.functions.langpack { - static func getLanguage(langPack: String, langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1784243458) - serializeString(langPack, buffer: buffer, boxed: false) - serializeString(langCode, buffer: buffer, boxed: false) - return (FunctionDescription(name: "langpack.getLanguage", parameters: [("langPack", String(describing: langPack)), ("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.LangPackLanguage? in - let reader = BufferReader(buffer) - var result: Api.LangPackLanguage? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.LangPackLanguage - } - return result - }) - } -} -public extension Api.functions.langpack { - static func getLanguages(langPack: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.LangPackLanguage]>) { - let buffer = Buffer() - buffer.appendInt32(1120311183) - serializeString(langPack, buffer: buffer, boxed: false) - return (FunctionDescription(name: "langpack.getLanguages", parameters: [("langPack", String(describing: langPack))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.LangPackLanguage]? in - let reader = BufferReader(buffer) - var result: [Api.LangPackLanguage]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.LangPackLanguage.self) - } - return result - }) - } -} -public extension Api.functions.langpack { - static func getStrings(langPack: String, langCode: String, keys: [String]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.LangPackString]>) { - let buffer = Buffer() - buffer.appendInt32(-269862909) - serializeString(langPack, buffer: buffer, boxed: false) - serializeString(langCode, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(keys.count)) - for item in keys { - serializeString(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "langpack.getStrings", parameters: [("langPack", String(describing: langPack)), ("langCode", String(describing: langCode)), ("keys", String(describing: keys))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.LangPackString]? in - let reader = BufferReader(buffer) - var result: [Api.LangPackString]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.LangPackString.self) - } - return result - }) - } -} -public extension Api.functions.messages { - static func acceptEncryption(peer: Api.InputEncryptedChat, gB: Buffer, keyFingerprint: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1035731989) - peer.serialize(buffer, true) - serializeBytes(gB, buffer: buffer, boxed: false) - serializeInt64(keyFingerprint, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.acceptEncryption", parameters: [("peer", String(describing: peer)), ("gB", String(describing: gB)), ("keyFingerprint", String(describing: keyFingerprint))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EncryptedChat? in - let reader = BufferReader(buffer) - var result: Api.EncryptedChat? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.EncryptedChat - } - return result - }) - } -} -public extension Api.functions.messages { - static func acceptUrlAuth(flags: Int32, peer: Api.InputPeer?, msgId: Int32?, buttonId: Int32?, url: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1322487515) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {peer!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(msgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(buttonId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(url!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.acceptUrlAuth", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("buttonId", String(describing: buttonId)), ("url", String(describing: url))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.UrlAuthResult? in - let reader = BufferReader(buffer) - var result: Api.UrlAuthResult? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.UrlAuthResult - } - return result - }) - } -} -public extension Api.functions.messages { - static func addChatUser(chatId: Int64, userId: Api.InputUser, fwdLimit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-876162809) - serializeInt64(chatId, buffer: buffer, boxed: false) - userId.serialize(buffer, true) - serializeInt32(fwdLimit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.addChatUser", parameters: [("chatId", String(describing: chatId)), ("userId", String(describing: userId)), ("fwdLimit", String(describing: fwdLimit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.InvitedUsers? in - let reader = BufferReader(buffer) - var result: Api.messages.InvitedUsers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.InvitedUsers - } - return result - }) - } -} -public extension Api.functions.messages { - static func appendTodoList(peer: Api.InputPeer, msgId: Int32, list: [Api.TodoItem]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(564531287) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(list.count)) - for item in list { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "messages.appendTodoList", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("list", String(describing: list))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func checkChatInvite(hash: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1051570619) - serializeString(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.checkChatInvite", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ChatInvite? in - let reader = BufferReader(buffer) - var result: Api.ChatInvite? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.ChatInvite - } - return result - }) - } -} -public extension Api.functions.messages { - static func checkHistoryImport(importHead: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1140726259) - serializeString(importHead, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.checkHistoryImport", parameters: [("importHead", String(describing: importHead))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.HistoryImportParsed? in - let reader = BufferReader(buffer) - var result: Api.messages.HistoryImportParsed? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.HistoryImportParsed - } - return result - }) - } -} -public extension Api.functions.messages { - static func checkHistoryImportPeer(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1573261059) - peer.serialize(buffer, true) - return (FunctionDescription(name: "messages.checkHistoryImportPeer", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.CheckedHistoryImportPeer? in - let reader = BufferReader(buffer) - var result: Api.messages.CheckedHistoryImportPeer? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.CheckedHistoryImportPeer - } - return result - }) - } -} -public extension Api.functions.messages { - static func checkQuickReplyShortcut(shortcut: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-237962285) - serializeString(shortcut, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.checkQuickReplyShortcut", parameters: [("shortcut", String(describing: shortcut))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func clearAllDrafts() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2119757468) - - return (FunctionDescription(name: "messages.clearAllDrafts", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func clearRecentReactions() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1644236876) - - return (FunctionDescription(name: "messages.clearRecentReactions", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func clearRecentStickers(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1986437075) - serializeInt32(flags, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.clearRecentStickers", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func clickSponsoredMessage(flags: Int32, randomId: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2110454402) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeBytes(randomId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.clickSponsoredMessage", parameters: [("flags", String(describing: flags)), ("randomId", String(describing: randomId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func createChat(flags: Int32, users: [Api.InputUser], title: String, ttlPeriod: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1831936556) - serializeInt32(flags, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - serializeString(title, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(ttlPeriod!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.createChat", parameters: [("flags", String(describing: flags)), ("users", String(describing: users)), ("title", String(describing: title)), ("ttlPeriod", String(describing: ttlPeriod))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.InvitedUsers? in - let reader = BufferReader(buffer) - var result: Api.messages.InvitedUsers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.InvitedUsers - } - return result - }) - } -} -public extension Api.functions.messages { - static func createForumTopic(flags: Int32, peer: Api.InputPeer, title: String, iconColor: Int32?, iconEmojiId: Int64?, randomId: Int64, sendAs: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(798540757) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeString(title, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(iconColor!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt64(iconEmojiId!, buffer: buffer, boxed: false)} - serializeInt64(randomId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {sendAs!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.createForumTopic", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("title", String(describing: title)), ("iconColor", String(describing: iconColor)), ("iconEmojiId", String(describing: iconEmojiId)), ("randomId", String(describing: randomId)), ("sendAs", String(describing: sendAs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func deleteChat(chatId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1540419152) - serializeInt64(chatId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.deleteChat", parameters: [("chatId", String(describing: chatId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func deleteChatUser(flags: Int32, chatId: Int64, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1575461717) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(chatId, buffer: buffer, boxed: false) - userId.serialize(buffer, true) - return (FunctionDescription(name: "messages.deleteChatUser", parameters: [("flags", String(describing: flags)), ("chatId", String(describing: chatId)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func deleteExportedChatInvite(peer: Api.InputPeer, link: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-731601877) - peer.serialize(buffer, true) - serializeString(link, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.deleteExportedChatInvite", parameters: [("peer", String(describing: peer)), ("link", String(describing: link))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func deleteFactCheck(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-774204404) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.deleteFactCheck", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func deleteHistory(flags: Int32, peer: Api.InputPeer, maxId: Int32, minDate: Int32?, maxDate: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1332768214) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(maxId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(minDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(maxDate!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.deleteHistory", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("maxId", String(describing: maxId)), ("minDate", String(describing: minDate)), ("maxDate", String(describing: maxDate))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedHistory? in - let reader = BufferReader(buffer) - var result: Api.messages.AffectedHistory? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AffectedHistory - } - return result - }) - } -} -public extension Api.functions.messages { - static func deleteMessages(flags: Int32, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-443640366) - serializeInt32(flags, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.deleteMessages", parameters: [("flags", String(describing: flags)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedMessages? in - let reader = BufferReader(buffer) - var result: Api.messages.AffectedMessages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AffectedMessages - } - return result - }) - } -} -public extension Api.functions.messages { - static func deletePhoneCallHistory(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-104078327) - serializeInt32(flags, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.deletePhoneCallHistory", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedFoundMessages? in - let reader = BufferReader(buffer) - var result: Api.messages.AffectedFoundMessages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AffectedFoundMessages - } - return result - }) - } -} -public extension Api.functions.messages { - static func deleteQuickReplyMessages(shortcutId: Int32, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-519706352) - serializeInt32(shortcutId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.deleteQuickReplyMessages", parameters: [("shortcutId", String(describing: shortcutId)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func deleteQuickReplyShortcut(shortcutId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1019234112) - serializeInt32(shortcutId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.deleteQuickReplyShortcut", parameters: [("shortcutId", String(describing: shortcutId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func deleteRevokedExportedChatInvites(peer: Api.InputPeer, adminId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1452833749) - peer.serialize(buffer, true) - adminId.serialize(buffer, true) - return (FunctionDescription(name: "messages.deleteRevokedExportedChatInvites", parameters: [("peer", String(describing: peer)), ("adminId", String(describing: adminId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func deleteSavedHistory(flags: Int32, parentPeer: Api.InputPeer?, peer: Api.InputPeer, maxId: Int32, minDate: Int32?, maxDate: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1304758367) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {parentPeer!.serialize(buffer, true)} - peer.serialize(buffer, true) - serializeInt32(maxId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(minDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(maxDate!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.deleteSavedHistory", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer)), ("peer", String(describing: peer)), ("maxId", String(describing: maxId)), ("minDate", String(describing: minDate)), ("maxDate", String(describing: maxDate))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedHistory? in - let reader = BufferReader(buffer) - var result: Api.messages.AffectedHistory? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AffectedHistory - } - return result - }) - } -} -public extension Api.functions.messages { - static func deleteScheduledMessages(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1504586518) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.deleteScheduledMessages", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func deleteTopicHistory(peer: Api.InputPeer, topMsgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-763269360) - peer.serialize(buffer, true) - serializeInt32(topMsgId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.deleteTopicHistory", parameters: [("peer", String(describing: peer)), ("topMsgId", String(describing: topMsgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedHistory? in - let reader = BufferReader(buffer) - var result: Api.messages.AffectedHistory? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AffectedHistory - } - return result - }) - } -} -public extension Api.functions.messages { - static func discardEncryption(flags: Int32, chatId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-208425312) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(chatId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.discardEncryption", parameters: [("flags", String(describing: flags)), ("chatId", String(describing: chatId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func editChatAbout(peer: Api.InputPeer, about: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-554301545) - peer.serialize(buffer, true) - serializeString(about, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.editChatAbout", parameters: [("peer", String(describing: peer)), ("about", String(describing: about))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func editChatAdmin(chatId: Int64, userId: Api.InputUser, isAdmin: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1470377534) - serializeInt64(chatId, buffer: buffer, boxed: false) - userId.serialize(buffer, true) - isAdmin.serialize(buffer, true) - return (FunctionDescription(name: "messages.editChatAdmin", parameters: [("chatId", String(describing: chatId)), ("userId", String(describing: userId)), ("isAdmin", String(describing: isAdmin))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func editChatDefaultBannedRights(peer: Api.InputPeer, bannedRights: Api.ChatBannedRights) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1517917375) - peer.serialize(buffer, true) - bannedRights.serialize(buffer, true) - return (FunctionDescription(name: "messages.editChatDefaultBannedRights", parameters: [("peer", String(describing: peer)), ("bannedRights", String(describing: bannedRights))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func editChatPhoto(chatId: Int64, photo: Api.InputChatPhoto) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(903730804) - serializeInt64(chatId, buffer: buffer, boxed: false) - photo.serialize(buffer, true) - return (FunctionDescription(name: "messages.editChatPhoto", parameters: [("chatId", String(describing: chatId)), ("photo", String(describing: photo))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func editChatTitle(chatId: Int64, title: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1937260541) - serializeInt64(chatId, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.editChatTitle", parameters: [("chatId", String(describing: chatId)), ("title", String(describing: title))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func editExportedChatInvite(flags: Int32, peer: Api.InputPeer, link: String, expireDate: Int32?, usageLimit: Int32?, requestNeeded: Api.Bool?, title: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1110823051) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeString(link, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(expireDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(usageLimit!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {requestNeeded!.serialize(buffer, true)} - if Int(flags) & Int(1 << 4) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.editExportedChatInvite", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("link", String(describing: link)), ("expireDate", String(describing: expireDate)), ("usageLimit", String(describing: usageLimit)), ("requestNeeded", String(describing: requestNeeded)), ("title", String(describing: title))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ExportedChatInvite? in - let reader = BufferReader(buffer) - var result: Api.messages.ExportedChatInvite? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.ExportedChatInvite - } - return result - }) - } -} -public extension Api.functions.messages { - static func editFactCheck(peer: Api.InputPeer, msgId: Int32, text: Api.TextWithEntities) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(92925557) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - text.serialize(buffer, true) - return (FunctionDescription(name: "messages.editFactCheck", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("text", String(describing: text))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func editForumTopic(flags: Int32, peer: Api.InputPeer, topicId: Int32, title: String?, iconEmojiId: Int64?, closed: Api.Bool?, hidden: Api.Bool?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-825487052) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(topicId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt64(iconEmojiId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {closed!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {hidden!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.editForumTopic", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("topicId", String(describing: topicId)), ("title", String(describing: title)), ("iconEmojiId", String(describing: iconEmojiId)), ("closed", String(describing: closed)), ("hidden", String(describing: hidden))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func editInlineBotMessage(flags: Int32, id: Api.InputBotInlineMessageID, message: String?, media: Api.InputMedia?, replyMarkup: Api.ReplyMarkup?, entities: [Api.MessageEntity]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2091549254) - serializeInt32(flags, buffer: buffer, boxed: false) - id.serialize(buffer, true) - if Int(flags) & Int(1 << 11) != 0 {serializeString(message!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 14) != 0 {media!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { - item.serialize(buffer, true) - }} - return (FunctionDescription(name: "messages.editInlineBotMessage", parameters: [("flags", String(describing: flags)), ("id", String(describing: id)), ("message", String(describing: message)), ("media", String(describing: media)), ("replyMarkup", String(describing: replyMarkup)), ("entities", String(describing: entities))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func editMessage(flags: Int32, peer: Api.InputPeer, id: Int32, message: String?, media: Api.InputMedia?, replyMarkup: Api.ReplyMarkup?, entities: [Api.MessageEntity]?, scheduleDate: Int32?, scheduleRepeatPeriod: Int32?, quickReplyShortcutId: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1374175969) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 11) != 0 {serializeString(message!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 14) != 0 {media!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 15) != 0 {serializeInt32(scheduleDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 18) != 0 {serializeInt32(scheduleRepeatPeriod!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 17) != 0 {serializeInt32(quickReplyShortcutId!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.editMessage", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("message", String(describing: message)), ("media", String(describing: media)), ("replyMarkup", String(describing: replyMarkup)), ("entities", String(describing: entities)), ("scheduleDate", String(describing: scheduleDate)), ("scheduleRepeatPeriod", String(describing: scheduleRepeatPeriod)), ("quickReplyShortcutId", String(describing: quickReplyShortcutId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func editQuickReplyShortcut(shortcutId: Int32, shortcut: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1543519471) - serializeInt32(shortcutId, buffer: buffer, boxed: false) - serializeString(shortcut, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.editQuickReplyShortcut", parameters: [("shortcutId", String(describing: shortcutId)), ("shortcut", String(describing: shortcut))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func exportChatInvite(flags: Int32, peer: Api.InputPeer, expireDate: Int32?, usageLimit: Int32?, title: String?, subscriptionPricing: Api.StarsSubscriptionPricing?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1537876336) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(expireDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(usageLimit!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {subscriptionPricing!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.exportChatInvite", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("expireDate", String(describing: expireDate)), ("usageLimit", String(describing: usageLimit)), ("title", String(describing: title)), ("subscriptionPricing", String(describing: subscriptionPricing))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ExportedChatInvite? in - let reader = BufferReader(buffer) - var result: Api.ExportedChatInvite? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite - } - return result - }) - } -} -public extension Api.functions.messages { - static func faveSticker(id: Api.InputDocument, unfave: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1174420133) - id.serialize(buffer, true) - unfave.serialize(buffer, true) - return (FunctionDescription(name: "messages.faveSticker", parameters: [("id", String(describing: id)), ("unfave", String(describing: unfave))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func forwardMessages(flags: Int32, fromPeer: Api.InputPeer, id: [Int32], randomId: [Int64], toPeer: Api.InputPeer, topMsgId: Int32?, replyTo: Api.InputReplyTo?, scheduleDate: Int32?, scheduleRepeatPeriod: Int32?, sendAs: Api.InputPeer?, quickReplyShortcut: Api.InputQuickReplyShortcut?, effect: Int64?, videoTimestamp: Int32?, allowPaidStars: Int64?, suggestedPost: Api.SuggestedPost?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(326126204) - serializeInt32(flags, buffer: buffer, boxed: false) - fromPeer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(randomId.count)) - for item in randomId { - serializeInt64(item, buffer: buffer, boxed: false) - } - toPeer.serialize(buffer, true) - if Int(flags) & Int(1 << 9) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 22) != 0 {replyTo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 10) != 0 {serializeInt32(scheduleDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 24) != 0 {serializeInt32(scheduleRepeatPeriod!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 13) != 0 {sendAs!.serialize(buffer, true)} - if Int(flags) & Int(1 << 17) != 0 {quickReplyShortcut!.serialize(buffer, true)} - if Int(flags) & Int(1 << 18) != 0 {serializeInt64(effect!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 20) != 0 {serializeInt32(videoTimestamp!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 21) != 0 {serializeInt64(allowPaidStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 23) != 0 {suggestedPost!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.forwardMessages", parameters: [("flags", String(describing: flags)), ("fromPeer", String(describing: fromPeer)), ("id", String(describing: id)), ("randomId", String(describing: randomId)), ("toPeer", String(describing: toPeer)), ("topMsgId", String(describing: topMsgId)), ("replyTo", String(describing: replyTo)), ("scheduleDate", String(describing: scheduleDate)), ("scheduleRepeatPeriod", String(describing: scheduleRepeatPeriod)), ("sendAs", String(describing: sendAs)), ("quickReplyShortcut", String(describing: quickReplyShortcut)), ("effect", String(describing: effect)), ("videoTimestamp", String(describing: videoTimestamp)), ("allowPaidStars", String(describing: allowPaidStars)), ("suggestedPost", String(describing: suggestedPost))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func getAdminsWithInvites(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(958457583) - peer.serialize(buffer, true) - return (FunctionDescription(name: "messages.getAdminsWithInvites", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ChatAdminsWithInvites? in - let reader = BufferReader(buffer) - var result: Api.messages.ChatAdminsWithInvites? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.ChatAdminsWithInvites - } - return result - }) - } -} -public extension Api.functions.messages { - static func getAllDrafts() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1782549861) - - return (FunctionDescription(name: "messages.getAllDrafts", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func getAllStickers(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1197432408) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getAllStickers", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AllStickers? in - let reader = BufferReader(buffer) - var result: Api.messages.AllStickers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AllStickers - } - return result - }) - } -} -public extension Api.functions.messages { - static func getArchivedStickers(flags: Int32, offsetId: Int64, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1475442322) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(offsetId, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getArchivedStickers", parameters: [("flags", String(describing: flags)), ("offsetId", String(describing: offsetId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ArchivedStickers? in - let reader = BufferReader(buffer) - var result: Api.messages.ArchivedStickers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.ArchivedStickers - } - return result - }) - } -} -public extension Api.functions.messages { - static func getAttachMenuBot(bot: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1998676370) - bot.serialize(buffer, true) - return (FunctionDescription(name: "messages.getAttachMenuBot", parameters: [("bot", String(describing: bot))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.AttachMenuBotsBot? in - let reader = BufferReader(buffer) - var result: Api.AttachMenuBotsBot? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.AttachMenuBotsBot - } - return result - }) - } -} -public extension Api.functions.messages { - static func getAttachMenuBots(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(385663691) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getAttachMenuBots", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.AttachMenuBots? in - let reader = BufferReader(buffer) - var result: Api.AttachMenuBots? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.AttachMenuBots - } - return result - }) - } -} -public extension Api.functions.messages { - static func getAttachedStickers(media: Api.InputStickeredMedia) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.StickerSetCovered]>) { - let buffer = Buffer() - buffer.appendInt32(-866424884) - media.serialize(buffer, true) - return (FunctionDescription(name: "messages.getAttachedStickers", parameters: [("media", String(describing: media))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.StickerSetCovered]? in - let reader = BufferReader(buffer) - var result: [Api.StickerSetCovered]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerSetCovered.self) - } - return result - }) - } -} -public extension Api.functions.messages { - static func getAvailableEffects(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-559805895) - serializeInt32(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getAvailableEffects", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AvailableEffects? in - let reader = BufferReader(buffer) - var result: Api.messages.AvailableEffects? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AvailableEffects - } - return result - }) - } -} -public extension Api.functions.messages { - static func getAvailableReactions(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(417243308) - serializeInt32(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getAvailableReactions", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AvailableReactions? in - let reader = BufferReader(buffer) - var result: Api.messages.AvailableReactions? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AvailableReactions - } - return result - }) - } -} -public extension Api.functions.messages { - static func getBotApp(app: Api.InputBotApp, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(889046467) - app.serialize(buffer, true) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getBotApp", parameters: [("app", String(describing: app)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.BotApp? in - let reader = BufferReader(buffer) - var result: Api.messages.BotApp? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.BotApp - } - return result - }) - } -} -public extension Api.functions.messages { - static func getBotCallbackAnswer(flags: Int32, peer: Api.InputPeer, msgId: Int32, data: Buffer?, password: Api.InputCheckPasswordSRP?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1824339449) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeBytes(data!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {password!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.getBotCallbackAnswer", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("data", String(describing: data)), ("password", String(describing: password))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.BotCallbackAnswer? in - let reader = BufferReader(buffer) - var result: Api.messages.BotCallbackAnswer? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.BotCallbackAnswer - } - return result - }) - } -} -public extension Api.functions.messages { - static func getChatInviteImporters(flags: Int32, peer: Api.InputPeer, link: String?, q: String?, offsetDate: Int32, offsetUser: Api.InputUser, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-553329330) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {serializeString(link!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(q!, buffer: buffer, boxed: false)} - serializeInt32(offsetDate, buffer: buffer, boxed: false) - offsetUser.serialize(buffer, true) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getChatInviteImporters", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("link", String(describing: link)), ("q", String(describing: q)), ("offsetDate", String(describing: offsetDate)), ("offsetUser", String(describing: offsetUser)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ChatInviteImporters? in - let reader = BufferReader(buffer) - var result: Api.messages.ChatInviteImporters? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.ChatInviteImporters - } - return result - }) - } -} -public extension Api.functions.messages { - static func getChats(id: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1240027791) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt64(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.getChats", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in - let reader = BufferReader(buffer) - var result: Api.messages.Chats? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Chats - } - return result - }) - } -} -public extension Api.functions.messages { - static func getCommonChats(userId: Api.InputUser, maxId: Int64, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-468934396) - userId.serialize(buffer, true) - serializeInt64(maxId, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getCommonChats", parameters: [("userId", String(describing: userId)), ("maxId", String(describing: maxId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in - let reader = BufferReader(buffer) - var result: Api.messages.Chats? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Chats - } - return result - }) - } -} -public extension Api.functions.messages { - static func getCustomEmojiDocuments(documentId: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.Document]>) { - let buffer = Buffer() - buffer.appendInt32(-643100844) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(documentId.count)) - for item in documentId { - serializeInt64(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.getCustomEmojiDocuments", parameters: [("documentId", String(describing: documentId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.Document]? in - let reader = BufferReader(buffer) - var result: [Api.Document]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) - } - return result - }) - } -} -public extension Api.functions.messages { - static func getDefaultHistoryTTL() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1703637384) - - return (FunctionDescription(name: "messages.getDefaultHistoryTTL", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.DefaultHistoryTTL? in - let reader = BufferReader(buffer) - var result: Api.DefaultHistoryTTL? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.DefaultHistoryTTL - } - return result - }) - } -} -public extension Api.functions.messages { - static func getDefaultTagReactions(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1107741656) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getDefaultTagReactions", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Reactions? in - let reader = BufferReader(buffer) - var result: Api.messages.Reactions? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Reactions - } - return result - }) - } -} -public extension Api.functions.messages { - static func getDhConfig(version: Int32, randomLength: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(651135312) - serializeInt32(version, buffer: buffer, boxed: false) - serializeInt32(randomLength, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getDhConfig", parameters: [("version", String(describing: version)), ("randomLength", String(describing: randomLength))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.DhConfig? in - let reader = BufferReader(buffer) - var result: Api.messages.DhConfig? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.DhConfig - } - return result - }) - } -} -public extension Api.functions.messages { - static func getDialogFilters() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-271283063) - - return (FunctionDescription(name: "messages.getDialogFilters", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.DialogFilters? in - let reader = BufferReader(buffer) - var result: Api.messages.DialogFilters? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.DialogFilters - } - return result - }) - } -} -public extension Api.functions.messages { - static func getDialogUnreadMarks(flags: Int32, parentPeer: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.DialogPeer]>) { - let buffer = Buffer() - buffer.appendInt32(555754018) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {parentPeer!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.getDialogUnreadMarks", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.DialogPeer]? in - let reader = BufferReader(buffer) - var result: [Api.DialogPeer]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.DialogPeer.self) - } - return result - }) - } -} -public extension Api.functions.messages { - static func getDialogs(flags: Int32, folderId: Int32?, offsetDate: Int32, offsetId: Int32, offsetPeer: Api.InputPeer, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1594569905) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(folderId!, buffer: buffer, boxed: false)} - serializeInt32(offsetDate, buffer: buffer, boxed: false) - serializeInt32(offsetId, buffer: buffer, boxed: false) - offsetPeer.serialize(buffer, true) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getDialogs", parameters: [("flags", String(describing: flags)), ("folderId", String(describing: folderId)), ("offsetDate", String(describing: offsetDate)), ("offsetId", String(describing: offsetId)), ("offsetPeer", String(describing: offsetPeer)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Dialogs? in - let reader = BufferReader(buffer) - var result: Api.messages.Dialogs? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Dialogs - } - return result - }) - } -} -public extension Api.functions.messages { - static func getDiscussionMessage(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1147761405) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getDiscussionMessage", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.DiscussionMessage? in - let reader = BufferReader(buffer) - var result: Api.messages.DiscussionMessage? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.DiscussionMessage - } - return result - }) - } -} -public extension Api.functions.messages { - static func getDocumentByHash(sha256: Buffer, size: Int64, mimeType: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1309538785) - serializeBytes(sha256, buffer: buffer, boxed: false) - serializeInt64(size, buffer: buffer, boxed: false) - serializeString(mimeType, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getDocumentByHash", parameters: [("sha256", String(describing: sha256)), ("size", String(describing: size)), ("mimeType", String(describing: mimeType))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Document? in - let reader = BufferReader(buffer) - var result: Api.Document? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Document - } - return result - }) - } -} -public extension Api.functions.messages { - static func getEmojiGameInfo() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-75592537) - - return (FunctionDescription(name: "messages.getEmojiGameInfo", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.EmojiGameInfo? in - let reader = BufferReader(buffer) - var result: Api.messages.EmojiGameInfo? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.EmojiGameInfo - } - return result - }) - } -} -public extension Api.functions.messages { - static func getEmojiGroups(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1955122779) - serializeInt32(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getEmojiGroups", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.EmojiGroups? in - let reader = BufferReader(buffer) - var result: Api.messages.EmojiGroups? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.EmojiGroups - } - return result - }) - } -} -public extension Api.functions.messages { - static func getEmojiKeywords(langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(899735650) - serializeString(langCode, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getEmojiKeywords", parameters: [("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiKeywordsDifference? in - let reader = BufferReader(buffer) - var result: Api.EmojiKeywordsDifference? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.EmojiKeywordsDifference - } - return result - }) - } -} -public extension Api.functions.messages { - static func getEmojiKeywordsDifference(langCode: String, fromVersion: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(352892591) - serializeString(langCode, buffer: buffer, boxed: false) - serializeInt32(fromVersion, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getEmojiKeywordsDifference", parameters: [("langCode", String(describing: langCode)), ("fromVersion", String(describing: fromVersion))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiKeywordsDifference? in - let reader = BufferReader(buffer) - var result: Api.EmojiKeywordsDifference? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.EmojiKeywordsDifference - } - return result - }) - } -} -public extension Api.functions.messages { - static func getEmojiKeywordsLanguages(langCodes: [String]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.EmojiLanguage]>) { - let buffer = Buffer() - buffer.appendInt32(1318675378) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(langCodes.count)) - for item in langCodes { - serializeString(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.getEmojiKeywordsLanguages", parameters: [("langCodes", String(describing: langCodes))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.EmojiLanguage]? in - let reader = BufferReader(buffer) - var result: [Api.EmojiLanguage]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.EmojiLanguage.self) - } - return result - }) - } -} -public extension Api.functions.messages { - static func getEmojiProfilePhotoGroups(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(564480243) - serializeInt32(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getEmojiProfilePhotoGroups", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.EmojiGroups? in - let reader = BufferReader(buffer) - var result: Api.messages.EmojiGroups? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.EmojiGroups - } - return result - }) - } -} -public extension Api.functions.messages { - static func getEmojiStatusGroups(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(785209037) - serializeInt32(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getEmojiStatusGroups", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.EmojiGroups? in - let reader = BufferReader(buffer) - var result: Api.messages.EmojiGroups? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.EmojiGroups - } - return result - }) - } -} -public extension Api.functions.messages { - static func getEmojiStickerGroups(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(500711669) - serializeInt32(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getEmojiStickerGroups", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.EmojiGroups? in - let reader = BufferReader(buffer) - var result: Api.messages.EmojiGroups? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.EmojiGroups - } - return result - }) - } -} -public extension Api.functions.messages { - static func getEmojiStickers(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-67329649) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getEmojiStickers", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AllStickers? in - let reader = BufferReader(buffer) - var result: Api.messages.AllStickers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AllStickers - } - return result - }) - } -} -public extension Api.functions.messages { - static func getEmojiURL(langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-709817306) - serializeString(langCode, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getEmojiURL", parameters: [("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiURL? in - let reader = BufferReader(buffer) - var result: Api.EmojiURL? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.EmojiURL - } - return result - }) - } -} -public extension Api.functions.messages { - static func getExportedChatInvite(peer: Api.InputPeer, link: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1937010524) - peer.serialize(buffer, true) - serializeString(link, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getExportedChatInvite", parameters: [("peer", String(describing: peer)), ("link", String(describing: link))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ExportedChatInvite? in - let reader = BufferReader(buffer) - var result: Api.messages.ExportedChatInvite? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.ExportedChatInvite - } - return result - }) - } -} -public extension Api.functions.messages { - static func getExportedChatInvites(flags: Int32, peer: Api.InputPeer, adminId: Api.InputUser, offsetDate: Int32?, offsetLink: String?, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1565154314) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - adminId.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(offsetDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(offsetLink!, buffer: buffer, boxed: false)} - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getExportedChatInvites", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("adminId", String(describing: adminId)), ("offsetDate", String(describing: offsetDate)), ("offsetLink", String(describing: offsetLink)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ExportedChatInvites? in - let reader = BufferReader(buffer) - var result: Api.messages.ExportedChatInvites? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.ExportedChatInvites - } - return result - }) - } -} -public extension Api.functions.messages { - static func getExtendedMedia(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2064119788) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.getExtendedMedia", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func getFactCheck(peer: Api.InputPeer, msgId: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.FactCheck]>) { - let buffer = Buffer() - buffer.appendInt32(-1177696786) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(msgId.count)) - for item in msgId { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.getFactCheck", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.FactCheck]? in - let reader = BufferReader(buffer) - var result: [Api.FactCheck]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.FactCheck.self) - } - return result - }) - } -} -public extension Api.functions.messages { - static func getFavedStickers(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(82946729) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getFavedStickers", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.FavedStickers? in - let reader = BufferReader(buffer) - var result: Api.messages.FavedStickers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.FavedStickers - } - return result - }) - } -} -public extension Api.functions.messages { - static func getFeaturedEmojiStickers(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(248473398) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getFeaturedEmojiStickers", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.FeaturedStickers? in - let reader = BufferReader(buffer) - var result: Api.messages.FeaturedStickers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.FeaturedStickers - } - return result - }) - } -} -public extension Api.functions.messages { - static func getFeaturedStickers(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1685588756) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getFeaturedStickers", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.FeaturedStickers? in - let reader = BufferReader(buffer) - var result: Api.messages.FeaturedStickers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.FeaturedStickers - } - return result - }) - } -} -public extension Api.functions.messages { - static func getForumTopics(flags: Int32, peer: Api.InputPeer, q: String?, offsetDate: Int32, offsetId: Int32, offsetTopic: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1000635391) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeString(q!, buffer: buffer, boxed: false)} - serializeInt32(offsetDate, buffer: buffer, boxed: false) - serializeInt32(offsetId, buffer: buffer, boxed: false) - serializeInt32(offsetTopic, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getForumTopics", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("q", String(describing: q)), ("offsetDate", String(describing: offsetDate)), ("offsetId", String(describing: offsetId)), ("offsetTopic", String(describing: offsetTopic)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ForumTopics? in - let reader = BufferReader(buffer) - var result: Api.messages.ForumTopics? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.ForumTopics - } - return result - }) - } -} -public extension Api.functions.messages { - static func getForumTopicsByID(peer: Api.InputPeer, topics: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1358280184) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(topics.count)) - for item in topics { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.getForumTopicsByID", parameters: [("peer", String(describing: peer)), ("topics", String(describing: topics))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ForumTopics? in - let reader = BufferReader(buffer) - var result: Api.messages.ForumTopics? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.ForumTopics - } - return result - }) - } -} -public extension Api.functions.messages { - static func getFullChat(chatId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1364194508) - serializeInt64(chatId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getFullChat", parameters: [("chatId", String(describing: chatId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ChatFull? in - let reader = BufferReader(buffer) - var result: Api.messages.ChatFull? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.ChatFull - } - return result - }) - } -} -public extension Api.functions.messages { - static func getGameHighScores(peer: Api.InputPeer, id: Int32, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-400399203) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - userId.serialize(buffer, true) - return (FunctionDescription(name: "messages.getGameHighScores", parameters: [("peer", String(describing: peer)), ("id", String(describing: id)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.HighScores? in - let reader = BufferReader(buffer) - var result: Api.messages.HighScores? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.HighScores - } - return result - }) - } -} -public extension Api.functions.messages { - static func getHistory(peer: Api.InputPeer, offsetId: Int32, offsetDate: Int32, addOffset: Int32, limit: Int32, maxId: Int32, minId: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1143203525) - peer.serialize(buffer, true) - serializeInt32(offsetId, buffer: buffer, boxed: false) - serializeInt32(offsetDate, buffer: buffer, boxed: false) - serializeInt32(addOffset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt32(maxId, buffer: buffer, boxed: false) - serializeInt32(minId, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getHistory", parameters: [("peer", String(describing: peer)), ("offsetId", String(describing: offsetId)), ("offsetDate", String(describing: offsetDate)), ("addOffset", String(describing: addOffset)), ("limit", String(describing: limit)), ("maxId", String(describing: maxId)), ("minId", String(describing: minId)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in - let reader = BufferReader(buffer) - var result: Api.messages.Messages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Messages - } - return result - }) - } -} -public extension Api.functions.messages { - static func getInlineBotResults(flags: Int32, bot: Api.InputUser, peer: Api.InputPeer, geoPoint: Api.InputGeoPoint?, query: String, offset: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1364105629) - serializeInt32(flags, buffer: buffer, boxed: false) - bot.serialize(buffer, true) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {geoPoint!.serialize(buffer, true)} - serializeString(query, buffer: buffer, boxed: false) - serializeString(offset, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getInlineBotResults", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("peer", String(describing: peer)), ("geoPoint", String(describing: geoPoint)), ("query", String(describing: query)), ("offset", String(describing: offset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.BotResults? in - let reader = BufferReader(buffer) - var result: Api.messages.BotResults? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.BotResults - } - return result - }) - } -} -public extension Api.functions.messages { - static func getInlineGameHighScores(id: Api.InputBotInlineMessageID, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(258170395) - id.serialize(buffer, true) - userId.serialize(buffer, true) - return (FunctionDescription(name: "messages.getInlineGameHighScores", parameters: [("id", String(describing: id)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.HighScores? in - let reader = BufferReader(buffer) - var result: Api.messages.HighScores? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.HighScores - } - return result - }) - } -} -public extension Api.functions.messages { - static func getMaskStickers(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1678738104) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getMaskStickers", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AllStickers? in - let reader = BufferReader(buffer) - var result: Api.messages.AllStickers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AllStickers - } - return result - }) - } -} -public extension Api.functions.messages { - static func getMessageEditData(peer: Api.InputPeer, id: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-39416522) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getMessageEditData", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.MessageEditData? in - let reader = BufferReader(buffer) - var result: Api.messages.MessageEditData? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.MessageEditData - } - return result - }) - } -} -public extension Api.functions.messages { - static func getMessageReactionsList(flags: Int32, peer: Api.InputPeer, id: Int32, reaction: Api.Reaction?, offset: String?, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1176190792) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {reaction!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(offset!, buffer: buffer, boxed: false)} - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getMessageReactionsList", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("reaction", String(describing: reaction)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.MessageReactionsList? in - let reader = BufferReader(buffer) - var result: Api.messages.MessageReactionsList? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.MessageReactionsList - } - return result - }) - } -} -public extension Api.functions.messages { - static func getMessageReadParticipants(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.ReadParticipantDate]>) { - let buffer = Buffer() - buffer.appendInt32(834782287) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getMessageReadParticipants", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.ReadParticipantDate]? in - let reader = BufferReader(buffer) - var result: [Api.ReadParticipantDate]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.ReadParticipantDate.self) - } - return result - }) - } -} -public extension Api.functions.messages { - static func getMessages(id: [Api.InputMessage]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1673946374) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "messages.getMessages", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in - let reader = BufferReader(buffer) - var result: Api.messages.Messages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Messages - } - return result - }) - } -} -public extension Api.functions.messages { - static func getMessagesReactions(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1950707482) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.getMessagesReactions", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func getMessagesViews(peer: Api.InputPeer, id: [Int32], increment: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1468322785) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - increment.serialize(buffer, true) - return (FunctionDescription(name: "messages.getMessagesViews", parameters: [("peer", String(describing: peer)), ("id", String(describing: id)), ("increment", String(describing: increment))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.MessageViews? in - let reader = BufferReader(buffer) - var result: Api.messages.MessageViews? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.MessageViews - } - return result - }) - } -} -public extension Api.functions.messages { - static func getMyStickers(offsetId: Int64, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-793386500) - serializeInt64(offsetId, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getMyStickers", parameters: [("offsetId", String(describing: offsetId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.MyStickers? in - let reader = BufferReader(buffer) - var result: Api.messages.MyStickers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.MyStickers - } - return result - }) - } -} -public extension Api.functions.messages { - static func getOldFeaturedStickers(offset: Int32, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2127598753) - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getOldFeaturedStickers", parameters: [("offset", String(describing: offset)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.FeaturedStickers? in - let reader = BufferReader(buffer) - var result: Api.messages.FeaturedStickers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.FeaturedStickers - } - return result - }) - } -} -public extension Api.functions.messages { - static func getOnlines(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1848369232) - peer.serialize(buffer, true) - return (FunctionDescription(name: "messages.getOnlines", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ChatOnlines? in - let reader = BufferReader(buffer) - var result: Api.ChatOnlines? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.ChatOnlines - } - return result - }) - } -} -public extension Api.functions.messages { - static func getOutboxReadDate(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1941176739) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getOutboxReadDate", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.OutboxReadDate? in - let reader = BufferReader(buffer) - var result: Api.OutboxReadDate? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.OutboxReadDate - } - return result - }) - } -} -public extension Api.functions.messages { - static func getPaidReactionPrivacy() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1193563562) - - return (FunctionDescription(name: "messages.getPaidReactionPrivacy", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func getPeerDialogs(peers: [Api.InputDialogPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-462373635) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peers.count)) - for item in peers { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "messages.getPeerDialogs", parameters: [("peers", String(describing: peers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.PeerDialogs? in - let reader = BufferReader(buffer) - var result: Api.messages.PeerDialogs? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.PeerDialogs - } - return result - }) - } -} -public extension Api.functions.messages { - static func getPeerSettings(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-270948702) - peer.serialize(buffer, true) - return (FunctionDescription(name: "messages.getPeerSettings", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.PeerSettings? in - let reader = BufferReader(buffer) - var result: Api.messages.PeerSettings? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.PeerSettings - } - return result - }) - } -} -public extension Api.functions.messages { - static func getPinnedDialogs(folderId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-692498958) - serializeInt32(folderId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getPinnedDialogs", parameters: [("folderId", String(describing: folderId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.PeerDialogs? in - let reader = BufferReader(buffer) - var result: Api.messages.PeerDialogs? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.PeerDialogs - } - return result - }) - } -} -public extension Api.functions.messages { - static func getPinnedSavedDialogs() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-700607264) - - return (FunctionDescription(name: "messages.getPinnedSavedDialogs", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SavedDialogs? in - let reader = BufferReader(buffer) - var result: Api.messages.SavedDialogs? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.SavedDialogs - } - return result - }) - } -} -public extension Api.functions.messages { - static func getPollResults(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1941660731) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getPollResults", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func getPollVotes(flags: Int32, peer: Api.InputPeer, id: Int32, option: Buffer?, offset: String?, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1200736242) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeBytes(option!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(offset!, buffer: buffer, boxed: false)} - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getPollVotes", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("option", String(describing: option)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.VotesList? in - let reader = BufferReader(buffer) - var result: Api.messages.VotesList? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.VotesList - } - return result - }) - } -} -public extension Api.functions.messages { - static func getPreparedInlineMessage(bot: Api.InputUser, id: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2055291464) - bot.serialize(buffer, true) - serializeString(id, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getPreparedInlineMessage", parameters: [("bot", String(describing: bot)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.PreparedInlineMessage? in - let reader = BufferReader(buffer) - var result: Api.messages.PreparedInlineMessage? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.PreparedInlineMessage - } - return result - }) - } -} -public extension Api.functions.messages { - static func getQuickReplies(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-729550168) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getQuickReplies", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.QuickReplies? in - let reader = BufferReader(buffer) - var result: Api.messages.QuickReplies? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.QuickReplies - } - return result - }) - } -} -public extension Api.functions.messages { - static func getQuickReplyMessages(flags: Int32, shortcutId: Int32, id: [Int32]?, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1801153085) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(shortcutId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id!.count)) - for item in id! { - serializeInt32(item, buffer: buffer, boxed: false) - }} - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getQuickReplyMessages", parameters: [("flags", String(describing: flags)), ("shortcutId", String(describing: shortcutId)), ("id", String(describing: id)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in - let reader = BufferReader(buffer) - var result: Api.messages.Messages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Messages - } - return result - }) - } -} -public extension Api.functions.messages { - static func getRecentLocations(peer: Api.InputPeer, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1881817312) - peer.serialize(buffer, true) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getRecentLocations", parameters: [("peer", String(describing: peer)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in - let reader = BufferReader(buffer) - var result: Api.messages.Messages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Messages - } - return result - }) - } -} -public extension Api.functions.messages { - static func getRecentReactions(limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(960896434) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getRecentReactions", parameters: [("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Reactions? in - let reader = BufferReader(buffer) - var result: Api.messages.Reactions? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Reactions - } - return result - }) - } -} -public extension Api.functions.messages { - static func getRecentStickers(flags: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1649852357) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getRecentStickers", parameters: [("flags", String(describing: flags)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.RecentStickers? in - let reader = BufferReader(buffer) - var result: Api.messages.RecentStickers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.RecentStickers - } - return result - }) - } -} -public extension Api.functions.messages { - static func getReplies(peer: Api.InputPeer, msgId: Int32, offsetId: Int32, offsetDate: Int32, addOffset: Int32, limit: Int32, maxId: Int32, minId: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(584962828) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeInt32(offsetId, buffer: buffer, boxed: false) - serializeInt32(offsetDate, buffer: buffer, boxed: false) - serializeInt32(addOffset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt32(maxId, buffer: buffer, boxed: false) - serializeInt32(minId, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getReplies", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("offsetId", String(describing: offsetId)), ("offsetDate", String(describing: offsetDate)), ("addOffset", String(describing: addOffset)), ("limit", String(describing: limit)), ("maxId", String(describing: maxId)), ("minId", String(describing: minId)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in - let reader = BufferReader(buffer) - var result: Api.messages.Messages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Messages - } - return result - }) - } -} -public extension Api.functions.messages { - static func getSavedDialogs(flags: Int32, parentPeer: Api.InputPeer?, offsetDate: Int32, offsetId: Int32, offsetPeer: Api.InputPeer, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(512883865) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {parentPeer!.serialize(buffer, true)} - serializeInt32(offsetDate, buffer: buffer, boxed: false) - serializeInt32(offsetId, buffer: buffer, boxed: false) - offsetPeer.serialize(buffer, true) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getSavedDialogs", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer)), ("offsetDate", String(describing: offsetDate)), ("offsetId", String(describing: offsetId)), ("offsetPeer", String(describing: offsetPeer)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SavedDialogs? in - let reader = BufferReader(buffer) - var result: Api.messages.SavedDialogs? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.SavedDialogs - } - return result - }) - } -} -public extension Api.functions.messages { - static func getSavedDialogsByID(flags: Int32, parentPeer: Api.InputPeer?, ids: [Api.InputPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1869585558) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {parentPeer!.serialize(buffer, true)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(ids.count)) - for item in ids { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "messages.getSavedDialogsByID", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer)), ("ids", String(describing: ids))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SavedDialogs? in - let reader = BufferReader(buffer) - var result: Api.messages.SavedDialogs? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.SavedDialogs - } - return result - }) - } -} -public extension Api.functions.messages { - static func getSavedGifs(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1559270965) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getSavedGifs", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SavedGifs? in - let reader = BufferReader(buffer) - var result: Api.messages.SavedGifs? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.SavedGifs - } - return result - }) - } -} -public extension Api.functions.messages { - static func getSavedHistory(flags: Int32, parentPeer: Api.InputPeer?, peer: Api.InputPeer, offsetId: Int32, offsetDate: Int32, addOffset: Int32, limit: Int32, maxId: Int32, minId: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1718964215) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {parentPeer!.serialize(buffer, true)} - peer.serialize(buffer, true) - serializeInt32(offsetId, buffer: buffer, boxed: false) - serializeInt32(offsetDate, buffer: buffer, boxed: false) - serializeInt32(addOffset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt32(maxId, buffer: buffer, boxed: false) - serializeInt32(minId, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getSavedHistory", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer)), ("peer", String(describing: peer)), ("offsetId", String(describing: offsetId)), ("offsetDate", String(describing: offsetDate)), ("addOffset", String(describing: addOffset)), ("limit", String(describing: limit)), ("maxId", String(describing: maxId)), ("minId", String(describing: minId)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in - let reader = BufferReader(buffer) - var result: Api.messages.Messages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Messages - } - return result - }) - } -} -public extension Api.functions.messages { - static func getSavedReactionTags(flags: Int32, peer: Api.InputPeer?, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(909631579) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {peer!.serialize(buffer, true)} - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getSavedReactionTags", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SavedReactionTags? in - let reader = BufferReader(buffer) - var result: Api.messages.SavedReactionTags? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.SavedReactionTags - } - return result - }) - } -} -public extension Api.functions.messages { - static func getScheduledHistory(peer: Api.InputPeer, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-183077365) - peer.serialize(buffer, true) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getScheduledHistory", parameters: [("peer", String(describing: peer)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in - let reader = BufferReader(buffer) - var result: Api.messages.Messages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Messages - } - return result - }) - } -} -public extension Api.functions.messages { - static func getScheduledMessages(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1111817116) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.getScheduledMessages", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in - let reader = BufferReader(buffer) - var result: Api.messages.Messages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Messages - } - return result - }) - } -} -public extension Api.functions.messages { - static func getSearchCounters(flags: Int32, peer: Api.InputPeer, savedPeerId: Api.InputPeer?, topMsgId: Int32?, filters: [Api.MessagesFilter]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.messages.SearchCounter]>) { - let buffer = Buffer() - buffer.appendInt32(465367808) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {savedPeerId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(filters.count)) - for item in filters { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "messages.getSearchCounters", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("savedPeerId", String(describing: savedPeerId)), ("topMsgId", String(describing: topMsgId)), ("filters", String(describing: filters))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.messages.SearchCounter]? in - let reader = BufferReader(buffer) - var result: [Api.messages.SearchCounter]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.messages.SearchCounter.self) - } - return result - }) - } -} -public extension Api.functions.messages { - static func getSearchResultsCalendar(flags: Int32, peer: Api.InputPeer, savedPeerId: Api.InputPeer?, filter: Api.MessagesFilter, offsetId: Int32, offsetDate: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1789130429) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {savedPeerId!.serialize(buffer, true)} - filter.serialize(buffer, true) - serializeInt32(offsetId, buffer: buffer, boxed: false) - serializeInt32(offsetDate, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getSearchResultsCalendar", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("savedPeerId", String(describing: savedPeerId)), ("filter", String(describing: filter)), ("offsetId", String(describing: offsetId)), ("offsetDate", String(describing: offsetDate))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SearchResultsCalendar? in - let reader = BufferReader(buffer) - var result: Api.messages.SearchResultsCalendar? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.SearchResultsCalendar - } - return result - }) - } -} -public extension Api.functions.messages { - static func getSearchResultsPositions(flags: Int32, peer: Api.InputPeer, savedPeerId: Api.InputPeer?, filter: Api.MessagesFilter, offsetId: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1669386480) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {savedPeerId!.serialize(buffer, true)} - filter.serialize(buffer, true) - serializeInt32(offsetId, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getSearchResultsPositions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("savedPeerId", String(describing: savedPeerId)), ("filter", String(describing: filter)), ("offsetId", String(describing: offsetId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SearchResultsPositions? in - let reader = BufferReader(buffer) - var result: Api.messages.SearchResultsPositions? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.SearchResultsPositions - } - return result - }) - } -} -public extension Api.functions.messages { - static func getSplitRanges() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.MessageRange]>) { - let buffer = Buffer() - buffer.appendInt32(486505992) - - return (FunctionDescription(name: "messages.getSplitRanges", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.MessageRange]? in - let reader = BufferReader(buffer) - var result: [Api.MessageRange]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageRange.self) - } - return result - }) - } -} -public extension Api.functions.messages { - static func getSponsoredMessages(flags: Int32, peer: Api.InputPeer, msgId: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1030547536) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(msgId!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.getSponsoredMessages", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SponsoredMessages? in - let reader = BufferReader(buffer) - var result: Api.messages.SponsoredMessages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.SponsoredMessages - } - return result - }) - } -} -public extension Api.functions.messages { - static func getStickerSet(stickerset: Api.InputStickerSet, hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-928977804) - stickerset.serialize(buffer, true) - serializeInt32(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getStickerSet", parameters: [("stickerset", String(describing: stickerset)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in - let reader = BufferReader(buffer) - var result: Api.messages.StickerSet? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet - } - return result - }) - } -} -public extension Api.functions.messages { - static func getStickers(emoticon: String, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-710552671) - serializeString(emoticon, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getStickers", parameters: [("emoticon", String(describing: emoticon)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Stickers? in - let reader = BufferReader(buffer) - var result: Api.messages.Stickers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Stickers - } - return result - }) - } -} -public extension Api.functions.messages { - static func getSuggestedDialogFilters() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.DialogFilterSuggested]>) { - let buffer = Buffer() - buffer.appendInt32(-1566780372) - - return (FunctionDescription(name: "messages.getSuggestedDialogFilters", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.DialogFilterSuggested]? in - let reader = BufferReader(buffer) - var result: [Api.DialogFilterSuggested]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.DialogFilterSuggested.self) - } - return result - }) - } -} -public extension Api.functions.messages { - static func getTopReactions(limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1149164102) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getTopReactions", parameters: [("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Reactions? in - let reader = BufferReader(buffer) - var result: Api.messages.Reactions? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Reactions - } - return result - }) - } -} -public extension Api.functions.messages { - static func getUnreadMentions(flags: Int32, peer: Api.InputPeer, topMsgId: Int32?, offsetId: Int32, addOffset: Int32, limit: Int32, maxId: Int32, minId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-251140208) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - serializeInt32(offsetId, buffer: buffer, boxed: false) - serializeInt32(addOffset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt32(maxId, buffer: buffer, boxed: false) - serializeInt32(minId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getUnreadMentions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("topMsgId", String(describing: topMsgId)), ("offsetId", String(describing: offsetId)), ("addOffset", String(describing: addOffset)), ("limit", String(describing: limit)), ("maxId", String(describing: maxId)), ("minId", String(describing: minId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in - let reader = BufferReader(buffer) - var result: Api.messages.Messages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Messages - } - return result - }) - } -} -public extension Api.functions.messages { - static func getUnreadReactions(flags: Int32, peer: Api.InputPeer, topMsgId: Int32?, savedPeerId: Api.InputPeer?, offsetId: Int32, addOffset: Int32, limit: Int32, maxId: Int32, minId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1115713364) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {savedPeerId!.serialize(buffer, true)} - serializeInt32(offsetId, buffer: buffer, boxed: false) - serializeInt32(addOffset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt32(maxId, buffer: buffer, boxed: false) - serializeInt32(minId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getUnreadReactions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("topMsgId", String(describing: topMsgId)), ("savedPeerId", String(describing: savedPeerId)), ("offsetId", String(describing: offsetId)), ("addOffset", String(describing: addOffset)), ("limit", String(describing: limit)), ("maxId", String(describing: maxId)), ("minId", String(describing: minId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in - let reader = BufferReader(buffer) - var result: Api.messages.Messages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Messages - } - return result - }) - } -} -public extension Api.functions.messages { - static func getWebPage(url: String, hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1919511901) - serializeString(url, buffer: buffer, boxed: false) - serializeInt32(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.getWebPage", parameters: [("url", String(describing: url)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.WebPage? in - let reader = BufferReader(buffer) - var result: Api.messages.WebPage? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.WebPage - } - return result - }) - } -} -public extension Api.functions.messages { - static func getWebPagePreview(flags: Int32, message: String, entities: [Api.MessageEntity]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1460498287) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { - item.serialize(buffer, true) - }} - return (FunctionDescription(name: "messages.getWebPagePreview", parameters: [("flags", String(describing: flags)), ("message", String(describing: message)), ("entities", String(describing: entities))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.WebPagePreview? in - let reader = BufferReader(buffer) - var result: Api.messages.WebPagePreview? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.WebPagePreview - } - return result - }) - } -} -public extension Api.functions.messages { - static func hideAllChatJoinRequests(flags: Int32, peer: Api.InputPeer, link: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-528091926) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {serializeString(link!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.hideAllChatJoinRequests", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("link", String(describing: link))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func hideChatJoinRequest(flags: Int32, peer: Api.InputPeer, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2145904661) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - userId.serialize(buffer, true) - return (FunctionDescription(name: "messages.hideChatJoinRequest", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func hidePeerSettingsBar(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1336717624) - peer.serialize(buffer, true) - return (FunctionDescription(name: "messages.hidePeerSettingsBar", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func importChatInvite(hash: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1817183516) - serializeString(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.importChatInvite", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func initHistoryImport(peer: Api.InputPeer, file: Api.InputFile, mediaCount: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(873008187) - peer.serialize(buffer, true) - file.serialize(buffer, true) - serializeInt32(mediaCount, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.initHistoryImport", parameters: [("peer", String(describing: peer)), ("file", String(describing: file)), ("mediaCount", String(describing: mediaCount))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.HistoryImport? in - let reader = BufferReader(buffer) - var result: Api.messages.HistoryImport? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.HistoryImport - } - return result - }) - } -} -public extension Api.functions.messages { - static func installStickerSet(stickerset: Api.InputStickerSet, archived: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-946871200) - stickerset.serialize(buffer, true) - archived.serialize(buffer, true) - return (FunctionDescription(name: "messages.installStickerSet", parameters: [("stickerset", String(describing: stickerset)), ("archived", String(describing: archived))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSetInstallResult? in - let reader = BufferReader(buffer) - var result: Api.messages.StickerSetInstallResult? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.StickerSetInstallResult - } - return result - }) - } -} -public extension Api.functions.messages { - static func markDialogUnread(flags: Int32, parentPeer: Api.InputPeer?, peer: Api.InputDialogPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1940912392) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {parentPeer!.serialize(buffer, true)} - peer.serialize(buffer, true) - return (FunctionDescription(name: "messages.markDialogUnread", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func migrateChat(chatId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1568189671) - serializeInt64(chatId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.migrateChat", parameters: [("chatId", String(describing: chatId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func prolongWebView(flags: Int32, peer: Api.InputPeer, bot: Api.InputUser, queryId: Int64, replyTo: Api.InputReplyTo?, sendAs: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1328014717) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - bot.serialize(buffer, true) - serializeInt64(queryId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {replyTo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 13) != 0 {sendAs!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.prolongWebView", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("bot", String(describing: bot)), ("queryId", String(describing: queryId)), ("replyTo", String(describing: replyTo)), ("sendAs", String(describing: sendAs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func rateTranscribedAudio(peer: Api.InputPeer, msgId: Int32, transcriptionId: Int64, good: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2132608815) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeInt64(transcriptionId, buffer: buffer, boxed: false) - good.serialize(buffer, true) - return (FunctionDescription(name: "messages.rateTranscribedAudio", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("transcriptionId", String(describing: transcriptionId)), ("good", String(describing: good))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func readDiscussion(peer: Api.InputPeer, msgId: Int32, readMaxId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-147740172) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeInt32(readMaxId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.readDiscussion", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("readMaxId", String(describing: readMaxId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func readEncryptedHistory(peer: Api.InputEncryptedChat, maxDate: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2135648522) - peer.serialize(buffer, true) - serializeInt32(maxDate, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.readEncryptedHistory", parameters: [("peer", String(describing: peer)), ("maxDate", String(describing: maxDate))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func readFeaturedStickers(id: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1527873830) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt64(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.readFeaturedStickers", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func readHistory(peer: Api.InputPeer, maxId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(238054714) - peer.serialize(buffer, true) - serializeInt32(maxId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.readHistory", parameters: [("peer", String(describing: peer)), ("maxId", String(describing: maxId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedMessages? in - let reader = BufferReader(buffer) - var result: Api.messages.AffectedMessages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AffectedMessages - } - return result - }) - } -} -public extension Api.functions.messages { - static func readMentions(flags: Int32, peer: Api.InputPeer, topMsgId: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(921026381) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.readMentions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("topMsgId", String(describing: topMsgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedHistory? in - let reader = BufferReader(buffer) - var result: Api.messages.AffectedHistory? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AffectedHistory - } - return result - }) - } -} -public extension Api.functions.messages { - static func readMessageContents(id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(916930423) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.readMessageContents", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedMessages? in - let reader = BufferReader(buffer) - var result: Api.messages.AffectedMessages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AffectedMessages - } - return result - }) - } -} -public extension Api.functions.messages { - static func readReactions(flags: Int32, peer: Api.InputPeer, topMsgId: Int32?, savedPeerId: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1631301741) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {savedPeerId!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.readReactions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("topMsgId", String(describing: topMsgId)), ("savedPeerId", String(describing: savedPeerId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedHistory? in - let reader = BufferReader(buffer) - var result: Api.messages.AffectedHistory? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AffectedHistory - } - return result - }) - } -} -public extension Api.functions.messages { - static func readSavedHistory(parentPeer: Api.InputPeer, peer: Api.InputPeer, maxId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1169540261) - parentPeer.serialize(buffer, true) - peer.serialize(buffer, true) - serializeInt32(maxId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.readSavedHistory", parameters: [("parentPeer", String(describing: parentPeer)), ("peer", String(describing: peer)), ("maxId", String(describing: maxId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func receivedMessages(maxId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.ReceivedNotifyMessage]>) { - let buffer = Buffer() - buffer.appendInt32(94983360) - serializeInt32(maxId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.receivedMessages", parameters: [("maxId", String(describing: maxId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.ReceivedNotifyMessage]? in - let reader = BufferReader(buffer) - var result: [Api.ReceivedNotifyMessage]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.ReceivedNotifyMessage.self) - } - return result - }) - } -} -public extension Api.functions.messages { - static func receivedQueue(maxQts: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Int64]>) { - let buffer = Buffer() - buffer.appendInt32(1436924774) - serializeInt32(maxQts, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.receivedQueue", parameters: [("maxQts", String(describing: maxQts))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Int64]? in - let reader = BufferReader(buffer) - var result: [Int64]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) - } - return result - }) - } -} -public extension Api.functions.messages { - static func reorderPinnedDialogs(flags: Int32, folderId: Int32, order: [Api.InputDialogPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(991616823) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(folderId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order.count)) - for item in order { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "messages.reorderPinnedDialogs", parameters: [("flags", String(describing: flags)), ("folderId", String(describing: folderId)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func reorderPinnedForumTopics(flags: Int32, peer: Api.InputPeer, order: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(242762224) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order.count)) - for item in order { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.reorderPinnedForumTopics", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func reorderPinnedSavedDialogs(flags: Int32, order: [Api.InputDialogPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1955502713) - serializeInt32(flags, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order.count)) - for item in order { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "messages.reorderPinnedSavedDialogs", parameters: [("flags", String(describing: flags)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func reorderQuickReplies(order: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1613961479) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order.count)) - for item in order { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.reorderQuickReplies", parameters: [("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func reorderStickerSets(flags: Int32, order: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2016638777) - serializeInt32(flags, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order.count)) - for item in order { - serializeInt64(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.reorderStickerSets", parameters: [("flags", String(describing: flags)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func report(peer: Api.InputPeer, id: [Int32], option: Buffer, message: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-59199589) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - serializeBytes(option, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.report", parameters: [("peer", String(describing: peer)), ("id", String(describing: id)), ("option", String(describing: option)), ("message", String(describing: message))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ReportResult? in - let reader = BufferReader(buffer) - var result: Api.ReportResult? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.ReportResult - } - return result - }) - } -} -public extension Api.functions.messages { - static func reportEncryptedSpam(peer: Api.InputEncryptedChat) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1259113487) - peer.serialize(buffer, true) - return (FunctionDescription(name: "messages.reportEncryptedSpam", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func reportMessagesDelivery(flags: Int32, peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1517122453) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.reportMessagesDelivery", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func reportReaction(peer: Api.InputPeer, id: Int32, reactionPeer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1063567478) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - reactionPeer.serialize(buffer, true) - return (FunctionDescription(name: "messages.reportReaction", parameters: [("peer", String(describing: peer)), ("id", String(describing: id)), ("reactionPeer", String(describing: reactionPeer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func reportSpam(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-820669733) - peer.serialize(buffer, true) - return (FunctionDescription(name: "messages.reportSpam", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func reportSponsoredMessage(randomId: Buffer, option: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(315355332) - serializeBytes(randomId, buffer: buffer, boxed: false) - serializeBytes(option, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.reportSponsoredMessage", parameters: [("randomId", String(describing: randomId)), ("option", String(describing: option))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.channels.SponsoredMessageReportResult? in - let reader = BufferReader(buffer) - var result: Api.channels.SponsoredMessageReportResult? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.channels.SponsoredMessageReportResult - } - return result - }) - } -} -public extension Api.functions.messages { - static func requestAppWebView(flags: Int32, peer: Api.InputPeer, app: Api.InputBotApp, startParam: String?, themeParams: Api.DataJSON?, platform: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1398901710) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - app.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {serializeString(startParam!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {themeParams!.serialize(buffer, true)} - serializeString(platform, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.requestAppWebView", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("app", String(describing: app)), ("startParam", String(describing: startParam)), ("themeParams", String(describing: themeParams)), ("platform", String(describing: platform))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.WebViewResult? in - let reader = BufferReader(buffer) - var result: Api.WebViewResult? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.WebViewResult - } - return result - }) - } -} -public extension Api.functions.messages { - static func requestEncryption(userId: Api.InputUser, randomId: Int32, gA: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-162681021) - userId.serialize(buffer, true) - serializeInt32(randomId, buffer: buffer, boxed: false) - serializeBytes(gA, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.requestEncryption", parameters: [("userId", String(describing: userId)), ("randomId", String(describing: randomId)), ("gA", String(describing: gA))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EncryptedChat? in - let reader = BufferReader(buffer) - var result: Api.EncryptedChat? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.EncryptedChat - } - return result - }) - } -} -public extension Api.functions.messages { - static func requestMainWebView(flags: Int32, peer: Api.InputPeer, bot: Api.InputUser, startParam: String?, themeParams: Api.DataJSON?, platform: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-908059013) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - bot.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {serializeString(startParam!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {themeParams!.serialize(buffer, true)} - serializeString(platform, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.requestMainWebView", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("bot", String(describing: bot)), ("startParam", String(describing: startParam)), ("themeParams", String(describing: themeParams)), ("platform", String(describing: platform))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.WebViewResult? in - let reader = BufferReader(buffer) - var result: Api.WebViewResult? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.WebViewResult - } - return result - }) - } -} -public extension Api.functions.messages { - static func requestSimpleWebView(flags: Int32, bot: Api.InputUser, url: String?, startParam: String?, themeParams: Api.DataJSON?, platform: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1094336115) - serializeInt32(flags, buffer: buffer, boxed: false) - bot.serialize(buffer, true) - if Int(flags) & Int(1 << 3) != 0 {serializeString(url!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeString(startParam!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {themeParams!.serialize(buffer, true)} - serializeString(platform, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.requestSimpleWebView", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("url", String(describing: url)), ("startParam", String(describing: startParam)), ("themeParams", String(describing: themeParams)), ("platform", String(describing: platform))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.WebViewResult? in - let reader = BufferReader(buffer) - var result: Api.WebViewResult? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.WebViewResult - } - return result - }) - } -} -public extension Api.functions.messages { - static func requestUrlAuth(flags: Int32, peer: Api.InputPeer?, msgId: Int32?, buttonId: Int32?, url: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(428848198) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {peer!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(msgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(buttonId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(url!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.requestUrlAuth", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("buttonId", String(describing: buttonId)), ("url", String(describing: url))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.UrlAuthResult? in - let reader = BufferReader(buffer) - var result: Api.UrlAuthResult? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.UrlAuthResult - } - return result - }) - } -} -public extension Api.functions.messages { - static func requestWebView(flags: Int32, peer: Api.InputPeer, bot: Api.InputUser, url: String?, startParam: String?, themeParams: Api.DataJSON?, platform: String, replyTo: Api.InputReplyTo?, sendAs: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(647873217) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - bot.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {serializeString(url!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeString(startParam!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {themeParams!.serialize(buffer, true)} - serializeString(platform, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {replyTo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 13) != 0 {sendAs!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.requestWebView", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("bot", String(describing: bot)), ("url", String(describing: url)), ("startParam", String(describing: startParam)), ("themeParams", String(describing: themeParams)), ("platform", String(describing: platform)), ("replyTo", String(describing: replyTo)), ("sendAs", String(describing: sendAs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.WebViewResult? in - let reader = BufferReader(buffer) - var result: Api.WebViewResult? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.WebViewResult - } - return result - }) - } -} -public extension Api.functions.messages { - static func saveDefaultSendAs(peer: Api.InputPeer, sendAs: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-855777386) - peer.serialize(buffer, true) - sendAs.serialize(buffer, true) - return (FunctionDescription(name: "messages.saveDefaultSendAs", parameters: [("peer", String(describing: peer)), ("sendAs", String(describing: sendAs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func saveDraft(flags: Int32, replyTo: Api.InputReplyTo?, peer: Api.InputPeer, message: String, entities: [Api.MessageEntity]?, media: Api.InputMedia?, effect: Int64?, suggestedPost: Api.SuggestedPost?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1420701838) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {replyTo!.serialize(buffer, true)} - peer.serialize(buffer, true) - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 5) != 0 {media!.serialize(buffer, true)} - if Int(flags) & Int(1 << 7) != 0 {serializeInt64(effect!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {suggestedPost!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.saveDraft", parameters: [("flags", String(describing: flags)), ("replyTo", String(describing: replyTo)), ("peer", String(describing: peer)), ("message", String(describing: message)), ("entities", String(describing: entities)), ("media", String(describing: media)), ("effect", String(describing: effect)), ("suggestedPost", String(describing: suggestedPost))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func saveGif(id: Api.InputDocument, unsave: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(846868683) - id.serialize(buffer, true) - unsave.serialize(buffer, true) - return (FunctionDescription(name: "messages.saveGif", parameters: [("id", String(describing: id)), ("unsave", String(describing: unsave))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func savePreparedInlineMessage(flags: Int32, result: Api.InputBotInlineResult, userId: Api.InputUser, peerTypes: [Api.InlineQueryPeerType]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-232816849) - serializeInt32(flags, buffer: buffer, boxed: false) - result.serialize(buffer, true) - userId.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peerTypes!.count)) - for item in peerTypes! { - item.serialize(buffer, true) - }} - return (FunctionDescription(name: "messages.savePreparedInlineMessage", parameters: [("flags", String(describing: flags)), ("result", String(describing: result)), ("userId", String(describing: userId)), ("peerTypes", String(describing: peerTypes))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.BotPreparedInlineMessage? in - let reader = BufferReader(buffer) - var result: Api.messages.BotPreparedInlineMessage? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.BotPreparedInlineMessage - } - return result - }) - } -} -public extension Api.functions.messages { - static func saveRecentSticker(flags: Int32, id: Api.InputDocument, unsave: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(958863608) - serializeInt32(flags, buffer: buffer, boxed: false) - id.serialize(buffer, true) - unsave.serialize(buffer, true) - return (FunctionDescription(name: "messages.saveRecentSticker", parameters: [("flags", String(describing: flags)), ("id", String(describing: id)), ("unsave", String(describing: unsave))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func search(flags: Int32, peer: Api.InputPeer, q: String, fromId: Api.InputPeer?, savedPeerId: Api.InputPeer?, savedReaction: [Api.Reaction]?, topMsgId: Int32?, filter: Api.MessagesFilter, minDate: Int32, maxDate: Int32, offsetId: Int32, addOffset: Int32, limit: Int32, maxId: Int32, minId: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(703497338) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeString(q, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {fromId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {savedPeerId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(savedReaction!.count)) - for item in savedReaction! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - filter.serialize(buffer, true) - serializeInt32(minDate, buffer: buffer, boxed: false) - serializeInt32(maxDate, buffer: buffer, boxed: false) - serializeInt32(offsetId, buffer: buffer, boxed: false) - serializeInt32(addOffset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt32(maxId, buffer: buffer, boxed: false) - serializeInt32(minId, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.search", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("q", String(describing: q)), ("fromId", String(describing: fromId)), ("savedPeerId", String(describing: savedPeerId)), ("savedReaction", String(describing: savedReaction)), ("topMsgId", String(describing: topMsgId)), ("filter", String(describing: filter)), ("minDate", String(describing: minDate)), ("maxDate", String(describing: maxDate)), ("offsetId", String(describing: offsetId)), ("addOffset", String(describing: addOffset)), ("limit", String(describing: limit)), ("maxId", String(describing: maxId)), ("minId", String(describing: minId)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in - let reader = BufferReader(buffer) - var result: Api.messages.Messages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Messages - } - return result - }) - } -} -public extension Api.functions.messages { - static func searchCustomEmoji(emoticon: String, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(739360983) - serializeString(emoticon, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.searchCustomEmoji", parameters: [("emoticon", String(describing: emoticon)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiList? in - let reader = BufferReader(buffer) - var result: Api.EmojiList? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.EmojiList - } - return result - }) - } -} -public extension Api.functions.messages { - static func searchEmojiStickerSets(flags: Int32, q: String, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1833678516) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(q, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.searchEmojiStickerSets", parameters: [("flags", String(describing: flags)), ("q", String(describing: q)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.FoundStickerSets? in - let reader = BufferReader(buffer) - var result: Api.messages.FoundStickerSets? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.FoundStickerSets - } - return result - }) - } -} -public extension Api.functions.messages { - static func searchGlobal(flags: Int32, folderId: Int32?, q: String, filter: Api.MessagesFilter, minDate: Int32, maxDate: Int32, offsetRate: Int32, offsetPeer: Api.InputPeer, offsetId: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1271290010) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(folderId!, buffer: buffer, boxed: false)} - serializeString(q, buffer: buffer, boxed: false) - filter.serialize(buffer, true) - serializeInt32(minDate, buffer: buffer, boxed: false) - serializeInt32(maxDate, buffer: buffer, boxed: false) - serializeInt32(offsetRate, buffer: buffer, boxed: false) - offsetPeer.serialize(buffer, true) - serializeInt32(offsetId, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.searchGlobal", parameters: [("flags", String(describing: flags)), ("folderId", String(describing: folderId)), ("q", String(describing: q)), ("filter", String(describing: filter)), ("minDate", String(describing: minDate)), ("maxDate", String(describing: maxDate)), ("offsetRate", String(describing: offsetRate)), ("offsetPeer", String(describing: offsetPeer)), ("offsetId", String(describing: offsetId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in - let reader = BufferReader(buffer) - var result: Api.messages.Messages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Messages - } - return result - }) - } -} -public extension Api.functions.messages { - static func searchSentMedia(q: String, filter: Api.MessagesFilter, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(276705696) - serializeString(q, buffer: buffer, boxed: false) - filter.serialize(buffer, true) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.searchSentMedia", parameters: [("q", String(describing: q)), ("filter", String(describing: filter)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in - let reader = BufferReader(buffer) - var result: Api.messages.Messages? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Messages - } - return result - }) - } -} -public extension Api.functions.messages { - static func searchStickerSets(flags: Int32, q: String, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(896555914) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(q, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.searchStickerSets", parameters: [("flags", String(describing: flags)), ("q", String(describing: q)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.FoundStickerSets? in - let reader = BufferReader(buffer) - var result: Api.messages.FoundStickerSets? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.FoundStickerSets - } - return result - }) - } -} -public extension Api.functions.messages { - static func searchStickers(flags: Int32, q: String, emoticon: String, langCode: [String], offset: Int32, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(699516522) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(q, buffer: buffer, boxed: false) - serializeString(emoticon, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(langCode.count)) - for item in langCode { - serializeString(item, buffer: buffer, boxed: false) - } - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.searchStickers", parameters: [("flags", String(describing: flags)), ("q", String(describing: q)), ("emoticon", String(describing: emoticon)), ("langCode", String(describing: langCode)), ("offset", String(describing: offset)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.FoundStickers? in - let reader = BufferReader(buffer) - var result: Api.messages.FoundStickers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.FoundStickers - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendBotRequestedPeer(peer: Api.InputPeer, msgId: Int32, buttonId: Int32, requestedPeers: [Api.InputPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1850552224) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeInt32(buttonId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(requestedPeers.count)) - for item in requestedPeers { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "messages.sendBotRequestedPeer", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("buttonId", String(describing: buttonId)), ("requestedPeers", String(describing: requestedPeers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendEncrypted(flags: Int32, peer: Api.InputEncryptedChat, randomId: Int64, data: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1157265941) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt64(randomId, buffer: buffer, boxed: false) - serializeBytes(data, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.sendEncrypted", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("randomId", String(describing: randomId)), ("data", String(describing: data))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SentEncryptedMessage? in - let reader = BufferReader(buffer) - var result: Api.messages.SentEncryptedMessage? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.SentEncryptedMessage - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendEncryptedFile(flags: Int32, peer: Api.InputEncryptedChat, randomId: Int64, data: Buffer, file: Api.InputEncryptedFile) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1431914525) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt64(randomId, buffer: buffer, boxed: false) - serializeBytes(data, buffer: buffer, boxed: false) - file.serialize(buffer, true) - return (FunctionDescription(name: "messages.sendEncryptedFile", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("randomId", String(describing: randomId)), ("data", String(describing: data)), ("file", String(describing: file))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SentEncryptedMessage? in - let reader = BufferReader(buffer) - var result: Api.messages.SentEncryptedMessage? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.SentEncryptedMessage - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendEncryptedService(peer: Api.InputEncryptedChat, randomId: Int64, data: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(852769188) - peer.serialize(buffer, true) - serializeInt64(randomId, buffer: buffer, boxed: false) - serializeBytes(data, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.sendEncryptedService", parameters: [("peer", String(describing: peer)), ("randomId", String(describing: randomId)), ("data", String(describing: data))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SentEncryptedMessage? in - let reader = BufferReader(buffer) - var result: Api.messages.SentEncryptedMessage? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.SentEncryptedMessage - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendInlineBotResult(flags: Int32, peer: Api.InputPeer, replyTo: Api.InputReplyTo?, randomId: Int64, queryId: Int64, id: String, scheduleDate: Int32?, sendAs: Api.InputPeer?, quickReplyShortcut: Api.InputQuickReplyShortcut?, allowPaidStars: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1060145594) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {replyTo!.serialize(buffer, true)} - serializeInt64(randomId, buffer: buffer, boxed: false) - serializeInt64(queryId, buffer: buffer, boxed: false) - serializeString(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 10) != 0 {serializeInt32(scheduleDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 13) != 0 {sendAs!.serialize(buffer, true)} - if Int(flags) & Int(1 << 17) != 0 {quickReplyShortcut!.serialize(buffer, true)} - if Int(flags) & Int(1 << 21) != 0 {serializeInt64(allowPaidStars!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.sendInlineBotResult", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("replyTo", String(describing: replyTo)), ("randomId", String(describing: randomId)), ("queryId", String(describing: queryId)), ("id", String(describing: id)), ("scheduleDate", String(describing: scheduleDate)), ("sendAs", String(describing: sendAs)), ("quickReplyShortcut", String(describing: quickReplyShortcut)), ("allowPaidStars", String(describing: allowPaidStars))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendMedia(flags: Int32, peer: Api.InputPeer, replyTo: Api.InputReplyTo?, media: Api.InputMedia, message: String, randomId: Int64, replyMarkup: Api.ReplyMarkup?, entities: [Api.MessageEntity]?, scheduleDate: Int32?, scheduleRepeatPeriod: Int32?, sendAs: Api.InputPeer?, quickReplyShortcut: Api.InputQuickReplyShortcut?, effect: Int64?, allowPaidStars: Int64?, suggestedPost: Api.SuggestedPost?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(53536639) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {replyTo!.serialize(buffer, true)} - media.serialize(buffer, true) - serializeString(message, buffer: buffer, boxed: false) - serializeInt64(randomId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 10) != 0 {serializeInt32(scheduleDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 24) != 0 {serializeInt32(scheduleRepeatPeriod!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 13) != 0 {sendAs!.serialize(buffer, true)} - if Int(flags) & Int(1 << 17) != 0 {quickReplyShortcut!.serialize(buffer, true)} - if Int(flags) & Int(1 << 18) != 0 {serializeInt64(effect!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 21) != 0 {serializeInt64(allowPaidStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 22) != 0 {suggestedPost!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.sendMedia", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("replyTo", String(describing: replyTo)), ("media", String(describing: media)), ("message", String(describing: message)), ("randomId", String(describing: randomId)), ("replyMarkup", String(describing: replyMarkup)), ("entities", String(describing: entities)), ("scheduleDate", String(describing: scheduleDate)), ("scheduleRepeatPeriod", String(describing: scheduleRepeatPeriod)), ("sendAs", String(describing: sendAs)), ("quickReplyShortcut", String(describing: quickReplyShortcut)), ("effect", String(describing: effect)), ("allowPaidStars", String(describing: allowPaidStars)), ("suggestedPost", String(describing: suggestedPost))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendMessage(flags: Int32, peer: Api.InputPeer, replyTo: Api.InputReplyTo?, message: String, randomId: Int64, replyMarkup: Api.ReplyMarkup?, entities: [Api.MessageEntity]?, scheduleDate: Int32?, scheduleRepeatPeriod: Int32?, sendAs: Api.InputPeer?, quickReplyShortcut: Api.InputQuickReplyShortcut?, effect: Int64?, allowPaidStars: Int64?, suggestedPost: Api.SuggestedPost?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1415369050) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {replyTo!.serialize(buffer, true)} - serializeString(message, buffer: buffer, boxed: false) - serializeInt64(randomId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 10) != 0 {serializeInt32(scheduleDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 24) != 0 {serializeInt32(scheduleRepeatPeriod!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 13) != 0 {sendAs!.serialize(buffer, true)} - if Int(flags) & Int(1 << 17) != 0 {quickReplyShortcut!.serialize(buffer, true)} - if Int(flags) & Int(1 << 18) != 0 {serializeInt64(effect!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 21) != 0 {serializeInt64(allowPaidStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 22) != 0 {suggestedPost!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.sendMessage", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("replyTo", String(describing: replyTo)), ("message", String(describing: message)), ("randomId", String(describing: randomId)), ("replyMarkup", String(describing: replyMarkup)), ("entities", String(describing: entities)), ("scheduleDate", String(describing: scheduleDate)), ("scheduleRepeatPeriod", String(describing: scheduleRepeatPeriod)), ("sendAs", String(describing: sendAs)), ("quickReplyShortcut", String(describing: quickReplyShortcut)), ("effect", String(describing: effect)), ("allowPaidStars", String(describing: allowPaidStars)), ("suggestedPost", String(describing: suggestedPost))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendMultiMedia(flags: Int32, peer: Api.InputPeer, replyTo: Api.InputReplyTo?, multiMedia: [Api.InputSingleMedia], scheduleDate: Int32?, sendAs: Api.InputPeer?, quickReplyShortcut: Api.InputQuickReplyShortcut?, effect: Int64?, allowPaidStars: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(469278068) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {replyTo!.serialize(buffer, true)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(multiMedia.count)) - for item in multiMedia { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 10) != 0 {serializeInt32(scheduleDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 13) != 0 {sendAs!.serialize(buffer, true)} - if Int(flags) & Int(1 << 17) != 0 {quickReplyShortcut!.serialize(buffer, true)} - if Int(flags) & Int(1 << 18) != 0 {serializeInt64(effect!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 21) != 0 {serializeInt64(allowPaidStars!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.sendMultiMedia", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("replyTo", String(describing: replyTo)), ("multiMedia", String(describing: multiMedia)), ("scheduleDate", String(describing: scheduleDate)), ("sendAs", String(describing: sendAs)), ("quickReplyShortcut", String(describing: quickReplyShortcut)), ("effect", String(describing: effect)), ("allowPaidStars", String(describing: allowPaidStars))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendPaidReaction(flags: Int32, peer: Api.InputPeer, msgId: Int32, count: Int32, randomId: Int64, `private`: Api.PaidReactionPrivacy?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1488702288) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeInt32(count, buffer: buffer, boxed: false) - serializeInt64(randomId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {`private`!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.sendPaidReaction", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("count", String(describing: count)), ("randomId", String(describing: randomId)), ("`private`", String(describing: `private`))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendQuickReplyMessages(peer: Api.InputPeer, shortcutId: Int32, id: [Int32], randomId: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1819610593) - peer.serialize(buffer, true) - serializeInt32(shortcutId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(randomId.count)) - for item in randomId { - serializeInt64(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.sendQuickReplyMessages", parameters: [("peer", String(describing: peer)), ("shortcutId", String(describing: shortcutId)), ("id", String(describing: id)), ("randomId", String(describing: randomId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendReaction(flags: Int32, peer: Api.InputPeer, msgId: Int32, reaction: [Api.Reaction]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-754091820) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(reaction!.count)) - for item in reaction! { - item.serialize(buffer, true) - }} - return (FunctionDescription(name: "messages.sendReaction", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("reaction", String(describing: reaction))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendScheduledMessages(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1120369398) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.sendScheduledMessages", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendScreenshotNotification(peer: Api.InputPeer, replyTo: Api.InputReplyTo, randomId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1589618665) - peer.serialize(buffer, true) - replyTo.serialize(buffer, true) - serializeInt64(randomId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.sendScreenshotNotification", parameters: [("peer", String(describing: peer)), ("replyTo", String(describing: replyTo)), ("randomId", String(describing: randomId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendVote(peer: Api.InputPeer, msgId: Int32, options: [Buffer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(283795844) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(options.count)) - for item in options { - serializeBytes(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.sendVote", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("options", String(describing: options))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendWebViewData(bot: Api.InputUser, randomId: Int64, buttonText: String, data: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-603831608) - bot.serialize(buffer, true) - serializeInt64(randomId, buffer: buffer, boxed: false) - serializeString(buttonText, buffer: buffer, boxed: false) - serializeString(data, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.sendWebViewData", parameters: [("bot", String(describing: bot)), ("randomId", String(describing: randomId)), ("buttonText", String(describing: buttonText)), ("data", String(describing: data))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func sendWebViewResultMessage(botQueryId: String, result: Api.InputBotInlineResult) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(172168437) - serializeString(botQueryId, buffer: buffer, boxed: false) - result.serialize(buffer, true) - return (FunctionDescription(name: "messages.sendWebViewResultMessage", parameters: [("botQueryId", String(describing: botQueryId)), ("result", String(describing: result))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.WebViewMessageSent? in - let reader = BufferReader(buffer) - var result: Api.WebViewMessageSent? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.WebViewMessageSent - } - return result - }) - } -} -public extension Api.functions.messages { - static func setBotCallbackAnswer(flags: Int32, queryId: Int64, message: String?, url: String?, cacheTime: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-712043766) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(queryId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(message!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(url!, buffer: buffer, boxed: false)} - serializeInt32(cacheTime, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.setBotCallbackAnswer", parameters: [("flags", String(describing: flags)), ("queryId", String(describing: queryId)), ("message", String(describing: message)), ("url", String(describing: url)), ("cacheTime", String(describing: cacheTime))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func setBotPrecheckoutResults(flags: Int32, queryId: Int64, error: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(163765653) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(queryId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(error!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.setBotPrecheckoutResults", parameters: [("flags", String(describing: flags)), ("queryId", String(describing: queryId)), ("error", String(describing: error))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func setBotShippingResults(flags: Int32, queryId: Int64, error: String?, shippingOptions: [Api.ShippingOption]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-436833542) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(queryId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(error!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(shippingOptions!.count)) - for item in shippingOptions! { - item.serialize(buffer, true) - }} - return (FunctionDescription(name: "messages.setBotShippingResults", parameters: [("flags", String(describing: flags)), ("queryId", String(describing: queryId)), ("error", String(describing: error)), ("shippingOptions", String(describing: shippingOptions))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func setChatAvailableReactions(flags: Int32, peer: Api.InputPeer, availableReactions: Api.ChatReactions, reactionsLimit: Int32?, paidEnabled: Api.Bool?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2041895551) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - availableReactions.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(reactionsLimit!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {paidEnabled!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.setChatAvailableReactions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("availableReactions", String(describing: availableReactions)), ("reactionsLimit", String(describing: reactionsLimit)), ("paidEnabled", String(describing: paidEnabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func setChatTheme(peer: Api.InputPeer, theme: Api.InputChatTheme) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(135398089) - peer.serialize(buffer, true) - theme.serialize(buffer, true) - return (FunctionDescription(name: "messages.setChatTheme", parameters: [("peer", String(describing: peer)), ("theme", String(describing: theme))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func setChatWallPaper(flags: Int32, peer: Api.InputPeer, wallpaper: Api.InputWallPaper?, settings: Api.WallPaperSettings?, id: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1879389471) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {wallpaper!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {settings!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(id!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.setChatWallPaper", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("wallpaper", String(describing: wallpaper)), ("settings", String(describing: settings)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func setDefaultHistoryTTL(period: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1632299963) - serializeInt32(period, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.setDefaultHistoryTTL", parameters: [("period", String(describing: period))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func setDefaultReaction(reaction: Api.Reaction) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1330094102) - reaction.serialize(buffer, true) - return (FunctionDescription(name: "messages.setDefaultReaction", parameters: [("reaction", String(describing: reaction))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func setEncryptedTyping(peer: Api.InputEncryptedChat, typing: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2031374829) - peer.serialize(buffer, true) - typing.serialize(buffer, true) - return (FunctionDescription(name: "messages.setEncryptedTyping", parameters: [("peer", String(describing: peer)), ("typing", String(describing: typing))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func setGameScore(flags: Int32, peer: Api.InputPeer, id: Int32, userId: Api.InputUser, score: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1896289088) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - userId.serialize(buffer, true) - serializeInt32(score, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.setGameScore", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("userId", String(describing: userId)), ("score", String(describing: score))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func setHistoryTTL(peer: Api.InputPeer, period: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1207017500) - peer.serialize(buffer, true) - serializeInt32(period, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.setHistoryTTL", parameters: [("peer", String(describing: peer)), ("period", String(describing: period))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func setInlineBotResults(flags: Int32, queryId: Int64, results: [Api.InputBotInlineResult], cacheTime: Int32, nextOffset: String?, switchPm: Api.InlineBotSwitchPM?, switchWebview: Api.InlineBotWebView?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1156406247) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(queryId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(results.count)) - for item in results { - item.serialize(buffer, true) - } - serializeInt32(cacheTime, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeString(nextOffset!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {switchPm!.serialize(buffer, true)} - if Int(flags) & Int(1 << 4) != 0 {switchWebview!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.setInlineBotResults", parameters: [("flags", String(describing: flags)), ("queryId", String(describing: queryId)), ("results", String(describing: results)), ("cacheTime", String(describing: cacheTime)), ("nextOffset", String(describing: nextOffset)), ("switchPm", String(describing: switchPm)), ("switchWebview", String(describing: switchWebview))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func setInlineGameScore(flags: Int32, id: Api.InputBotInlineMessageID, userId: Api.InputUser, score: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(363700068) - serializeInt32(flags, buffer: buffer, boxed: false) - id.serialize(buffer, true) - userId.serialize(buffer, true) - serializeInt32(score, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.setInlineGameScore", parameters: [("flags", String(describing: flags)), ("id", String(describing: id)), ("userId", String(describing: userId)), ("score", String(describing: score))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func setTyping(flags: Int32, peer: Api.InputPeer, topMsgId: Int32?, action: Api.SendMessageAction) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1486110434) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - action.serialize(buffer, true) - return (FunctionDescription(name: "messages.setTyping", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("topMsgId", String(describing: topMsgId)), ("action", String(describing: action))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func startBot(bot: Api.InputUser, peer: Api.InputPeer, randomId: Int64, startParam: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-421563528) - bot.serialize(buffer, true) - peer.serialize(buffer, true) - serializeInt64(randomId, buffer: buffer, boxed: false) - serializeString(startParam, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.startBot", parameters: [("bot", String(describing: bot)), ("peer", String(describing: peer)), ("randomId", String(describing: randomId)), ("startParam", String(describing: startParam))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func startHistoryImport(peer: Api.InputPeer, importId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1271008444) - peer.serialize(buffer, true) - serializeInt64(importId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.startHistoryImport", parameters: [("peer", String(describing: peer)), ("importId", String(describing: importId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func summarizeText(flags: Int32, peer: Api.InputPeer, id: Int32, toLang: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1656683294) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(toLang!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.summarizeText", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("toLang", String(describing: toLang))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.TextWithEntities? in - let reader = BufferReader(buffer) - var result: Api.TextWithEntities? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.TextWithEntities - } - return result - }) - } -} -public extension Api.functions.messages { - static func toggleBotInAttachMenu(flags: Int32, bot: Api.InputUser, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1777704297) - serializeInt32(flags, buffer: buffer, boxed: false) - bot.serialize(buffer, true) - enabled.serialize(buffer, true) - return (FunctionDescription(name: "messages.toggleBotInAttachMenu", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func toggleDialogFilterTags(enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-47326647) - enabled.serialize(buffer, true) - return (FunctionDescription(name: "messages.toggleDialogFilterTags", parameters: [("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func toggleDialogPin(flags: Int32, peer: Api.InputDialogPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1489903017) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - return (FunctionDescription(name: "messages.toggleDialogPin", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func toggleNoForwards(peer: Api.InputPeer, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1323389022) - peer.serialize(buffer, true) - enabled.serialize(buffer, true) - return (FunctionDescription(name: "messages.toggleNoForwards", parameters: [("peer", String(describing: peer)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func togglePaidReactionPrivacy(peer: Api.InputPeer, msgId: Int32, `private`: Api.PaidReactionPrivacy) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1129874869) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - `private`.serialize(buffer, true) - return (FunctionDescription(name: "messages.togglePaidReactionPrivacy", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("`private`", String(describing: `private`))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func togglePeerTranslations(flags: Int32, peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-461589127) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - return (FunctionDescription(name: "messages.togglePeerTranslations", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func toggleSavedDialogPin(flags: Int32, peer: Api.InputDialogPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1400783906) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - return (FunctionDescription(name: "messages.toggleSavedDialogPin", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func toggleStickerSets(flags: Int32, stickersets: [Api.InputStickerSet]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1257951254) - serializeInt32(flags, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stickersets.count)) - for item in stickersets { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "messages.toggleStickerSets", parameters: [("flags", String(describing: flags)), ("stickersets", String(describing: stickersets))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func toggleSuggestedPostApproval(flags: Int32, peer: Api.InputPeer, msgId: Int32, scheduleDate: Int32?, rejectComment: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2130229924) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(scheduleDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(rejectComment!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.toggleSuggestedPostApproval", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("scheduleDate", String(describing: scheduleDate)), ("rejectComment", String(describing: rejectComment))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func toggleTodoCompleted(peer: Api.InputPeer, msgId: Int32, completed: [Int32], incompleted: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-740282076) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(completed.count)) - for item in completed { - serializeInt32(item, buffer: buffer, boxed: false) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(incompleted.count)) - for item in incompleted { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.toggleTodoCompleted", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("completed", String(describing: completed)), ("incompleted", String(describing: incompleted))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func transcribeAudio(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(647928393) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.transcribeAudio", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.TranscribedAudio? in - let reader = BufferReader(buffer) - var result: Api.messages.TranscribedAudio? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.TranscribedAudio - } - return result - }) - } -} -public extension Api.functions.messages { - static func translateText(flags: Int32, peer: Api.InputPeer?, id: [Int32]?, text: [Api.TextWithEntities]?, toLang: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1662529584) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {peer!.serialize(buffer, true)} - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id!.count)) - for item in id! { - serializeInt32(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(text!.count)) - for item in text! { - item.serialize(buffer, true) - }} - serializeString(toLang, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.translateText", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("text", String(describing: text)), ("toLang", String(describing: toLang))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.TranslatedText? in - let reader = BufferReader(buffer) - var result: Api.messages.TranslatedText? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.TranslatedText - } - return result - }) - } -} -public extension Api.functions.messages { - static func uninstallStickerSet(stickerset: Api.InputStickerSet) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-110209570) - stickerset.serialize(buffer, true) - return (FunctionDescription(name: "messages.uninstallStickerSet", parameters: [("stickerset", String(describing: stickerset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func unpinAllMessages(flags: Int32, peer: Api.InputPeer, topMsgId: Int32?, savedPeerId: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(103667527) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {savedPeerId!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.unpinAllMessages", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("topMsgId", String(describing: topMsgId)), ("savedPeerId", String(describing: savedPeerId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedHistory? in - let reader = BufferReader(buffer) - var result: Api.messages.AffectedHistory? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.AffectedHistory - } - return result - }) - } -} -public extension Api.functions.messages { - static func updateDialogFilter(flags: Int32, id: Int32, filter: Api.DialogFilter?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(450142282) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {filter!.serialize(buffer, true)} - return (FunctionDescription(name: "messages.updateDialogFilter", parameters: [("flags", String(describing: flags)), ("id", String(describing: id)), ("filter", String(describing: filter))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func updateDialogFiltersOrder(order: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-983318044) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order.count)) - for item in order { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "messages.updateDialogFiltersOrder", parameters: [("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func updatePinnedForumTopic(peer: Api.InputPeer, topicId: Int32, pinned: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(392032849) - peer.serialize(buffer, true) - serializeInt32(topicId, buffer: buffer, boxed: false) - pinned.serialize(buffer, true) - return (FunctionDescription(name: "messages.updatePinnedForumTopic", parameters: [("peer", String(describing: peer)), ("topicId", String(describing: topicId)), ("pinned", String(describing: pinned))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func updatePinnedMessage(flags: Int32, peer: Api.InputPeer, id: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-760547348) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.updatePinnedMessage", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.messages { - static func updateSavedReactionTag(flags: Int32, reaction: Api.Reaction, title: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1613331948) - serializeInt32(flags, buffer: buffer, boxed: false) - reaction.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "messages.updateSavedReactionTag", parameters: [("flags", String(describing: flags)), ("reaction", String(describing: reaction)), ("title", String(describing: title))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.messages { - static func uploadEncryptedFile(peer: Api.InputEncryptedChat, file: Api.InputEncryptedFile) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1347929239) - peer.serialize(buffer, true) - file.serialize(buffer, true) - return (FunctionDescription(name: "messages.uploadEncryptedFile", parameters: [("peer", String(describing: peer)), ("file", String(describing: file))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EncryptedFile? in - let reader = BufferReader(buffer) - var result: Api.EncryptedFile? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.EncryptedFile - } - return result - }) - } -} -public extension Api.functions.messages { - static func uploadImportedMedia(peer: Api.InputPeer, importId: Int64, fileName: String, media: Api.InputMedia) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(713433234) - peer.serialize(buffer, true) - serializeInt64(importId, buffer: buffer, boxed: false) - serializeString(fileName, buffer: buffer, boxed: false) - media.serialize(buffer, true) - return (FunctionDescription(name: "messages.uploadImportedMedia", parameters: [("peer", String(describing: peer)), ("importId", String(describing: importId)), ("fileName", String(describing: fileName)), ("media", String(describing: media))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.MessageMedia? in - let reader = BufferReader(buffer) - var result: Api.MessageMedia? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.MessageMedia - } - return result - }) - } -} -public extension Api.functions.messages { - static func uploadMedia(flags: Int32, businessConnectionId: String?, peer: Api.InputPeer, media: Api.InputMedia) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(345405816) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(businessConnectionId!, buffer: buffer, boxed: false)} - peer.serialize(buffer, true) - media.serialize(buffer, true) - return (FunctionDescription(name: "messages.uploadMedia", parameters: [("flags", String(describing: flags)), ("businessConnectionId", String(describing: businessConnectionId)), ("peer", String(describing: peer)), ("media", String(describing: media))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.MessageMedia? in - let reader = BufferReader(buffer) - var result: Api.MessageMedia? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.MessageMedia - } - return result - }) - } -} -public extension Api.functions.messages { - static func viewSponsoredMessage(randomId: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(647902787) - serializeBytes(randomId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "messages.viewSponsoredMessage", parameters: [("randomId", String(describing: randomId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.payments { - static func applyGiftCode(slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-152934316) - serializeString(slug, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.applyGiftCode", parameters: [("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.payments { - static func assignAppStoreTransaction(receipt: Buffer, purpose: Api.InputStorePaymentPurpose) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2131921795) - serializeBytes(receipt, buffer: buffer, boxed: false) - purpose.serialize(buffer, true) - return (FunctionDescription(name: "payments.assignAppStoreTransaction", parameters: [("receipt", String(describing: receipt)), ("purpose", String(describing: purpose))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.payments { - static func assignPlayMarketTransaction(receipt: Api.DataJSON, purpose: Api.InputStorePaymentPurpose) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-537046829) - receipt.serialize(buffer, true) - purpose.serialize(buffer, true) - return (FunctionDescription(name: "payments.assignPlayMarketTransaction", parameters: [("receipt", String(describing: receipt)), ("purpose", String(describing: purpose))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.payments { - static func botCancelStarsSubscription(flags: Int32, userId: Api.InputUser, chargeId: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1845102114) - serializeInt32(flags, buffer: buffer, boxed: false) - userId.serialize(buffer, true) - serializeString(chargeId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.botCancelStarsSubscription", parameters: [("flags", String(describing: flags)), ("userId", String(describing: userId)), ("chargeId", String(describing: chargeId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.payments { - static func canPurchaseStore(purpose: Api.InputStorePaymentPurpose) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1339842215) - purpose.serialize(buffer, true) - return (FunctionDescription(name: "payments.canPurchaseStore", parameters: [("purpose", String(describing: purpose))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.payments { - static func changeStarsSubscription(flags: Int32, peer: Api.InputPeer, subscriptionId: String, canceled: Api.Bool?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-948500360) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeString(subscriptionId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {canceled!.serialize(buffer, true)} - return (FunctionDescription(name: "payments.changeStarsSubscription", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("subscriptionId", String(describing: subscriptionId)), ("canceled", String(describing: canceled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.payments { - static func checkCanSendGift(giftId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1060835895) - serializeInt64(giftId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.checkCanSendGift", parameters: [("giftId", String(describing: giftId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.CheckCanSendGiftResult? in - let reader = BufferReader(buffer) - var result: Api.payments.CheckCanSendGiftResult? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.CheckCanSendGiftResult - } - return result - }) - } -} -public extension Api.functions.payments { - static func checkGiftCode(slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1907247935) - serializeString(slug, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.checkGiftCode", parameters: [("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.CheckedGiftCode? in - let reader = BufferReader(buffer) - var result: Api.payments.CheckedGiftCode? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.CheckedGiftCode - } - return result - }) - } -} -public extension Api.functions.payments { - static func clearSavedInfo(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-667062079) - serializeInt32(flags, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.clearSavedInfo", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.payments { - static func connectStarRefBot(peer: Api.InputPeer, bot: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2127901834) - peer.serialize(buffer, true) - bot.serialize(buffer, true) - return (FunctionDescription(name: "payments.connectStarRefBot", parameters: [("peer", String(describing: peer)), ("bot", String(describing: bot))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.ConnectedStarRefBots? in - let reader = BufferReader(buffer) - var result: Api.payments.ConnectedStarRefBots? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.ConnectedStarRefBots - } - return result - }) - } -} -public extension Api.functions.payments { - static func convertStarGift(stargift: Api.InputSavedStarGift) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1958676331) - stargift.serialize(buffer, true) - return (FunctionDescription(name: "payments.convertStarGift", parameters: [("stargift", String(describing: stargift))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.payments { - static func createStarGiftCollection(peer: Api.InputPeer, title: String, stargift: [Api.InputSavedStarGift]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(524947079) - peer.serialize(buffer, true) - serializeString(title, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stargift.count)) - for item in stargift { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "payments.createStarGiftCollection", parameters: [("peer", String(describing: peer)), ("title", String(describing: title)), ("stargift", String(describing: stargift))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.StarGiftCollection? in - let reader = BufferReader(buffer) - var result: Api.StarGiftCollection? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.StarGiftCollection - } - return result - }) - } -} -public extension Api.functions.payments { - static func deleteStarGiftCollection(peer: Api.InputPeer, collectionId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1386854168) - peer.serialize(buffer, true) - serializeInt32(collectionId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.deleteStarGiftCollection", parameters: [("peer", String(describing: peer)), ("collectionId", String(describing: collectionId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.payments { - static func editConnectedStarRefBot(flags: Int32, peer: Api.InputPeer, link: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-453204829) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeString(link, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.editConnectedStarRefBot", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("link", String(describing: link))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.ConnectedStarRefBots? in - let reader = BufferReader(buffer) - var result: Api.payments.ConnectedStarRefBots? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.ConnectedStarRefBots - } - return result - }) - } -} -public extension Api.functions.payments { - static func exportInvoice(invoiceMedia: Api.InputMedia) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(261206117) - invoiceMedia.serialize(buffer, true) - return (FunctionDescription(name: "payments.exportInvoice", parameters: [("invoiceMedia", String(describing: invoiceMedia))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.ExportedInvoice? in - let reader = BufferReader(buffer) - var result: Api.payments.ExportedInvoice? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.ExportedInvoice - } - return result - }) - } -} -public extension Api.functions.payments { - static func fulfillStarsSubscription(peer: Api.InputPeer, subscriptionId: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-866391117) - peer.serialize(buffer, true) - serializeString(subscriptionId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.fulfillStarsSubscription", parameters: [("peer", String(describing: peer)), ("subscriptionId", String(describing: subscriptionId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.payments { - static func getBankCardData(number: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(779736953) - serializeString(number, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getBankCardData", parameters: [("number", String(describing: number))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.BankCardData? in - let reader = BufferReader(buffer) - var result: Api.payments.BankCardData? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.BankCardData - } - return result - }) - } -} -public extension Api.functions.payments { - static func getConnectedStarRefBot(peer: Api.InputPeer, bot: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1210476304) - peer.serialize(buffer, true) - bot.serialize(buffer, true) - return (FunctionDescription(name: "payments.getConnectedStarRefBot", parameters: [("peer", String(describing: peer)), ("bot", String(describing: bot))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.ConnectedStarRefBots? in - let reader = BufferReader(buffer) - var result: Api.payments.ConnectedStarRefBots? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.ConnectedStarRefBots - } - return result - }) - } -} -public extension Api.functions.payments { - static func getConnectedStarRefBots(flags: Int32, peer: Api.InputPeer, offsetDate: Int32?, offsetLink: String?, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1483318611) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(offsetDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(offsetLink!, buffer: buffer, boxed: false)} - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getConnectedStarRefBots", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("offsetDate", String(describing: offsetDate)), ("offsetLink", String(describing: offsetLink)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.ConnectedStarRefBots? in - let reader = BufferReader(buffer) - var result: Api.payments.ConnectedStarRefBots? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.ConnectedStarRefBots - } - return result - }) - } -} -public extension Api.functions.payments { - static func getGiveawayInfo(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-198994907) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getGiveawayInfo", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.GiveawayInfo? in - let reader = BufferReader(buffer) - var result: Api.payments.GiveawayInfo? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.GiveawayInfo - } - return result - }) - } -} -public extension Api.functions.payments { - static func getPaymentForm(flags: Int32, invoice: Api.InputInvoice, themeParams: Api.DataJSON?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(924093883) - serializeInt32(flags, buffer: buffer, boxed: false) - invoice.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {themeParams!.serialize(buffer, true)} - return (FunctionDescription(name: "payments.getPaymentForm", parameters: [("flags", String(describing: flags)), ("invoice", String(describing: invoice)), ("themeParams", String(describing: themeParams))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.PaymentForm? in - let reader = BufferReader(buffer) - var result: Api.payments.PaymentForm? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.PaymentForm - } - return result - }) - } -} -public extension Api.functions.payments { - static func getPaymentReceipt(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(611897804) - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getPaymentReceipt", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.PaymentReceipt? in - let reader = BufferReader(buffer) - var result: Api.payments.PaymentReceipt? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.PaymentReceipt - } - return result - }) - } -} -public extension Api.functions.payments { - static func getPremiumGiftCodeOptions(flags: Int32, boostPeer: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.PremiumGiftCodeOption]>) { - let buffer = Buffer() - buffer.appendInt32(660060756) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {boostPeer!.serialize(buffer, true)} - return (FunctionDescription(name: "payments.getPremiumGiftCodeOptions", parameters: [("flags", String(describing: flags)), ("boostPeer", String(describing: boostPeer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.PremiumGiftCodeOption]? in - let reader = BufferReader(buffer) - var result: [Api.PremiumGiftCodeOption]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.PremiumGiftCodeOption.self) - } - return result - }) - } -} -public extension Api.functions.payments { - static func getResaleStarGifts(flags: Int32, attributesHash: Int64?, giftId: Int64, attributes: [Api.StarGiftAttributeId]?, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2053087798) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(attributesHash!, buffer: buffer, boxed: false)} - serializeInt64(giftId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(attributes!.count)) - for item in attributes! { - item.serialize(buffer, true) - }} - serializeString(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getResaleStarGifts", parameters: [("flags", String(describing: flags)), ("attributesHash", String(describing: attributesHash)), ("giftId", String(describing: giftId)), ("attributes", String(describing: attributes)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.ResaleStarGifts? in - let reader = BufferReader(buffer) - var result: Api.payments.ResaleStarGifts? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.ResaleStarGifts - } - return result - }) - } -} -public extension Api.functions.payments { - static func getSavedInfo() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(578650699) - - return (FunctionDescription(name: "payments.getSavedInfo", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.SavedInfo? in - let reader = BufferReader(buffer) - var result: Api.payments.SavedInfo? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.SavedInfo - } - return result - }) - } -} -public extension Api.functions.payments { - static func getSavedStarGift(stargift: [Api.InputSavedStarGift]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1269456634) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stargift.count)) - for item in stargift { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "payments.getSavedStarGift", parameters: [("stargift", String(describing: stargift))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.SavedStarGifts? in - let reader = BufferReader(buffer) - var result: Api.payments.SavedStarGifts? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.SavedStarGifts - } - return result - }) - } -} -public extension Api.functions.payments { - static func getSavedStarGifts(flags: Int32, peer: Api.InputPeer, collectionId: Int32?, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1558583959) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 6) != 0 {serializeInt32(collectionId!, buffer: buffer, boxed: false)} - serializeString(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getSavedStarGifts", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("collectionId", String(describing: collectionId)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.SavedStarGifts? in - let reader = BufferReader(buffer) - var result: Api.payments.SavedStarGifts? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.SavedStarGifts - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarGiftActiveAuctions(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1513074355) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getStarGiftActiveAuctions", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGiftActiveAuctions? in - let reader = BufferReader(buffer) - var result: Api.payments.StarGiftActiveAuctions? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.StarGiftActiveAuctions - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarGiftAuctionAcquiredGifts(giftId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1805831148) - serializeInt64(giftId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getStarGiftAuctionAcquiredGifts", parameters: [("giftId", String(describing: giftId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGiftAuctionAcquiredGifts? in - let reader = BufferReader(buffer) - var result: Api.payments.StarGiftAuctionAcquiredGifts? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.StarGiftAuctionAcquiredGifts - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarGiftAuctionState(auction: Api.InputStarGiftAuction, version: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1553986774) - auction.serialize(buffer, true) - serializeInt32(version, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getStarGiftAuctionState", parameters: [("auction", String(describing: auction)), ("version", String(describing: version))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGiftAuctionState? in - let reader = BufferReader(buffer) - var result: Api.payments.StarGiftAuctionState? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.StarGiftAuctionState - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarGiftCollections(peer: Api.InputPeer, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1743023651) - peer.serialize(buffer, true) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getStarGiftCollections", parameters: [("peer", String(describing: peer)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGiftCollections? in - let reader = BufferReader(buffer) - var result: Api.payments.StarGiftCollections? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.StarGiftCollections - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarGiftUpgradeAttributes(giftId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1828948824) - serializeInt64(giftId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getStarGiftUpgradeAttributes", parameters: [("giftId", String(describing: giftId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGiftUpgradeAttributes? in - let reader = BufferReader(buffer) - var result: Api.payments.StarGiftUpgradeAttributes? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.StarGiftUpgradeAttributes - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarGiftUpgradePreview(giftId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1667580751) - serializeInt64(giftId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getStarGiftUpgradePreview", parameters: [("giftId", String(describing: giftId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGiftUpgradePreview? in - let reader = BufferReader(buffer) - var result: Api.payments.StarGiftUpgradePreview? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.StarGiftUpgradePreview - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarGiftWithdrawalUrl(stargift: Api.InputSavedStarGift, password: Api.InputCheckPasswordSRP) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-798059608) - stargift.serialize(buffer, true) - password.serialize(buffer, true) - return (FunctionDescription(name: "payments.getStarGiftWithdrawalUrl", parameters: [("stargift", String(describing: stargift)), ("password", String(describing: password))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGiftWithdrawalUrl? in - let reader = BufferReader(buffer) - var result: Api.payments.StarGiftWithdrawalUrl? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.StarGiftWithdrawalUrl - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarGifts(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1000983152) - serializeInt32(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getStarGifts", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGifts? in - let reader = BufferReader(buffer) - var result: Api.payments.StarGifts? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.StarGifts - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarsGiftOptions(flags: Int32, userId: Api.InputUser?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.StarsGiftOption]>) { - let buffer = Buffer() - buffer.appendInt32(-741774392) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {userId!.serialize(buffer, true)} - return (FunctionDescription(name: "payments.getStarsGiftOptions", parameters: [("flags", String(describing: flags)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.StarsGiftOption]? in - let reader = BufferReader(buffer) - var result: [Api.StarsGiftOption]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarsGiftOption.self) - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarsGiveawayOptions() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.StarsGiveawayOption]>) { - let buffer = Buffer() - buffer.appendInt32(-1122042562) - - return (FunctionDescription(name: "payments.getStarsGiveawayOptions", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.StarsGiveawayOption]? in - let reader = BufferReader(buffer) - var result: [Api.StarsGiveawayOption]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarsGiveawayOption.self) - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarsRevenueAdsAccountUrl(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-774377531) - peer.serialize(buffer, true) - return (FunctionDescription(name: "payments.getStarsRevenueAdsAccountUrl", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarsRevenueAdsAccountUrl? in - let reader = BufferReader(buffer) - var result: Api.payments.StarsRevenueAdsAccountUrl? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.StarsRevenueAdsAccountUrl - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarsRevenueStats(flags: Int32, peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-652215594) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - return (FunctionDescription(name: "payments.getStarsRevenueStats", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarsRevenueStats? in - let reader = BufferReader(buffer) - var result: Api.payments.StarsRevenueStats? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.StarsRevenueStats - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarsRevenueWithdrawalUrl(flags: Int32, peer: Api.InputPeer, amount: Int64?, password: Api.InputCheckPasswordSRP) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(607378578) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {serializeInt64(amount!, buffer: buffer, boxed: false)} - password.serialize(buffer, true) - return (FunctionDescription(name: "payments.getStarsRevenueWithdrawalUrl", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("amount", String(describing: amount)), ("password", String(describing: password))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarsRevenueWithdrawalUrl? in - let reader = BufferReader(buffer) - var result: Api.payments.StarsRevenueWithdrawalUrl? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.StarsRevenueWithdrawalUrl - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarsStatus(flags: Int32, peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1319744447) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - return (FunctionDescription(name: "payments.getStarsStatus", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarsStatus? in - let reader = BufferReader(buffer) - var result: Api.payments.StarsStatus? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.StarsStatus - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarsSubscriptions(flags: Int32, peer: Api.InputPeer, offset: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(52761285) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeString(offset, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getStarsSubscriptions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("offset", String(describing: offset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarsStatus? in - let reader = BufferReader(buffer) - var result: Api.payments.StarsStatus? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.StarsStatus - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarsTopupOptions() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.StarsTopupOption]>) { - let buffer = Buffer() - buffer.appendInt32(-1072773165) - - return (FunctionDescription(name: "payments.getStarsTopupOptions", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.StarsTopupOption]? in - let reader = BufferReader(buffer) - var result: [Api.StarsTopupOption]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarsTopupOption.self) - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarsTransactions(flags: Int32, subscriptionId: String?, peer: Api.InputPeer, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1775912279) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {serializeString(subscriptionId!, buffer: buffer, boxed: false)} - peer.serialize(buffer, true) - serializeString(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getStarsTransactions", parameters: [("flags", String(describing: flags)), ("subscriptionId", String(describing: subscriptionId)), ("peer", String(describing: peer)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarsStatus? in - let reader = BufferReader(buffer) - var result: Api.payments.StarsStatus? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.StarsStatus - } - return result - }) - } -} -public extension Api.functions.payments { - static func getStarsTransactionsByID(flags: Int32, peer: Api.InputPeer, id: [Api.InputStarsTransaction]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(768218808) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "payments.getStarsTransactionsByID", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarsStatus? in - let reader = BufferReader(buffer) - var result: Api.payments.StarsStatus? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.StarsStatus - } - return result - }) - } -} -public extension Api.functions.payments { - static func getSuggestedStarRefBots(flags: Int32, peer: Api.InputPeer, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(225134839) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeString(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getSuggestedStarRefBots", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.SuggestedStarRefBots? in - let reader = BufferReader(buffer) - var result: Api.payments.SuggestedStarRefBots? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.SuggestedStarRefBots - } - return result - }) - } -} -public extension Api.functions.payments { - static func getUniqueStarGift(slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1583919758) - serializeString(slug, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getUniqueStarGift", parameters: [("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.UniqueStarGift? in - let reader = BufferReader(buffer) - var result: Api.payments.UniqueStarGift? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.UniqueStarGift - } - return result - }) - } -} -public extension Api.functions.payments { - static func getUniqueStarGiftValueInfo(slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1130737515) - serializeString(slug, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.getUniqueStarGiftValueInfo", parameters: [("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.UniqueStarGiftValueInfo? in - let reader = BufferReader(buffer) - var result: Api.payments.UniqueStarGiftValueInfo? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.UniqueStarGiftValueInfo - } - return result - }) - } -} -public extension Api.functions.payments { - static func launchPrepaidGiveaway(peer: Api.InputPeer, giveawayId: Int64, purpose: Api.InputStorePaymentPurpose) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1609928480) - peer.serialize(buffer, true) - serializeInt64(giveawayId, buffer: buffer, boxed: false) - purpose.serialize(buffer, true) - return (FunctionDescription(name: "payments.launchPrepaidGiveaway", parameters: [("peer", String(describing: peer)), ("giveawayId", String(describing: giveawayId)), ("purpose", String(describing: purpose))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.payments { - static func refundStarsCharge(userId: Api.InputUser, chargeId: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(632196938) - userId.serialize(buffer, true) - serializeString(chargeId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.refundStarsCharge", parameters: [("userId", String(describing: userId)), ("chargeId", String(describing: chargeId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.payments { - static func reorderStarGiftCollections(peer: Api.InputPeer, order: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1020594996) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order.count)) - for item in order { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "payments.reorderStarGiftCollections", parameters: [("peer", String(describing: peer)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.payments { - static func resolveStarGiftOffer(flags: Int32, offerMsgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-372344804) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(offerMsgId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "payments.resolveStarGiftOffer", parameters: [("flags", String(describing: flags)), ("offerMsgId", String(describing: offerMsgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.payments { - static func saveStarGift(flags: Int32, stargift: Api.InputSavedStarGift) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(707422588) - serializeInt32(flags, buffer: buffer, boxed: false) - stargift.serialize(buffer, true) - return (FunctionDescription(name: "payments.saveStarGift", parameters: [("flags", String(describing: flags)), ("stargift", String(describing: stargift))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.payments { - static func sendPaymentForm(flags: Int32, formId: Int64, invoice: Api.InputInvoice, requestedInfoId: String?, shippingOptionId: String?, credentials: Api.InputPaymentCredentials, tipAmount: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(755192367) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(formId, buffer: buffer, boxed: false) - invoice.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeString(requestedInfoId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(shippingOptionId!, buffer: buffer, boxed: false)} - credentials.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {serializeInt64(tipAmount!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "payments.sendPaymentForm", parameters: [("flags", String(describing: flags)), ("formId", String(describing: formId)), ("invoice", String(describing: invoice)), ("requestedInfoId", String(describing: requestedInfoId)), ("shippingOptionId", String(describing: shippingOptionId)), ("credentials", String(describing: credentials)), ("tipAmount", String(describing: tipAmount))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.PaymentResult? in - let reader = BufferReader(buffer) - var result: Api.payments.PaymentResult? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.PaymentResult - } - return result - }) - } -} -public extension Api.functions.payments { - static func sendStarGiftOffer(flags: Int32, peer: Api.InputPeer, slug: String, price: Api.StarsAmount, duration: Int32, randomId: Int64, allowPaidStars: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1883739327) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeString(slug, buffer: buffer, boxed: false) - price.serialize(buffer, true) - serializeInt32(duration, buffer: buffer, boxed: false) - serializeInt64(randomId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(allowPaidStars!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "payments.sendStarGiftOffer", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("slug", String(describing: slug)), ("price", String(describing: price)), ("duration", String(describing: duration)), ("randomId", String(describing: randomId)), ("allowPaidStars", String(describing: allowPaidStars))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.payments { - static func sendStarsForm(formId: Int64, invoice: Api.InputInvoice) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2040056084) - serializeInt64(formId, buffer: buffer, boxed: false) - invoice.serialize(buffer, true) - return (FunctionDescription(name: "payments.sendStarsForm", parameters: [("formId", String(describing: formId)), ("invoice", String(describing: invoice))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.PaymentResult? in - let reader = BufferReader(buffer) - var result: Api.payments.PaymentResult? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.PaymentResult - } - return result - }) - } -} -public extension Api.functions.payments { - static func toggleChatStarGiftNotifications(flags: Int32, peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1626009505) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - return (FunctionDescription(name: "payments.toggleChatStarGiftNotifications", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.payments { - static func toggleStarGiftsPinnedToTop(peer: Api.InputPeer, stargift: [Api.InputSavedStarGift]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(353626032) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stargift.count)) - for item in stargift { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "payments.toggleStarGiftsPinnedToTop", parameters: [("peer", String(describing: peer)), ("stargift", String(describing: stargift))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.payments { - static func transferStarGift(stargift: Api.InputSavedStarGift, toId: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2132285290) - stargift.serialize(buffer, true) - toId.serialize(buffer, true) - return (FunctionDescription(name: "payments.transferStarGift", parameters: [("stargift", String(describing: stargift)), ("toId", String(describing: toId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.payments { - static func updateStarGiftCollection(flags: Int32, peer: Api.InputPeer, collectionId: Int32, title: String?, deleteStargift: [Api.InputSavedStarGift]?, addStargift: [Api.InputSavedStarGift]?, order: [Api.InputSavedStarGift]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1339932391) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(collectionId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(deleteStargift!.count)) - for item in deleteStargift! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 2) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(addStargift!.count)) - for item in addStargift! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order!.count)) - for item in order! { - item.serialize(buffer, true) - }} - return (FunctionDescription(name: "payments.updateStarGiftCollection", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("collectionId", String(describing: collectionId)), ("title", String(describing: title)), ("deleteStargift", String(describing: deleteStargift)), ("addStargift", String(describing: addStargift)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.StarGiftCollection? in - let reader = BufferReader(buffer) - var result: Api.StarGiftCollection? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.StarGiftCollection - } - return result - }) - } -} -public extension Api.functions.payments { - static func updateStarGiftPrice(stargift: Api.InputSavedStarGift, resellAmount: Api.StarsAmount) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-306287413) - stargift.serialize(buffer, true) - resellAmount.serialize(buffer, true) - return (FunctionDescription(name: "payments.updateStarGiftPrice", parameters: [("stargift", String(describing: stargift)), ("resellAmount", String(describing: resellAmount))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.payments { - static func upgradeStarGift(flags: Int32, stargift: Api.InputSavedStarGift) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1361648395) - serializeInt32(flags, buffer: buffer, boxed: false) - stargift.serialize(buffer, true) - return (FunctionDescription(name: "payments.upgradeStarGift", parameters: [("flags", String(describing: flags)), ("stargift", String(describing: stargift))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.payments { - static func validateRequestedInfo(flags: Int32, invoice: Api.InputInvoice, info: Api.PaymentRequestedInfo) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1228345045) - serializeInt32(flags, buffer: buffer, boxed: false) - invoice.serialize(buffer, true) - info.serialize(buffer, true) - return (FunctionDescription(name: "payments.validateRequestedInfo", parameters: [("flags", String(describing: flags)), ("invoice", String(describing: invoice)), ("info", String(describing: info))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.ValidatedRequestedInfo? in - let reader = BufferReader(buffer) - var result: Api.payments.ValidatedRequestedInfo? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.payments.ValidatedRequestedInfo - } - return result - }) - } -} -public extension Api.functions.phone { - static func acceptCall(peer: Api.InputPhoneCall, gB: Buffer, `protocol`: Api.PhoneCallProtocol) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1003664544) - peer.serialize(buffer, true) - serializeBytes(gB, buffer: buffer, boxed: false) - `protocol`.serialize(buffer, true) - return (FunctionDescription(name: "phone.acceptCall", parameters: [("peer", String(describing: peer)), ("gB", String(describing: gB)), ("`protocol`", String(describing: `protocol`))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.PhoneCall? in - let reader = BufferReader(buffer) - var result: Api.phone.PhoneCall? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.phone.PhoneCall - } - return result - }) - } -} -public extension Api.functions.phone { - static func checkGroupCall(call: Api.InputGroupCall, sources: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Int32]>) { - let buffer = Buffer() - buffer.appendInt32(-1248003721) - call.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(sources.count)) - for item in sources { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "phone.checkGroupCall", parameters: [("call", String(describing: call)), ("sources", String(describing: sources))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Int32]? in - let reader = BufferReader(buffer) - var result: [Int32]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - return result - }) - } -} -public extension Api.functions.phone { - static func confirmCall(peer: Api.InputPhoneCall, gA: Buffer, keyFingerprint: Int64, `protocol`: Api.PhoneCallProtocol) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(788404002) - peer.serialize(buffer, true) - serializeBytes(gA, buffer: buffer, boxed: false) - serializeInt64(keyFingerprint, buffer: buffer, boxed: false) - `protocol`.serialize(buffer, true) - return (FunctionDescription(name: "phone.confirmCall", parameters: [("peer", String(describing: peer)), ("gA", String(describing: gA)), ("keyFingerprint", String(describing: keyFingerprint)), ("`protocol`", String(describing: `protocol`))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.PhoneCall? in - let reader = BufferReader(buffer) - var result: Api.phone.PhoneCall? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.phone.PhoneCall - } - return result - }) - } -} -public extension Api.functions.phone { - static func createConferenceCall(flags: Int32, randomId: Int32, publicKey: Int256?, block: Buffer?, params: Api.DataJSON?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2097431739) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(randomId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {serializeInt256(publicKey!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeBytes(block!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {params!.serialize(buffer, true)} - return (FunctionDescription(name: "phone.createConferenceCall", parameters: [("flags", String(describing: flags)), ("randomId", String(describing: randomId)), ("publicKey", String(describing: publicKey)), ("block", String(describing: block)), ("params", String(describing: params))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func createGroupCall(flags: Int32, peer: Api.InputPeer, randomId: Int32, title: String?, scheduleDate: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1221445336) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(randomId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(scheduleDate!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "phone.createGroupCall", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("randomId", String(describing: randomId)), ("title", String(describing: title)), ("scheduleDate", String(describing: scheduleDate))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func declineConferenceCallInvite(msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1011325297) - serializeInt32(msgId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "phone.declineConferenceCallInvite", parameters: [("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func deleteConferenceCallParticipants(flags: Int32, call: Api.InputGroupCall, ids: [Int64], block: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1935276763) - serializeInt32(flags, buffer: buffer, boxed: false) - call.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(ids.count)) - for item in ids { - serializeInt64(item, buffer: buffer, boxed: false) - } - serializeBytes(block, buffer: buffer, boxed: false) - return (FunctionDescription(name: "phone.deleteConferenceCallParticipants", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("ids", String(describing: ids)), ("block", String(describing: block))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func deleteGroupCallMessages(flags: Int32, call: Api.InputGroupCall, messages: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-162573065) - serializeInt32(flags, buffer: buffer, boxed: false) - call.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(messages.count)) - for item in messages { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "phone.deleteGroupCallMessages", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("messages", String(describing: messages))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func deleteGroupCallParticipantMessages(flags: Int32, call: Api.InputGroupCall, participant: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(499117216) - serializeInt32(flags, buffer: buffer, boxed: false) - call.serialize(buffer, true) - participant.serialize(buffer, true) - return (FunctionDescription(name: "phone.deleteGroupCallParticipantMessages", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("participant", String(describing: participant))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func discardCall(flags: Int32, peer: Api.InputPhoneCall, duration: Int32, reason: Api.PhoneCallDiscardReason, connectionId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1295269440) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(duration, buffer: buffer, boxed: false) - reason.serialize(buffer, true) - serializeInt64(connectionId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "phone.discardCall", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("duration", String(describing: duration)), ("reason", String(describing: reason)), ("connectionId", String(describing: connectionId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func discardGroupCall(call: Api.InputGroupCall) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2054648117) - call.serialize(buffer, true) - return (FunctionDescription(name: "phone.discardGroupCall", parameters: [("call", String(describing: call))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func editGroupCallParticipant(flags: Int32, call: Api.InputGroupCall, participant: Api.InputPeer, muted: Api.Bool?, volume: Int32?, raiseHand: Api.Bool?, videoStopped: Api.Bool?, videoPaused: Api.Bool?, presentationPaused: Api.Bool?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1524155713) - serializeInt32(flags, buffer: buffer, boxed: false) - call.serialize(buffer, true) - participant.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {muted!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(volume!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {raiseHand!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {videoStopped!.serialize(buffer, true)} - if Int(flags) & Int(1 << 4) != 0 {videoPaused!.serialize(buffer, true)} - if Int(flags) & Int(1 << 5) != 0 {presentationPaused!.serialize(buffer, true)} - return (FunctionDescription(name: "phone.editGroupCallParticipant", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("participant", String(describing: participant)), ("muted", String(describing: muted)), ("volume", String(describing: volume)), ("raiseHand", String(describing: raiseHand)), ("videoStopped", String(describing: videoStopped)), ("videoPaused", String(describing: videoPaused)), ("presentationPaused", String(describing: presentationPaused))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func editGroupCallTitle(call: Api.InputGroupCall, title: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(480685066) - call.serialize(buffer, true) - serializeString(title, buffer: buffer, boxed: false) - return (FunctionDescription(name: "phone.editGroupCallTitle", parameters: [("call", String(describing: call)), ("title", String(describing: title))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func exportGroupCallInvite(flags: Int32, call: Api.InputGroupCall) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-425040769) - serializeInt32(flags, buffer: buffer, boxed: false) - call.serialize(buffer, true) - return (FunctionDescription(name: "phone.exportGroupCallInvite", parameters: [("flags", String(describing: flags)), ("call", String(describing: call))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.ExportedGroupCallInvite? in - let reader = BufferReader(buffer) - var result: Api.phone.ExportedGroupCallInvite? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.phone.ExportedGroupCallInvite - } - return result - }) - } -} -public extension Api.functions.phone { - static func getCallConfig() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1430593449) - - return (FunctionDescription(name: "phone.getCallConfig", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.DataJSON? in - let reader = BufferReader(buffer) - var result: Api.DataJSON? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.DataJSON - } - return result - }) - } -} -public extension Api.functions.phone { - static func getGroupCall(call: Api.InputGroupCall, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(68699611) - call.serialize(buffer, true) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "phone.getGroupCall", parameters: [("call", String(describing: call)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.GroupCall? in - let reader = BufferReader(buffer) - var result: Api.phone.GroupCall? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.phone.GroupCall - } - return result - }) - } -} -public extension Api.functions.phone { - static func getGroupCallChainBlocks(call: Api.InputGroupCall, subChainId: Int32, offset: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-291534682) - call.serialize(buffer, true) - serializeInt32(subChainId, buffer: buffer, boxed: false) - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "phone.getGroupCallChainBlocks", parameters: [("call", String(describing: call)), ("subChainId", String(describing: subChainId)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func getGroupCallJoinAs(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-277077702) - peer.serialize(buffer, true) - return (FunctionDescription(name: "phone.getGroupCallJoinAs", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.JoinAsPeers? in - let reader = BufferReader(buffer) - var result: Api.phone.JoinAsPeers? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.phone.JoinAsPeers - } - return result - }) - } -} -public extension Api.functions.phone { - static func getGroupCallStars(call: Api.InputGroupCall) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1868784386) - call.serialize(buffer, true) - return (FunctionDescription(name: "phone.getGroupCallStars", parameters: [("call", String(describing: call))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.GroupCallStars? in - let reader = BufferReader(buffer) - var result: Api.phone.GroupCallStars? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.phone.GroupCallStars - } - return result - }) - } -} -public extension Api.functions.phone { - static func getGroupCallStreamChannels(call: Api.InputGroupCall) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(447879488) - call.serialize(buffer, true) - return (FunctionDescription(name: "phone.getGroupCallStreamChannels", parameters: [("call", String(describing: call))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.GroupCallStreamChannels? in - let reader = BufferReader(buffer) - var result: Api.phone.GroupCallStreamChannels? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.phone.GroupCallStreamChannels - } - return result - }) - } -} -public extension Api.functions.phone { - static func getGroupCallStreamRtmpUrl(flags: Int32, peer: Api.InputPeer, revoke: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1525991226) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - revoke.serialize(buffer, true) - return (FunctionDescription(name: "phone.getGroupCallStreamRtmpUrl", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("revoke", String(describing: revoke))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.GroupCallStreamRtmpUrl? in - let reader = BufferReader(buffer) - var result: Api.phone.GroupCallStreamRtmpUrl? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.phone.GroupCallStreamRtmpUrl - } - return result - }) - } -} -public extension Api.functions.phone { - static func getGroupParticipants(call: Api.InputGroupCall, ids: [Api.InputPeer], sources: [Int32], offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-984033109) - call.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(ids.count)) - for item in ids { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(sources.count)) - for item in sources { - serializeInt32(item, buffer: buffer, boxed: false) - } - serializeString(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "phone.getGroupParticipants", parameters: [("call", String(describing: call)), ("ids", String(describing: ids)), ("sources", String(describing: sources)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.GroupParticipants? in - let reader = BufferReader(buffer) - var result: Api.phone.GroupParticipants? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.phone.GroupParticipants - } - return result - }) - } -} -public extension Api.functions.phone { - static func inviteConferenceCallParticipant(flags: Int32, call: Api.InputGroupCall, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1124981115) - serializeInt32(flags, buffer: buffer, boxed: false) - call.serialize(buffer, true) - userId.serialize(buffer, true) - return (FunctionDescription(name: "phone.inviteConferenceCallParticipant", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func inviteToGroupCall(call: Api.InputGroupCall, users: [Api.InputUser]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2067345760) - call.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users.count)) - for item in users { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "phone.inviteToGroupCall", parameters: [("call", String(describing: call)), ("users", String(describing: users))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func joinGroupCall(flags: Int32, call: Api.InputGroupCall, joinAs: Api.InputPeer, inviteHash: String?, publicKey: Int256?, block: Buffer?, params: Api.DataJSON) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1883951017) - serializeInt32(flags, buffer: buffer, boxed: false) - call.serialize(buffer, true) - joinAs.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {serializeString(inviteHash!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt256(publicKey!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeBytes(block!, buffer: buffer, boxed: false)} - params.serialize(buffer, true) - return (FunctionDescription(name: "phone.joinGroupCall", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("joinAs", String(describing: joinAs)), ("inviteHash", String(describing: inviteHash)), ("publicKey", String(describing: publicKey)), ("block", String(describing: block)), ("params", String(describing: params))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func joinGroupCallPresentation(call: Api.InputGroupCall, params: Api.DataJSON) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-873829436) - call.serialize(buffer, true) - params.serialize(buffer, true) - return (FunctionDescription(name: "phone.joinGroupCallPresentation", parameters: [("call", String(describing: call)), ("params", String(describing: params))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func leaveGroupCall(call: Api.InputGroupCall, source: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1342404601) - call.serialize(buffer, true) - serializeInt32(source, buffer: buffer, boxed: false) - return (FunctionDescription(name: "phone.leaveGroupCall", parameters: [("call", String(describing: call)), ("source", String(describing: source))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func leaveGroupCallPresentation(call: Api.InputGroupCall) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(475058500) - call.serialize(buffer, true) - return (FunctionDescription(name: "phone.leaveGroupCallPresentation", parameters: [("call", String(describing: call))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func receivedCall(peer: Api.InputPhoneCall) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(399855457) - peer.serialize(buffer, true) - return (FunctionDescription(name: "phone.receivedCall", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.phone { - static func requestCall(flags: Int32, userId: Api.InputUser, randomId: Int32, gAHash: Buffer, `protocol`: Api.PhoneCallProtocol) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1124046573) - serializeInt32(flags, buffer: buffer, boxed: false) - userId.serialize(buffer, true) - serializeInt32(randomId, buffer: buffer, boxed: false) - serializeBytes(gAHash, buffer: buffer, boxed: false) - `protocol`.serialize(buffer, true) - return (FunctionDescription(name: "phone.requestCall", parameters: [("flags", String(describing: flags)), ("userId", String(describing: userId)), ("randomId", String(describing: randomId)), ("gAHash", String(describing: gAHash)), ("`protocol`", String(describing: `protocol`))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.PhoneCall? in - let reader = BufferReader(buffer) - var result: Api.phone.PhoneCall? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.phone.PhoneCall - } - return result - }) - } -} -public extension Api.functions.phone { - static func saveCallDebug(peer: Api.InputPhoneCall, debug: Api.DataJSON) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(662363518) - peer.serialize(buffer, true) - debug.serialize(buffer, true) - return (FunctionDescription(name: "phone.saveCallDebug", parameters: [("peer", String(describing: peer)), ("debug", String(describing: debug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.phone { - static func saveCallLog(peer: Api.InputPhoneCall, file: Api.InputFile) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1092913030) - peer.serialize(buffer, true) - file.serialize(buffer, true) - return (FunctionDescription(name: "phone.saveCallLog", parameters: [("peer", String(describing: peer)), ("file", String(describing: file))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.phone { - static func saveDefaultGroupCallJoinAs(peer: Api.InputPeer, joinAs: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1465786252) - peer.serialize(buffer, true) - joinAs.serialize(buffer, true) - return (FunctionDescription(name: "phone.saveDefaultGroupCallJoinAs", parameters: [("peer", String(describing: peer)), ("joinAs", String(describing: joinAs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.phone { - static func saveDefaultSendAs(call: Api.InputGroupCall, sendAs: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1097313745) - call.serialize(buffer, true) - sendAs.serialize(buffer, true) - return (FunctionDescription(name: "phone.saveDefaultSendAs", parameters: [("call", String(describing: call)), ("sendAs", String(describing: sendAs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.phone { - static func sendConferenceCallBroadcast(call: Api.InputGroupCall, block: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-965732096) - call.serialize(buffer, true) - serializeBytes(block, buffer: buffer, boxed: false) - return (FunctionDescription(name: "phone.sendConferenceCallBroadcast", parameters: [("call", String(describing: call)), ("block", String(describing: block))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func sendGroupCallEncryptedMessage(call: Api.InputGroupCall, encryptedMessage: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-441473683) - call.serialize(buffer, true) - serializeBytes(encryptedMessage, buffer: buffer, boxed: false) - return (FunctionDescription(name: "phone.sendGroupCallEncryptedMessage", parameters: [("call", String(describing: call)), ("encryptedMessage", String(describing: encryptedMessage))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.phone { - static func sendGroupCallMessage(flags: Int32, call: Api.InputGroupCall, randomId: Int64, message: Api.TextWithEntities, allowPaidStars: Int64?, sendAs: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1311697904) - serializeInt32(flags, buffer: buffer, boxed: false) - call.serialize(buffer, true) - serializeInt64(randomId, buffer: buffer, boxed: false) - message.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(allowPaidStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {sendAs!.serialize(buffer, true)} - return (FunctionDescription(name: "phone.sendGroupCallMessage", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("randomId", String(describing: randomId)), ("message", String(describing: message)), ("allowPaidStars", String(describing: allowPaidStars)), ("sendAs", String(describing: sendAs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func sendSignalingData(peer: Api.InputPhoneCall, data: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-8744061) - peer.serialize(buffer, true) - serializeBytes(data, buffer: buffer, boxed: false) - return (FunctionDescription(name: "phone.sendSignalingData", parameters: [("peer", String(describing: peer)), ("data", String(describing: data))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.phone { - static func setCallRating(flags: Int32, peer: Api.InputPhoneCall, rating: Int32, comment: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1508562471) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(rating, buffer: buffer, boxed: false) - serializeString(comment, buffer: buffer, boxed: false) - return (FunctionDescription(name: "phone.setCallRating", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("rating", String(describing: rating)), ("comment", String(describing: comment))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func startScheduledGroupCall(call: Api.InputGroupCall) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1451287362) - call.serialize(buffer, true) - return (FunctionDescription(name: "phone.startScheduledGroupCall", parameters: [("call", String(describing: call))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func toggleGroupCallRecord(flags: Int32, call: Api.InputGroupCall, title: String?, videoPortrait: Api.Bool?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-248985848) - serializeInt32(flags, buffer: buffer, boxed: false) - call.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {videoPortrait!.serialize(buffer, true)} - return (FunctionDescription(name: "phone.toggleGroupCallRecord", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("title", String(describing: title)), ("videoPortrait", String(describing: videoPortrait))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func toggleGroupCallSettings(flags: Int32, call: Api.InputGroupCall, joinMuted: Api.Bool?, messagesEnabled: Api.Bool?, sendPaidMessagesStars: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1757179150) - serializeInt32(flags, buffer: buffer, boxed: false) - call.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {joinMuted!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {messagesEnabled!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt64(sendPaidMessagesStars!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "phone.toggleGroupCallSettings", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("joinMuted", String(describing: joinMuted)), ("messagesEnabled", String(describing: messagesEnabled)), ("sendPaidMessagesStars", String(describing: sendPaidMessagesStars))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.phone { - static func toggleGroupCallStartSubscription(call: Api.InputGroupCall, subscribed: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(563885286) - call.serialize(buffer, true) - subscribed.serialize(buffer, true) - return (FunctionDescription(name: "phone.toggleGroupCallStartSubscription", parameters: [("call", String(describing: call)), ("subscribed", String(describing: subscribed))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.photos { - static func deletePhotos(id: [Api.InputPhoto]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Int64]>) { - let buffer = Buffer() - buffer.appendInt32(-2016444625) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "photos.deletePhotos", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Int64]? in - let reader = BufferReader(buffer) - var result: [Int64]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) - } - return result - }) - } -} -public extension Api.functions.photos { - static func getUserPhotos(userId: Api.InputUser, offset: Int32, maxId: Int64, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1848823128) - userId.serialize(buffer, true) - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt64(maxId, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "photos.getUserPhotos", parameters: [("userId", String(describing: userId)), ("offset", String(describing: offset)), ("maxId", String(describing: maxId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.photos.Photos? in - let reader = BufferReader(buffer) - var result: Api.photos.Photos? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.photos.Photos - } - return result - }) - } -} -public extension Api.functions.photos { - static func updateProfilePhoto(flags: Int32, bot: Api.InputUser?, id: Api.InputPhoto) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(166207545) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {bot!.serialize(buffer, true)} - id.serialize(buffer, true) - return (FunctionDescription(name: "photos.updateProfilePhoto", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.photos.Photo? in - let reader = BufferReader(buffer) - var result: Api.photos.Photo? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.photos.Photo - } - return result - }) - } -} -public extension Api.functions.photos { - static func uploadContactProfilePhoto(flags: Int32, userId: Api.InputUser, file: Api.InputFile?, video: Api.InputFile?, videoStartTs: Double?, videoEmojiMarkup: Api.VideoSize?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-515093903) - serializeInt32(flags, buffer: buffer, boxed: false) - userId.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {file!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {video!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeDouble(videoStartTs!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {videoEmojiMarkup!.serialize(buffer, true)} - return (FunctionDescription(name: "photos.uploadContactProfilePhoto", parameters: [("flags", String(describing: flags)), ("userId", String(describing: userId)), ("file", String(describing: file)), ("video", String(describing: video)), ("videoStartTs", String(describing: videoStartTs)), ("videoEmojiMarkup", String(describing: videoEmojiMarkup))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.photos.Photo? in - let reader = BufferReader(buffer) - var result: Api.photos.Photo? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.photos.Photo - } - return result - }) - } -} -public extension Api.functions.photos { - static func uploadProfilePhoto(flags: Int32, bot: Api.InputUser?, file: Api.InputFile?, video: Api.InputFile?, videoStartTs: Double?, videoEmojiMarkup: Api.VideoSize?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(59286453) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 5) != 0 {bot!.serialize(buffer, true)} - if Int(flags) & Int(1 << 0) != 0 {file!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {video!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeDouble(videoStartTs!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {videoEmojiMarkup!.serialize(buffer, true)} - return (FunctionDescription(name: "photos.uploadProfilePhoto", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("file", String(describing: file)), ("video", String(describing: video)), ("videoStartTs", String(describing: videoStartTs)), ("videoEmojiMarkup", String(describing: videoEmojiMarkup))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.photos.Photo? in - let reader = BufferReader(buffer) - var result: Api.photos.Photo? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.photos.Photo - } - return result - }) - } -} -public extension Api.functions.premium { - static func applyBoost(flags: Int32, slots: [Int32]?, peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1803396934) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(slots!.count)) - for item in slots! { - serializeInt32(item, buffer: buffer, boxed: false) - }} - peer.serialize(buffer, true) - return (FunctionDescription(name: "premium.applyBoost", parameters: [("flags", String(describing: flags)), ("slots", String(describing: slots)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.premium.MyBoosts? in - let reader = BufferReader(buffer) - var result: Api.premium.MyBoosts? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.premium.MyBoosts - } - return result - }) - } -} -public extension Api.functions.premium { - static func getBoostsList(flags: Int32, peer: Api.InputPeer, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1626764896) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeString(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "premium.getBoostsList", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.premium.BoostsList? in - let reader = BufferReader(buffer) - var result: Api.premium.BoostsList? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.premium.BoostsList - } - return result - }) - } -} -public extension Api.functions.premium { - static func getBoostsStatus(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(70197089) - peer.serialize(buffer, true) - return (FunctionDescription(name: "premium.getBoostsStatus", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.premium.BoostsStatus? in - let reader = BufferReader(buffer) - var result: Api.premium.BoostsStatus? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.premium.BoostsStatus - } - return result - }) - } -} -public extension Api.functions.premium { - static func getMyBoosts() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(199719754) - - return (FunctionDescription(name: "premium.getMyBoosts", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.premium.MyBoosts? in - let reader = BufferReader(buffer) - var result: Api.premium.MyBoosts? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.premium.MyBoosts - } - return result - }) - } -} -public extension Api.functions.premium { - static func getUserBoosts(peer: Api.InputPeer, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(965037343) - peer.serialize(buffer, true) - userId.serialize(buffer, true) - return (FunctionDescription(name: "premium.getUserBoosts", parameters: [("peer", String(describing: peer)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.premium.BoostsList? in - let reader = BufferReader(buffer) - var result: Api.premium.BoostsList? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.premium.BoostsList - } - return result - }) - } -} -public extension Api.functions.smsjobs { - static func finishJob(flags: Int32, jobId: String, error: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1327415076) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(jobId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(error!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "smsjobs.finishJob", parameters: [("flags", String(describing: flags)), ("jobId", String(describing: jobId)), ("error", String(describing: error))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.smsjobs { - static func getSmsJob(jobId: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2005766191) - serializeString(jobId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "smsjobs.getSmsJob", parameters: [("jobId", String(describing: jobId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.SmsJob? in - let reader = BufferReader(buffer) - var result: Api.SmsJob? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.SmsJob - } - return result - }) - } -} -public extension Api.functions.smsjobs { - static func getStatus() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(279353576) - - return (FunctionDescription(name: "smsjobs.getStatus", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.smsjobs.Status? in - let reader = BufferReader(buffer) - var result: Api.smsjobs.Status? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.smsjobs.Status - } - return result - }) - } -} -public extension Api.functions.smsjobs { - static func isEligibleToJoin() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(249313744) - - return (FunctionDescription(name: "smsjobs.isEligibleToJoin", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.smsjobs.EligibilityToJoin? in - let reader = BufferReader(buffer) - var result: Api.smsjobs.EligibilityToJoin? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.smsjobs.EligibilityToJoin - } - return result - }) - } -} -public extension Api.functions.smsjobs { - static func join() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1488007635) - - return (FunctionDescription(name: "smsjobs.join", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.smsjobs { - static func leave() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1734824589) - - return (FunctionDescription(name: "smsjobs.leave", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.smsjobs { - static func updateSettings(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(155164863) - serializeInt32(flags, buffer: buffer, boxed: false) - return (FunctionDescription(name: "smsjobs.updateSettings", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.stats { - static func getBroadcastStats(flags: Int32, channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1421720550) - serializeInt32(flags, buffer: buffer, boxed: false) - channel.serialize(buffer, true) - return (FunctionDescription(name: "stats.getBroadcastStats", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stats.BroadcastStats? in - let reader = BufferReader(buffer) - var result: Api.stats.BroadcastStats? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stats.BroadcastStats - } - return result - }) - } -} -public extension Api.functions.stats { - static func getMegagroupStats(flags: Int32, channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-589330937) - serializeInt32(flags, buffer: buffer, boxed: false) - channel.serialize(buffer, true) - return (FunctionDescription(name: "stats.getMegagroupStats", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stats.MegagroupStats? in - let reader = BufferReader(buffer) - var result: Api.stats.MegagroupStats? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stats.MegagroupStats - } - return result - }) - } -} -public extension Api.functions.stats { - static func getMessagePublicForwards(channel: Api.InputChannel, msgId: Int32, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1595212100) - channel.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeString(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stats.getMessagePublicForwards", parameters: [("channel", String(describing: channel)), ("msgId", String(describing: msgId)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stats.PublicForwards? in - let reader = BufferReader(buffer) - var result: Api.stats.PublicForwards? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stats.PublicForwards - } - return result - }) - } -} -public extension Api.functions.stats { - static func getMessageStats(flags: Int32, channel: Api.InputChannel, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1226791947) - serializeInt32(flags, buffer: buffer, boxed: false) - channel.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stats.getMessageStats", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stats.MessageStats? in - let reader = BufferReader(buffer) - var result: Api.stats.MessageStats? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stats.MessageStats - } - return result - }) - } -} -public extension Api.functions.stats { - static func getStoryPublicForwards(peer: Api.InputPeer, id: Int32, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1505526026) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - serializeString(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stats.getStoryPublicForwards", parameters: [("peer", String(describing: peer)), ("id", String(describing: id)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stats.PublicForwards? in - let reader = BufferReader(buffer) - var result: Api.stats.PublicForwards? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stats.PublicForwards - } - return result - }) - } -} -public extension Api.functions.stats { - static func getStoryStats(flags: Int32, peer: Api.InputPeer, id: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(927985472) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stats.getStoryStats", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stats.StoryStats? in - let reader = BufferReader(buffer) - var result: Api.stats.StoryStats? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stats.StoryStats - } - return result - }) - } -} -public extension Api.functions.stats { - static func loadAsyncGraph(flags: Int32, token: String, x: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1646092192) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(token, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(x!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "stats.loadAsyncGraph", parameters: [("flags", String(describing: flags)), ("token", String(describing: token)), ("x", String(describing: x))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.StatsGraph? in - let reader = BufferReader(buffer) - var result: Api.StatsGraph? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.StatsGraph - } - return result - }) - } -} -public extension Api.functions.stickers { - static func addStickerToSet(stickerset: Api.InputStickerSet, sticker: Api.InputStickerSetItem) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2041315650) - stickerset.serialize(buffer, true) - sticker.serialize(buffer, true) - return (FunctionDescription(name: "stickers.addStickerToSet", parameters: [("stickerset", String(describing: stickerset)), ("sticker", String(describing: sticker))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in - let reader = BufferReader(buffer) - var result: Api.messages.StickerSet? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet - } - return result - }) - } -} -public extension Api.functions.stickers { - static func changeSticker(flags: Int32, sticker: Api.InputDocument, emoji: String?, maskCoords: Api.MaskCoords?, keywords: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-179077444) - serializeInt32(flags, buffer: buffer, boxed: false) - sticker.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeString(emoji!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {maskCoords!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(keywords!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "stickers.changeSticker", parameters: [("flags", String(describing: flags)), ("sticker", String(describing: sticker)), ("emoji", String(describing: emoji)), ("maskCoords", String(describing: maskCoords)), ("keywords", String(describing: keywords))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in - let reader = BufferReader(buffer) - var result: Api.messages.StickerSet? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet - } - return result - }) - } -} -public extension Api.functions.stickers { - static func changeStickerPosition(sticker: Api.InputDocument, position: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-4795190) - sticker.serialize(buffer, true) - serializeInt32(position, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stickers.changeStickerPosition", parameters: [("sticker", String(describing: sticker)), ("position", String(describing: position))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in - let reader = BufferReader(buffer) - var result: Api.messages.StickerSet? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet - } - return result - }) - } -} -public extension Api.functions.stickers { - static func checkShortName(shortName: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(676017721) - serializeString(shortName, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stickers.checkShortName", parameters: [("shortName", String(describing: shortName))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.stickers { - static func createStickerSet(flags: Int32, userId: Api.InputUser, title: String, shortName: String, thumb: Api.InputDocument?, stickers: [Api.InputStickerSetItem], software: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1876841625) - serializeInt32(flags, buffer: buffer, boxed: false) - userId.serialize(buffer, true) - serializeString(title, buffer: buffer, boxed: false) - serializeString(shortName, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {thumb!.serialize(buffer, true)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stickers.count)) - for item in stickers { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 3) != 0 {serializeString(software!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "stickers.createStickerSet", parameters: [("flags", String(describing: flags)), ("userId", String(describing: userId)), ("title", String(describing: title)), ("shortName", String(describing: shortName)), ("thumb", String(describing: thumb)), ("stickers", String(describing: stickers)), ("software", String(describing: software))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in - let reader = BufferReader(buffer) - var result: Api.messages.StickerSet? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet - } - return result - }) - } -} -public extension Api.functions.stickers { - static func deleteStickerSet(stickerset: Api.InputStickerSet) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2022685804) - stickerset.serialize(buffer, true) - return (FunctionDescription(name: "stickers.deleteStickerSet", parameters: [("stickerset", String(describing: stickerset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.stickers { - static func removeStickerFromSet(sticker: Api.InputDocument) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-143257775) - sticker.serialize(buffer, true) - return (FunctionDescription(name: "stickers.removeStickerFromSet", parameters: [("sticker", String(describing: sticker))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in - let reader = BufferReader(buffer) - var result: Api.messages.StickerSet? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet - } - return result - }) - } -} -public extension Api.functions.stickers { - static func renameStickerSet(stickerset: Api.InputStickerSet, title: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(306912256) - stickerset.serialize(buffer, true) - serializeString(title, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stickers.renameStickerSet", parameters: [("stickerset", String(describing: stickerset)), ("title", String(describing: title))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in - let reader = BufferReader(buffer) - var result: Api.messages.StickerSet? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet - } - return result - }) - } -} -public extension Api.functions.stickers { - static func replaceSticker(sticker: Api.InputDocument, newSticker: Api.InputStickerSetItem) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1184253338) - sticker.serialize(buffer, true) - newSticker.serialize(buffer, true) - return (FunctionDescription(name: "stickers.replaceSticker", parameters: [("sticker", String(describing: sticker)), ("newSticker", String(describing: newSticker))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in - let reader = BufferReader(buffer) - var result: Api.messages.StickerSet? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet - } - return result - }) - } -} -public extension Api.functions.stickers { - static func setStickerSetThumb(flags: Int32, stickerset: Api.InputStickerSet, thumb: Api.InputDocument?, thumbDocumentId: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1486204014) - serializeInt32(flags, buffer: buffer, boxed: false) - stickerset.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {thumb!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt64(thumbDocumentId!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "stickers.setStickerSetThumb", parameters: [("flags", String(describing: flags)), ("stickerset", String(describing: stickerset)), ("thumb", String(describing: thumb)), ("thumbDocumentId", String(describing: thumbDocumentId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in - let reader = BufferReader(buffer) - var result: Api.messages.StickerSet? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet - } - return result - }) - } -} -public extension Api.functions.stickers { - static func suggestShortName(title: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1303364867) - serializeString(title, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stickers.suggestShortName", parameters: [("title", String(describing: title))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stickers.SuggestedShortName? in - let reader = BufferReader(buffer) - var result: Api.stickers.SuggestedShortName? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stickers.SuggestedShortName - } - return result - }) - } -} -public extension Api.functions.stories { - static func activateStealthMode(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1471926630) - serializeInt32(flags, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stories.activateStealthMode", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.stories { - static func canSendStory(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(820732912) - peer.serialize(buffer, true) - return (FunctionDescription(name: "stories.canSendStory", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.CanSendStoryCount? in - let reader = BufferReader(buffer) - var result: Api.stories.CanSendStoryCount? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stories.CanSendStoryCount - } - return result - }) - } -} -public extension Api.functions.stories { - static func createAlbum(peer: Api.InputPeer, title: String, stories: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1553754395) - peer.serialize(buffer, true) - serializeString(title, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(stories.count)) - for item in stories { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "stories.createAlbum", parameters: [("peer", String(describing: peer)), ("title", String(describing: title)), ("stories", String(describing: stories))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.StoryAlbum? in - let reader = BufferReader(buffer) - var result: Api.StoryAlbum? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.StoryAlbum - } - return result - }) - } -} -public extension Api.functions.stories { - static func deleteAlbum(peer: Api.InputPeer, albumId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1925949744) - peer.serialize(buffer, true) - serializeInt32(albumId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stories.deleteAlbum", parameters: [("peer", String(describing: peer)), ("albumId", String(describing: albumId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.stories { - static func deleteStories(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Int32]>) { - let buffer = Buffer() - buffer.appendInt32(-1369842849) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "stories.deleteStories", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Int32]? in - let reader = BufferReader(buffer) - var result: [Int32]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - return result - }) - } -} -public extension Api.functions.stories { - static func editStory(flags: Int32, peer: Api.InputPeer, id: Int32, media: Api.InputMedia?, mediaAreas: [Api.MediaArea]?, caption: String?, entities: [Api.MessageEntity]?, privacyRules: [Api.InputPrivacyRule]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1249658298) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {media!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(mediaAreas!.count)) - for item in mediaAreas! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 1) != 0 {serializeString(caption!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 2) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(privacyRules!.count)) - for item in privacyRules! { - item.serialize(buffer, true) - }} - return (FunctionDescription(name: "stories.editStory", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("media", String(describing: media)), ("mediaAreas", String(describing: mediaAreas)), ("caption", String(describing: caption)), ("entities", String(describing: entities)), ("privacyRules", String(describing: privacyRules))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.stories { - static func exportStoryLink(peer: Api.InputPeer, id: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2072899360) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stories.exportStoryLink", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ExportedStoryLink? in - let reader = BufferReader(buffer) - var result: Api.ExportedStoryLink? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.ExportedStoryLink - } - return result - }) - } -} -public extension Api.functions.stories { - static func getAlbumStories(peer: Api.InputPeer, albumId: Int32, offset: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1400869535) - peer.serialize(buffer, true) - serializeInt32(albumId, buffer: buffer, boxed: false) - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stories.getAlbumStories", parameters: [("peer", String(describing: peer)), ("albumId", String(describing: albumId)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.Stories? in - let reader = BufferReader(buffer) - var result: Api.stories.Stories? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stories.Stories - } - return result - }) - } -} -public extension Api.functions.stories { - static func getAlbums(peer: Api.InputPeer, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(632548039) - peer.serialize(buffer, true) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stories.getAlbums", parameters: [("peer", String(describing: peer)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.Albums? in - let reader = BufferReader(buffer) - var result: Api.stories.Albums? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stories.Albums - } - return result - }) - } -} -public extension Api.functions.stories { - static func getAllReadPeerStories() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1688541191) - - return (FunctionDescription(name: "stories.getAllReadPeerStories", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.stories { - static func getAllStories(flags: Int32, state: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-290400731) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(state!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "stories.getAllStories", parameters: [("flags", String(describing: flags)), ("state", String(describing: state))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.AllStories? in - let reader = BufferReader(buffer) - var result: Api.stories.AllStories? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stories.AllStories - } - return result - }) - } -} -public extension Api.functions.stories { - static func getChatsToSend() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1519744160) - - return (FunctionDescription(name: "stories.getChatsToSend", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in - let reader = BufferReader(buffer) - var result: Api.messages.Chats? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.messages.Chats - } - return result - }) - } -} -public extension Api.functions.stories { - static func getPeerMaxIDs(id: [Api.InputPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.RecentStory]>) { - let buffer = Buffer() - buffer.appendInt32(2018087280) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "stories.getPeerMaxIDs", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.RecentStory]? in - let reader = BufferReader(buffer) - var result: [Api.RecentStory]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.RecentStory.self) - } - return result - }) - } -} -public extension Api.functions.stories { - static func getPeerStories(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(743103056) - peer.serialize(buffer, true) - return (FunctionDescription(name: "stories.getPeerStories", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.PeerStories? in - let reader = BufferReader(buffer) - var result: Api.stories.PeerStories? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stories.PeerStories - } - return result - }) - } -} -public extension Api.functions.stories { - static func getPinnedStories(peer: Api.InputPeer, offsetId: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1478600156) - peer.serialize(buffer, true) - serializeInt32(offsetId, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stories.getPinnedStories", parameters: [("peer", String(describing: peer)), ("offsetId", String(describing: offsetId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.Stories? in - let reader = BufferReader(buffer) - var result: Api.stories.Stories? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stories.Stories - } - return result - }) - } -} -public extension Api.functions.stories { - static func getStoriesArchive(peer: Api.InputPeer, offsetId: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1271586794) - peer.serialize(buffer, true) - serializeInt32(offsetId, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stories.getStoriesArchive", parameters: [("peer", String(describing: peer)), ("offsetId", String(describing: offsetId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.Stories? in - let reader = BufferReader(buffer) - var result: Api.stories.Stories? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stories.Stories - } - return result - }) - } -} -public extension Api.functions.stories { - static func getStoriesByID(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1467271796) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "stories.getStoriesByID", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.Stories? in - let reader = BufferReader(buffer) - var result: Api.stories.Stories? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stories.Stories - } - return result - }) - } -} -public extension Api.functions.stories { - static func getStoriesViews(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(685862088) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "stories.getStoriesViews", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.StoryViews? in - let reader = BufferReader(buffer) - var result: Api.stories.StoryViews? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stories.StoryViews - } - return result - }) - } -} -public extension Api.functions.stories { - static func getStoryReactionsList(flags: Int32, peer: Api.InputPeer, id: Int32, reaction: Api.Reaction?, offset: String?, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1179482081) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {reaction!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(offset!, buffer: buffer, boxed: false)} - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stories.getStoryReactionsList", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("reaction", String(describing: reaction)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.StoryReactionsList? in - let reader = BufferReader(buffer) - var result: Api.stories.StoryReactionsList? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stories.StoryReactionsList - } - return result - }) - } -} -public extension Api.functions.stories { - static func getStoryViewsList(flags: Int32, peer: Api.InputPeer, q: String?, id: Int32, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2127707223) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 1) != 0 {serializeString(q!, buffer: buffer, boxed: false)} - serializeInt32(id, buffer: buffer, boxed: false) - serializeString(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stories.getStoryViewsList", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("q", String(describing: q)), ("id", String(describing: id)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.StoryViewsList? in - let reader = BufferReader(buffer) - var result: Api.stories.StoryViewsList? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stories.StoryViewsList - } - return result - }) - } -} -public extension Api.functions.stories { - static func incrementStoryViews(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1308456197) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "stories.incrementStoryViews", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.stories { - static func readStories(peer: Api.InputPeer, maxId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Int32]>) { - let buffer = Buffer() - buffer.appendInt32(-1521034552) - peer.serialize(buffer, true) - serializeInt32(maxId, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stories.readStories", parameters: [("peer", String(describing: peer)), ("maxId", String(describing: maxId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Int32]? in - let reader = BufferReader(buffer) - var result: [Int32]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - return result - }) - } -} -public extension Api.functions.stories { - static func reorderAlbums(peer: Api.InputPeer, order: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-2060059687) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order.count)) - for item in order { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "stories.reorderAlbums", parameters: [("peer", String(describing: peer)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.stories { - static func report(peer: Api.InputPeer, id: [Int32], option: Buffer, message: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(433646405) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - serializeBytes(option, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stories.report", parameters: [("peer", String(describing: peer)), ("id", String(describing: id)), ("option", String(describing: option)), ("message", String(describing: message))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ReportResult? in - let reader = BufferReader(buffer) - var result: Api.ReportResult? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.ReportResult - } - return result - }) - } -} -public extension Api.functions.stories { - static func searchPosts(flags: Int32, hashtag: String?, area: Api.MediaArea?, peer: Api.InputPeer?, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-780072697) - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(hashtag!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {area!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {peer!.serialize(buffer, true)} - serializeString(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "stories.searchPosts", parameters: [("flags", String(describing: flags)), ("hashtag", String(describing: hashtag)), ("area", String(describing: area)), ("peer", String(describing: peer)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.FoundStories? in - let reader = BufferReader(buffer) - var result: Api.stories.FoundStories? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.stories.FoundStories - } - return result - }) - } -} -public extension Api.functions.stories { - static func sendReaction(flags: Int32, peer: Api.InputPeer, storyId: Int32, reaction: Api.Reaction) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2144810674) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(storyId, buffer: buffer, boxed: false) - reaction.serialize(buffer, true) - return (FunctionDescription(name: "stories.sendReaction", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("storyId", String(describing: storyId)), ("reaction", String(describing: reaction))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.stories { - static func sendStory(flags: Int32, peer: Api.InputPeer, media: Api.InputMedia, mediaAreas: [Api.MediaArea]?, caption: String?, entities: [Api.MessageEntity]?, privacyRules: [Api.InputPrivacyRule], randomId: Int64, period: Int32?, fwdFromId: Api.InputPeer?, fwdFromStory: Int32?, albums: [Int32]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1937752812) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - media.serialize(buffer, true) - if Int(flags) & Int(1 << 5) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(mediaAreas!.count)) - for item in mediaAreas! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 0) != 0 {serializeString(caption!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { - item.serialize(buffer, true) - }} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(privacyRules.count)) - for item in privacyRules { - item.serialize(buffer, true) - } - serializeInt64(randomId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(period!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 6) != 0 {fwdFromId!.serialize(buffer, true)} - if Int(flags) & Int(1 << 6) != 0 {serializeInt32(fwdFromStory!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(albums!.count)) - for item in albums! { - serializeInt32(item, buffer: buffer, boxed: false) - }} - return (FunctionDescription(name: "stories.sendStory", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("media", String(describing: media)), ("mediaAreas", String(describing: mediaAreas)), ("caption", String(describing: caption)), ("entities", String(describing: entities)), ("privacyRules", String(describing: privacyRules)), ("randomId", String(describing: randomId)), ("period", String(describing: period)), ("fwdFromId", String(describing: fwdFromId)), ("fwdFromStory", String(describing: fwdFromStory)), ("albums", String(describing: albums))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.stories { - static func startLive(flags: Int32, peer: Api.InputPeer, caption: String?, entities: [Api.MessageEntity]?, privacyRules: [Api.InputPrivacyRule], randomId: Int64, messagesEnabled: Api.Bool?, sendPaidMessagesStars: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-798372642) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeString(caption!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { - item.serialize(buffer, true) - }} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(privacyRules.count)) - for item in privacyRules { - item.serialize(buffer, true) - } - serializeInt64(randomId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 6) != 0 {messagesEnabled!.serialize(buffer, true)} - if Int(flags) & Int(1 << 7) != 0 {serializeInt64(sendPaidMessagesStars!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "stories.startLive", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("caption", String(describing: caption)), ("entities", String(describing: entities)), ("privacyRules", String(describing: privacyRules)), ("randomId", String(describing: randomId)), ("messagesEnabled", String(describing: messagesEnabled)), ("sendPaidMessagesStars", String(describing: sendPaidMessagesStars))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) - } -} -public extension Api.functions.stories { - static func toggleAllStoriesHidden(hidden: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2082822084) - hidden.serialize(buffer, true) - return (FunctionDescription(name: "stories.toggleAllStoriesHidden", parameters: [("hidden", String(describing: hidden))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.stories { - static func togglePeerStoriesHidden(peer: Api.InputPeer, hidden: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1123805756) - peer.serialize(buffer, true) - hidden.serialize(buffer, true) - return (FunctionDescription(name: "stories.togglePeerStoriesHidden", parameters: [("peer", String(describing: peer)), ("hidden", String(describing: hidden))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.stories { - static func togglePinned(peer: Api.InputPeer, id: [Int32], pinned: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Int32]>) { - let buffer = Buffer() - buffer.appendInt32(-1703566865) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - pinned.serialize(buffer, true) - return (FunctionDescription(name: "stories.togglePinned", parameters: [("peer", String(describing: peer)), ("id", String(describing: id)), ("pinned", String(describing: pinned))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Int32]? in - let reader = BufferReader(buffer) - var result: [Int32]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) - } - return result - }) - } -} -public extension Api.functions.stories { - static func togglePinnedToTop(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(187268763) - peer.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - serializeInt32(item, buffer: buffer, boxed: false) - } - return (FunctionDescription(name: "stories.togglePinnedToTop", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.stories { - static func updateAlbum(flags: Int32, peer: Api.InputPeer, albumId: Int32, title: String?, deleteStories: [Int32]?, addStories: [Int32]?, order: [Int32]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1582455222) - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(albumId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(deleteStories!.count)) - for item in deleteStories! { - serializeInt32(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 2) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(addStories!.count)) - for item in addStories! { - serializeInt32(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(order!.count)) - for item in order! { - serializeInt32(item, buffer: buffer, boxed: false) - }} - return (FunctionDescription(name: "stories.updateAlbum", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("albumId", String(describing: albumId)), ("title", String(describing: title)), ("deleteStories", String(describing: deleteStories)), ("addStories", String(describing: addStories)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.StoryAlbum? in - let reader = BufferReader(buffer) - var result: Api.StoryAlbum? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.StoryAlbum - } - return result - }) - } -} -public extension Api.functions.updates { - static func getChannelDifference(flags: Int32, channel: Api.InputChannel, filter: Api.ChannelMessagesFilter, pts: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(51854712) - serializeInt32(flags, buffer: buffer, boxed: false) - channel.serialize(buffer, true) - filter.serialize(buffer, true) - serializeInt32(pts, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "updates.getChannelDifference", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel)), ("filter", String(describing: filter)), ("pts", String(describing: pts)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.updates.ChannelDifference? in - let reader = BufferReader(buffer) - var result: Api.updates.ChannelDifference? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.updates.ChannelDifference - } - return result - }) - } -} -public extension Api.functions.updates { - static func getDifference(flags: Int32, pts: Int32, ptsLimit: Int32?, ptsTotalLimit: Int32?, date: Int32, qts: Int32, qtsLimit: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(432207715) - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(pts, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(ptsLimit!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(ptsTotalLimit!, buffer: buffer, boxed: false)} - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt32(qts, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(qtsLimit!, buffer: buffer, boxed: false)} - return (FunctionDescription(name: "updates.getDifference", parameters: [("flags", String(describing: flags)), ("pts", String(describing: pts)), ("ptsLimit", String(describing: ptsLimit)), ("ptsTotalLimit", String(describing: ptsTotalLimit)), ("date", String(describing: date)), ("qts", String(describing: qts)), ("qtsLimit", String(describing: qtsLimit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.updates.Difference? in - let reader = BufferReader(buffer) - var result: Api.updates.Difference? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.updates.Difference - } - return result - }) - } -} -public extension Api.functions.updates { - static func getState() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-304838614) - - return (FunctionDescription(name: "updates.getState", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.updates.State? in - let reader = BufferReader(buffer) - var result: Api.updates.State? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.updates.State - } - return result - }) - } -} -public extension Api.functions.upload { - static func getCdnFile(fileToken: Buffer, offset: Int64, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(962554330) - serializeBytes(fileToken, buffer: buffer, boxed: false) - serializeInt64(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "upload.getCdnFile", parameters: [("fileToken", String(describing: fileToken)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.upload.CdnFile? in - let reader = BufferReader(buffer) - var result: Api.upload.CdnFile? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.upload.CdnFile - } - return result - }) - } -} -public extension Api.functions.upload { - static func getCdnFileHashes(fileToken: Buffer, offset: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.FileHash]>) { - let buffer = Buffer() - buffer.appendInt32(-1847836879) - serializeBytes(fileToken, buffer: buffer, boxed: false) - serializeInt64(offset, buffer: buffer, boxed: false) - return (FunctionDescription(name: "upload.getCdnFileHashes", parameters: [("fileToken", String(describing: fileToken)), ("offset", String(describing: offset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.FileHash]? in - let reader = BufferReader(buffer) - var result: [Api.FileHash]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.FileHash.self) - } - return result - }) - } -} -public extension Api.functions.upload { - static func getFile(flags: Int32, location: Api.InputFileLocation, offset: Int64, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1101843010) - serializeInt32(flags, buffer: buffer, boxed: false) - location.serialize(buffer, true) - serializeInt64(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "upload.getFile", parameters: [("flags", String(describing: flags)), ("location", String(describing: location)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.upload.File? in - let reader = BufferReader(buffer) - var result: Api.upload.File? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.upload.File - } - return result - }) - } -} -public extension Api.functions.upload { - static func getFileHashes(location: Api.InputFileLocation, offset: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.FileHash]>) { - let buffer = Buffer() - buffer.appendInt32(-1856595926) - location.serialize(buffer, true) - serializeInt64(offset, buffer: buffer, boxed: false) - return (FunctionDescription(name: "upload.getFileHashes", parameters: [("location", String(describing: location)), ("offset", String(describing: offset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.FileHash]? in - let reader = BufferReader(buffer) - var result: [Api.FileHash]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.FileHash.self) - } - return result - }) - } -} -public extension Api.functions.upload { - static func getWebFile(location: Api.InputWebFileLocation, offset: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(619086221) - location.serialize(buffer, true) - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - return (FunctionDescription(name: "upload.getWebFile", parameters: [("location", String(describing: location)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.upload.WebFile? in - let reader = BufferReader(buffer) - var result: Api.upload.WebFile? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.upload.WebFile - } - return result - }) - } -} -public extension Api.functions.upload { - static func reuploadCdnFile(fileToken: Buffer, requestToken: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.FileHash]>) { - let buffer = Buffer() - buffer.appendInt32(-1691921240) - serializeBytes(fileToken, buffer: buffer, boxed: false) - serializeBytes(requestToken, buffer: buffer, boxed: false) - return (FunctionDescription(name: "upload.reuploadCdnFile", parameters: [("fileToken", String(describing: fileToken)), ("requestToken", String(describing: requestToken))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.FileHash]? in - let reader = BufferReader(buffer) - var result: [Api.FileHash]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.FileHash.self) - } - return result - }) - } -} -public extension Api.functions.upload { - static func saveBigFilePart(fileId: Int64, filePart: Int32, fileTotalParts: Int32, bytes: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-562337987) - serializeInt64(fileId, buffer: buffer, boxed: false) - serializeInt32(filePart, buffer: buffer, boxed: false) - serializeInt32(fileTotalParts, buffer: buffer, boxed: false) - serializeBytes(bytes, buffer: buffer, boxed: false) - return (FunctionDescription(name: "upload.saveBigFilePart", parameters: [("fileId", String(describing: fileId)), ("filePart", String(describing: filePart)), ("fileTotalParts", String(describing: fileTotalParts)), ("bytes", String(describing: bytes))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.upload { - static func saveFilePart(fileId: Int64, filePart: Int32, bytes: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1291540959) - serializeInt64(fileId, buffer: buffer, boxed: false) - serializeInt32(filePart, buffer: buffer, boxed: false) - serializeBytes(bytes, buffer: buffer, boxed: false) - return (FunctionDescription(name: "upload.saveFilePart", parameters: [("fileId", String(describing: fileId)), ("filePart", String(describing: filePart)), ("bytes", String(describing: bytes))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.users { - static func getFullUser(id: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1240508136) - id.serialize(buffer, true) - return (FunctionDescription(name: "users.getFullUser", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.users.UserFull? in - let reader = BufferReader(buffer) - var result: Api.users.UserFull? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.users.UserFull - } - return result - }) - } -} -public extension Api.functions.users { - static func getRequirementsToContact(id: [Api.InputUser]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.RequirementToContact]>) { - let buffer = Buffer() - buffer.appendInt32(-660962397) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "users.getRequirementsToContact", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.RequirementToContact]? in - let reader = BufferReader(buffer) - var result: [Api.RequirementToContact]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.RequirementToContact.self) - } - return result - }) - } -} -public extension Api.functions.users { - static func getSavedMusic(id: Api.InputUser, offset: Int32, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(2022539235) - id.serialize(buffer, true) - serializeInt32(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeInt64(hash, buffer: buffer, boxed: false) - return (FunctionDescription(name: "users.getSavedMusic", parameters: [("id", String(describing: id)), ("offset", String(describing: offset)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.users.SavedMusic? in - let reader = BufferReader(buffer) - var result: Api.users.SavedMusic? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.users.SavedMusic - } - return result - }) - } -} -public extension Api.functions.users { - static func getSavedMusicByID(id: Api.InputUser, documents: [Api.InputDocument]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(1970513129) - id.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(documents.count)) - for item in documents { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "users.getSavedMusicByID", parameters: [("id", String(describing: id)), ("documents", String(describing: documents))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.users.SavedMusic? in - let reader = BufferReader(buffer) - var result: Api.users.SavedMusic? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.users.SavedMusic - } - return result - }) - } -} -public extension Api.functions.users { - static func getUsers(id: [Api.InputUser]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.User]>) { - let buffer = Buffer() - buffer.appendInt32(227648840) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(id.count)) - for item in id { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "users.getUsers", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.User]? in - let reader = BufferReader(buffer) - var result: [Api.User]? - if let _ = reader.readInt32() { - result = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } - return result - }) - } -} -public extension Api.functions.users { - static func setSecureValueErrors(id: Api.InputUser, errors: [Api.SecureValueError]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-1865902923) - id.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(errors.count)) - for item in errors { - item.serialize(buffer, true) - } - return (FunctionDescription(name: "users.setSecureValueErrors", parameters: [("id", String(describing: id)), ("errors", String(describing: errors))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in - let reader = BufferReader(buffer) - var result: Api.Bool? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Bool - } - return result - }) - } -} -public extension Api.functions.users { - static func suggestBirthday(id: Api.InputUser, birthday: Api.Birthday) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { - let buffer = Buffer() - buffer.appendInt32(-61656206) - id.serialize(buffer, true) - birthday.serialize(buffer, true) - return (FunctionDescription(name: "users.suggestBirthday", parameters: [("id", String(describing: id)), ("birthday", String(describing: birthday))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in - let reader = BufferReader(buffer) - var result: Api.Updates? - if let signature = reader.readInt32() { - result = Api.parse(reader, signature: signature) as? Api.Updates - } - return result - }) } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .stories(let _data): + return ("stories", [("flags", _data.flags as Any), ("count", _data.count as Any), ("stories", _data.stories as Any), ("pinnedToTop", _data.pinnedToTop as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_stories(_ reader: BufferReader) -> Stories? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: [Api.StoryItem]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StoryItem.self) + } + var _4: [Int32]? + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + } + var _5: [Api.Chat]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _6: [Api.User]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.stories.Stories.stories(Cons_stories(flags: _1!, count: _2!, stories: _3!, pinnedToTop: _4, chats: _5!, users: _6!)) + } + else { + return nil + } + } + } +} +public extension Api.stories { + enum StoryReactionsList: TypeConstructorDescription { + public class Cons_storyReactionsList { + public var flags: Int32 + public var count: Int32 + public var reactions: [Api.StoryReaction] + public var chats: [Api.Chat] + public var users: [Api.User] + public var nextOffset: String? + public init(flags: Int32, count: Int32, reactions: [Api.StoryReaction], chats: [Api.Chat], users: [Api.User], nextOffset: String?) { + self.flags = flags + self.count = count + self.reactions = reactions + self.chats = chats + self.users = users + self.nextOffset = nextOffset + } + } + case storyReactionsList(Cons_storyReactionsList) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .storyReactionsList(let _data): + if boxed { + buffer.appendInt32(-1436583780) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.reactions.count)) + for item in _data.reactions { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.nextOffset!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .storyReactionsList(let _data): + return ("storyReactionsList", [("flags", _data.flags as Any), ("count", _data.count as Any), ("reactions", _data.reactions as Any), ("chats", _data.chats as Any), ("users", _data.users as Any), ("nextOffset", _data.nextOffset as Any)]) + } + } + + public static func parse_storyReactionsList(_ reader: BufferReader) -> StoryReactionsList? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: [Api.StoryReaction]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StoryReaction.self) + } + var _4: [Api.Chat]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _5: [Api.User]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + var _6: String? + if Int(_1!) & Int(1 << 0) != 0 { + _6 = parseString(reader) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.stories.StoryReactionsList.storyReactionsList(Cons_storyReactionsList(flags: _1!, count: _2!, reactions: _3!, chats: _4!, users: _5!, nextOffset: _6)) + } + else { + return nil + } + } + } +} +public extension Api.stories { + enum StoryViews: TypeConstructorDescription { + public class Cons_storyViews { + public var views: [Api.StoryViews] + public var users: [Api.User] + public init(views: [Api.StoryViews], users: [Api.User]) { + self.views = views + self.users = users + } + } + case storyViews(Cons_storyViews) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .storyViews(let _data): + if boxed { + buffer.appendInt32(-560009955) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.views.count)) + for item in _data.views { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .storyViews(let _data): + return ("storyViews", [("views", _data.views as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_storyViews(_ reader: BufferReader) -> StoryViews? { + var _1: [Api.StoryViews]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StoryViews.self) + } + var _2: [Api.User]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.stories.StoryViews.storyViews(Cons_storyViews(views: _1!, users: _2!)) + } + else { + return nil + } + } + } +} +public extension Api.stories { + enum StoryViewsList: TypeConstructorDescription { + public class Cons_storyViewsList { + public var flags: Int32 + public var count: Int32 + public var viewsCount: Int32 + public var forwardsCount: Int32 + public var reactionsCount: Int32 + public var views: [Api.StoryView] + public var chats: [Api.Chat] + public var users: [Api.User] + public var nextOffset: String? + public init(flags: Int32, count: Int32, viewsCount: Int32, forwardsCount: Int32, reactionsCount: Int32, views: [Api.StoryView], chats: [Api.Chat], users: [Api.User], nextOffset: String?) { + self.flags = flags + self.count = count + self.viewsCount = viewsCount + self.forwardsCount = forwardsCount + self.reactionsCount = reactionsCount + self.views = views + self.chats = chats + self.users = users + self.nextOffset = nextOffset + } + } + case storyViewsList(Cons_storyViewsList) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .storyViewsList(let _data): + if boxed { + buffer.appendInt32(1507299269) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.count, buffer: buffer, boxed: false) + serializeInt32(_data.viewsCount, buffer: buffer, boxed: false) + serializeInt32(_data.forwardsCount, buffer: buffer, boxed: false) + serializeInt32(_data.reactionsCount, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.views.count)) + for item in _data.views { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.nextOffset!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .storyViewsList(let _data): + return ("storyViewsList", [("flags", _data.flags as Any), ("count", _data.count as Any), ("viewsCount", _data.viewsCount as Any), ("forwardsCount", _data.forwardsCount as Any), ("reactionsCount", _data.reactionsCount as Any), ("views", _data.views as Any), ("chats", _data.chats as Any), ("users", _data.users as Any), ("nextOffset", _data.nextOffset as Any)]) + } + } + + public static func parse_storyViewsList(_ reader: BufferReader) -> StoryViewsList? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + var _4: Int32? + _4 = reader.readInt32() + var _5: Int32? + _5 = reader.readInt32() + var _6: [Api.StoryView]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.StoryView.self) + } + var _7: [Api.Chat]? + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _8: [Api.User]? + if let _ = reader.readInt32() { + _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + var _9: String? + if Int(_1!) & Int(1 << 0) != 0 { + _9 = parseString(reader) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + let _c7 = _7 != nil + let _c8 = _8 != nil + let _c9 = (Int(_1!) & Int(1 << 0) == 0) || _9 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.stories.StoryViewsList.storyViewsList(Cons_storyViewsList(flags: _1!, count: _2!, viewsCount: _3!, forwardsCount: _4!, reactionsCount: _5!, views: _6!, chats: _7!, users: _8!, nextOffset: _9)) + } + else { + return nil + } + } + } +} +public extension Api.updates { + indirect enum ChannelDifference: TypeConstructorDescription { + public class Cons_channelDifference { + public var flags: Int32 + public var pts: Int32 + public var timeout: Int32? + public var newMessages: [Api.Message] + public var otherUpdates: [Api.Update] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, pts: Int32, timeout: Int32?, newMessages: [Api.Message], otherUpdates: [Api.Update], chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.pts = pts + self.timeout = timeout + self.newMessages = newMessages + self.otherUpdates = otherUpdates + self.chats = chats + self.users = users + } + } + public class Cons_channelDifferenceEmpty { + public var flags: Int32 + public var pts: Int32 + public var timeout: Int32? + public init(flags: Int32, pts: Int32, timeout: Int32?) { + self.flags = flags + self.pts = pts + self.timeout = timeout + } + } + public class Cons_channelDifferenceTooLong { + public var flags: Int32 + public var timeout: Int32? + public var dialog: Api.Dialog + public var messages: [Api.Message] + public var chats: [Api.Chat] + public var users: [Api.User] + public init(flags: Int32, timeout: Int32?, dialog: Api.Dialog, messages: [Api.Message], chats: [Api.Chat], users: [Api.User]) { + self.flags = flags + self.timeout = timeout + self.dialog = dialog + self.messages = messages + self.chats = chats + self.users = users + } + } + case channelDifference(Cons_channelDifference) + case channelDifferenceEmpty(Cons_channelDifferenceEmpty) + case channelDifferenceTooLong(Cons_channelDifferenceTooLong) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .channelDifference(let _data): + if boxed { + buffer.appendInt32(543450958) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.pts, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.timeout!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.newMessages.count)) + for item in _data.newMessages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.otherUpdates.count)) + for item in _data.otherUpdates { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .channelDifferenceEmpty(let _data): + if boxed { + buffer.appendInt32(1041346555) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.pts, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.timeout!, buffer: buffer, boxed: false) + } + break + case .channelDifferenceTooLong(let _data): + if boxed { + buffer.appendInt32(-1531132162) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.timeout!, buffer: buffer, boxed: false) + } + _data.dialog.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.messages.count)) + for item in _data.messages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .channelDifference(let _data): + return ("channelDifference", [("flags", _data.flags as Any), ("pts", _data.pts as Any), ("timeout", _data.timeout as Any), ("newMessages", _data.newMessages as Any), ("otherUpdates", _data.otherUpdates as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + case .channelDifferenceEmpty(let _data): + return ("channelDifferenceEmpty", [("flags", _data.flags as Any), ("pts", _data.pts as Any), ("timeout", _data.timeout as Any)]) + case .channelDifferenceTooLong(let _data): + return ("channelDifferenceTooLong", [("flags", _data.flags as Any), ("timeout", _data.timeout as Any), ("dialog", _data.dialog as Any), ("messages", _data.messages as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_channelDifference(_ reader: BufferReader) -> ChannelDifference? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _3 = reader.readInt32() + } + var _4: [Api.Message]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) + } + var _5: [Api.Update]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Update.self) + } + var _6: [Api.Chat]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _7: [Api.User]? + if let _ = reader.readInt32() { + _7 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + let _c7 = _7 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.updates.ChannelDifference.channelDifference(Cons_channelDifference(flags: _1!, pts: _2!, timeout: _3, newMessages: _4!, otherUpdates: _5!, chats: _6!, users: _7!)) + } + else { + return nil + } + } + public static func parse_channelDifferenceEmpty(_ reader: BufferReader) -> ChannelDifference? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _3 = reader.readInt32() + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil + if _c1 && _c2 && _c3 { + return Api.updates.ChannelDifference.channelDifferenceEmpty(Cons_channelDifferenceEmpty(flags: _1!, pts: _2!, timeout: _3)) + } + else { + return nil + } + } + public static func parse_channelDifferenceTooLong(_ reader: BufferReader) -> ChannelDifference? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + if Int(_1!) & Int(1 << 1) != 0 { + _2 = reader.readInt32() + } + var _3: Api.Dialog? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.Dialog + } + var _4: [Api.Message]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) + } + var _5: [Api.Chat]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _6: [Api.User]? + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.updates.ChannelDifference.channelDifferenceTooLong(Cons_channelDifferenceTooLong(flags: _1!, timeout: _2, dialog: _3!, messages: _4!, chats: _5!, users: _6!)) + } + else { + return nil + } + } + } +} +public extension Api.updates { + enum Difference: TypeConstructorDescription { + public class Cons_difference { + public var newMessages: [Api.Message] + public var newEncryptedMessages: [Api.EncryptedMessage] + public var otherUpdates: [Api.Update] + public var chats: [Api.Chat] + public var users: [Api.User] + public var state: Api.updates.State + public init(newMessages: [Api.Message], newEncryptedMessages: [Api.EncryptedMessage], otherUpdates: [Api.Update], chats: [Api.Chat], users: [Api.User], state: Api.updates.State) { + self.newMessages = newMessages + self.newEncryptedMessages = newEncryptedMessages + self.otherUpdates = otherUpdates + self.chats = chats + self.users = users + self.state = state + } + } + public class Cons_differenceEmpty { + public var date: Int32 + public var seq: Int32 + public init(date: Int32, seq: Int32) { + self.date = date + self.seq = seq + } + } + public class Cons_differenceSlice { + public var newMessages: [Api.Message] + public var newEncryptedMessages: [Api.EncryptedMessage] + public var otherUpdates: [Api.Update] + public var chats: [Api.Chat] + public var users: [Api.User] + public var intermediateState: Api.updates.State + public init(newMessages: [Api.Message], newEncryptedMessages: [Api.EncryptedMessage], otherUpdates: [Api.Update], chats: [Api.Chat], users: [Api.User], intermediateState: Api.updates.State) { + self.newMessages = newMessages + self.newEncryptedMessages = newEncryptedMessages + self.otherUpdates = otherUpdates + self.chats = chats + self.users = users + self.intermediateState = intermediateState + } + } + public class Cons_differenceTooLong { + public var pts: Int32 + public init(pts: Int32) { + self.pts = pts + } + } + case difference(Cons_difference) + case differenceEmpty(Cons_differenceEmpty) + case differenceSlice(Cons_differenceSlice) + case differenceTooLong(Cons_differenceTooLong) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .difference(let _data): + if boxed { + buffer.appendInt32(16030880) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.newMessages.count)) + for item in _data.newMessages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.newEncryptedMessages.count)) + for item in _data.newEncryptedMessages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.otherUpdates.count)) + for item in _data.otherUpdates { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + _data.state.serialize(buffer, true) + break + case .differenceEmpty(let _data): + if boxed { + buffer.appendInt32(1567990072) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt32(_data.seq, buffer: buffer, boxed: false) + break + case .differenceSlice(let _data): + if boxed { + buffer.appendInt32(-1459938943) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.newMessages.count)) + for item in _data.newMessages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.newEncryptedMessages.count)) + for item in _data.newEncryptedMessages { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.otherUpdates.count)) + for item in _data.otherUpdates { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + _data.intermediateState.serialize(buffer, true) + break + case .differenceTooLong(let _data): + if boxed { + buffer.appendInt32(1258196845) + } + serializeInt32(_data.pts, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .difference(let _data): + return ("difference", [("newMessages", _data.newMessages as Any), ("newEncryptedMessages", _data.newEncryptedMessages as Any), ("otherUpdates", _data.otherUpdates as Any), ("chats", _data.chats as Any), ("users", _data.users as Any), ("state", _data.state as Any)]) + case .differenceEmpty(let _data): + return ("differenceEmpty", [("date", _data.date as Any), ("seq", _data.seq as Any)]) + case .differenceSlice(let _data): + return ("differenceSlice", [("newMessages", _data.newMessages as Any), ("newEncryptedMessages", _data.newEncryptedMessages as Any), ("otherUpdates", _data.otherUpdates as Any), ("chats", _data.chats as Any), ("users", _data.users as Any), ("intermediateState", _data.intermediateState as Any)]) + case .differenceTooLong(let _data): + return ("differenceTooLong", [("pts", _data.pts as Any)]) + } + } + + public static func parse_difference(_ reader: BufferReader) -> Difference? { + var _1: [Api.Message]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) + } + var _2: [Api.EncryptedMessage]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.EncryptedMessage.self) + } + var _3: [Api.Update]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Update.self) + } + var _4: [Api.Chat]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _5: [Api.User]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + var _6: Api.updates.State? + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.updates.State + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.updates.Difference.difference(Cons_difference(newMessages: _1!, newEncryptedMessages: _2!, otherUpdates: _3!, chats: _4!, users: _5!, state: _6!)) + } + else { + return nil + } + } + public static func parse_differenceEmpty(_ reader: BufferReader) -> Difference? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.updates.Difference.differenceEmpty(Cons_differenceEmpty(date: _1!, seq: _2!)) + } + else { + return nil + } + } + public static func parse_differenceSlice(_ reader: BufferReader) -> Difference? { + var _1: [Api.Message]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Message.self) + } + var _2: [Api.EncryptedMessage]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.EncryptedMessage.self) + } + var _3: [Api.Update]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Update.self) + } + var _4: [Api.Chat]? + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _5: [Api.User]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + var _6: Api.updates.State? + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.updates.State + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + let _c6 = _6 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.updates.Difference.differenceSlice(Cons_differenceSlice(newMessages: _1!, newEncryptedMessages: _2!, otherUpdates: _3!, chats: _4!, users: _5!, intermediateState: _6!)) + } + else { + return nil + } + } + public static func parse_differenceTooLong(_ reader: BufferReader) -> Difference? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.updates.Difference.differenceTooLong(Cons_differenceTooLong(pts: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.updates { + enum State: TypeConstructorDescription { + public class Cons_state { + public var pts: Int32 + public var qts: Int32 + public var date: Int32 + public var seq: Int32 + public var unreadCount: Int32 + public init(pts: Int32, qts: Int32, date: Int32, seq: Int32, unreadCount: Int32) { + self.pts = pts + self.qts = qts + self.date = date + self.seq = seq + self.unreadCount = unreadCount + } + } + case state(Cons_state) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .state(let _data): + if boxed { + buffer.appendInt32(-1519637954) + } + serializeInt32(_data.pts, buffer: buffer, boxed: false) + serializeInt32(_data.qts, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt32(_data.seq, buffer: buffer, boxed: false) + serializeInt32(_data.unreadCount, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .state(let _data): + return ("state", [("pts", _data.pts as Any), ("qts", _data.qts as Any), ("date", _data.date as Any), ("seq", _data.seq as Any), ("unreadCount", _data.unreadCount as Any)]) + } + } + + public static func parse_state(_ reader: BufferReader) -> State? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Int32? + _2 = reader.readInt32() + var _3: Int32? + _3 = reader.readInt32() + var _4: Int32? + _4 = reader.readInt32() + var _5: Int32? + _5 = reader.readInt32() + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.updates.State.state(Cons_state(pts: _1!, qts: _2!, date: _3!, seq: _4!, unreadCount: _5!)) + } + else { + return nil + } + } + } +} +public extension Api.upload { + enum CdnFile: TypeConstructorDescription { + public class Cons_cdnFile { + public var bytes: Buffer + public init(bytes: Buffer) { + self.bytes = bytes + } + } + public class Cons_cdnFileReuploadNeeded { + public var requestToken: Buffer + public init(requestToken: Buffer) { + self.requestToken = requestToken + } + } + case cdnFile(Cons_cdnFile) + case cdnFileReuploadNeeded(Cons_cdnFileReuploadNeeded) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .cdnFile(let _data): + if boxed { + buffer.appendInt32(-1449145777) + } + serializeBytes(_data.bytes, buffer: buffer, boxed: false) + break + case .cdnFileReuploadNeeded(let _data): + if boxed { + buffer.appendInt32(-290921362) + } + serializeBytes(_data.requestToken, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .cdnFile(let _data): + return ("cdnFile", [("bytes", _data.bytes as Any)]) + case .cdnFileReuploadNeeded(let _data): + return ("cdnFileReuploadNeeded", [("requestToken", _data.requestToken as Any)]) + } + } + + public static func parse_cdnFile(_ reader: BufferReader) -> CdnFile? { + var _1: Buffer? + _1 = parseBytes(reader) + let _c1 = _1 != nil + if _c1 { + return Api.upload.CdnFile.cdnFile(Cons_cdnFile(bytes: _1!)) + } + else { + return nil + } + } + public static func parse_cdnFileReuploadNeeded(_ reader: BufferReader) -> CdnFile? { + var _1: Buffer? + _1 = parseBytes(reader) + let _c1 = _1 != nil + if _c1 { + return Api.upload.CdnFile.cdnFileReuploadNeeded(Cons_cdnFileReuploadNeeded(requestToken: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.upload { + enum File: TypeConstructorDescription { + public class Cons_file { + public var type: Api.storage.FileType + public var mtime: Int32 + public var bytes: Buffer + public init(type: Api.storage.FileType, mtime: Int32, bytes: Buffer) { + self.type = type + self.mtime = mtime + self.bytes = bytes + } + } + public class Cons_fileCdnRedirect { + public var dcId: Int32 + public var fileToken: Buffer + public var encryptionKey: Buffer + public var encryptionIv: Buffer + public var fileHashes: [Api.FileHash] + public init(dcId: Int32, fileToken: Buffer, encryptionKey: Buffer, encryptionIv: Buffer, fileHashes: [Api.FileHash]) { + self.dcId = dcId + self.fileToken = fileToken + self.encryptionKey = encryptionKey + self.encryptionIv = encryptionIv + self.fileHashes = fileHashes + } + } + case file(Cons_file) + case fileCdnRedirect(Cons_fileCdnRedirect) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .file(let _data): + if boxed { + buffer.appendInt32(157948117) + } + _data.type.serialize(buffer, true) + serializeInt32(_data.mtime, buffer: buffer, boxed: false) + serializeBytes(_data.bytes, buffer: buffer, boxed: false) + break + case .fileCdnRedirect(let _data): + if boxed { + buffer.appendInt32(-242427324) + } + serializeInt32(_data.dcId, buffer: buffer, boxed: false) + serializeBytes(_data.fileToken, buffer: buffer, boxed: false) + serializeBytes(_data.encryptionKey, buffer: buffer, boxed: false) + serializeBytes(_data.encryptionIv, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.fileHashes.count)) + for item in _data.fileHashes { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .file(let _data): + return ("file", [("type", _data.type as Any), ("mtime", _data.mtime as Any), ("bytes", _data.bytes as Any)]) + case .fileCdnRedirect(let _data): + return ("fileCdnRedirect", [("dcId", _data.dcId as Any), ("fileToken", _data.fileToken as Any), ("encryptionKey", _data.encryptionKey as Any), ("encryptionIv", _data.encryptionIv as Any), ("fileHashes", _data.fileHashes as Any)]) + } + } + + public static func parse_file(_ reader: BufferReader) -> File? { + var _1: Api.storage.FileType? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.storage.FileType + } + var _2: Int32? + _2 = reader.readInt32() + var _3: Buffer? + _3 = parseBytes(reader) + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.upload.File.file(Cons_file(type: _1!, mtime: _2!, bytes: _3!)) + } + else { + return nil + } + } + public static func parse_fileCdnRedirect(_ reader: BufferReader) -> File? { + var _1: Int32? + _1 = reader.readInt32() + var _2: Buffer? + _2 = parseBytes(reader) + var _3: Buffer? + _3 = parseBytes(reader) + var _4: Buffer? + _4 = parseBytes(reader) + var _5: [Api.FileHash]? + if let _ = reader.readInt32() { + _5 = Api.parseVector(reader, elementSignature: 0, elementType: Api.FileHash.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.upload.File.fileCdnRedirect(Cons_fileCdnRedirect(dcId: _1!, fileToken: _2!, encryptionKey: _3!, encryptionIv: _4!, fileHashes: _5!)) + } + else { + return nil + } + } + } +} +public extension Api.upload { + enum WebFile: TypeConstructorDescription { + public class Cons_webFile { + public var size: Int32 + public var mimeType: String + public var fileType: Api.storage.FileType + public var mtime: Int32 + public var bytes: Buffer + public init(size: Int32, mimeType: String, fileType: Api.storage.FileType, mtime: Int32, bytes: Buffer) { + self.size = size + self.mimeType = mimeType + self.fileType = fileType + self.mtime = mtime + self.bytes = bytes + } + } + case webFile(Cons_webFile) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .webFile(let _data): + if boxed { + buffer.appendInt32(568808380) + } + serializeInt32(_data.size, buffer: buffer, boxed: false) + serializeString(_data.mimeType, buffer: buffer, boxed: false) + _data.fileType.serialize(buffer, true) + serializeInt32(_data.mtime, buffer: buffer, boxed: false) + serializeBytes(_data.bytes, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .webFile(let _data): + return ("webFile", [("size", _data.size as Any), ("mimeType", _data.mimeType as Any), ("fileType", _data.fileType as Any), ("mtime", _data.mtime as Any), ("bytes", _data.bytes as Any)]) + } + } + + public static func parse_webFile(_ reader: BufferReader) -> WebFile? { + var _1: Int32? + _1 = reader.readInt32() + var _2: String? + _2 = parseString(reader) + var _3: Api.storage.FileType? + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.storage.FileType + } + var _4: Int32? + _4 = reader.readInt32() + var _5: Buffer? + _5 = parseBytes(reader) + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + let _c4 = _4 != nil + let _c5 = _5 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.upload.WebFile.webFile(Cons_webFile(size: _1!, mimeType: _2!, fileType: _3!, mtime: _4!, bytes: _5!)) + } + else { + return nil + } + } + } +} +public extension Api.users { + enum SavedMusic: TypeConstructorDescription { + public class Cons_savedMusic { + public var count: Int32 + public var documents: [Api.Document] + public init(count: Int32, documents: [Api.Document]) { + self.count = count + self.documents = documents + } + } + public class Cons_savedMusicNotModified { + public var count: Int32 + public init(count: Int32) { + self.count = count + } + } + case savedMusic(Cons_savedMusic) + case savedMusicNotModified(Cons_savedMusicNotModified) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .savedMusic(let _data): + if boxed { + buffer.appendInt32(883094167) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.documents.count)) + for item in _data.documents { + item.serialize(buffer, true) + } + break + case .savedMusicNotModified(let _data): + if boxed { + buffer.appendInt32(-477656412) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .savedMusic(let _data): + return ("savedMusic", [("count", _data.count as Any), ("documents", _data.documents as Any)]) + case .savedMusicNotModified(let _data): + return ("savedMusicNotModified", [("count", _data.count as Any)]) + } + } + + public static func parse_savedMusic(_ reader: BufferReader) -> SavedMusic? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.Document]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.users.SavedMusic.savedMusic(Cons_savedMusic(count: _1!, documents: _2!)) + } + else { + return nil + } + } + public static func parse_savedMusicNotModified(_ reader: BufferReader) -> SavedMusic? { + var _1: Int32? + _1 = reader.readInt32() + let _c1 = _1 != nil + if _c1 { + return Api.users.SavedMusic.savedMusicNotModified(Cons_savedMusicNotModified(count: _1!)) + } + else { + return nil + } + } + } +} +public extension Api.users { + enum UserFull: TypeConstructorDescription { + public class Cons_userFull { + public var fullUser: Api.UserFull + public var chats: [Api.Chat] + public var users: [Api.User] + public init(fullUser: Api.UserFull, chats: [Api.Chat], users: [Api.User]) { + self.fullUser = fullUser + self.chats = chats + self.users = users + } + } + case userFull(Cons_userFull) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .userFull(let _data): + if boxed { + buffer.appendInt32(997004590) + } + _data.fullUser.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.chats.count)) + for item in _data.chats { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .userFull(let _data): + return ("userFull", [("fullUser", _data.fullUser as Any), ("chats", _data.chats as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_userFull(_ reader: BufferReader) -> UserFull? { + var _1: Api.UserFull? + if let signature = reader.readInt32() { + _1 = Api.parse(reader, signature: signature) as? Api.UserFull + } + var _2: [Api.Chat]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Chat.self) + } + var _3: [Api.User]? + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + let _c3 = _3 != nil + if _c1 && _c2 && _c3 { + return Api.users.UserFull.userFull(Cons_userFull(fullUser: _1!, chats: _2!, users: _3!)) + } + else { + return nil + } + } + } +} +public extension Api.users { + enum Users: TypeConstructorDescription { + public class Cons_users { + public var users: [Api.User] + public init(users: [Api.User]) { + self.users = users + } + } + public class Cons_usersSlice { + public var count: Int32 + public var users: [Api.User] + public init(count: Int32, users: [Api.User]) { + self.count = count + self.users = users + } + } + case users(Cons_users) + case usersSlice(Cons_usersSlice) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .users(let _data): + if boxed { + buffer.appendInt32(1658259128) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + case .usersSlice(let _data): + if boxed { + buffer.appendInt32(828000628) + } + serializeInt32(_data.count, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users.count)) + for item in _data.users { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .users(let _data): + return ("users", [("users", _data.users as Any)]) + case .usersSlice(let _data): + return ("usersSlice", [("count", _data.count as Any), ("users", _data.users as Any)]) + } + } + + public static func parse_users(_ reader: BufferReader) -> Users? { + var _1: [Api.User]? + if let _ = reader.readInt32() { + _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + if _c1 { + return Api.users.Users.users(Cons_users(users: _1!)) + } + else { + return nil + } + } + public static func parse_usersSlice(_ reader: BufferReader) -> Users? { + var _1: Int32? + _1 = reader.readInt32() + var _2: [Api.User]? + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + let _c1 = _1 != nil + let _c2 = _2 != nil + if _c1 && _c2 { + return Api.users.Users.usersSlice(Cons_usersSlice(count: _1!, users: _2!)) + } + else { + return nil + } + } + } } diff --git a/submodules/TelegramApi/Sources/Api4.swift b/submodules/TelegramApi/Sources/Api4.swift index 33c86e99..395f2822 100644 --- a/submodules/TelegramApi/Sources/Api4.swift +++ b/submodules/TelegramApi/Sources/Api4.swift @@ -1,67 +1,83 @@ public extension Api { enum ChannelAdminLogEventsFilter: TypeConstructorDescription { - case channelAdminLogEventsFilter(flags: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .channelAdminLogEventsFilter(let flags): - if boxed { - buffer.appendInt32(-368018716) - } - serializeInt32(flags, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .channelAdminLogEventsFilter(let flags): - return ("channelAdminLogEventsFilter", [("flags", flags as Any)]) - } - } - + public class Cons_channelAdminLogEventsFilter { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } + case channelAdminLogEventsFilter(Cons_channelAdminLogEventsFilter) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .channelAdminLogEventsFilter(let _data): + if boxed { + buffer.appendInt32(-368018716) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .channelAdminLogEventsFilter(let _data): + return ("channelAdminLogEventsFilter", [("flags", _data.flags as Any)]) + } + } + public static func parse_channelAdminLogEventsFilter(_ reader: BufferReader) -> ChannelAdminLogEventsFilter? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelAdminLogEventsFilter.channelAdminLogEventsFilter(flags: _1!) + if _c1 { + return Api.ChannelAdminLogEventsFilter.channelAdminLogEventsFilter(Cons_channelAdminLogEventsFilter(flags: _1!)) + } + else { + return nil + } } - } } public extension Api { enum ChannelLocation: TypeConstructorDescription { - case channelLocation(geoPoint: Api.GeoPoint, address: String) + public class Cons_channelLocation { + public var geoPoint: Api.GeoPoint + public var address: String + public init(geoPoint: Api.GeoPoint, address: String) { + self.geoPoint = geoPoint + self.address = address + } + } + case channelLocation(Cons_channelLocation) case channelLocationEmpty - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .channelLocation(let geoPoint, let address): - if boxed { - buffer.appendInt32(547062491) - } - geoPoint.serialize(buffer, true) - serializeString(address, buffer: buffer, boxed: false) - break - case .channelLocationEmpty: - if boxed { - buffer.appendInt32(-1078612597) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .channelLocation(let geoPoint, let address): - return ("channelLocation", [("geoPoint", geoPoint as Any), ("address", address as Any)]) - case .channelLocationEmpty: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .channelLocation(let _data): + if boxed { + buffer.appendInt32(547062491) + } + _data.geoPoint.serialize(buffer, true) + serializeString(_data.address, buffer: buffer, boxed: false) + break + case .channelLocationEmpty: + if boxed { + buffer.appendInt32(-1078612597) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .channelLocation(let _data): + return ("channelLocation", [("geoPoint", _data.geoPoint as Any), ("address", _data.address as Any)]) + case .channelLocationEmpty: return ("channelLocationEmpty", []) - } - } - + } + } + public static func parse_channelLocation(_ reader: BufferReader) -> ChannelLocation? { var _1: Api.GeoPoint? if let signature = reader.readInt32() { @@ -71,52 +87,61 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelLocation.channelLocation(geoPoint: _1!, address: _2!) + if _c1 && _c2 { + return Api.ChannelLocation.channelLocation(Cons_channelLocation(geoPoint: _1!, address: _2!)) + } + else { + return nil + } } public static func parse_channelLocationEmpty(_ reader: BufferReader) -> ChannelLocation? { return Api.ChannelLocation.channelLocationEmpty } - } } public extension Api { enum ChannelMessagesFilter: TypeConstructorDescription { - case channelMessagesFilter(flags: Int32, ranges: [Api.MessageRange]) + public class Cons_channelMessagesFilter { + public var flags: Int32 + public var ranges: [Api.MessageRange] + public init(flags: Int32, ranges: [Api.MessageRange]) { + self.flags = flags + self.ranges = ranges + } + } + case channelMessagesFilter(Cons_channelMessagesFilter) case channelMessagesFilterEmpty - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .channelMessagesFilter(let flags, let ranges): - if boxed { - buffer.appendInt32(-847783593) - } - serializeInt32(flags, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(ranges.count)) - for item in ranges { - item.serialize(buffer, true) - } - break - case .channelMessagesFilterEmpty: - if boxed { - buffer.appendInt32(-1798033689) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .channelMessagesFilter(let flags, let ranges): - return ("channelMessagesFilter", [("flags", flags as Any), ("ranges", ranges as Any)]) - case .channelMessagesFilterEmpty: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .channelMessagesFilter(let _data): + if boxed { + buffer.appendInt32(-847783593) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.ranges.count)) + for item in _data.ranges { + item.serialize(buffer, true) + } + break + case .channelMessagesFilterEmpty: + if boxed { + buffer.appendInt32(-1798033689) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .channelMessagesFilter(let _data): + return ("channelMessagesFilter", [("flags", _data.flags as Any), ("ranges", _data.ranges as Any)]) + case .channelMessagesFilterEmpty: return ("channelMessagesFilterEmpty", []) - } - } - + } + } + public static func parse_channelMessagesFilter(_ reader: BufferReader) -> ChannelMessagesFilter? { var _1: Int32? _1 = reader.readInt32() @@ -126,103 +151,191 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChannelMessagesFilter.channelMessagesFilter(flags: _1!, ranges: _2!) + if _c1 && _c2 { + return Api.ChannelMessagesFilter.channelMessagesFilter(Cons_channelMessagesFilter(flags: _1!, ranges: _2!)) + } + else { + return nil + } } public static func parse_channelMessagesFilterEmpty(_ reader: BufferReader) -> ChannelMessagesFilter? { return Api.ChannelMessagesFilter.channelMessagesFilterEmpty } - } } public extension Api { enum ChannelParticipant: TypeConstructorDescription { - case channelParticipant(flags: Int32, userId: Int64, date: Int32, subscriptionUntilDate: Int32?) - case channelParticipantAdmin(flags: Int32, userId: Int64, inviterId: Int64?, promotedBy: Int64, date: Int32, adminRights: Api.ChatAdminRights, rank: String?) - case channelParticipantBanned(flags: Int32, peer: Api.Peer, kickedBy: Int64, date: Int32, bannedRights: Api.ChatBannedRights) - case channelParticipantCreator(flags: Int32, userId: Int64, adminRights: Api.ChatAdminRights, rank: String?) - case channelParticipantLeft(peer: Api.Peer) - case channelParticipantSelf(flags: Int32, userId: Int64, inviterId: Int64, date: Int32, subscriptionUntilDate: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .channelParticipant(let flags, let userId, let date, let subscriptionUntilDate): - if boxed { - buffer.appendInt32(-885426663) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(subscriptionUntilDate!, buffer: buffer, boxed: false)} - break - case .channelParticipantAdmin(let flags, let userId, let inviterId, let promotedBy, let date, let adminRights, let rank): - if boxed { - buffer.appendInt32(885242707) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt64(inviterId!, buffer: buffer, boxed: false)} - serializeInt64(promotedBy, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - adminRights.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {serializeString(rank!, buffer: buffer, boxed: false)} - break - case .channelParticipantBanned(let flags, let peer, let kickedBy, let date, let bannedRights): - if boxed { - buffer.appendInt32(1844969806) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt64(kickedBy, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - bannedRights.serialize(buffer, true) - break - case .channelParticipantCreator(let flags, let userId, let adminRights, let rank): - if boxed { - buffer.appendInt32(803602899) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - adminRights.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeString(rank!, buffer: buffer, boxed: false)} - break - case .channelParticipantLeft(let peer): - if boxed { - buffer.appendInt32(453242886) - } - peer.serialize(buffer, true) - break - case .channelParticipantSelf(let flags, let userId, let inviterId, let date, let subscriptionUntilDate): - if boxed { - buffer.appendInt32(1331723247) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt64(inviterId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(subscriptionUntilDate!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .channelParticipant(let flags, let userId, let date, let subscriptionUntilDate): - return ("channelParticipant", [("flags", flags as Any), ("userId", userId as Any), ("date", date as Any), ("subscriptionUntilDate", subscriptionUntilDate as Any)]) - case .channelParticipantAdmin(let flags, let userId, let inviterId, let promotedBy, let date, let adminRights, let rank): - return ("channelParticipantAdmin", [("flags", flags as Any), ("userId", userId as Any), ("inviterId", inviterId as Any), ("promotedBy", promotedBy as Any), ("date", date as Any), ("adminRights", adminRights as Any), ("rank", rank as Any)]) - case .channelParticipantBanned(let flags, let peer, let kickedBy, let date, let bannedRights): - return ("channelParticipantBanned", [("flags", flags as Any), ("peer", peer as Any), ("kickedBy", kickedBy as Any), ("date", date as Any), ("bannedRights", bannedRights as Any)]) - case .channelParticipantCreator(let flags, let userId, let adminRights, let rank): - return ("channelParticipantCreator", [("flags", flags as Any), ("userId", userId as Any), ("adminRights", adminRights as Any), ("rank", rank as Any)]) - case .channelParticipantLeft(let peer): - return ("channelParticipantLeft", [("peer", peer as Any)]) - case .channelParticipantSelf(let flags, let userId, let inviterId, let date, let subscriptionUntilDate): - return ("channelParticipantSelf", [("flags", flags as Any), ("userId", userId as Any), ("inviterId", inviterId as Any), ("date", date as Any), ("subscriptionUntilDate", subscriptionUntilDate as Any)]) - } - } - + public class Cons_channelParticipant { + public var flags: Int32 + public var userId: Int64 + public var date: Int32 + public var subscriptionUntilDate: Int32? + public init(flags: Int32, userId: Int64, date: Int32, subscriptionUntilDate: Int32?) { + self.flags = flags + self.userId = userId + self.date = date + self.subscriptionUntilDate = subscriptionUntilDate + } + } + public class Cons_channelParticipantAdmin { + public var flags: Int32 + public var userId: Int64 + public var inviterId: Int64? + public var promotedBy: Int64 + public var date: Int32 + public var adminRights: Api.ChatAdminRights + public var rank: String? + public init(flags: Int32, userId: Int64, inviterId: Int64?, promotedBy: Int64, date: Int32, adminRights: Api.ChatAdminRights, rank: String?) { + self.flags = flags + self.userId = userId + self.inviterId = inviterId + self.promotedBy = promotedBy + self.date = date + self.adminRights = adminRights + self.rank = rank + } + } + public class Cons_channelParticipantBanned { + public var flags: Int32 + public var peer: Api.Peer + public var kickedBy: Int64 + public var date: Int32 + public var bannedRights: Api.ChatBannedRights + public init(flags: Int32, peer: Api.Peer, kickedBy: Int64, date: Int32, bannedRights: Api.ChatBannedRights) { + self.flags = flags + self.peer = peer + self.kickedBy = kickedBy + self.date = date + self.bannedRights = bannedRights + } + } + public class Cons_channelParticipantCreator { + public var flags: Int32 + public var userId: Int64 + public var adminRights: Api.ChatAdminRights + public var rank: String? + public init(flags: Int32, userId: Int64, adminRights: Api.ChatAdminRights, rank: String?) { + self.flags = flags + self.userId = userId + self.adminRights = adminRights + self.rank = rank + } + } + public class Cons_channelParticipantLeft { + public var peer: Api.Peer + public init(peer: Api.Peer) { + self.peer = peer + } + } + public class Cons_channelParticipantSelf { + public var flags: Int32 + public var userId: Int64 + public var inviterId: Int64 + public var date: Int32 + public var subscriptionUntilDate: Int32? + public init(flags: Int32, userId: Int64, inviterId: Int64, date: Int32, subscriptionUntilDate: Int32?) { + self.flags = flags + self.userId = userId + self.inviterId = inviterId + self.date = date + self.subscriptionUntilDate = subscriptionUntilDate + } + } + case channelParticipant(Cons_channelParticipant) + case channelParticipantAdmin(Cons_channelParticipantAdmin) + case channelParticipantBanned(Cons_channelParticipantBanned) + case channelParticipantCreator(Cons_channelParticipantCreator) + case channelParticipantLeft(Cons_channelParticipantLeft) + case channelParticipantSelf(Cons_channelParticipantSelf) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .channelParticipant(let _data): + if boxed { + buffer.appendInt32(-885426663) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.subscriptionUntilDate!, buffer: buffer, boxed: false) + } + break + case .channelParticipantAdmin(let _data): + if boxed { + buffer.appendInt32(885242707) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt64(_data.inviterId!, buffer: buffer, boxed: false) + } + serializeInt64(_data.promotedBy, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + _data.adminRights.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.rank!, buffer: buffer, boxed: false) + } + break + case .channelParticipantBanned(let _data): + if boxed { + buffer.appendInt32(1844969806) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeInt64(_data.kickedBy, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + _data.bannedRights.serialize(buffer, true) + break + case .channelParticipantCreator(let _data): + if boxed { + buffer.appendInt32(803602899) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + _data.adminRights.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.rank!, buffer: buffer, boxed: false) + } + break + case .channelParticipantLeft(let _data): + if boxed { + buffer.appendInt32(453242886) + } + _data.peer.serialize(buffer, true) + break + case .channelParticipantSelf(let _data): + if boxed { + buffer.appendInt32(1331723247) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt64(_data.inviterId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.subscriptionUntilDate!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .channelParticipant(let _data): + return ("channelParticipant", [("flags", _data.flags as Any), ("userId", _data.userId as Any), ("date", _data.date as Any), ("subscriptionUntilDate", _data.subscriptionUntilDate as Any)]) + case .channelParticipantAdmin(let _data): + return ("channelParticipantAdmin", [("flags", _data.flags as Any), ("userId", _data.userId as Any), ("inviterId", _data.inviterId as Any), ("promotedBy", _data.promotedBy as Any), ("date", _data.date as Any), ("adminRights", _data.adminRights as Any), ("rank", _data.rank as Any)]) + case .channelParticipantBanned(let _data): + return ("channelParticipantBanned", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("kickedBy", _data.kickedBy as Any), ("date", _data.date as Any), ("bannedRights", _data.bannedRights as Any)]) + case .channelParticipantCreator(let _data): + return ("channelParticipantCreator", [("flags", _data.flags as Any), ("userId", _data.userId as Any), ("adminRights", _data.adminRights as Any), ("rank", _data.rank as Any)]) + case .channelParticipantLeft(let _data): + return ("channelParticipantLeft", [("peer", _data.peer as Any)]) + case .channelParticipantSelf(let _data): + return ("channelParticipantSelf", [("flags", _data.flags as Any), ("userId", _data.userId as Any), ("inviterId", _data.inviterId as Any), ("date", _data.date as Any), ("subscriptionUntilDate", _data.subscriptionUntilDate as Any)]) + } + } + public static func parse_channelParticipant(_ reader: BufferReader) -> ChannelParticipant? { var _1: Int32? _1 = reader.readInt32() @@ -231,16 +344,19 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.ChannelParticipant.channelParticipant(flags: _1!, userId: _2!, date: _3!, subscriptionUntilDate: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.ChannelParticipant.channelParticipant(Cons_channelParticipant(flags: _1!, userId: _2!, date: _3!, subscriptionUntilDate: _4)) + } + else { + return nil + } } public static func parse_channelParticipantAdmin(_ reader: BufferReader) -> ChannelParticipant? { var _1: Int32? @@ -248,7 +364,9 @@ public extension Api { var _2: Int64? _2 = reader.readInt64() var _3: Int64? - if Int(_1!) & Int(1 << 1) != 0 {_3 = reader.readInt64() } + if Int(_1!) & Int(1 << 1) != 0 { + _3 = reader.readInt64() + } var _4: Int64? _4 = reader.readInt64() var _5: Int32? @@ -258,7 +376,9 @@ public extension Api { _6 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights } var _7: String? - if Int(_1!) & Int(1 << 2) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _7 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil @@ -266,14 +386,12 @@ public extension Api { let _c5 = _5 != nil let _c6 = _6 != nil let _c7 = (Int(_1!) & Int(1 << 2) == 0) || _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.ChannelParticipant.channelParticipantAdmin(flags: _1!, userId: _2!, inviterId: _3, promotedBy: _4!, date: _5!, adminRights: _6!, rank: _7) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.ChannelParticipant.channelParticipantAdmin(Cons_channelParticipantAdmin(flags: _1!, userId: _2!, inviterId: _3, promotedBy: _4!, date: _5!, adminRights: _6!, rank: _7)) + } + else { + return nil + } } public static func parse_channelParticipantBanned(_ reader: BufferReader) -> ChannelParticipant? { var _1: Int32? @@ -295,12 +413,12 @@ public extension Api { let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.ChannelParticipant.channelParticipantBanned(flags: _1!, peer: _2!, kickedBy: _3!, date: _4!, bannedRights: _5!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.ChannelParticipant.channelParticipantBanned(Cons_channelParticipantBanned(flags: _1!, peer: _2!, kickedBy: _3!, date: _4!, bannedRights: _5!)) + } + else { + return nil + } } public static func parse_channelParticipantCreator(_ reader: BufferReader) -> ChannelParticipant? { var _1: Int32? @@ -312,16 +430,19 @@ public extension Api { _3 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights } var _4: String? - if Int(_1!) & Int(1 << 0) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _4 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.ChannelParticipant.channelParticipantCreator(flags: _1!, userId: _2!, adminRights: _3!, rank: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.ChannelParticipant.channelParticipantCreator(Cons_channelParticipantCreator(flags: _1!, userId: _2!, adminRights: _3!, rank: _4)) + } + else { + return nil + } } public static func parse_channelParticipantLeft(_ reader: BufferReader) -> ChannelParticipant? { var _1: Api.Peer? @@ -329,8 +450,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Peer } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelParticipant.channelParticipantLeft(peer: _1!) + if _c1 { + return Api.ChannelParticipant.channelParticipantLeft(Cons_channelParticipantLeft(peer: _1!)) + } + else { + return nil + } } public static func parse_channelParticipantSelf(_ reader: BufferReader) -> ChannelParticipant? { var _1: Int32? @@ -342,109 +467,145 @@ public extension Api { var _4: Int32? _4 = reader.readInt32() var _5: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _5 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.ChannelParticipant.channelParticipantSelf(flags: _1!, userId: _2!, inviterId: _3!, date: _4!, subscriptionUntilDate: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.ChannelParticipant.channelParticipantSelf(Cons_channelParticipantSelf(flags: _1!, userId: _2!, inviterId: _3!, date: _4!, subscriptionUntilDate: _5)) + } + else { + return nil + } } - } } public extension Api { enum ChannelParticipantsFilter: TypeConstructorDescription { + public class Cons_channelParticipantsBanned { + public var q: String + public init(q: String) { + self.q = q + } + } + public class Cons_channelParticipantsContacts { + public var q: String + public init(q: String) { + self.q = q + } + } + public class Cons_channelParticipantsKicked { + public var q: String + public init(q: String) { + self.q = q + } + } + public class Cons_channelParticipantsMentions { + public var flags: Int32 + public var q: String? + public var topMsgId: Int32? + public init(flags: Int32, q: String?, topMsgId: Int32?) { + self.flags = flags + self.q = q + self.topMsgId = topMsgId + } + } + public class Cons_channelParticipantsSearch { + public var q: String + public init(q: String) { + self.q = q + } + } case channelParticipantsAdmins - case channelParticipantsBanned(q: String) + case channelParticipantsBanned(Cons_channelParticipantsBanned) case channelParticipantsBots - case channelParticipantsContacts(q: String) - case channelParticipantsKicked(q: String) - case channelParticipantsMentions(flags: Int32, q: String?, topMsgId: Int32?) + case channelParticipantsContacts(Cons_channelParticipantsContacts) + case channelParticipantsKicked(Cons_channelParticipantsKicked) + case channelParticipantsMentions(Cons_channelParticipantsMentions) case channelParticipantsRecent - case channelParticipantsSearch(q: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .channelParticipantsAdmins: - if boxed { - buffer.appendInt32(-1268741783) - } - - break - case .channelParticipantsBanned(let q): - if boxed { - buffer.appendInt32(338142689) - } - serializeString(q, buffer: buffer, boxed: false) - break - case .channelParticipantsBots: - if boxed { - buffer.appendInt32(-1328445861) - } - - break - case .channelParticipantsContacts(let q): - if boxed { - buffer.appendInt32(-1150621555) - } - serializeString(q, buffer: buffer, boxed: false) - break - case .channelParticipantsKicked(let q): - if boxed { - buffer.appendInt32(-1548400251) - } - serializeString(q, buffer: buffer, boxed: false) - break - case .channelParticipantsMentions(let flags, let q, let topMsgId): - if boxed { - buffer.appendInt32(-531931925) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(q!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(topMsgId!, buffer: buffer, boxed: false)} - break - case .channelParticipantsRecent: - if boxed { - buffer.appendInt32(-566281095) - } - - break - case .channelParticipantsSearch(let q): - if boxed { - buffer.appendInt32(106343499) - } - serializeString(q, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .channelParticipantsAdmins: + case channelParticipantsSearch(Cons_channelParticipantsSearch) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .channelParticipantsAdmins: + if boxed { + buffer.appendInt32(-1268741783) + } + break + case .channelParticipantsBanned(let _data): + if boxed { + buffer.appendInt32(338142689) + } + serializeString(_data.q, buffer: buffer, boxed: false) + break + case .channelParticipantsBots: + if boxed { + buffer.appendInt32(-1328445861) + } + break + case .channelParticipantsContacts(let _data): + if boxed { + buffer.appendInt32(-1150621555) + } + serializeString(_data.q, buffer: buffer, boxed: false) + break + case .channelParticipantsKicked(let _data): + if boxed { + buffer.appendInt32(-1548400251) + } + serializeString(_data.q, buffer: buffer, boxed: false) + break + case .channelParticipantsMentions(let _data): + if boxed { + buffer.appendInt32(-531931925) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.q!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.topMsgId!, buffer: buffer, boxed: false) + } + break + case .channelParticipantsRecent: + if boxed { + buffer.appendInt32(-566281095) + } + break + case .channelParticipantsSearch(let _data): + if boxed { + buffer.appendInt32(106343499) + } + serializeString(_data.q, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .channelParticipantsAdmins: return ("channelParticipantsAdmins", []) - case .channelParticipantsBanned(let q): - return ("channelParticipantsBanned", [("q", q as Any)]) - case .channelParticipantsBots: + case .channelParticipantsBanned(let _data): + return ("channelParticipantsBanned", [("q", _data.q as Any)]) + case .channelParticipantsBots: return ("channelParticipantsBots", []) - case .channelParticipantsContacts(let q): - return ("channelParticipantsContacts", [("q", q as Any)]) - case .channelParticipantsKicked(let q): - return ("channelParticipantsKicked", [("q", q as Any)]) - case .channelParticipantsMentions(let flags, let q, let topMsgId): - return ("channelParticipantsMentions", [("flags", flags as Any), ("q", q as Any), ("topMsgId", topMsgId as Any)]) - case .channelParticipantsRecent: + case .channelParticipantsContacts(let _data): + return ("channelParticipantsContacts", [("q", _data.q as Any)]) + case .channelParticipantsKicked(let _data): + return ("channelParticipantsKicked", [("q", _data.q as Any)]) + case .channelParticipantsMentions(let _data): + return ("channelParticipantsMentions", [("flags", _data.flags as Any), ("q", _data.q as Any), ("topMsgId", _data.topMsgId as Any)]) + case .channelParticipantsRecent: return ("channelParticipantsRecent", []) - case .channelParticipantsSearch(let q): - return ("channelParticipantsSearch", [("q", q as Any)]) - } - } - + case .channelParticipantsSearch(let _data): + return ("channelParticipantsSearch", [("q", _data.q as Any)]) + } + } + public static func parse_channelParticipantsAdmins(_ reader: BufferReader) -> ChannelParticipantsFilter? { return Api.ChannelParticipantsFilter.channelParticipantsAdmins } @@ -452,8 +613,12 @@ public extension Api { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelParticipantsFilter.channelParticipantsBanned(q: _1!) + if _c1 { + return Api.ChannelParticipantsFilter.channelParticipantsBanned(Cons_channelParticipantsBanned(q: _1!)) + } + else { + return nil + } } public static func parse_channelParticipantsBots(_ reader: BufferReader) -> ChannelParticipantsFilter? { return Api.ChannelParticipantsFilter.channelParticipantsBots @@ -462,30 +627,44 @@ public extension Api { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelParticipantsFilter.channelParticipantsContacts(q: _1!) + if _c1 { + return Api.ChannelParticipantsFilter.channelParticipantsContacts(Cons_channelParticipantsContacts(q: _1!)) + } + else { + return nil + } } public static func parse_channelParticipantsKicked(_ reader: BufferReader) -> ChannelParticipantsFilter? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelParticipantsFilter.channelParticipantsKicked(q: _1!) + if _c1 { + return Api.ChannelParticipantsFilter.channelParticipantsKicked(Cons_channelParticipantsKicked(q: _1!)) + } + else { + return nil + } } public static func parse_channelParticipantsMentions(_ reader: BufferReader) -> ChannelParticipantsFilter? { var _1: Int32? _1 = reader.readInt32() var _2: String? - if Int(_1!) & Int(1 << 0) != 0 {_2 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = parseString(reader) + } var _3: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _3 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.ChannelParticipantsFilter.channelParticipantsMentions(flags: _1!, q: _2, topMsgId: _3) + if _c1 && _c2 && _c3 { + return Api.ChannelParticipantsFilter.channelParticipantsMentions(Cons_channelParticipantsMentions(flags: _1!, q: _2, topMsgId: _3)) + } + else { + return nil + } } public static func parse_channelParticipantsRecent(_ reader: BufferReader) -> ChannelParticipantsFilter? { return Api.ChannelParticipantsFilter.channelParticipantsRecent @@ -494,114 +673,261 @@ public extension Api { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChannelParticipantsFilter.channelParticipantsSearch(q: _1!) + if _c1 { + return Api.ChannelParticipantsFilter.channelParticipantsSearch(Cons_channelParticipantsSearch(q: _1!)) + } + else { + return nil + } } - } } public extension Api { indirect enum Chat: TypeConstructorDescription { - case channel(flags: Int32, flags2: Int32, id: Int64, accessHash: Int64?, title: String, username: String?, photo: Api.ChatPhoto, date: Int32, restrictionReason: [Api.RestrictionReason]?, adminRights: Api.ChatAdminRights?, bannedRights: Api.ChatBannedRights?, defaultBannedRights: Api.ChatBannedRights?, participantsCount: Int32?, usernames: [Api.Username]?, storiesMaxId: Api.RecentStory?, color: Api.PeerColor?, profileColor: Api.PeerColor?, emojiStatus: Api.EmojiStatus?, level: Int32?, subscriptionUntilDate: Int32?, botVerificationIcon: Int64?, sendPaidMessagesStars: Int64?, linkedMonoforumId: Int64?) - case channelForbidden(flags: Int32, id: Int64, accessHash: Int64, title: String, untilDate: Int32?) - case chat(flags: Int32, id: Int64, title: String, photo: Api.ChatPhoto, participantsCount: Int32, date: Int32, version: Int32, migratedTo: Api.InputChannel?, adminRights: Api.ChatAdminRights?, defaultBannedRights: Api.ChatBannedRights?) - case chatEmpty(id: Int64) - case chatForbidden(id: Int64, title: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .channel(let flags, let flags2, let id, let accessHash, let title, let username, let photo, let date, let restrictionReason, let adminRights, let bannedRights, let defaultBannedRights, let participantsCount, let usernames, let storiesMaxId, let color, let profileColor, let emojiStatus, let level, let subscriptionUntilDate, let botVerificationIcon, let sendPaidMessagesStars, let linkedMonoforumId): - if boxed { - buffer.appendInt32(473084188) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(flags2, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 13) != 0 {serializeInt64(accessHash!, buffer: buffer, boxed: false)} - serializeString(title, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 6) != 0 {serializeString(username!, buffer: buffer, boxed: false)} - photo.serialize(buffer, true) - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 9) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(restrictionReason!.count)) - for item in restrictionReason! { + public class Cons_channel { + public var flags: Int32 + public var flags2: Int32 + public var id: Int64 + public var accessHash: Int64? + public var title: String + public var username: String? + public var photo: Api.ChatPhoto + public var date: Int32 + public var restrictionReason: [Api.RestrictionReason]? + public var adminRights: Api.ChatAdminRights? + public var bannedRights: Api.ChatBannedRights? + public var defaultBannedRights: Api.ChatBannedRights? + public var participantsCount: Int32? + public var usernames: [Api.Username]? + public var storiesMaxId: Api.RecentStory? + public var color: Api.PeerColor? + public var profileColor: Api.PeerColor? + public var emojiStatus: Api.EmojiStatus? + public var level: Int32? + public var subscriptionUntilDate: Int32? + public var botVerificationIcon: Int64? + public var sendPaidMessagesStars: Int64? + public var linkedMonoforumId: Int64? + public init(flags: Int32, flags2: Int32, id: Int64, accessHash: Int64?, title: String, username: String?, photo: Api.ChatPhoto, date: Int32, restrictionReason: [Api.RestrictionReason]?, adminRights: Api.ChatAdminRights?, bannedRights: Api.ChatBannedRights?, defaultBannedRights: Api.ChatBannedRights?, participantsCount: Int32?, usernames: [Api.Username]?, storiesMaxId: Api.RecentStory?, color: Api.PeerColor?, profileColor: Api.PeerColor?, emojiStatus: Api.EmojiStatus?, level: Int32?, subscriptionUntilDate: Int32?, botVerificationIcon: Int64?, sendPaidMessagesStars: Int64?, linkedMonoforumId: Int64?) { + self.flags = flags + self.flags2 = flags2 + self.id = id + self.accessHash = accessHash + self.title = title + self.username = username + self.photo = photo + self.date = date + self.restrictionReason = restrictionReason + self.adminRights = adminRights + self.bannedRights = bannedRights + self.defaultBannedRights = defaultBannedRights + self.participantsCount = participantsCount + self.usernames = usernames + self.storiesMaxId = storiesMaxId + self.color = color + self.profileColor = profileColor + self.emojiStatus = emojiStatus + self.level = level + self.subscriptionUntilDate = subscriptionUntilDate + self.botVerificationIcon = botVerificationIcon + self.sendPaidMessagesStars = sendPaidMessagesStars + self.linkedMonoforumId = linkedMonoforumId + } + } + public class Cons_channelForbidden { + public var flags: Int32 + public var id: Int64 + public var accessHash: Int64 + public var title: String + public var untilDate: Int32? + public init(flags: Int32, id: Int64, accessHash: Int64, title: String, untilDate: Int32?) { + self.flags = flags + self.id = id + self.accessHash = accessHash + self.title = title + self.untilDate = untilDate + } + } + public class Cons_chat { + public var flags: Int32 + public var id: Int64 + public var title: String + public var photo: Api.ChatPhoto + public var participantsCount: Int32 + public var date: Int32 + public var version: Int32 + public var migratedTo: Api.InputChannel? + public var adminRights: Api.ChatAdminRights? + public var defaultBannedRights: Api.ChatBannedRights? + public init(flags: Int32, id: Int64, title: String, photo: Api.ChatPhoto, participantsCount: Int32, date: Int32, version: Int32, migratedTo: Api.InputChannel?, adminRights: Api.ChatAdminRights?, defaultBannedRights: Api.ChatBannedRights?) { + self.flags = flags + self.id = id + self.title = title + self.photo = photo + self.participantsCount = participantsCount + self.date = date + self.version = version + self.migratedTo = migratedTo + self.adminRights = adminRights + self.defaultBannedRights = defaultBannedRights + } + } + public class Cons_chatEmpty { + public var id: Int64 + public init(id: Int64) { + self.id = id + } + } + public class Cons_chatForbidden { + public var id: Int64 + public var title: String + public init(id: Int64, title: String) { + self.id = id + self.title = title + } + } + case channel(Cons_channel) + case channelForbidden(Cons_channelForbidden) + case chat(Cons_chat) + case chatEmpty(Cons_chatEmpty) + case chatForbidden(Cons_chatForbidden) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .channel(let _data): + if boxed { + buffer.appendInt32(473084188) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.flags2, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 13) != 0 { + serializeInt64(_data.accessHash!, buffer: buffer, boxed: false) + } + serializeString(_data.title, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 6) != 0 { + serializeString(_data.username!, buffer: buffer, boxed: false) + } + _data.photo.serialize(buffer, true) + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 9) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.restrictionReason!.count)) + for item in _data.restrictionReason! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 14) != 0 {adminRights!.serialize(buffer, true)} - if Int(flags) & Int(1 << 15) != 0 {bannedRights!.serialize(buffer, true)} - if Int(flags) & Int(1 << 18) != 0 {defaultBannedRights!.serialize(buffer, true)} - if Int(flags) & Int(1 << 17) != 0 {serializeInt32(participantsCount!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(usernames!.count)) - for item in usernames! { + } + } + if Int(_data.flags) & Int(1 << 14) != 0 { + _data.adminRights!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 15) != 0 { + _data.bannedRights!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 18) != 0 { + _data.defaultBannedRights!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 17) != 0 { + serializeInt32(_data.participantsCount!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.usernames!.count)) + for item in _data.usernames! { item.serialize(buffer, true) - }} - if Int(flags2) & Int(1 << 4) != 0 {storiesMaxId!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 7) != 0 {color!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 8) != 0 {profileColor!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 9) != 0 {emojiStatus!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 10) != 0 {serializeInt32(level!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 11) != 0 {serializeInt32(subscriptionUntilDate!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 13) != 0 {serializeInt64(botVerificationIcon!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 14) != 0 {serializeInt64(sendPaidMessagesStars!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 18) != 0 {serializeInt64(linkedMonoforumId!, buffer: buffer, boxed: false)} - break - case .channelForbidden(let flags, let id, let accessHash, let title, let untilDate): - if boxed { - buffer.appendInt32(399807445) } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 16) != 0 {serializeInt32(untilDate!, buffer: buffer, boxed: false)} - break - case .chat(let flags, let id, let title, let photo, let participantsCount, let date, let version, let migratedTo, let adminRights, let defaultBannedRights): - if boxed { - buffer.appendInt32(1103884886) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - photo.serialize(buffer, true) - serializeInt32(participantsCount, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt32(version, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 6) != 0 {migratedTo!.serialize(buffer, true)} - if Int(flags) & Int(1 << 14) != 0 {adminRights!.serialize(buffer, true)} - if Int(flags) & Int(1 << 18) != 0 {defaultBannedRights!.serialize(buffer, true)} - break - case .chatEmpty(let id): - if boxed { - buffer.appendInt32(693512293) - } - serializeInt64(id, buffer: buffer, boxed: false) - break - case .chatForbidden(let id, let title): - if boxed { - buffer.appendInt32(1704108455) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .channel(let flags, let flags2, let id, let accessHash, let title, let username, let photo, let date, let restrictionReason, let adminRights, let bannedRights, let defaultBannedRights, let participantsCount, let usernames, let storiesMaxId, let color, let profileColor, let emojiStatus, let level, let subscriptionUntilDate, let botVerificationIcon, let sendPaidMessagesStars, let linkedMonoforumId): - return ("channel", [("flags", flags as Any), ("flags2", flags2 as Any), ("id", id as Any), ("accessHash", accessHash as Any), ("title", title as Any), ("username", username as Any), ("photo", photo as Any), ("date", date as Any), ("restrictionReason", restrictionReason as Any), ("adminRights", adminRights as Any), ("bannedRights", bannedRights as Any), ("defaultBannedRights", defaultBannedRights as Any), ("participantsCount", participantsCount as Any), ("usernames", usernames as Any), ("storiesMaxId", storiesMaxId as Any), ("color", color as Any), ("profileColor", profileColor as Any), ("emojiStatus", emojiStatus as Any), ("level", level as Any), ("subscriptionUntilDate", subscriptionUntilDate as Any), ("botVerificationIcon", botVerificationIcon as Any), ("sendPaidMessagesStars", sendPaidMessagesStars as Any), ("linkedMonoforumId", linkedMonoforumId as Any)]) - case .channelForbidden(let flags, let id, let accessHash, let title, let untilDate): - return ("channelForbidden", [("flags", flags as Any), ("id", id as Any), ("accessHash", accessHash as Any), ("title", title as Any), ("untilDate", untilDate as Any)]) - case .chat(let flags, let id, let title, let photo, let participantsCount, let date, let version, let migratedTo, let adminRights, let defaultBannedRights): - return ("chat", [("flags", flags as Any), ("id", id as Any), ("title", title as Any), ("photo", photo as Any), ("participantsCount", participantsCount as Any), ("date", date as Any), ("version", version as Any), ("migratedTo", migratedTo as Any), ("adminRights", adminRights as Any), ("defaultBannedRights", defaultBannedRights as Any)]) - case .chatEmpty(let id): - return ("chatEmpty", [("id", id as Any)]) - case .chatForbidden(let id, let title): - return ("chatForbidden", [("id", id as Any), ("title", title as Any)]) - } - } - + } + if Int(_data.flags2) & Int(1 << 4) != 0 { + _data.storiesMaxId!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 7) != 0 { + _data.color!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 8) != 0 { + _data.profileColor!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 9) != 0 { + _data.emojiStatus!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 10) != 0 { + serializeInt32(_data.level!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 11) != 0 { + serializeInt32(_data.subscriptionUntilDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 13) != 0 { + serializeInt64(_data.botVerificationIcon!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 14) != 0 { + serializeInt64(_data.sendPaidMessagesStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 18) != 0 { + serializeInt64(_data.linkedMonoforumId!, buffer: buffer, boxed: false) + } + break + case .channelForbidden(let _data): + if boxed { + buffer.appendInt32(399807445) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 16) != 0 { + serializeInt32(_data.untilDate!, buffer: buffer, boxed: false) + } + break + case .chat(let _data): + if boxed { + buffer.appendInt32(1103884886) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + _data.photo.serialize(buffer, true) + serializeInt32(_data.participantsCount, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt32(_data.version, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 6) != 0 { + _data.migratedTo!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 14) != 0 { + _data.adminRights!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 18) != 0 { + _data.defaultBannedRights!.serialize(buffer, true) + } + break + case .chatEmpty(let _data): + if boxed { + buffer.appendInt32(693512293) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + break + case .chatForbidden(let _data): + if boxed { + buffer.appendInt32(1704108455) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .channel(let _data): + return ("channel", [("flags", _data.flags as Any), ("flags2", _data.flags2 as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("title", _data.title as Any), ("username", _data.username as Any), ("photo", _data.photo as Any), ("date", _data.date as Any), ("restrictionReason", _data.restrictionReason as Any), ("adminRights", _data.adminRights as Any), ("bannedRights", _data.bannedRights as Any), ("defaultBannedRights", _data.defaultBannedRights as Any), ("participantsCount", _data.participantsCount as Any), ("usernames", _data.usernames as Any), ("storiesMaxId", _data.storiesMaxId as Any), ("color", _data.color as Any), ("profileColor", _data.profileColor as Any), ("emojiStatus", _data.emojiStatus as Any), ("level", _data.level as Any), ("subscriptionUntilDate", _data.subscriptionUntilDate as Any), ("botVerificationIcon", _data.botVerificationIcon as Any), ("sendPaidMessagesStars", _data.sendPaidMessagesStars as Any), ("linkedMonoforumId", _data.linkedMonoforumId as Any)]) + case .channelForbidden(let _data): + return ("channelForbidden", [("flags", _data.flags as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("title", _data.title as Any), ("untilDate", _data.untilDate as Any)]) + case .chat(let _data): + return ("chat", [("flags", _data.flags as Any), ("id", _data.id as Any), ("title", _data.title as Any), ("photo", _data.photo as Any), ("participantsCount", _data.participantsCount as Any), ("date", _data.date as Any), ("version", _data.version as Any), ("migratedTo", _data.migratedTo as Any), ("adminRights", _data.adminRights as Any), ("defaultBannedRights", _data.defaultBannedRights as Any)]) + case .chatEmpty(let _data): + return ("chatEmpty", [("id", _data.id as Any)]) + case .chatForbidden(let _data): + return ("chatForbidden", [("id", _data.id as Any), ("title", _data.title as Any)]) + } + } + public static func parse_channel(_ reader: BufferReader) -> Chat? { var _1: Int32? _1 = reader.readInt32() @@ -610,11 +936,15 @@ public extension Api { var _3: Int64? _3 = reader.readInt64() var _4: Int64? - if Int(_1!) & Int(1 << 13) != 0 {_4 = reader.readInt64() } + if Int(_1!) & Int(1 << 13) != 0 { + _4 = reader.readInt64() + } var _5: String? _5 = parseString(reader) var _6: String? - if Int(_1!) & Int(1 << 6) != 0 {_6 = parseString(reader) } + if Int(_1!) & Int(1 << 6) != 0 { + _6 = parseString(reader) + } var _7: Api.ChatPhoto? if let signature = reader.readInt32() { _7 = Api.parse(reader, signature: signature) as? Api.ChatPhoto @@ -622,53 +952,83 @@ public extension Api { var _8: Int32? _8 = reader.readInt32() var _9: [Api.RestrictionReason]? - if Int(_1!) & Int(1 << 9) != 0 {if let _ = reader.readInt32() { - _9 = Api.parseVector(reader, elementSignature: 0, elementType: Api.RestrictionReason.self) - } } + if Int(_1!) & Int(1 << 9) != 0 { + if let _ = reader.readInt32() { + _9 = Api.parseVector(reader, elementSignature: 0, elementType: Api.RestrictionReason.self) + } + } var _10: Api.ChatAdminRights? - if Int(_1!) & Int(1 << 14) != 0 {if let signature = reader.readInt32() { - _10 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights - } } + if Int(_1!) & Int(1 << 14) != 0 { + if let signature = reader.readInt32() { + _10 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights + } + } var _11: Api.ChatBannedRights? - if Int(_1!) & Int(1 << 15) != 0 {if let signature = reader.readInt32() { - _11 = Api.parse(reader, signature: signature) as? Api.ChatBannedRights - } } + if Int(_1!) & Int(1 << 15) != 0 { + if let signature = reader.readInt32() { + _11 = Api.parse(reader, signature: signature) as? Api.ChatBannedRights + } + } var _12: Api.ChatBannedRights? - if Int(_1!) & Int(1 << 18) != 0 {if let signature = reader.readInt32() { - _12 = Api.parse(reader, signature: signature) as? Api.ChatBannedRights - } } + if Int(_1!) & Int(1 << 18) != 0 { + if let signature = reader.readInt32() { + _12 = Api.parse(reader, signature: signature) as? Api.ChatBannedRights + } + } var _13: Int32? - if Int(_1!) & Int(1 << 17) != 0 {_13 = reader.readInt32() } + if Int(_1!) & Int(1 << 17) != 0 { + _13 = reader.readInt32() + } var _14: [Api.Username]? - if Int(_2!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _14 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Username.self) - } } + if Int(_2!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _14 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Username.self) + } + } var _15: Api.RecentStory? - if Int(_2!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _15 = Api.parse(reader, signature: signature) as? Api.RecentStory - } } + if Int(_2!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _15 = Api.parse(reader, signature: signature) as? Api.RecentStory + } + } var _16: Api.PeerColor? - if Int(_2!) & Int(1 << 7) != 0 {if let signature = reader.readInt32() { - _16 = Api.parse(reader, signature: signature) as? Api.PeerColor - } } + if Int(_2!) & Int(1 << 7) != 0 { + if let signature = reader.readInt32() { + _16 = Api.parse(reader, signature: signature) as? Api.PeerColor + } + } var _17: Api.PeerColor? - if Int(_2!) & Int(1 << 8) != 0 {if let signature = reader.readInt32() { - _17 = Api.parse(reader, signature: signature) as? Api.PeerColor - } } + if Int(_2!) & Int(1 << 8) != 0 { + if let signature = reader.readInt32() { + _17 = Api.parse(reader, signature: signature) as? Api.PeerColor + } + } var _18: Api.EmojiStatus? - if Int(_2!) & Int(1 << 9) != 0 {if let signature = reader.readInt32() { - _18 = Api.parse(reader, signature: signature) as? Api.EmojiStatus - } } + if Int(_2!) & Int(1 << 9) != 0 { + if let signature = reader.readInt32() { + _18 = Api.parse(reader, signature: signature) as? Api.EmojiStatus + } + } var _19: Int32? - if Int(_2!) & Int(1 << 10) != 0 {_19 = reader.readInt32() } + if Int(_2!) & Int(1 << 10) != 0 { + _19 = reader.readInt32() + } var _20: Int32? - if Int(_2!) & Int(1 << 11) != 0 {_20 = reader.readInt32() } + if Int(_2!) & Int(1 << 11) != 0 { + _20 = reader.readInt32() + } var _21: Int64? - if Int(_2!) & Int(1 << 13) != 0 {_21 = reader.readInt64() } + if Int(_2!) & Int(1 << 13) != 0 { + _21 = reader.readInt64() + } var _22: Int64? - if Int(_2!) & Int(1 << 14) != 0 {_22 = reader.readInt64() } + if Int(_2!) & Int(1 << 14) != 0 { + _22 = reader.readInt64() + } var _23: Int64? - if Int(_2!) & Int(1 << 18) != 0 {_23 = reader.readInt64() } + if Int(_2!) & Int(1 << 18) != 0 { + _23 = reader.readInt64() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -692,30 +1052,12 @@ public extension Api { let _c21 = (Int(_2!) & Int(1 << 13) == 0) || _21 != nil let _c22 = (Int(_2!) & Int(1 << 14) == 0) || _22 != nil let _c23 = (Int(_2!) & Int(1 << 18) == 0) || _23 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - if !_c16 { return nil } - if !_c17 { return nil } - if !_c18 { return nil } - if !_c19 { return nil } - if !_c20 { return nil } - if !_c21 { return nil } - if !_c22 { return nil } - if !_c23 { return nil } - return Api.Chat.channel(flags: _1!, flags2: _2!, id: _3!, accessHash: _4, title: _5!, username: _6, photo: _7!, date: _8!, restrictionReason: _9, adminRights: _10, bannedRights: _11, defaultBannedRights: _12, participantsCount: _13, usernames: _14, storiesMaxId: _15, color: _16, profileColor: _17, emojiStatus: _18, level: _19, subscriptionUntilDate: _20, botVerificationIcon: _21, sendPaidMessagesStars: _22, linkedMonoforumId: _23) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 && _c18 && _c19 && _c20 && _c21 && _c22 && _c23 { + return Api.Chat.channel(Cons_channel(flags: _1!, flags2: _2!, id: _3!, accessHash: _4, title: _5!, username: _6, photo: _7!, date: _8!, restrictionReason: _9, adminRights: _10, bannedRights: _11, defaultBannedRights: _12, participantsCount: _13, usernames: _14, storiesMaxId: _15, color: _16, profileColor: _17, emojiStatus: _18, level: _19, subscriptionUntilDate: _20, botVerificationIcon: _21, sendPaidMessagesStars: _22, linkedMonoforumId: _23)) + } + else { + return nil + } } public static func parse_channelForbidden(_ reader: BufferReader) -> Chat? { var _1: Int32? @@ -727,18 +1069,20 @@ public extension Api { var _4: String? _4 = parseString(reader) var _5: Int32? - if Int(_1!) & Int(1 << 16) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 16) != 0 { + _5 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 16) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.Chat.channelForbidden(flags: _1!, id: _2!, accessHash: _3!, title: _4!, untilDate: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.Chat.channelForbidden(Cons_channelForbidden(flags: _1!, id: _2!, accessHash: _3!, title: _4!, untilDate: _5)) + } + else { + return nil + } } public static func parse_chat(_ reader: BufferReader) -> Chat? { var _1: Int32? @@ -758,17 +1102,23 @@ public extension Api { var _7: Int32? _7 = reader.readInt32() var _8: Api.InputChannel? - if Int(_1!) & Int(1 << 6) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.InputChannel - } } + if Int(_1!) & Int(1 << 6) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.InputChannel + } + } var _9: Api.ChatAdminRights? - if Int(_1!) & Int(1 << 14) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights - } } + if Int(_1!) & Int(1 << 14) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.ChatAdminRights + } + } var _10: Api.ChatBannedRights? - if Int(_1!) & Int(1 << 18) != 0 {if let signature = reader.readInt32() { - _10 = Api.parse(reader, signature: signature) as? Api.ChatBannedRights - } } + if Int(_1!) & Int(1 << 18) != 0 { + if let signature = reader.readInt32() { + _10 = Api.parse(reader, signature: signature) as? Api.ChatBannedRights + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -779,24 +1129,23 @@ public extension Api { let _c8 = (Int(_1!) & Int(1 << 6) == 0) || _8 != nil let _c9 = (Int(_1!) & Int(1 << 14) == 0) || _9 != nil let _c10 = (Int(_1!) & Int(1 << 18) == 0) || _10 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - return Api.Chat.chat(flags: _1!, id: _2!, title: _3!, photo: _4!, participantsCount: _5!, date: _6!, version: _7!, migratedTo: _8, adminRights: _9, defaultBannedRights: _10) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 { + return Api.Chat.chat(Cons_chat(flags: _1!, id: _2!, title: _3!, photo: _4!, participantsCount: _5!, date: _6!, version: _7!, migratedTo: _8, adminRights: _9, defaultBannedRights: _10)) + } + else { + return nil + } } public static func parse_chatEmpty(_ reader: BufferReader) -> Chat? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Chat.chatEmpty(id: _1!) + if _c1 { + return Api.Chat.chatEmpty(Cons_chatEmpty(id: _1!)) + } + else { + return nil + } } public static func parse_chatForbidden(_ reader: BufferReader) -> Chat? { var _1: Int64? @@ -805,69 +1154,90 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Chat.chatForbidden(id: _1!, title: _2!) + if _c1 && _c2 { + return Api.Chat.chatForbidden(Cons_chatForbidden(id: _1!, title: _2!)) + } + else { + return nil + } } - } } public extension Api { enum ChatAdminRights: TypeConstructorDescription { - case chatAdminRights(flags: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatAdminRights(let flags): - if boxed { - buffer.appendInt32(1605510357) - } - serializeInt32(flags, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatAdminRights(let flags): - return ("chatAdminRights", [("flags", flags as Any)]) - } - } - + public class Cons_chatAdminRights { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } + case chatAdminRights(Cons_chatAdminRights) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatAdminRights(let _data): + if boxed { + buffer.appendInt32(1605510357) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatAdminRights(let _data): + return ("chatAdminRights", [("flags", _data.flags as Any)]) + } + } + public static func parse_chatAdminRights(_ reader: BufferReader) -> ChatAdminRights? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChatAdminRights.chatAdminRights(flags: _1!) + if _c1 { + return Api.ChatAdminRights.chatAdminRights(Cons_chatAdminRights(flags: _1!)) + } + else { + return nil + } } - } } public extension Api { enum ChatAdminWithInvites: TypeConstructorDescription { - case chatAdminWithInvites(adminId: Int64, invitesCount: Int32, revokedInvitesCount: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatAdminWithInvites(let adminId, let invitesCount, let revokedInvitesCount): - if boxed { - buffer.appendInt32(-219353309) - } - serializeInt64(adminId, buffer: buffer, boxed: false) - serializeInt32(invitesCount, buffer: buffer, boxed: false) - serializeInt32(revokedInvitesCount, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatAdminWithInvites(let adminId, let invitesCount, let revokedInvitesCount): - return ("chatAdminWithInvites", [("adminId", adminId as Any), ("invitesCount", invitesCount as Any), ("revokedInvitesCount", revokedInvitesCount as Any)]) - } - } - + public class Cons_chatAdminWithInvites { + public var adminId: Int64 + public var invitesCount: Int32 + public var revokedInvitesCount: Int32 + public init(adminId: Int64, invitesCount: Int32, revokedInvitesCount: Int32) { + self.adminId = adminId + self.invitesCount = invitesCount + self.revokedInvitesCount = revokedInvitesCount + } + } + case chatAdminWithInvites(Cons_chatAdminWithInvites) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatAdminWithInvites(let _data): + if boxed { + buffer.appendInt32(-219353309) + } + serializeInt64(_data.adminId, buffer: buffer, boxed: false) + serializeInt32(_data.invitesCount, buffer: buffer, boxed: false) + serializeInt32(_data.revokedInvitesCount, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatAdminWithInvites(let _data): + return ("chatAdminWithInvites", [("adminId", _data.adminId as Any), ("invitesCount", _data.invitesCount as Any), ("revokedInvitesCount", _data.revokedInvitesCount as Any)]) + } + } + public static func parse_chatAdminWithInvites(_ reader: BufferReader) -> ChatAdminWithInvites? { var _1: Int64? _1 = reader.readInt64() @@ -878,37 +1248,46 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.ChatAdminWithInvites.chatAdminWithInvites(adminId: _1!, invitesCount: _2!, revokedInvitesCount: _3!) + if _c1 && _c2 && _c3 { + return Api.ChatAdminWithInvites.chatAdminWithInvites(Cons_chatAdminWithInvites(adminId: _1!, invitesCount: _2!, revokedInvitesCount: _3!)) + } + else { + return nil + } } - } } public extension Api { enum ChatBannedRights: TypeConstructorDescription { - case chatBannedRights(flags: Int32, untilDate: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatBannedRights(let flags, let untilDate): - if boxed { - buffer.appendInt32(-1626209256) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(untilDate, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatBannedRights(let flags, let untilDate): - return ("chatBannedRights", [("flags", flags as Any), ("untilDate", untilDate as Any)]) - } - } - + public class Cons_chatBannedRights { + public var flags: Int32 + public var untilDate: Int32 + public init(flags: Int32, untilDate: Int32) { + self.flags = flags + self.untilDate = untilDate + } + } + case chatBannedRights(Cons_chatBannedRights) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatBannedRights(let _data): + if boxed { + buffer.appendInt32(-1626209256) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.untilDate, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatBannedRights(let _data): + return ("chatBannedRights", [("flags", _data.flags as Any), ("untilDate", _data.untilDate as Any)]) + } + } + public static func parse_chatBannedRights(_ reader: BufferReader) -> ChatBannedRights? { var _1: Int32? _1 = reader.readInt32() @@ -916,127 +1295,365 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChatBannedRights.chatBannedRights(flags: _1!, untilDate: _2!) + if _c1 && _c2 { + return Api.ChatBannedRights.chatBannedRights(Cons_chatBannedRights(flags: _1!, untilDate: _2!)) + } + else { + return nil + } } - } } public extension Api { enum ChatFull: TypeConstructorDescription { - case channelFull(flags: Int32, flags2: Int32, id: Int64, about: String, participantsCount: Int32?, adminsCount: Int32?, kickedCount: Int32?, bannedCount: Int32?, onlineCount: Int32?, readInboxMaxId: Int32, readOutboxMaxId: Int32, unreadCount: Int32, chatPhoto: Api.Photo, notifySettings: Api.PeerNotifySettings, exportedInvite: Api.ExportedChatInvite?, botInfo: [Api.BotInfo], migratedFromChatId: Int64?, migratedFromMaxId: Int32?, pinnedMsgId: Int32?, stickerset: Api.StickerSet?, availableMinId: Int32?, folderId: Int32?, linkedChatId: Int64?, location: Api.ChannelLocation?, slowmodeSeconds: Int32?, slowmodeNextSendDate: Int32?, statsDc: Int32?, pts: Int32, call: Api.InputGroupCall?, ttlPeriod: Int32?, pendingSuggestions: [String]?, groupcallDefaultJoinAs: Api.Peer?, themeEmoticon: String?, requestsPending: Int32?, recentRequesters: [Int64]?, defaultSendAs: Api.Peer?, availableReactions: Api.ChatReactions?, reactionsLimit: Int32?, stories: Api.PeerStories?, wallpaper: Api.WallPaper?, boostsApplied: Int32?, boostsUnrestrict: Int32?, emojiset: Api.StickerSet?, botVerification: Api.BotVerification?, stargiftsCount: Int32?, sendPaidMessagesStars: Int64?, mainTab: Api.ProfileTab?) - case chatFull(flags: Int32, id: Int64, about: String, participants: Api.ChatParticipants, chatPhoto: Api.Photo?, notifySettings: Api.PeerNotifySettings, exportedInvite: Api.ExportedChatInvite?, botInfo: [Api.BotInfo]?, pinnedMsgId: Int32?, folderId: Int32?, call: Api.InputGroupCall?, ttlPeriod: Int32?, groupcallDefaultJoinAs: Api.Peer?, themeEmoticon: String?, requestsPending: Int32?, recentRequesters: [Int64]?, availableReactions: Api.ChatReactions?, reactionsLimit: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .channelFull(let flags, let flags2, let id, let about, let participantsCount, let adminsCount, let kickedCount, let bannedCount, let onlineCount, let readInboxMaxId, let readOutboxMaxId, let unreadCount, let chatPhoto, let notifySettings, let exportedInvite, let botInfo, let migratedFromChatId, let migratedFromMaxId, let pinnedMsgId, let stickerset, let availableMinId, let folderId, let linkedChatId, let location, let slowmodeSeconds, let slowmodeNextSendDate, let statsDc, let pts, let call, let ttlPeriod, let pendingSuggestions, let groupcallDefaultJoinAs, let themeEmoticon, let requestsPending, let recentRequesters, let defaultSendAs, let availableReactions, let reactionsLimit, let stories, let wallpaper, let boostsApplied, let boostsUnrestrict, let emojiset, let botVerification, let stargiftsCount, let sendPaidMessagesStars, let mainTab): - if boxed { - buffer.appendInt32(-455036259) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(flags2, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeString(about, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(participantsCount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(adminsCount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(kickedCount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(bannedCount!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 13) != 0 {serializeInt32(onlineCount!, buffer: buffer, boxed: false)} - serializeInt32(readInboxMaxId, buffer: buffer, boxed: false) - serializeInt32(readOutboxMaxId, buffer: buffer, boxed: false) - serializeInt32(unreadCount, buffer: buffer, boxed: false) - chatPhoto.serialize(buffer, true) - notifySettings.serialize(buffer, true) - if Int(flags) & Int(1 << 23) != 0 {exportedInvite!.serialize(buffer, true)} + public class Cons_channelFull { + public var flags: Int32 + public var flags2: Int32 + public var id: Int64 + public var about: String + public var participantsCount: Int32? + public var adminsCount: Int32? + public var kickedCount: Int32? + public var bannedCount: Int32? + public var onlineCount: Int32? + public var readInboxMaxId: Int32 + public var readOutboxMaxId: Int32 + public var unreadCount: Int32 + public var chatPhoto: Api.Photo + public var notifySettings: Api.PeerNotifySettings + public var exportedInvite: Api.ExportedChatInvite? + public var botInfo: [Api.BotInfo] + public var migratedFromChatId: Int64? + public var migratedFromMaxId: Int32? + public var pinnedMsgId: Int32? + public var stickerset: Api.StickerSet? + public var availableMinId: Int32? + public var folderId: Int32? + public var linkedChatId: Int64? + public var location: Api.ChannelLocation? + public var slowmodeSeconds: Int32? + public var slowmodeNextSendDate: Int32? + public var statsDc: Int32? + public var pts: Int32 + public var call: Api.InputGroupCall? + public var ttlPeriod: Int32? + public var pendingSuggestions: [String]? + public var groupcallDefaultJoinAs: Api.Peer? + public var themeEmoticon: String? + public var requestsPending: Int32? + public var recentRequesters: [Int64]? + public var defaultSendAs: Api.Peer? + public var availableReactions: Api.ChatReactions? + public var reactionsLimit: Int32? + public var stories: Api.PeerStories? + public var wallpaper: Api.WallPaper? + public var boostsApplied: Int32? + public var boostsUnrestrict: Int32? + public var emojiset: Api.StickerSet? + public var botVerification: Api.BotVerification? + public var stargiftsCount: Int32? + public var sendPaidMessagesStars: Int64? + public var mainTab: Api.ProfileTab? + public init(flags: Int32, flags2: Int32, id: Int64, about: String, participantsCount: Int32?, adminsCount: Int32?, kickedCount: Int32?, bannedCount: Int32?, onlineCount: Int32?, readInboxMaxId: Int32, readOutboxMaxId: Int32, unreadCount: Int32, chatPhoto: Api.Photo, notifySettings: Api.PeerNotifySettings, exportedInvite: Api.ExportedChatInvite?, botInfo: [Api.BotInfo], migratedFromChatId: Int64?, migratedFromMaxId: Int32?, pinnedMsgId: Int32?, stickerset: Api.StickerSet?, availableMinId: Int32?, folderId: Int32?, linkedChatId: Int64?, location: Api.ChannelLocation?, slowmodeSeconds: Int32?, slowmodeNextSendDate: Int32?, statsDc: Int32?, pts: Int32, call: Api.InputGroupCall?, ttlPeriod: Int32?, pendingSuggestions: [String]?, groupcallDefaultJoinAs: Api.Peer?, themeEmoticon: String?, requestsPending: Int32?, recentRequesters: [Int64]?, defaultSendAs: Api.Peer?, availableReactions: Api.ChatReactions?, reactionsLimit: Int32?, stories: Api.PeerStories?, wallpaper: Api.WallPaper?, boostsApplied: Int32?, boostsUnrestrict: Int32?, emojiset: Api.StickerSet?, botVerification: Api.BotVerification?, stargiftsCount: Int32?, sendPaidMessagesStars: Int64?, mainTab: Api.ProfileTab?) { + self.flags = flags + self.flags2 = flags2 + self.id = id + self.about = about + self.participantsCount = participantsCount + self.adminsCount = adminsCount + self.kickedCount = kickedCount + self.bannedCount = bannedCount + self.onlineCount = onlineCount + self.readInboxMaxId = readInboxMaxId + self.readOutboxMaxId = readOutboxMaxId + self.unreadCount = unreadCount + self.chatPhoto = chatPhoto + self.notifySettings = notifySettings + self.exportedInvite = exportedInvite + self.botInfo = botInfo + self.migratedFromChatId = migratedFromChatId + self.migratedFromMaxId = migratedFromMaxId + self.pinnedMsgId = pinnedMsgId + self.stickerset = stickerset + self.availableMinId = availableMinId + self.folderId = folderId + self.linkedChatId = linkedChatId + self.location = location + self.slowmodeSeconds = slowmodeSeconds + self.slowmodeNextSendDate = slowmodeNextSendDate + self.statsDc = statsDc + self.pts = pts + self.call = call + self.ttlPeriod = ttlPeriod + self.pendingSuggestions = pendingSuggestions + self.groupcallDefaultJoinAs = groupcallDefaultJoinAs + self.themeEmoticon = themeEmoticon + self.requestsPending = requestsPending + self.recentRequesters = recentRequesters + self.defaultSendAs = defaultSendAs + self.availableReactions = availableReactions + self.reactionsLimit = reactionsLimit + self.stories = stories + self.wallpaper = wallpaper + self.boostsApplied = boostsApplied + self.boostsUnrestrict = boostsUnrestrict + self.emojiset = emojiset + self.botVerification = botVerification + self.stargiftsCount = stargiftsCount + self.sendPaidMessagesStars = sendPaidMessagesStars + self.mainTab = mainTab + } + } + public class Cons_chatFull { + public var flags: Int32 + public var id: Int64 + public var about: String + public var participants: Api.ChatParticipants + public var chatPhoto: Api.Photo? + public var notifySettings: Api.PeerNotifySettings + public var exportedInvite: Api.ExportedChatInvite? + public var botInfo: [Api.BotInfo]? + public var pinnedMsgId: Int32? + public var folderId: Int32? + public var call: Api.InputGroupCall? + public var ttlPeriod: Int32? + public var groupcallDefaultJoinAs: Api.Peer? + public var themeEmoticon: String? + public var requestsPending: Int32? + public var recentRequesters: [Int64]? + public var availableReactions: Api.ChatReactions? + public var reactionsLimit: Int32? + public init(flags: Int32, id: Int64, about: String, participants: Api.ChatParticipants, chatPhoto: Api.Photo?, notifySettings: Api.PeerNotifySettings, exportedInvite: Api.ExportedChatInvite?, botInfo: [Api.BotInfo]?, pinnedMsgId: Int32?, folderId: Int32?, call: Api.InputGroupCall?, ttlPeriod: Int32?, groupcallDefaultJoinAs: Api.Peer?, themeEmoticon: String?, requestsPending: Int32?, recentRequesters: [Int64]?, availableReactions: Api.ChatReactions?, reactionsLimit: Int32?) { + self.flags = flags + self.id = id + self.about = about + self.participants = participants + self.chatPhoto = chatPhoto + self.notifySettings = notifySettings + self.exportedInvite = exportedInvite + self.botInfo = botInfo + self.pinnedMsgId = pinnedMsgId + self.folderId = folderId + self.call = call + self.ttlPeriod = ttlPeriod + self.groupcallDefaultJoinAs = groupcallDefaultJoinAs + self.themeEmoticon = themeEmoticon + self.requestsPending = requestsPending + self.recentRequesters = recentRequesters + self.availableReactions = availableReactions + self.reactionsLimit = reactionsLimit + } + } + case channelFull(Cons_channelFull) + case chatFull(Cons_chatFull) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .channelFull(let _data): + if boxed { + buffer.appendInt32(-455036259) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.flags2, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeString(_data.about, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.participantsCount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.adminsCount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.kickedCount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.bannedCount!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 13) != 0 { + serializeInt32(_data.onlineCount!, buffer: buffer, boxed: false) + } + serializeInt32(_data.readInboxMaxId, buffer: buffer, boxed: false) + serializeInt32(_data.readOutboxMaxId, buffer: buffer, boxed: false) + serializeInt32(_data.unreadCount, buffer: buffer, boxed: false) + _data.chatPhoto.serialize(buffer, true) + _data.notifySettings.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 23) != 0 { + _data.exportedInvite!.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.botInfo.count)) + for item in _data.botInfo { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt64(_data.migratedFromChatId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.migratedFromMaxId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeInt32(_data.pinnedMsgId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + _data.stickerset!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 9) != 0 { + serializeInt32(_data.availableMinId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 11) != 0 { + serializeInt32(_data.folderId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 14) != 0 { + serializeInt64(_data.linkedChatId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 15) != 0 { + _data.location!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 17) != 0 { + serializeInt32(_data.slowmodeSeconds!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 18) != 0 { + serializeInt32(_data.slowmodeNextSendDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 12) != 0 { + serializeInt32(_data.statsDc!, buffer: buffer, boxed: false) + } + serializeInt32(_data.pts, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 21) != 0 { + _data.call!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 24) != 0 { + serializeInt32(_data.ttlPeriod!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 25) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(botInfo.count)) - for item in botInfo { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 4) != 0 {serializeInt64(migratedFromChatId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(migratedFromMaxId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeInt32(pinnedMsgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {stickerset!.serialize(buffer, true)} - if Int(flags) & Int(1 << 9) != 0 {serializeInt32(availableMinId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 11) != 0 {serializeInt32(folderId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 14) != 0 {serializeInt64(linkedChatId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 15) != 0 {location!.serialize(buffer, true)} - if Int(flags) & Int(1 << 17) != 0 {serializeInt32(slowmodeSeconds!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 18) != 0 {serializeInt32(slowmodeNextSendDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 12) != 0 {serializeInt32(statsDc!, buffer: buffer, boxed: false)} - serializeInt32(pts, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 21) != 0 {call!.serialize(buffer, true)} - if Int(flags) & Int(1 << 24) != 0 {serializeInt32(ttlPeriod!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 25) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(pendingSuggestions!.count)) - for item in pendingSuggestions! { + buffer.appendInt32(Int32(_data.pendingSuggestions!.count)) + for item in _data.pendingSuggestions! { serializeString(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 26) != 0 {groupcallDefaultJoinAs!.serialize(buffer, true)} - if Int(flags) & Int(1 << 27) != 0 {serializeString(themeEmoticon!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 28) != 0 {serializeInt32(requestsPending!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 28) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(recentRequesters!.count)) - for item in recentRequesters! { - serializeInt64(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 29) != 0 {defaultSendAs!.serialize(buffer, true)} - if Int(flags) & Int(1 << 30) != 0 {availableReactions!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 13) != 0 {serializeInt32(reactionsLimit!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 4) != 0 {stories!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 7) != 0 {wallpaper!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 8) != 0 {serializeInt32(boostsApplied!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 9) != 0 {serializeInt32(boostsUnrestrict!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 10) != 0 {emojiset!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 17) != 0 {botVerification!.serialize(buffer, true)} - if Int(flags2) & Int(1 << 18) != 0 {serializeInt32(stargiftsCount!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 21) != 0 {serializeInt64(sendPaidMessagesStars!, buffer: buffer, boxed: false)} - if Int(flags2) & Int(1 << 22) != 0 {mainTab!.serialize(buffer, true)} - break - case .chatFull(let flags, let id, let about, let participants, let chatPhoto, let notifySettings, let exportedInvite, let botInfo, let pinnedMsgId, let folderId, let call, let ttlPeriod, let groupcallDefaultJoinAs, let themeEmoticon, let requestsPending, let recentRequesters, let availableReactions, let reactionsLimit): - if boxed { - buffer.appendInt32(640893467) } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeString(about, buffer: buffer, boxed: false) - participants.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {chatPhoto!.serialize(buffer, true)} - notifySettings.serialize(buffer, true) - if Int(flags) & Int(1 << 13) != 0 {exportedInvite!.serialize(buffer, true)} - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(botInfo!.count)) - for item in botInfo! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 6) != 0 {serializeInt32(pinnedMsgId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 11) != 0 {serializeInt32(folderId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 12) != 0 {call!.serialize(buffer, true)} - if Int(flags) & Int(1 << 14) != 0 {serializeInt32(ttlPeriod!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 15) != 0 {groupcallDefaultJoinAs!.serialize(buffer, true)} - if Int(flags) & Int(1 << 16) != 0 {serializeString(themeEmoticon!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 17) != 0 {serializeInt32(requestsPending!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 17) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(recentRequesters!.count)) - for item in recentRequesters! { + } + if Int(_data.flags) & Int(1 << 26) != 0 { + _data.groupcallDefaultJoinAs!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 27) != 0 { + serializeString(_data.themeEmoticon!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 28) != 0 { + serializeInt32(_data.requestsPending!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 28) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.recentRequesters!.count)) + for item in _data.recentRequesters! { serializeInt64(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 18) != 0 {availableReactions!.serialize(buffer, true)} - if Int(flags) & Int(1 << 20) != 0 {serializeInt32(reactionsLimit!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .channelFull(let flags, let flags2, let id, let about, let participantsCount, let adminsCount, let kickedCount, let bannedCount, let onlineCount, let readInboxMaxId, let readOutboxMaxId, let unreadCount, let chatPhoto, let notifySettings, let exportedInvite, let botInfo, let migratedFromChatId, let migratedFromMaxId, let pinnedMsgId, let stickerset, let availableMinId, let folderId, let linkedChatId, let location, let slowmodeSeconds, let slowmodeNextSendDate, let statsDc, let pts, let call, let ttlPeriod, let pendingSuggestions, let groupcallDefaultJoinAs, let themeEmoticon, let requestsPending, let recentRequesters, let defaultSendAs, let availableReactions, let reactionsLimit, let stories, let wallpaper, let boostsApplied, let boostsUnrestrict, let emojiset, let botVerification, let stargiftsCount, let sendPaidMessagesStars, let mainTab): - return ("channelFull", [("flags", flags as Any), ("flags2", flags2 as Any), ("id", id as Any), ("about", about as Any), ("participantsCount", participantsCount as Any), ("adminsCount", adminsCount as Any), ("kickedCount", kickedCount as Any), ("bannedCount", bannedCount as Any), ("onlineCount", onlineCount as Any), ("readInboxMaxId", readInboxMaxId as Any), ("readOutboxMaxId", readOutboxMaxId as Any), ("unreadCount", unreadCount as Any), ("chatPhoto", chatPhoto as Any), ("notifySettings", notifySettings as Any), ("exportedInvite", exportedInvite as Any), ("botInfo", botInfo as Any), ("migratedFromChatId", migratedFromChatId as Any), ("migratedFromMaxId", migratedFromMaxId as Any), ("pinnedMsgId", pinnedMsgId as Any), ("stickerset", stickerset as Any), ("availableMinId", availableMinId as Any), ("folderId", folderId as Any), ("linkedChatId", linkedChatId as Any), ("location", location as Any), ("slowmodeSeconds", slowmodeSeconds as Any), ("slowmodeNextSendDate", slowmodeNextSendDate as Any), ("statsDc", statsDc as Any), ("pts", pts as Any), ("call", call as Any), ("ttlPeriod", ttlPeriod as Any), ("pendingSuggestions", pendingSuggestions as Any), ("groupcallDefaultJoinAs", groupcallDefaultJoinAs as Any), ("themeEmoticon", themeEmoticon as Any), ("requestsPending", requestsPending as Any), ("recentRequesters", recentRequesters as Any), ("defaultSendAs", defaultSendAs as Any), ("availableReactions", availableReactions as Any), ("reactionsLimit", reactionsLimit as Any), ("stories", stories as Any), ("wallpaper", wallpaper as Any), ("boostsApplied", boostsApplied as Any), ("boostsUnrestrict", boostsUnrestrict as Any), ("emojiset", emojiset as Any), ("botVerification", botVerification as Any), ("stargiftsCount", stargiftsCount as Any), ("sendPaidMessagesStars", sendPaidMessagesStars as Any), ("mainTab", mainTab as Any)]) - case .chatFull(let flags, let id, let about, let participants, let chatPhoto, let notifySettings, let exportedInvite, let botInfo, let pinnedMsgId, let folderId, let call, let ttlPeriod, let groupcallDefaultJoinAs, let themeEmoticon, let requestsPending, let recentRequesters, let availableReactions, let reactionsLimit): - return ("chatFull", [("flags", flags as Any), ("id", id as Any), ("about", about as Any), ("participants", participants as Any), ("chatPhoto", chatPhoto as Any), ("notifySettings", notifySettings as Any), ("exportedInvite", exportedInvite as Any), ("botInfo", botInfo as Any), ("pinnedMsgId", pinnedMsgId as Any), ("folderId", folderId as Any), ("call", call as Any), ("ttlPeriod", ttlPeriod as Any), ("groupcallDefaultJoinAs", groupcallDefaultJoinAs as Any), ("themeEmoticon", themeEmoticon as Any), ("requestsPending", requestsPending as Any), ("recentRequesters", recentRequesters as Any), ("availableReactions", availableReactions as Any), ("reactionsLimit", reactionsLimit as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 29) != 0 { + _data.defaultSendAs!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 30) != 0 { + _data.availableReactions!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 13) != 0 { + serializeInt32(_data.reactionsLimit!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 4) != 0 { + _data.stories!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 7) != 0 { + _data.wallpaper!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 8) != 0 { + serializeInt32(_data.boostsApplied!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 9) != 0 { + serializeInt32(_data.boostsUnrestrict!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 10) != 0 { + _data.emojiset!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 17) != 0 { + _data.botVerification!.serialize(buffer, true) + } + if Int(_data.flags2) & Int(1 << 18) != 0 { + serializeInt32(_data.stargiftsCount!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 21) != 0 { + serializeInt64(_data.sendPaidMessagesStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags2) & Int(1 << 22) != 0 { + _data.mainTab!.serialize(buffer, true) + } + break + case .chatFull(let _data): + if boxed { + buffer.appendInt32(640893467) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeString(_data.about, buffer: buffer, boxed: false) + _data.participants.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.chatPhoto!.serialize(buffer, true) + } + _data.notifySettings.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 13) != 0 { + _data.exportedInvite!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.botInfo!.count)) + for item in _data.botInfo! { + item.serialize(buffer, true) + } + } + if Int(_data.flags) & Int(1 << 6) != 0 { + serializeInt32(_data.pinnedMsgId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 11) != 0 { + serializeInt32(_data.folderId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 12) != 0 { + _data.call!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 14) != 0 { + serializeInt32(_data.ttlPeriod!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 15) != 0 { + _data.groupcallDefaultJoinAs!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 16) != 0 { + serializeString(_data.themeEmoticon!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 17) != 0 { + serializeInt32(_data.requestsPending!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 17) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.recentRequesters!.count)) + for item in _data.recentRequesters! { + serializeInt64(item, buffer: buffer, boxed: false) + } + } + if Int(_data.flags) & Int(1 << 18) != 0 { + _data.availableReactions!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 20) != 0 { + serializeInt32(_data.reactionsLimit!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .channelFull(let _data): + return ("channelFull", [("flags", _data.flags as Any), ("flags2", _data.flags2 as Any), ("id", _data.id as Any), ("about", _data.about as Any), ("participantsCount", _data.participantsCount as Any), ("adminsCount", _data.adminsCount as Any), ("kickedCount", _data.kickedCount as Any), ("bannedCount", _data.bannedCount as Any), ("onlineCount", _data.onlineCount as Any), ("readInboxMaxId", _data.readInboxMaxId as Any), ("readOutboxMaxId", _data.readOutboxMaxId as Any), ("unreadCount", _data.unreadCount as Any), ("chatPhoto", _data.chatPhoto as Any), ("notifySettings", _data.notifySettings as Any), ("exportedInvite", _data.exportedInvite as Any), ("botInfo", _data.botInfo as Any), ("migratedFromChatId", _data.migratedFromChatId as Any), ("migratedFromMaxId", _data.migratedFromMaxId as Any), ("pinnedMsgId", _data.pinnedMsgId as Any), ("stickerset", _data.stickerset as Any), ("availableMinId", _data.availableMinId as Any), ("folderId", _data.folderId as Any), ("linkedChatId", _data.linkedChatId as Any), ("location", _data.location as Any), ("slowmodeSeconds", _data.slowmodeSeconds as Any), ("slowmodeNextSendDate", _data.slowmodeNextSendDate as Any), ("statsDc", _data.statsDc as Any), ("pts", _data.pts as Any), ("call", _data.call as Any), ("ttlPeriod", _data.ttlPeriod as Any), ("pendingSuggestions", _data.pendingSuggestions as Any), ("groupcallDefaultJoinAs", _data.groupcallDefaultJoinAs as Any), ("themeEmoticon", _data.themeEmoticon as Any), ("requestsPending", _data.requestsPending as Any), ("recentRequesters", _data.recentRequesters as Any), ("defaultSendAs", _data.defaultSendAs as Any), ("availableReactions", _data.availableReactions as Any), ("reactionsLimit", _data.reactionsLimit as Any), ("stories", _data.stories as Any), ("wallpaper", _data.wallpaper as Any), ("boostsApplied", _data.boostsApplied as Any), ("boostsUnrestrict", _data.boostsUnrestrict as Any), ("emojiset", _data.emojiset as Any), ("botVerification", _data.botVerification as Any), ("stargiftsCount", _data.stargiftsCount as Any), ("sendPaidMessagesStars", _data.sendPaidMessagesStars as Any), ("mainTab", _data.mainTab as Any)]) + case .chatFull(let _data): + return ("chatFull", [("flags", _data.flags as Any), ("id", _data.id as Any), ("about", _data.about as Any), ("participants", _data.participants as Any), ("chatPhoto", _data.chatPhoto as Any), ("notifySettings", _data.notifySettings as Any), ("exportedInvite", _data.exportedInvite as Any), ("botInfo", _data.botInfo as Any), ("pinnedMsgId", _data.pinnedMsgId as Any), ("folderId", _data.folderId as Any), ("call", _data.call as Any), ("ttlPeriod", _data.ttlPeriod as Any), ("groupcallDefaultJoinAs", _data.groupcallDefaultJoinAs as Any), ("themeEmoticon", _data.themeEmoticon as Any), ("requestsPending", _data.requestsPending as Any), ("recentRequesters", _data.recentRequesters as Any), ("availableReactions", _data.availableReactions as Any), ("reactionsLimit", _data.reactionsLimit as Any)]) + } + } + public static func parse_channelFull(_ reader: BufferReader) -> ChatFull? { var _1: Int32? _1 = reader.readInt32() @@ -1047,15 +1664,25 @@ public extension Api { var _4: String? _4 = parseString(reader) var _5: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _5 = reader.readInt32() + } var _6: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _6 = reader.readInt32() + } var _7: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_7 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _7 = reader.readInt32() + } var _8: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_8 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _8 = reader.readInt32() + } var _9: Int32? - if Int(_1!) & Int(1 << 13) != 0 {_9 = reader.readInt32() } + if Int(_1!) & Int(1 << 13) != 0 { + _9 = reader.readInt32() + } var _10: Int32? _10 = reader.readInt32() var _11: Int32? @@ -1071,101 +1698,163 @@ public extension Api { _14 = Api.parse(reader, signature: signature) as? Api.PeerNotifySettings } var _15: Api.ExportedChatInvite? - if Int(_1!) & Int(1 << 23) != 0 {if let signature = reader.readInt32() { - _15 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite - } } + if Int(_1!) & Int(1 << 23) != 0 { + if let signature = reader.readInt32() { + _15 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite + } + } var _16: [Api.BotInfo]? if let _ = reader.readInt32() { _16 = Api.parseVector(reader, elementSignature: 0, elementType: Api.BotInfo.self) } var _17: Int64? - if Int(_1!) & Int(1 << 4) != 0 {_17 = reader.readInt64() } + if Int(_1!) & Int(1 << 4) != 0 { + _17 = reader.readInt64() + } var _18: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_18 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _18 = reader.readInt32() + } var _19: Int32? - if Int(_1!) & Int(1 << 5) != 0 {_19 = reader.readInt32() } + if Int(_1!) & Int(1 << 5) != 0 { + _19 = reader.readInt32() + } var _20: Api.StickerSet? - if Int(_1!) & Int(1 << 8) != 0 {if let signature = reader.readInt32() { - _20 = Api.parse(reader, signature: signature) as? Api.StickerSet - } } + if Int(_1!) & Int(1 << 8) != 0 { + if let signature = reader.readInt32() { + _20 = Api.parse(reader, signature: signature) as? Api.StickerSet + } + } var _21: Int32? - if Int(_1!) & Int(1 << 9) != 0 {_21 = reader.readInt32() } + if Int(_1!) & Int(1 << 9) != 0 { + _21 = reader.readInt32() + } var _22: Int32? - if Int(_1!) & Int(1 << 11) != 0 {_22 = reader.readInt32() } + if Int(_1!) & Int(1 << 11) != 0 { + _22 = reader.readInt32() + } var _23: Int64? - if Int(_1!) & Int(1 << 14) != 0 {_23 = reader.readInt64() } + if Int(_1!) & Int(1 << 14) != 0 { + _23 = reader.readInt64() + } var _24: Api.ChannelLocation? - if Int(_1!) & Int(1 << 15) != 0 {if let signature = reader.readInt32() { - _24 = Api.parse(reader, signature: signature) as? Api.ChannelLocation - } } + if Int(_1!) & Int(1 << 15) != 0 { + if let signature = reader.readInt32() { + _24 = Api.parse(reader, signature: signature) as? Api.ChannelLocation + } + } var _25: Int32? - if Int(_1!) & Int(1 << 17) != 0 {_25 = reader.readInt32() } + if Int(_1!) & Int(1 << 17) != 0 { + _25 = reader.readInt32() + } var _26: Int32? - if Int(_1!) & Int(1 << 18) != 0 {_26 = reader.readInt32() } + if Int(_1!) & Int(1 << 18) != 0 { + _26 = reader.readInt32() + } var _27: Int32? - if Int(_1!) & Int(1 << 12) != 0 {_27 = reader.readInt32() } + if Int(_1!) & Int(1 << 12) != 0 { + _27 = reader.readInt32() + } var _28: Int32? _28 = reader.readInt32() var _29: Api.InputGroupCall? - if Int(_1!) & Int(1 << 21) != 0 {if let signature = reader.readInt32() { - _29 = Api.parse(reader, signature: signature) as? Api.InputGroupCall - } } + if Int(_1!) & Int(1 << 21) != 0 { + if let signature = reader.readInt32() { + _29 = Api.parse(reader, signature: signature) as? Api.InputGroupCall + } + } var _30: Int32? - if Int(_1!) & Int(1 << 24) != 0 {_30 = reader.readInt32() } + if Int(_1!) & Int(1 << 24) != 0 { + _30 = reader.readInt32() + } var _31: [String]? - if Int(_1!) & Int(1 << 25) != 0 {if let _ = reader.readInt32() { - _31 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) - } } + if Int(_1!) & Int(1 << 25) != 0 { + if let _ = reader.readInt32() { + _31 = Api.parseVector(reader, elementSignature: -1255641564, elementType: String.self) + } + } var _32: Api.Peer? - if Int(_1!) & Int(1 << 26) != 0 {if let signature = reader.readInt32() { - _32 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 26) != 0 { + if let signature = reader.readInt32() { + _32 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _33: String? - if Int(_1!) & Int(1 << 27) != 0 {_33 = parseString(reader) } + if Int(_1!) & Int(1 << 27) != 0 { + _33 = parseString(reader) + } var _34: Int32? - if Int(_1!) & Int(1 << 28) != 0 {_34 = reader.readInt32() } + if Int(_1!) & Int(1 << 28) != 0 { + _34 = reader.readInt32() + } var _35: [Int64]? - if Int(_1!) & Int(1 << 28) != 0 {if let _ = reader.readInt32() { - _35 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) - } } + if Int(_1!) & Int(1 << 28) != 0 { + if let _ = reader.readInt32() { + _35 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) + } + } var _36: Api.Peer? - if Int(_1!) & Int(1 << 29) != 0 {if let signature = reader.readInt32() { - _36 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 29) != 0 { + if let signature = reader.readInt32() { + _36 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _37: Api.ChatReactions? - if Int(_1!) & Int(1 << 30) != 0 {if let signature = reader.readInt32() { - _37 = Api.parse(reader, signature: signature) as? Api.ChatReactions - } } + if Int(_1!) & Int(1 << 30) != 0 { + if let signature = reader.readInt32() { + _37 = Api.parse(reader, signature: signature) as? Api.ChatReactions + } + } var _38: Int32? - if Int(_2!) & Int(1 << 13) != 0 {_38 = reader.readInt32() } + if Int(_2!) & Int(1 << 13) != 0 { + _38 = reader.readInt32() + } var _39: Api.PeerStories? - if Int(_2!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _39 = Api.parse(reader, signature: signature) as? Api.PeerStories - } } + if Int(_2!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _39 = Api.parse(reader, signature: signature) as? Api.PeerStories + } + } var _40: Api.WallPaper? - if Int(_2!) & Int(1 << 7) != 0 {if let signature = reader.readInt32() { - _40 = Api.parse(reader, signature: signature) as? Api.WallPaper - } } + if Int(_2!) & Int(1 << 7) != 0 { + if let signature = reader.readInt32() { + _40 = Api.parse(reader, signature: signature) as? Api.WallPaper + } + } var _41: Int32? - if Int(_2!) & Int(1 << 8) != 0 {_41 = reader.readInt32() } + if Int(_2!) & Int(1 << 8) != 0 { + _41 = reader.readInt32() + } var _42: Int32? - if Int(_2!) & Int(1 << 9) != 0 {_42 = reader.readInt32() } + if Int(_2!) & Int(1 << 9) != 0 { + _42 = reader.readInt32() + } var _43: Api.StickerSet? - if Int(_2!) & Int(1 << 10) != 0 {if let signature = reader.readInt32() { - _43 = Api.parse(reader, signature: signature) as? Api.StickerSet - } } + if Int(_2!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _43 = Api.parse(reader, signature: signature) as? Api.StickerSet + } + } var _44: Api.BotVerification? - if Int(_2!) & Int(1 << 17) != 0 {if let signature = reader.readInt32() { - _44 = Api.parse(reader, signature: signature) as? Api.BotVerification - } } + if Int(_2!) & Int(1 << 17) != 0 { + if let signature = reader.readInt32() { + _44 = Api.parse(reader, signature: signature) as? Api.BotVerification + } + } var _45: Int32? - if Int(_2!) & Int(1 << 18) != 0 {_45 = reader.readInt32() } + if Int(_2!) & Int(1 << 18) != 0 { + _45 = reader.readInt32() + } var _46: Int64? - if Int(_2!) & Int(1 << 21) != 0 {_46 = reader.readInt64() } + if Int(_2!) & Int(1 << 21) != 0 { + _46 = reader.readInt64() + } var _47: Api.ProfileTab? - if Int(_2!) & Int(1 << 22) != 0 {if let signature = reader.readInt32() { - _47 = Api.parse(reader, signature: signature) as? Api.ProfileTab - } } + if Int(_2!) & Int(1 << 22) != 0 { + if let signature = reader.readInt32() { + _47 = Api.parse(reader, signature: signature) as? Api.ProfileTab + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -1213,54 +1902,12 @@ public extension Api { let _c45 = (Int(_2!) & Int(1 << 18) == 0) || _45 != nil let _c46 = (Int(_2!) & Int(1 << 21) == 0) || _46 != nil let _c47 = (Int(_2!) & Int(1 << 22) == 0) || _47 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - if !_c16 { return nil } - if !_c17 { return nil } - if !_c18 { return nil } - if !_c19 { return nil } - if !_c20 { return nil } - if !_c21 { return nil } - if !_c22 { return nil } - if !_c23 { return nil } - if !_c24 { return nil } - if !_c25 { return nil } - if !_c26 { return nil } - if !_c27 { return nil } - if !_c28 { return nil } - if !_c29 { return nil } - if !_c30 { return nil } - if !_c31 { return nil } - if !_c32 { return nil } - if !_c33 { return nil } - if !_c34 { return nil } - if !_c35 { return nil } - if !_c36 { return nil } - if !_c37 { return nil } - if !_c38 { return nil } - if !_c39 { return nil } - if !_c40 { return nil } - if !_c41 { return nil } - if !_c42 { return nil } - if !_c43 { return nil } - if !_c44 { return nil } - if !_c45 { return nil } - if !_c46 { return nil } - if !_c47 { return nil } - return Api.ChatFull.channelFull(flags: _1!, flags2: _2!, id: _3!, about: _4!, participantsCount: _5, adminsCount: _6, kickedCount: _7, bannedCount: _8, onlineCount: _9, readInboxMaxId: _10!, readOutboxMaxId: _11!, unreadCount: _12!, chatPhoto: _13!, notifySettings: _14!, exportedInvite: _15, botInfo: _16!, migratedFromChatId: _17, migratedFromMaxId: _18, pinnedMsgId: _19, stickerset: _20, availableMinId: _21, folderId: _22, linkedChatId: _23, location: _24, slowmodeSeconds: _25, slowmodeNextSendDate: _26, statsDc: _27, pts: _28!, call: _29, ttlPeriod: _30, pendingSuggestions: _31, groupcallDefaultJoinAs: _32, themeEmoticon: _33, requestsPending: _34, recentRequesters: _35, defaultSendAs: _36, availableReactions: _37, reactionsLimit: _38, stories: _39, wallpaper: _40, boostsApplied: _41, boostsUnrestrict: _42, emojiset: _43, botVerification: _44, stargiftsCount: _45, sendPaidMessagesStars: _46, mainTab: _47) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 && _c18 && _c19 && _c20 && _c21 && _c22 && _c23 && _c24 && _c25 && _c26 && _c27 && _c28 && _c29 && _c30 && _c31 && _c32 && _c33 && _c34 && _c35 && _c36 && _c37 && _c38 && _c39 && _c40 && _c41 && _c42 && _c43 && _c44 && _c45 && _c46 && _c47 { + return Api.ChatFull.channelFull(Cons_channelFull(flags: _1!, flags2: _2!, id: _3!, about: _4!, participantsCount: _5, adminsCount: _6, kickedCount: _7, bannedCount: _8, onlineCount: _9, readInboxMaxId: _10!, readOutboxMaxId: _11!, unreadCount: _12!, chatPhoto: _13!, notifySettings: _14!, exportedInvite: _15, botInfo: _16!, migratedFromChatId: _17, migratedFromMaxId: _18, pinnedMsgId: _19, stickerset: _20, availableMinId: _21, folderId: _22, linkedChatId: _23, location: _24, slowmodeSeconds: _25, slowmodeNextSendDate: _26, statsDc: _27, pts: _28!, call: _29, ttlPeriod: _30, pendingSuggestions: _31, groupcallDefaultJoinAs: _32, themeEmoticon: _33, requestsPending: _34, recentRequesters: _35, defaultSendAs: _36, availableReactions: _37, reactionsLimit: _38, stories: _39, wallpaper: _40, boostsApplied: _41, boostsUnrestrict: _42, emojiset: _43, botVerification: _44, stargiftsCount: _45, sendPaidMessagesStars: _46, mainTab: _47)) + } + else { + return nil + } } public static func parse_chatFull(_ reader: BufferReader) -> ChatFull? { var _1: Int32? @@ -1274,49 +1921,75 @@ public extension Api { _4 = Api.parse(reader, signature: signature) as? Api.ChatParticipants } var _5: Api.Photo? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.Photo - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.Photo + } + } var _6: Api.PeerNotifySettings? if let signature = reader.readInt32() { _6 = Api.parse(reader, signature: signature) as? Api.PeerNotifySettings } var _7: Api.ExportedChatInvite? - if Int(_1!) & Int(1 << 13) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite - } } + if Int(_1!) & Int(1 << 13) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite + } + } var _8: [Api.BotInfo]? - if Int(_1!) & Int(1 << 3) != 0 {if let _ = reader.readInt32() { - _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.BotInfo.self) - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let _ = reader.readInt32() { + _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.BotInfo.self) + } + } var _9: Int32? - if Int(_1!) & Int(1 << 6) != 0 {_9 = reader.readInt32() } + if Int(_1!) & Int(1 << 6) != 0 { + _9 = reader.readInt32() + } var _10: Int32? - if Int(_1!) & Int(1 << 11) != 0 {_10 = reader.readInt32() } + if Int(_1!) & Int(1 << 11) != 0 { + _10 = reader.readInt32() + } var _11: Api.InputGroupCall? - if Int(_1!) & Int(1 << 12) != 0 {if let signature = reader.readInt32() { - _11 = Api.parse(reader, signature: signature) as? Api.InputGroupCall - } } + if Int(_1!) & Int(1 << 12) != 0 { + if let signature = reader.readInt32() { + _11 = Api.parse(reader, signature: signature) as? Api.InputGroupCall + } + } var _12: Int32? - if Int(_1!) & Int(1 << 14) != 0 {_12 = reader.readInt32() } + if Int(_1!) & Int(1 << 14) != 0 { + _12 = reader.readInt32() + } var _13: Api.Peer? - if Int(_1!) & Int(1 << 15) != 0 {if let signature = reader.readInt32() { - _13 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 15) != 0 { + if let signature = reader.readInt32() { + _13 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _14: String? - if Int(_1!) & Int(1 << 16) != 0 {_14 = parseString(reader) } + if Int(_1!) & Int(1 << 16) != 0 { + _14 = parseString(reader) + } var _15: Int32? - if Int(_1!) & Int(1 << 17) != 0 {_15 = reader.readInt32() } + if Int(_1!) & Int(1 << 17) != 0 { + _15 = reader.readInt32() + } var _16: [Int64]? - if Int(_1!) & Int(1 << 17) != 0 {if let _ = reader.readInt32() { - _16 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) - } } + if Int(_1!) & Int(1 << 17) != 0 { + if let _ = reader.readInt32() { + _16 = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) + } + } var _17: Api.ChatReactions? - if Int(_1!) & Int(1 << 18) != 0 {if let signature = reader.readInt32() { - _17 = Api.parse(reader, signature: signature) as? Api.ChatReactions - } } + if Int(_1!) & Int(1 << 18) != 0 { + if let signature = reader.readInt32() { + _17 = Api.parse(reader, signature: signature) as? Api.ChatReactions + } + } var _18: Int32? - if Int(_1!) & Int(1 << 20) != 0 {_18 = reader.readInt32() } + if Int(_1!) & Int(1 << 20) != 0 { + _18 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -1335,90 +2008,126 @@ public extension Api { let _c16 = (Int(_1!) & Int(1 << 17) == 0) || _16 != nil let _c17 = (Int(_1!) & Int(1 << 18) == 0) || _17 != nil let _c18 = (Int(_1!) & Int(1 << 20) == 0) || _18 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - if !_c16 { return nil } - if !_c17 { return nil } - if !_c18 { return nil } - return Api.ChatFull.chatFull(flags: _1!, id: _2!, about: _3!, participants: _4!, chatPhoto: _5, notifySettings: _6!, exportedInvite: _7, botInfo: _8, pinnedMsgId: _9, folderId: _10, call: _11, ttlPeriod: _12, groupcallDefaultJoinAs: _13, themeEmoticon: _14, requestsPending: _15, recentRequesters: _16, availableReactions: _17, reactionsLimit: _18) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 && _c18 { + return Api.ChatFull.chatFull(Cons_chatFull(flags: _1!, id: _2!, about: _3!, participants: _4!, chatPhoto: _5, notifySettings: _6!, exportedInvite: _7, botInfo: _8, pinnedMsgId: _9, folderId: _10, call: _11, ttlPeriod: _12, groupcallDefaultJoinAs: _13, themeEmoticon: _14, requestsPending: _15, recentRequesters: _16, availableReactions: _17, reactionsLimit: _18)) + } + else { + return nil + } } - } } public extension Api { indirect enum ChatInvite: TypeConstructorDescription { - case chatInvite(flags: Int32, title: String, about: String?, photo: Api.Photo, participantsCount: Int32, participants: [Api.User]?, color: Int32, subscriptionPricing: Api.StarsSubscriptionPricing?, subscriptionFormId: Int64?, botVerification: Api.BotVerification?) - case chatInviteAlready(chat: Api.Chat) - case chatInvitePeek(chat: Api.Chat, expires: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatInvite(let flags, let title, let about, let photo, let participantsCount, let participants, let color, let subscriptionPricing, let subscriptionFormId, let botVerification): - if boxed { - buffer.appendInt32(1553807106) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 5) != 0 {serializeString(about!, buffer: buffer, boxed: false)} - photo.serialize(buffer, true) - serializeInt32(participantsCount, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(participants!.count)) - for item in participants! { + public class Cons_chatInvite { + public var flags: Int32 + public var title: String + public var about: String? + public var photo: Api.Photo + public var participantsCount: Int32 + public var participants: [Api.User]? + public var color: Int32 + public var subscriptionPricing: Api.StarsSubscriptionPricing? + public var subscriptionFormId: Int64? + public var botVerification: Api.BotVerification? + public init(flags: Int32, title: String, about: String?, photo: Api.Photo, participantsCount: Int32, participants: [Api.User]?, color: Int32, subscriptionPricing: Api.StarsSubscriptionPricing?, subscriptionFormId: Int64?, botVerification: Api.BotVerification?) { + self.flags = flags + self.title = title + self.about = about + self.photo = photo + self.participantsCount = participantsCount + self.participants = participants + self.color = color + self.subscriptionPricing = subscriptionPricing + self.subscriptionFormId = subscriptionFormId + self.botVerification = botVerification + } + } + public class Cons_chatInviteAlready { + public var chat: Api.Chat + public init(chat: Api.Chat) { + self.chat = chat + } + } + public class Cons_chatInvitePeek { + public var chat: Api.Chat + public var expires: Int32 + public init(chat: Api.Chat, expires: Int32) { + self.chat = chat + self.expires = expires + } + } + case chatInvite(Cons_chatInvite) + case chatInviteAlready(Cons_chatInviteAlready) + case chatInvitePeek(Cons_chatInvitePeek) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatInvite(let _data): + if boxed { + buffer.appendInt32(1553807106) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeString(_data.about!, buffer: buffer, boxed: false) + } + _data.photo.serialize(buffer, true) + serializeInt32(_data.participantsCount, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 4) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.participants!.count)) + for item in _data.participants! { item.serialize(buffer, true) - }} - serializeInt32(color, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 10) != 0 {subscriptionPricing!.serialize(buffer, true)} - if Int(flags) & Int(1 << 12) != 0 {serializeInt64(subscriptionFormId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 13) != 0 {botVerification!.serialize(buffer, true)} - break - case .chatInviteAlready(let chat): - if boxed { - buffer.appendInt32(1516793212) } - chat.serialize(buffer, true) - break - case .chatInvitePeek(let chat, let expires): - if boxed { - buffer.appendInt32(1634294960) - } - chat.serialize(buffer, true) - serializeInt32(expires, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatInvite(let flags, let title, let about, let photo, let participantsCount, let participants, let color, let subscriptionPricing, let subscriptionFormId, let botVerification): - return ("chatInvite", [("flags", flags as Any), ("title", title as Any), ("about", about as Any), ("photo", photo as Any), ("participantsCount", participantsCount as Any), ("participants", participants as Any), ("color", color as Any), ("subscriptionPricing", subscriptionPricing as Any), ("subscriptionFormId", subscriptionFormId as Any), ("botVerification", botVerification as Any)]) - case .chatInviteAlready(let chat): - return ("chatInviteAlready", [("chat", chat as Any)]) - case .chatInvitePeek(let chat, let expires): - return ("chatInvitePeek", [("chat", chat as Any), ("expires", expires as Any)]) - } - } - + } + serializeInt32(_data.color, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + _data.subscriptionPricing!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 12) != 0 { + serializeInt64(_data.subscriptionFormId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 13) != 0 { + _data.botVerification!.serialize(buffer, true) + } + break + case .chatInviteAlready(let _data): + if boxed { + buffer.appendInt32(1516793212) + } + _data.chat.serialize(buffer, true) + break + case .chatInvitePeek(let _data): + if boxed { + buffer.appendInt32(1634294960) + } + _data.chat.serialize(buffer, true) + serializeInt32(_data.expires, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatInvite(let _data): + return ("chatInvite", [("flags", _data.flags as Any), ("title", _data.title as Any), ("about", _data.about as Any), ("photo", _data.photo as Any), ("participantsCount", _data.participantsCount as Any), ("participants", _data.participants as Any), ("color", _data.color as Any), ("subscriptionPricing", _data.subscriptionPricing as Any), ("subscriptionFormId", _data.subscriptionFormId as Any), ("botVerification", _data.botVerification as Any)]) + case .chatInviteAlready(let _data): + return ("chatInviteAlready", [("chat", _data.chat as Any)]) + case .chatInvitePeek(let _data): + return ("chatInvitePeek", [("chat", _data.chat as Any), ("expires", _data.expires as Any)]) + } + } + public static func parse_chatInvite(_ reader: BufferReader) -> ChatInvite? { var _1: Int32? _1 = reader.readInt32() var _2: String? _2 = parseString(reader) var _3: String? - if Int(_1!) & Int(1 << 5) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 5) != 0 { + _3 = parseString(reader) + } var _4: Api.Photo? if let signature = reader.readInt32() { _4 = Api.parse(reader, signature: signature) as? Api.Photo @@ -1426,21 +2135,29 @@ public extension Api { var _5: Int32? _5 = reader.readInt32() var _6: [Api.User]? - if Int(_1!) & Int(1 << 4) != 0 {if let _ = reader.readInt32() { - _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let _ = reader.readInt32() { + _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + } var _7: Int32? _7 = reader.readInt32() var _8: Api.StarsSubscriptionPricing? - if Int(_1!) & Int(1 << 10) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.StarsSubscriptionPricing - } } + if Int(_1!) & Int(1 << 10) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.StarsSubscriptionPricing + } + } var _9: Int64? - if Int(_1!) & Int(1 << 12) != 0 {_9 = reader.readInt64() } + if Int(_1!) & Int(1 << 12) != 0 { + _9 = reader.readInt64() + } var _10: Api.BotVerification? - if Int(_1!) & Int(1 << 13) != 0 {if let signature = reader.readInt32() { - _10 = Api.parse(reader, signature: signature) as? Api.BotVerification - } } + if Int(_1!) & Int(1 << 13) != 0 { + if let signature = reader.readInt32() { + _10 = Api.parse(reader, signature: signature) as? Api.BotVerification + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 5) == 0) || _3 != nil @@ -1451,17 +2168,12 @@ public extension Api { let _c8 = (Int(_1!) & Int(1 << 10) == 0) || _8 != nil let _c9 = (Int(_1!) & Int(1 << 12) == 0) || _9 != nil let _c10 = (Int(_1!) & Int(1 << 13) == 0) || _10 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - return Api.ChatInvite.chatInvite(flags: _1!, title: _2!, about: _3, photo: _4!, participantsCount: _5!, participants: _6, color: _7!, subscriptionPricing: _8, subscriptionFormId: _9, botVerification: _10) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 { + return Api.ChatInvite.chatInvite(Cons_chatInvite(flags: _1!, title: _2!, about: _3, photo: _4!, participantsCount: _5!, participants: _6, color: _7!, subscriptionPricing: _8, subscriptionFormId: _9, botVerification: _10)) + } + else { + return nil + } } public static func parse_chatInviteAlready(_ reader: BufferReader) -> ChatInvite? { var _1: Api.Chat? @@ -1469,8 +2181,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.Chat } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChatInvite.chatInviteAlready(chat: _1!) + if _c1 { + return Api.ChatInvite.chatInviteAlready(Cons_chatInviteAlready(chat: _1!)) + } + else { + return nil + } } public static func parse_chatInvitePeek(_ reader: BufferReader) -> ChatInvite? { var _1: Api.Chat? @@ -1481,10 +2197,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChatInvite.chatInvitePeek(chat: _1!, expires: _2!) + if _c1 && _c2 { + return Api.ChatInvite.chatInvitePeek(Cons_chatInvitePeek(chat: _1!, expires: _2!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api40.swift b/submodules/TelegramApi/Sources/Api40.swift new file mode 100644 index 00000000..1cf0af77 --- /dev/null +++ b/submodules/TelegramApi/Sources/Api40.swift @@ -0,0 +1,13444 @@ +public extension Api.functions.account { + static func acceptAuthorization(botId: Int64, scope: String, publicKey: String, valueHashes: [Api.SecureValueHash], credentials: Api.SecureCredentialsEncrypted) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-202552205) + serializeInt64(botId, buffer: buffer, boxed: false) + serializeString(scope, buffer: buffer, boxed: false) + serializeString(publicKey, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(valueHashes.count)) + for item in valueHashes { + item.serialize(buffer, true) + } + credentials.serialize(buffer, true) + return (FunctionDescription(name: "account.acceptAuthorization", parameters: [("botId", String(describing: botId)), ("scope", String(describing: scope)), ("publicKey", String(describing: publicKey)), ("valueHashes", String(describing: valueHashes)), ("credentials", String(describing: credentials))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func cancelPasswordEmail() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1043606090) + return (FunctionDescription(name: "account.cancelPasswordEmail", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func changeAuthorizationSettings(flags: Int32, hash: Int64, encryptedRequestsDisabled: Api.Bool?, callRequestsDisabled: Api.Bool?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1089766498) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + encryptedRequestsDisabled!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 1) != 0 { + callRequestsDisabled!.serialize(buffer, true) + } + return (FunctionDescription(name: "account.changeAuthorizationSettings", parameters: [("flags", String(describing: flags)), ("hash", String(describing: hash)), ("encryptedRequestsDisabled", String(describing: encryptedRequestsDisabled)), ("callRequestsDisabled", String(describing: callRequestsDisabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func changePhone(phoneNumber: String, phoneCodeHash: String, phoneCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1891839707) + serializeString(phoneNumber, buffer: buffer, boxed: false) + serializeString(phoneCodeHash, buffer: buffer, boxed: false) + serializeString(phoneCode, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.changePhone", parameters: [("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("phoneCode", String(describing: phoneCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.User? in + let reader = BufferReader(buffer) + var result: Api.User? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.User + } + return result + }) + } +} +public extension Api.functions.account { + static func checkUsername(username: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(655677548) + serializeString(username, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.checkUsername", parameters: [("username", String(describing: username))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func clearRecentEmojiStatuses() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(404757166) + return (FunctionDescription(name: "account.clearRecentEmojiStatuses", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func confirmPasswordEmail(code: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1881204448) + serializeString(code, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.confirmPasswordEmail", parameters: [("code", String(describing: code))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func confirmPhone(phoneCodeHash: String, phoneCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1596029123) + serializeString(phoneCodeHash, buffer: buffer, boxed: false) + serializeString(phoneCode, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.confirmPhone", parameters: [("phoneCodeHash", String(describing: phoneCodeHash)), ("phoneCode", String(describing: phoneCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func createBusinessChatLink(link: Api.InputBusinessChatLink) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2007898482) + link.serialize(buffer, true) + return (FunctionDescription(name: "account.createBusinessChatLink", parameters: [("link", String(describing: link))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.BusinessChatLink? in + let reader = BufferReader(buffer) + var result: Api.BusinessChatLink? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.BusinessChatLink + } + return result + }) + } +} +public extension Api.functions.account { + static func createTheme(flags: Int32, slug: String, title: String, document: Api.InputDocument?, settings: [Api.InputThemeSettings]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1697530880) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(slug, buffer: buffer, boxed: false) + serializeString(title, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 2) != 0 { + document!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(settings!.count)) + for item in settings! { + item.serialize(buffer, true) + } + } + return (FunctionDescription(name: "account.createTheme", parameters: [("flags", String(describing: flags)), ("slug", String(describing: slug)), ("title", String(describing: title)), ("document", String(describing: document)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Theme? in + let reader = BufferReader(buffer) + var result: Api.Theme? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Theme + } + return result + }) + } +} +public extension Api.functions.account { + static func declinePasswordReset() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1284770294) + return (FunctionDescription(name: "account.declinePasswordReset", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func deleteAccount(flags: Int32, reason: String, password: Api.InputCheckPasswordSRP?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1564422284) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(reason, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + password!.serialize(buffer, true) + } + return (FunctionDescription(name: "account.deleteAccount", parameters: [("flags", String(describing: flags)), ("reason", String(describing: reason)), ("password", String(describing: password))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func deleteAutoSaveExceptions() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1404829728) + return (FunctionDescription(name: "account.deleteAutoSaveExceptions", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func deleteBusinessChatLink(slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1611085428) + serializeString(slug, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.deleteBusinessChatLink", parameters: [("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func deletePasskey(id: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-172665281) + serializeString(id, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.deletePasskey", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func deleteSecureValue(types: [Api.SecureValueType]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1199522741) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(types.count)) + for item in types { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "account.deleteSecureValue", parameters: [("types", String(describing: types))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func disablePeerConnectedBot(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1581481689) + peer.serialize(buffer, true) + return (FunctionDescription(name: "account.disablePeerConnectedBot", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func editBusinessChatLink(slug: String, link: Api.InputBusinessChatLink) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1942744913) + serializeString(slug, buffer: buffer, boxed: false) + link.serialize(buffer, true) + return (FunctionDescription(name: "account.editBusinessChatLink", parameters: [("slug", String(describing: slug)), ("link", String(describing: link))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.BusinessChatLink? in + let reader = BufferReader(buffer) + var result: Api.BusinessChatLink? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.BusinessChatLink + } + return result + }) + } +} +public extension Api.functions.account { + static func finishTakeoutSession(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(489050862) + serializeInt32(flags, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.finishTakeoutSession", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func getAccountTTL() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(150761757) + return (FunctionDescription(name: "account.getAccountTTL", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.AccountDaysTTL? in + let reader = BufferReader(buffer) + var result: Api.AccountDaysTTL? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.AccountDaysTTL + } + return result + }) + } +} +public extension Api.functions.account { + static func getAllSecureValues() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.SecureValue]>) { + let buffer = Buffer() + buffer.appendInt32(-1299661699) + return (FunctionDescription(name: "account.getAllSecureValues", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.SecureValue]? in + let reader = BufferReader(buffer) + var result: [Api.SecureValue]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureValue.self) + } + return result + }) + } +} +public extension Api.functions.account { + static func getAuthorizationForm(botId: Int64, scope: String, publicKey: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1456907910) + serializeInt64(botId, buffer: buffer, boxed: false) + serializeString(scope, buffer: buffer, boxed: false) + serializeString(publicKey, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getAuthorizationForm", parameters: [("botId", String(describing: botId)), ("scope", String(describing: scope)), ("publicKey", String(describing: publicKey))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.AuthorizationForm? in + let reader = BufferReader(buffer) + var result: Api.account.AuthorizationForm? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.AuthorizationForm + } + return result + }) + } +} +public extension Api.functions.account { + static func getAuthorizations() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-484392616) + return (FunctionDescription(name: "account.getAuthorizations", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.Authorizations? in + let reader = BufferReader(buffer) + var result: Api.account.Authorizations? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.Authorizations + } + return result + }) + } +} +public extension Api.functions.account { + static func getAutoDownloadSettings() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1457130303) + return (FunctionDescription(name: "account.getAutoDownloadSettings", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.AutoDownloadSettings? in + let reader = BufferReader(buffer) + var result: Api.account.AutoDownloadSettings? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.AutoDownloadSettings + } + return result + }) + } +} +public extension Api.functions.account { + static func getAutoSaveSettings() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1379156774) + return (FunctionDescription(name: "account.getAutoSaveSettings", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.AutoSaveSettings? in + let reader = BufferReader(buffer) + var result: Api.account.AutoSaveSettings? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.AutoSaveSettings + } + return result + }) + } +} +public extension Api.functions.account { + static func getBotBusinessConnection(connectionId: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1990746736) + serializeString(connectionId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getBotBusinessConnection", parameters: [("connectionId", String(describing: connectionId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.account { + static func getBusinessChatLinks() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1869667809) + return (FunctionDescription(name: "account.getBusinessChatLinks", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.BusinessChatLinks? in + let reader = BufferReader(buffer) + var result: Api.account.BusinessChatLinks? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.BusinessChatLinks + } + return result + }) + } +} +public extension Api.functions.account { + static func getChannelDefaultEmojiStatuses(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1999087573) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getChannelDefaultEmojiStatuses", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.EmojiStatuses? in + let reader = BufferReader(buffer) + var result: Api.account.EmojiStatuses? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.EmojiStatuses + } + return result + }) + } +} +public extension Api.functions.account { + static func getChannelRestrictedStatusEmojis(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(900325589) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getChannelRestrictedStatusEmojis", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiList? in + let reader = BufferReader(buffer) + var result: Api.EmojiList? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.EmojiList + } + return result + }) + } +} +public extension Api.functions.account { + static func getChatThemes(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-700916087) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getChatThemes", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.Themes? in + let reader = BufferReader(buffer) + var result: Api.account.Themes? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.Themes + } + return result + }) + } +} +public extension Api.functions.account { + static func getCollectibleEmojiStatuses(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(779830595) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getCollectibleEmojiStatuses", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.EmojiStatuses? in + let reader = BufferReader(buffer) + var result: Api.account.EmojiStatuses? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.EmojiStatuses + } + return result + }) + } +} +public extension Api.functions.account { + static func getConnectedBots() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1319421967) + return (FunctionDescription(name: "account.getConnectedBots", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.ConnectedBots? in + let reader = BufferReader(buffer) + var result: Api.account.ConnectedBots? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.ConnectedBots + } + return result + }) + } +} +public extension Api.functions.account { + static func getContactSignUpNotification() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1626880216) + return (FunctionDescription(name: "account.getContactSignUpNotification", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func getContentSettings() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1952756306) + return (FunctionDescription(name: "account.getContentSettings", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.ContentSettings? in + let reader = BufferReader(buffer) + var result: Api.account.ContentSettings? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.ContentSettings + } + return result + }) + } +} +public extension Api.functions.account { + static func getDefaultBackgroundEmojis(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1509246514) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getDefaultBackgroundEmojis", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiList? in + let reader = BufferReader(buffer) + var result: Api.EmojiList? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.EmojiList + } + return result + }) + } +} +public extension Api.functions.account { + static func getDefaultEmojiStatuses(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-696962170) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getDefaultEmojiStatuses", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.EmojiStatuses? in + let reader = BufferReader(buffer) + var result: Api.account.EmojiStatuses? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.EmojiStatuses + } + return result + }) + } +} +public extension Api.functions.account { + static func getDefaultGroupPhotoEmojis(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1856479058) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getDefaultGroupPhotoEmojis", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiList? in + let reader = BufferReader(buffer) + var result: Api.EmojiList? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.EmojiList + } + return result + }) + } +} +public extension Api.functions.account { + static func getDefaultProfilePhotoEmojis(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-495647960) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getDefaultProfilePhotoEmojis", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiList? in + let reader = BufferReader(buffer) + var result: Api.EmojiList? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.EmojiList + } + return result + }) + } +} +public extension Api.functions.account { + static func getGlobalPrivacySettings() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-349483786) + return (FunctionDescription(name: "account.getGlobalPrivacySettings", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.GlobalPrivacySettings? in + let reader = BufferReader(buffer) + var result: Api.GlobalPrivacySettings? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.GlobalPrivacySettings + } + return result + }) + } +} +public extension Api.functions.account { + static func getMultiWallPapers(wallpapers: [Api.InputWallPaper]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.WallPaper]>) { + let buffer = Buffer() + buffer.appendInt32(1705865692) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(wallpapers.count)) + for item in wallpapers { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "account.getMultiWallPapers", parameters: [("wallpapers", String(describing: wallpapers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.WallPaper]? in + let reader = BufferReader(buffer) + var result: [Api.WallPaper]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.WallPaper.self) + } + return result + }) + } +} +public extension Api.functions.account { + static func getNotifyExceptions(flags: Int32, peer: Api.InputNotifyPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1398240377) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + peer!.serialize(buffer, true) + } + return (FunctionDescription(name: "account.getNotifyExceptions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.account { + static func getNotifySettings(peer: Api.InputNotifyPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(313765169) + peer.serialize(buffer, true) + return (FunctionDescription(name: "account.getNotifySettings", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.PeerNotifySettings? in + let reader = BufferReader(buffer) + var result: Api.PeerNotifySettings? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.PeerNotifySettings + } + return result + }) + } +} +public extension Api.functions.account { + static func getPaidMessagesRevenue(flags: Int32, parentPeer: Api.InputPeer?, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(431639143) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + parentPeer!.serialize(buffer, true) + } + userId.serialize(buffer, true) + return (FunctionDescription(name: "account.getPaidMessagesRevenue", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.PaidMessagesRevenue? in + let reader = BufferReader(buffer) + var result: Api.account.PaidMessagesRevenue? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.PaidMessagesRevenue + } + return result + }) + } +} +public extension Api.functions.account { + static func getPasskeys() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-367063982) + return (FunctionDescription(name: "account.getPasskeys", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.Passkeys? in + let reader = BufferReader(buffer) + var result: Api.account.Passkeys? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.Passkeys + } + return result + }) + } +} +public extension Api.functions.account { + static func getPassword() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1418342645) + return (FunctionDescription(name: "account.getPassword", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.Password? in + let reader = BufferReader(buffer) + var result: Api.account.Password? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.Password + } + return result + }) + } +} +public extension Api.functions.account { + static func getPasswordSettings(password: Api.InputCheckPasswordSRP) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1663767815) + password.serialize(buffer, true) + return (FunctionDescription(name: "account.getPasswordSettings", parameters: [("password", String(describing: password))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.PasswordSettings? in + let reader = BufferReader(buffer) + var result: Api.account.PasswordSettings? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.PasswordSettings + } + return result + }) + } +} +public extension Api.functions.account { + static func getPrivacy(key: Api.InputPrivacyKey) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-623130288) + key.serialize(buffer, true) + return (FunctionDescription(name: "account.getPrivacy", parameters: [("key", String(describing: key))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.PrivacyRules? in + let reader = BufferReader(buffer) + var result: Api.account.PrivacyRules? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.PrivacyRules + } + return result + }) + } +} +public extension Api.functions.account { + static func getReactionsNotifySettings() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(115172684) + return (FunctionDescription(name: "account.getReactionsNotifySettings", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ReactionsNotifySettings? in + let reader = BufferReader(buffer) + var result: Api.ReactionsNotifySettings? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.ReactionsNotifySettings + } + return result + }) + } +} +public extension Api.functions.account { + static func getRecentEmojiStatuses(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(257392901) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getRecentEmojiStatuses", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.EmojiStatuses? in + let reader = BufferReader(buffer) + var result: Api.account.EmojiStatuses? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.EmojiStatuses + } + return result + }) + } +} +public extension Api.functions.account { + static func getSavedMusicIds(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-526557265) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getSavedMusicIds", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.SavedMusicIds? in + let reader = BufferReader(buffer) + var result: Api.account.SavedMusicIds? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.SavedMusicIds + } + return result + }) + } +} +public extension Api.functions.account { + static func getSavedRingtones(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-510647672) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getSavedRingtones", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.SavedRingtones? in + let reader = BufferReader(buffer) + var result: Api.account.SavedRingtones? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.SavedRingtones + } + return result + }) + } +} +public extension Api.functions.account { + static func getSecureValue(types: [Api.SecureValueType]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.SecureValue]>) { + let buffer = Buffer() + buffer.appendInt32(1936088002) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(types.count)) + for item in types { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "account.getSecureValue", parameters: [("types", String(describing: types))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.SecureValue]? in + let reader = BufferReader(buffer) + var result: [Api.SecureValue]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.SecureValue.self) + } + return result + }) + } +} +public extension Api.functions.account { + static func getTheme(format: String, theme: Api.InputTheme) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(978872812) + serializeString(format, buffer: buffer, boxed: false) + theme.serialize(buffer, true) + return (FunctionDescription(name: "account.getTheme", parameters: [("format", String(describing: format)), ("theme", String(describing: theme))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Theme? in + let reader = BufferReader(buffer) + var result: Api.Theme? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Theme + } + return result + }) + } +} +public extension Api.functions.account { + static func getThemes(format: String, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1913054296) + serializeString(format, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getThemes", parameters: [("format", String(describing: format)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.Themes? in + let reader = BufferReader(buffer) + var result: Api.account.Themes? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.Themes + } + return result + }) + } +} +public extension Api.functions.account { + static func getTmpPassword(password: Api.InputCheckPasswordSRP, period: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1151208273) + password.serialize(buffer, true) + serializeInt32(period, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getTmpPassword", parameters: [("password", String(describing: password)), ("period", String(describing: period))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.TmpPassword? in + let reader = BufferReader(buffer) + var result: Api.account.TmpPassword? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.TmpPassword + } + return result + }) + } +} +public extension Api.functions.account { + static func getUniqueGiftChatThemes(offset: String, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-466818615) + serializeString(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getUniqueGiftChatThemes", parameters: [("offset", String(describing: offset)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.ChatThemes? in + let reader = BufferReader(buffer) + var result: Api.account.ChatThemes? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.ChatThemes + } + return result + }) + } +} +public extension Api.functions.account { + static func getWallPaper(wallpaper: Api.InputWallPaper) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-57811990) + wallpaper.serialize(buffer, true) + return (FunctionDescription(name: "account.getWallPaper", parameters: [("wallpaper", String(describing: wallpaper))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.WallPaper? in + let reader = BufferReader(buffer) + var result: Api.WallPaper? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.WallPaper + } + return result + }) + } +} +public extension Api.functions.account { + static func getWallPapers(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(127302966) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.getWallPapers", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.WallPapers? in + let reader = BufferReader(buffer) + var result: Api.account.WallPapers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.WallPapers + } + return result + }) + } +} +public extension Api.functions.account { + static func getWebAuthorizations() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(405695855) + return (FunctionDescription(name: "account.getWebAuthorizations", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.WebAuthorizations? in + let reader = BufferReader(buffer) + var result: Api.account.WebAuthorizations? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.WebAuthorizations + } + return result + }) + } +} +public extension Api.functions.account { + static func initPasskeyRegistration() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1117079528) + return (FunctionDescription(name: "account.initPasskeyRegistration", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.PasskeyRegistrationOptions? in + let reader = BufferReader(buffer) + var result: Api.account.PasskeyRegistrationOptions? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.PasskeyRegistrationOptions + } + return result + }) + } +} +public extension Api.functions.account { + static func initTakeoutSession(flags: Int32, fileMaxSize: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1896617296) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 5) != 0 { + serializeInt64(fileMaxSize!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "account.initTakeoutSession", parameters: [("flags", String(describing: flags)), ("fileMaxSize", String(describing: fileMaxSize))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.Takeout? in + let reader = BufferReader(buffer) + var result: Api.account.Takeout? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.Takeout + } + return result + }) + } +} +public extension Api.functions.account { + static func installTheme(flags: Int32, theme: Api.InputTheme?, format: String?, baseTheme: Api.BaseTheme?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-953697477) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 1) != 0 { + theme!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 2) != 0 { + serializeString(format!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 3) != 0 { + baseTheme!.serialize(buffer, true) + } + return (FunctionDescription(name: "account.installTheme", parameters: [("flags", String(describing: flags)), ("theme", String(describing: theme)), ("format", String(describing: format)), ("baseTheme", String(describing: baseTheme))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func installWallPaper(wallpaper: Api.InputWallPaper, settings: Api.WallPaperSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-18000023) + wallpaper.serialize(buffer, true) + settings.serialize(buffer, true) + return (FunctionDescription(name: "account.installWallPaper", parameters: [("wallpaper", String(describing: wallpaper)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func invalidateSignInCodes(codes: [String]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-896866118) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(codes.count)) + for item in codes { + serializeString(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "account.invalidateSignInCodes", parameters: [("codes", String(describing: codes))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func registerDevice(flags: Int32, tokenType: Int32, token: String, appSandbox: Api.Bool, secret: Buffer, otherUids: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-326762118) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt32(tokenType, buffer: buffer, boxed: false) + serializeString(token, buffer: buffer, boxed: false) + appSandbox.serialize(buffer, true) + serializeBytes(secret, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(otherUids.count)) + for item in otherUids { + serializeInt64(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "account.registerDevice", parameters: [("flags", String(describing: flags)), ("tokenType", String(describing: tokenType)), ("token", String(describing: token)), ("appSandbox", String(describing: appSandbox)), ("secret", String(describing: secret)), ("otherUids", String(describing: otherUids))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func registerPasskey(credential: Api.InputPasskeyCredential) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1437867990) + credential.serialize(buffer, true) + return (FunctionDescription(name: "account.registerPasskey", parameters: [("credential", String(describing: credential))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Passkey? in + let reader = BufferReader(buffer) + var result: Api.Passkey? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Passkey + } + return result + }) + } +} +public extension Api.functions.account { + static func reorderUsernames(order: [String]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-279966037) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(order.count)) + for item in order { + serializeString(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "account.reorderUsernames", parameters: [("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func reportPeer(peer: Api.InputPeer, reason: Api.ReportReason, message: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-977650298) + peer.serialize(buffer, true) + reason.serialize(buffer, true) + serializeString(message, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.reportPeer", parameters: [("peer", String(describing: peer)), ("reason", String(describing: reason)), ("message", String(describing: message))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func reportProfilePhoto(peer: Api.InputPeer, photoId: Api.InputPhoto, reason: Api.ReportReason, message: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-91437323) + peer.serialize(buffer, true) + photoId.serialize(buffer, true) + reason.serialize(buffer, true) + serializeString(message, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.reportProfilePhoto", parameters: [("peer", String(describing: peer)), ("photoId", String(describing: photoId)), ("reason", String(describing: reason)), ("message", String(describing: message))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func resendPasswordEmail() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2055154197) + return (FunctionDescription(name: "account.resendPasswordEmail", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func resetAuthorization(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-545786948) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.resetAuthorization", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func resetNotifySettings() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-612493497) + return (FunctionDescription(name: "account.resetNotifySettings", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func resetPassword() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1828139493) + return (FunctionDescription(name: "account.resetPassword", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.ResetPasswordResult? in + let reader = BufferReader(buffer) + var result: Api.account.ResetPasswordResult? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.ResetPasswordResult + } + return result + }) + } +} +public extension Api.functions.account { + static func resetWallPapers() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1153722364) + return (FunctionDescription(name: "account.resetWallPapers", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func resetWebAuthorization(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(755087855) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.resetWebAuthorization", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func resetWebAuthorizations() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1747789204) + return (FunctionDescription(name: "account.resetWebAuthorizations", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func resolveBusinessChatLink(slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1418913262) + serializeString(slug, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.resolveBusinessChatLink", parameters: [("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.ResolvedBusinessChatLinks? in + let reader = BufferReader(buffer) + var result: Api.account.ResolvedBusinessChatLinks? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.ResolvedBusinessChatLinks + } + return result + }) + } +} +public extension Api.functions.account { + static func saveAutoDownloadSettings(flags: Int32, settings: Api.AutoDownloadSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1995661875) + serializeInt32(flags, buffer: buffer, boxed: false) + settings.serialize(buffer, true) + return (FunctionDescription(name: "account.saveAutoDownloadSettings", parameters: [("flags", String(describing: flags)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func saveAutoSaveSettings(flags: Int32, peer: Api.InputPeer?, settings: Api.AutoSaveSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-694451359) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 3) != 0 { + peer!.serialize(buffer, true) + } + settings.serialize(buffer, true) + return (FunctionDescription(name: "account.saveAutoSaveSettings", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func saveMusic(flags: Int32, id: Api.InputDocument, afterId: Api.InputDocument?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1301859671) + serializeInt32(flags, buffer: buffer, boxed: false) + id.serialize(buffer, true) + if Int(flags) & Int(1 << 1) != 0 { + afterId!.serialize(buffer, true) + } + return (FunctionDescription(name: "account.saveMusic", parameters: [("flags", String(describing: flags)), ("id", String(describing: id)), ("afterId", String(describing: afterId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func saveRingtone(id: Api.InputDocument, unsave: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1038768899) + id.serialize(buffer, true) + unsave.serialize(buffer, true) + return (FunctionDescription(name: "account.saveRingtone", parameters: [("id", String(describing: id)), ("unsave", String(describing: unsave))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.SavedRingtone? in + let reader = BufferReader(buffer) + var result: Api.account.SavedRingtone? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.SavedRingtone + } + return result + }) + } +} +public extension Api.functions.account { + static func saveSecureValue(value: Api.InputSecureValue, secureSecretId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1986010339) + value.serialize(buffer, true) + serializeInt64(secureSecretId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.saveSecureValue", parameters: [("value", String(describing: value)), ("secureSecretId", String(describing: secureSecretId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.SecureValue? in + let reader = BufferReader(buffer) + var result: Api.SecureValue? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.SecureValue + } + return result + }) + } +} +public extension Api.functions.account { + static func saveTheme(theme: Api.InputTheme, unsave: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-229175188) + theme.serialize(buffer, true) + unsave.serialize(buffer, true) + return (FunctionDescription(name: "account.saveTheme", parameters: [("theme", String(describing: theme)), ("unsave", String(describing: unsave))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func saveWallPaper(wallpaper: Api.InputWallPaper, unsave: Api.Bool, settings: Api.WallPaperSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1817860919) + wallpaper.serialize(buffer, true) + unsave.serialize(buffer, true) + settings.serialize(buffer, true) + return (FunctionDescription(name: "account.saveWallPaper", parameters: [("wallpaper", String(describing: wallpaper)), ("unsave", String(describing: unsave)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func sendChangePhoneCode(phoneNumber: String, settings: Api.CodeSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2108208411) + serializeString(phoneNumber, buffer: buffer, boxed: false) + settings.serialize(buffer, true) + return (FunctionDescription(name: "account.sendChangePhoneCode", parameters: [("phoneNumber", String(describing: phoneNumber)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.SentCode? in + let reader = BufferReader(buffer) + var result: Api.auth.SentCode? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.SentCode + } + return result + }) + } +} +public extension Api.functions.account { + static func sendConfirmPhoneCode(hash: String, settings: Api.CodeSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(457157256) + serializeString(hash, buffer: buffer, boxed: false) + settings.serialize(buffer, true) + return (FunctionDescription(name: "account.sendConfirmPhoneCode", parameters: [("hash", String(describing: hash)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.SentCode? in + let reader = BufferReader(buffer) + var result: Api.auth.SentCode? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.SentCode + } + return result + }) + } +} +public extension Api.functions.account { + static func sendVerifyEmailCode(purpose: Api.EmailVerifyPurpose, email: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1730136133) + purpose.serialize(buffer, true) + serializeString(email, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.sendVerifyEmailCode", parameters: [("purpose", String(describing: purpose)), ("email", String(describing: email))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.SentEmailCode? in + let reader = BufferReader(buffer) + var result: Api.account.SentEmailCode? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.SentEmailCode + } + return result + }) + } +} +public extension Api.functions.account { + static func sendVerifyPhoneCode(phoneNumber: String, settings: Api.CodeSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1516022023) + serializeString(phoneNumber, buffer: buffer, boxed: false) + settings.serialize(buffer, true) + return (FunctionDescription(name: "account.sendVerifyPhoneCode", parameters: [("phoneNumber", String(describing: phoneNumber)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.SentCode? in + let reader = BufferReader(buffer) + var result: Api.auth.SentCode? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.SentCode + } + return result + }) + } +} +public extension Api.functions.account { + static func setAccountTTL(ttl: Api.AccountDaysTTL) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(608323678) + ttl.serialize(buffer, true) + return (FunctionDescription(name: "account.setAccountTTL", parameters: [("ttl", String(describing: ttl))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func setAuthorizationTTL(authorizationTtlDays: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1081501024) + serializeInt32(authorizationTtlDays, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.setAuthorizationTTL", parameters: [("authorizationTtlDays", String(describing: authorizationTtlDays))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func setContactSignUpNotification(silent: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-806076575) + silent.serialize(buffer, true) + return (FunctionDescription(name: "account.setContactSignUpNotification", parameters: [("silent", String(describing: silent))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func setContentSettings(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1250643605) + serializeInt32(flags, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.setContentSettings", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func setGlobalPrivacySettings(settings: Api.GlobalPrivacySettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(517647042) + settings.serialize(buffer, true) + return (FunctionDescription(name: "account.setGlobalPrivacySettings", parameters: [("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.GlobalPrivacySettings? in + let reader = BufferReader(buffer) + var result: Api.GlobalPrivacySettings? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.GlobalPrivacySettings + } + return result + }) + } +} +public extension Api.functions.account { + static func setMainProfileTab(tab: Api.ProfileTab) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1575909552) + tab.serialize(buffer, true) + return (FunctionDescription(name: "account.setMainProfileTab", parameters: [("tab", String(describing: tab))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func setPrivacy(key: Api.InputPrivacyKey, rules: [Api.InputPrivacyRule]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-906486552) + key.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(rules.count)) + for item in rules { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "account.setPrivacy", parameters: [("key", String(describing: key)), ("rules", String(describing: rules))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.PrivacyRules? in + let reader = BufferReader(buffer) + var result: Api.account.PrivacyRules? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.PrivacyRules + } + return result + }) + } +} +public extension Api.functions.account { + static func setReactionsNotifySettings(settings: Api.ReactionsNotifySettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(829220168) + settings.serialize(buffer, true) + return (FunctionDescription(name: "account.setReactionsNotifySettings", parameters: [("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ReactionsNotifySettings? in + let reader = BufferReader(buffer) + var result: Api.ReactionsNotifySettings? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.ReactionsNotifySettings + } + return result + }) + } +} +public extension Api.functions.account { + static func toggleConnectedBotPaused(peer: Api.InputPeer, paused: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1684934807) + peer.serialize(buffer, true) + paused.serialize(buffer, true) + return (FunctionDescription(name: "account.toggleConnectedBotPaused", parameters: [("peer", String(describing: peer)), ("paused", String(describing: paused))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func toggleNoPaidMessagesException(flags: Int32, parentPeer: Api.InputPeer?, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-30483850) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 1) != 0 { + parentPeer!.serialize(buffer, true) + } + userId.serialize(buffer, true) + return (FunctionDescription(name: "account.toggleNoPaidMessagesException", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func toggleSponsoredMessages(enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1176919155) + enabled.serialize(buffer, true) + return (FunctionDescription(name: "account.toggleSponsoredMessages", parameters: [("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func toggleUsername(username: String, active: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1490465654) + serializeString(username, buffer: buffer, boxed: false) + active.serialize(buffer, true) + return (FunctionDescription(name: "account.toggleUsername", parameters: [("username", String(describing: username)), ("active", String(describing: active))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func unregisterDevice(tokenType: Int32, token: String, otherUids: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1779249670) + serializeInt32(tokenType, buffer: buffer, boxed: false) + serializeString(token, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(otherUids.count)) + for item in otherUids { + serializeInt64(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "account.unregisterDevice", parameters: [("tokenType", String(describing: tokenType)), ("token", String(describing: token)), ("otherUids", String(describing: otherUids))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func updateBirthday(flags: Int32, birthday: Api.Birthday?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-865203183) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + birthday!.serialize(buffer, true) + } + return (FunctionDescription(name: "account.updateBirthday", parameters: [("flags", String(describing: flags)), ("birthday", String(describing: birthday))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func updateBusinessAwayMessage(flags: Int32, message: Api.InputBusinessAwayMessage?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1570078811) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + message!.serialize(buffer, true) + } + return (FunctionDescription(name: "account.updateBusinessAwayMessage", parameters: [("flags", String(describing: flags)), ("message", String(describing: message))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func updateBusinessGreetingMessage(flags: Int32, message: Api.InputBusinessGreetingMessage?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1724755908) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + message!.serialize(buffer, true) + } + return (FunctionDescription(name: "account.updateBusinessGreetingMessage", parameters: [("flags", String(describing: flags)), ("message", String(describing: message))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func updateBusinessIntro(flags: Int32, intro: Api.InputBusinessIntro?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1508585420) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + intro!.serialize(buffer, true) + } + return (FunctionDescription(name: "account.updateBusinessIntro", parameters: [("flags", String(describing: flags)), ("intro", String(describing: intro))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func updateBusinessLocation(flags: Int32, geoPoint: Api.InputGeoPoint?, address: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1637149926) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 1) != 0 { + geoPoint!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 0) != 0 { + serializeString(address!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "account.updateBusinessLocation", parameters: [("flags", String(describing: flags)), ("geoPoint", String(describing: geoPoint)), ("address", String(describing: address))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func updateBusinessWorkHours(flags: Int32, businessWorkHours: Api.BusinessWorkHours?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1258348646) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + businessWorkHours!.serialize(buffer, true) + } + return (FunctionDescription(name: "account.updateBusinessWorkHours", parameters: [("flags", String(describing: flags)), ("businessWorkHours", String(describing: businessWorkHours))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func updateColor(flags: Int32, color: Api.PeerColor?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1749885262) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 2) != 0 { + color!.serialize(buffer, true) + } + return (FunctionDescription(name: "account.updateColor", parameters: [("flags", String(describing: flags)), ("color", String(describing: color))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func updateConnectedBot(flags: Int32, rights: Api.BusinessBotRights?, bot: Api.InputUser, recipients: Api.InputBusinessBotRecipients) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1721797758) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + rights!.serialize(buffer, true) + } + bot.serialize(buffer, true) + recipients.serialize(buffer, true) + return (FunctionDescription(name: "account.updateConnectedBot", parameters: [("flags", String(describing: flags)), ("rights", String(describing: rights)), ("bot", String(describing: bot)), ("recipients", String(describing: recipients))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.account { + static func updateDeviceLocked(period: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(954152242) + serializeInt32(period, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.updateDeviceLocked", parameters: [("period", String(describing: period))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func updateEmojiStatus(emojiStatus: Api.EmojiStatus) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-70001045) + emojiStatus.serialize(buffer, true) + return (FunctionDescription(name: "account.updateEmojiStatus", parameters: [("emojiStatus", String(describing: emojiStatus))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func updateNotifySettings(peer: Api.InputNotifyPeer, settings: Api.InputPeerNotifySettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2067899501) + peer.serialize(buffer, true) + settings.serialize(buffer, true) + return (FunctionDescription(name: "account.updateNotifySettings", parameters: [("peer", String(describing: peer)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func updatePasswordSettings(password: Api.InputCheckPasswordSRP, newSettings: Api.account.PasswordInputSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1516564433) + password.serialize(buffer, true) + newSettings.serialize(buffer, true) + return (FunctionDescription(name: "account.updatePasswordSettings", parameters: [("password", String(describing: password)), ("newSettings", String(describing: newSettings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func updatePersonalChannel(channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-649919008) + channel.serialize(buffer, true) + return (FunctionDescription(name: "account.updatePersonalChannel", parameters: [("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func updateProfile(flags: Int32, firstName: String?, lastName: String?, about: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2018596725) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(firstName!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeString(lastName!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + serializeString(about!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "account.updateProfile", parameters: [("flags", String(describing: flags)), ("firstName", String(describing: firstName)), ("lastName", String(describing: lastName)), ("about", String(describing: about))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.User? in + let reader = BufferReader(buffer) + var result: Api.User? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.User + } + return result + }) + } +} +public extension Api.functions.account { + static func updateStatus(offline: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1713919532) + offline.serialize(buffer, true) + return (FunctionDescription(name: "account.updateStatus", parameters: [("offline", String(describing: offline))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.account { + static func updateTheme(flags: Int32, format: String, theme: Api.InputTheme, slug: String?, title: String?, document: Api.InputDocument?, settings: [Api.InputThemeSettings]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(737414348) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(format, buffer: buffer, boxed: false) + theme.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(slug!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeString(title!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + document!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(settings!.count)) + for item in settings! { + item.serialize(buffer, true) + } + } + return (FunctionDescription(name: "account.updateTheme", parameters: [("flags", String(describing: flags)), ("format", String(describing: format)), ("theme", String(describing: theme)), ("slug", String(describing: slug)), ("title", String(describing: title)), ("document", String(describing: document)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Theme? in + let reader = BufferReader(buffer) + var result: Api.Theme? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Theme + } + return result + }) + } +} +public extension Api.functions.account { + static func updateUsername(username: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1040964988) + serializeString(username, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.updateUsername", parameters: [("username", String(describing: username))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.User? in + let reader = BufferReader(buffer) + var result: Api.User? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.User + } + return result + }) + } +} +public extension Api.functions.account { + static func uploadRingtone(file: Api.InputFile, fileName: String, mimeType: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2095414366) + file.serialize(buffer, true) + serializeString(fileName, buffer: buffer, boxed: false) + serializeString(mimeType, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.uploadRingtone", parameters: [("file", String(describing: file)), ("fileName", String(describing: fileName)), ("mimeType", String(describing: mimeType))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Document? in + let reader = BufferReader(buffer) + var result: Api.Document? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Document + } + return result + }) + } +} +public extension Api.functions.account { + static func uploadTheme(flags: Int32, file: Api.InputFile, thumb: Api.InputFile?, fileName: String, mimeType: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(473805619) + serializeInt32(flags, buffer: buffer, boxed: false) + file.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + thumb!.serialize(buffer, true) + } + serializeString(fileName, buffer: buffer, boxed: false) + serializeString(mimeType, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.uploadTheme", parameters: [("flags", String(describing: flags)), ("file", String(describing: file)), ("thumb", String(describing: thumb)), ("fileName", String(describing: fileName)), ("mimeType", String(describing: mimeType))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Document? in + let reader = BufferReader(buffer) + var result: Api.Document? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Document + } + return result + }) + } +} +public extension Api.functions.account { + static func uploadWallPaper(flags: Int32, file: Api.InputFile, mimeType: String, settings: Api.WallPaperSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-476410109) + serializeInt32(flags, buffer: buffer, boxed: false) + file.serialize(buffer, true) + serializeString(mimeType, buffer: buffer, boxed: false) + settings.serialize(buffer, true) + return (FunctionDescription(name: "account.uploadWallPaper", parameters: [("flags", String(describing: flags)), ("file", String(describing: file)), ("mimeType", String(describing: mimeType)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.WallPaper? in + let reader = BufferReader(buffer) + var result: Api.WallPaper? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.WallPaper + } + return result + }) + } +} +public extension Api.functions.account { + static func verifyEmail(purpose: Api.EmailVerifyPurpose, verification: Api.EmailVerification) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(53322959) + purpose.serialize(buffer, true) + verification.serialize(buffer, true) + return (FunctionDescription(name: "account.verifyEmail", parameters: [("purpose", String(describing: purpose)), ("verification", String(describing: verification))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.account.EmailVerified? in + let reader = BufferReader(buffer) + var result: Api.account.EmailVerified? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.account.EmailVerified + } + return result + }) + } +} +public extension Api.functions.account { + static func verifyPhone(phoneNumber: String, phoneCodeHash: String, phoneCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1305716726) + serializeString(phoneNumber, buffer: buffer, boxed: false) + serializeString(phoneCodeHash, buffer: buffer, boxed: false) + serializeString(phoneCode, buffer: buffer, boxed: false) + return (FunctionDescription(name: "account.verifyPhone", parameters: [("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("phoneCode", String(describing: phoneCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.auth { + static func acceptLoginToken(token: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-392909491) + serializeBytes(token, buffer: buffer, boxed: false) + return (FunctionDescription(name: "auth.acceptLoginToken", parameters: [("token", String(describing: token))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Authorization? in + let reader = BufferReader(buffer) + var result: Api.Authorization? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Authorization + } + return result + }) + } +} +public extension Api.functions.auth { + static func bindTempAuthKey(permAuthKeyId: Int64, nonce: Int64, expiresAt: Int32, encryptedMessage: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-841733627) + serializeInt64(permAuthKeyId, buffer: buffer, boxed: false) + serializeInt64(nonce, buffer: buffer, boxed: false) + serializeInt32(expiresAt, buffer: buffer, boxed: false) + serializeBytes(encryptedMessage, buffer: buffer, boxed: false) + return (FunctionDescription(name: "auth.bindTempAuthKey", parameters: [("permAuthKeyId", String(describing: permAuthKeyId)), ("nonce", String(describing: nonce)), ("expiresAt", String(describing: expiresAt)), ("encryptedMessage", String(describing: encryptedMessage))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.auth { + static func cancelCode(phoneNumber: String, phoneCodeHash: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(520357240) + serializeString(phoneNumber, buffer: buffer, boxed: false) + serializeString(phoneCodeHash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "auth.cancelCode", parameters: [("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.auth { + static func checkPaidAuth(phoneNumber: String, phoneCodeHash: String, formId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1457889180) + serializeString(phoneNumber, buffer: buffer, boxed: false) + serializeString(phoneCodeHash, buffer: buffer, boxed: false) + serializeInt64(formId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "auth.checkPaidAuth", parameters: [("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("formId", String(describing: formId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.SentCode? in + let reader = BufferReader(buffer) + var result: Api.auth.SentCode? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.SentCode + } + return result + }) + } +} +public extension Api.functions.auth { + static func checkPassword(password: Api.InputCheckPasswordSRP) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-779399914) + password.serialize(buffer, true) + return (FunctionDescription(name: "auth.checkPassword", parameters: [("password", String(describing: password))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in + let reader = BufferReader(buffer) + var result: Api.auth.Authorization? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.Authorization + } + return result + }) + } +} +public extension Api.functions.auth { + static func checkRecoveryPassword(code: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(221691769) + serializeString(code, buffer: buffer, boxed: false) + return (FunctionDescription(name: "auth.checkRecoveryPassword", parameters: [("code", String(describing: code))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.auth { + static func dropTempAuthKeys(exceptAuthKeys: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1907842680) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(exceptAuthKeys.count)) + for item in exceptAuthKeys { + serializeInt64(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "auth.dropTempAuthKeys", parameters: [("exceptAuthKeys", String(describing: exceptAuthKeys))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.auth { + static func exportAuthorization(dcId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-440401971) + serializeInt32(dcId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "auth.exportAuthorization", parameters: [("dcId", String(describing: dcId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.ExportedAuthorization? in + let reader = BufferReader(buffer) + var result: Api.auth.ExportedAuthorization? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.ExportedAuthorization + } + return result + }) + } +} +public extension Api.functions.auth { + static func exportLoginToken(apiId: Int32, apiHash: String, exceptIds: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1210022402) + serializeInt32(apiId, buffer: buffer, boxed: false) + serializeString(apiHash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(exceptIds.count)) + for item in exceptIds { + serializeInt64(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "auth.exportLoginToken", parameters: [("apiId", String(describing: apiId)), ("apiHash", String(describing: apiHash)), ("exceptIds", String(describing: exceptIds))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.LoginToken? in + let reader = BufferReader(buffer) + var result: Api.auth.LoginToken? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.LoginToken + } + return result + }) + } +} +public extension Api.functions.auth { + static func finishPasskeyLogin(flags: Int32, credential: Api.InputPasskeyCredential, fromDcId: Int32?, fromAuthKeyId: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1739084537) + serializeInt32(flags, buffer: buffer, boxed: false) + credential.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(fromDcId!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 0) != 0 { + serializeInt64(fromAuthKeyId!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "auth.finishPasskeyLogin", parameters: [("flags", String(describing: flags)), ("credential", String(describing: credential)), ("fromDcId", String(describing: fromDcId)), ("fromAuthKeyId", String(describing: fromAuthKeyId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in + let reader = BufferReader(buffer) + var result: Api.auth.Authorization? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.Authorization + } + return result + }) + } +} +public extension Api.functions.auth { + static func importAuthorization(id: Int64, bytes: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1518699091) + serializeInt64(id, buffer: buffer, boxed: false) + serializeBytes(bytes, buffer: buffer, boxed: false) + return (FunctionDescription(name: "auth.importAuthorization", parameters: [("id", String(describing: id)), ("bytes", String(describing: bytes))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in + let reader = BufferReader(buffer) + var result: Api.auth.Authorization? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.Authorization + } + return result + }) + } +} +public extension Api.functions.auth { + static func importBotAuthorization(flags: Int32, apiId: Int32, apiHash: String, botAuthToken: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1738800940) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt32(apiId, buffer: buffer, boxed: false) + serializeString(apiHash, buffer: buffer, boxed: false) + serializeString(botAuthToken, buffer: buffer, boxed: false) + return (FunctionDescription(name: "auth.importBotAuthorization", parameters: [("flags", String(describing: flags)), ("apiId", String(describing: apiId)), ("apiHash", String(describing: apiHash)), ("botAuthToken", String(describing: botAuthToken))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in + let reader = BufferReader(buffer) + var result: Api.auth.Authorization? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.Authorization + } + return result + }) + } +} +public extension Api.functions.auth { + static func importLoginToken(token: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1783866140) + serializeBytes(token, buffer: buffer, boxed: false) + return (FunctionDescription(name: "auth.importLoginToken", parameters: [("token", String(describing: token))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.LoginToken? in + let reader = BufferReader(buffer) + var result: Api.auth.LoginToken? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.LoginToken + } + return result + }) + } +} +public extension Api.functions.auth { + static func importWebTokenAuthorization(apiId: Int32, apiHash: String, webAuthToken: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(767062953) + serializeInt32(apiId, buffer: buffer, boxed: false) + serializeString(apiHash, buffer: buffer, boxed: false) + serializeString(webAuthToken, buffer: buffer, boxed: false) + return (FunctionDescription(name: "auth.importWebTokenAuthorization", parameters: [("apiId", String(describing: apiId)), ("apiHash", String(describing: apiHash)), ("webAuthToken", String(describing: webAuthToken))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in + let reader = BufferReader(buffer) + var result: Api.auth.Authorization? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.Authorization + } + return result + }) + } +} +public extension Api.functions.auth { + static func initPasskeyLogin(apiId: Int32, apiHash: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1368051895) + serializeInt32(apiId, buffer: buffer, boxed: false) + serializeString(apiHash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "auth.initPasskeyLogin", parameters: [("apiId", String(describing: apiId)), ("apiHash", String(describing: apiHash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.PasskeyLoginOptions? in + let reader = BufferReader(buffer) + var result: Api.auth.PasskeyLoginOptions? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.PasskeyLoginOptions + } + return result + }) + } +} +public extension Api.functions.auth { + static func logOut() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1047706137) + return (FunctionDescription(name: "auth.logOut", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.LoggedOut? in + let reader = BufferReader(buffer) + var result: Api.auth.LoggedOut? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.LoggedOut + } + return result + }) + } +} +public extension Api.functions.auth { + static func recoverPassword(flags: Int32, code: String, newSettings: Api.account.PasswordInputSettings?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(923364464) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(code, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + newSettings!.serialize(buffer, true) + } + return (FunctionDescription(name: "auth.recoverPassword", parameters: [("flags", String(describing: flags)), ("code", String(describing: code)), ("newSettings", String(describing: newSettings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in + let reader = BufferReader(buffer) + var result: Api.auth.Authorization? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.Authorization + } + return result + }) + } +} +public extension Api.functions.auth { + static func reportMissingCode(phoneNumber: String, phoneCodeHash: String, mnc: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-878841866) + serializeString(phoneNumber, buffer: buffer, boxed: false) + serializeString(phoneCodeHash, buffer: buffer, boxed: false) + serializeString(mnc, buffer: buffer, boxed: false) + return (FunctionDescription(name: "auth.reportMissingCode", parameters: [("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("mnc", String(describing: mnc))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.auth { + static func requestFirebaseSms(flags: Int32, phoneNumber: String, phoneCodeHash: String, safetyNetToken: String?, playIntegrityToken: String?, iosPushSecret: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1908857314) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(phoneNumber, buffer: buffer, boxed: false) + serializeString(phoneCodeHash, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(safetyNetToken!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + serializeString(playIntegrityToken!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeString(iosPushSecret!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "auth.requestFirebaseSms", parameters: [("flags", String(describing: flags)), ("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("safetyNetToken", String(describing: safetyNetToken)), ("playIntegrityToken", String(describing: playIntegrityToken)), ("iosPushSecret", String(describing: iosPushSecret))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.auth { + static func requestPasswordRecovery() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-661144474) + return (FunctionDescription(name: "auth.requestPasswordRecovery", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.PasswordRecovery? in + let reader = BufferReader(buffer) + var result: Api.auth.PasswordRecovery? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.PasswordRecovery + } + return result + }) + } +} +public extension Api.functions.auth { + static func resendCode(flags: Int32, phoneNumber: String, phoneCodeHash: String, reason: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-890997469) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(phoneNumber, buffer: buffer, boxed: false) + serializeString(phoneCodeHash, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(reason!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "auth.resendCode", parameters: [("flags", String(describing: flags)), ("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("reason", String(describing: reason))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.SentCode? in + let reader = BufferReader(buffer) + var result: Api.auth.SentCode? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.SentCode + } + return result + }) + } +} +public extension Api.functions.auth { + static func resetAuthorizations() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1616179942) + return (FunctionDescription(name: "auth.resetAuthorizations", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.auth { + static func resetLoginEmail(phoneNumber: String, phoneCodeHash: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2123760019) + serializeString(phoneNumber, buffer: buffer, boxed: false) + serializeString(phoneCodeHash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "auth.resetLoginEmail", parameters: [("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.SentCode? in + let reader = BufferReader(buffer) + var result: Api.auth.SentCode? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.SentCode + } + return result + }) + } +} +public extension Api.functions.auth { + static func sendCode(phoneNumber: String, apiId: Int32, apiHash: String, settings: Api.CodeSettings) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1502141361) + serializeString(phoneNumber, buffer: buffer, boxed: false) + serializeInt32(apiId, buffer: buffer, boxed: false) + serializeString(apiHash, buffer: buffer, boxed: false) + settings.serialize(buffer, true) + return (FunctionDescription(name: "auth.sendCode", parameters: [("phoneNumber", String(describing: phoneNumber)), ("apiId", String(describing: apiId)), ("apiHash", String(describing: apiHash)), ("settings", String(describing: settings))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.SentCode? in + let reader = BufferReader(buffer) + var result: Api.auth.SentCode? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.SentCode + } + return result + }) + } +} +public extension Api.functions.auth { + static func signIn(flags: Int32, phoneNumber: String, phoneCodeHash: String, phoneCode: String?, emailVerification: Api.EmailVerification?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1923962543) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(phoneNumber, buffer: buffer, boxed: false) + serializeString(phoneCodeHash, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(phoneCode!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + emailVerification!.serialize(buffer, true) + } + return (FunctionDescription(name: "auth.signIn", parameters: [("flags", String(describing: flags)), ("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("phoneCode", String(describing: phoneCode)), ("emailVerification", String(describing: emailVerification))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in + let reader = BufferReader(buffer) + var result: Api.auth.Authorization? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.Authorization + } + return result + }) + } +} +public extension Api.functions.auth { + static func signUp(flags: Int32, phoneNumber: String, phoneCodeHash: String, firstName: String, lastName: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1429752041) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(phoneNumber, buffer: buffer, boxed: false) + serializeString(phoneCodeHash, buffer: buffer, boxed: false) + serializeString(firstName, buffer: buffer, boxed: false) + serializeString(lastName, buffer: buffer, boxed: false) + return (FunctionDescription(name: "auth.signUp", parameters: [("flags", String(describing: flags)), ("phoneNumber", String(describing: phoneNumber)), ("phoneCodeHash", String(describing: phoneCodeHash)), ("firstName", String(describing: firstName)), ("lastName", String(describing: lastName))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.auth.Authorization? in + let reader = BufferReader(buffer) + var result: Api.auth.Authorization? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.auth.Authorization + } + return result + }) + } +} +public extension Api.functions.bots { + static func addPreviewMedia(bot: Api.InputUser, langCode: String, media: Api.InputMedia) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(397326170) + bot.serialize(buffer, true) + serializeString(langCode, buffer: buffer, boxed: false) + media.serialize(buffer, true) + return (FunctionDescription(name: "bots.addPreviewMedia", parameters: [("bot", String(describing: bot)), ("langCode", String(describing: langCode)), ("media", String(describing: media))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.BotPreviewMedia? in + let reader = BufferReader(buffer) + var result: Api.BotPreviewMedia? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.BotPreviewMedia + } + return result + }) + } +} +public extension Api.functions.bots { + static func allowSendMessage(bot: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-248323089) + bot.serialize(buffer, true) + return (FunctionDescription(name: "bots.allowSendMessage", parameters: [("bot", String(describing: bot))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.bots { + static func answerWebhookJSONQuery(queryId: Int64, data: Api.DataJSON) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-434028723) + serializeInt64(queryId, buffer: buffer, boxed: false) + data.serialize(buffer, true) + return (FunctionDescription(name: "bots.answerWebhookJSONQuery", parameters: [("queryId", String(describing: queryId)), ("data", String(describing: data))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.bots { + static func canSendMessage(bot: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(324662502) + bot.serialize(buffer, true) + return (FunctionDescription(name: "bots.canSendMessage", parameters: [("bot", String(describing: bot))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.bots { + static func checkDownloadFileParams(bot: Api.InputUser, fileName: String, url: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1342666121) + bot.serialize(buffer, true) + serializeString(fileName, buffer: buffer, boxed: false) + serializeString(url, buffer: buffer, boxed: false) + return (FunctionDescription(name: "bots.checkDownloadFileParams", parameters: [("bot", String(describing: bot)), ("fileName", String(describing: fileName)), ("url", String(describing: url))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.bots { + static func deletePreviewMedia(bot: Api.InputUser, langCode: String, media: [Api.InputMedia]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(755054003) + bot.serialize(buffer, true) + serializeString(langCode, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(media.count)) + for item in media { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "bots.deletePreviewMedia", parameters: [("bot", String(describing: bot)), ("langCode", String(describing: langCode)), ("media", String(describing: media))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.bots { + static func editPreviewMedia(bot: Api.InputUser, langCode: String, media: Api.InputMedia, newMedia: Api.InputMedia) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2061148049) + bot.serialize(buffer, true) + serializeString(langCode, buffer: buffer, boxed: false) + media.serialize(buffer, true) + newMedia.serialize(buffer, true) + return (FunctionDescription(name: "bots.editPreviewMedia", parameters: [("bot", String(describing: bot)), ("langCode", String(describing: langCode)), ("media", String(describing: media)), ("newMedia", String(describing: newMedia))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.BotPreviewMedia? in + let reader = BufferReader(buffer) + var result: Api.BotPreviewMedia? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.BotPreviewMedia + } + return result + }) + } +} +public extension Api.functions.bots { + static func getAdminedBots() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.User]>) { + let buffer = Buffer() + buffer.appendInt32(-1334764157) + return (FunctionDescription(name: "bots.getAdminedBots", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.User]? in + let reader = BufferReader(buffer) + var result: [Api.User]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + return result + }) + } +} +public extension Api.functions.bots { + static func getBotCommands(scope: Api.BotCommandScope, langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.BotCommand]>) { + let buffer = Buffer() + buffer.appendInt32(-481554986) + scope.serialize(buffer, true) + serializeString(langCode, buffer: buffer, boxed: false) + return (FunctionDescription(name: "bots.getBotCommands", parameters: [("scope", String(describing: scope)), ("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.BotCommand]? in + let reader = BufferReader(buffer) + var result: [Api.BotCommand]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.BotCommand.self) + } + return result + }) + } +} +public extension Api.functions.bots { + static func getBotInfo(flags: Int32, bot: Api.InputUser?, langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-589753091) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + bot!.serialize(buffer, true) + } + serializeString(langCode, buffer: buffer, boxed: false) + return (FunctionDescription(name: "bots.getBotInfo", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.bots.BotInfo? in + let reader = BufferReader(buffer) + var result: Api.bots.BotInfo? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.bots.BotInfo + } + return result + }) + } +} +public extension Api.functions.bots { + static func getBotMenuButton(userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1671369944) + userId.serialize(buffer, true) + return (FunctionDescription(name: "bots.getBotMenuButton", parameters: [("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.BotMenuButton? in + let reader = BufferReader(buffer) + var result: Api.BotMenuButton? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.BotMenuButton + } + return result + }) + } +} +public extension Api.functions.bots { + static func getBotRecommendations(bot: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1581840363) + bot.serialize(buffer, true) + return (FunctionDescription(name: "bots.getBotRecommendations", parameters: [("bot", String(describing: bot))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.users.Users? in + let reader = BufferReader(buffer) + var result: Api.users.Users? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.users.Users + } + return result + }) + } +} +public extension Api.functions.bots { + static func getPopularAppBots(offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1034878574) + serializeString(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "bots.getPopularAppBots", parameters: [("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.bots.PopularAppBots? in + let reader = BufferReader(buffer) + var result: Api.bots.PopularAppBots? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.bots.PopularAppBots + } + return result + }) + } +} +public extension Api.functions.bots { + static func getPreviewInfo(bot: Api.InputUser, langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1111143341) + bot.serialize(buffer, true) + serializeString(langCode, buffer: buffer, boxed: false) + return (FunctionDescription(name: "bots.getPreviewInfo", parameters: [("bot", String(describing: bot)), ("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.bots.PreviewInfo? in + let reader = BufferReader(buffer) + var result: Api.bots.PreviewInfo? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.bots.PreviewInfo + } + return result + }) + } +} +public extension Api.functions.bots { + static func getPreviewMedias(bot: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.BotPreviewMedia]>) { + let buffer = Buffer() + buffer.appendInt32(-1566222003) + bot.serialize(buffer, true) + return (FunctionDescription(name: "bots.getPreviewMedias", parameters: [("bot", String(describing: bot))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.BotPreviewMedia]? in + let reader = BufferReader(buffer) + var result: [Api.BotPreviewMedia]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.BotPreviewMedia.self) + } + return result + }) + } +} +public extension Api.functions.bots { + static func invokeWebViewCustomMethod(bot: Api.InputUser, customMethod: String, params: Api.DataJSON) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(142591463) + bot.serialize(buffer, true) + serializeString(customMethod, buffer: buffer, boxed: false) + params.serialize(buffer, true) + return (FunctionDescription(name: "bots.invokeWebViewCustomMethod", parameters: [("bot", String(describing: bot)), ("customMethod", String(describing: customMethod)), ("params", String(describing: params))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.DataJSON? in + let reader = BufferReader(buffer) + var result: Api.DataJSON? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.DataJSON + } + return result + }) + } +} +public extension Api.functions.bots { + static func reorderPreviewMedias(bot: Api.InputUser, langCode: String, order: [Api.InputMedia]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1238895702) + bot.serialize(buffer, true) + serializeString(langCode, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(order.count)) + for item in order { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "bots.reorderPreviewMedias", parameters: [("bot", String(describing: bot)), ("langCode", String(describing: langCode)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.bots { + static func reorderUsernames(bot: Api.InputUser, order: [String]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1760972350) + bot.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(order.count)) + for item in order { + serializeString(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "bots.reorderUsernames", parameters: [("bot", String(describing: bot)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.bots { + static func resetBotCommands(scope: Api.BotCommandScope, langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1032708345) + scope.serialize(buffer, true) + serializeString(langCode, buffer: buffer, boxed: false) + return (FunctionDescription(name: "bots.resetBotCommands", parameters: [("scope", String(describing: scope)), ("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.bots { + static func sendCustomRequest(customMethod: String, params: Api.DataJSON) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1440257555) + serializeString(customMethod, buffer: buffer, boxed: false) + params.serialize(buffer, true) + return (FunctionDescription(name: "bots.sendCustomRequest", parameters: [("customMethod", String(describing: customMethod)), ("params", String(describing: params))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.DataJSON? in + let reader = BufferReader(buffer) + var result: Api.DataJSON? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.DataJSON + } + return result + }) + } +} +public extension Api.functions.bots { + static func setBotBroadcastDefaultAdminRights(adminRights: Api.ChatAdminRights) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2021942497) + adminRights.serialize(buffer, true) + return (FunctionDescription(name: "bots.setBotBroadcastDefaultAdminRights", parameters: [("adminRights", String(describing: adminRights))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.bots { + static func setBotCommands(scope: Api.BotCommandScope, langCode: String, commands: [Api.BotCommand]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(85399130) + scope.serialize(buffer, true) + serializeString(langCode, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(commands.count)) + for item in commands { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "bots.setBotCommands", parameters: [("scope", String(describing: scope)), ("langCode", String(describing: langCode)), ("commands", String(describing: commands))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.bots { + static func setBotGroupDefaultAdminRights(adminRights: Api.ChatAdminRights) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1839281686) + adminRights.serialize(buffer, true) + return (FunctionDescription(name: "bots.setBotGroupDefaultAdminRights", parameters: [("adminRights", String(describing: adminRights))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.bots { + static func setBotInfo(flags: Int32, bot: Api.InputUser?, langCode: String, name: String?, about: String?, description: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(282013987) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 2) != 0 { + bot!.serialize(buffer, true) + } + serializeString(langCode, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 3) != 0 { + serializeString(name!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 0) != 0 { + serializeString(about!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeString(description!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "bots.setBotInfo", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("langCode", String(describing: langCode)), ("name", String(describing: name)), ("about", String(describing: about)), ("description", String(describing: description))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.bots { + static func setBotMenuButton(userId: Api.InputUser, button: Api.BotMenuButton) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1157944655) + userId.serialize(buffer, true) + button.serialize(buffer, true) + return (FunctionDescription(name: "bots.setBotMenuButton", parameters: [("userId", String(describing: userId)), ("button", String(describing: button))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.bots { + static func setCustomVerification(flags: Int32, bot: Api.InputUser?, peer: Api.InputPeer, customDescription: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1953898563) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + bot!.serialize(buffer, true) + } + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 2) != 0 { + serializeString(customDescription!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "bots.setCustomVerification", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("peer", String(describing: peer)), ("customDescription", String(describing: customDescription))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.bots { + static func toggleUserEmojiStatusPermission(bot: Api.InputUser, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(115237778) + bot.serialize(buffer, true) + enabled.serialize(buffer, true) + return (FunctionDescription(name: "bots.toggleUserEmojiStatusPermission", parameters: [("bot", String(describing: bot)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.bots { + static func toggleUsername(bot: Api.InputUser, username: String, active: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(87861619) + bot.serialize(buffer, true) + serializeString(username, buffer: buffer, boxed: false) + active.serialize(buffer, true) + return (FunctionDescription(name: "bots.toggleUsername", parameters: [("bot", String(describing: bot)), ("username", String(describing: username)), ("active", String(describing: active))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.bots { + static func updateStarRefProgram(flags: Int32, bot: Api.InputUser, commissionPermille: Int32, durationMonths: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2005621427) + serializeInt32(flags, buffer: buffer, boxed: false) + bot.serialize(buffer, true) + serializeInt32(commissionPermille, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(durationMonths!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "bots.updateStarRefProgram", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("commissionPermille", String(describing: commissionPermille)), ("durationMonths", String(describing: durationMonths))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.StarRefProgram? in + let reader = BufferReader(buffer) + var result: Api.StarRefProgram? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.StarRefProgram + } + return result + }) + } +} +public extension Api.functions.bots { + static func updateUserEmojiStatus(userId: Api.InputUser, emojiStatus: Api.EmojiStatus) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-308334395) + userId.serialize(buffer, true) + emojiStatus.serialize(buffer, true) + return (FunctionDescription(name: "bots.updateUserEmojiStatus", parameters: [("userId", String(describing: userId)), ("emojiStatus", String(describing: emojiStatus))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.channels { + static func checkSearchPostsFlood(flags: Int32, query: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(576090389) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(query!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "channels.checkSearchPostsFlood", parameters: [("flags", String(describing: flags)), ("query", String(describing: query))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.SearchPostsFlood? in + let reader = BufferReader(buffer) + var result: Api.SearchPostsFlood? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.SearchPostsFlood + } + return result + }) + } +} +public extension Api.functions.channels { + static func checkUsername(channel: Api.InputChannel, username: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(283557164) + channel.serialize(buffer, true) + serializeString(username, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.checkUsername", parameters: [("channel", String(describing: channel)), ("username", String(describing: username))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.channels { + static func convertToGigagroup(channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(187239529) + channel.serialize(buffer, true) + return (FunctionDescription(name: "channels.convertToGigagroup", parameters: [("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func createChannel(flags: Int32, title: String, about: String, geoPoint: Api.InputGeoPoint?, address: String?, ttlPeriod: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1862244601) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(title, buffer: buffer, boxed: false) + serializeString(about, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 2) != 0 { + geoPoint!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 2) != 0 { + serializeString(address!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 4) != 0 { + serializeInt32(ttlPeriod!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "channels.createChannel", parameters: [("flags", String(describing: flags)), ("title", String(describing: title)), ("about", String(describing: about)), ("geoPoint", String(describing: geoPoint)), ("address", String(describing: address)), ("ttlPeriod", String(describing: ttlPeriod))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func deactivateAllUsernames(channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(170155475) + channel.serialize(buffer, true) + return (FunctionDescription(name: "channels.deactivateAllUsernames", parameters: [("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.channels { + static func deleteChannel(channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1072619549) + channel.serialize(buffer, true) + return (FunctionDescription(name: "channels.deleteChannel", parameters: [("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func deleteHistory(flags: Int32, channel: Api.InputChannel, maxId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1683319225) + serializeInt32(flags, buffer: buffer, boxed: false) + channel.serialize(buffer, true) + serializeInt32(maxId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.deleteHistory", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel)), ("maxId", String(describing: maxId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func deleteMessages(channel: Api.InputChannel, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2067661490) + channel.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "channels.deleteMessages", parameters: [("channel", String(describing: channel)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedMessages? in + let reader = BufferReader(buffer) + var result: Api.messages.AffectedMessages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AffectedMessages + } + return result + }) + } +} +public extension Api.functions.channels { + static func deleteParticipantHistory(channel: Api.InputChannel, participant: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(913655003) + channel.serialize(buffer, true) + participant.serialize(buffer, true) + return (FunctionDescription(name: "channels.deleteParticipantHistory", parameters: [("channel", String(describing: channel)), ("participant", String(describing: participant))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedHistory? in + let reader = BufferReader(buffer) + var result: Api.messages.AffectedHistory? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AffectedHistory + } + return result + }) + } +} +public extension Api.functions.channels { + static func editAdmin(channel: Api.InputChannel, userId: Api.InputUser, adminRights: Api.ChatAdminRights, rank: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-751007486) + channel.serialize(buffer, true) + userId.serialize(buffer, true) + adminRights.serialize(buffer, true) + serializeString(rank, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.editAdmin", parameters: [("channel", String(describing: channel)), ("userId", String(describing: userId)), ("adminRights", String(describing: adminRights)), ("rank", String(describing: rank))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func editBanned(channel: Api.InputChannel, participant: Api.InputPeer, bannedRights: Api.ChatBannedRights) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1763259007) + channel.serialize(buffer, true) + participant.serialize(buffer, true) + bannedRights.serialize(buffer, true) + return (FunctionDescription(name: "channels.editBanned", parameters: [("channel", String(describing: channel)), ("participant", String(describing: participant)), ("bannedRights", String(describing: bannedRights))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func editCreator(channel: Api.InputChannel, userId: Api.InputUser, password: Api.InputCheckPasswordSRP) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1892102881) + channel.serialize(buffer, true) + userId.serialize(buffer, true) + password.serialize(buffer, true) + return (FunctionDescription(name: "channels.editCreator", parameters: [("channel", String(describing: channel)), ("userId", String(describing: userId)), ("password", String(describing: password))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func editLocation(channel: Api.InputChannel, geoPoint: Api.InputGeoPoint, address: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1491484525) + channel.serialize(buffer, true) + geoPoint.serialize(buffer, true) + serializeString(address, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.editLocation", parameters: [("channel", String(describing: channel)), ("geoPoint", String(describing: geoPoint)), ("address", String(describing: address))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.channels { + static func editPhoto(channel: Api.InputChannel, photo: Api.InputChatPhoto) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-248621111) + channel.serialize(buffer, true) + photo.serialize(buffer, true) + return (FunctionDescription(name: "channels.editPhoto", parameters: [("channel", String(describing: channel)), ("photo", String(describing: photo))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func editTitle(channel: Api.InputChannel, title: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1450044624) + channel.serialize(buffer, true) + serializeString(title, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.editTitle", parameters: [("channel", String(describing: channel)), ("title", String(describing: title))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func exportMessageLink(flags: Int32, channel: Api.InputChannel, id: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-432034325) + serializeInt32(flags, buffer: buffer, boxed: false) + channel.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.exportMessageLink", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ExportedMessageLink? in + let reader = BufferReader(buffer) + var result: Api.ExportedMessageLink? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.ExportedMessageLink + } + return result + }) + } +} +public extension Api.functions.channels { + static func getAdminLog(flags: Int32, channel: Api.InputChannel, q: String, eventsFilter: Api.ChannelAdminLogEventsFilter?, admins: [Api.InputUser]?, maxId: Int64, minId: Int64, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(870184064) + serializeInt32(flags, buffer: buffer, boxed: false) + channel.serialize(buffer, true) + serializeString(q, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + eventsFilter!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(admins!.count)) + for item in admins! { + item.serialize(buffer, true) + } + } + serializeInt64(maxId, buffer: buffer, boxed: false) + serializeInt64(minId, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.getAdminLog", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel)), ("q", String(describing: q)), ("eventsFilter", String(describing: eventsFilter)), ("admins", String(describing: admins)), ("maxId", String(describing: maxId)), ("minId", String(describing: minId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.channels.AdminLogResults? in + let reader = BufferReader(buffer) + var result: Api.channels.AdminLogResults? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.channels.AdminLogResults + } + return result + }) + } +} +public extension Api.functions.channels { + static func getAdminedPublicChannels(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-122669393) + serializeInt32(flags, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.getAdminedPublicChannels", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in + let reader = BufferReader(buffer) + var result: Api.messages.Chats? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Chats + } + return result + }) + } +} +public extension Api.functions.channels { + static func getChannelRecommendations(flags: Int32, channel: Api.InputChannel?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(631707458) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + channel!.serialize(buffer, true) + } + return (FunctionDescription(name: "channels.getChannelRecommendations", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in + let reader = BufferReader(buffer) + var result: Api.messages.Chats? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Chats + } + return result + }) + } +} +public extension Api.functions.channels { + static func getChannels(id: [Api.InputChannel]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(176122811) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "channels.getChannels", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in + let reader = BufferReader(buffer) + var result: Api.messages.Chats? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Chats + } + return result + }) + } +} +public extension Api.functions.channels { + static func getFullChannel(channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(141781513) + channel.serialize(buffer, true) + return (FunctionDescription(name: "channels.getFullChannel", parameters: [("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ChatFull? in + let reader = BufferReader(buffer) + var result: Api.messages.ChatFull? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.ChatFull + } + return result + }) + } +} +public extension Api.functions.channels { + static func getFutureCreatorAfterLeave(channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1610016593) + channel.serialize(buffer, true) + return (FunctionDescription(name: "channels.getFutureCreatorAfterLeave", parameters: [("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.User? in + let reader = BufferReader(buffer) + var result: Api.User? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.User + } + return result + }) + } +} +public extension Api.functions.channels { + static func getGroupsForDiscussion() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-170208392) + return (FunctionDescription(name: "channels.getGroupsForDiscussion", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in + let reader = BufferReader(buffer) + var result: Api.messages.Chats? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Chats + } + return result + }) + } +} +public extension Api.functions.channels { + static func getInactiveChannels() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(300429806) + return (FunctionDescription(name: "channels.getInactiveChannels", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.InactiveChats? in + let reader = BufferReader(buffer) + var result: Api.messages.InactiveChats? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.InactiveChats + } + return result + }) + } +} +public extension Api.functions.channels { + static func getLeftChannels(offset: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2092831552) + serializeInt32(offset, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.getLeftChannels", parameters: [("offset", String(describing: offset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in + let reader = BufferReader(buffer) + var result: Api.messages.Chats? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Chats + } + return result + }) + } +} +public extension Api.functions.channels { + static func getMessageAuthor(channel: Api.InputChannel, id: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-320691994) + channel.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.getMessageAuthor", parameters: [("channel", String(describing: channel)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.User? in + let reader = BufferReader(buffer) + var result: Api.User? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.User + } + return result + }) + } +} +public extension Api.functions.channels { + static func getMessages(channel: Api.InputChannel, id: [Api.InputMessage]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1383294429) + channel.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "channels.getMessages", parameters: [("channel", String(describing: channel)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in + let reader = BufferReader(buffer) + var result: Api.messages.Messages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Messages + } + return result + }) + } +} +public extension Api.functions.channels { + static func getParticipant(channel: Api.InputChannel, participant: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1599378234) + channel.serialize(buffer, true) + participant.serialize(buffer, true) + return (FunctionDescription(name: "channels.getParticipant", parameters: [("channel", String(describing: channel)), ("participant", String(describing: participant))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.channels.ChannelParticipant? in + let reader = BufferReader(buffer) + var result: Api.channels.ChannelParticipant? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.channels.ChannelParticipant + } + return result + }) + } +} +public extension Api.functions.channels { + static func getParticipants(channel: Api.InputChannel, filter: Api.ChannelParticipantsFilter, offset: Int32, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2010044880) + channel.serialize(buffer, true) + filter.serialize(buffer, true) + serializeInt32(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.getParticipants", parameters: [("channel", String(describing: channel)), ("filter", String(describing: filter)), ("offset", String(describing: offset)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.channels.ChannelParticipants? in + let reader = BufferReader(buffer) + var result: Api.channels.ChannelParticipants? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.channels.ChannelParticipants + } + return result + }) + } +} +public extension Api.functions.channels { + static func getSendAs(flags: Int32, peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-410672065) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + return (FunctionDescription(name: "channels.getSendAs", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.channels.SendAsPeers? in + let reader = BufferReader(buffer) + var result: Api.channels.SendAsPeers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.channels.SendAsPeers + } + return result + }) + } +} +public extension Api.functions.channels { + static func inviteToChannel(channel: Api.InputChannel, users: [Api.InputUser]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-907854508) + channel.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(users.count)) + for item in users { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "channels.inviteToChannel", parameters: [("channel", String(describing: channel)), ("users", String(describing: users))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.InvitedUsers? in + let reader = BufferReader(buffer) + var result: Api.messages.InvitedUsers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.InvitedUsers + } + return result + }) + } +} +public extension Api.functions.channels { + static func joinChannel(channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(615851205) + channel.serialize(buffer, true) + return (FunctionDescription(name: "channels.joinChannel", parameters: [("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func leaveChannel(channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-130635115) + channel.serialize(buffer, true) + return (FunctionDescription(name: "channels.leaveChannel", parameters: [("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func readHistory(channel: Api.InputChannel, maxId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-871347913) + channel.serialize(buffer, true) + serializeInt32(maxId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.readHistory", parameters: [("channel", String(describing: channel)), ("maxId", String(describing: maxId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.channels { + static func readMessageContents(channel: Api.InputChannel, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-357180360) + channel.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "channels.readMessageContents", parameters: [("channel", String(describing: channel)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.channels { + static func reorderUsernames(channel: Api.InputChannel, order: [String]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1268978403) + channel.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(order.count)) + for item in order { + serializeString(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "channels.reorderUsernames", parameters: [("channel", String(describing: channel)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.channels { + static func reportAntiSpamFalsePositive(channel: Api.InputChannel, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1471109485) + channel.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.reportAntiSpamFalsePositive", parameters: [("channel", String(describing: channel)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.channels { + static func reportSpam(channel: Api.InputChannel, participant: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-196443371) + channel.serialize(buffer, true) + participant.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "channels.reportSpam", parameters: [("channel", String(describing: channel)), ("participant", String(describing: participant)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.channels { + static func restrictSponsoredMessages(channel: Api.InputChannel, restricted: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1696000743) + channel.serialize(buffer, true) + restricted.serialize(buffer, true) + return (FunctionDescription(name: "channels.restrictSponsoredMessages", parameters: [("channel", String(describing: channel)), ("restricted", String(describing: restricted))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func searchPosts(flags: Int32, hashtag: String?, query: String?, offsetRate: Int32, offsetPeer: Api.InputPeer, offsetId: Int32, limit: Int32, allowPaidStars: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-221973939) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(hashtag!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeString(query!, buffer: buffer, boxed: false) + } + serializeInt32(offsetRate, buffer: buffer, boxed: false) + offsetPeer.serialize(buffer, true) + serializeInt32(offsetId, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 2) != 0 { + serializeInt64(allowPaidStars!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "channels.searchPosts", parameters: [("flags", String(describing: flags)), ("hashtag", String(describing: hashtag)), ("query", String(describing: query)), ("offsetRate", String(describing: offsetRate)), ("offsetPeer", String(describing: offsetPeer)), ("offsetId", String(describing: offsetId)), ("limit", String(describing: limit)), ("allowPaidStars", String(describing: allowPaidStars))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in + let reader = BufferReader(buffer) + var result: Api.messages.Messages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Messages + } + return result + }) + } +} +public extension Api.functions.channels { + static func setBoostsToUnblockRestrictions(channel: Api.InputChannel, boosts: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1388733202) + channel.serialize(buffer, true) + serializeInt32(boosts, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.setBoostsToUnblockRestrictions", parameters: [("channel", String(describing: channel)), ("boosts", String(describing: boosts))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func setDiscussionGroup(broadcast: Api.InputChannel, group: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1079520178) + broadcast.serialize(buffer, true) + group.serialize(buffer, true) + return (FunctionDescription(name: "channels.setDiscussionGroup", parameters: [("broadcast", String(describing: broadcast)), ("group", String(describing: group))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.channels { + static func setEmojiStickers(channel: Api.InputChannel, stickerset: Api.InputStickerSet) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1020866743) + channel.serialize(buffer, true) + stickerset.serialize(buffer, true) + return (FunctionDescription(name: "channels.setEmojiStickers", parameters: [("channel", String(describing: channel)), ("stickerset", String(describing: stickerset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.channels { + static func setMainProfileTab(channel: Api.InputChannel, tab: Api.ProfileTab) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(897842353) + channel.serialize(buffer, true) + tab.serialize(buffer, true) + return (FunctionDescription(name: "channels.setMainProfileTab", parameters: [("channel", String(describing: channel)), ("tab", String(describing: tab))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.channels { + static func setStickers(channel: Api.InputChannel, stickerset: Api.InputStickerSet) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-359881479) + channel.serialize(buffer, true) + stickerset.serialize(buffer, true) + return (FunctionDescription(name: "channels.setStickers", parameters: [("channel", String(describing: channel)), ("stickerset", String(describing: stickerset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.channels { + static func toggleAntiSpam(channel: Api.InputChannel, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1760814315) + channel.serialize(buffer, true) + enabled.serialize(buffer, true) + return (FunctionDescription(name: "channels.toggleAntiSpam", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func toggleAutotranslation(channel: Api.InputChannel, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(377471137) + channel.serialize(buffer, true) + enabled.serialize(buffer, true) + return (FunctionDescription(name: "channels.toggleAutotranslation", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func toggleForum(channel: Api.InputChannel, enabled: Api.Bool, tabs: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1073174324) + channel.serialize(buffer, true) + enabled.serialize(buffer, true) + tabs.serialize(buffer, true) + return (FunctionDescription(name: "channels.toggleForum", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled)), ("tabs", String(describing: tabs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func toggleJoinRequest(channel: Api.InputChannel, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1277789622) + channel.serialize(buffer, true) + enabled.serialize(buffer, true) + return (FunctionDescription(name: "channels.toggleJoinRequest", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func toggleJoinToSend(channel: Api.InputChannel, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-456419968) + channel.serialize(buffer, true) + enabled.serialize(buffer, true) + return (FunctionDescription(name: "channels.toggleJoinToSend", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func toggleParticipantsHidden(channel: Api.InputChannel, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1785624660) + channel.serialize(buffer, true) + enabled.serialize(buffer, true) + return (FunctionDescription(name: "channels.toggleParticipantsHidden", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func togglePreHistoryHidden(channel: Api.InputChannel, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-356796084) + channel.serialize(buffer, true) + enabled.serialize(buffer, true) + return (FunctionDescription(name: "channels.togglePreHistoryHidden", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func toggleSignatures(flags: Int32, channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1099781276) + serializeInt32(flags, buffer: buffer, boxed: false) + channel.serialize(buffer, true) + return (FunctionDescription(name: "channels.toggleSignatures", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func toggleSlowMode(channel: Api.InputChannel, seconds: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-304832784) + channel.serialize(buffer, true) + serializeInt32(seconds, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.toggleSlowMode", parameters: [("channel", String(describing: channel)), ("seconds", String(describing: seconds))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func toggleUsername(channel: Api.InputChannel, username: String, active: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1358053637) + channel.serialize(buffer, true) + serializeString(username, buffer: buffer, boxed: false) + active.serialize(buffer, true) + return (FunctionDescription(name: "channels.toggleUsername", parameters: [("channel", String(describing: channel)), ("username", String(describing: username)), ("active", String(describing: active))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.channels { + static func toggleViewForumAsMessages(channel: Api.InputChannel, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1757889771) + channel.serialize(buffer, true) + enabled.serialize(buffer, true) + return (FunctionDescription(name: "channels.toggleViewForumAsMessages", parameters: [("channel", String(describing: channel)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func updateColor(flags: Int32, channel: Api.InputChannel, color: Int32?, backgroundEmojiId: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-659933583) + serializeInt32(flags, buffer: buffer, boxed: false) + channel.serialize(buffer, true) + if Int(flags) & Int(1 << 2) != 0 { + serializeInt32(color!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 0) != 0 { + serializeInt64(backgroundEmojiId!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "channels.updateColor", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel)), ("color", String(describing: color)), ("backgroundEmojiId", String(describing: backgroundEmojiId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func updateEmojiStatus(channel: Api.InputChannel, emojiStatus: Api.EmojiStatus) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-254548312) + channel.serialize(buffer, true) + emojiStatus.serialize(buffer, true) + return (FunctionDescription(name: "channels.updateEmojiStatus", parameters: [("channel", String(describing: channel)), ("emojiStatus", String(describing: emojiStatus))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func updatePaidMessagesPrice(flags: Int32, channel: Api.InputChannel, sendPaidMessagesStars: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1259483771) + serializeInt32(flags, buffer: buffer, boxed: false) + channel.serialize(buffer, true) + serializeInt64(sendPaidMessagesStars, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.updatePaidMessagesPrice", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel)), ("sendPaidMessagesStars", String(describing: sendPaidMessagesStars))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.channels { + static func updateUsername(channel: Api.InputChannel, username: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(890549214) + channel.serialize(buffer, true) + serializeString(username, buffer: buffer, boxed: false) + return (FunctionDescription(name: "channels.updateUsername", parameters: [("channel", String(describing: channel)), ("username", String(describing: username))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.chatlists { + static func checkChatlistInvite(slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1103171583) + serializeString(slug, buffer: buffer, boxed: false) + return (FunctionDescription(name: "chatlists.checkChatlistInvite", parameters: [("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.chatlists.ChatlistInvite? in + let reader = BufferReader(buffer) + var result: Api.chatlists.ChatlistInvite? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.chatlists.ChatlistInvite + } + return result + }) + } +} +public extension Api.functions.chatlists { + static func deleteExportedInvite(chatlist: Api.InputChatlist, slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1906072670) + chatlist.serialize(buffer, true) + serializeString(slug, buffer: buffer, boxed: false) + return (FunctionDescription(name: "chatlists.deleteExportedInvite", parameters: [("chatlist", String(describing: chatlist)), ("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.chatlists { + static func editExportedInvite(flags: Int32, chatlist: Api.InputChatlist, slug: String, title: String?, peers: [Api.InputPeer]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1698543165) + serializeInt32(flags, buffer: buffer, boxed: false) + chatlist.serialize(buffer, true) + serializeString(slug, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 1) != 0 { + serializeString(title!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(peers!.count)) + for item in peers! { + item.serialize(buffer, true) + } + } + return (FunctionDescription(name: "chatlists.editExportedInvite", parameters: [("flags", String(describing: flags)), ("chatlist", String(describing: chatlist)), ("slug", String(describing: slug)), ("title", String(describing: title)), ("peers", String(describing: peers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ExportedChatlistInvite? in + let reader = BufferReader(buffer) + var result: Api.ExportedChatlistInvite? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.ExportedChatlistInvite + } + return result + }) + } +} +public extension Api.functions.chatlists { + static func exportChatlistInvite(chatlist: Api.InputChatlist, title: String, peers: [Api.InputPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2072885362) + chatlist.serialize(buffer, true) + serializeString(title, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(peers.count)) + for item in peers { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "chatlists.exportChatlistInvite", parameters: [("chatlist", String(describing: chatlist)), ("title", String(describing: title)), ("peers", String(describing: peers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.chatlists.ExportedChatlistInvite? in + let reader = BufferReader(buffer) + var result: Api.chatlists.ExportedChatlistInvite? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.chatlists.ExportedChatlistInvite + } + return result + }) + } +} +public extension Api.functions.chatlists { + static func getChatlistUpdates(chatlist: Api.InputChatlist) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1992190687) + chatlist.serialize(buffer, true) + return (FunctionDescription(name: "chatlists.getChatlistUpdates", parameters: [("chatlist", String(describing: chatlist))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.chatlists.ChatlistUpdates? in + let reader = BufferReader(buffer) + var result: Api.chatlists.ChatlistUpdates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.chatlists.ChatlistUpdates + } + return result + }) + } +} +public extension Api.functions.chatlists { + static func getExportedInvites(chatlist: Api.InputChatlist) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-838608253) + chatlist.serialize(buffer, true) + return (FunctionDescription(name: "chatlists.getExportedInvites", parameters: [("chatlist", String(describing: chatlist))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.chatlists.ExportedInvites? in + let reader = BufferReader(buffer) + var result: Api.chatlists.ExportedInvites? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.chatlists.ExportedInvites + } + return result + }) + } +} +public extension Api.functions.chatlists { + static func getLeaveChatlistSuggestions(chatlist: Api.InputChatlist) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.Peer]>) { + let buffer = Buffer() + buffer.appendInt32(-37955820) + chatlist.serialize(buffer, true) + return (FunctionDescription(name: "chatlists.getLeaveChatlistSuggestions", parameters: [("chatlist", String(describing: chatlist))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.Peer]? in + let reader = BufferReader(buffer) + var result: [Api.Peer]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.Peer.self) + } + return result + }) + } +} +public extension Api.functions.chatlists { + static func hideChatlistUpdates(chatlist: Api.InputChatlist) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1726252795) + chatlist.serialize(buffer, true) + return (FunctionDescription(name: "chatlists.hideChatlistUpdates", parameters: [("chatlist", String(describing: chatlist))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.chatlists { + static func joinChatlistInvite(slug: String, peers: [Api.InputPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1498291302) + serializeString(slug, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(peers.count)) + for item in peers { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "chatlists.joinChatlistInvite", parameters: [("slug", String(describing: slug)), ("peers", String(describing: peers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.chatlists { + static func joinChatlistUpdates(chatlist: Api.InputChatlist, peers: [Api.InputPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-527828747) + chatlist.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(peers.count)) + for item in peers { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "chatlists.joinChatlistUpdates", parameters: [("chatlist", String(describing: chatlist)), ("peers", String(describing: peers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.chatlists { + static func leaveChatlist(chatlist: Api.InputChatlist, peers: [Api.InputPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1962598714) + chatlist.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(peers.count)) + for item in peers { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "chatlists.leaveChatlist", parameters: [("chatlist", String(describing: chatlist)), ("peers", String(describing: peers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.contacts { + static func acceptContact(id: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-130964977) + id.serialize(buffer, true) + return (FunctionDescription(name: "contacts.acceptContact", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.contacts { + static func addContact(flags: Int32, id: Api.InputUser, firstName: String, lastName: String, phone: String, note: Api.TextWithEntities?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-642109868) + serializeInt32(flags, buffer: buffer, boxed: false) + id.serialize(buffer, true) + serializeString(firstName, buffer: buffer, boxed: false) + serializeString(lastName, buffer: buffer, boxed: false) + serializeString(phone, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 1) != 0 { + note!.serialize(buffer, true) + } + return (FunctionDescription(name: "contacts.addContact", parameters: [("flags", String(describing: flags)), ("id", String(describing: id)), ("firstName", String(describing: firstName)), ("lastName", String(describing: lastName)), ("phone", String(describing: phone)), ("note", String(describing: note))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.contacts { + static func block(flags: Int32, id: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(774801204) + serializeInt32(flags, buffer: buffer, boxed: false) + id.serialize(buffer, true) + return (FunctionDescription(name: "contacts.block", parameters: [("flags", String(describing: flags)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.contacts { + static func blockFromReplies(flags: Int32, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(698914348) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt32(msgId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "contacts.blockFromReplies", parameters: [("flags", String(describing: flags)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.contacts { + static func deleteByPhones(phones: [String]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(269745566) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(phones.count)) + for item in phones { + serializeString(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "contacts.deleteByPhones", parameters: [("phones", String(describing: phones))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.contacts { + static func deleteContacts(id: [Api.InputUser]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(157945344) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "contacts.deleteContacts", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.contacts { + static func editCloseFriends(id: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1167653392) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt64(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "contacts.editCloseFriends", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.contacts { + static func exportContactToken() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-127582169) + return (FunctionDescription(name: "contacts.exportContactToken", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ExportedContactToken? in + let reader = BufferReader(buffer) + var result: Api.ExportedContactToken? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.ExportedContactToken + } + return result + }) + } +} +public extension Api.functions.contacts { + static func getBirthdays() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-621959068) + return (FunctionDescription(name: "contacts.getBirthdays", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.ContactBirthdays? in + let reader = BufferReader(buffer) + var result: Api.contacts.ContactBirthdays? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.contacts.ContactBirthdays + } + return result + }) + } +} +public extension Api.functions.contacts { + static func getBlocked(flags: Int32, offset: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1702457472) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt32(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "contacts.getBlocked", parameters: [("flags", String(describing: flags)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.Blocked? in + let reader = BufferReader(buffer) + var result: Api.contacts.Blocked? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.contacts.Blocked + } + return result + }) + } +} +public extension Api.functions.contacts { + static func getContactIDs(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Int32]>) { + let buffer = Buffer() + buffer.appendInt32(2061264541) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "contacts.getContactIDs", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Int32]? in + let reader = BufferReader(buffer) + var result: [Int32]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + return result + }) + } +} +public extension Api.functions.contacts { + static func getContacts(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1574346258) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "contacts.getContacts", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.Contacts? in + let reader = BufferReader(buffer) + var result: Api.contacts.Contacts? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.contacts.Contacts + } + return result + }) + } +} +public extension Api.functions.contacts { + static func getLocated(flags: Int32, geoPoint: Api.InputGeoPoint, selfExpires: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-750207932) + serializeInt32(flags, buffer: buffer, boxed: false) + geoPoint.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(selfExpires!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "contacts.getLocated", parameters: [("flags", String(describing: flags)), ("geoPoint", String(describing: geoPoint)), ("selfExpires", String(describing: selfExpires))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.contacts { + static func getSaved() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.SavedContact]>) { + let buffer = Buffer() + buffer.appendInt32(-2098076769) + return (FunctionDescription(name: "contacts.getSaved", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.SavedContact]? in + let reader = BufferReader(buffer) + var result: [Api.SavedContact]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.SavedContact.self) + } + return result + }) + } +} +public extension Api.functions.contacts { + static func getSponsoredPeers(q: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1228356717) + serializeString(q, buffer: buffer, boxed: false) + return (FunctionDescription(name: "contacts.getSponsoredPeers", parameters: [("q", String(describing: q))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.SponsoredPeers? in + let reader = BufferReader(buffer) + var result: Api.contacts.SponsoredPeers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.contacts.SponsoredPeers + } + return result + }) + } +} +public extension Api.functions.contacts { + static func getStatuses() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.ContactStatus]>) { + let buffer = Buffer() + buffer.appendInt32(-995929106) + return (FunctionDescription(name: "contacts.getStatuses", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.ContactStatus]? in + let reader = BufferReader(buffer) + var result: [Api.ContactStatus]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.ContactStatus.self) + } + return result + }) + } +} +public extension Api.functions.contacts { + static func getTopPeers(flags: Int32, offset: Int32, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1758168906) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt32(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "contacts.getTopPeers", parameters: [("flags", String(describing: flags)), ("offset", String(describing: offset)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.TopPeers? in + let reader = BufferReader(buffer) + var result: Api.contacts.TopPeers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.contacts.TopPeers + } + return result + }) + } +} +public extension Api.functions.contacts { + static func importContactToken(token: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(318789512) + serializeString(token, buffer: buffer, boxed: false) + return (FunctionDescription(name: "contacts.importContactToken", parameters: [("token", String(describing: token))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.User? in + let reader = BufferReader(buffer) + var result: Api.User? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.User + } + return result + }) + } +} +public extension Api.functions.contacts { + static func importContacts(contacts: [Api.InputContact]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(746589157) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(contacts.count)) + for item in contacts { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "contacts.importContacts", parameters: [("contacts", String(describing: contacts))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.ImportedContacts? in + let reader = BufferReader(buffer) + var result: Api.contacts.ImportedContacts? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.contacts.ImportedContacts + } + return result + }) + } +} +public extension Api.functions.contacts { + static func resetSaved() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2020263951) + return (FunctionDescription(name: "contacts.resetSaved", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.contacts { + static func resetTopPeerRating(category: Api.TopPeerCategory, peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(451113900) + category.serialize(buffer, true) + peer.serialize(buffer, true) + return (FunctionDescription(name: "contacts.resetTopPeerRating", parameters: [("category", String(describing: category)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.contacts { + static func resolvePhone(phone: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1963375804) + serializeString(phone, buffer: buffer, boxed: false) + return (FunctionDescription(name: "contacts.resolvePhone", parameters: [("phone", String(describing: phone))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.ResolvedPeer? in + let reader = BufferReader(buffer) + var result: Api.contacts.ResolvedPeer? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.contacts.ResolvedPeer + } + return result + }) + } +} +public extension Api.functions.contacts { + static func resolveUsername(flags: Int32, username: String, referer: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1918565308) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(username, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(referer!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "contacts.resolveUsername", parameters: [("flags", String(describing: flags)), ("username", String(describing: username)), ("referer", String(describing: referer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.ResolvedPeer? in + let reader = BufferReader(buffer) + var result: Api.contacts.ResolvedPeer? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.contacts.ResolvedPeer + } + return result + }) + } +} +public extension Api.functions.contacts { + static func search(q: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(301470424) + serializeString(q, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "contacts.search", parameters: [("q", String(describing: q)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.contacts.Found? in + let reader = BufferReader(buffer) + var result: Api.contacts.Found? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.contacts.Found + } + return result + }) + } +} +public extension Api.functions.contacts { + static func setBlocked(flags: Int32, id: [Api.InputPeer], limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1798939530) + serializeInt32(flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + item.serialize(buffer, true) + } + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "contacts.setBlocked", parameters: [("flags", String(describing: flags)), ("id", String(describing: id)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.contacts { + static func toggleTopPeers(enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2062238246) + enabled.serialize(buffer, true) + return (FunctionDescription(name: "contacts.toggleTopPeers", parameters: [("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.contacts { + static func unblock(flags: Int32, id: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1252994264) + serializeInt32(flags, buffer: buffer, boxed: false) + id.serialize(buffer, true) + return (FunctionDescription(name: "contacts.unblock", parameters: [("flags", String(describing: flags)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.contacts { + static func updateContactNote(id: Api.InputUser, note: Api.TextWithEntities) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(329212923) + id.serialize(buffer, true) + note.serialize(buffer, true) + return (FunctionDescription(name: "contacts.updateContactNote", parameters: [("id", String(describing: id)), ("note", String(describing: note))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.folders { + static func editPeerFolders(folderPeers: [Api.InputFolderPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1749536939) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(folderPeers.count)) + for item in folderPeers { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "folders.editPeerFolders", parameters: [("folderPeers", String(describing: folderPeers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.fragment { + static func getCollectibleInfo(collectible: Api.InputCollectible) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1105295942) + collectible.serialize(buffer, true) + return (FunctionDescription(name: "fragment.getCollectibleInfo", parameters: [("collectible", String(describing: collectible))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.fragment.CollectibleInfo? in + let reader = BufferReader(buffer) + var result: Api.fragment.CollectibleInfo? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.fragment.CollectibleInfo + } + return result + }) + } +} +public extension Api.functions.help { + static func acceptTermsOfService(id: Api.DataJSON) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-294455398) + id.serialize(buffer, true) + return (FunctionDescription(name: "help.acceptTermsOfService", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.help { + static func dismissSuggestion(peer: Api.InputPeer, suggestion: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-183649631) + peer.serialize(buffer, true) + serializeString(suggestion, buffer: buffer, boxed: false) + return (FunctionDescription(name: "help.dismissSuggestion", parameters: [("peer", String(describing: peer)), ("suggestion", String(describing: suggestion))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.help { + static func editUserInfo(userId: Api.InputUser, message: String, entities: [Api.MessageEntity]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1723407216) + userId.serialize(buffer, true) + serializeString(message, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(entities.count)) + for item in entities { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "help.editUserInfo", parameters: [("userId", String(describing: userId)), ("message", String(describing: message)), ("entities", String(describing: entities))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.UserInfo? in + let reader = BufferReader(buffer) + var result: Api.help.UserInfo? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.UserInfo + } + return result + }) + } +} +public extension Api.functions.help { + static func getAppConfig(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1642330196) + serializeInt32(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "help.getAppConfig", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.AppConfig? in + let reader = BufferReader(buffer) + var result: Api.help.AppConfig? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.AppConfig + } + return result + }) + } +} +public extension Api.functions.help { + static func getAppUpdate(source: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1378703997) + serializeString(source, buffer: buffer, boxed: false) + return (FunctionDescription(name: "help.getAppUpdate", parameters: [("source", String(describing: source))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.AppUpdate? in + let reader = BufferReader(buffer) + var result: Api.help.AppUpdate? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.AppUpdate + } + return result + }) + } +} +public extension Api.functions.help { + static func getCdnConfig() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1375900482) + return (FunctionDescription(name: "help.getCdnConfig", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.CdnConfig? in + let reader = BufferReader(buffer) + var result: Api.CdnConfig? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.CdnConfig + } + return result + }) + } +} +public extension Api.functions.help { + static func getConfig() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-990308245) + return (FunctionDescription(name: "help.getConfig", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Config? in + let reader = BufferReader(buffer) + var result: Api.Config? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Config + } + return result + }) + } +} +public extension Api.functions.help { + static func getCountriesList(langCode: String, hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1935116200) + serializeString(langCode, buffer: buffer, boxed: false) + serializeInt32(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "help.getCountriesList", parameters: [("langCode", String(describing: langCode)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.CountriesList? in + let reader = BufferReader(buffer) + var result: Api.help.CountriesList? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.CountriesList + } + return result + }) + } +} +public extension Api.functions.help { + static func getDeepLinkInfo(path: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1072547679) + serializeString(path, buffer: buffer, boxed: false) + return (FunctionDescription(name: "help.getDeepLinkInfo", parameters: [("path", String(describing: path))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.DeepLinkInfo? in + let reader = BufferReader(buffer) + var result: Api.help.DeepLinkInfo? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.DeepLinkInfo + } + return result + }) + } +} +public extension Api.functions.help { + static func getInviteText() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1295590211) + return (FunctionDescription(name: "help.getInviteText", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.InviteText? in + let reader = BufferReader(buffer) + var result: Api.help.InviteText? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.InviteText + } + return result + }) + } +} +public extension Api.functions.help { + static func getNearestDc() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(531836966) + return (FunctionDescription(name: "help.getNearestDc", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.NearestDc? in + let reader = BufferReader(buffer) + var result: Api.NearestDc? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.NearestDc + } + return result + }) + } +} +public extension Api.functions.help { + static func getPassportConfig(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-966677240) + serializeInt32(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "help.getPassportConfig", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.PassportConfig? in + let reader = BufferReader(buffer) + var result: Api.help.PassportConfig? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.PassportConfig + } + return result + }) + } +} +public extension Api.functions.help { + static func getPeerColors(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-629083089) + serializeInt32(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "help.getPeerColors", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.PeerColors? in + let reader = BufferReader(buffer) + var result: Api.help.PeerColors? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.PeerColors + } + return result + }) + } +} +public extension Api.functions.help { + static func getPeerProfileColors(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1412453891) + serializeInt32(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "help.getPeerProfileColors", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.PeerColors? in + let reader = BufferReader(buffer) + var result: Api.help.PeerColors? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.PeerColors + } + return result + }) + } +} +public extension Api.functions.help { + static func getPremiumPromo() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1206152236) + return (FunctionDescription(name: "help.getPremiumPromo", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.PremiumPromo? in + let reader = BufferReader(buffer) + var result: Api.help.PremiumPromo? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.PremiumPromo + } + return result + }) + } +} +public extension Api.functions.help { + static func getPromoData() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1063816159) + return (FunctionDescription(name: "help.getPromoData", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.PromoData? in + let reader = BufferReader(buffer) + var result: Api.help.PromoData? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.PromoData + } + return result + }) + } +} +public extension Api.functions.help { + static func getRecentMeUrls(referer: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1036054804) + serializeString(referer, buffer: buffer, boxed: false) + return (FunctionDescription(name: "help.getRecentMeUrls", parameters: [("referer", String(describing: referer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.RecentMeUrls? in + let reader = BufferReader(buffer) + var result: Api.help.RecentMeUrls? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.RecentMeUrls + } + return result + }) + } +} +public extension Api.functions.help { + static func getSupport() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1663104819) + return (FunctionDescription(name: "help.getSupport", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.Support? in + let reader = BufferReader(buffer) + var result: Api.help.Support? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.Support + } + return result + }) + } +} +public extension Api.functions.help { + static func getSupportName() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-748624084) + return (FunctionDescription(name: "help.getSupportName", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.SupportName? in + let reader = BufferReader(buffer) + var result: Api.help.SupportName? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.SupportName + } + return result + }) + } +} +public extension Api.functions.help { + static func getTermsOfServiceUpdate() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(749019089) + return (FunctionDescription(name: "help.getTermsOfServiceUpdate", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.TermsOfServiceUpdate? in + let reader = BufferReader(buffer) + var result: Api.help.TermsOfServiceUpdate? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.TermsOfServiceUpdate + } + return result + }) + } +} +public extension Api.functions.help { + static func getTimezonesList(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1236468288) + serializeInt32(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "help.getTimezonesList", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.TimezonesList? in + let reader = BufferReader(buffer) + var result: Api.help.TimezonesList? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.TimezonesList + } + return result + }) + } +} +public extension Api.functions.help { + static func getUserInfo(userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(59377875) + userId.serialize(buffer, true) + return (FunctionDescription(name: "help.getUserInfo", parameters: [("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.help.UserInfo? in + let reader = BufferReader(buffer) + var result: Api.help.UserInfo? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.help.UserInfo + } + return result + }) + } +} +public extension Api.functions.help { + static func hidePromoData(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(505748629) + peer.serialize(buffer, true) + return (FunctionDescription(name: "help.hidePromoData", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.help { + static func saveAppLog(events: [Api.InputAppEvent]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1862465352) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(events.count)) + for item in events { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "help.saveAppLog", parameters: [("events", String(describing: events))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.help { + static func setBotUpdatesStatus(pendingUpdatesCount: Int32, message: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-333262899) + serializeInt32(pendingUpdatesCount, buffer: buffer, boxed: false) + serializeString(message, buffer: buffer, boxed: false) + return (FunctionDescription(name: "help.setBotUpdatesStatus", parameters: [("pendingUpdatesCount", String(describing: pendingUpdatesCount)), ("message", String(describing: message))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.help { + static func test() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1058929929) + return (FunctionDescription(name: "help.test", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.langpack { + static func getDifference(langPack: String, langCode: String, fromVersion: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-845657435) + serializeString(langPack, buffer: buffer, boxed: false) + serializeString(langCode, buffer: buffer, boxed: false) + serializeInt32(fromVersion, buffer: buffer, boxed: false) + return (FunctionDescription(name: "langpack.getDifference", parameters: [("langPack", String(describing: langPack)), ("langCode", String(describing: langCode)), ("fromVersion", String(describing: fromVersion))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.LangPackDifference? in + let reader = BufferReader(buffer) + var result: Api.LangPackDifference? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.LangPackDifference + } + return result + }) + } +} +public extension Api.functions.langpack { + static func getLangPack(langPack: String, langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-219008246) + serializeString(langPack, buffer: buffer, boxed: false) + serializeString(langCode, buffer: buffer, boxed: false) + return (FunctionDescription(name: "langpack.getLangPack", parameters: [("langPack", String(describing: langPack)), ("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.LangPackDifference? in + let reader = BufferReader(buffer) + var result: Api.LangPackDifference? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.LangPackDifference + } + return result + }) + } +} +public extension Api.functions.langpack { + static func getLanguage(langPack: String, langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1784243458) + serializeString(langPack, buffer: buffer, boxed: false) + serializeString(langCode, buffer: buffer, boxed: false) + return (FunctionDescription(name: "langpack.getLanguage", parameters: [("langPack", String(describing: langPack)), ("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.LangPackLanguage? in + let reader = BufferReader(buffer) + var result: Api.LangPackLanguage? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.LangPackLanguage + } + return result + }) + } +} +public extension Api.functions.langpack { + static func getLanguages(langPack: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.LangPackLanguage]>) { + let buffer = Buffer() + buffer.appendInt32(1120311183) + serializeString(langPack, buffer: buffer, boxed: false) + return (FunctionDescription(name: "langpack.getLanguages", parameters: [("langPack", String(describing: langPack))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.LangPackLanguage]? in + let reader = BufferReader(buffer) + var result: [Api.LangPackLanguage]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.LangPackLanguage.self) + } + return result + }) + } +} +public extension Api.functions.langpack { + static func getStrings(langPack: String, langCode: String, keys: [String]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.LangPackString]>) { + let buffer = Buffer() + buffer.appendInt32(-269862909) + serializeString(langPack, buffer: buffer, boxed: false) + serializeString(langCode, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(keys.count)) + for item in keys { + serializeString(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "langpack.getStrings", parameters: [("langPack", String(describing: langPack)), ("langCode", String(describing: langCode)), ("keys", String(describing: keys))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.LangPackString]? in + let reader = BufferReader(buffer) + var result: [Api.LangPackString]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.LangPackString.self) + } + return result + }) + } +} +public extension Api.functions.messages { + static func acceptEncryption(peer: Api.InputEncryptedChat, gB: Buffer, keyFingerprint: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1035731989) + peer.serialize(buffer, true) + serializeBytes(gB, buffer: buffer, boxed: false) + serializeInt64(keyFingerprint, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.acceptEncryption", parameters: [("peer", String(describing: peer)), ("gB", String(describing: gB)), ("keyFingerprint", String(describing: keyFingerprint))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EncryptedChat? in + let reader = BufferReader(buffer) + var result: Api.EncryptedChat? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.EncryptedChat + } + return result + }) + } +} +public extension Api.functions.messages { + static func acceptUrlAuth(flags: Int32, peer: Api.InputPeer?, msgId: Int32?, buttonId: Int32?, url: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1322487515) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 1) != 0 { + peer!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeInt32(msgId!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeInt32(buttonId!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + serializeString(url!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.acceptUrlAuth", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("buttonId", String(describing: buttonId)), ("url", String(describing: url))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.UrlAuthResult? in + let reader = BufferReader(buffer) + var result: Api.UrlAuthResult? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.UrlAuthResult + } + return result + }) + } +} +public extension Api.functions.messages { + static func addChatUser(chatId: Int64, userId: Api.InputUser, fwdLimit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-876162809) + serializeInt64(chatId, buffer: buffer, boxed: false) + userId.serialize(buffer, true) + serializeInt32(fwdLimit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.addChatUser", parameters: [("chatId", String(describing: chatId)), ("userId", String(describing: userId)), ("fwdLimit", String(describing: fwdLimit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.InvitedUsers? in + let reader = BufferReader(buffer) + var result: Api.messages.InvitedUsers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.InvitedUsers + } + return result + }) + } +} +public extension Api.functions.messages { + static func appendTodoList(peer: Api.InputPeer, msgId: Int32, list: [Api.TodoItem]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(564531287) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(list.count)) + for item in list { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.appendTodoList", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("list", String(describing: list))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func checkChatInvite(hash: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1051570619) + serializeString(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.checkChatInvite", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ChatInvite? in + let reader = BufferReader(buffer) + var result: Api.ChatInvite? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.ChatInvite + } + return result + }) + } +} +public extension Api.functions.messages { + static func checkHistoryImport(importHead: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1140726259) + serializeString(importHead, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.checkHistoryImport", parameters: [("importHead", String(describing: importHead))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.HistoryImportParsed? in + let reader = BufferReader(buffer) + var result: Api.messages.HistoryImportParsed? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.HistoryImportParsed + } + return result + }) + } +} +public extension Api.functions.messages { + static func checkHistoryImportPeer(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1573261059) + peer.serialize(buffer, true) + return (FunctionDescription(name: "messages.checkHistoryImportPeer", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.CheckedHistoryImportPeer? in + let reader = BufferReader(buffer) + var result: Api.messages.CheckedHistoryImportPeer? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.CheckedHistoryImportPeer + } + return result + }) + } +} +public extension Api.functions.messages { + static func checkQuickReplyShortcut(shortcut: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-237962285) + serializeString(shortcut, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.checkQuickReplyShortcut", parameters: [("shortcut", String(describing: shortcut))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func clearAllDrafts() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2119757468) + return (FunctionDescription(name: "messages.clearAllDrafts", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func clearRecentReactions() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1644236876) + return (FunctionDescription(name: "messages.clearRecentReactions", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func clearRecentStickers(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1986437075) + serializeInt32(flags, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.clearRecentStickers", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func clickSponsoredMessage(flags: Int32, randomId: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2110454402) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeBytes(randomId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.clickSponsoredMessage", parameters: [("flags", String(describing: flags)), ("randomId", String(describing: randomId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func createChat(flags: Int32, users: [Api.InputUser], title: String, ttlPeriod: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1831936556) + serializeInt32(flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(users.count)) + for item in users { + item.serialize(buffer, true) + } + serializeString(title, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(ttlPeriod!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.createChat", parameters: [("flags", String(describing: flags)), ("users", String(describing: users)), ("title", String(describing: title)), ("ttlPeriod", String(describing: ttlPeriod))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.InvitedUsers? in + let reader = BufferReader(buffer) + var result: Api.messages.InvitedUsers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.InvitedUsers + } + return result + }) + } +} +public extension Api.functions.messages { + static func createForumTopic(flags: Int32, peer: Api.InputPeer, title: String, iconColor: Int32?, iconEmojiId: Int64?, randomId: Int64, sendAs: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(798540757) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeString(title, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(iconColor!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 3) != 0 { + serializeInt64(iconEmojiId!, buffer: buffer, boxed: false) + } + serializeInt64(randomId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 2) != 0 { + sendAs!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.createForumTopic", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("title", String(describing: title)), ("iconColor", String(describing: iconColor)), ("iconEmojiId", String(describing: iconEmojiId)), ("randomId", String(describing: randomId)), ("sendAs", String(describing: sendAs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func deleteChat(chatId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1540419152) + serializeInt64(chatId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.deleteChat", parameters: [("chatId", String(describing: chatId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func deleteChatUser(flags: Int32, chatId: Int64, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1575461717) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt64(chatId, buffer: buffer, boxed: false) + userId.serialize(buffer, true) + return (FunctionDescription(name: "messages.deleteChatUser", parameters: [("flags", String(describing: flags)), ("chatId", String(describing: chatId)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func deleteExportedChatInvite(peer: Api.InputPeer, link: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-731601877) + peer.serialize(buffer, true) + serializeString(link, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.deleteExportedChatInvite", parameters: [("peer", String(describing: peer)), ("link", String(describing: link))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func deleteFactCheck(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-774204404) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.deleteFactCheck", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func deleteHistory(flags: Int32, peer: Api.InputPeer, maxId: Int32, minDate: Int32?, maxDate: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1332768214) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(maxId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 2) != 0 { + serializeInt32(minDate!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 3) != 0 { + serializeInt32(maxDate!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.deleteHistory", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("maxId", String(describing: maxId)), ("minDate", String(describing: minDate)), ("maxDate", String(describing: maxDate))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedHistory? in + let reader = BufferReader(buffer) + var result: Api.messages.AffectedHistory? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AffectedHistory + } + return result + }) + } +} +public extension Api.functions.messages { + static func deleteMessages(flags: Int32, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-443640366) + serializeInt32(flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.deleteMessages", parameters: [("flags", String(describing: flags)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedMessages? in + let reader = BufferReader(buffer) + var result: Api.messages.AffectedMessages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AffectedMessages + } + return result + }) + } +} +public extension Api.functions.messages { + static func deletePhoneCallHistory(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-104078327) + serializeInt32(flags, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.deletePhoneCallHistory", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedFoundMessages? in + let reader = BufferReader(buffer) + var result: Api.messages.AffectedFoundMessages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AffectedFoundMessages + } + return result + }) + } +} +public extension Api.functions.messages { + static func deleteQuickReplyMessages(shortcutId: Int32, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-519706352) + serializeInt32(shortcutId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.deleteQuickReplyMessages", parameters: [("shortcutId", String(describing: shortcutId)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func deleteQuickReplyShortcut(shortcutId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1019234112) + serializeInt32(shortcutId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.deleteQuickReplyShortcut", parameters: [("shortcutId", String(describing: shortcutId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func deleteRevokedExportedChatInvites(peer: Api.InputPeer, adminId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1452833749) + peer.serialize(buffer, true) + adminId.serialize(buffer, true) + return (FunctionDescription(name: "messages.deleteRevokedExportedChatInvites", parameters: [("peer", String(describing: peer)), ("adminId", String(describing: adminId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func deleteSavedHistory(flags: Int32, parentPeer: Api.InputPeer?, peer: Api.InputPeer, maxId: Int32, minDate: Int32?, maxDate: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1304758367) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + parentPeer!.serialize(buffer, true) + } + peer.serialize(buffer, true) + serializeInt32(maxId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 2) != 0 { + serializeInt32(minDate!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 3) != 0 { + serializeInt32(maxDate!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.deleteSavedHistory", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer)), ("peer", String(describing: peer)), ("maxId", String(describing: maxId)), ("minDate", String(describing: minDate)), ("maxDate", String(describing: maxDate))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedHistory? in + let reader = BufferReader(buffer) + var result: Api.messages.AffectedHistory? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AffectedHistory + } + return result + }) + } +} +public extension Api.functions.messages { + static func deleteScheduledMessages(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1504586518) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.deleteScheduledMessages", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func deleteTopicHistory(peer: Api.InputPeer, topMsgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-763269360) + peer.serialize(buffer, true) + serializeInt32(topMsgId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.deleteTopicHistory", parameters: [("peer", String(describing: peer)), ("topMsgId", String(describing: topMsgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedHistory? in + let reader = BufferReader(buffer) + var result: Api.messages.AffectedHistory? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AffectedHistory + } + return result + }) + } +} +public extension Api.functions.messages { + static func discardEncryption(flags: Int32, chatId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-208425312) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt32(chatId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.discardEncryption", parameters: [("flags", String(describing: flags)), ("chatId", String(describing: chatId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func editChatAbout(peer: Api.InputPeer, about: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-554301545) + peer.serialize(buffer, true) + serializeString(about, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.editChatAbout", parameters: [("peer", String(describing: peer)), ("about", String(describing: about))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func editChatAdmin(chatId: Int64, userId: Api.InputUser, isAdmin: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1470377534) + serializeInt64(chatId, buffer: buffer, boxed: false) + userId.serialize(buffer, true) + isAdmin.serialize(buffer, true) + return (FunctionDescription(name: "messages.editChatAdmin", parameters: [("chatId", String(describing: chatId)), ("userId", String(describing: userId)), ("isAdmin", String(describing: isAdmin))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func editChatDefaultBannedRights(peer: Api.InputPeer, bannedRights: Api.ChatBannedRights) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1517917375) + peer.serialize(buffer, true) + bannedRights.serialize(buffer, true) + return (FunctionDescription(name: "messages.editChatDefaultBannedRights", parameters: [("peer", String(describing: peer)), ("bannedRights", String(describing: bannedRights))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func editChatPhoto(chatId: Int64, photo: Api.InputChatPhoto) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(903730804) + serializeInt64(chatId, buffer: buffer, boxed: false) + photo.serialize(buffer, true) + return (FunctionDescription(name: "messages.editChatPhoto", parameters: [("chatId", String(describing: chatId)), ("photo", String(describing: photo))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func editChatTitle(chatId: Int64, title: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1937260541) + serializeInt64(chatId, buffer: buffer, boxed: false) + serializeString(title, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.editChatTitle", parameters: [("chatId", String(describing: chatId)), ("title", String(describing: title))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func editExportedChatInvite(flags: Int32, peer: Api.InputPeer, link: String, expireDate: Int32?, usageLimit: Int32?, requestNeeded: Api.Bool?, title: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1110823051) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeString(link, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(expireDate!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeInt32(usageLimit!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 3) != 0 { + requestNeeded!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 4) != 0 { + serializeString(title!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.editExportedChatInvite", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("link", String(describing: link)), ("expireDate", String(describing: expireDate)), ("usageLimit", String(describing: usageLimit)), ("requestNeeded", String(describing: requestNeeded)), ("title", String(describing: title))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ExportedChatInvite? in + let reader = BufferReader(buffer) + var result: Api.messages.ExportedChatInvite? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.ExportedChatInvite + } + return result + }) + } +} +public extension Api.functions.messages { + static func editFactCheck(peer: Api.InputPeer, msgId: Int32, text: Api.TextWithEntities) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(92925557) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + text.serialize(buffer, true) + return (FunctionDescription(name: "messages.editFactCheck", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("text", String(describing: text))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func editForumTopic(flags: Int32, peer: Api.InputPeer, topicId: Int32, title: String?, iconEmojiId: Int64?, closed: Api.Bool?, hidden: Api.Bool?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-825487052) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(topicId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(title!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeInt64(iconEmojiId!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + closed!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 3) != 0 { + hidden!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.editForumTopic", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("topicId", String(describing: topicId)), ("title", String(describing: title)), ("iconEmojiId", String(describing: iconEmojiId)), ("closed", String(describing: closed)), ("hidden", String(describing: hidden))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func editInlineBotMessage(flags: Int32, id: Api.InputBotInlineMessageID, message: String?, media: Api.InputMedia?, replyMarkup: Api.ReplyMarkup?, entities: [Api.MessageEntity]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2091549254) + serializeInt32(flags, buffer: buffer, boxed: false) + id.serialize(buffer, true) + if Int(flags) & Int(1 << 11) != 0 { + serializeString(message!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 14) != 0 { + media!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 2) != 0 { + replyMarkup!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(entities!.count)) + for item in entities! { + item.serialize(buffer, true) + } + } + return (FunctionDescription(name: "messages.editInlineBotMessage", parameters: [("flags", String(describing: flags)), ("id", String(describing: id)), ("message", String(describing: message)), ("media", String(describing: media)), ("replyMarkup", String(describing: replyMarkup)), ("entities", String(describing: entities))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func editMessage(flags: Int32, peer: Api.InputPeer, id: Int32, message: String?, media: Api.InputMedia?, replyMarkup: Api.ReplyMarkup?, entities: [Api.MessageEntity]?, scheduleDate: Int32?, scheduleRepeatPeriod: Int32?, quickReplyShortcutId: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1374175969) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 11) != 0 { + serializeString(message!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 14) != 0 { + media!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 2) != 0 { + replyMarkup!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(entities!.count)) + for item in entities! { + item.serialize(buffer, true) + } + } + if Int(flags) & Int(1 << 15) != 0 { + serializeInt32(scheduleDate!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 18) != 0 { + serializeInt32(scheduleRepeatPeriod!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 17) != 0 { + serializeInt32(quickReplyShortcutId!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.editMessage", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("message", String(describing: message)), ("media", String(describing: media)), ("replyMarkup", String(describing: replyMarkup)), ("entities", String(describing: entities)), ("scheduleDate", String(describing: scheduleDate)), ("scheduleRepeatPeriod", String(describing: scheduleRepeatPeriod)), ("quickReplyShortcutId", String(describing: quickReplyShortcutId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func editQuickReplyShortcut(shortcutId: Int32, shortcut: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1543519471) + serializeInt32(shortcutId, buffer: buffer, boxed: false) + serializeString(shortcut, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.editQuickReplyShortcut", parameters: [("shortcutId", String(describing: shortcutId)), ("shortcut", String(describing: shortcut))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func exportChatInvite(flags: Int32, peer: Api.InputPeer, expireDate: Int32?, usageLimit: Int32?, title: String?, subscriptionPricing: Api.StarsSubscriptionPricing?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1537876336) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(expireDate!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeInt32(usageLimit!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 4) != 0 { + serializeString(title!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 5) != 0 { + subscriptionPricing!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.exportChatInvite", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("expireDate", String(describing: expireDate)), ("usageLimit", String(describing: usageLimit)), ("title", String(describing: title)), ("subscriptionPricing", String(describing: subscriptionPricing))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ExportedChatInvite? in + let reader = BufferReader(buffer) + var result: Api.ExportedChatInvite? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.ExportedChatInvite + } + return result + }) + } +} +public extension Api.functions.messages { + static func faveSticker(id: Api.InputDocument, unfave: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1174420133) + id.serialize(buffer, true) + unfave.serialize(buffer, true) + return (FunctionDescription(name: "messages.faveSticker", parameters: [("id", String(describing: id)), ("unfave", String(describing: unfave))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func forwardMessages(flags: Int32, fromPeer: Api.InputPeer, id: [Int32], randomId: [Int64], toPeer: Api.InputPeer, topMsgId: Int32?, replyTo: Api.InputReplyTo?, scheduleDate: Int32?, scheduleRepeatPeriod: Int32?, sendAs: Api.InputPeer?, quickReplyShortcut: Api.InputQuickReplyShortcut?, effect: Int64?, videoTimestamp: Int32?, allowPaidStars: Int64?, suggestedPost: Api.SuggestedPost?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(326126204) + serializeInt32(flags, buffer: buffer, boxed: false) + fromPeer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(randomId.count)) + for item in randomId { + serializeInt64(item, buffer: buffer, boxed: false) + } + toPeer.serialize(buffer, true) + if Int(flags) & Int(1 << 9) != 0 { + serializeInt32(topMsgId!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 22) != 0 { + replyTo!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 10) != 0 { + serializeInt32(scheduleDate!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 24) != 0 { + serializeInt32(scheduleRepeatPeriod!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 13) != 0 { + sendAs!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 17) != 0 { + quickReplyShortcut!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 18) != 0 { + serializeInt64(effect!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 20) != 0 { + serializeInt32(videoTimestamp!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 21) != 0 { + serializeInt64(allowPaidStars!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 23) != 0 { + suggestedPost!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.forwardMessages", parameters: [("flags", String(describing: flags)), ("fromPeer", String(describing: fromPeer)), ("id", String(describing: id)), ("randomId", String(describing: randomId)), ("toPeer", String(describing: toPeer)), ("topMsgId", String(describing: topMsgId)), ("replyTo", String(describing: replyTo)), ("scheduleDate", String(describing: scheduleDate)), ("scheduleRepeatPeriod", String(describing: scheduleRepeatPeriod)), ("sendAs", String(describing: sendAs)), ("quickReplyShortcut", String(describing: quickReplyShortcut)), ("effect", String(describing: effect)), ("videoTimestamp", String(describing: videoTimestamp)), ("allowPaidStars", String(describing: allowPaidStars)), ("suggestedPost", String(describing: suggestedPost))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func getAdminsWithInvites(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(958457583) + peer.serialize(buffer, true) + return (FunctionDescription(name: "messages.getAdminsWithInvites", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ChatAdminsWithInvites? in + let reader = BufferReader(buffer) + var result: Api.messages.ChatAdminsWithInvites? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.ChatAdminsWithInvites + } + return result + }) + } +} +public extension Api.functions.messages { + static func getAllDrafts() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1782549861) + return (FunctionDescription(name: "messages.getAllDrafts", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func getAllStickers(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1197432408) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getAllStickers", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AllStickers? in + let reader = BufferReader(buffer) + var result: Api.messages.AllStickers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AllStickers + } + return result + }) + } +} +public extension Api.functions.messages { + static func getArchivedStickers(flags: Int32, offsetId: Int64, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1475442322) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt64(offsetId, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getArchivedStickers", parameters: [("flags", String(describing: flags)), ("offsetId", String(describing: offsetId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ArchivedStickers? in + let reader = BufferReader(buffer) + var result: Api.messages.ArchivedStickers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.ArchivedStickers + } + return result + }) + } +} +public extension Api.functions.messages { + static func getAttachMenuBot(bot: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1998676370) + bot.serialize(buffer, true) + return (FunctionDescription(name: "messages.getAttachMenuBot", parameters: [("bot", String(describing: bot))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.AttachMenuBotsBot? in + let reader = BufferReader(buffer) + var result: Api.AttachMenuBotsBot? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.AttachMenuBotsBot + } + return result + }) + } +} +public extension Api.functions.messages { + static func getAttachMenuBots(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(385663691) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getAttachMenuBots", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.AttachMenuBots? in + let reader = BufferReader(buffer) + var result: Api.AttachMenuBots? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.AttachMenuBots + } + return result + }) + } +} +public extension Api.functions.messages { + static func getAttachedStickers(media: Api.InputStickeredMedia) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.StickerSetCovered]>) { + let buffer = Buffer() + buffer.appendInt32(-866424884) + media.serialize(buffer, true) + return (FunctionDescription(name: "messages.getAttachedStickers", parameters: [("media", String(describing: media))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.StickerSetCovered]? in + let reader = BufferReader(buffer) + var result: [Api.StickerSetCovered]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.StickerSetCovered.self) + } + return result + }) + } +} +public extension Api.functions.messages { + static func getAvailableEffects(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-559805895) + serializeInt32(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getAvailableEffects", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AvailableEffects? in + let reader = BufferReader(buffer) + var result: Api.messages.AvailableEffects? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AvailableEffects + } + return result + }) + } +} +public extension Api.functions.messages { + static func getAvailableReactions(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(417243308) + serializeInt32(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getAvailableReactions", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AvailableReactions? in + let reader = BufferReader(buffer) + var result: Api.messages.AvailableReactions? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AvailableReactions + } + return result + }) + } +} +public extension Api.functions.messages { + static func getBotApp(app: Api.InputBotApp, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(889046467) + app.serialize(buffer, true) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getBotApp", parameters: [("app", String(describing: app)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.BotApp? in + let reader = BufferReader(buffer) + var result: Api.messages.BotApp? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.BotApp + } + return result + }) + } +} +public extension Api.functions.messages { + static func getBotCallbackAnswer(flags: Int32, peer: Api.InputPeer, msgId: Int32, data: Buffer?, password: Api.InputCheckPasswordSRP?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1824339449) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeBytes(data!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + password!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.getBotCallbackAnswer", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("data", String(describing: data)), ("password", String(describing: password))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.BotCallbackAnswer? in + let reader = BufferReader(buffer) + var result: Api.messages.BotCallbackAnswer? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.BotCallbackAnswer + } + return result + }) + } +} +public extension Api.functions.messages { + static func getChatInviteImporters(flags: Int32, peer: Api.InputPeer, link: String?, q: String?, offsetDate: Int32, offsetUser: Api.InputUser, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-553329330) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 1) != 0 { + serializeString(link!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + serializeString(q!, buffer: buffer, boxed: false) + } + serializeInt32(offsetDate, buffer: buffer, boxed: false) + offsetUser.serialize(buffer, true) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getChatInviteImporters", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("link", String(describing: link)), ("q", String(describing: q)), ("offsetDate", String(describing: offsetDate)), ("offsetUser", String(describing: offsetUser)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ChatInviteImporters? in + let reader = BufferReader(buffer) + var result: Api.messages.ChatInviteImporters? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.ChatInviteImporters + } + return result + }) + } +} +public extension Api.functions.messages { + static func getChats(id: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1240027791) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt64(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.getChats", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in + let reader = BufferReader(buffer) + var result: Api.messages.Chats? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Chats + } + return result + }) + } +} +public extension Api.functions.messages { + static func getCommonChats(userId: Api.InputUser, maxId: Int64, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-468934396) + userId.serialize(buffer, true) + serializeInt64(maxId, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getCommonChats", parameters: [("userId", String(describing: userId)), ("maxId", String(describing: maxId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in + let reader = BufferReader(buffer) + var result: Api.messages.Chats? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Chats + } + return result + }) + } +} +public extension Api.functions.messages { + static func getCustomEmojiDocuments(documentId: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.Document]>) { + let buffer = Buffer() + buffer.appendInt32(-643100844) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(documentId.count)) + for item in documentId { + serializeInt64(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.getCustomEmojiDocuments", parameters: [("documentId", String(describing: documentId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.Document]? in + let reader = BufferReader(buffer) + var result: [Api.Document]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.Document.self) + } + return result + }) + } +} +public extension Api.functions.messages { + static func getDefaultHistoryTTL() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1703637384) + return (FunctionDescription(name: "messages.getDefaultHistoryTTL", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.DefaultHistoryTTL? in + let reader = BufferReader(buffer) + var result: Api.DefaultHistoryTTL? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.DefaultHistoryTTL + } + return result + }) + } +} +public extension Api.functions.messages { + static func getDefaultTagReactions(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1107741656) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getDefaultTagReactions", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Reactions? in + let reader = BufferReader(buffer) + var result: Api.messages.Reactions? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Reactions + } + return result + }) + } +} +public extension Api.functions.messages { + static func getDhConfig(version: Int32, randomLength: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(651135312) + serializeInt32(version, buffer: buffer, boxed: false) + serializeInt32(randomLength, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getDhConfig", parameters: [("version", String(describing: version)), ("randomLength", String(describing: randomLength))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.DhConfig? in + let reader = BufferReader(buffer) + var result: Api.messages.DhConfig? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.DhConfig + } + return result + }) + } +} +public extension Api.functions.messages { + static func getDialogFilters() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-271283063) + return (FunctionDescription(name: "messages.getDialogFilters", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.DialogFilters? in + let reader = BufferReader(buffer) + var result: Api.messages.DialogFilters? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.DialogFilters + } + return result + }) + } +} +public extension Api.functions.messages { + static func getDialogUnreadMarks(flags: Int32, parentPeer: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.DialogPeer]>) { + let buffer = Buffer() + buffer.appendInt32(555754018) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + parentPeer!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.getDialogUnreadMarks", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.DialogPeer]? in + let reader = BufferReader(buffer) + var result: [Api.DialogPeer]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.DialogPeer.self) + } + return result + }) + } +} +public extension Api.functions.messages { + static func getDialogs(flags: Int32, folderId: Int32?, offsetDate: Int32, offsetId: Int32, offsetPeer: Api.InputPeer, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1594569905) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 1) != 0 { + serializeInt32(folderId!, buffer: buffer, boxed: false) + } + serializeInt32(offsetDate, buffer: buffer, boxed: false) + serializeInt32(offsetId, buffer: buffer, boxed: false) + offsetPeer.serialize(buffer, true) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getDialogs", parameters: [("flags", String(describing: flags)), ("folderId", String(describing: folderId)), ("offsetDate", String(describing: offsetDate)), ("offsetId", String(describing: offsetId)), ("offsetPeer", String(describing: offsetPeer)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Dialogs? in + let reader = BufferReader(buffer) + var result: Api.messages.Dialogs? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Dialogs + } + return result + }) + } +} +public extension Api.functions.messages { + static func getDiscussionMessage(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1147761405) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getDiscussionMessage", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.DiscussionMessage? in + let reader = BufferReader(buffer) + var result: Api.messages.DiscussionMessage? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.DiscussionMessage + } + return result + }) + } +} +public extension Api.functions.messages { + static func getDocumentByHash(sha256: Buffer, size: Int64, mimeType: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1309538785) + serializeBytes(sha256, buffer: buffer, boxed: false) + serializeInt64(size, buffer: buffer, boxed: false) + serializeString(mimeType, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getDocumentByHash", parameters: [("sha256", String(describing: sha256)), ("size", String(describing: size)), ("mimeType", String(describing: mimeType))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Document? in + let reader = BufferReader(buffer) + var result: Api.Document? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Document + } + return result + }) + } +} +public extension Api.functions.messages { + static func getEmojiGameInfo() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-75592537) + return (FunctionDescription(name: "messages.getEmojiGameInfo", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.EmojiGameInfo? in + let reader = BufferReader(buffer) + var result: Api.messages.EmojiGameInfo? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.EmojiGameInfo + } + return result + }) + } +} +public extension Api.functions.messages { + static func getEmojiGroups(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1955122779) + serializeInt32(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getEmojiGroups", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.EmojiGroups? in + let reader = BufferReader(buffer) + var result: Api.messages.EmojiGroups? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.EmojiGroups + } + return result + }) + } +} +public extension Api.functions.messages { + static func getEmojiKeywords(langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(899735650) + serializeString(langCode, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getEmojiKeywords", parameters: [("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiKeywordsDifference? in + let reader = BufferReader(buffer) + var result: Api.EmojiKeywordsDifference? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.EmojiKeywordsDifference + } + return result + }) + } +} +public extension Api.functions.messages { + static func getEmojiKeywordsDifference(langCode: String, fromVersion: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(352892591) + serializeString(langCode, buffer: buffer, boxed: false) + serializeInt32(fromVersion, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getEmojiKeywordsDifference", parameters: [("langCode", String(describing: langCode)), ("fromVersion", String(describing: fromVersion))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiKeywordsDifference? in + let reader = BufferReader(buffer) + var result: Api.EmojiKeywordsDifference? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.EmojiKeywordsDifference + } + return result + }) + } +} +public extension Api.functions.messages { + static func getEmojiKeywordsLanguages(langCodes: [String]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.EmojiLanguage]>) { + let buffer = Buffer() + buffer.appendInt32(1318675378) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(langCodes.count)) + for item in langCodes { + serializeString(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.getEmojiKeywordsLanguages", parameters: [("langCodes", String(describing: langCodes))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.EmojiLanguage]? in + let reader = BufferReader(buffer) + var result: [Api.EmojiLanguage]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.EmojiLanguage.self) + } + return result + }) + } +} +public extension Api.functions.messages { + static func getEmojiProfilePhotoGroups(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(564480243) + serializeInt32(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getEmojiProfilePhotoGroups", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.EmojiGroups? in + let reader = BufferReader(buffer) + var result: Api.messages.EmojiGroups? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.EmojiGroups + } + return result + }) + } +} +public extension Api.functions.messages { + static func getEmojiStatusGroups(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(785209037) + serializeInt32(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getEmojiStatusGroups", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.EmojiGroups? in + let reader = BufferReader(buffer) + var result: Api.messages.EmojiGroups? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.EmojiGroups + } + return result + }) + } +} +public extension Api.functions.messages { + static func getEmojiStickerGroups(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(500711669) + serializeInt32(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getEmojiStickerGroups", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.EmojiGroups? in + let reader = BufferReader(buffer) + var result: Api.messages.EmojiGroups? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.EmojiGroups + } + return result + }) + } +} +public extension Api.functions.messages { + static func getEmojiStickers(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-67329649) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getEmojiStickers", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AllStickers? in + let reader = BufferReader(buffer) + var result: Api.messages.AllStickers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AllStickers + } + return result + }) + } +} +public extension Api.functions.messages { + static func getEmojiURL(langCode: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-709817306) + serializeString(langCode, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getEmojiURL", parameters: [("langCode", String(describing: langCode))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiURL? in + let reader = BufferReader(buffer) + var result: Api.EmojiURL? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.EmojiURL + } + return result + }) + } +} +public extension Api.functions.messages { + static func getExportedChatInvite(peer: Api.InputPeer, link: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1937010524) + peer.serialize(buffer, true) + serializeString(link, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getExportedChatInvite", parameters: [("peer", String(describing: peer)), ("link", String(describing: link))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ExportedChatInvite? in + let reader = BufferReader(buffer) + var result: Api.messages.ExportedChatInvite? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.ExportedChatInvite + } + return result + }) + } +} +public extension Api.functions.messages { + static func getExportedChatInvites(flags: Int32, peer: Api.InputPeer, adminId: Api.InputUser, offsetDate: Int32?, offsetLink: String?, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1565154314) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + adminId.serialize(buffer, true) + if Int(flags) & Int(1 << 2) != 0 { + serializeInt32(offsetDate!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + serializeString(offsetLink!, buffer: buffer, boxed: false) + } + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getExportedChatInvites", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("adminId", String(describing: adminId)), ("offsetDate", String(describing: offsetDate)), ("offsetLink", String(describing: offsetLink)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ExportedChatInvites? in + let reader = BufferReader(buffer) + var result: Api.messages.ExportedChatInvites? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.ExportedChatInvites + } + return result + }) + } +} +public extension Api.functions.messages { + static func getExtendedMedia(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2064119788) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.getExtendedMedia", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func getFactCheck(peer: Api.InputPeer, msgId: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.FactCheck]>) { + let buffer = Buffer() + buffer.appendInt32(-1177696786) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(msgId.count)) + for item in msgId { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.getFactCheck", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.FactCheck]? in + let reader = BufferReader(buffer) + var result: [Api.FactCheck]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.FactCheck.self) + } + return result + }) + } +} +public extension Api.functions.messages { + static func getFavedStickers(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(82946729) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getFavedStickers", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.FavedStickers? in + let reader = BufferReader(buffer) + var result: Api.messages.FavedStickers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.FavedStickers + } + return result + }) + } +} +public extension Api.functions.messages { + static func getFeaturedEmojiStickers(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(248473398) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getFeaturedEmojiStickers", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.FeaturedStickers? in + let reader = BufferReader(buffer) + var result: Api.messages.FeaturedStickers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.FeaturedStickers + } + return result + }) + } +} +public extension Api.functions.messages { + static func getFeaturedStickers(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1685588756) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getFeaturedStickers", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.FeaturedStickers? in + let reader = BufferReader(buffer) + var result: Api.messages.FeaturedStickers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.FeaturedStickers + } + return result + }) + } +} +public extension Api.functions.messages { + static func getForumTopics(flags: Int32, peer: Api.InputPeer, q: String?, offsetDate: Int32, offsetId: Int32, offsetTopic: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1000635391) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(q!, buffer: buffer, boxed: false) + } + serializeInt32(offsetDate, buffer: buffer, boxed: false) + serializeInt32(offsetId, buffer: buffer, boxed: false) + serializeInt32(offsetTopic, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getForumTopics", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("q", String(describing: q)), ("offsetDate", String(describing: offsetDate)), ("offsetId", String(describing: offsetId)), ("offsetTopic", String(describing: offsetTopic)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ForumTopics? in + let reader = BufferReader(buffer) + var result: Api.messages.ForumTopics? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.ForumTopics + } + return result + }) + } +} +public extension Api.functions.messages { + static func getForumTopicsByID(peer: Api.InputPeer, topics: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1358280184) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(topics.count)) + for item in topics { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.getForumTopicsByID", parameters: [("peer", String(describing: peer)), ("topics", String(describing: topics))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ForumTopics? in + let reader = BufferReader(buffer) + var result: Api.messages.ForumTopics? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.ForumTopics + } + return result + }) + } +} +public extension Api.functions.messages { + static func getFullChat(chatId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1364194508) + serializeInt64(chatId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getFullChat", parameters: [("chatId", String(describing: chatId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.ChatFull? in + let reader = BufferReader(buffer) + var result: Api.messages.ChatFull? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.ChatFull + } + return result + }) + } +} +public extension Api.functions.messages { + static func getGameHighScores(peer: Api.InputPeer, id: Int32, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-400399203) + peer.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + userId.serialize(buffer, true) + return (FunctionDescription(name: "messages.getGameHighScores", parameters: [("peer", String(describing: peer)), ("id", String(describing: id)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.HighScores? in + let reader = BufferReader(buffer) + var result: Api.messages.HighScores? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.HighScores + } + return result + }) + } +} +public extension Api.functions.messages { + static func getHistory(peer: Api.InputPeer, offsetId: Int32, offsetDate: Int32, addOffset: Int32, limit: Int32, maxId: Int32, minId: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1143203525) + peer.serialize(buffer, true) + serializeInt32(offsetId, buffer: buffer, boxed: false) + serializeInt32(offsetDate, buffer: buffer, boxed: false) + serializeInt32(addOffset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt32(maxId, buffer: buffer, boxed: false) + serializeInt32(minId, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getHistory", parameters: [("peer", String(describing: peer)), ("offsetId", String(describing: offsetId)), ("offsetDate", String(describing: offsetDate)), ("addOffset", String(describing: addOffset)), ("limit", String(describing: limit)), ("maxId", String(describing: maxId)), ("minId", String(describing: minId)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in + let reader = BufferReader(buffer) + var result: Api.messages.Messages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Messages + } + return result + }) + } +} +public extension Api.functions.messages { + static func getInlineBotResults(flags: Int32, bot: Api.InputUser, peer: Api.InputPeer, geoPoint: Api.InputGeoPoint?, query: String, offset: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1364105629) + serializeInt32(flags, buffer: buffer, boxed: false) + bot.serialize(buffer, true) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + geoPoint!.serialize(buffer, true) + } + serializeString(query, buffer: buffer, boxed: false) + serializeString(offset, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getInlineBotResults", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("peer", String(describing: peer)), ("geoPoint", String(describing: geoPoint)), ("query", String(describing: query)), ("offset", String(describing: offset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.BotResults? in + let reader = BufferReader(buffer) + var result: Api.messages.BotResults? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.BotResults + } + return result + }) + } +} +public extension Api.functions.messages { + static func getInlineGameHighScores(id: Api.InputBotInlineMessageID, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(258170395) + id.serialize(buffer, true) + userId.serialize(buffer, true) + return (FunctionDescription(name: "messages.getInlineGameHighScores", parameters: [("id", String(describing: id)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.HighScores? in + let reader = BufferReader(buffer) + var result: Api.messages.HighScores? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.HighScores + } + return result + }) + } +} +public extension Api.functions.messages { + static func getMaskStickers(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1678738104) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getMaskStickers", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AllStickers? in + let reader = BufferReader(buffer) + var result: Api.messages.AllStickers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AllStickers + } + return result + }) + } +} +public extension Api.functions.messages { + static func getMessageEditData(peer: Api.InputPeer, id: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-39416522) + peer.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getMessageEditData", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.MessageEditData? in + let reader = BufferReader(buffer) + var result: Api.messages.MessageEditData? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.MessageEditData + } + return result + }) + } +} +public extension Api.functions.messages { + static func getMessageReactionsList(flags: Int32, peer: Api.InputPeer, id: Int32, reaction: Api.Reaction?, offset: String?, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1176190792) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + reaction!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeString(offset!, buffer: buffer, boxed: false) + } + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getMessageReactionsList", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("reaction", String(describing: reaction)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.MessageReactionsList? in + let reader = BufferReader(buffer) + var result: Api.messages.MessageReactionsList? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.MessageReactionsList + } + return result + }) + } +} +public extension Api.functions.messages { + static func getMessageReadParticipants(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.ReadParticipantDate]>) { + let buffer = Buffer() + buffer.appendInt32(834782287) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getMessageReadParticipants", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.ReadParticipantDate]? in + let reader = BufferReader(buffer) + var result: [Api.ReadParticipantDate]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.ReadParticipantDate.self) + } + return result + }) + } +} +public extension Api.functions.messages { + static func getMessages(id: [Api.InputMessage]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1673946374) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.getMessages", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in + let reader = BufferReader(buffer) + var result: Api.messages.Messages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Messages + } + return result + }) + } +} +public extension Api.functions.messages { + static func getMessagesReactions(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1950707482) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.getMessagesReactions", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func getMessagesViews(peer: Api.InputPeer, id: [Int32], increment: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1468322785) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + increment.serialize(buffer, true) + return (FunctionDescription(name: "messages.getMessagesViews", parameters: [("peer", String(describing: peer)), ("id", String(describing: id)), ("increment", String(describing: increment))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.MessageViews? in + let reader = BufferReader(buffer) + var result: Api.messages.MessageViews? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.MessageViews + } + return result + }) + } +} +public extension Api.functions.messages { + static func getMyStickers(offsetId: Int64, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-793386500) + serializeInt64(offsetId, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getMyStickers", parameters: [("offsetId", String(describing: offsetId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.MyStickers? in + let reader = BufferReader(buffer) + var result: Api.messages.MyStickers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.MyStickers + } + return result + }) + } +} +public extension Api.functions.messages { + static func getOldFeaturedStickers(offset: Int32, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2127598753) + serializeInt32(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getOldFeaturedStickers", parameters: [("offset", String(describing: offset)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.FeaturedStickers? in + let reader = BufferReader(buffer) + var result: Api.messages.FeaturedStickers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.FeaturedStickers + } + return result + }) + } +} +public extension Api.functions.messages { + static func getOnlines(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1848369232) + peer.serialize(buffer, true) + return (FunctionDescription(name: "messages.getOnlines", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ChatOnlines? in + let reader = BufferReader(buffer) + var result: Api.ChatOnlines? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.ChatOnlines + } + return result + }) + } +} +public extension Api.functions.messages { + static func getOutboxReadDate(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1941176739) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getOutboxReadDate", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.OutboxReadDate? in + let reader = BufferReader(buffer) + var result: Api.OutboxReadDate? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.OutboxReadDate + } + return result + }) + } +} +public extension Api.functions.messages { + static func getPaidReactionPrivacy() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1193563562) + return (FunctionDescription(name: "messages.getPaidReactionPrivacy", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func getPeerDialogs(peers: [Api.InputDialogPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-462373635) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(peers.count)) + for item in peers { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.getPeerDialogs", parameters: [("peers", String(describing: peers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.PeerDialogs? in + let reader = BufferReader(buffer) + var result: Api.messages.PeerDialogs? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.PeerDialogs + } + return result + }) + } +} +public extension Api.functions.messages { + static func getPeerSettings(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-270948702) + peer.serialize(buffer, true) + return (FunctionDescription(name: "messages.getPeerSettings", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.PeerSettings? in + let reader = BufferReader(buffer) + var result: Api.messages.PeerSettings? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.PeerSettings + } + return result + }) + } +} +public extension Api.functions.messages { + static func getPinnedDialogs(folderId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-692498958) + serializeInt32(folderId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getPinnedDialogs", parameters: [("folderId", String(describing: folderId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.PeerDialogs? in + let reader = BufferReader(buffer) + var result: Api.messages.PeerDialogs? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.PeerDialogs + } + return result + }) + } +} +public extension Api.functions.messages { + static func getPinnedSavedDialogs() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-700607264) + return (FunctionDescription(name: "messages.getPinnedSavedDialogs", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SavedDialogs? in + let reader = BufferReader(buffer) + var result: Api.messages.SavedDialogs? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.SavedDialogs + } + return result + }) + } +} +public extension Api.functions.messages { + static func getPollResults(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1941660731) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getPollResults", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func getPollVotes(flags: Int32, peer: Api.InputPeer, id: Int32, option: Buffer?, offset: String?, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1200736242) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeBytes(option!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeString(offset!, buffer: buffer, boxed: false) + } + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getPollVotes", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("option", String(describing: option)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.VotesList? in + let reader = BufferReader(buffer) + var result: Api.messages.VotesList? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.VotesList + } + return result + }) + } +} +public extension Api.functions.messages { + static func getPreparedInlineMessage(bot: Api.InputUser, id: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2055291464) + bot.serialize(buffer, true) + serializeString(id, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getPreparedInlineMessage", parameters: [("bot", String(describing: bot)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.PreparedInlineMessage? in + let reader = BufferReader(buffer) + var result: Api.messages.PreparedInlineMessage? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.PreparedInlineMessage + } + return result + }) + } +} +public extension Api.functions.messages { + static func getQuickReplies(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-729550168) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getQuickReplies", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.QuickReplies? in + let reader = BufferReader(buffer) + var result: Api.messages.QuickReplies? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.QuickReplies + } + return result + }) + } +} +public extension Api.functions.messages { + static func getQuickReplyMessages(flags: Int32, shortcutId: Int32, id: [Int32]?, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1801153085) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt32(shortcutId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id!.count)) + for item in id! { + serializeInt32(item, buffer: buffer, boxed: false) + } + } + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getQuickReplyMessages", parameters: [("flags", String(describing: flags)), ("shortcutId", String(describing: shortcutId)), ("id", String(describing: id)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in + let reader = BufferReader(buffer) + var result: Api.messages.Messages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Messages + } + return result + }) + } +} +public extension Api.functions.messages { + static func getRecentLocations(peer: Api.InputPeer, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1881817312) + peer.serialize(buffer, true) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getRecentLocations", parameters: [("peer", String(describing: peer)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in + let reader = BufferReader(buffer) + var result: Api.messages.Messages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Messages + } + return result + }) + } +} +public extension Api.functions.messages { + static func getRecentReactions(limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(960896434) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getRecentReactions", parameters: [("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Reactions? in + let reader = BufferReader(buffer) + var result: Api.messages.Reactions? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Reactions + } + return result + }) + } +} +public extension Api.functions.messages { + static func getRecentStickers(flags: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1649852357) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getRecentStickers", parameters: [("flags", String(describing: flags)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.RecentStickers? in + let reader = BufferReader(buffer) + var result: Api.messages.RecentStickers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.RecentStickers + } + return result + }) + } +} +public extension Api.functions.messages { + static func getReplies(peer: Api.InputPeer, msgId: Int32, offsetId: Int32, offsetDate: Int32, addOffset: Int32, limit: Int32, maxId: Int32, minId: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(584962828) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + serializeInt32(offsetId, buffer: buffer, boxed: false) + serializeInt32(offsetDate, buffer: buffer, boxed: false) + serializeInt32(addOffset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt32(maxId, buffer: buffer, boxed: false) + serializeInt32(minId, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getReplies", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("offsetId", String(describing: offsetId)), ("offsetDate", String(describing: offsetDate)), ("addOffset", String(describing: addOffset)), ("limit", String(describing: limit)), ("maxId", String(describing: maxId)), ("minId", String(describing: minId)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in + let reader = BufferReader(buffer) + var result: Api.messages.Messages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Messages + } + return result + }) + } +} +public extension Api.functions.messages { + static func getSavedDialogs(flags: Int32, parentPeer: Api.InputPeer?, offsetDate: Int32, offsetId: Int32, offsetPeer: Api.InputPeer, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(512883865) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 1) != 0 { + parentPeer!.serialize(buffer, true) + } + serializeInt32(offsetDate, buffer: buffer, boxed: false) + serializeInt32(offsetId, buffer: buffer, boxed: false) + offsetPeer.serialize(buffer, true) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getSavedDialogs", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer)), ("offsetDate", String(describing: offsetDate)), ("offsetId", String(describing: offsetId)), ("offsetPeer", String(describing: offsetPeer)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SavedDialogs? in + let reader = BufferReader(buffer) + var result: Api.messages.SavedDialogs? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.SavedDialogs + } + return result + }) + } +} +public extension Api.functions.messages { + static func getSavedDialogsByID(flags: Int32, parentPeer: Api.InputPeer?, ids: [Api.InputPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1869585558) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 1) != 0 { + parentPeer!.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(ids.count)) + for item in ids { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.getSavedDialogsByID", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer)), ("ids", String(describing: ids))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SavedDialogs? in + let reader = BufferReader(buffer) + var result: Api.messages.SavedDialogs? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.SavedDialogs + } + return result + }) + } +} +public extension Api.functions.messages { + static func getSavedGifs(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1559270965) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getSavedGifs", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SavedGifs? in + let reader = BufferReader(buffer) + var result: Api.messages.SavedGifs? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.SavedGifs + } + return result + }) + } +} +public extension Api.functions.messages { + static func getSavedHistory(flags: Int32, parentPeer: Api.InputPeer?, peer: Api.InputPeer, offsetId: Int32, offsetDate: Int32, addOffset: Int32, limit: Int32, maxId: Int32, minId: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1718964215) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + parentPeer!.serialize(buffer, true) + } + peer.serialize(buffer, true) + serializeInt32(offsetId, buffer: buffer, boxed: false) + serializeInt32(offsetDate, buffer: buffer, boxed: false) + serializeInt32(addOffset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt32(maxId, buffer: buffer, boxed: false) + serializeInt32(minId, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getSavedHistory", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer)), ("peer", String(describing: peer)), ("offsetId", String(describing: offsetId)), ("offsetDate", String(describing: offsetDate)), ("addOffset", String(describing: addOffset)), ("limit", String(describing: limit)), ("maxId", String(describing: maxId)), ("minId", String(describing: minId)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in + let reader = BufferReader(buffer) + var result: Api.messages.Messages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Messages + } + return result + }) + } +} +public extension Api.functions.messages { + static func getSavedReactionTags(flags: Int32, peer: Api.InputPeer?, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(909631579) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + peer!.serialize(buffer, true) + } + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getSavedReactionTags", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SavedReactionTags? in + let reader = BufferReader(buffer) + var result: Api.messages.SavedReactionTags? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.SavedReactionTags + } + return result + }) + } +} +public extension Api.functions.messages { + static func getScheduledHistory(peer: Api.InputPeer, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-183077365) + peer.serialize(buffer, true) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getScheduledHistory", parameters: [("peer", String(describing: peer)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in + let reader = BufferReader(buffer) + var result: Api.messages.Messages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Messages + } + return result + }) + } +} +public extension Api.functions.messages { + static func getScheduledMessages(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1111817116) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.getScheduledMessages", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in + let reader = BufferReader(buffer) + var result: Api.messages.Messages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Messages + } + return result + }) + } +} +public extension Api.functions.messages { + static func getSearchCounters(flags: Int32, peer: Api.InputPeer, savedPeerId: Api.InputPeer?, topMsgId: Int32?, filters: [Api.MessagesFilter]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.messages.SearchCounter]>) { + let buffer = Buffer() + buffer.appendInt32(465367808) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 2) != 0 { + savedPeerId!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(topMsgId!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(filters.count)) + for item in filters { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.getSearchCounters", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("savedPeerId", String(describing: savedPeerId)), ("topMsgId", String(describing: topMsgId)), ("filters", String(describing: filters))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.messages.SearchCounter]? in + let reader = BufferReader(buffer) + var result: [Api.messages.SearchCounter]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.messages.SearchCounter.self) + } + return result + }) + } +} +public extension Api.functions.messages { + static func getSearchResultsCalendar(flags: Int32, peer: Api.InputPeer, savedPeerId: Api.InputPeer?, filter: Api.MessagesFilter, offsetId: Int32, offsetDate: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1789130429) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 2) != 0 { + savedPeerId!.serialize(buffer, true) + } + filter.serialize(buffer, true) + serializeInt32(offsetId, buffer: buffer, boxed: false) + serializeInt32(offsetDate, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getSearchResultsCalendar", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("savedPeerId", String(describing: savedPeerId)), ("filter", String(describing: filter)), ("offsetId", String(describing: offsetId)), ("offsetDate", String(describing: offsetDate))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SearchResultsCalendar? in + let reader = BufferReader(buffer) + var result: Api.messages.SearchResultsCalendar? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.SearchResultsCalendar + } + return result + }) + } +} +public extension Api.functions.messages { + static func getSearchResultsPositions(flags: Int32, peer: Api.InputPeer, savedPeerId: Api.InputPeer?, filter: Api.MessagesFilter, offsetId: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1669386480) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 2) != 0 { + savedPeerId!.serialize(buffer, true) + } + filter.serialize(buffer, true) + serializeInt32(offsetId, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getSearchResultsPositions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("savedPeerId", String(describing: savedPeerId)), ("filter", String(describing: filter)), ("offsetId", String(describing: offsetId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SearchResultsPositions? in + let reader = BufferReader(buffer) + var result: Api.messages.SearchResultsPositions? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.SearchResultsPositions + } + return result + }) + } +} +public extension Api.functions.messages { + static func getSplitRanges() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.MessageRange]>) { + let buffer = Buffer() + buffer.appendInt32(486505992) + return (FunctionDescription(name: "messages.getSplitRanges", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.MessageRange]? in + let reader = BufferReader(buffer) + var result: [Api.MessageRange]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageRange.self) + } + return result + }) + } +} +public extension Api.functions.messages { + static func getSponsoredMessages(flags: Int32, peer: Api.InputPeer, msgId: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1030547536) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(msgId!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.getSponsoredMessages", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SponsoredMessages? in + let reader = BufferReader(buffer) + var result: Api.messages.SponsoredMessages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.SponsoredMessages + } + return result + }) + } +} +public extension Api.functions.messages { + static func getStickerSet(stickerset: Api.InputStickerSet, hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-928977804) + stickerset.serialize(buffer, true) + serializeInt32(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getStickerSet", parameters: [("stickerset", String(describing: stickerset)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in + let reader = BufferReader(buffer) + var result: Api.messages.StickerSet? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet + } + return result + }) + } +} +public extension Api.functions.messages { + static func getStickers(emoticon: String, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-710552671) + serializeString(emoticon, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getStickers", parameters: [("emoticon", String(describing: emoticon)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Stickers? in + let reader = BufferReader(buffer) + var result: Api.messages.Stickers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Stickers + } + return result + }) + } +} +public extension Api.functions.messages { + static func getSuggestedDialogFilters() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.DialogFilterSuggested]>) { + let buffer = Buffer() + buffer.appendInt32(-1566780372) + return (FunctionDescription(name: "messages.getSuggestedDialogFilters", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.DialogFilterSuggested]? in + let reader = BufferReader(buffer) + var result: [Api.DialogFilterSuggested]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.DialogFilterSuggested.self) + } + return result + }) + } +} +public extension Api.functions.messages { + static func getTopReactions(limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1149164102) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getTopReactions", parameters: [("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Reactions? in + let reader = BufferReader(buffer) + var result: Api.messages.Reactions? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Reactions + } + return result + }) + } +} +public extension Api.functions.messages { + static func getUnreadMentions(flags: Int32, peer: Api.InputPeer, topMsgId: Int32?, offsetId: Int32, addOffset: Int32, limit: Int32, maxId: Int32, minId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-251140208) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(topMsgId!, buffer: buffer, boxed: false) + } + serializeInt32(offsetId, buffer: buffer, boxed: false) + serializeInt32(addOffset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt32(maxId, buffer: buffer, boxed: false) + serializeInt32(minId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getUnreadMentions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("topMsgId", String(describing: topMsgId)), ("offsetId", String(describing: offsetId)), ("addOffset", String(describing: addOffset)), ("limit", String(describing: limit)), ("maxId", String(describing: maxId)), ("minId", String(describing: minId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in + let reader = BufferReader(buffer) + var result: Api.messages.Messages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Messages + } + return result + }) + } +} +public extension Api.functions.messages { + static func getUnreadReactions(flags: Int32, peer: Api.InputPeer, topMsgId: Int32?, savedPeerId: Api.InputPeer?, offsetId: Int32, addOffset: Int32, limit: Int32, maxId: Int32, minId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1115713364) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(topMsgId!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + savedPeerId!.serialize(buffer, true) + } + serializeInt32(offsetId, buffer: buffer, boxed: false) + serializeInt32(addOffset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt32(maxId, buffer: buffer, boxed: false) + serializeInt32(minId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getUnreadReactions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("topMsgId", String(describing: topMsgId)), ("savedPeerId", String(describing: savedPeerId)), ("offsetId", String(describing: offsetId)), ("addOffset", String(describing: addOffset)), ("limit", String(describing: limit)), ("maxId", String(describing: maxId)), ("minId", String(describing: minId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in + let reader = BufferReader(buffer) + var result: Api.messages.Messages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Messages + } + return result + }) + } +} +public extension Api.functions.messages { + static func getWebPage(url: String, hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1919511901) + serializeString(url, buffer: buffer, boxed: false) + serializeInt32(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.getWebPage", parameters: [("url", String(describing: url)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.WebPage? in + let reader = BufferReader(buffer) + var result: Api.messages.WebPage? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.WebPage + } + return result + }) + } +} +public extension Api.functions.messages { + static func getWebPagePreview(flags: Int32, message: String, entities: [Api.MessageEntity]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1460498287) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(message, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(entities!.count)) + for item in entities! { + item.serialize(buffer, true) + } + } + return (FunctionDescription(name: "messages.getWebPagePreview", parameters: [("flags", String(describing: flags)), ("message", String(describing: message)), ("entities", String(describing: entities))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.WebPagePreview? in + let reader = BufferReader(buffer) + var result: Api.messages.WebPagePreview? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.WebPagePreview + } + return result + }) + } +} +public extension Api.functions.messages { + static func hideAllChatJoinRequests(flags: Int32, peer: Api.InputPeer, link: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-528091926) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 1) != 0 { + serializeString(link!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.hideAllChatJoinRequests", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("link", String(describing: link))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func hideChatJoinRequest(flags: Int32, peer: Api.InputPeer, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2145904661) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + userId.serialize(buffer, true) + return (FunctionDescription(name: "messages.hideChatJoinRequest", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func hidePeerSettingsBar(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1336717624) + peer.serialize(buffer, true) + return (FunctionDescription(name: "messages.hidePeerSettingsBar", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func importChatInvite(hash: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1817183516) + serializeString(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.importChatInvite", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func initHistoryImport(peer: Api.InputPeer, file: Api.InputFile, mediaCount: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(873008187) + peer.serialize(buffer, true) + file.serialize(buffer, true) + serializeInt32(mediaCount, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.initHistoryImport", parameters: [("peer", String(describing: peer)), ("file", String(describing: file)), ("mediaCount", String(describing: mediaCount))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.HistoryImport? in + let reader = BufferReader(buffer) + var result: Api.messages.HistoryImport? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.HistoryImport + } + return result + }) + } +} +public extension Api.functions.messages { + static func installStickerSet(stickerset: Api.InputStickerSet, archived: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-946871200) + stickerset.serialize(buffer, true) + archived.serialize(buffer, true) + return (FunctionDescription(name: "messages.installStickerSet", parameters: [("stickerset", String(describing: stickerset)), ("archived", String(describing: archived))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSetInstallResult? in + let reader = BufferReader(buffer) + var result: Api.messages.StickerSetInstallResult? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.StickerSetInstallResult + } + return result + }) + } +} +public extension Api.functions.messages { + static func markDialogUnread(flags: Int32, parentPeer: Api.InputPeer?, peer: Api.InputDialogPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1940912392) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 1) != 0 { + parentPeer!.serialize(buffer, true) + } + peer.serialize(buffer, true) + return (FunctionDescription(name: "messages.markDialogUnread", parameters: [("flags", String(describing: flags)), ("parentPeer", String(describing: parentPeer)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func migrateChat(chatId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1568189671) + serializeInt64(chatId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.migrateChat", parameters: [("chatId", String(describing: chatId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func prolongWebView(flags: Int32, peer: Api.InputPeer, bot: Api.InputUser, queryId: Int64, replyTo: Api.InputReplyTo?, sendAs: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1328014717) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + bot.serialize(buffer, true) + serializeInt64(queryId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + replyTo!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 13) != 0 { + sendAs!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.prolongWebView", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("bot", String(describing: bot)), ("queryId", String(describing: queryId)), ("replyTo", String(describing: replyTo)), ("sendAs", String(describing: sendAs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func rateTranscribedAudio(peer: Api.InputPeer, msgId: Int32, transcriptionId: Int64, good: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2132608815) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + serializeInt64(transcriptionId, buffer: buffer, boxed: false) + good.serialize(buffer, true) + return (FunctionDescription(name: "messages.rateTranscribedAudio", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("transcriptionId", String(describing: transcriptionId)), ("good", String(describing: good))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func readDiscussion(peer: Api.InputPeer, msgId: Int32, readMaxId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-147740172) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + serializeInt32(readMaxId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.readDiscussion", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("readMaxId", String(describing: readMaxId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func readEncryptedHistory(peer: Api.InputEncryptedChat, maxDate: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2135648522) + peer.serialize(buffer, true) + serializeInt32(maxDate, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.readEncryptedHistory", parameters: [("peer", String(describing: peer)), ("maxDate", String(describing: maxDate))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func readFeaturedStickers(id: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1527873830) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt64(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.readFeaturedStickers", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func readHistory(peer: Api.InputPeer, maxId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(238054714) + peer.serialize(buffer, true) + serializeInt32(maxId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.readHistory", parameters: [("peer", String(describing: peer)), ("maxId", String(describing: maxId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedMessages? in + let reader = BufferReader(buffer) + var result: Api.messages.AffectedMessages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AffectedMessages + } + return result + }) + } +} +public extension Api.functions.messages { + static func readMentions(flags: Int32, peer: Api.InputPeer, topMsgId: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(921026381) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(topMsgId!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.readMentions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("topMsgId", String(describing: topMsgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedHistory? in + let reader = BufferReader(buffer) + var result: Api.messages.AffectedHistory? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AffectedHistory + } + return result + }) + } +} +public extension Api.functions.messages { + static func readMessageContents(id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(916930423) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.readMessageContents", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedMessages? in + let reader = BufferReader(buffer) + var result: Api.messages.AffectedMessages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AffectedMessages + } + return result + }) + } +} +public extension Api.functions.messages { + static func readReactions(flags: Int32, peer: Api.InputPeer, topMsgId: Int32?, savedPeerId: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1631301741) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(topMsgId!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + savedPeerId!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.readReactions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("topMsgId", String(describing: topMsgId)), ("savedPeerId", String(describing: savedPeerId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedHistory? in + let reader = BufferReader(buffer) + var result: Api.messages.AffectedHistory? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AffectedHistory + } + return result + }) + } +} +public extension Api.functions.messages { + static func readSavedHistory(parentPeer: Api.InputPeer, peer: Api.InputPeer, maxId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1169540261) + parentPeer.serialize(buffer, true) + peer.serialize(buffer, true) + serializeInt32(maxId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.readSavedHistory", parameters: [("parentPeer", String(describing: parentPeer)), ("peer", String(describing: peer)), ("maxId", String(describing: maxId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func receivedMessages(maxId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.ReceivedNotifyMessage]>) { + let buffer = Buffer() + buffer.appendInt32(94983360) + serializeInt32(maxId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.receivedMessages", parameters: [("maxId", String(describing: maxId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.ReceivedNotifyMessage]? in + let reader = BufferReader(buffer) + var result: [Api.ReceivedNotifyMessage]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.ReceivedNotifyMessage.self) + } + return result + }) + } +} +public extension Api.functions.messages { + static func receivedQueue(maxQts: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Int64]>) { + let buffer = Buffer() + buffer.appendInt32(1436924774) + serializeInt32(maxQts, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.receivedQueue", parameters: [("maxQts", String(describing: maxQts))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Int64]? in + let reader = BufferReader(buffer) + var result: [Int64]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) + } + return result + }) + } +} +public extension Api.functions.messages { + static func reorderPinnedDialogs(flags: Int32, folderId: Int32, order: [Api.InputDialogPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(991616823) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt32(folderId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(order.count)) + for item in order { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.reorderPinnedDialogs", parameters: [("flags", String(describing: flags)), ("folderId", String(describing: folderId)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func reorderPinnedForumTopics(flags: Int32, peer: Api.InputPeer, order: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(242762224) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(order.count)) + for item in order { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.reorderPinnedForumTopics", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func reorderPinnedSavedDialogs(flags: Int32, order: [Api.InputDialogPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1955502713) + serializeInt32(flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(order.count)) + for item in order { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.reorderPinnedSavedDialogs", parameters: [("flags", String(describing: flags)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func reorderQuickReplies(order: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1613961479) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(order.count)) + for item in order { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.reorderQuickReplies", parameters: [("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func reorderStickerSets(flags: Int32, order: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2016638777) + serializeInt32(flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(order.count)) + for item in order { + serializeInt64(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.reorderStickerSets", parameters: [("flags", String(describing: flags)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func report(peer: Api.InputPeer, id: [Int32], option: Buffer, message: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-59199589) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + serializeBytes(option, buffer: buffer, boxed: false) + serializeString(message, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.report", parameters: [("peer", String(describing: peer)), ("id", String(describing: id)), ("option", String(describing: option)), ("message", String(describing: message))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ReportResult? in + let reader = BufferReader(buffer) + var result: Api.ReportResult? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.ReportResult + } + return result + }) + } +} +public extension Api.functions.messages { + static func reportEncryptedSpam(peer: Api.InputEncryptedChat) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1259113487) + peer.serialize(buffer, true) + return (FunctionDescription(name: "messages.reportEncryptedSpam", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func reportMessagesDelivery(flags: Int32, peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1517122453) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.reportMessagesDelivery", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func reportReaction(peer: Api.InputPeer, id: Int32, reactionPeer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1063567478) + peer.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + reactionPeer.serialize(buffer, true) + return (FunctionDescription(name: "messages.reportReaction", parameters: [("peer", String(describing: peer)), ("id", String(describing: id)), ("reactionPeer", String(describing: reactionPeer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func reportSpam(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-820669733) + peer.serialize(buffer, true) + return (FunctionDescription(name: "messages.reportSpam", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func reportSponsoredMessage(randomId: Buffer, option: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(315355332) + serializeBytes(randomId, buffer: buffer, boxed: false) + serializeBytes(option, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.reportSponsoredMessage", parameters: [("randomId", String(describing: randomId)), ("option", String(describing: option))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.channels.SponsoredMessageReportResult? in + let reader = BufferReader(buffer) + var result: Api.channels.SponsoredMessageReportResult? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.channels.SponsoredMessageReportResult + } + return result + }) + } +} +public extension Api.functions.messages { + static func requestAppWebView(flags: Int32, peer: Api.InputPeer, app: Api.InputBotApp, startParam: String?, themeParams: Api.DataJSON?, platform: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1398901710) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + app.serialize(buffer, true) + if Int(flags) & Int(1 << 1) != 0 { + serializeString(startParam!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + themeParams!.serialize(buffer, true) + } + serializeString(platform, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.requestAppWebView", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("app", String(describing: app)), ("startParam", String(describing: startParam)), ("themeParams", String(describing: themeParams)), ("platform", String(describing: platform))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.WebViewResult? in + let reader = BufferReader(buffer) + var result: Api.WebViewResult? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.WebViewResult + } + return result + }) + } +} +public extension Api.functions.messages { + static func requestEncryption(userId: Api.InputUser, randomId: Int32, gA: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-162681021) + userId.serialize(buffer, true) + serializeInt32(randomId, buffer: buffer, boxed: false) + serializeBytes(gA, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.requestEncryption", parameters: [("userId", String(describing: userId)), ("randomId", String(describing: randomId)), ("gA", String(describing: gA))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EncryptedChat? in + let reader = BufferReader(buffer) + var result: Api.EncryptedChat? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.EncryptedChat + } + return result + }) + } +} +public extension Api.functions.messages { + static func requestMainWebView(flags: Int32, peer: Api.InputPeer, bot: Api.InputUser, startParam: String?, themeParams: Api.DataJSON?, platform: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-908059013) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + bot.serialize(buffer, true) + if Int(flags) & Int(1 << 1) != 0 { + serializeString(startParam!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 0) != 0 { + themeParams!.serialize(buffer, true) + } + serializeString(platform, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.requestMainWebView", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("bot", String(describing: bot)), ("startParam", String(describing: startParam)), ("themeParams", String(describing: themeParams)), ("platform", String(describing: platform))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.WebViewResult? in + let reader = BufferReader(buffer) + var result: Api.WebViewResult? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.WebViewResult + } + return result + }) + } +} +public extension Api.functions.messages { + static func requestSimpleWebView(flags: Int32, bot: Api.InputUser, url: String?, startParam: String?, themeParams: Api.DataJSON?, platform: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1094336115) + serializeInt32(flags, buffer: buffer, boxed: false) + bot.serialize(buffer, true) + if Int(flags) & Int(1 << 3) != 0 { + serializeString(url!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 4) != 0 { + serializeString(startParam!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 0) != 0 { + themeParams!.serialize(buffer, true) + } + serializeString(platform, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.requestSimpleWebView", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("url", String(describing: url)), ("startParam", String(describing: startParam)), ("themeParams", String(describing: themeParams)), ("platform", String(describing: platform))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.WebViewResult? in + let reader = BufferReader(buffer) + var result: Api.WebViewResult? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.WebViewResult + } + return result + }) + } +} +public extension Api.functions.messages { + static func requestUrlAuth(flags: Int32, peer: Api.InputPeer?, msgId: Int32?, buttonId: Int32?, url: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(428848198) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 1) != 0 { + peer!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeInt32(msgId!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeInt32(buttonId!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + serializeString(url!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.requestUrlAuth", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("buttonId", String(describing: buttonId)), ("url", String(describing: url))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.UrlAuthResult? in + let reader = BufferReader(buffer) + var result: Api.UrlAuthResult? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.UrlAuthResult + } + return result + }) + } +} +public extension Api.functions.messages { + static func requestWebView(flags: Int32, peer: Api.InputPeer, bot: Api.InputUser, url: String?, startParam: String?, themeParams: Api.DataJSON?, platform: String, replyTo: Api.InputReplyTo?, sendAs: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(647873217) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + bot.serialize(buffer, true) + if Int(flags) & Int(1 << 1) != 0 { + serializeString(url!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 3) != 0 { + serializeString(startParam!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + themeParams!.serialize(buffer, true) + } + serializeString(platform, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + replyTo!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 13) != 0 { + sendAs!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.requestWebView", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("bot", String(describing: bot)), ("url", String(describing: url)), ("startParam", String(describing: startParam)), ("themeParams", String(describing: themeParams)), ("platform", String(describing: platform)), ("replyTo", String(describing: replyTo)), ("sendAs", String(describing: sendAs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.WebViewResult? in + let reader = BufferReader(buffer) + var result: Api.WebViewResult? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.WebViewResult + } + return result + }) + } +} +public extension Api.functions.messages { + static func saveDefaultSendAs(peer: Api.InputPeer, sendAs: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-855777386) + peer.serialize(buffer, true) + sendAs.serialize(buffer, true) + return (FunctionDescription(name: "messages.saveDefaultSendAs", parameters: [("peer", String(describing: peer)), ("sendAs", String(describing: sendAs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func saveDraft(flags: Int32, replyTo: Api.InputReplyTo?, peer: Api.InputPeer, message: String, entities: [Api.MessageEntity]?, media: Api.InputMedia?, effect: Int64?, suggestedPost: Api.SuggestedPost?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1420701838) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 4) != 0 { + replyTo!.serialize(buffer, true) + } + peer.serialize(buffer, true) + serializeString(message, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(entities!.count)) + for item in entities! { + item.serialize(buffer, true) + } + } + if Int(flags) & Int(1 << 5) != 0 { + media!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 7) != 0 { + serializeInt64(effect!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 8) != 0 { + suggestedPost!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.saveDraft", parameters: [("flags", String(describing: flags)), ("replyTo", String(describing: replyTo)), ("peer", String(describing: peer)), ("message", String(describing: message)), ("entities", String(describing: entities)), ("media", String(describing: media)), ("effect", String(describing: effect)), ("suggestedPost", String(describing: suggestedPost))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func saveGif(id: Api.InputDocument, unsave: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(846868683) + id.serialize(buffer, true) + unsave.serialize(buffer, true) + return (FunctionDescription(name: "messages.saveGif", parameters: [("id", String(describing: id)), ("unsave", String(describing: unsave))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func savePreparedInlineMessage(flags: Int32, result: Api.InputBotInlineResult, userId: Api.InputUser, peerTypes: [Api.InlineQueryPeerType]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-232816849) + serializeInt32(flags, buffer: buffer, boxed: false) + result.serialize(buffer, true) + userId.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(peerTypes!.count)) + for item in peerTypes! { + item.serialize(buffer, true) + } + } + return (FunctionDescription(name: "messages.savePreparedInlineMessage", parameters: [("flags", String(describing: flags)), ("result", String(describing: result)), ("userId", String(describing: userId)), ("peerTypes", String(describing: peerTypes))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.BotPreparedInlineMessage? in + let reader = BufferReader(buffer) + var result: Api.messages.BotPreparedInlineMessage? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.BotPreparedInlineMessage + } + return result + }) + } +} +public extension Api.functions.messages { + static func saveRecentSticker(flags: Int32, id: Api.InputDocument, unsave: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(958863608) + serializeInt32(flags, buffer: buffer, boxed: false) + id.serialize(buffer, true) + unsave.serialize(buffer, true) + return (FunctionDescription(name: "messages.saveRecentSticker", parameters: [("flags", String(describing: flags)), ("id", String(describing: id)), ("unsave", String(describing: unsave))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func search(flags: Int32, peer: Api.InputPeer, q: String, fromId: Api.InputPeer?, savedPeerId: Api.InputPeer?, savedReaction: [Api.Reaction]?, topMsgId: Int32?, filter: Api.MessagesFilter, minDate: Int32, maxDate: Int32, offsetId: Int32, addOffset: Int32, limit: Int32, maxId: Int32, minId: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(703497338) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeString(q, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + fromId!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 2) != 0 { + savedPeerId!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(savedReaction!.count)) + for item in savedReaction! { + item.serialize(buffer, true) + } + } + if Int(flags) & Int(1 << 1) != 0 { + serializeInt32(topMsgId!, buffer: buffer, boxed: false) + } + filter.serialize(buffer, true) + serializeInt32(minDate, buffer: buffer, boxed: false) + serializeInt32(maxDate, buffer: buffer, boxed: false) + serializeInt32(offsetId, buffer: buffer, boxed: false) + serializeInt32(addOffset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt32(maxId, buffer: buffer, boxed: false) + serializeInt32(minId, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.search", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("q", String(describing: q)), ("fromId", String(describing: fromId)), ("savedPeerId", String(describing: savedPeerId)), ("savedReaction", String(describing: savedReaction)), ("topMsgId", String(describing: topMsgId)), ("filter", String(describing: filter)), ("minDate", String(describing: minDate)), ("maxDate", String(describing: maxDate)), ("offsetId", String(describing: offsetId)), ("addOffset", String(describing: addOffset)), ("limit", String(describing: limit)), ("maxId", String(describing: maxId)), ("minId", String(describing: minId)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in + let reader = BufferReader(buffer) + var result: Api.messages.Messages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Messages + } + return result + }) + } +} +public extension Api.functions.messages { + static func searchCustomEmoji(emoticon: String, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(739360983) + serializeString(emoticon, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.searchCustomEmoji", parameters: [("emoticon", String(describing: emoticon)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EmojiList? in + let reader = BufferReader(buffer) + var result: Api.EmojiList? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.EmojiList + } + return result + }) + } +} +public extension Api.functions.messages { + static func searchEmojiStickerSets(flags: Int32, q: String, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1833678516) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(q, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.searchEmojiStickerSets", parameters: [("flags", String(describing: flags)), ("q", String(describing: q)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.FoundStickerSets? in + let reader = BufferReader(buffer) + var result: Api.messages.FoundStickerSets? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.FoundStickerSets + } + return result + }) + } +} +public extension Api.functions.messages { + static func searchGlobal(flags: Int32, folderId: Int32?, q: String, filter: Api.MessagesFilter, minDate: Int32, maxDate: Int32, offsetRate: Int32, offsetPeer: Api.InputPeer, offsetId: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1271290010) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(folderId!, buffer: buffer, boxed: false) + } + serializeString(q, buffer: buffer, boxed: false) + filter.serialize(buffer, true) + serializeInt32(minDate, buffer: buffer, boxed: false) + serializeInt32(maxDate, buffer: buffer, boxed: false) + serializeInt32(offsetRate, buffer: buffer, boxed: false) + offsetPeer.serialize(buffer, true) + serializeInt32(offsetId, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.searchGlobal", parameters: [("flags", String(describing: flags)), ("folderId", String(describing: folderId)), ("q", String(describing: q)), ("filter", String(describing: filter)), ("minDate", String(describing: minDate)), ("maxDate", String(describing: maxDate)), ("offsetRate", String(describing: offsetRate)), ("offsetPeer", String(describing: offsetPeer)), ("offsetId", String(describing: offsetId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in + let reader = BufferReader(buffer) + var result: Api.messages.Messages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Messages + } + return result + }) + } +} +public extension Api.functions.messages { + static func searchSentMedia(q: String, filter: Api.MessagesFilter, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(276705696) + serializeString(q, buffer: buffer, boxed: false) + filter.serialize(buffer, true) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.searchSentMedia", parameters: [("q", String(describing: q)), ("filter", String(describing: filter)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Messages? in + let reader = BufferReader(buffer) + var result: Api.messages.Messages? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Messages + } + return result + }) + } +} +public extension Api.functions.messages { + static func searchStickerSets(flags: Int32, q: String, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(896555914) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(q, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.searchStickerSets", parameters: [("flags", String(describing: flags)), ("q", String(describing: q)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.FoundStickerSets? in + let reader = BufferReader(buffer) + var result: Api.messages.FoundStickerSets? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.FoundStickerSets + } + return result + }) + } +} +public extension Api.functions.messages { + static func searchStickers(flags: Int32, q: String, emoticon: String, langCode: [String], offset: Int32, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(699516522) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(q, buffer: buffer, boxed: false) + serializeString(emoticon, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(langCode.count)) + for item in langCode { + serializeString(item, buffer: buffer, boxed: false) + } + serializeInt32(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.searchStickers", parameters: [("flags", String(describing: flags)), ("q", String(describing: q)), ("emoticon", String(describing: emoticon)), ("langCode", String(describing: langCode)), ("offset", String(describing: offset)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.FoundStickers? in + let reader = BufferReader(buffer) + var result: Api.messages.FoundStickers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.FoundStickers + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendBotRequestedPeer(peer: Api.InputPeer, msgId: Int32, buttonId: Int32, requestedPeers: [Api.InputPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1850552224) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + serializeInt32(buttonId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(requestedPeers.count)) + for item in requestedPeers { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.sendBotRequestedPeer", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("buttonId", String(describing: buttonId)), ("requestedPeers", String(describing: requestedPeers))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendEncrypted(flags: Int32, peer: Api.InputEncryptedChat, randomId: Int64, data: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1157265941) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt64(randomId, buffer: buffer, boxed: false) + serializeBytes(data, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.sendEncrypted", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("randomId", String(describing: randomId)), ("data", String(describing: data))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SentEncryptedMessage? in + let reader = BufferReader(buffer) + var result: Api.messages.SentEncryptedMessage? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.SentEncryptedMessage + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendEncryptedFile(flags: Int32, peer: Api.InputEncryptedChat, randomId: Int64, data: Buffer, file: Api.InputEncryptedFile) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1431914525) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt64(randomId, buffer: buffer, boxed: false) + serializeBytes(data, buffer: buffer, boxed: false) + file.serialize(buffer, true) + return (FunctionDescription(name: "messages.sendEncryptedFile", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("randomId", String(describing: randomId)), ("data", String(describing: data)), ("file", String(describing: file))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SentEncryptedMessage? in + let reader = BufferReader(buffer) + var result: Api.messages.SentEncryptedMessage? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.SentEncryptedMessage + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendEncryptedService(peer: Api.InputEncryptedChat, randomId: Int64, data: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(852769188) + peer.serialize(buffer, true) + serializeInt64(randomId, buffer: buffer, boxed: false) + serializeBytes(data, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.sendEncryptedService", parameters: [("peer", String(describing: peer)), ("randomId", String(describing: randomId)), ("data", String(describing: data))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.SentEncryptedMessage? in + let reader = BufferReader(buffer) + var result: Api.messages.SentEncryptedMessage? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.SentEncryptedMessage + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendInlineBotResult(flags: Int32, peer: Api.InputPeer, replyTo: Api.InputReplyTo?, randomId: Int64, queryId: Int64, id: String, scheduleDate: Int32?, sendAs: Api.InputPeer?, quickReplyShortcut: Api.InputQuickReplyShortcut?, allowPaidStars: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1060145594) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + replyTo!.serialize(buffer, true) + } + serializeInt64(randomId, buffer: buffer, boxed: false) + serializeInt64(queryId, buffer: buffer, boxed: false) + serializeString(id, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 10) != 0 { + serializeInt32(scheduleDate!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 13) != 0 { + sendAs!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 17) != 0 { + quickReplyShortcut!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 21) != 0 { + serializeInt64(allowPaidStars!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.sendInlineBotResult", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("replyTo", String(describing: replyTo)), ("randomId", String(describing: randomId)), ("queryId", String(describing: queryId)), ("id", String(describing: id)), ("scheduleDate", String(describing: scheduleDate)), ("sendAs", String(describing: sendAs)), ("quickReplyShortcut", String(describing: quickReplyShortcut)), ("allowPaidStars", String(describing: allowPaidStars))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendMedia(flags: Int32, peer: Api.InputPeer, replyTo: Api.InputReplyTo?, media: Api.InputMedia, message: String, randomId: Int64, replyMarkup: Api.ReplyMarkup?, entities: [Api.MessageEntity]?, scheduleDate: Int32?, scheduleRepeatPeriod: Int32?, sendAs: Api.InputPeer?, quickReplyShortcut: Api.InputQuickReplyShortcut?, effect: Int64?, allowPaidStars: Int64?, suggestedPost: Api.SuggestedPost?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(53536639) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + replyTo!.serialize(buffer, true) + } + media.serialize(buffer, true) + serializeString(message, buffer: buffer, boxed: false) + serializeInt64(randomId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 2) != 0 { + replyMarkup!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(entities!.count)) + for item in entities! { + item.serialize(buffer, true) + } + } + if Int(flags) & Int(1 << 10) != 0 { + serializeInt32(scheduleDate!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 24) != 0 { + serializeInt32(scheduleRepeatPeriod!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 13) != 0 { + sendAs!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 17) != 0 { + quickReplyShortcut!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 18) != 0 { + serializeInt64(effect!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 21) != 0 { + serializeInt64(allowPaidStars!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 22) != 0 { + suggestedPost!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.sendMedia", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("replyTo", String(describing: replyTo)), ("media", String(describing: media)), ("message", String(describing: message)), ("randomId", String(describing: randomId)), ("replyMarkup", String(describing: replyMarkup)), ("entities", String(describing: entities)), ("scheduleDate", String(describing: scheduleDate)), ("scheduleRepeatPeriod", String(describing: scheduleRepeatPeriod)), ("sendAs", String(describing: sendAs)), ("quickReplyShortcut", String(describing: quickReplyShortcut)), ("effect", String(describing: effect)), ("allowPaidStars", String(describing: allowPaidStars)), ("suggestedPost", String(describing: suggestedPost))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendMessage(flags: Int32, peer: Api.InputPeer, replyTo: Api.InputReplyTo?, message: String, randomId: Int64, replyMarkup: Api.ReplyMarkup?, entities: [Api.MessageEntity]?, scheduleDate: Int32?, scheduleRepeatPeriod: Int32?, sendAs: Api.InputPeer?, quickReplyShortcut: Api.InputQuickReplyShortcut?, effect: Int64?, allowPaidStars: Int64?, suggestedPost: Api.SuggestedPost?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1415369050) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + replyTo!.serialize(buffer, true) + } + serializeString(message, buffer: buffer, boxed: false) + serializeInt64(randomId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 2) != 0 { + replyMarkup!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(entities!.count)) + for item in entities! { + item.serialize(buffer, true) + } + } + if Int(flags) & Int(1 << 10) != 0 { + serializeInt32(scheduleDate!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 24) != 0 { + serializeInt32(scheduleRepeatPeriod!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 13) != 0 { + sendAs!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 17) != 0 { + quickReplyShortcut!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 18) != 0 { + serializeInt64(effect!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 21) != 0 { + serializeInt64(allowPaidStars!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 22) != 0 { + suggestedPost!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.sendMessage", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("replyTo", String(describing: replyTo)), ("message", String(describing: message)), ("randomId", String(describing: randomId)), ("replyMarkup", String(describing: replyMarkup)), ("entities", String(describing: entities)), ("scheduleDate", String(describing: scheduleDate)), ("scheduleRepeatPeriod", String(describing: scheduleRepeatPeriod)), ("sendAs", String(describing: sendAs)), ("quickReplyShortcut", String(describing: quickReplyShortcut)), ("effect", String(describing: effect)), ("allowPaidStars", String(describing: allowPaidStars)), ("suggestedPost", String(describing: suggestedPost))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendMultiMedia(flags: Int32, peer: Api.InputPeer, replyTo: Api.InputReplyTo?, multiMedia: [Api.InputSingleMedia], scheduleDate: Int32?, sendAs: Api.InputPeer?, quickReplyShortcut: Api.InputQuickReplyShortcut?, effect: Int64?, allowPaidStars: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(469278068) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + replyTo!.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(multiMedia.count)) + for item in multiMedia { + item.serialize(buffer, true) + } + if Int(flags) & Int(1 << 10) != 0 { + serializeInt32(scheduleDate!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 13) != 0 { + sendAs!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 17) != 0 { + quickReplyShortcut!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 18) != 0 { + serializeInt64(effect!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 21) != 0 { + serializeInt64(allowPaidStars!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.sendMultiMedia", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("replyTo", String(describing: replyTo)), ("multiMedia", String(describing: multiMedia)), ("scheduleDate", String(describing: scheduleDate)), ("sendAs", String(describing: sendAs)), ("quickReplyShortcut", String(describing: quickReplyShortcut)), ("effect", String(describing: effect)), ("allowPaidStars", String(describing: allowPaidStars))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendPaidReaction(flags: Int32, peer: Api.InputPeer, msgId: Int32, count: Int32, randomId: Int64, `private`: Api.PaidReactionPrivacy?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1488702288) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + serializeInt32(count, buffer: buffer, boxed: false) + serializeInt64(randomId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + `private`!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.sendPaidReaction", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("count", String(describing: count)), ("randomId", String(describing: randomId)), ("`private`", String(describing: `private`))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendQuickReplyMessages(peer: Api.InputPeer, shortcutId: Int32, id: [Int32], randomId: [Int64]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1819610593) + peer.serialize(buffer, true) + serializeInt32(shortcutId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(randomId.count)) + for item in randomId { + serializeInt64(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.sendQuickReplyMessages", parameters: [("peer", String(describing: peer)), ("shortcutId", String(describing: shortcutId)), ("id", String(describing: id)), ("randomId", String(describing: randomId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendReaction(flags: Int32, peer: Api.InputPeer, msgId: Int32, reaction: [Api.Reaction]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-754091820) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(reaction!.count)) + for item in reaction! { + item.serialize(buffer, true) + } + } + return (FunctionDescription(name: "messages.sendReaction", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("reaction", String(describing: reaction))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendScheduledMessages(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1120369398) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.sendScheduledMessages", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendScreenshotNotification(peer: Api.InputPeer, replyTo: Api.InputReplyTo, randomId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1589618665) + peer.serialize(buffer, true) + replyTo.serialize(buffer, true) + serializeInt64(randomId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.sendScreenshotNotification", parameters: [("peer", String(describing: peer)), ("replyTo", String(describing: replyTo)), ("randomId", String(describing: randomId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendVote(peer: Api.InputPeer, msgId: Int32, options: [Buffer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(283795844) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(options.count)) + for item in options { + serializeBytes(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.sendVote", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("options", String(describing: options))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendWebViewData(bot: Api.InputUser, randomId: Int64, buttonText: String, data: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-603831608) + bot.serialize(buffer, true) + serializeInt64(randomId, buffer: buffer, boxed: false) + serializeString(buttonText, buffer: buffer, boxed: false) + serializeString(data, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.sendWebViewData", parameters: [("bot", String(describing: bot)), ("randomId", String(describing: randomId)), ("buttonText", String(describing: buttonText)), ("data", String(describing: data))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func sendWebViewResultMessage(botQueryId: String, result: Api.InputBotInlineResult) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(172168437) + serializeString(botQueryId, buffer: buffer, boxed: false) + result.serialize(buffer, true) + return (FunctionDescription(name: "messages.sendWebViewResultMessage", parameters: [("botQueryId", String(describing: botQueryId)), ("result", String(describing: result))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.WebViewMessageSent? in + let reader = BufferReader(buffer) + var result: Api.WebViewMessageSent? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.WebViewMessageSent + } + return result + }) + } +} +public extension Api.functions.messages { + static func setBotCallbackAnswer(flags: Int32, queryId: Int64, message: String?, url: String?, cacheTime: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-712043766) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt64(queryId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(message!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + serializeString(url!, buffer: buffer, boxed: false) + } + serializeInt32(cacheTime, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.setBotCallbackAnswer", parameters: [("flags", String(describing: flags)), ("queryId", String(describing: queryId)), ("message", String(describing: message)), ("url", String(describing: url)), ("cacheTime", String(describing: cacheTime))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func setBotPrecheckoutResults(flags: Int32, queryId: Int64, error: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(163765653) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt64(queryId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(error!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.setBotPrecheckoutResults", parameters: [("flags", String(describing: flags)), ("queryId", String(describing: queryId)), ("error", String(describing: error))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func setBotShippingResults(flags: Int32, queryId: Int64, error: String?, shippingOptions: [Api.ShippingOption]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-436833542) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt64(queryId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(error!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(shippingOptions!.count)) + for item in shippingOptions! { + item.serialize(buffer, true) + } + } + return (FunctionDescription(name: "messages.setBotShippingResults", parameters: [("flags", String(describing: flags)), ("queryId", String(describing: queryId)), ("error", String(describing: error)), ("shippingOptions", String(describing: shippingOptions))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func setChatAvailableReactions(flags: Int32, peer: Api.InputPeer, availableReactions: Api.ChatReactions, reactionsLimit: Int32?, paidEnabled: Api.Bool?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2041895551) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + availableReactions.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(reactionsLimit!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + paidEnabled!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.setChatAvailableReactions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("availableReactions", String(describing: availableReactions)), ("reactionsLimit", String(describing: reactionsLimit)), ("paidEnabled", String(describing: paidEnabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func setChatTheme(peer: Api.InputPeer, theme: Api.InputChatTheme) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(135398089) + peer.serialize(buffer, true) + theme.serialize(buffer, true) + return (FunctionDescription(name: "messages.setChatTheme", parameters: [("peer", String(describing: peer)), ("theme", String(describing: theme))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func setChatWallPaper(flags: Int32, peer: Api.InputPeer, wallpaper: Api.InputWallPaper?, settings: Api.WallPaperSettings?, id: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1879389471) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + wallpaper!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 2) != 0 { + settings!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeInt32(id!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.setChatWallPaper", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("wallpaper", String(describing: wallpaper)), ("settings", String(describing: settings)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func setDefaultHistoryTTL(period: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1632299963) + serializeInt32(period, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.setDefaultHistoryTTL", parameters: [("period", String(describing: period))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func setDefaultReaction(reaction: Api.Reaction) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1330094102) + reaction.serialize(buffer, true) + return (FunctionDescription(name: "messages.setDefaultReaction", parameters: [("reaction", String(describing: reaction))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func setEncryptedTyping(peer: Api.InputEncryptedChat, typing: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2031374829) + peer.serialize(buffer, true) + typing.serialize(buffer, true) + return (FunctionDescription(name: "messages.setEncryptedTyping", parameters: [("peer", String(describing: peer)), ("typing", String(describing: typing))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func setGameScore(flags: Int32, peer: Api.InputPeer, id: Int32, userId: Api.InputUser, score: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1896289088) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + userId.serialize(buffer, true) + serializeInt32(score, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.setGameScore", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("userId", String(describing: userId)), ("score", String(describing: score))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func setHistoryTTL(peer: Api.InputPeer, period: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1207017500) + peer.serialize(buffer, true) + serializeInt32(period, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.setHistoryTTL", parameters: [("peer", String(describing: peer)), ("period", String(describing: period))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func setInlineBotResults(flags: Int32, queryId: Int64, results: [Api.InputBotInlineResult], cacheTime: Int32, nextOffset: String?, switchPm: Api.InlineBotSwitchPM?, switchWebview: Api.InlineBotWebView?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1156406247) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt64(queryId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(results.count)) + for item in results { + item.serialize(buffer, true) + } + serializeInt32(cacheTime, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 2) != 0 { + serializeString(nextOffset!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 3) != 0 { + switchPm!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 4) != 0 { + switchWebview!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.setInlineBotResults", parameters: [("flags", String(describing: flags)), ("queryId", String(describing: queryId)), ("results", String(describing: results)), ("cacheTime", String(describing: cacheTime)), ("nextOffset", String(describing: nextOffset)), ("switchPm", String(describing: switchPm)), ("switchWebview", String(describing: switchWebview))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func setInlineGameScore(flags: Int32, id: Api.InputBotInlineMessageID, userId: Api.InputUser, score: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(363700068) + serializeInt32(flags, buffer: buffer, boxed: false) + id.serialize(buffer, true) + userId.serialize(buffer, true) + serializeInt32(score, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.setInlineGameScore", parameters: [("flags", String(describing: flags)), ("id", String(describing: id)), ("userId", String(describing: userId)), ("score", String(describing: score))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func setTyping(flags: Int32, peer: Api.InputPeer, topMsgId: Int32?, action: Api.SendMessageAction) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1486110434) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(topMsgId!, buffer: buffer, boxed: false) + } + action.serialize(buffer, true) + return (FunctionDescription(name: "messages.setTyping", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("topMsgId", String(describing: topMsgId)), ("action", String(describing: action))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func startBot(bot: Api.InputUser, peer: Api.InputPeer, randomId: Int64, startParam: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-421563528) + bot.serialize(buffer, true) + peer.serialize(buffer, true) + serializeInt64(randomId, buffer: buffer, boxed: false) + serializeString(startParam, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.startBot", parameters: [("bot", String(describing: bot)), ("peer", String(describing: peer)), ("randomId", String(describing: randomId)), ("startParam", String(describing: startParam))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func startHistoryImport(peer: Api.InputPeer, importId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1271008444) + peer.serialize(buffer, true) + serializeInt64(importId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.startHistoryImport", parameters: [("peer", String(describing: peer)), ("importId", String(describing: importId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func summarizeText(flags: Int32, peer: Api.InputPeer, id: Int32, toLang: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1656683294) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(toLang!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.summarizeText", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("toLang", String(describing: toLang))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.TextWithEntities? in + let reader = BufferReader(buffer) + var result: Api.TextWithEntities? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.TextWithEntities + } + return result + }) + } +} +public extension Api.functions.messages { + static func toggleBotInAttachMenu(flags: Int32, bot: Api.InputUser, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1777704297) + serializeInt32(flags, buffer: buffer, boxed: false) + bot.serialize(buffer, true) + enabled.serialize(buffer, true) + return (FunctionDescription(name: "messages.toggleBotInAttachMenu", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func toggleDialogFilterTags(enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-47326647) + enabled.serialize(buffer, true) + return (FunctionDescription(name: "messages.toggleDialogFilterTags", parameters: [("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func toggleDialogPin(flags: Int32, peer: Api.InputDialogPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1489903017) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + return (FunctionDescription(name: "messages.toggleDialogPin", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func toggleNoForwards(peer: Api.InputPeer, enabled: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1323389022) + peer.serialize(buffer, true) + enabled.serialize(buffer, true) + return (FunctionDescription(name: "messages.toggleNoForwards", parameters: [("peer", String(describing: peer)), ("enabled", String(describing: enabled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func togglePaidReactionPrivacy(peer: Api.InputPeer, msgId: Int32, `private`: Api.PaidReactionPrivacy) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1129874869) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + `private`.serialize(buffer, true) + return (FunctionDescription(name: "messages.togglePaidReactionPrivacy", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("`private`", String(describing: `private`))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func togglePeerTranslations(flags: Int32, peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-461589127) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + return (FunctionDescription(name: "messages.togglePeerTranslations", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func toggleSavedDialogPin(flags: Int32, peer: Api.InputDialogPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1400783906) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + return (FunctionDescription(name: "messages.toggleSavedDialogPin", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func toggleStickerSets(flags: Int32, stickersets: [Api.InputStickerSet]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1257951254) + serializeInt32(flags, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(stickersets.count)) + for item in stickersets { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.toggleStickerSets", parameters: [("flags", String(describing: flags)), ("stickersets", String(describing: stickersets))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func toggleSuggestedPostApproval(flags: Int32, peer: Api.InputPeer, msgId: Int32, scheduleDate: Int32?, rejectComment: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2130229924) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(scheduleDate!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + serializeString(rejectComment!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.toggleSuggestedPostApproval", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("scheduleDate", String(describing: scheduleDate)), ("rejectComment", String(describing: rejectComment))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func toggleTodoCompleted(peer: Api.InputPeer, msgId: Int32, completed: [Int32], incompleted: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-740282076) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(completed.count)) + for item in completed { + serializeInt32(item, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(incompleted.count)) + for item in incompleted { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.toggleTodoCompleted", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId)), ("completed", String(describing: completed)), ("incompleted", String(describing: incompleted))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func transcribeAudio(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(647928393) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.transcribeAudio", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.TranscribedAudio? in + let reader = BufferReader(buffer) + var result: Api.messages.TranscribedAudio? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.TranscribedAudio + } + return result + }) + } +} +public extension Api.functions.messages { + static func translateText(flags: Int32, peer: Api.InputPeer?, id: [Int32]?, text: [Api.TextWithEntities]?, toLang: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1662529584) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + peer!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id!.count)) + for item in id! { + serializeInt32(item, buffer: buffer, boxed: false) + } + } + if Int(flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(text!.count)) + for item in text! { + item.serialize(buffer, true) + } + } + serializeString(toLang, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.translateText", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("text", String(describing: text)), ("toLang", String(describing: toLang))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.TranslatedText? in + let reader = BufferReader(buffer) + var result: Api.messages.TranslatedText? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.TranslatedText + } + return result + }) + } +} +public extension Api.functions.messages { + static func uninstallStickerSet(stickerset: Api.InputStickerSet) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-110209570) + stickerset.serialize(buffer, true) + return (FunctionDescription(name: "messages.uninstallStickerSet", parameters: [("stickerset", String(describing: stickerset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func unpinAllMessages(flags: Int32, peer: Api.InputPeer, topMsgId: Int32?, savedPeerId: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(103667527) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(topMsgId!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + savedPeerId!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.unpinAllMessages", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("topMsgId", String(describing: topMsgId)), ("savedPeerId", String(describing: savedPeerId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.AffectedHistory? in + let reader = BufferReader(buffer) + var result: Api.messages.AffectedHistory? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.AffectedHistory + } + return result + }) + } +} +public extension Api.functions.messages { + static func updateDialogFilter(flags: Int32, id: Int32, filter: Api.DialogFilter?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(450142282) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt32(id, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + filter!.serialize(buffer, true) + } + return (FunctionDescription(name: "messages.updateDialogFilter", parameters: [("flags", String(describing: flags)), ("id", String(describing: id)), ("filter", String(describing: filter))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func updateDialogFiltersOrder(order: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-983318044) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(order.count)) + for item in order { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.updateDialogFiltersOrder", parameters: [("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func updatePinnedForumTopic(peer: Api.InputPeer, topicId: Int32, pinned: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(392032849) + peer.serialize(buffer, true) + serializeInt32(topicId, buffer: buffer, boxed: false) + pinned.serialize(buffer, true) + return (FunctionDescription(name: "messages.updatePinnedForumTopic", parameters: [("peer", String(describing: peer)), ("topicId", String(describing: topicId)), ("pinned", String(describing: pinned))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func updatePinnedMessage(flags: Int32, peer: Api.InputPeer, id: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-760547348) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.updatePinnedMessage", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.messages { + static func updateSavedReactionTag(flags: Int32, reaction: Api.Reaction, title: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1613331948) + serializeInt32(flags, buffer: buffer, boxed: false) + reaction.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(title!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "messages.updateSavedReactionTag", parameters: [("flags", String(describing: flags)), ("reaction", String(describing: reaction)), ("title", String(describing: title))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.messages { + static func uploadEncryptedFile(peer: Api.InputEncryptedChat, file: Api.InputEncryptedFile) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1347929239) + peer.serialize(buffer, true) + file.serialize(buffer, true) + return (FunctionDescription(name: "messages.uploadEncryptedFile", parameters: [("peer", String(describing: peer)), ("file", String(describing: file))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.EncryptedFile? in + let reader = BufferReader(buffer) + var result: Api.EncryptedFile? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.EncryptedFile + } + return result + }) + } +} +public extension Api.functions.messages { + static func uploadImportedMedia(peer: Api.InputPeer, importId: Int64, fileName: String, media: Api.InputMedia) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(713433234) + peer.serialize(buffer, true) + serializeInt64(importId, buffer: buffer, boxed: false) + serializeString(fileName, buffer: buffer, boxed: false) + media.serialize(buffer, true) + return (FunctionDescription(name: "messages.uploadImportedMedia", parameters: [("peer", String(describing: peer)), ("importId", String(describing: importId)), ("fileName", String(describing: fileName)), ("media", String(describing: media))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.MessageMedia? in + let reader = BufferReader(buffer) + var result: Api.MessageMedia? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.MessageMedia + } + return result + }) + } +} +public extension Api.functions.messages { + static func uploadMedia(flags: Int32, businessConnectionId: String?, peer: Api.InputPeer, media: Api.InputMedia) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(345405816) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(businessConnectionId!, buffer: buffer, boxed: false) + } + peer.serialize(buffer, true) + media.serialize(buffer, true) + return (FunctionDescription(name: "messages.uploadMedia", parameters: [("flags", String(describing: flags)), ("businessConnectionId", String(describing: businessConnectionId)), ("peer", String(describing: peer)), ("media", String(describing: media))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.MessageMedia? in + let reader = BufferReader(buffer) + var result: Api.MessageMedia? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.MessageMedia + } + return result + }) + } +} +public extension Api.functions.messages { + static func viewSponsoredMessage(randomId: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(647902787) + serializeBytes(randomId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "messages.viewSponsoredMessage", parameters: [("randomId", String(describing: randomId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.payments { + static func applyGiftCode(slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-152934316) + serializeString(slug, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.applyGiftCode", parameters: [("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.payments { + static func assignAppStoreTransaction(receipt: Buffer, purpose: Api.InputStorePaymentPurpose) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2131921795) + serializeBytes(receipt, buffer: buffer, boxed: false) + purpose.serialize(buffer, true) + return (FunctionDescription(name: "payments.assignAppStoreTransaction", parameters: [("receipt", String(describing: receipt)), ("purpose", String(describing: purpose))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.payments { + static func assignPlayMarketTransaction(receipt: Api.DataJSON, purpose: Api.InputStorePaymentPurpose) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-537046829) + receipt.serialize(buffer, true) + purpose.serialize(buffer, true) + return (FunctionDescription(name: "payments.assignPlayMarketTransaction", parameters: [("receipt", String(describing: receipt)), ("purpose", String(describing: purpose))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.payments { + static func botCancelStarsSubscription(flags: Int32, userId: Api.InputUser, chargeId: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1845102114) + serializeInt32(flags, buffer: buffer, boxed: false) + userId.serialize(buffer, true) + serializeString(chargeId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.botCancelStarsSubscription", parameters: [("flags", String(describing: flags)), ("userId", String(describing: userId)), ("chargeId", String(describing: chargeId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.payments { + static func canPurchaseStore(purpose: Api.InputStorePaymentPurpose) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1339842215) + purpose.serialize(buffer, true) + return (FunctionDescription(name: "payments.canPurchaseStore", parameters: [("purpose", String(describing: purpose))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.payments { + static func changeStarsSubscription(flags: Int32, peer: Api.InputPeer, subscriptionId: String, canceled: Api.Bool?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-948500360) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeString(subscriptionId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + canceled!.serialize(buffer, true) + } + return (FunctionDescription(name: "payments.changeStarsSubscription", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("subscriptionId", String(describing: subscriptionId)), ("canceled", String(describing: canceled))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.payments { + static func checkCanSendGift(giftId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1060835895) + serializeInt64(giftId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.checkCanSendGift", parameters: [("giftId", String(describing: giftId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.CheckCanSendGiftResult? in + let reader = BufferReader(buffer) + var result: Api.payments.CheckCanSendGiftResult? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.CheckCanSendGiftResult + } + return result + }) + } +} +public extension Api.functions.payments { + static func checkGiftCode(slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1907247935) + serializeString(slug, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.checkGiftCode", parameters: [("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.CheckedGiftCode? in + let reader = BufferReader(buffer) + var result: Api.payments.CheckedGiftCode? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.CheckedGiftCode + } + return result + }) + } +} +public extension Api.functions.payments { + static func clearSavedInfo(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-667062079) + serializeInt32(flags, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.clearSavedInfo", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.payments { + static func connectStarRefBot(peer: Api.InputPeer, bot: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2127901834) + peer.serialize(buffer, true) + bot.serialize(buffer, true) + return (FunctionDescription(name: "payments.connectStarRefBot", parameters: [("peer", String(describing: peer)), ("bot", String(describing: bot))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.ConnectedStarRefBots? in + let reader = BufferReader(buffer) + var result: Api.payments.ConnectedStarRefBots? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.ConnectedStarRefBots + } + return result + }) + } +} +public extension Api.functions.payments { + static func convertStarGift(stargift: Api.InputSavedStarGift) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1958676331) + stargift.serialize(buffer, true) + return (FunctionDescription(name: "payments.convertStarGift", parameters: [("stargift", String(describing: stargift))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.payments { + static func craftStarGift(stargift: [Api.InputSavedStarGift]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1325832113) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(stargift.count)) + for item in stargift { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "payments.craftStarGift", parameters: [("stargift", String(describing: stargift))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.payments { + static func createStarGiftCollection(peer: Api.InputPeer, title: String, stargift: [Api.InputSavedStarGift]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(524947079) + peer.serialize(buffer, true) + serializeString(title, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(stargift.count)) + for item in stargift { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "payments.createStarGiftCollection", parameters: [("peer", String(describing: peer)), ("title", String(describing: title)), ("stargift", String(describing: stargift))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.StarGiftCollection? in + let reader = BufferReader(buffer) + var result: Api.StarGiftCollection? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.StarGiftCollection + } + return result + }) + } +} +public extension Api.functions.payments { + static func deleteStarGiftCollection(peer: Api.InputPeer, collectionId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1386854168) + peer.serialize(buffer, true) + serializeInt32(collectionId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.deleteStarGiftCollection", parameters: [("peer", String(describing: peer)), ("collectionId", String(describing: collectionId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.payments { + static func editConnectedStarRefBot(flags: Int32, peer: Api.InputPeer, link: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-453204829) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeString(link, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.editConnectedStarRefBot", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("link", String(describing: link))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.ConnectedStarRefBots? in + let reader = BufferReader(buffer) + var result: Api.payments.ConnectedStarRefBots? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.ConnectedStarRefBots + } + return result + }) + } +} +public extension Api.functions.payments { + static func exportInvoice(invoiceMedia: Api.InputMedia) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(261206117) + invoiceMedia.serialize(buffer, true) + return (FunctionDescription(name: "payments.exportInvoice", parameters: [("invoiceMedia", String(describing: invoiceMedia))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.ExportedInvoice? in + let reader = BufferReader(buffer) + var result: Api.payments.ExportedInvoice? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.ExportedInvoice + } + return result + }) + } +} +public extension Api.functions.payments { + static func fulfillStarsSubscription(peer: Api.InputPeer, subscriptionId: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-866391117) + peer.serialize(buffer, true) + serializeString(subscriptionId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.fulfillStarsSubscription", parameters: [("peer", String(describing: peer)), ("subscriptionId", String(describing: subscriptionId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.payments { + static func getBankCardData(number: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(779736953) + serializeString(number, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getBankCardData", parameters: [("number", String(describing: number))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.BankCardData? in + let reader = BufferReader(buffer) + var result: Api.payments.BankCardData? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.BankCardData + } + return result + }) + } +} +public extension Api.functions.payments { + static func getConnectedStarRefBot(peer: Api.InputPeer, bot: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1210476304) + peer.serialize(buffer, true) + bot.serialize(buffer, true) + return (FunctionDescription(name: "payments.getConnectedStarRefBot", parameters: [("peer", String(describing: peer)), ("bot", String(describing: bot))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.ConnectedStarRefBots? in + let reader = BufferReader(buffer) + var result: Api.payments.ConnectedStarRefBots? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.ConnectedStarRefBots + } + return result + }) + } +} +public extension Api.functions.payments { + static func getConnectedStarRefBots(flags: Int32, peer: Api.InputPeer, offsetDate: Int32?, offsetLink: String?, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1483318611) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 2) != 0 { + serializeInt32(offsetDate!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + serializeString(offsetLink!, buffer: buffer, boxed: false) + } + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getConnectedStarRefBots", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("offsetDate", String(describing: offsetDate)), ("offsetLink", String(describing: offsetLink)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.ConnectedStarRefBots? in + let reader = BufferReader(buffer) + var result: Api.payments.ConnectedStarRefBots? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.ConnectedStarRefBots + } + return result + }) + } +} +public extension Api.functions.payments { + static func getCraftStarGifts(giftId: Int64, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-49947392) + serializeInt64(giftId, buffer: buffer, boxed: false) + serializeString(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getCraftStarGifts", parameters: [("giftId", String(describing: giftId)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.SavedStarGifts? in + let reader = BufferReader(buffer) + var result: Api.payments.SavedStarGifts? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.SavedStarGifts + } + return result + }) + } +} +public extension Api.functions.payments { + static func getGiveawayInfo(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-198994907) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getGiveawayInfo", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.GiveawayInfo? in + let reader = BufferReader(buffer) + var result: Api.payments.GiveawayInfo? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.GiveawayInfo + } + return result + }) + } +} +public extension Api.functions.payments { + static func getPaymentForm(flags: Int32, invoice: Api.InputInvoice, themeParams: Api.DataJSON?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(924093883) + serializeInt32(flags, buffer: buffer, boxed: false) + invoice.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + themeParams!.serialize(buffer, true) + } + return (FunctionDescription(name: "payments.getPaymentForm", parameters: [("flags", String(describing: flags)), ("invoice", String(describing: invoice)), ("themeParams", String(describing: themeParams))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.PaymentForm? in + let reader = BufferReader(buffer) + var result: Api.payments.PaymentForm? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.PaymentForm + } + return result + }) + } +} +public extension Api.functions.payments { + static func getPaymentReceipt(peer: Api.InputPeer, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(611897804) + peer.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getPaymentReceipt", parameters: [("peer", String(describing: peer)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.PaymentReceipt? in + let reader = BufferReader(buffer) + var result: Api.payments.PaymentReceipt? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.PaymentReceipt + } + return result + }) + } +} +public extension Api.functions.payments { + static func getPremiumGiftCodeOptions(flags: Int32, boostPeer: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.PremiumGiftCodeOption]>) { + let buffer = Buffer() + buffer.appendInt32(660060756) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + boostPeer!.serialize(buffer, true) + } + return (FunctionDescription(name: "payments.getPremiumGiftCodeOptions", parameters: [("flags", String(describing: flags)), ("boostPeer", String(describing: boostPeer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.PremiumGiftCodeOption]? in + let reader = BufferReader(buffer) + var result: [Api.PremiumGiftCodeOption]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.PremiumGiftCodeOption.self) + } + return result + }) + } +} +public extension Api.functions.payments { + static func getResaleStarGifts(flags: Int32, attributesHash: Int64?, giftId: Int64, attributes: [Api.StarGiftAttributeId]?, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2053087798) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt64(attributesHash!, buffer: buffer, boxed: false) + } + serializeInt64(giftId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(attributes!.count)) + for item in attributes! { + item.serialize(buffer, true) + } + } + serializeString(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getResaleStarGifts", parameters: [("flags", String(describing: flags)), ("attributesHash", String(describing: attributesHash)), ("giftId", String(describing: giftId)), ("attributes", String(describing: attributes)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.ResaleStarGifts? in + let reader = BufferReader(buffer) + var result: Api.payments.ResaleStarGifts? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.ResaleStarGifts + } + return result + }) + } +} +public extension Api.functions.payments { + static func getSavedInfo() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(578650699) + return (FunctionDescription(name: "payments.getSavedInfo", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.SavedInfo? in + let reader = BufferReader(buffer) + var result: Api.payments.SavedInfo? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.SavedInfo + } + return result + }) + } +} +public extension Api.functions.payments { + static func getSavedStarGift(stargift: [Api.InputSavedStarGift]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1269456634) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(stargift.count)) + for item in stargift { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "payments.getSavedStarGift", parameters: [("stargift", String(describing: stargift))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.SavedStarGifts? in + let reader = BufferReader(buffer) + var result: Api.payments.SavedStarGifts? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.SavedStarGifts + } + return result + }) + } +} +public extension Api.functions.payments { + static func getSavedStarGifts(flags: Int32, peer: Api.InputPeer, collectionId: Int32?, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1558583959) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 6) != 0 { + serializeInt32(collectionId!, buffer: buffer, boxed: false) + } + serializeString(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getSavedStarGifts", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("collectionId", String(describing: collectionId)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.SavedStarGifts? in + let reader = BufferReader(buffer) + var result: Api.payments.SavedStarGifts? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.SavedStarGifts + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarGiftActiveAuctions(hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1513074355) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getStarGiftActiveAuctions", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGiftActiveAuctions? in + let reader = BufferReader(buffer) + var result: Api.payments.StarGiftActiveAuctions? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.StarGiftActiveAuctions + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarGiftAuctionAcquiredGifts(giftId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1805831148) + serializeInt64(giftId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getStarGiftAuctionAcquiredGifts", parameters: [("giftId", String(describing: giftId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGiftAuctionAcquiredGifts? in + let reader = BufferReader(buffer) + var result: Api.payments.StarGiftAuctionAcquiredGifts? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.StarGiftAuctionAcquiredGifts + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarGiftAuctionState(auction: Api.InputStarGiftAuction, version: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1553986774) + auction.serialize(buffer, true) + serializeInt32(version, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getStarGiftAuctionState", parameters: [("auction", String(describing: auction)), ("version", String(describing: version))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGiftAuctionState? in + let reader = BufferReader(buffer) + var result: Api.payments.StarGiftAuctionState? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.StarGiftAuctionState + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarGiftCollections(peer: Api.InputPeer, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1743023651) + peer.serialize(buffer, true) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getStarGiftCollections", parameters: [("peer", String(describing: peer)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGiftCollections? in + let reader = BufferReader(buffer) + var result: Api.payments.StarGiftCollections? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.StarGiftCollections + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarGiftUpgradeAttributes(giftId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1828948824) + serializeInt64(giftId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getStarGiftUpgradeAttributes", parameters: [("giftId", String(describing: giftId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGiftUpgradeAttributes? in + let reader = BufferReader(buffer) + var result: Api.payments.StarGiftUpgradeAttributes? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.StarGiftUpgradeAttributes + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarGiftUpgradePreview(giftId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1667580751) + serializeInt64(giftId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getStarGiftUpgradePreview", parameters: [("giftId", String(describing: giftId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGiftUpgradePreview? in + let reader = BufferReader(buffer) + var result: Api.payments.StarGiftUpgradePreview? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.StarGiftUpgradePreview + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarGiftWithdrawalUrl(stargift: Api.InputSavedStarGift, password: Api.InputCheckPasswordSRP) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-798059608) + stargift.serialize(buffer, true) + password.serialize(buffer, true) + return (FunctionDescription(name: "payments.getStarGiftWithdrawalUrl", parameters: [("stargift", String(describing: stargift)), ("password", String(describing: password))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGiftWithdrawalUrl? in + let reader = BufferReader(buffer) + var result: Api.payments.StarGiftWithdrawalUrl? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.StarGiftWithdrawalUrl + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarGifts(hash: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1000983152) + serializeInt32(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getStarGifts", parameters: [("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarGifts? in + let reader = BufferReader(buffer) + var result: Api.payments.StarGifts? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.StarGifts + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarsGiftOptions(flags: Int32, userId: Api.InputUser?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.StarsGiftOption]>) { + let buffer = Buffer() + buffer.appendInt32(-741774392) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + userId!.serialize(buffer, true) + } + return (FunctionDescription(name: "payments.getStarsGiftOptions", parameters: [("flags", String(describing: flags)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.StarsGiftOption]? in + let reader = BufferReader(buffer) + var result: [Api.StarsGiftOption]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarsGiftOption.self) + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarsGiveawayOptions() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.StarsGiveawayOption]>) { + let buffer = Buffer() + buffer.appendInt32(-1122042562) + return (FunctionDescription(name: "payments.getStarsGiveawayOptions", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.StarsGiveawayOption]? in + let reader = BufferReader(buffer) + var result: [Api.StarsGiveawayOption]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarsGiveawayOption.self) + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarsRevenueAdsAccountUrl(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-774377531) + peer.serialize(buffer, true) + return (FunctionDescription(name: "payments.getStarsRevenueAdsAccountUrl", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarsRevenueAdsAccountUrl? in + let reader = BufferReader(buffer) + var result: Api.payments.StarsRevenueAdsAccountUrl? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.StarsRevenueAdsAccountUrl + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarsRevenueStats(flags: Int32, peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-652215594) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + return (FunctionDescription(name: "payments.getStarsRevenueStats", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarsRevenueStats? in + let reader = BufferReader(buffer) + var result: Api.payments.StarsRevenueStats? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.StarsRevenueStats + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarsRevenueWithdrawalUrl(flags: Int32, peer: Api.InputPeer, amount: Int64?, password: Api.InputCheckPasswordSRP) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(607378578) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 1) != 0 { + serializeInt64(amount!, buffer: buffer, boxed: false) + } + password.serialize(buffer, true) + return (FunctionDescription(name: "payments.getStarsRevenueWithdrawalUrl", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("amount", String(describing: amount)), ("password", String(describing: password))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarsRevenueWithdrawalUrl? in + let reader = BufferReader(buffer) + var result: Api.payments.StarsRevenueWithdrawalUrl? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.StarsRevenueWithdrawalUrl + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarsStatus(flags: Int32, peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1319744447) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + return (FunctionDescription(name: "payments.getStarsStatus", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarsStatus? in + let reader = BufferReader(buffer) + var result: Api.payments.StarsStatus? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.StarsStatus + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarsSubscriptions(flags: Int32, peer: Api.InputPeer, offset: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(52761285) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeString(offset, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getStarsSubscriptions", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("offset", String(describing: offset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarsStatus? in + let reader = BufferReader(buffer) + var result: Api.payments.StarsStatus? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.StarsStatus + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarsTopupOptions() -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.StarsTopupOption]>) { + let buffer = Buffer() + buffer.appendInt32(-1072773165) + return (FunctionDescription(name: "payments.getStarsTopupOptions", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.StarsTopupOption]? in + let reader = BufferReader(buffer) + var result: [Api.StarsTopupOption]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.StarsTopupOption.self) + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarsTransactions(flags: Int32, subscriptionId: String?, peer: Api.InputPeer, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1775912279) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 3) != 0 { + serializeString(subscriptionId!, buffer: buffer, boxed: false) + } + peer.serialize(buffer, true) + serializeString(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getStarsTransactions", parameters: [("flags", String(describing: flags)), ("subscriptionId", String(describing: subscriptionId)), ("peer", String(describing: peer)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarsStatus? in + let reader = BufferReader(buffer) + var result: Api.payments.StarsStatus? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.StarsStatus + } + return result + }) + } +} +public extension Api.functions.payments { + static func getStarsTransactionsByID(flags: Int32, peer: Api.InputPeer, id: [Api.InputStarsTransaction]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(768218808) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "payments.getStarsTransactionsByID", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.StarsStatus? in + let reader = BufferReader(buffer) + var result: Api.payments.StarsStatus? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.StarsStatus + } + return result + }) + } +} +public extension Api.functions.payments { + static func getSuggestedStarRefBots(flags: Int32, peer: Api.InputPeer, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(225134839) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeString(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getSuggestedStarRefBots", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.SuggestedStarRefBots? in + let reader = BufferReader(buffer) + var result: Api.payments.SuggestedStarRefBots? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.SuggestedStarRefBots + } + return result + }) + } +} +public extension Api.functions.payments { + static func getUniqueStarGift(slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1583919758) + serializeString(slug, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getUniqueStarGift", parameters: [("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.UniqueStarGift? in + let reader = BufferReader(buffer) + var result: Api.payments.UniqueStarGift? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.UniqueStarGift + } + return result + }) + } +} +public extension Api.functions.payments { + static func getUniqueStarGiftValueInfo(slug: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1130737515) + serializeString(slug, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.getUniqueStarGiftValueInfo", parameters: [("slug", String(describing: slug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.UniqueStarGiftValueInfo? in + let reader = BufferReader(buffer) + var result: Api.payments.UniqueStarGiftValueInfo? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.UniqueStarGiftValueInfo + } + return result + }) + } +} +public extension Api.functions.payments { + static func launchPrepaidGiveaway(peer: Api.InputPeer, giveawayId: Int64, purpose: Api.InputStorePaymentPurpose) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1609928480) + peer.serialize(buffer, true) + serializeInt64(giveawayId, buffer: buffer, boxed: false) + purpose.serialize(buffer, true) + return (FunctionDescription(name: "payments.launchPrepaidGiveaway", parameters: [("peer", String(describing: peer)), ("giveawayId", String(describing: giveawayId)), ("purpose", String(describing: purpose))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.payments { + static func refundStarsCharge(userId: Api.InputUser, chargeId: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(632196938) + userId.serialize(buffer, true) + serializeString(chargeId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.refundStarsCharge", parameters: [("userId", String(describing: userId)), ("chargeId", String(describing: chargeId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.payments { + static func reorderStarGiftCollections(peer: Api.InputPeer, order: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1020594996) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(order.count)) + for item in order { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "payments.reorderStarGiftCollections", parameters: [("peer", String(describing: peer)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.payments { + static func resolveStarGiftOffer(flags: Int32, offerMsgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-372344804) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt32(offerMsgId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "payments.resolveStarGiftOffer", parameters: [("flags", String(describing: flags)), ("offerMsgId", String(describing: offerMsgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.payments { + static func saveStarGift(flags: Int32, stargift: Api.InputSavedStarGift) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(707422588) + serializeInt32(flags, buffer: buffer, boxed: false) + stargift.serialize(buffer, true) + return (FunctionDescription(name: "payments.saveStarGift", parameters: [("flags", String(describing: flags)), ("stargift", String(describing: stargift))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.payments { + static func sendPaymentForm(flags: Int32, formId: Int64, invoice: Api.InputInvoice, requestedInfoId: String?, shippingOptionId: String?, credentials: Api.InputPaymentCredentials, tipAmount: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(755192367) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt64(formId, buffer: buffer, boxed: false) + invoice.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(requestedInfoId!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeString(shippingOptionId!, buffer: buffer, boxed: false) + } + credentials.serialize(buffer, true) + if Int(flags) & Int(1 << 2) != 0 { + serializeInt64(tipAmount!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "payments.sendPaymentForm", parameters: [("flags", String(describing: flags)), ("formId", String(describing: formId)), ("invoice", String(describing: invoice)), ("requestedInfoId", String(describing: requestedInfoId)), ("shippingOptionId", String(describing: shippingOptionId)), ("credentials", String(describing: credentials)), ("tipAmount", String(describing: tipAmount))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.PaymentResult? in + let reader = BufferReader(buffer) + var result: Api.payments.PaymentResult? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.PaymentResult + } + return result + }) + } +} +public extension Api.functions.payments { + static func sendStarGiftOffer(flags: Int32, peer: Api.InputPeer, slug: String, price: Api.StarsAmount, duration: Int32, randomId: Int64, allowPaidStars: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1883739327) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeString(slug, buffer: buffer, boxed: false) + price.serialize(buffer, true) + serializeInt32(duration, buffer: buffer, boxed: false) + serializeInt64(randomId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt64(allowPaidStars!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "payments.sendStarGiftOffer", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("slug", String(describing: slug)), ("price", String(describing: price)), ("duration", String(describing: duration)), ("randomId", String(describing: randomId)), ("allowPaidStars", String(describing: allowPaidStars))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.payments { + static func sendStarsForm(formId: Int64, invoice: Api.InputInvoice) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2040056084) + serializeInt64(formId, buffer: buffer, boxed: false) + invoice.serialize(buffer, true) + return (FunctionDescription(name: "payments.sendStarsForm", parameters: [("formId", String(describing: formId)), ("invoice", String(describing: invoice))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.PaymentResult? in + let reader = BufferReader(buffer) + var result: Api.payments.PaymentResult? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.PaymentResult + } + return result + }) + } +} +public extension Api.functions.payments { + static func toggleChatStarGiftNotifications(flags: Int32, peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1626009505) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + return (FunctionDescription(name: "payments.toggleChatStarGiftNotifications", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.payments { + static func toggleStarGiftsPinnedToTop(peer: Api.InputPeer, stargift: [Api.InputSavedStarGift]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(353626032) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(stargift.count)) + for item in stargift { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "payments.toggleStarGiftsPinnedToTop", parameters: [("peer", String(describing: peer)), ("stargift", String(describing: stargift))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.payments { + static func transferStarGift(stargift: Api.InputSavedStarGift, toId: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2132285290) + stargift.serialize(buffer, true) + toId.serialize(buffer, true) + return (FunctionDescription(name: "payments.transferStarGift", parameters: [("stargift", String(describing: stargift)), ("toId", String(describing: toId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.payments { + static func updateStarGiftCollection(flags: Int32, peer: Api.InputPeer, collectionId: Int32, title: String?, deleteStargift: [Api.InputSavedStarGift]?, addStargift: [Api.InputSavedStarGift]?, order: [Api.InputSavedStarGift]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1339932391) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(collectionId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(title!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(deleteStargift!.count)) + for item in deleteStargift! { + item.serialize(buffer, true) + } + } + if Int(flags) & Int(1 << 2) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(addStargift!.count)) + for item in addStargift! { + item.serialize(buffer, true) + } + } + if Int(flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(order!.count)) + for item in order! { + item.serialize(buffer, true) + } + } + return (FunctionDescription(name: "payments.updateStarGiftCollection", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("collectionId", String(describing: collectionId)), ("title", String(describing: title)), ("deleteStargift", String(describing: deleteStargift)), ("addStargift", String(describing: addStargift)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.StarGiftCollection? in + let reader = BufferReader(buffer) + var result: Api.StarGiftCollection? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.StarGiftCollection + } + return result + }) + } +} +public extension Api.functions.payments { + static func updateStarGiftPrice(stargift: Api.InputSavedStarGift, resellAmount: Api.StarsAmount) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-306287413) + stargift.serialize(buffer, true) + resellAmount.serialize(buffer, true) + return (FunctionDescription(name: "payments.updateStarGiftPrice", parameters: [("stargift", String(describing: stargift)), ("resellAmount", String(describing: resellAmount))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.payments { + static func upgradeStarGift(flags: Int32, stargift: Api.InputSavedStarGift) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1361648395) + serializeInt32(flags, buffer: buffer, boxed: false) + stargift.serialize(buffer, true) + return (FunctionDescription(name: "payments.upgradeStarGift", parameters: [("flags", String(describing: flags)), ("stargift", String(describing: stargift))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.payments { + static func validateRequestedInfo(flags: Int32, invoice: Api.InputInvoice, info: Api.PaymentRequestedInfo) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1228345045) + serializeInt32(flags, buffer: buffer, boxed: false) + invoice.serialize(buffer, true) + info.serialize(buffer, true) + return (FunctionDescription(name: "payments.validateRequestedInfo", parameters: [("flags", String(describing: flags)), ("invoice", String(describing: invoice)), ("info", String(describing: info))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.payments.ValidatedRequestedInfo? in + let reader = BufferReader(buffer) + var result: Api.payments.ValidatedRequestedInfo? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.payments.ValidatedRequestedInfo + } + return result + }) + } +} +public extension Api.functions.phone { + static func acceptCall(peer: Api.InputPhoneCall, gB: Buffer, `protocol`: Api.PhoneCallProtocol) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1003664544) + peer.serialize(buffer, true) + serializeBytes(gB, buffer: buffer, boxed: false) + `protocol`.serialize(buffer, true) + return (FunctionDescription(name: "phone.acceptCall", parameters: [("peer", String(describing: peer)), ("gB", String(describing: gB)), ("`protocol`", String(describing: `protocol`))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.PhoneCall? in + let reader = BufferReader(buffer) + var result: Api.phone.PhoneCall? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.phone.PhoneCall + } + return result + }) + } +} +public extension Api.functions.phone { + static func checkGroupCall(call: Api.InputGroupCall, sources: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Int32]>) { + let buffer = Buffer() + buffer.appendInt32(-1248003721) + call.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(sources.count)) + for item in sources { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "phone.checkGroupCall", parameters: [("call", String(describing: call)), ("sources", String(describing: sources))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Int32]? in + let reader = BufferReader(buffer) + var result: [Int32]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + return result + }) + } +} +public extension Api.functions.phone { + static func confirmCall(peer: Api.InputPhoneCall, gA: Buffer, keyFingerprint: Int64, `protocol`: Api.PhoneCallProtocol) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(788404002) + peer.serialize(buffer, true) + serializeBytes(gA, buffer: buffer, boxed: false) + serializeInt64(keyFingerprint, buffer: buffer, boxed: false) + `protocol`.serialize(buffer, true) + return (FunctionDescription(name: "phone.confirmCall", parameters: [("peer", String(describing: peer)), ("gA", String(describing: gA)), ("keyFingerprint", String(describing: keyFingerprint)), ("`protocol`", String(describing: `protocol`))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.PhoneCall? in + let reader = BufferReader(buffer) + var result: Api.phone.PhoneCall? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.phone.PhoneCall + } + return result + }) + } +} +public extension Api.functions.phone { + static func createConferenceCall(flags: Int32, randomId: Int32, publicKey: Int256?, block: Buffer?, params: Api.DataJSON?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2097431739) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt32(randomId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 3) != 0 { + serializeInt256(publicKey!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 3) != 0 { + serializeBytes(block!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 3) != 0 { + params!.serialize(buffer, true) + } + return (FunctionDescription(name: "phone.createConferenceCall", parameters: [("flags", String(describing: flags)), ("randomId", String(describing: randomId)), ("publicKey", String(describing: publicKey)), ("block", String(describing: block)), ("params", String(describing: params))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func createGroupCall(flags: Int32, peer: Api.InputPeer, randomId: Int32, title: String?, scheduleDate: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1221445336) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(randomId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(title!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeInt32(scheduleDate!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "phone.createGroupCall", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("randomId", String(describing: randomId)), ("title", String(describing: title)), ("scheduleDate", String(describing: scheduleDate))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func declineConferenceCallInvite(msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1011325297) + serializeInt32(msgId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "phone.declineConferenceCallInvite", parameters: [("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func deleteConferenceCallParticipants(flags: Int32, call: Api.InputGroupCall, ids: [Int64], block: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1935276763) + serializeInt32(flags, buffer: buffer, boxed: false) + call.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(ids.count)) + for item in ids { + serializeInt64(item, buffer: buffer, boxed: false) + } + serializeBytes(block, buffer: buffer, boxed: false) + return (FunctionDescription(name: "phone.deleteConferenceCallParticipants", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("ids", String(describing: ids)), ("block", String(describing: block))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func deleteGroupCallMessages(flags: Int32, call: Api.InputGroupCall, messages: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-162573065) + serializeInt32(flags, buffer: buffer, boxed: false) + call.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(messages.count)) + for item in messages { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "phone.deleteGroupCallMessages", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("messages", String(describing: messages))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func deleteGroupCallParticipantMessages(flags: Int32, call: Api.InputGroupCall, participant: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(499117216) + serializeInt32(flags, buffer: buffer, boxed: false) + call.serialize(buffer, true) + participant.serialize(buffer, true) + return (FunctionDescription(name: "phone.deleteGroupCallParticipantMessages", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("participant", String(describing: participant))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func discardCall(flags: Int32, peer: Api.InputPhoneCall, duration: Int32, reason: Api.PhoneCallDiscardReason, connectionId: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1295269440) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(duration, buffer: buffer, boxed: false) + reason.serialize(buffer, true) + serializeInt64(connectionId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "phone.discardCall", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("duration", String(describing: duration)), ("reason", String(describing: reason)), ("connectionId", String(describing: connectionId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func discardGroupCall(call: Api.InputGroupCall) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2054648117) + call.serialize(buffer, true) + return (FunctionDescription(name: "phone.discardGroupCall", parameters: [("call", String(describing: call))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func editGroupCallParticipant(flags: Int32, call: Api.InputGroupCall, participant: Api.InputPeer, muted: Api.Bool?, volume: Int32?, raiseHand: Api.Bool?, videoStopped: Api.Bool?, videoPaused: Api.Bool?, presentationPaused: Api.Bool?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1524155713) + serializeInt32(flags, buffer: buffer, boxed: false) + call.serialize(buffer, true) + participant.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + muted!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeInt32(volume!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + raiseHand!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 3) != 0 { + videoStopped!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 4) != 0 { + videoPaused!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 5) != 0 { + presentationPaused!.serialize(buffer, true) + } + return (FunctionDescription(name: "phone.editGroupCallParticipant", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("participant", String(describing: participant)), ("muted", String(describing: muted)), ("volume", String(describing: volume)), ("raiseHand", String(describing: raiseHand)), ("videoStopped", String(describing: videoStopped)), ("videoPaused", String(describing: videoPaused)), ("presentationPaused", String(describing: presentationPaused))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func editGroupCallTitle(call: Api.InputGroupCall, title: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(480685066) + call.serialize(buffer, true) + serializeString(title, buffer: buffer, boxed: false) + return (FunctionDescription(name: "phone.editGroupCallTitle", parameters: [("call", String(describing: call)), ("title", String(describing: title))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func exportGroupCallInvite(flags: Int32, call: Api.InputGroupCall) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-425040769) + serializeInt32(flags, buffer: buffer, boxed: false) + call.serialize(buffer, true) + return (FunctionDescription(name: "phone.exportGroupCallInvite", parameters: [("flags", String(describing: flags)), ("call", String(describing: call))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.ExportedGroupCallInvite? in + let reader = BufferReader(buffer) + var result: Api.phone.ExportedGroupCallInvite? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.phone.ExportedGroupCallInvite + } + return result + }) + } +} +public extension Api.functions.phone { + static func getCallConfig() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1430593449) + return (FunctionDescription(name: "phone.getCallConfig", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.DataJSON? in + let reader = BufferReader(buffer) + var result: Api.DataJSON? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.DataJSON + } + return result + }) + } +} +public extension Api.functions.phone { + static func getGroupCall(call: Api.InputGroupCall, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(68699611) + call.serialize(buffer, true) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "phone.getGroupCall", parameters: [("call", String(describing: call)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.GroupCall? in + let reader = BufferReader(buffer) + var result: Api.phone.GroupCall? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.phone.GroupCall + } + return result + }) + } +} +public extension Api.functions.phone { + static func getGroupCallChainBlocks(call: Api.InputGroupCall, subChainId: Int32, offset: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-291534682) + call.serialize(buffer, true) + serializeInt32(subChainId, buffer: buffer, boxed: false) + serializeInt32(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "phone.getGroupCallChainBlocks", parameters: [("call", String(describing: call)), ("subChainId", String(describing: subChainId)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func getGroupCallJoinAs(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-277077702) + peer.serialize(buffer, true) + return (FunctionDescription(name: "phone.getGroupCallJoinAs", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.JoinAsPeers? in + let reader = BufferReader(buffer) + var result: Api.phone.JoinAsPeers? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.phone.JoinAsPeers + } + return result + }) + } +} +public extension Api.functions.phone { + static func getGroupCallStars(call: Api.InputGroupCall) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1868784386) + call.serialize(buffer, true) + return (FunctionDescription(name: "phone.getGroupCallStars", parameters: [("call", String(describing: call))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.GroupCallStars? in + let reader = BufferReader(buffer) + var result: Api.phone.GroupCallStars? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.phone.GroupCallStars + } + return result + }) + } +} +public extension Api.functions.phone { + static func getGroupCallStreamChannels(call: Api.InputGroupCall) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(447879488) + call.serialize(buffer, true) + return (FunctionDescription(name: "phone.getGroupCallStreamChannels", parameters: [("call", String(describing: call))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.GroupCallStreamChannels? in + let reader = BufferReader(buffer) + var result: Api.phone.GroupCallStreamChannels? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.phone.GroupCallStreamChannels + } + return result + }) + } +} +public extension Api.functions.phone { + static func getGroupCallStreamRtmpUrl(flags: Int32, peer: Api.InputPeer, revoke: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1525991226) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + revoke.serialize(buffer, true) + return (FunctionDescription(name: "phone.getGroupCallStreamRtmpUrl", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("revoke", String(describing: revoke))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.GroupCallStreamRtmpUrl? in + let reader = BufferReader(buffer) + var result: Api.phone.GroupCallStreamRtmpUrl? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.phone.GroupCallStreamRtmpUrl + } + return result + }) + } +} +public extension Api.functions.phone { + static func getGroupParticipants(call: Api.InputGroupCall, ids: [Api.InputPeer], sources: [Int32], offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-984033109) + call.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(ids.count)) + for item in ids { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(sources.count)) + for item in sources { + serializeInt32(item, buffer: buffer, boxed: false) + } + serializeString(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "phone.getGroupParticipants", parameters: [("call", String(describing: call)), ("ids", String(describing: ids)), ("sources", String(describing: sources)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.GroupParticipants? in + let reader = BufferReader(buffer) + var result: Api.phone.GroupParticipants? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.phone.GroupParticipants + } + return result + }) + } +} +public extension Api.functions.phone { + static func inviteConferenceCallParticipant(flags: Int32, call: Api.InputGroupCall, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1124981115) + serializeInt32(flags, buffer: buffer, boxed: false) + call.serialize(buffer, true) + userId.serialize(buffer, true) + return (FunctionDescription(name: "phone.inviteConferenceCallParticipant", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func inviteToGroupCall(call: Api.InputGroupCall, users: [Api.InputUser]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2067345760) + call.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(users.count)) + for item in users { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "phone.inviteToGroupCall", parameters: [("call", String(describing: call)), ("users", String(describing: users))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func joinGroupCall(flags: Int32, call: Api.InputGroupCall, joinAs: Api.InputPeer, inviteHash: String?, publicKey: Int256?, block: Buffer?, params: Api.DataJSON) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1883951017) + serializeInt32(flags, buffer: buffer, boxed: false) + call.serialize(buffer, true) + joinAs.serialize(buffer, true) + if Int(flags) & Int(1 << 1) != 0 { + serializeString(inviteHash!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 3) != 0 { + serializeInt256(publicKey!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 3) != 0 { + serializeBytes(block!, buffer: buffer, boxed: false) + } + params.serialize(buffer, true) + return (FunctionDescription(name: "phone.joinGroupCall", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("joinAs", String(describing: joinAs)), ("inviteHash", String(describing: inviteHash)), ("publicKey", String(describing: publicKey)), ("block", String(describing: block)), ("params", String(describing: params))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func joinGroupCallPresentation(call: Api.InputGroupCall, params: Api.DataJSON) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-873829436) + call.serialize(buffer, true) + params.serialize(buffer, true) + return (FunctionDescription(name: "phone.joinGroupCallPresentation", parameters: [("call", String(describing: call)), ("params", String(describing: params))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func leaveGroupCall(call: Api.InputGroupCall, source: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1342404601) + call.serialize(buffer, true) + serializeInt32(source, buffer: buffer, boxed: false) + return (FunctionDescription(name: "phone.leaveGroupCall", parameters: [("call", String(describing: call)), ("source", String(describing: source))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func leaveGroupCallPresentation(call: Api.InputGroupCall) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(475058500) + call.serialize(buffer, true) + return (FunctionDescription(name: "phone.leaveGroupCallPresentation", parameters: [("call", String(describing: call))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func receivedCall(peer: Api.InputPhoneCall) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(399855457) + peer.serialize(buffer, true) + return (FunctionDescription(name: "phone.receivedCall", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.phone { + static func requestCall(flags: Int32, userId: Api.InputUser, randomId: Int32, gAHash: Buffer, `protocol`: Api.PhoneCallProtocol) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1124046573) + serializeInt32(flags, buffer: buffer, boxed: false) + userId.serialize(buffer, true) + serializeInt32(randomId, buffer: buffer, boxed: false) + serializeBytes(gAHash, buffer: buffer, boxed: false) + `protocol`.serialize(buffer, true) + return (FunctionDescription(name: "phone.requestCall", parameters: [("flags", String(describing: flags)), ("userId", String(describing: userId)), ("randomId", String(describing: randomId)), ("gAHash", String(describing: gAHash)), ("`protocol`", String(describing: `protocol`))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.phone.PhoneCall? in + let reader = BufferReader(buffer) + var result: Api.phone.PhoneCall? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.phone.PhoneCall + } + return result + }) + } +} +public extension Api.functions.phone { + static func saveCallDebug(peer: Api.InputPhoneCall, debug: Api.DataJSON) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(662363518) + peer.serialize(buffer, true) + debug.serialize(buffer, true) + return (FunctionDescription(name: "phone.saveCallDebug", parameters: [("peer", String(describing: peer)), ("debug", String(describing: debug))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.phone { + static func saveCallLog(peer: Api.InputPhoneCall, file: Api.InputFile) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1092913030) + peer.serialize(buffer, true) + file.serialize(buffer, true) + return (FunctionDescription(name: "phone.saveCallLog", parameters: [("peer", String(describing: peer)), ("file", String(describing: file))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.phone { + static func saveDefaultGroupCallJoinAs(peer: Api.InputPeer, joinAs: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1465786252) + peer.serialize(buffer, true) + joinAs.serialize(buffer, true) + return (FunctionDescription(name: "phone.saveDefaultGroupCallJoinAs", parameters: [("peer", String(describing: peer)), ("joinAs", String(describing: joinAs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.phone { + static func saveDefaultSendAs(call: Api.InputGroupCall, sendAs: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1097313745) + call.serialize(buffer, true) + sendAs.serialize(buffer, true) + return (FunctionDescription(name: "phone.saveDefaultSendAs", parameters: [("call", String(describing: call)), ("sendAs", String(describing: sendAs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.phone { + static func sendConferenceCallBroadcast(call: Api.InputGroupCall, block: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-965732096) + call.serialize(buffer, true) + serializeBytes(block, buffer: buffer, boxed: false) + return (FunctionDescription(name: "phone.sendConferenceCallBroadcast", parameters: [("call", String(describing: call)), ("block", String(describing: block))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func sendGroupCallEncryptedMessage(call: Api.InputGroupCall, encryptedMessage: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-441473683) + call.serialize(buffer, true) + serializeBytes(encryptedMessage, buffer: buffer, boxed: false) + return (FunctionDescription(name: "phone.sendGroupCallEncryptedMessage", parameters: [("call", String(describing: call)), ("encryptedMessage", String(describing: encryptedMessage))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.phone { + static func sendGroupCallMessage(flags: Int32, call: Api.InputGroupCall, randomId: Int64, message: Api.TextWithEntities, allowPaidStars: Int64?, sendAs: Api.InputPeer?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1311697904) + serializeInt32(flags, buffer: buffer, boxed: false) + call.serialize(buffer, true) + serializeInt64(randomId, buffer: buffer, boxed: false) + message.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt64(allowPaidStars!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + sendAs!.serialize(buffer, true) + } + return (FunctionDescription(name: "phone.sendGroupCallMessage", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("randomId", String(describing: randomId)), ("message", String(describing: message)), ("allowPaidStars", String(describing: allowPaidStars)), ("sendAs", String(describing: sendAs))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func sendSignalingData(peer: Api.InputPhoneCall, data: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-8744061) + peer.serialize(buffer, true) + serializeBytes(data, buffer: buffer, boxed: false) + return (FunctionDescription(name: "phone.sendSignalingData", parameters: [("peer", String(describing: peer)), ("data", String(describing: data))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.phone { + static func setCallRating(flags: Int32, peer: Api.InputPhoneCall, rating: Int32, comment: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1508562471) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(rating, buffer: buffer, boxed: false) + serializeString(comment, buffer: buffer, boxed: false) + return (FunctionDescription(name: "phone.setCallRating", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("rating", String(describing: rating)), ("comment", String(describing: comment))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func startScheduledGroupCall(call: Api.InputGroupCall) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1451287362) + call.serialize(buffer, true) + return (FunctionDescription(name: "phone.startScheduledGroupCall", parameters: [("call", String(describing: call))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func toggleGroupCallRecord(flags: Int32, call: Api.InputGroupCall, title: String?, videoPortrait: Api.Bool?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-248985848) + serializeInt32(flags, buffer: buffer, boxed: false) + call.serialize(buffer, true) + if Int(flags) & Int(1 << 1) != 0 { + serializeString(title!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 2) != 0 { + videoPortrait!.serialize(buffer, true) + } + return (FunctionDescription(name: "phone.toggleGroupCallRecord", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("title", String(describing: title)), ("videoPortrait", String(describing: videoPortrait))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func toggleGroupCallSettings(flags: Int32, call: Api.InputGroupCall, joinMuted: Api.Bool?, messagesEnabled: Api.Bool?, sendPaidMessagesStars: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1757179150) + serializeInt32(flags, buffer: buffer, boxed: false) + call.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + joinMuted!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 2) != 0 { + messagesEnabled!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 3) != 0 { + serializeInt64(sendPaidMessagesStars!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "phone.toggleGroupCallSettings", parameters: [("flags", String(describing: flags)), ("call", String(describing: call)), ("joinMuted", String(describing: joinMuted)), ("messagesEnabled", String(describing: messagesEnabled)), ("sendPaidMessagesStars", String(describing: sendPaidMessagesStars))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.phone { + static func toggleGroupCallStartSubscription(call: Api.InputGroupCall, subscribed: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(563885286) + call.serialize(buffer, true) + subscribed.serialize(buffer, true) + return (FunctionDescription(name: "phone.toggleGroupCallStartSubscription", parameters: [("call", String(describing: call)), ("subscribed", String(describing: subscribed))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.photos { + static func deletePhotos(id: [Api.InputPhoto]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Int64]>) { + let buffer = Buffer() + buffer.appendInt32(-2016444625) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "photos.deletePhotos", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Int64]? in + let reader = BufferReader(buffer) + var result: [Int64]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 570911930, elementType: Int64.self) + } + return result + }) + } +} +public extension Api.functions.photos { + static func getUserPhotos(userId: Api.InputUser, offset: Int32, maxId: Int64, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1848823128) + userId.serialize(buffer, true) + serializeInt32(offset, buffer: buffer, boxed: false) + serializeInt64(maxId, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "photos.getUserPhotos", parameters: [("userId", String(describing: userId)), ("offset", String(describing: offset)), ("maxId", String(describing: maxId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.photos.Photos? in + let reader = BufferReader(buffer) + var result: Api.photos.Photos? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.photos.Photos + } + return result + }) + } +} +public extension Api.functions.photos { + static func updateProfilePhoto(flags: Int32, bot: Api.InputUser?, id: Api.InputPhoto) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(166207545) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 1) != 0 { + bot!.serialize(buffer, true) + } + id.serialize(buffer, true) + return (FunctionDescription(name: "photos.updateProfilePhoto", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.photos.Photo? in + let reader = BufferReader(buffer) + var result: Api.photos.Photo? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.photos.Photo + } + return result + }) + } +} +public extension Api.functions.photos { + static func uploadContactProfilePhoto(flags: Int32, userId: Api.InputUser, file: Api.InputFile?, video: Api.InputFile?, videoStartTs: Double?, videoEmojiMarkup: Api.VideoSize?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-515093903) + serializeInt32(flags, buffer: buffer, boxed: false) + userId.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + file!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 1) != 0 { + video!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 2) != 0 { + serializeDouble(videoStartTs!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 5) != 0 { + videoEmojiMarkup!.serialize(buffer, true) + } + return (FunctionDescription(name: "photos.uploadContactProfilePhoto", parameters: [("flags", String(describing: flags)), ("userId", String(describing: userId)), ("file", String(describing: file)), ("video", String(describing: video)), ("videoStartTs", String(describing: videoStartTs)), ("videoEmojiMarkup", String(describing: videoEmojiMarkup))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.photos.Photo? in + let reader = BufferReader(buffer) + var result: Api.photos.Photo? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.photos.Photo + } + return result + }) + } +} +public extension Api.functions.photos { + static func uploadProfilePhoto(flags: Int32, bot: Api.InputUser?, file: Api.InputFile?, video: Api.InputFile?, videoStartTs: Double?, videoEmojiMarkup: Api.VideoSize?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(59286453) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 5) != 0 { + bot!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 0) != 0 { + file!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 1) != 0 { + video!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 2) != 0 { + serializeDouble(videoStartTs!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 4) != 0 { + videoEmojiMarkup!.serialize(buffer, true) + } + return (FunctionDescription(name: "photos.uploadProfilePhoto", parameters: [("flags", String(describing: flags)), ("bot", String(describing: bot)), ("file", String(describing: file)), ("video", String(describing: video)), ("videoStartTs", String(describing: videoStartTs)), ("videoEmojiMarkup", String(describing: videoEmojiMarkup))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.photos.Photo? in + let reader = BufferReader(buffer) + var result: Api.photos.Photo? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.photos.Photo + } + return result + }) + } +} +public extension Api.functions.premium { + static func applyBoost(flags: Int32, slots: [Int32]?, peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1803396934) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(slots!.count)) + for item in slots! { + serializeInt32(item, buffer: buffer, boxed: false) + } + } + peer.serialize(buffer, true) + return (FunctionDescription(name: "premium.applyBoost", parameters: [("flags", String(describing: flags)), ("slots", String(describing: slots)), ("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.premium.MyBoosts? in + let reader = BufferReader(buffer) + var result: Api.premium.MyBoosts? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.premium.MyBoosts + } + return result + }) + } +} +public extension Api.functions.premium { + static func getBoostsList(flags: Int32, peer: Api.InputPeer, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1626764896) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeString(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "premium.getBoostsList", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.premium.BoostsList? in + let reader = BufferReader(buffer) + var result: Api.premium.BoostsList? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.premium.BoostsList + } + return result + }) + } +} +public extension Api.functions.premium { + static func getBoostsStatus(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(70197089) + peer.serialize(buffer, true) + return (FunctionDescription(name: "premium.getBoostsStatus", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.premium.BoostsStatus? in + let reader = BufferReader(buffer) + var result: Api.premium.BoostsStatus? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.premium.BoostsStatus + } + return result + }) + } +} +public extension Api.functions.premium { + static func getMyBoosts() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(199719754) + return (FunctionDescription(name: "premium.getMyBoosts", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.premium.MyBoosts? in + let reader = BufferReader(buffer) + var result: Api.premium.MyBoosts? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.premium.MyBoosts + } + return result + }) + } +} +public extension Api.functions.premium { + static func getUserBoosts(peer: Api.InputPeer, userId: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(965037343) + peer.serialize(buffer, true) + userId.serialize(buffer, true) + return (FunctionDescription(name: "premium.getUserBoosts", parameters: [("peer", String(describing: peer)), ("userId", String(describing: userId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.premium.BoostsList? in + let reader = BufferReader(buffer) + var result: Api.premium.BoostsList? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.premium.BoostsList + } + return result + }) + } +} +public extension Api.functions.smsjobs { + static func finishJob(flags: Int32, jobId: String, error: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1327415076) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(jobId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(error!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "smsjobs.finishJob", parameters: [("flags", String(describing: flags)), ("jobId", String(describing: jobId)), ("error", String(describing: error))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.smsjobs { + static func getSmsJob(jobId: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2005766191) + serializeString(jobId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "smsjobs.getSmsJob", parameters: [("jobId", String(describing: jobId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.SmsJob? in + let reader = BufferReader(buffer) + var result: Api.SmsJob? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.SmsJob + } + return result + }) + } +} +public extension Api.functions.smsjobs { + static func getStatus() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(279353576) + return (FunctionDescription(name: "smsjobs.getStatus", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.smsjobs.Status? in + let reader = BufferReader(buffer) + var result: Api.smsjobs.Status? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.smsjobs.Status + } + return result + }) + } +} +public extension Api.functions.smsjobs { + static func isEligibleToJoin() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(249313744) + return (FunctionDescription(name: "smsjobs.isEligibleToJoin", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.smsjobs.EligibilityToJoin? in + let reader = BufferReader(buffer) + var result: Api.smsjobs.EligibilityToJoin? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.smsjobs.EligibilityToJoin + } + return result + }) + } +} +public extension Api.functions.smsjobs { + static func join() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1488007635) + return (FunctionDescription(name: "smsjobs.join", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.smsjobs { + static func leave() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1734824589) + return (FunctionDescription(name: "smsjobs.leave", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.smsjobs { + static func updateSettings(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(155164863) + serializeInt32(flags, buffer: buffer, boxed: false) + return (FunctionDescription(name: "smsjobs.updateSettings", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.stats { + static func getBroadcastStats(flags: Int32, channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1421720550) + serializeInt32(flags, buffer: buffer, boxed: false) + channel.serialize(buffer, true) + return (FunctionDescription(name: "stats.getBroadcastStats", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stats.BroadcastStats? in + let reader = BufferReader(buffer) + var result: Api.stats.BroadcastStats? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stats.BroadcastStats + } + return result + }) + } +} +public extension Api.functions.stats { + static func getMegagroupStats(flags: Int32, channel: Api.InputChannel) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-589330937) + serializeInt32(flags, buffer: buffer, boxed: false) + channel.serialize(buffer, true) + return (FunctionDescription(name: "stats.getMegagroupStats", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stats.MegagroupStats? in + let reader = BufferReader(buffer) + var result: Api.stats.MegagroupStats? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stats.MegagroupStats + } + return result + }) + } +} +public extension Api.functions.stats { + static func getMessagePublicForwards(channel: Api.InputChannel, msgId: Int32, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1595212100) + channel.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + serializeString(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stats.getMessagePublicForwards", parameters: [("channel", String(describing: channel)), ("msgId", String(describing: msgId)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stats.PublicForwards? in + let reader = BufferReader(buffer) + var result: Api.stats.PublicForwards? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stats.PublicForwards + } + return result + }) + } +} +public extension Api.functions.stats { + static func getMessageStats(flags: Int32, channel: Api.InputChannel, msgId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1226791947) + serializeInt32(flags, buffer: buffer, boxed: false) + channel.serialize(buffer, true) + serializeInt32(msgId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stats.getMessageStats", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel)), ("msgId", String(describing: msgId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stats.MessageStats? in + let reader = BufferReader(buffer) + var result: Api.stats.MessageStats? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stats.MessageStats + } + return result + }) + } +} +public extension Api.functions.stats { + static func getStoryPublicForwards(peer: Api.InputPeer, id: Int32, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1505526026) + peer.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + serializeString(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stats.getStoryPublicForwards", parameters: [("peer", String(describing: peer)), ("id", String(describing: id)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stats.PublicForwards? in + let reader = BufferReader(buffer) + var result: Api.stats.PublicForwards? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stats.PublicForwards + } + return result + }) + } +} +public extension Api.functions.stats { + static func getStoryStats(flags: Int32, peer: Api.InputPeer, id: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(927985472) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stats.getStoryStats", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stats.StoryStats? in + let reader = BufferReader(buffer) + var result: Api.stats.StoryStats? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stats.StoryStats + } + return result + }) + } +} +public extension Api.functions.stats { + static func loadAsyncGraph(flags: Int32, token: String, x: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1646092192) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeString(token, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeInt64(x!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "stats.loadAsyncGraph", parameters: [("flags", String(describing: flags)), ("token", String(describing: token)), ("x", String(describing: x))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.StatsGraph? in + let reader = BufferReader(buffer) + var result: Api.StatsGraph? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.StatsGraph + } + return result + }) + } +} +public extension Api.functions.stickers { + static func addStickerToSet(stickerset: Api.InputStickerSet, sticker: Api.InputStickerSetItem) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2041315650) + stickerset.serialize(buffer, true) + sticker.serialize(buffer, true) + return (FunctionDescription(name: "stickers.addStickerToSet", parameters: [("stickerset", String(describing: stickerset)), ("sticker", String(describing: sticker))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in + let reader = BufferReader(buffer) + var result: Api.messages.StickerSet? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet + } + return result + }) + } +} +public extension Api.functions.stickers { + static func changeSticker(flags: Int32, sticker: Api.InputDocument, emoji: String?, maskCoords: Api.MaskCoords?, keywords: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-179077444) + serializeInt32(flags, buffer: buffer, boxed: false) + sticker.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(emoji!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + maskCoords!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 2) != 0 { + serializeString(keywords!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "stickers.changeSticker", parameters: [("flags", String(describing: flags)), ("sticker", String(describing: sticker)), ("emoji", String(describing: emoji)), ("maskCoords", String(describing: maskCoords)), ("keywords", String(describing: keywords))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in + let reader = BufferReader(buffer) + var result: Api.messages.StickerSet? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet + } + return result + }) + } +} +public extension Api.functions.stickers { + static func changeStickerPosition(sticker: Api.InputDocument, position: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-4795190) + sticker.serialize(buffer, true) + serializeInt32(position, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stickers.changeStickerPosition", parameters: [("sticker", String(describing: sticker)), ("position", String(describing: position))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in + let reader = BufferReader(buffer) + var result: Api.messages.StickerSet? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet + } + return result + }) + } +} +public extension Api.functions.stickers { + static func checkShortName(shortName: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(676017721) + serializeString(shortName, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stickers.checkShortName", parameters: [("shortName", String(describing: shortName))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.stickers { + static func createStickerSet(flags: Int32, userId: Api.InputUser, title: String, shortName: String, thumb: Api.InputDocument?, stickers: [Api.InputStickerSetItem], software: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1876841625) + serializeInt32(flags, buffer: buffer, boxed: false) + userId.serialize(buffer, true) + serializeString(title, buffer: buffer, boxed: false) + serializeString(shortName, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 2) != 0 { + thumb!.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(stickers.count)) + for item in stickers { + item.serialize(buffer, true) + } + if Int(flags) & Int(1 << 3) != 0 { + serializeString(software!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "stickers.createStickerSet", parameters: [("flags", String(describing: flags)), ("userId", String(describing: userId)), ("title", String(describing: title)), ("shortName", String(describing: shortName)), ("thumb", String(describing: thumb)), ("stickers", String(describing: stickers)), ("software", String(describing: software))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in + let reader = BufferReader(buffer) + var result: Api.messages.StickerSet? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet + } + return result + }) + } +} +public extension Api.functions.stickers { + static func deleteStickerSet(stickerset: Api.InputStickerSet) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2022685804) + stickerset.serialize(buffer, true) + return (FunctionDescription(name: "stickers.deleteStickerSet", parameters: [("stickerset", String(describing: stickerset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.stickers { + static func removeStickerFromSet(sticker: Api.InputDocument) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-143257775) + sticker.serialize(buffer, true) + return (FunctionDescription(name: "stickers.removeStickerFromSet", parameters: [("sticker", String(describing: sticker))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in + let reader = BufferReader(buffer) + var result: Api.messages.StickerSet? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet + } + return result + }) + } +} +public extension Api.functions.stickers { + static func renameStickerSet(stickerset: Api.InputStickerSet, title: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(306912256) + stickerset.serialize(buffer, true) + serializeString(title, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stickers.renameStickerSet", parameters: [("stickerset", String(describing: stickerset)), ("title", String(describing: title))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in + let reader = BufferReader(buffer) + var result: Api.messages.StickerSet? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet + } + return result + }) + } +} +public extension Api.functions.stickers { + static func replaceSticker(sticker: Api.InputDocument, newSticker: Api.InputStickerSetItem) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1184253338) + sticker.serialize(buffer, true) + newSticker.serialize(buffer, true) + return (FunctionDescription(name: "stickers.replaceSticker", parameters: [("sticker", String(describing: sticker)), ("newSticker", String(describing: newSticker))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in + let reader = BufferReader(buffer) + var result: Api.messages.StickerSet? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet + } + return result + }) + } +} +public extension Api.functions.stickers { + static func setStickerSetThumb(flags: Int32, stickerset: Api.InputStickerSet, thumb: Api.InputDocument?, thumbDocumentId: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1486204014) + serializeInt32(flags, buffer: buffer, boxed: false) + stickerset.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + thumb!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeInt64(thumbDocumentId!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "stickers.setStickerSetThumb", parameters: [("flags", String(describing: flags)), ("stickerset", String(describing: stickerset)), ("thumb", String(describing: thumb)), ("thumbDocumentId", String(describing: thumbDocumentId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.StickerSet? in + let reader = BufferReader(buffer) + var result: Api.messages.StickerSet? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.StickerSet + } + return result + }) + } +} +public extension Api.functions.stickers { + static func suggestShortName(title: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1303364867) + serializeString(title, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stickers.suggestShortName", parameters: [("title", String(describing: title))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stickers.SuggestedShortName? in + let reader = BufferReader(buffer) + var result: Api.stickers.SuggestedShortName? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stickers.SuggestedShortName + } + return result + }) + } +} +public extension Api.functions.stories { + static func activateStealthMode(flags: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1471926630) + serializeInt32(flags, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stories.activateStealthMode", parameters: [("flags", String(describing: flags))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.stories { + static func canSendStory(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(820732912) + peer.serialize(buffer, true) + return (FunctionDescription(name: "stories.canSendStory", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.CanSendStoryCount? in + let reader = BufferReader(buffer) + var result: Api.stories.CanSendStoryCount? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stories.CanSendStoryCount + } + return result + }) + } +} +public extension Api.functions.stories { + static func createAlbum(peer: Api.InputPeer, title: String, stories: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1553754395) + peer.serialize(buffer, true) + serializeString(title, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(stories.count)) + for item in stories { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "stories.createAlbum", parameters: [("peer", String(describing: peer)), ("title", String(describing: title)), ("stories", String(describing: stories))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.StoryAlbum? in + let reader = BufferReader(buffer) + var result: Api.StoryAlbum? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.StoryAlbum + } + return result + }) + } +} +public extension Api.functions.stories { + static func deleteAlbum(peer: Api.InputPeer, albumId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1925949744) + peer.serialize(buffer, true) + serializeInt32(albumId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stories.deleteAlbum", parameters: [("peer", String(describing: peer)), ("albumId", String(describing: albumId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.stories { + static func deleteStories(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Int32]>) { + let buffer = Buffer() + buffer.appendInt32(-1369842849) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "stories.deleteStories", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Int32]? in + let reader = BufferReader(buffer) + var result: [Int32]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + return result + }) + } +} +public extension Api.functions.stories { + static func editStory(flags: Int32, peer: Api.InputPeer, id: Int32, media: Api.InputMedia?, mediaAreas: [Api.MediaArea]?, caption: String?, entities: [Api.MessageEntity]?, privacyRules: [Api.InputPrivacyRule]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1249658298) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + media!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(mediaAreas!.count)) + for item in mediaAreas! { + item.serialize(buffer, true) + } + } + if Int(flags) & Int(1 << 1) != 0 { + serializeString(caption!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(entities!.count)) + for item in entities! { + item.serialize(buffer, true) + } + } + if Int(flags) & Int(1 << 2) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(privacyRules!.count)) + for item in privacyRules! { + item.serialize(buffer, true) + } + } + return (FunctionDescription(name: "stories.editStory", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("media", String(describing: media)), ("mediaAreas", String(describing: mediaAreas)), ("caption", String(describing: caption)), ("entities", String(describing: entities)), ("privacyRules", String(describing: privacyRules))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.stories { + static func exportStoryLink(peer: Api.InputPeer, id: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2072899360) + peer.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stories.exportStoryLink", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ExportedStoryLink? in + let reader = BufferReader(buffer) + var result: Api.ExportedStoryLink? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.ExportedStoryLink + } + return result + }) + } +} +public extension Api.functions.stories { + static func getAlbumStories(peer: Api.InputPeer, albumId: Int32, offset: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1400869535) + peer.serialize(buffer, true) + serializeInt32(albumId, buffer: buffer, boxed: false) + serializeInt32(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stories.getAlbumStories", parameters: [("peer", String(describing: peer)), ("albumId", String(describing: albumId)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.Stories? in + let reader = BufferReader(buffer) + var result: Api.stories.Stories? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stories.Stories + } + return result + }) + } +} +public extension Api.functions.stories { + static func getAlbums(peer: Api.InputPeer, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(632548039) + peer.serialize(buffer, true) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stories.getAlbums", parameters: [("peer", String(describing: peer)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.Albums? in + let reader = BufferReader(buffer) + var result: Api.stories.Albums? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stories.Albums + } + return result + }) + } +} +public extension Api.functions.stories { + static func getAllReadPeerStories() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1688541191) + return (FunctionDescription(name: "stories.getAllReadPeerStories", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.stories { + static func getAllStories(flags: Int32, state: String?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-290400731) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(state!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "stories.getAllStories", parameters: [("flags", String(describing: flags)), ("state", String(describing: state))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.AllStories? in + let reader = BufferReader(buffer) + var result: Api.stories.AllStories? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stories.AllStories + } + return result + }) + } +} +public extension Api.functions.stories { + static func getChatsToSend() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1519744160) + return (FunctionDescription(name: "stories.getChatsToSend", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.messages.Chats? in + let reader = BufferReader(buffer) + var result: Api.messages.Chats? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.messages.Chats + } + return result + }) + } +} +public extension Api.functions.stories { + static func getPeerMaxIDs(id: [Api.InputPeer]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.RecentStory]>) { + let buffer = Buffer() + buffer.appendInt32(2018087280) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "stories.getPeerMaxIDs", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.RecentStory]? in + let reader = BufferReader(buffer) + var result: [Api.RecentStory]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.RecentStory.self) + } + return result + }) + } +} +public extension Api.functions.stories { + static func getPeerStories(peer: Api.InputPeer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(743103056) + peer.serialize(buffer, true) + return (FunctionDescription(name: "stories.getPeerStories", parameters: [("peer", String(describing: peer))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.PeerStories? in + let reader = BufferReader(buffer) + var result: Api.stories.PeerStories? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stories.PeerStories + } + return result + }) + } +} +public extension Api.functions.stories { + static func getPinnedStories(peer: Api.InputPeer, offsetId: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1478600156) + peer.serialize(buffer, true) + serializeInt32(offsetId, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stories.getPinnedStories", parameters: [("peer", String(describing: peer)), ("offsetId", String(describing: offsetId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.Stories? in + let reader = BufferReader(buffer) + var result: Api.stories.Stories? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stories.Stories + } + return result + }) + } +} +public extension Api.functions.stories { + static func getStoriesArchive(peer: Api.InputPeer, offsetId: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1271586794) + peer.serialize(buffer, true) + serializeInt32(offsetId, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stories.getStoriesArchive", parameters: [("peer", String(describing: peer)), ("offsetId", String(describing: offsetId)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.Stories? in + let reader = BufferReader(buffer) + var result: Api.stories.Stories? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stories.Stories + } + return result + }) + } +} +public extension Api.functions.stories { + static func getStoriesByID(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1467271796) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "stories.getStoriesByID", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.Stories? in + let reader = BufferReader(buffer) + var result: Api.stories.Stories? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stories.Stories + } + return result + }) + } +} +public extension Api.functions.stories { + static func getStoriesViews(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(685862088) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "stories.getStoriesViews", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.StoryViews? in + let reader = BufferReader(buffer) + var result: Api.stories.StoryViews? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stories.StoryViews + } + return result + }) + } +} +public extension Api.functions.stories { + static func getStoryReactionsList(flags: Int32, peer: Api.InputPeer, id: Int32, reaction: Api.Reaction?, offset: String?, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1179482081) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(id, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + reaction!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 1) != 0 { + serializeString(offset!, buffer: buffer, boxed: false) + } + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stories.getStoryReactionsList", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("id", String(describing: id)), ("reaction", String(describing: reaction)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.StoryReactionsList? in + let reader = BufferReader(buffer) + var result: Api.stories.StoryReactionsList? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stories.StoryReactionsList + } + return result + }) + } +} +public extension Api.functions.stories { + static func getStoryViewsList(flags: Int32, peer: Api.InputPeer, q: String?, id: Int32, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2127707223) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 1) != 0 { + serializeString(q!, buffer: buffer, boxed: false) + } + serializeInt32(id, buffer: buffer, boxed: false) + serializeString(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stories.getStoryViewsList", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("q", String(describing: q)), ("id", String(describing: id)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.StoryViewsList? in + let reader = BufferReader(buffer) + var result: Api.stories.StoryViewsList? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stories.StoryViewsList + } + return result + }) + } +} +public extension Api.functions.stories { + static func incrementStoryViews(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1308456197) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "stories.incrementStoryViews", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.stories { + static func readStories(peer: Api.InputPeer, maxId: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Int32]>) { + let buffer = Buffer() + buffer.appendInt32(-1521034552) + peer.serialize(buffer, true) + serializeInt32(maxId, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stories.readStories", parameters: [("peer", String(describing: peer)), ("maxId", String(describing: maxId))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Int32]? in + let reader = BufferReader(buffer) + var result: [Int32]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + return result + }) + } +} +public extension Api.functions.stories { + static func reorderAlbums(peer: Api.InputPeer, order: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-2060059687) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(order.count)) + for item in order { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "stories.reorderAlbums", parameters: [("peer", String(describing: peer)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.stories { + static func report(peer: Api.InputPeer, id: [Int32], option: Buffer, message: String) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(433646405) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + serializeBytes(option, buffer: buffer, boxed: false) + serializeString(message, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stories.report", parameters: [("peer", String(describing: peer)), ("id", String(describing: id)), ("option", String(describing: option)), ("message", String(describing: message))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.ReportResult? in + let reader = BufferReader(buffer) + var result: Api.ReportResult? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.ReportResult + } + return result + }) + } +} +public extension Api.functions.stories { + static func searchPosts(flags: Int32, hashtag: String?, area: Api.MediaArea?, peer: Api.InputPeer?, offset: String, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-780072697) + serializeInt32(flags, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(hashtag!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + area!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 2) != 0 { + peer!.serialize(buffer, true) + } + serializeString(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "stories.searchPosts", parameters: [("flags", String(describing: flags)), ("hashtag", String(describing: hashtag)), ("area", String(describing: area)), ("peer", String(describing: peer)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.stories.FoundStories? in + let reader = BufferReader(buffer) + var result: Api.stories.FoundStories? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.stories.FoundStories + } + return result + }) + } +} +public extension Api.functions.stories { + static func sendReaction(flags: Int32, peer: Api.InputPeer, storyId: Int32, reaction: Api.Reaction) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2144810674) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(storyId, buffer: buffer, boxed: false) + reaction.serialize(buffer, true) + return (FunctionDescription(name: "stories.sendReaction", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("storyId", String(describing: storyId)), ("reaction", String(describing: reaction))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.stories { + static func sendStory(flags: Int32, peer: Api.InputPeer, media: Api.InputMedia, mediaAreas: [Api.MediaArea]?, caption: String?, entities: [Api.MessageEntity]?, privacyRules: [Api.InputPrivacyRule], randomId: Int64, period: Int32?, fwdFromId: Api.InputPeer?, fwdFromStory: Int32?, albums: [Int32]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1937752812) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + media.serialize(buffer, true) + if Int(flags) & Int(1 << 5) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(mediaAreas!.count)) + for item in mediaAreas! { + item.serialize(buffer, true) + } + } + if Int(flags) & Int(1 << 0) != 0 { + serializeString(caption!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(entities!.count)) + for item in entities! { + item.serialize(buffer, true) + } + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(privacyRules.count)) + for item in privacyRules { + item.serialize(buffer, true) + } + serializeInt64(randomId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 3) != 0 { + serializeInt32(period!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 6) != 0 { + fwdFromId!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 6) != 0 { + serializeInt32(fwdFromStory!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 8) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(albums!.count)) + for item in albums! { + serializeInt32(item, buffer: buffer, boxed: false) + } + } + return (FunctionDescription(name: "stories.sendStory", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("media", String(describing: media)), ("mediaAreas", String(describing: mediaAreas)), ("caption", String(describing: caption)), ("entities", String(describing: entities)), ("privacyRules", String(describing: privacyRules)), ("randomId", String(describing: randomId)), ("period", String(describing: period)), ("fwdFromId", String(describing: fwdFromId)), ("fwdFromStory", String(describing: fwdFromStory)), ("albums", String(describing: albums))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.stories { + static func startLive(flags: Int32, peer: Api.InputPeer, caption: String?, entities: [Api.MessageEntity]?, privacyRules: [Api.InputPrivacyRule], randomId: Int64, messagesEnabled: Api.Bool?, sendPaidMessagesStars: Int64?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-798372642) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(caption!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(entities!.count)) + for item in entities! { + item.serialize(buffer, true) + } + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(privacyRules.count)) + for item in privacyRules { + item.serialize(buffer, true) + } + serializeInt64(randomId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 6) != 0 { + messagesEnabled!.serialize(buffer, true) + } + if Int(flags) & Int(1 << 7) != 0 { + serializeInt64(sendPaidMessagesStars!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "stories.startLive", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("caption", String(describing: caption)), ("entities", String(describing: entities)), ("privacyRules", String(describing: privacyRules)), ("randomId", String(describing: randomId)), ("messagesEnabled", String(describing: messagesEnabled)), ("sendPaidMessagesStars", String(describing: sendPaidMessagesStars))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} +public extension Api.functions.stories { + static func toggleAllStoriesHidden(hidden: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2082822084) + hidden.serialize(buffer, true) + return (FunctionDescription(name: "stories.toggleAllStoriesHidden", parameters: [("hidden", String(describing: hidden))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.stories { + static func togglePeerStoriesHidden(peer: Api.InputPeer, hidden: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1123805756) + peer.serialize(buffer, true) + hidden.serialize(buffer, true) + return (FunctionDescription(name: "stories.togglePeerStoriesHidden", parameters: [("peer", String(describing: peer)), ("hidden", String(describing: hidden))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.stories { + static func togglePinned(peer: Api.InputPeer, id: [Int32], pinned: Api.Bool) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Int32]>) { + let buffer = Buffer() + buffer.appendInt32(-1703566865) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + pinned.serialize(buffer, true) + return (FunctionDescription(name: "stories.togglePinned", parameters: [("peer", String(describing: peer)), ("id", String(describing: id)), ("pinned", String(describing: pinned))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Int32]? in + let reader = BufferReader(buffer) + var result: [Int32]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: -1471112230, elementType: Int32.self) + } + return result + }) + } +} +public extension Api.functions.stories { + static func togglePinnedToTop(peer: Api.InputPeer, id: [Int32]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(187268763) + peer.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + serializeInt32(item, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "stories.togglePinnedToTop", parameters: [("peer", String(describing: peer)), ("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.stories { + static func updateAlbum(flags: Int32, peer: Api.InputPeer, albumId: Int32, title: String?, deleteStories: [Int32]?, addStories: [Int32]?, order: [Int32]?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1582455222) + serializeInt32(flags, buffer: buffer, boxed: false) + peer.serialize(buffer, true) + serializeInt32(albumId, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 0) != 0 { + serializeString(title!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(deleteStories!.count)) + for item in deleteStories! { + serializeInt32(item, buffer: buffer, boxed: false) + } + } + if Int(flags) & Int(1 << 2) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(addStories!.count)) + for item in addStories! { + serializeInt32(item, buffer: buffer, boxed: false) + } + } + if Int(flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(order!.count)) + for item in order! { + serializeInt32(item, buffer: buffer, boxed: false) + } + } + return (FunctionDescription(name: "stories.updateAlbum", parameters: [("flags", String(describing: flags)), ("peer", String(describing: peer)), ("albumId", String(describing: albumId)), ("title", String(describing: title)), ("deleteStories", String(describing: deleteStories)), ("addStories", String(describing: addStories)), ("order", String(describing: order))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.StoryAlbum? in + let reader = BufferReader(buffer) + var result: Api.StoryAlbum? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.StoryAlbum + } + return result + }) + } +} +public extension Api.functions.updates { + static func getChannelDifference(flags: Int32, channel: Api.InputChannel, filter: Api.ChannelMessagesFilter, pts: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(51854712) + serializeInt32(flags, buffer: buffer, boxed: false) + channel.serialize(buffer, true) + filter.serialize(buffer, true) + serializeInt32(pts, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "updates.getChannelDifference", parameters: [("flags", String(describing: flags)), ("channel", String(describing: channel)), ("filter", String(describing: filter)), ("pts", String(describing: pts)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.updates.ChannelDifference? in + let reader = BufferReader(buffer) + var result: Api.updates.ChannelDifference? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.updates.ChannelDifference + } + return result + }) + } +} +public extension Api.functions.updates { + static func getDifference(flags: Int32, pts: Int32, ptsLimit: Int32?, ptsTotalLimit: Int32?, date: Int32, qts: Int32, qtsLimit: Int32?) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(432207715) + serializeInt32(flags, buffer: buffer, boxed: false) + serializeInt32(pts, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 1) != 0 { + serializeInt32(ptsLimit!, buffer: buffer, boxed: false) + } + if Int(flags) & Int(1 << 0) != 0 { + serializeInt32(ptsTotalLimit!, buffer: buffer, boxed: false) + } + serializeInt32(date, buffer: buffer, boxed: false) + serializeInt32(qts, buffer: buffer, boxed: false) + if Int(flags) & Int(1 << 2) != 0 { + serializeInt32(qtsLimit!, buffer: buffer, boxed: false) + } + return (FunctionDescription(name: "updates.getDifference", parameters: [("flags", String(describing: flags)), ("pts", String(describing: pts)), ("ptsLimit", String(describing: ptsLimit)), ("ptsTotalLimit", String(describing: ptsTotalLimit)), ("date", String(describing: date)), ("qts", String(describing: qts)), ("qtsLimit", String(describing: qtsLimit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.updates.Difference? in + let reader = BufferReader(buffer) + var result: Api.updates.Difference? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.updates.Difference + } + return result + }) + } +} +public extension Api.functions.updates { + static func getState() -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-304838614) + return (FunctionDescription(name: "updates.getState", parameters: []), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.updates.State? in + let reader = BufferReader(buffer) + var result: Api.updates.State? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.updates.State + } + return result + }) + } +} +public extension Api.functions.upload { + static func getCdnFile(fileToken: Buffer, offset: Int64, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(962554330) + serializeBytes(fileToken, buffer: buffer, boxed: false) + serializeInt64(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "upload.getCdnFile", parameters: [("fileToken", String(describing: fileToken)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.upload.CdnFile? in + let reader = BufferReader(buffer) + var result: Api.upload.CdnFile? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.upload.CdnFile + } + return result + }) + } +} +public extension Api.functions.upload { + static func getCdnFileHashes(fileToken: Buffer, offset: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.FileHash]>) { + let buffer = Buffer() + buffer.appendInt32(-1847836879) + serializeBytes(fileToken, buffer: buffer, boxed: false) + serializeInt64(offset, buffer: buffer, boxed: false) + return (FunctionDescription(name: "upload.getCdnFileHashes", parameters: [("fileToken", String(describing: fileToken)), ("offset", String(describing: offset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.FileHash]? in + let reader = BufferReader(buffer) + var result: [Api.FileHash]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.FileHash.self) + } + return result + }) + } +} +public extension Api.functions.upload { + static func getFile(flags: Int32, location: Api.InputFileLocation, offset: Int64, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1101843010) + serializeInt32(flags, buffer: buffer, boxed: false) + location.serialize(buffer, true) + serializeInt64(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "upload.getFile", parameters: [("flags", String(describing: flags)), ("location", String(describing: location)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.upload.File? in + let reader = BufferReader(buffer) + var result: Api.upload.File? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.upload.File + } + return result + }) + } +} +public extension Api.functions.upload { + static func getFileHashes(location: Api.InputFileLocation, offset: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.FileHash]>) { + let buffer = Buffer() + buffer.appendInt32(-1856595926) + location.serialize(buffer, true) + serializeInt64(offset, buffer: buffer, boxed: false) + return (FunctionDescription(name: "upload.getFileHashes", parameters: [("location", String(describing: location)), ("offset", String(describing: offset))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.FileHash]? in + let reader = BufferReader(buffer) + var result: [Api.FileHash]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.FileHash.self) + } + return result + }) + } +} +public extension Api.functions.upload { + static func getWebFile(location: Api.InputWebFileLocation, offset: Int32, limit: Int32) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(619086221) + location.serialize(buffer, true) + serializeInt32(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + return (FunctionDescription(name: "upload.getWebFile", parameters: [("location", String(describing: location)), ("offset", String(describing: offset)), ("limit", String(describing: limit))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.upload.WebFile? in + let reader = BufferReader(buffer) + var result: Api.upload.WebFile? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.upload.WebFile + } + return result + }) + } +} +public extension Api.functions.upload { + static func reuploadCdnFile(fileToken: Buffer, requestToken: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.FileHash]>) { + let buffer = Buffer() + buffer.appendInt32(-1691921240) + serializeBytes(fileToken, buffer: buffer, boxed: false) + serializeBytes(requestToken, buffer: buffer, boxed: false) + return (FunctionDescription(name: "upload.reuploadCdnFile", parameters: [("fileToken", String(describing: fileToken)), ("requestToken", String(describing: requestToken))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.FileHash]? in + let reader = BufferReader(buffer) + var result: [Api.FileHash]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.FileHash.self) + } + return result + }) + } +} +public extension Api.functions.upload { + static func saveBigFilePart(fileId: Int64, filePart: Int32, fileTotalParts: Int32, bytes: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-562337987) + serializeInt64(fileId, buffer: buffer, boxed: false) + serializeInt32(filePart, buffer: buffer, boxed: false) + serializeInt32(fileTotalParts, buffer: buffer, boxed: false) + serializeBytes(bytes, buffer: buffer, boxed: false) + return (FunctionDescription(name: "upload.saveBigFilePart", parameters: [("fileId", String(describing: fileId)), ("filePart", String(describing: filePart)), ("fileTotalParts", String(describing: fileTotalParts)), ("bytes", String(describing: bytes))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.upload { + static func saveFilePart(fileId: Int64, filePart: Int32, bytes: Buffer) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1291540959) + serializeInt64(fileId, buffer: buffer, boxed: false) + serializeInt32(filePart, buffer: buffer, boxed: false) + serializeBytes(bytes, buffer: buffer, boxed: false) + return (FunctionDescription(name: "upload.saveFilePart", parameters: [("fileId", String(describing: fileId)), ("filePart", String(describing: filePart)), ("bytes", String(describing: bytes))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.users { + static func getFullUser(id: Api.InputUser) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1240508136) + id.serialize(buffer, true) + return (FunctionDescription(name: "users.getFullUser", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.users.UserFull? in + let reader = BufferReader(buffer) + var result: Api.users.UserFull? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.users.UserFull + } + return result + }) + } +} +public extension Api.functions.users { + static func getRequirementsToContact(id: [Api.InputUser]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.RequirementToContact]>) { + let buffer = Buffer() + buffer.appendInt32(-660962397) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "users.getRequirementsToContact", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.RequirementToContact]? in + let reader = BufferReader(buffer) + var result: [Api.RequirementToContact]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.RequirementToContact.self) + } + return result + }) + } +} +public extension Api.functions.users { + static func getSavedMusic(id: Api.InputUser, offset: Int32, limit: Int32, hash: Int64) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(2022539235) + id.serialize(buffer, true) + serializeInt32(offset, buffer: buffer, boxed: false) + serializeInt32(limit, buffer: buffer, boxed: false) + serializeInt64(hash, buffer: buffer, boxed: false) + return (FunctionDescription(name: "users.getSavedMusic", parameters: [("id", String(describing: id)), ("offset", String(describing: offset)), ("limit", String(describing: limit)), ("hash", String(describing: hash))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.users.SavedMusic? in + let reader = BufferReader(buffer) + var result: Api.users.SavedMusic? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.users.SavedMusic + } + return result + }) + } +} +public extension Api.functions.users { + static func getSavedMusicByID(id: Api.InputUser, documents: [Api.InputDocument]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(1970513129) + id.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(documents.count)) + for item in documents { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "users.getSavedMusicByID", parameters: [("id", String(describing: id)), ("documents", String(describing: documents))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.users.SavedMusic? in + let reader = BufferReader(buffer) + var result: Api.users.SavedMusic? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.users.SavedMusic + } + return result + }) + } +} +public extension Api.functions.users { + static func getUsers(id: [Api.InputUser]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse<[Api.User]>) { + let buffer = Buffer() + buffer.appendInt32(227648840) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(id.count)) + for item in id { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "users.getUsers", parameters: [("id", String(describing: id))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> [Api.User]? in + let reader = BufferReader(buffer) + var result: [Api.User]? + if let _ = reader.readInt32() { + result = Api.parseVector(reader, elementSignature: 0, elementType: Api.User.self) + } + return result + }) + } +} +public extension Api.functions.users { + static func setSecureValueErrors(id: Api.InputUser, errors: [Api.SecureValueError]) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-1865902923) + id.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(errors.count)) + for item in errors { + item.serialize(buffer, true) + } + return (FunctionDescription(name: "users.setSecureValueErrors", parameters: [("id", String(describing: id)), ("errors", String(describing: errors))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Bool? in + let reader = BufferReader(buffer) + var result: Api.Bool? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Bool + } + return result + }) + } +} +public extension Api.functions.users { + static func suggestBirthday(id: Api.InputUser, birthday: Api.Birthday) -> (FunctionDescription, Buffer, DeserializeFunctionResponse) { + let buffer = Buffer() + buffer.appendInt32(-61656206) + id.serialize(buffer, true) + birthday.serialize(buffer, true) + return (FunctionDescription(name: "users.suggestBirthday", parameters: [("id", String(describing: id)), ("birthday", String(describing: birthday))]), buffer, DeserializeFunctionResponse { (buffer: Buffer) -> Api.Updates? in + let reader = BufferReader(buffer) + var result: Api.Updates? + if let signature = reader.readInt32() { + result = Api.parse(reader, signature: signature) as? Api.Updates + } + return result + }) + } +} diff --git a/submodules/TelegramApi/Sources/Api5.swift b/submodules/TelegramApi/Sources/Api5.swift index 87fba995..006fc661 100644 --- a/submodules/TelegramApi/Sources/Api5.swift +++ b/submodules/TelegramApi/Sources/Api5.swift @@ -1,29 +1,47 @@ public extension Api { enum ChatInviteImporter: TypeConstructorDescription { - case chatInviteImporter(flags: Int32, userId: Int64, date: Int32, about: String?, approvedBy: Int64?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatInviteImporter(let flags, let userId, let date, let about, let approvedBy): - if boxed { - buffer.appendInt32(-1940201511) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeString(about!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt64(approvedBy!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatInviteImporter(let flags, let userId, let date, let about, let approvedBy): - return ("chatInviteImporter", [("flags", flags as Any), ("userId", userId as Any), ("date", date as Any), ("about", about as Any), ("approvedBy", approvedBy as Any)]) - } - } - + public class Cons_chatInviteImporter { + public var flags: Int32 + public var userId: Int64 + public var date: Int32 + public var about: String? + public var approvedBy: Int64? + public init(flags: Int32, userId: Int64, date: Int32, about: String?, approvedBy: Int64?) { + self.flags = flags + self.userId = userId + self.date = date + self.about = about + self.approvedBy = approvedBy + } + } + case chatInviteImporter(Cons_chatInviteImporter) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatInviteImporter(let _data): + if boxed { + buffer.appendInt32(-1940201511) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.about!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt64(_data.approvedBy!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatInviteImporter(let _data): + return ("chatInviteImporter", [("flags", _data.flags as Any), ("userId", _data.userId as Any), ("date", _data.date as Any), ("about", _data.about as Any), ("approvedBy", _data.approvedBy as Any)]) + } + } + public static func parse_chatInviteImporter(_ reader: BufferReader) -> ChatInviteImporter? { var _1: Int32? _1 = reader.readInt32() @@ -32,100 +50,138 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: String? - if Int(_1!) & Int(1 << 2) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _4 = parseString(reader) + } var _5: Int64? - if Int(_1!) & Int(1 << 1) != 0 {_5 = reader.readInt64() } + if Int(_1!) & Int(1 << 1) != 0 { + _5 = reader.readInt64() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 1) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.ChatInviteImporter.chatInviteImporter(flags: _1!, userId: _2!, date: _3!, about: _4, approvedBy: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.ChatInviteImporter.chatInviteImporter(Cons_chatInviteImporter(flags: _1!, userId: _2!, date: _3!, about: _4, approvedBy: _5)) + } + else { + return nil + } } - } } public extension Api { enum ChatOnlines: TypeConstructorDescription { - case chatOnlines(onlines: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatOnlines(let onlines): - if boxed { - buffer.appendInt32(-264117680) - } - serializeInt32(onlines, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatOnlines(let onlines): - return ("chatOnlines", [("onlines", onlines as Any)]) - } - } - + public class Cons_chatOnlines { + public var onlines: Int32 + public init(onlines: Int32) { + self.onlines = onlines + } + } + case chatOnlines(Cons_chatOnlines) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatOnlines(let _data): + if boxed { + buffer.appendInt32(-264117680) + } + serializeInt32(_data.onlines, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatOnlines(let _data): + return ("chatOnlines", [("onlines", _data.onlines as Any)]) + } + } + public static func parse_chatOnlines(_ reader: BufferReader) -> ChatOnlines? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChatOnlines.chatOnlines(onlines: _1!) + if _c1 { + return Api.ChatOnlines.chatOnlines(Cons_chatOnlines(onlines: _1!)) + } + else { + return nil + } } - } } public extension Api { enum ChatParticipant: TypeConstructorDescription { - case chatParticipant(userId: Int64, inviterId: Int64, date: Int32) - case chatParticipantAdmin(userId: Int64, inviterId: Int64, date: Int32) - case chatParticipantCreator(userId: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatParticipant(let userId, let inviterId, let date): - if boxed { - buffer.appendInt32(-1070776313) - } - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt64(inviterId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - break - case .chatParticipantAdmin(let userId, let inviterId, let date): - if boxed { - buffer.appendInt32(-1600962725) - } - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt64(inviterId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - break - case .chatParticipantCreator(let userId): - if boxed { - buffer.appendInt32(-462696732) - } - serializeInt64(userId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatParticipant(let userId, let inviterId, let date): - return ("chatParticipant", [("userId", userId as Any), ("inviterId", inviterId as Any), ("date", date as Any)]) - case .chatParticipantAdmin(let userId, let inviterId, let date): - return ("chatParticipantAdmin", [("userId", userId as Any), ("inviterId", inviterId as Any), ("date", date as Any)]) - case .chatParticipantCreator(let userId): - return ("chatParticipantCreator", [("userId", userId as Any)]) - } - } - + public class Cons_chatParticipant { + public var userId: Int64 + public var inviterId: Int64 + public var date: Int32 + public init(userId: Int64, inviterId: Int64, date: Int32) { + self.userId = userId + self.inviterId = inviterId + self.date = date + } + } + public class Cons_chatParticipantAdmin { + public var userId: Int64 + public var inviterId: Int64 + public var date: Int32 + public init(userId: Int64, inviterId: Int64, date: Int32) { + self.userId = userId + self.inviterId = inviterId + self.date = date + } + } + public class Cons_chatParticipantCreator { + public var userId: Int64 + public init(userId: Int64) { + self.userId = userId + } + } + case chatParticipant(Cons_chatParticipant) + case chatParticipantAdmin(Cons_chatParticipantAdmin) + case chatParticipantCreator(Cons_chatParticipantCreator) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatParticipant(let _data): + if boxed { + buffer.appendInt32(-1070776313) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt64(_data.inviterId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + case .chatParticipantAdmin(let _data): + if boxed { + buffer.appendInt32(-1600962725) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt64(_data.inviterId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + break + case .chatParticipantCreator(let _data): + if boxed { + buffer.appendInt32(-462696732) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatParticipant(let _data): + return ("chatParticipant", [("userId", _data.userId as Any), ("inviterId", _data.inviterId as Any), ("date", _data.date as Any)]) + case .chatParticipantAdmin(let _data): + return ("chatParticipantAdmin", [("userId", _data.userId as Any), ("inviterId", _data.inviterId as Any), ("date", _data.date as Any)]) + case .chatParticipantCreator(let _data): + return ("chatParticipantCreator", [("userId", _data.userId as Any)]) + } + } + public static func parse_chatParticipant(_ reader: BufferReader) -> ChatParticipant? { var _1: Int64? _1 = reader.readInt64() @@ -136,10 +192,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.ChatParticipant.chatParticipant(userId: _1!, inviterId: _2!, date: _3!) + if _c1 && _c2 && _c3 { + return Api.ChatParticipant.chatParticipant(Cons_chatParticipant(userId: _1!, inviterId: _2!, date: _3!)) + } + else { + return nil + } } public static func parse_chatParticipantAdmin(_ reader: BufferReader) -> ChatParticipant? { var _1: Int64? @@ -151,60 +209,87 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.ChatParticipant.chatParticipantAdmin(userId: _1!, inviterId: _2!, date: _3!) + if _c1 && _c2 && _c3 { + return Api.ChatParticipant.chatParticipantAdmin(Cons_chatParticipantAdmin(userId: _1!, inviterId: _2!, date: _3!)) + } + else { + return nil + } } public static func parse_chatParticipantCreator(_ reader: BufferReader) -> ChatParticipant? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChatParticipant.chatParticipantCreator(userId: _1!) + if _c1 { + return Api.ChatParticipant.chatParticipantCreator(Cons_chatParticipantCreator(userId: _1!)) + } + else { + return nil + } } - } } public extension Api { enum ChatParticipants: TypeConstructorDescription { - case chatParticipants(chatId: Int64, participants: [Api.ChatParticipant], version: Int32) - case chatParticipantsForbidden(flags: Int32, chatId: Int64, selfParticipant: Api.ChatParticipant?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatParticipants(let chatId, let participants, let version): - if boxed { - buffer.appendInt32(1018991608) - } - serializeInt64(chatId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(participants.count)) - for item in participants { - item.serialize(buffer, true) - } - serializeInt32(version, buffer: buffer, boxed: false) - break - case .chatParticipantsForbidden(let flags, let chatId, let selfParticipant): - if boxed { - buffer.appendInt32(-2023500831) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(chatId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {selfParticipant!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatParticipants(let chatId, let participants, let version): - return ("chatParticipants", [("chatId", chatId as Any), ("participants", participants as Any), ("version", version as Any)]) - case .chatParticipantsForbidden(let flags, let chatId, let selfParticipant): - return ("chatParticipantsForbidden", [("flags", flags as Any), ("chatId", chatId as Any), ("selfParticipant", selfParticipant as Any)]) - } - } - + public class Cons_chatParticipants { + public var chatId: Int64 + public var participants: [Api.ChatParticipant] + public var version: Int32 + public init(chatId: Int64, participants: [Api.ChatParticipant], version: Int32) { + self.chatId = chatId + self.participants = participants + self.version = version + } + } + public class Cons_chatParticipantsForbidden { + public var flags: Int32 + public var chatId: Int64 + public var selfParticipant: Api.ChatParticipant? + public init(flags: Int32, chatId: Int64, selfParticipant: Api.ChatParticipant?) { + self.flags = flags + self.chatId = chatId + self.selfParticipant = selfParticipant + } + } + case chatParticipants(Cons_chatParticipants) + case chatParticipantsForbidden(Cons_chatParticipantsForbidden) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatParticipants(let _data): + if boxed { + buffer.appendInt32(1018991608) + } + serializeInt64(_data.chatId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.participants.count)) + for item in _data.participants { + item.serialize(buffer, true) + } + serializeInt32(_data.version, buffer: buffer, boxed: false) + break + case .chatParticipantsForbidden(let _data): + if boxed { + buffer.appendInt32(-2023500831) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.chatId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.selfParticipant!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatParticipants(let _data): + return ("chatParticipants", [("chatId", _data.chatId as Any), ("participants", _data.participants as Any), ("version", _data.version as Any)]) + case .chatParticipantsForbidden(let _data): + return ("chatParticipantsForbidden", [("flags", _data.flags as Any), ("chatId", _data.chatId as Any), ("selfParticipant", _data.selfParticipant as Any)]) + } + } + public static func parse_chatParticipants(_ reader: BufferReader) -> ChatParticipants? { var _1: Int64? _1 = reader.readInt64() @@ -217,10 +302,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.ChatParticipants.chatParticipants(chatId: _1!, participants: _2!, version: _3!) + if _c1 && _c2 && _c3 { + return Api.ChatParticipants.chatParticipants(Cons_chatParticipants(chatId: _1!, participants: _2!, version: _3!)) + } + else { + return nil + } } public static func parse_chatParticipantsForbidden(_ reader: BufferReader) -> ChatParticipants? { var _1: Int32? @@ -228,129 +315,162 @@ public extension Api { var _2: Int64? _2 = reader.readInt64() var _3: Api.ChatParticipant? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.ChatParticipant - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.ChatParticipant + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.ChatParticipants.chatParticipantsForbidden(flags: _1!, chatId: _2!, selfParticipant: _3) + if _c1 && _c2 && _c3 { + return Api.ChatParticipants.chatParticipantsForbidden(Cons_chatParticipantsForbidden(flags: _1!, chatId: _2!, selfParticipant: _3)) + } + else { + return nil + } } - } } public extension Api { enum ChatPhoto: TypeConstructorDescription { - case chatPhoto(flags: Int32, photoId: Int64, strippedThumb: Buffer?, dcId: Int32) + public class Cons_chatPhoto { + public var flags: Int32 + public var photoId: Int64 + public var strippedThumb: Buffer? + public var dcId: Int32 + public init(flags: Int32, photoId: Int64, strippedThumb: Buffer?, dcId: Int32) { + self.flags = flags + self.photoId = photoId + self.strippedThumb = strippedThumb + self.dcId = dcId + } + } + case chatPhoto(Cons_chatPhoto) case chatPhotoEmpty - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatPhoto(let flags, let photoId, let strippedThumb, let dcId): - if boxed { - buffer.appendInt32(476978193) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(photoId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeBytes(strippedThumb!, buffer: buffer, boxed: false)} - serializeInt32(dcId, buffer: buffer, boxed: false) - break - case .chatPhotoEmpty: - if boxed { - buffer.appendInt32(935395612) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatPhoto(let flags, let photoId, let strippedThumb, let dcId): - return ("chatPhoto", [("flags", flags as Any), ("photoId", photoId as Any), ("strippedThumb", strippedThumb as Any), ("dcId", dcId as Any)]) - case .chatPhotoEmpty: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatPhoto(let _data): + if boxed { + buffer.appendInt32(476978193) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.photoId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeBytes(_data.strippedThumb!, buffer: buffer, boxed: false) + } + serializeInt32(_data.dcId, buffer: buffer, boxed: false) + break + case .chatPhotoEmpty: + if boxed { + buffer.appendInt32(935395612) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatPhoto(let _data): + return ("chatPhoto", [("flags", _data.flags as Any), ("photoId", _data.photoId as Any), ("strippedThumb", _data.strippedThumb as Any), ("dcId", _data.dcId as Any)]) + case .chatPhotoEmpty: return ("chatPhotoEmpty", []) - } - } - + } + } + public static func parse_chatPhoto(_ reader: BufferReader) -> ChatPhoto? { var _1: Int32? _1 = reader.readInt32() var _2: Int64? _2 = reader.readInt64() var _3: Buffer? - if Int(_1!) & Int(1 << 1) != 0 {_3 = parseBytes(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _3 = parseBytes(reader) + } var _4: Int32? _4 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.ChatPhoto.chatPhoto(flags: _1!, photoId: _2!, strippedThumb: _3, dcId: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.ChatPhoto.chatPhoto(Cons_chatPhoto(flags: _1!, photoId: _2!, strippedThumb: _3, dcId: _4!)) + } + else { + return nil + } } public static func parse_chatPhotoEmpty(_ reader: BufferReader) -> ChatPhoto? { return Api.ChatPhoto.chatPhotoEmpty } - } } public extension Api { enum ChatReactions: TypeConstructorDescription { - case chatReactionsAll(flags: Int32) + public class Cons_chatReactionsAll { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } + public class Cons_chatReactionsSome { + public var reactions: [Api.Reaction] + public init(reactions: [Api.Reaction]) { + self.reactions = reactions + } + } + case chatReactionsAll(Cons_chatReactionsAll) case chatReactionsNone - case chatReactionsSome(reactions: [Api.Reaction]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatReactionsAll(let flags): - if boxed { - buffer.appendInt32(1385335754) - } - serializeInt32(flags, buffer: buffer, boxed: false) - break - case .chatReactionsNone: - if boxed { - buffer.appendInt32(-352570692) - } - - break - case .chatReactionsSome(let reactions): - if boxed { - buffer.appendInt32(1713193015) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(reactions.count)) - for item in reactions { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatReactionsAll(let flags): - return ("chatReactionsAll", [("flags", flags as Any)]) - case .chatReactionsNone: + case chatReactionsSome(Cons_chatReactionsSome) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatReactionsAll(let _data): + if boxed { + buffer.appendInt32(1385335754) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + case .chatReactionsNone: + if boxed { + buffer.appendInt32(-352570692) + } + break + case .chatReactionsSome(let _data): + if boxed { + buffer.appendInt32(1713193015) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.reactions.count)) + for item in _data.reactions { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatReactionsAll(let _data): + return ("chatReactionsAll", [("flags", _data.flags as Any)]) + case .chatReactionsNone: return ("chatReactionsNone", []) - case .chatReactionsSome(let reactions): - return ("chatReactionsSome", [("reactions", reactions as Any)]) - } - } - + case .chatReactionsSome(let _data): + return ("chatReactionsSome", [("reactions", _data.reactions as Any)]) + } + } + public static func parse_chatReactionsAll(_ reader: BufferReader) -> ChatReactions? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChatReactions.chatReactionsAll(flags: _1!) + if _c1 { + return Api.ChatReactions.chatReactionsAll(Cons_chatReactionsAll(flags: _1!)) + } + else { + return nil + } } public static func parse_chatReactionsNone(_ reader: BufferReader) -> ChatReactions? { return Api.ChatReactions.chatReactionsNone @@ -361,54 +481,75 @@ public extension Api { _1 = Api.parseVector(reader, elementSignature: 0, elementType: Api.Reaction.self) } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChatReactions.chatReactionsSome(reactions: _1!) + if _c1 { + return Api.ChatReactions.chatReactionsSome(Cons_chatReactionsSome(reactions: _1!)) + } + else { + return nil + } } - } } public extension Api { enum ChatTheme: TypeConstructorDescription { - case chatTheme(emoticon: String) - case chatThemeUniqueGift(gift: Api.StarGift, themeSettings: [Api.ThemeSettings]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatTheme(let emoticon): - if boxed { - buffer.appendInt32(-1008731132) - } - serializeString(emoticon, buffer: buffer, boxed: false) - break - case .chatThemeUniqueGift(let gift, let themeSettings): - if boxed { - buffer.appendInt32(878246344) - } - gift.serialize(buffer, true) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(themeSettings.count)) - for item in themeSettings { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatTheme(let emoticon): - return ("chatTheme", [("emoticon", emoticon as Any)]) - case .chatThemeUniqueGift(let gift, let themeSettings): - return ("chatThemeUniqueGift", [("gift", gift as Any), ("themeSettings", themeSettings as Any)]) - } - } - + public class Cons_chatTheme { + public var emoticon: String + public init(emoticon: String) { + self.emoticon = emoticon + } + } + public class Cons_chatThemeUniqueGift { + public var gift: Api.StarGift + public var themeSettings: [Api.ThemeSettings] + public init(gift: Api.StarGift, themeSettings: [Api.ThemeSettings]) { + self.gift = gift + self.themeSettings = themeSettings + } + } + case chatTheme(Cons_chatTheme) + case chatThemeUniqueGift(Cons_chatThemeUniqueGift) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatTheme(let _data): + if boxed { + buffer.appendInt32(-1008731132) + } + serializeString(_data.emoticon, buffer: buffer, boxed: false) + break + case .chatThemeUniqueGift(let _data): + if boxed { + buffer.appendInt32(878246344) + } + _data.gift.serialize(buffer, true) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.themeSettings.count)) + for item in _data.themeSettings { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatTheme(let _data): + return ("chatTheme", [("emoticon", _data.emoticon as Any)]) + case .chatThemeUniqueGift(let _data): + return ("chatThemeUniqueGift", [("gift", _data.gift as Any), ("themeSettings", _data.themeSettings as Any)]) + } + } + public static func parse_chatTheme(_ reader: BufferReader) -> ChatTheme? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ChatTheme.chatTheme(emoticon: _1!) + if _c1 { + return Api.ChatTheme.chatTheme(Cons_chatTheme(emoticon: _1!)) + } + else { + return nil + } } public static func parse_chatThemeUniqueGift(_ reader: BufferReader) -> ChatTheme? { var _1: Api.StarGift? @@ -421,136 +562,274 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ChatTheme.chatThemeUniqueGift(gift: _1!, themeSettings: _2!) + if _c1 && _c2 { + return Api.ChatTheme.chatThemeUniqueGift(Cons_chatThemeUniqueGift(gift: _1!, themeSettings: _2!)) + } + else { + return nil + } } - } } public extension Api { enum CodeSettings: TypeConstructorDescription { - case codeSettings(flags: Int32, logoutTokens: [Buffer]?, token: String?, appSandbox: Api.Bool?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .codeSettings(let flags, let logoutTokens, let token, let appSandbox): - if boxed { - buffer.appendInt32(-1390068360) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 6) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(logoutTokens!.count)) - for item in logoutTokens! { + public class Cons_codeSettings { + public var flags: Int32 + public var logoutTokens: [Buffer]? + public var token: String? + public var appSandbox: Api.Bool? + public init(flags: Int32, logoutTokens: [Buffer]?, token: String?, appSandbox: Api.Bool?) { + self.flags = flags + self.logoutTokens = logoutTokens + self.token = token + self.appSandbox = appSandbox + } + } + case codeSettings(Cons_codeSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .codeSettings(let _data): + if boxed { + buffer.appendInt32(-1390068360) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 6) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.logoutTokens!.count)) + for item in _data.logoutTokens! { serializeBytes(item, buffer: buffer, boxed: false) - }} - if Int(flags) & Int(1 << 8) != 0 {serializeString(token!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {appSandbox!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .codeSettings(let flags, let logoutTokens, let token, let appSandbox): - return ("codeSettings", [("flags", flags as Any), ("logoutTokens", logoutTokens as Any), ("token", token as Any), ("appSandbox", appSandbox as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 8) != 0 { + serializeString(_data.token!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + _data.appSandbox!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .codeSettings(let _data): + return ("codeSettings", [("flags", _data.flags as Any), ("logoutTokens", _data.logoutTokens as Any), ("token", _data.token as Any), ("appSandbox", _data.appSandbox as Any)]) + } + } + public static func parse_codeSettings(_ reader: BufferReader) -> CodeSettings? { var _1: Int32? _1 = reader.readInt32() var _2: [Buffer]? - if Int(_1!) & Int(1 << 6) != 0 {if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: -1255641564, elementType: Buffer.self) - } } + if Int(_1!) & Int(1 << 6) != 0 { + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: -1255641564, elementType: Buffer.self) + } + } var _3: String? - if Int(_1!) & Int(1 << 8) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 8) != 0 { + _3 = parseString(reader) + } var _4: Api.Bool? - if Int(_1!) & Int(1 << 8) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.Bool - } } + if Int(_1!) & Int(1 << 8) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.Bool + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 6) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 8) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 8) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.CodeSettings.codeSettings(flags: _1!, logoutTokens: _2, token: _3, appSandbox: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.CodeSettings.codeSettings(Cons_codeSettings(flags: _1!, logoutTokens: _2, token: _3, appSandbox: _4)) + } + else { + return nil + } } - } } public extension Api { enum Config: TypeConstructorDescription { - case config(flags: Int32, date: Int32, expires: Int32, testMode: Api.Bool, thisDc: Int32, dcOptions: [Api.DcOption], dcTxtDomainName: String, chatSizeMax: Int32, megagroupSizeMax: Int32, forwardedCountMax: Int32, onlineUpdatePeriodMs: Int32, offlineBlurTimeoutMs: Int32, offlineIdleTimeoutMs: Int32, onlineCloudTimeoutMs: Int32, notifyCloudDelayMs: Int32, notifyDefaultDelayMs: Int32, pushChatPeriodMs: Int32, pushChatLimit: Int32, editTimeLimit: Int32, revokeTimeLimit: Int32, revokePmTimeLimit: Int32, ratingEDecay: Int32, stickersRecentLimit: Int32, channelsReadMediaPeriod: Int32, tmpSessions: Int32?, callReceiveTimeoutMs: Int32, callRingTimeoutMs: Int32, callConnectTimeoutMs: Int32, callPacketTimeoutMs: Int32, meUrlPrefix: String, autoupdateUrlPrefix: String?, gifSearchUsername: String?, venueSearchUsername: String?, imgSearchUsername: String?, staticMapsProvider: String?, captionLengthMax: Int32, messageLengthMax: Int32, webfileDcId: Int32, suggestedLangCode: String?, langPackVersion: Int32?, baseLangPackVersion: Int32?, reactionsDefault: Api.Reaction?, autologinToken: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .config(let flags, let date, let expires, let testMode, let thisDc, let dcOptions, let dcTxtDomainName, let chatSizeMax, let megagroupSizeMax, let forwardedCountMax, let onlineUpdatePeriodMs, let offlineBlurTimeoutMs, let offlineIdleTimeoutMs, let onlineCloudTimeoutMs, let notifyCloudDelayMs, let notifyDefaultDelayMs, let pushChatPeriodMs, let pushChatLimit, let editTimeLimit, let revokeTimeLimit, let revokePmTimeLimit, let ratingEDecay, let stickersRecentLimit, let channelsReadMediaPeriod, let tmpSessions, let callReceiveTimeoutMs, let callRingTimeoutMs, let callConnectTimeoutMs, let callPacketTimeoutMs, let meUrlPrefix, let autoupdateUrlPrefix, let gifSearchUsername, let venueSearchUsername, let imgSearchUsername, let staticMapsProvider, let captionLengthMax, let messageLengthMax, let webfileDcId, let suggestedLangCode, let langPackVersion, let baseLangPackVersion, let reactionsDefault, let autologinToken): - if boxed { - buffer.appendInt32(-870702050) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt32(expires, buffer: buffer, boxed: false) - testMode.serialize(buffer, true) - serializeInt32(thisDc, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(dcOptions.count)) - for item in dcOptions { - item.serialize(buffer, true) - } - serializeString(dcTxtDomainName, buffer: buffer, boxed: false) - serializeInt32(chatSizeMax, buffer: buffer, boxed: false) - serializeInt32(megagroupSizeMax, buffer: buffer, boxed: false) - serializeInt32(forwardedCountMax, buffer: buffer, boxed: false) - serializeInt32(onlineUpdatePeriodMs, buffer: buffer, boxed: false) - serializeInt32(offlineBlurTimeoutMs, buffer: buffer, boxed: false) - serializeInt32(offlineIdleTimeoutMs, buffer: buffer, boxed: false) - serializeInt32(onlineCloudTimeoutMs, buffer: buffer, boxed: false) - serializeInt32(notifyCloudDelayMs, buffer: buffer, boxed: false) - serializeInt32(notifyDefaultDelayMs, buffer: buffer, boxed: false) - serializeInt32(pushChatPeriodMs, buffer: buffer, boxed: false) - serializeInt32(pushChatLimit, buffer: buffer, boxed: false) - serializeInt32(editTimeLimit, buffer: buffer, boxed: false) - serializeInt32(revokeTimeLimit, buffer: buffer, boxed: false) - serializeInt32(revokePmTimeLimit, buffer: buffer, boxed: false) - serializeInt32(ratingEDecay, buffer: buffer, boxed: false) - serializeInt32(stickersRecentLimit, buffer: buffer, boxed: false) - serializeInt32(channelsReadMediaPeriod, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(tmpSessions!, buffer: buffer, boxed: false)} - serializeInt32(callReceiveTimeoutMs, buffer: buffer, boxed: false) - serializeInt32(callRingTimeoutMs, buffer: buffer, boxed: false) - serializeInt32(callConnectTimeoutMs, buffer: buffer, boxed: false) - serializeInt32(callPacketTimeoutMs, buffer: buffer, boxed: false) - serializeString(meUrlPrefix, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 7) != 0 {serializeString(autoupdateUrlPrefix!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 9) != 0 {serializeString(gifSearchUsername!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 10) != 0 {serializeString(venueSearchUsername!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 11) != 0 {serializeString(imgSearchUsername!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 12) != 0 {serializeString(staticMapsProvider!, buffer: buffer, boxed: false)} - serializeInt32(captionLengthMax, buffer: buffer, boxed: false) - serializeInt32(messageLengthMax, buffer: buffer, boxed: false) - serializeInt32(webfileDcId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeString(suggestedLangCode!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(langPackVersion!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(baseLangPackVersion!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 15) != 0 {reactionsDefault!.serialize(buffer, true)} - if Int(flags) & Int(1 << 16) != 0 {serializeString(autologinToken!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .config(let flags, let date, let expires, let testMode, let thisDc, let dcOptions, let dcTxtDomainName, let chatSizeMax, let megagroupSizeMax, let forwardedCountMax, let onlineUpdatePeriodMs, let offlineBlurTimeoutMs, let offlineIdleTimeoutMs, let onlineCloudTimeoutMs, let notifyCloudDelayMs, let notifyDefaultDelayMs, let pushChatPeriodMs, let pushChatLimit, let editTimeLimit, let revokeTimeLimit, let revokePmTimeLimit, let ratingEDecay, let stickersRecentLimit, let channelsReadMediaPeriod, let tmpSessions, let callReceiveTimeoutMs, let callRingTimeoutMs, let callConnectTimeoutMs, let callPacketTimeoutMs, let meUrlPrefix, let autoupdateUrlPrefix, let gifSearchUsername, let venueSearchUsername, let imgSearchUsername, let staticMapsProvider, let captionLengthMax, let messageLengthMax, let webfileDcId, let suggestedLangCode, let langPackVersion, let baseLangPackVersion, let reactionsDefault, let autologinToken): - return ("config", [("flags", flags as Any), ("date", date as Any), ("expires", expires as Any), ("testMode", testMode as Any), ("thisDc", thisDc as Any), ("dcOptions", dcOptions as Any), ("dcTxtDomainName", dcTxtDomainName as Any), ("chatSizeMax", chatSizeMax as Any), ("megagroupSizeMax", megagroupSizeMax as Any), ("forwardedCountMax", forwardedCountMax as Any), ("onlineUpdatePeriodMs", onlineUpdatePeriodMs as Any), ("offlineBlurTimeoutMs", offlineBlurTimeoutMs as Any), ("offlineIdleTimeoutMs", offlineIdleTimeoutMs as Any), ("onlineCloudTimeoutMs", onlineCloudTimeoutMs as Any), ("notifyCloudDelayMs", notifyCloudDelayMs as Any), ("notifyDefaultDelayMs", notifyDefaultDelayMs as Any), ("pushChatPeriodMs", pushChatPeriodMs as Any), ("pushChatLimit", pushChatLimit as Any), ("editTimeLimit", editTimeLimit as Any), ("revokeTimeLimit", revokeTimeLimit as Any), ("revokePmTimeLimit", revokePmTimeLimit as Any), ("ratingEDecay", ratingEDecay as Any), ("stickersRecentLimit", stickersRecentLimit as Any), ("channelsReadMediaPeriod", channelsReadMediaPeriod as Any), ("tmpSessions", tmpSessions as Any), ("callReceiveTimeoutMs", callReceiveTimeoutMs as Any), ("callRingTimeoutMs", callRingTimeoutMs as Any), ("callConnectTimeoutMs", callConnectTimeoutMs as Any), ("callPacketTimeoutMs", callPacketTimeoutMs as Any), ("meUrlPrefix", meUrlPrefix as Any), ("autoupdateUrlPrefix", autoupdateUrlPrefix as Any), ("gifSearchUsername", gifSearchUsername as Any), ("venueSearchUsername", venueSearchUsername as Any), ("imgSearchUsername", imgSearchUsername as Any), ("staticMapsProvider", staticMapsProvider as Any), ("captionLengthMax", captionLengthMax as Any), ("messageLengthMax", messageLengthMax as Any), ("webfileDcId", webfileDcId as Any), ("suggestedLangCode", suggestedLangCode as Any), ("langPackVersion", langPackVersion as Any), ("baseLangPackVersion", baseLangPackVersion as Any), ("reactionsDefault", reactionsDefault as Any), ("autologinToken", autologinToken as Any)]) - } - } - + public class Cons_config { + public var flags: Int32 + public var date: Int32 + public var expires: Int32 + public var testMode: Api.Bool + public var thisDc: Int32 + public var dcOptions: [Api.DcOption] + public var dcTxtDomainName: String + public var chatSizeMax: Int32 + public var megagroupSizeMax: Int32 + public var forwardedCountMax: Int32 + public var onlineUpdatePeriodMs: Int32 + public var offlineBlurTimeoutMs: Int32 + public var offlineIdleTimeoutMs: Int32 + public var onlineCloudTimeoutMs: Int32 + public var notifyCloudDelayMs: Int32 + public var notifyDefaultDelayMs: Int32 + public var pushChatPeriodMs: Int32 + public var pushChatLimit: Int32 + public var editTimeLimit: Int32 + public var revokeTimeLimit: Int32 + public var revokePmTimeLimit: Int32 + public var ratingEDecay: Int32 + public var stickersRecentLimit: Int32 + public var channelsReadMediaPeriod: Int32 + public var tmpSessions: Int32? + public var callReceiveTimeoutMs: Int32 + public var callRingTimeoutMs: Int32 + public var callConnectTimeoutMs: Int32 + public var callPacketTimeoutMs: Int32 + public var meUrlPrefix: String + public var autoupdateUrlPrefix: String? + public var gifSearchUsername: String? + public var venueSearchUsername: String? + public var imgSearchUsername: String? + public var staticMapsProvider: String? + public var captionLengthMax: Int32 + public var messageLengthMax: Int32 + public var webfileDcId: Int32 + public var suggestedLangCode: String? + public var langPackVersion: Int32? + public var baseLangPackVersion: Int32? + public var reactionsDefault: Api.Reaction? + public var autologinToken: String? + public init(flags: Int32, date: Int32, expires: Int32, testMode: Api.Bool, thisDc: Int32, dcOptions: [Api.DcOption], dcTxtDomainName: String, chatSizeMax: Int32, megagroupSizeMax: Int32, forwardedCountMax: Int32, onlineUpdatePeriodMs: Int32, offlineBlurTimeoutMs: Int32, offlineIdleTimeoutMs: Int32, onlineCloudTimeoutMs: Int32, notifyCloudDelayMs: Int32, notifyDefaultDelayMs: Int32, pushChatPeriodMs: Int32, pushChatLimit: Int32, editTimeLimit: Int32, revokeTimeLimit: Int32, revokePmTimeLimit: Int32, ratingEDecay: Int32, stickersRecentLimit: Int32, channelsReadMediaPeriod: Int32, tmpSessions: Int32?, callReceiveTimeoutMs: Int32, callRingTimeoutMs: Int32, callConnectTimeoutMs: Int32, callPacketTimeoutMs: Int32, meUrlPrefix: String, autoupdateUrlPrefix: String?, gifSearchUsername: String?, venueSearchUsername: String?, imgSearchUsername: String?, staticMapsProvider: String?, captionLengthMax: Int32, messageLengthMax: Int32, webfileDcId: Int32, suggestedLangCode: String?, langPackVersion: Int32?, baseLangPackVersion: Int32?, reactionsDefault: Api.Reaction?, autologinToken: String?) { + self.flags = flags + self.date = date + self.expires = expires + self.testMode = testMode + self.thisDc = thisDc + self.dcOptions = dcOptions + self.dcTxtDomainName = dcTxtDomainName + self.chatSizeMax = chatSizeMax + self.megagroupSizeMax = megagroupSizeMax + self.forwardedCountMax = forwardedCountMax + self.onlineUpdatePeriodMs = onlineUpdatePeriodMs + self.offlineBlurTimeoutMs = offlineBlurTimeoutMs + self.offlineIdleTimeoutMs = offlineIdleTimeoutMs + self.onlineCloudTimeoutMs = onlineCloudTimeoutMs + self.notifyCloudDelayMs = notifyCloudDelayMs + self.notifyDefaultDelayMs = notifyDefaultDelayMs + self.pushChatPeriodMs = pushChatPeriodMs + self.pushChatLimit = pushChatLimit + self.editTimeLimit = editTimeLimit + self.revokeTimeLimit = revokeTimeLimit + self.revokePmTimeLimit = revokePmTimeLimit + self.ratingEDecay = ratingEDecay + self.stickersRecentLimit = stickersRecentLimit + self.channelsReadMediaPeriod = channelsReadMediaPeriod + self.tmpSessions = tmpSessions + self.callReceiveTimeoutMs = callReceiveTimeoutMs + self.callRingTimeoutMs = callRingTimeoutMs + self.callConnectTimeoutMs = callConnectTimeoutMs + self.callPacketTimeoutMs = callPacketTimeoutMs + self.meUrlPrefix = meUrlPrefix + self.autoupdateUrlPrefix = autoupdateUrlPrefix + self.gifSearchUsername = gifSearchUsername + self.venueSearchUsername = venueSearchUsername + self.imgSearchUsername = imgSearchUsername + self.staticMapsProvider = staticMapsProvider + self.captionLengthMax = captionLengthMax + self.messageLengthMax = messageLengthMax + self.webfileDcId = webfileDcId + self.suggestedLangCode = suggestedLangCode + self.langPackVersion = langPackVersion + self.baseLangPackVersion = baseLangPackVersion + self.reactionsDefault = reactionsDefault + self.autologinToken = autologinToken + } + } + case config(Cons_config) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .config(let _data): + if boxed { + buffer.appendInt32(-870702050) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt32(_data.expires, buffer: buffer, boxed: false) + _data.testMode.serialize(buffer, true) + serializeInt32(_data.thisDc, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.dcOptions.count)) + for item in _data.dcOptions { + item.serialize(buffer, true) + } + serializeString(_data.dcTxtDomainName, buffer: buffer, boxed: false) + serializeInt32(_data.chatSizeMax, buffer: buffer, boxed: false) + serializeInt32(_data.megagroupSizeMax, buffer: buffer, boxed: false) + serializeInt32(_data.forwardedCountMax, buffer: buffer, boxed: false) + serializeInt32(_data.onlineUpdatePeriodMs, buffer: buffer, boxed: false) + serializeInt32(_data.offlineBlurTimeoutMs, buffer: buffer, boxed: false) + serializeInt32(_data.offlineIdleTimeoutMs, buffer: buffer, boxed: false) + serializeInt32(_data.onlineCloudTimeoutMs, buffer: buffer, boxed: false) + serializeInt32(_data.notifyCloudDelayMs, buffer: buffer, boxed: false) + serializeInt32(_data.notifyDefaultDelayMs, buffer: buffer, boxed: false) + serializeInt32(_data.pushChatPeriodMs, buffer: buffer, boxed: false) + serializeInt32(_data.pushChatLimit, buffer: buffer, boxed: false) + serializeInt32(_data.editTimeLimit, buffer: buffer, boxed: false) + serializeInt32(_data.revokeTimeLimit, buffer: buffer, boxed: false) + serializeInt32(_data.revokePmTimeLimit, buffer: buffer, boxed: false) + serializeInt32(_data.ratingEDecay, buffer: buffer, boxed: false) + serializeInt32(_data.stickersRecentLimit, buffer: buffer, boxed: false) + serializeInt32(_data.channelsReadMediaPeriod, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.tmpSessions!, buffer: buffer, boxed: false) + } + serializeInt32(_data.callReceiveTimeoutMs, buffer: buffer, boxed: false) + serializeInt32(_data.callRingTimeoutMs, buffer: buffer, boxed: false) + serializeInt32(_data.callConnectTimeoutMs, buffer: buffer, boxed: false) + serializeInt32(_data.callPacketTimeoutMs, buffer: buffer, boxed: false) + serializeString(_data.meUrlPrefix, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 7) != 0 { + serializeString(_data.autoupdateUrlPrefix!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 9) != 0 { + serializeString(_data.gifSearchUsername!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 10) != 0 { + serializeString(_data.venueSearchUsername!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 11) != 0 { + serializeString(_data.imgSearchUsername!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 12) != 0 { + serializeString(_data.staticMapsProvider!, buffer: buffer, boxed: false) + } + serializeInt32(_data.captionLengthMax, buffer: buffer, boxed: false) + serializeInt32(_data.messageLengthMax, buffer: buffer, boxed: false) + serializeInt32(_data.webfileDcId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.suggestedLangCode!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.langPackVersion!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.baseLangPackVersion!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 15) != 0 { + _data.reactionsDefault!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 16) != 0 { + serializeString(_data.autologinToken!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .config(let _data): + return ("config", [("flags", _data.flags as Any), ("date", _data.date as Any), ("expires", _data.expires as Any), ("testMode", _data.testMode as Any), ("thisDc", _data.thisDc as Any), ("dcOptions", _data.dcOptions as Any), ("dcTxtDomainName", _data.dcTxtDomainName as Any), ("chatSizeMax", _data.chatSizeMax as Any), ("megagroupSizeMax", _data.megagroupSizeMax as Any), ("forwardedCountMax", _data.forwardedCountMax as Any), ("onlineUpdatePeriodMs", _data.onlineUpdatePeriodMs as Any), ("offlineBlurTimeoutMs", _data.offlineBlurTimeoutMs as Any), ("offlineIdleTimeoutMs", _data.offlineIdleTimeoutMs as Any), ("onlineCloudTimeoutMs", _data.onlineCloudTimeoutMs as Any), ("notifyCloudDelayMs", _data.notifyCloudDelayMs as Any), ("notifyDefaultDelayMs", _data.notifyDefaultDelayMs as Any), ("pushChatPeriodMs", _data.pushChatPeriodMs as Any), ("pushChatLimit", _data.pushChatLimit as Any), ("editTimeLimit", _data.editTimeLimit as Any), ("revokeTimeLimit", _data.revokeTimeLimit as Any), ("revokePmTimeLimit", _data.revokePmTimeLimit as Any), ("ratingEDecay", _data.ratingEDecay as Any), ("stickersRecentLimit", _data.stickersRecentLimit as Any), ("channelsReadMediaPeriod", _data.channelsReadMediaPeriod as Any), ("tmpSessions", _data.tmpSessions as Any), ("callReceiveTimeoutMs", _data.callReceiveTimeoutMs as Any), ("callRingTimeoutMs", _data.callRingTimeoutMs as Any), ("callConnectTimeoutMs", _data.callConnectTimeoutMs as Any), ("callPacketTimeoutMs", _data.callPacketTimeoutMs as Any), ("meUrlPrefix", _data.meUrlPrefix as Any), ("autoupdateUrlPrefix", _data.autoupdateUrlPrefix as Any), ("gifSearchUsername", _data.gifSearchUsername as Any), ("venueSearchUsername", _data.venueSearchUsername as Any), ("imgSearchUsername", _data.imgSearchUsername as Any), ("staticMapsProvider", _data.staticMapsProvider as Any), ("captionLengthMax", _data.captionLengthMax as Any), ("messageLengthMax", _data.messageLengthMax as Any), ("webfileDcId", _data.webfileDcId as Any), ("suggestedLangCode", _data.suggestedLangCode as Any), ("langPackVersion", _data.langPackVersion as Any), ("baseLangPackVersion", _data.baseLangPackVersion as Any), ("reactionsDefault", _data.reactionsDefault as Any), ("autologinToken", _data.autologinToken as Any)]) + } + } + public static func parse_config(_ reader: BufferReader) -> Config? { var _1: Int32? _1 = reader.readInt32() @@ -605,7 +884,9 @@ public extension Api { var _24: Int32? _24 = reader.readInt32() var _25: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_25 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _25 = reader.readInt32() + } var _26: Int32? _26 = reader.readInt32() var _27: Int32? @@ -617,15 +898,25 @@ public extension Api { var _30: String? _30 = parseString(reader) var _31: String? - if Int(_1!) & Int(1 << 7) != 0 {_31 = parseString(reader) } + if Int(_1!) & Int(1 << 7) != 0 { + _31 = parseString(reader) + } var _32: String? - if Int(_1!) & Int(1 << 9) != 0 {_32 = parseString(reader) } + if Int(_1!) & Int(1 << 9) != 0 { + _32 = parseString(reader) + } var _33: String? - if Int(_1!) & Int(1 << 10) != 0 {_33 = parseString(reader) } + if Int(_1!) & Int(1 << 10) != 0 { + _33 = parseString(reader) + } var _34: String? - if Int(_1!) & Int(1 << 11) != 0 {_34 = parseString(reader) } + if Int(_1!) & Int(1 << 11) != 0 { + _34 = parseString(reader) + } var _35: String? - if Int(_1!) & Int(1 << 12) != 0 {_35 = parseString(reader) } + if Int(_1!) & Int(1 << 12) != 0 { + _35 = parseString(reader) + } var _36: Int32? _36 = reader.readInt32() var _37: Int32? @@ -633,17 +924,27 @@ public extension Api { var _38: Int32? _38 = reader.readInt32() var _39: String? - if Int(_1!) & Int(1 << 2) != 0 {_39 = parseString(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _39 = parseString(reader) + } var _40: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_40 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _40 = reader.readInt32() + } var _41: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_41 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _41 = reader.readInt32() + } var _42: Api.Reaction? - if Int(_1!) & Int(1 << 15) != 0 {if let signature = reader.readInt32() { - _42 = Api.parse(reader, signature: signature) as? Api.Reaction - } } + if Int(_1!) & Int(1 << 15) != 0 { + if let signature = reader.readInt32() { + _42 = Api.parse(reader, signature: signature) as? Api.Reaction + } + } var _43: String? - if Int(_1!) & Int(1 << 16) != 0 {_43 = parseString(reader) } + if Int(_1!) & Int(1 << 16) != 0 { + _43 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -687,79 +988,52 @@ public extension Api { let _c41 = (Int(_1!) & Int(1 << 2) == 0) || _41 != nil let _c42 = (Int(_1!) & Int(1 << 15) == 0) || _42 != nil let _c43 = (Int(_1!) & Int(1 << 16) == 0) || _43 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - if !_c16 { return nil } - if !_c17 { return nil } - if !_c18 { return nil } - if !_c19 { return nil } - if !_c20 { return nil } - if !_c21 { return nil } - if !_c22 { return nil } - if !_c23 { return nil } - if !_c24 { return nil } - if !_c25 { return nil } - if !_c26 { return nil } - if !_c27 { return nil } - if !_c28 { return nil } - if !_c29 { return nil } - if !_c30 { return nil } - if !_c31 { return nil } - if !_c32 { return nil } - if !_c33 { return nil } - if !_c34 { return nil } - if !_c35 { return nil } - if !_c36 { return nil } - if !_c37 { return nil } - if !_c38 { return nil } - if !_c39 { return nil } - if !_c40 { return nil } - if !_c41 { return nil } - if !_c42 { return nil } - if !_c43 { return nil } - return Api.Config.config(flags: _1!, date: _2!, expires: _3!, testMode: _4!, thisDc: _5!, dcOptions: _6!, dcTxtDomainName: _7!, chatSizeMax: _8!, megagroupSizeMax: _9!, forwardedCountMax: _10!, onlineUpdatePeriodMs: _11!, offlineBlurTimeoutMs: _12!, offlineIdleTimeoutMs: _13!, onlineCloudTimeoutMs: _14!, notifyCloudDelayMs: _15!, notifyDefaultDelayMs: _16!, pushChatPeriodMs: _17!, pushChatLimit: _18!, editTimeLimit: _19!, revokeTimeLimit: _20!, revokePmTimeLimit: _21!, ratingEDecay: _22!, stickersRecentLimit: _23!, channelsReadMediaPeriod: _24!, tmpSessions: _25, callReceiveTimeoutMs: _26!, callRingTimeoutMs: _27!, callConnectTimeoutMs: _28!, callPacketTimeoutMs: _29!, meUrlPrefix: _30!, autoupdateUrlPrefix: _31, gifSearchUsername: _32, venueSearchUsername: _33, imgSearchUsername: _34, staticMapsProvider: _35, captionLengthMax: _36!, messageLengthMax: _37!, webfileDcId: _38!, suggestedLangCode: _39, langPackVersion: _40, baseLangPackVersion: _41, reactionsDefault: _42, autologinToken: _43) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 && _c18 && _c19 && _c20 && _c21 && _c22 && _c23 && _c24 && _c25 && _c26 && _c27 && _c28 && _c29 && _c30 && _c31 && _c32 && _c33 && _c34 && _c35 && _c36 && _c37 && _c38 && _c39 && _c40 && _c41 && _c42 && _c43 { + return Api.Config.config(Cons_config(flags: _1!, date: _2!, expires: _3!, testMode: _4!, thisDc: _5!, dcOptions: _6!, dcTxtDomainName: _7!, chatSizeMax: _8!, megagroupSizeMax: _9!, forwardedCountMax: _10!, onlineUpdatePeriodMs: _11!, offlineBlurTimeoutMs: _12!, offlineIdleTimeoutMs: _13!, onlineCloudTimeoutMs: _14!, notifyCloudDelayMs: _15!, notifyDefaultDelayMs: _16!, pushChatPeriodMs: _17!, pushChatLimit: _18!, editTimeLimit: _19!, revokeTimeLimit: _20!, revokePmTimeLimit: _21!, ratingEDecay: _22!, stickersRecentLimit: _23!, channelsReadMediaPeriod: _24!, tmpSessions: _25, callReceiveTimeoutMs: _26!, callRingTimeoutMs: _27!, callConnectTimeoutMs: _28!, callPacketTimeoutMs: _29!, meUrlPrefix: _30!, autoupdateUrlPrefix: _31, gifSearchUsername: _32, venueSearchUsername: _33, imgSearchUsername: _34, staticMapsProvider: _35, captionLengthMax: _36!, messageLengthMax: _37!, webfileDcId: _38!, suggestedLangCode: _39, langPackVersion: _40, baseLangPackVersion: _41, reactionsDefault: _42, autologinToken: _43)) + } + else { + return nil + } } - } } public extension Api { enum ConnectedBot: TypeConstructorDescription { - case connectedBot(flags: Int32, botId: Int64, recipients: Api.BusinessBotRecipients, rights: Api.BusinessBotRights) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .connectedBot(let flags, let botId, let recipients, let rights): - if boxed { - buffer.appendInt32(-849058964) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(botId, buffer: buffer, boxed: false) - recipients.serialize(buffer, true) - rights.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .connectedBot(let flags, let botId, let recipients, let rights): - return ("connectedBot", [("flags", flags as Any), ("botId", botId as Any), ("recipients", recipients as Any), ("rights", rights as Any)]) - } - } - + public class Cons_connectedBot { + public var flags: Int32 + public var botId: Int64 + public var recipients: Api.BusinessBotRecipients + public var rights: Api.BusinessBotRights + public init(flags: Int32, botId: Int64, recipients: Api.BusinessBotRecipients, rights: Api.BusinessBotRights) { + self.flags = flags + self.botId = botId + self.recipients = recipients + self.rights = rights + } + } + case connectedBot(Cons_connectedBot) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .connectedBot(let _data): + if boxed { + buffer.appendInt32(-849058964) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.botId, buffer: buffer, boxed: false) + _data.recipients.serialize(buffer, true) + _data.rights.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .connectedBot(let _data): + return ("connectedBot", [("flags", _data.flags as Any), ("botId", _data.botId as Any), ("recipients", _data.recipients as Any), ("rights", _data.rights as Any)]) + } + } + public static func parse_connectedBot(_ reader: BufferReader) -> ConnectedBot? { var _1: Int32? _1 = reader.readInt32() @@ -777,44 +1051,66 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.ConnectedBot.connectedBot(flags: _1!, botId: _2!, recipients: _3!, rights: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.ConnectedBot.connectedBot(Cons_connectedBot(flags: _1!, botId: _2!, recipients: _3!, rights: _4!)) + } + else { + return nil + } } - } } public extension Api { enum ConnectedBotStarRef: TypeConstructorDescription { - case connectedBotStarRef(flags: Int32, url: String, date: Int32, botId: Int64, commissionPermille: Int32, durationMonths: Int32?, participants: Int64, revenue: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .connectedBotStarRef(let flags, let url, let date, let botId, let commissionPermille, let durationMonths, let participants, let revenue): - if boxed { - buffer.appendInt32(429997937) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(botId, buffer: buffer, boxed: false) - serializeInt32(commissionPermille, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(durationMonths!, buffer: buffer, boxed: false)} - serializeInt64(participants, buffer: buffer, boxed: false) - serializeInt64(revenue, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .connectedBotStarRef(let flags, let url, let date, let botId, let commissionPermille, let durationMonths, let participants, let revenue): - return ("connectedBotStarRef", [("flags", flags as Any), ("url", url as Any), ("date", date as Any), ("botId", botId as Any), ("commissionPermille", commissionPermille as Any), ("durationMonths", durationMonths as Any), ("participants", participants as Any), ("revenue", revenue as Any)]) - } - } - + public class Cons_connectedBotStarRef { + public var flags: Int32 + public var url: String + public var date: Int32 + public var botId: Int64 + public var commissionPermille: Int32 + public var durationMonths: Int32? + public var participants: Int64 + public var revenue: Int64 + public init(flags: Int32, url: String, date: Int32, botId: Int64, commissionPermille: Int32, durationMonths: Int32?, participants: Int64, revenue: Int64) { + self.flags = flags + self.url = url + self.date = date + self.botId = botId + self.commissionPermille = commissionPermille + self.durationMonths = durationMonths + self.participants = participants + self.revenue = revenue + } + } + case connectedBotStarRef(Cons_connectedBotStarRef) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .connectedBotStarRef(let _data): + if boxed { + buffer.appendInt32(429997937) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.botId, buffer: buffer, boxed: false) + serializeInt32(_data.commissionPermille, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.durationMonths!, buffer: buffer, boxed: false) + } + serializeInt64(_data.participants, buffer: buffer, boxed: false) + serializeInt64(_data.revenue, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .connectedBotStarRef(let _data): + return ("connectedBotStarRef", [("flags", _data.flags as Any), ("url", _data.url as Any), ("date", _data.date as Any), ("botId", _data.botId as Any), ("commissionPermille", _data.commissionPermille as Any), ("durationMonths", _data.durationMonths as Any), ("participants", _data.participants as Any), ("revenue", _data.revenue as Any)]) + } + } + public static func parse_connectedBotStarRef(_ reader: BufferReader) -> ConnectedBotStarRef? { var _1: Int32? _1 = reader.readInt32() @@ -827,7 +1123,9 @@ public extension Api { var _5: Int32? _5 = reader.readInt32() var _6: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _6 = reader.readInt32() + } var _7: Int64? _7 = reader.readInt64() var _8: Int64? @@ -840,42 +1138,46 @@ public extension Api { let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil let _c7 = _7 != nil let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.ConnectedBotStarRef.connectedBotStarRef(flags: _1!, url: _2!, date: _3!, botId: _4!, commissionPermille: _5!, durationMonths: _6, participants: _7!, revenue: _8!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.ConnectedBotStarRef.connectedBotStarRef(Cons_connectedBotStarRef(flags: _1!, url: _2!, date: _3!, botId: _4!, commissionPermille: _5!, durationMonths: _6, participants: _7!, revenue: _8!)) + } + else { + return nil + } } - } } public extension Api { enum Contact: TypeConstructorDescription { - case contact(userId: Int64, mutual: Api.Bool) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .contact(let userId, let mutual): - if boxed { - buffer.appendInt32(341499403) - } - serializeInt64(userId, buffer: buffer, boxed: false) - mutual.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .contact(let userId, let mutual): - return ("contact", [("userId", userId as Any), ("mutual", mutual as Any)]) - } - } - + public class Cons_contact { + public var userId: Int64 + public var mutual: Api.Bool + public init(userId: Int64, mutual: Api.Bool) { + self.userId = userId + self.mutual = mutual + } + } + case contact(Cons_contact) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .contact(let _data): + if boxed { + buffer.appendInt32(341499403) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + _data.mutual.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .contact(let _data): + return ("contact", [("userId", _data.userId as Any), ("mutual", _data.mutual as Any)]) + } + } + public static func parse_contact(_ reader: BufferReader) -> Contact? { var _1: Int64? _1 = reader.readInt64() @@ -885,36 +1187,46 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.Contact.contact(userId: _1!, mutual: _2!) + if _c1 && _c2 { + return Api.Contact.contact(Cons_contact(userId: _1!, mutual: _2!)) + } + else { + return nil + } } - } } public extension Api { enum ContactBirthday: TypeConstructorDescription { - case contactBirthday(contactId: Int64, birthday: Api.Birthday) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .contactBirthday(let contactId, let birthday): - if boxed { - buffer.appendInt32(496600883) - } - serializeInt64(contactId, buffer: buffer, boxed: false) - birthday.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .contactBirthday(let contactId, let birthday): - return ("contactBirthday", [("contactId", contactId as Any), ("birthday", birthday as Any)]) - } - } - + public class Cons_contactBirthday { + public var contactId: Int64 + public var birthday: Api.Birthday + public init(contactId: Int64, birthday: Api.Birthday) { + self.contactId = contactId + self.birthday = birthday + } + } + case contactBirthday(Cons_contactBirthday) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .contactBirthday(let _data): + if boxed { + buffer.appendInt32(496600883) + } + serializeInt64(_data.contactId, buffer: buffer, boxed: false) + _data.birthday.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .contactBirthday(let _data): + return ("contactBirthday", [("contactId", _data.contactId as Any), ("birthday", _data.birthday as Any)]) + } + } + public static func parse_contactBirthday(_ reader: BufferReader) -> ContactBirthday? { var _1: Int64? _1 = reader.readInt64() @@ -924,36 +1236,46 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ContactBirthday.contactBirthday(contactId: _1!, birthday: _2!) + if _c1 && _c2 { + return Api.ContactBirthday.contactBirthday(Cons_contactBirthday(contactId: _1!, birthday: _2!)) + } + else { + return nil + } } - } } public extension Api { enum ContactStatus: TypeConstructorDescription { - case contactStatus(userId: Int64, status: Api.UserStatus) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .contactStatus(let userId, let status): - if boxed { - buffer.appendInt32(383348795) - } - serializeInt64(userId, buffer: buffer, boxed: false) - status.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .contactStatus(let userId, let status): - return ("contactStatus", [("userId", userId as Any), ("status", status as Any)]) - } - } - + public class Cons_contactStatus { + public var userId: Int64 + public var status: Api.UserStatus + public init(userId: Int64, status: Api.UserStatus) { + self.userId = userId + self.status = status + } + } + case contactStatus(Cons_contactStatus) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .contactStatus(let _data): + if boxed { + buffer.appendInt32(383348795) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + _data.status.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .contactStatus(let _data): + return ("contactStatus", [("userId", _data.userId as Any), ("status", _data.status as Any)]) + } + } + public static func parse_contactStatus(_ reader: BufferReader) -> ContactStatus? { var _1: Int64? _1 = reader.readInt64() @@ -963,71 +1285,98 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ContactStatus.contactStatus(userId: _1!, status: _2!) + if _c1 && _c2 { + return Api.ContactStatus.contactStatus(Cons_contactStatus(userId: _1!, status: _2!)) + } + else { + return nil + } } - } } public extension Api { enum DataJSON: TypeConstructorDescription { - case dataJSON(data: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .dataJSON(let data): - if boxed { - buffer.appendInt32(2104790276) - } - serializeString(data, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .dataJSON(let data): - return ("dataJSON", [("data", data as Any)]) - } - } - + public class Cons_dataJSON { + public var data: String + public init(data: String) { + self.data = data + } + } + case dataJSON(Cons_dataJSON) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .dataJSON(let _data): + if boxed { + buffer.appendInt32(2104790276) + } + serializeString(_data.data, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .dataJSON(let _data): + return ("dataJSON", [("data", _data.data as Any)]) + } + } + public static func parse_dataJSON(_ reader: BufferReader) -> DataJSON? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.DataJSON.dataJSON(data: _1!) + if _c1 { + return Api.DataJSON.dataJSON(Cons_dataJSON(data: _1!)) + } + else { + return nil + } } - } } public extension Api { enum DcOption: TypeConstructorDescription { - case dcOption(flags: Int32, id: Int32, ipAddress: String, port: Int32, secret: Buffer?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .dcOption(let flags, let id, let ipAddress, let port, let secret): - if boxed { - buffer.appendInt32(414687501) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - serializeString(ipAddress, buffer: buffer, boxed: false) - serializeInt32(port, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 10) != 0 {serializeBytes(secret!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .dcOption(let flags, let id, let ipAddress, let port, let secret): - return ("dcOption", [("flags", flags as Any), ("id", id as Any), ("ipAddress", ipAddress as Any), ("port", port as Any), ("secret", secret as Any)]) - } - } - + public class Cons_dcOption { + public var flags: Int32 + public var id: Int32 + public var ipAddress: String + public var port: Int32 + public var secret: Buffer? + public init(flags: Int32, id: Int32, ipAddress: String, port: Int32, secret: Buffer?) { + self.flags = flags + self.id = id + self.ipAddress = ipAddress + self.port = port + self.secret = secret + } + } + case dcOption(Cons_dcOption) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .dcOption(let _data): + if boxed { + buffer.appendInt32(414687501) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeString(_data.ipAddress, buffer: buffer, boxed: false) + serializeInt32(_data.port, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 10) != 0 { + serializeBytes(_data.secret!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .dcOption(let _data): + return ("dcOption", [("flags", _data.flags as Any), ("id", _data.id as Any), ("ipAddress", _data.ipAddress as Any), ("port", _data.port as Any), ("secret", _data.secret as Any)]) + } + } + public static func parse_dcOption(_ reader: BufferReader) -> DcOption? { var _1: Int32? _1 = reader.readInt32() @@ -1038,104 +1387,172 @@ public extension Api { var _4: Int32? _4 = reader.readInt32() var _5: Buffer? - if Int(_1!) & Int(1 << 10) != 0 {_5 = parseBytes(reader) } + if Int(_1!) & Int(1 << 10) != 0 { + _5 = parseBytes(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 10) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.DcOption.dcOption(flags: _1!, id: _2!, ipAddress: _3!, port: _4!, secret: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.DcOption.dcOption(Cons_dcOption(flags: _1!, id: _2!, ipAddress: _3!, port: _4!, secret: _5)) + } + else { + return nil + } } - } } public extension Api { enum DefaultHistoryTTL: TypeConstructorDescription { - case defaultHistoryTTL(period: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .defaultHistoryTTL(let period): - if boxed { - buffer.appendInt32(1135897376) - } - serializeInt32(period, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .defaultHistoryTTL(let period): - return ("defaultHistoryTTL", [("period", period as Any)]) - } - } - + public class Cons_defaultHistoryTTL { + public var period: Int32 + public init(period: Int32) { + self.period = period + } + } + case defaultHistoryTTL(Cons_defaultHistoryTTL) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .defaultHistoryTTL(let _data): + if boxed { + buffer.appendInt32(1135897376) + } + serializeInt32(_data.period, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .defaultHistoryTTL(let _data): + return ("defaultHistoryTTL", [("period", _data.period as Any)]) + } + } + public static func parse_defaultHistoryTTL(_ reader: BufferReader) -> DefaultHistoryTTL? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.DefaultHistoryTTL.defaultHistoryTTL(period: _1!) + if _c1 { + return Api.DefaultHistoryTTL.defaultHistoryTTL(Cons_defaultHistoryTTL(period: _1!)) + } + else { + return nil + } } - } } public extension Api { indirect enum Dialog: TypeConstructorDescription { - case dialog(flags: Int32, peer: Api.Peer, topMessage: Int32, readInboxMaxId: Int32, readOutboxMaxId: Int32, unreadCount: Int32, unreadMentionsCount: Int32, unreadReactionsCount: Int32, notifySettings: Api.PeerNotifySettings, pts: Int32?, draft: Api.DraftMessage?, folderId: Int32?, ttlPeriod: Int32?) - case dialogFolder(flags: Int32, folder: Api.Folder, peer: Api.Peer, topMessage: Int32, unreadMutedPeersCount: Int32, unreadUnmutedPeersCount: Int32, unreadMutedMessagesCount: Int32, unreadUnmutedMessagesCount: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .dialog(let flags, let peer, let topMessage, let readInboxMaxId, let readOutboxMaxId, let unreadCount, let unreadMentionsCount, let unreadReactionsCount, let notifySettings, let pts, let draft, let folderId, let ttlPeriod): - if boxed { - buffer.appendInt32(-712374074) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(topMessage, buffer: buffer, boxed: false) - serializeInt32(readInboxMaxId, buffer: buffer, boxed: false) - serializeInt32(readOutboxMaxId, buffer: buffer, boxed: false) - serializeInt32(unreadCount, buffer: buffer, boxed: false) - serializeInt32(unreadMentionsCount, buffer: buffer, boxed: false) - serializeInt32(unreadReactionsCount, buffer: buffer, boxed: false) - notifySettings.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(pts!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {draft!.serialize(buffer, true)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(folderId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeInt32(ttlPeriod!, buffer: buffer, boxed: false)} - break - case .dialogFolder(let flags, let folder, let peer, let topMessage, let unreadMutedPeersCount, let unreadUnmutedPeersCount, let unreadMutedMessagesCount, let unreadUnmutedMessagesCount): - if boxed { - buffer.appendInt32(1908216652) - } - serializeInt32(flags, buffer: buffer, boxed: false) - folder.serialize(buffer, true) - peer.serialize(buffer, true) - serializeInt32(topMessage, buffer: buffer, boxed: false) - serializeInt32(unreadMutedPeersCount, buffer: buffer, boxed: false) - serializeInt32(unreadUnmutedPeersCount, buffer: buffer, boxed: false) - serializeInt32(unreadMutedMessagesCount, buffer: buffer, boxed: false) - serializeInt32(unreadUnmutedMessagesCount, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .dialog(let flags, let peer, let topMessage, let readInboxMaxId, let readOutboxMaxId, let unreadCount, let unreadMentionsCount, let unreadReactionsCount, let notifySettings, let pts, let draft, let folderId, let ttlPeriod): - return ("dialog", [("flags", flags as Any), ("peer", peer as Any), ("topMessage", topMessage as Any), ("readInboxMaxId", readInboxMaxId as Any), ("readOutboxMaxId", readOutboxMaxId as Any), ("unreadCount", unreadCount as Any), ("unreadMentionsCount", unreadMentionsCount as Any), ("unreadReactionsCount", unreadReactionsCount as Any), ("notifySettings", notifySettings as Any), ("pts", pts as Any), ("draft", draft as Any), ("folderId", folderId as Any), ("ttlPeriod", ttlPeriod as Any)]) - case .dialogFolder(let flags, let folder, let peer, let topMessage, let unreadMutedPeersCount, let unreadUnmutedPeersCount, let unreadMutedMessagesCount, let unreadUnmutedMessagesCount): - return ("dialogFolder", [("flags", flags as Any), ("folder", folder as Any), ("peer", peer as Any), ("topMessage", topMessage as Any), ("unreadMutedPeersCount", unreadMutedPeersCount as Any), ("unreadUnmutedPeersCount", unreadUnmutedPeersCount as Any), ("unreadMutedMessagesCount", unreadMutedMessagesCount as Any), ("unreadUnmutedMessagesCount", unreadUnmutedMessagesCount as Any)]) - } - } - + public class Cons_dialog { + public var flags: Int32 + public var peer: Api.Peer + public var topMessage: Int32 + public var readInboxMaxId: Int32 + public var readOutboxMaxId: Int32 + public var unreadCount: Int32 + public var unreadMentionsCount: Int32 + public var unreadReactionsCount: Int32 + public var notifySettings: Api.PeerNotifySettings + public var pts: Int32? + public var draft: Api.DraftMessage? + public var folderId: Int32? + public var ttlPeriod: Int32? + public init(flags: Int32, peer: Api.Peer, topMessage: Int32, readInboxMaxId: Int32, readOutboxMaxId: Int32, unreadCount: Int32, unreadMentionsCount: Int32, unreadReactionsCount: Int32, notifySettings: Api.PeerNotifySettings, pts: Int32?, draft: Api.DraftMessage?, folderId: Int32?, ttlPeriod: Int32?) { + self.flags = flags + self.peer = peer + self.topMessage = topMessage + self.readInboxMaxId = readInboxMaxId + self.readOutboxMaxId = readOutboxMaxId + self.unreadCount = unreadCount + self.unreadMentionsCount = unreadMentionsCount + self.unreadReactionsCount = unreadReactionsCount + self.notifySettings = notifySettings + self.pts = pts + self.draft = draft + self.folderId = folderId + self.ttlPeriod = ttlPeriod + } + } + public class Cons_dialogFolder { + public var flags: Int32 + public var folder: Api.Folder + public var peer: Api.Peer + public var topMessage: Int32 + public var unreadMutedPeersCount: Int32 + public var unreadUnmutedPeersCount: Int32 + public var unreadMutedMessagesCount: Int32 + public var unreadUnmutedMessagesCount: Int32 + public init(flags: Int32, folder: Api.Folder, peer: Api.Peer, topMessage: Int32, unreadMutedPeersCount: Int32, unreadUnmutedPeersCount: Int32, unreadMutedMessagesCount: Int32, unreadUnmutedMessagesCount: Int32) { + self.flags = flags + self.folder = folder + self.peer = peer + self.topMessage = topMessage + self.unreadMutedPeersCount = unreadMutedPeersCount + self.unreadUnmutedPeersCount = unreadUnmutedPeersCount + self.unreadMutedMessagesCount = unreadMutedMessagesCount + self.unreadUnmutedMessagesCount = unreadUnmutedMessagesCount + } + } + case dialog(Cons_dialog) + case dialogFolder(Cons_dialogFolder) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .dialog(let _data): + if boxed { + buffer.appendInt32(-712374074) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeInt32(_data.topMessage, buffer: buffer, boxed: false) + serializeInt32(_data.readInboxMaxId, buffer: buffer, boxed: false) + serializeInt32(_data.readOutboxMaxId, buffer: buffer, boxed: false) + serializeInt32(_data.unreadCount, buffer: buffer, boxed: false) + serializeInt32(_data.unreadMentionsCount, buffer: buffer, boxed: false) + serializeInt32(_data.unreadReactionsCount, buffer: buffer, boxed: false) + _data.notifySettings.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.pts!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.draft!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.folderId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeInt32(_data.ttlPeriod!, buffer: buffer, boxed: false) + } + break + case .dialogFolder(let _data): + if boxed { + buffer.appendInt32(1908216652) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.folder.serialize(buffer, true) + _data.peer.serialize(buffer, true) + serializeInt32(_data.topMessage, buffer: buffer, boxed: false) + serializeInt32(_data.unreadMutedPeersCount, buffer: buffer, boxed: false) + serializeInt32(_data.unreadUnmutedPeersCount, buffer: buffer, boxed: false) + serializeInt32(_data.unreadMutedMessagesCount, buffer: buffer, boxed: false) + serializeInt32(_data.unreadUnmutedMessagesCount, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .dialog(let _data): + return ("dialog", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("topMessage", _data.topMessage as Any), ("readInboxMaxId", _data.readInboxMaxId as Any), ("readOutboxMaxId", _data.readOutboxMaxId as Any), ("unreadCount", _data.unreadCount as Any), ("unreadMentionsCount", _data.unreadMentionsCount as Any), ("unreadReactionsCount", _data.unreadReactionsCount as Any), ("notifySettings", _data.notifySettings as Any), ("pts", _data.pts as Any), ("draft", _data.draft as Any), ("folderId", _data.folderId as Any), ("ttlPeriod", _data.ttlPeriod as Any)]) + case .dialogFolder(let _data): + return ("dialogFolder", [("flags", _data.flags as Any), ("folder", _data.folder as Any), ("peer", _data.peer as Any), ("topMessage", _data.topMessage as Any), ("unreadMutedPeersCount", _data.unreadMutedPeersCount as Any), ("unreadUnmutedPeersCount", _data.unreadUnmutedPeersCount as Any), ("unreadMutedMessagesCount", _data.unreadMutedMessagesCount as Any), ("unreadUnmutedMessagesCount", _data.unreadUnmutedMessagesCount as Any)]) + } + } + public static func parse_dialog(_ reader: BufferReader) -> Dialog? { var _1: Int32? _1 = reader.readInt32() @@ -1160,15 +1577,23 @@ public extension Api { _9 = Api.parse(reader, signature: signature) as? Api.PeerNotifySettings } var _10: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_10 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _10 = reader.readInt32() + } var _11: Api.DraftMessage? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _11 = Api.parse(reader, signature: signature) as? Api.DraftMessage - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _11 = Api.parse(reader, signature: signature) as? Api.DraftMessage + } + } var _12: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_12 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _12 = reader.readInt32() + } var _13: Int32? - if Int(_1!) & Int(1 << 5) != 0 {_13 = reader.readInt32() } + if Int(_1!) & Int(1 << 5) != 0 { + _13 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -1182,20 +1607,12 @@ public extension Api { let _c11 = (Int(_1!) & Int(1 << 1) == 0) || _11 != nil let _c12 = (Int(_1!) & Int(1 << 4) == 0) || _12 != nil let _c13 = (Int(_1!) & Int(1 << 5) == 0) || _13 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - return Api.Dialog.dialog(flags: _1!, peer: _2!, topMessage: _3!, readInboxMaxId: _4!, readOutboxMaxId: _5!, unreadCount: _6!, unreadMentionsCount: _7!, unreadReactionsCount: _8!, notifySettings: _9!, pts: _10, draft: _11, folderId: _12, ttlPeriod: _13) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 { + return Api.Dialog.dialog(Cons_dialog(flags: _1!, peer: _2!, topMessage: _3!, readInboxMaxId: _4!, readOutboxMaxId: _5!, unreadCount: _6!, unreadMentionsCount: _7!, unreadReactionsCount: _8!, notifySettings: _9!, pts: _10, draft: _11, folderId: _12, ttlPeriod: _13)) + } + else { + return nil + } } public static func parse_dialogFolder(_ reader: BufferReader) -> Dialog? { var _1: Int32? @@ -1226,92 +1643,133 @@ public extension Api { let _c6 = _6 != nil let _c7 = _7 != nil let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.Dialog.dialogFolder(flags: _1!, folder: _2!, peer: _3!, topMessage: _4!, unreadMutedPeersCount: _5!, unreadUnmutedPeersCount: _6!, unreadMutedMessagesCount: _7!, unreadUnmutedMessagesCount: _8!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.Dialog.dialogFolder(Cons_dialogFolder(flags: _1!, folder: _2!, peer: _3!, topMessage: _4!, unreadMutedPeersCount: _5!, unreadUnmutedPeersCount: _6!, unreadMutedMessagesCount: _7!, unreadUnmutedMessagesCount: _8!)) + } + else { + return nil + } } - } } public extension Api { enum DialogFilter: TypeConstructorDescription { - case dialogFilter(flags: Int32, id: Int32, title: Api.TextWithEntities, emoticon: String?, color: Int32?, pinnedPeers: [Api.InputPeer], includePeers: [Api.InputPeer], excludePeers: [Api.InputPeer]) - case dialogFilterChatlist(flags: Int32, id: Int32, title: Api.TextWithEntities, emoticon: String?, color: Int32?, pinnedPeers: [Api.InputPeer], includePeers: [Api.InputPeer]) + public class Cons_dialogFilter { + public var flags: Int32 + public var id: Int32 + public var title: Api.TextWithEntities + public var emoticon: String? + public var color: Int32? + public var pinnedPeers: [Api.InputPeer] + public var includePeers: [Api.InputPeer] + public var excludePeers: [Api.InputPeer] + public init(flags: Int32, id: Int32, title: Api.TextWithEntities, emoticon: String?, color: Int32?, pinnedPeers: [Api.InputPeer], includePeers: [Api.InputPeer], excludePeers: [Api.InputPeer]) { + self.flags = flags + self.id = id + self.title = title + self.emoticon = emoticon + self.color = color + self.pinnedPeers = pinnedPeers + self.includePeers = includePeers + self.excludePeers = excludePeers + } + } + public class Cons_dialogFilterChatlist { + public var flags: Int32 + public var id: Int32 + public var title: Api.TextWithEntities + public var emoticon: String? + public var color: Int32? + public var pinnedPeers: [Api.InputPeer] + public var includePeers: [Api.InputPeer] + public init(flags: Int32, id: Int32, title: Api.TextWithEntities, emoticon: String?, color: Int32?, pinnedPeers: [Api.InputPeer], includePeers: [Api.InputPeer]) { + self.flags = flags + self.id = id + self.title = title + self.emoticon = emoticon + self.color = color + self.pinnedPeers = pinnedPeers + self.includePeers = includePeers + } + } + case dialogFilter(Cons_dialogFilter) + case dialogFilterChatlist(Cons_dialogFilterChatlist) case dialogFilterDefault - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .dialogFilter(let flags, let id, let title, let emoticon, let color, let pinnedPeers, let includePeers, let excludePeers): - if boxed { - buffer.appendInt32(-1438177711) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - title.serialize(buffer, true) - if Int(flags) & Int(1 << 25) != 0 {serializeString(emoticon!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 27) != 0 {serializeInt32(color!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(pinnedPeers.count)) - for item in pinnedPeers { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(includePeers.count)) - for item in includePeers { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(excludePeers.count)) - for item in excludePeers { - item.serialize(buffer, true) - } - break - case .dialogFilterChatlist(let flags, let id, let title, let emoticon, let color, let pinnedPeers, let includePeers): - if boxed { - buffer.appendInt32(-1772913705) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - title.serialize(buffer, true) - if Int(flags) & Int(1 << 25) != 0 {serializeString(emoticon!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 27) != 0 {serializeInt32(color!, buffer: buffer, boxed: false)} - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(pinnedPeers.count)) - for item in pinnedPeers { - item.serialize(buffer, true) - } - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(includePeers.count)) - for item in includePeers { - item.serialize(buffer, true) - } - break - case .dialogFilterDefault: - if boxed { - buffer.appendInt32(909284270) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .dialogFilter(let flags, let id, let title, let emoticon, let color, let pinnedPeers, let includePeers, let excludePeers): - return ("dialogFilter", [("flags", flags as Any), ("id", id as Any), ("title", title as Any), ("emoticon", emoticon as Any), ("color", color as Any), ("pinnedPeers", pinnedPeers as Any), ("includePeers", includePeers as Any), ("excludePeers", excludePeers as Any)]) - case .dialogFilterChatlist(let flags, let id, let title, let emoticon, let color, let pinnedPeers, let includePeers): - return ("dialogFilterChatlist", [("flags", flags as Any), ("id", id as Any), ("title", title as Any), ("emoticon", emoticon as Any), ("color", color as Any), ("pinnedPeers", pinnedPeers as Any), ("includePeers", includePeers as Any)]) - case .dialogFilterDefault: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .dialogFilter(let _data): + if boxed { + buffer.appendInt32(-1438177711) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + _data.title.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 25) != 0 { + serializeString(_data.emoticon!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 27) != 0 { + serializeInt32(_data.color!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.pinnedPeers.count)) + for item in _data.pinnedPeers { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.includePeers.count)) + for item in _data.includePeers { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.excludePeers.count)) + for item in _data.excludePeers { + item.serialize(buffer, true) + } + break + case .dialogFilterChatlist(let _data): + if boxed { + buffer.appendInt32(-1772913705) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + _data.title.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 25) != 0 { + serializeString(_data.emoticon!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 27) != 0 { + serializeInt32(_data.color!, buffer: buffer, boxed: false) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.pinnedPeers.count)) + for item in _data.pinnedPeers { + item.serialize(buffer, true) + } + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.includePeers.count)) + for item in _data.includePeers { + item.serialize(buffer, true) + } + break + case .dialogFilterDefault: + if boxed { + buffer.appendInt32(909284270) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .dialogFilter(let _data): + return ("dialogFilter", [("flags", _data.flags as Any), ("id", _data.id as Any), ("title", _data.title as Any), ("emoticon", _data.emoticon as Any), ("color", _data.color as Any), ("pinnedPeers", _data.pinnedPeers as Any), ("includePeers", _data.includePeers as Any), ("excludePeers", _data.excludePeers as Any)]) + case .dialogFilterChatlist(let _data): + return ("dialogFilterChatlist", [("flags", _data.flags as Any), ("id", _data.id as Any), ("title", _data.title as Any), ("emoticon", _data.emoticon as Any), ("color", _data.color as Any), ("pinnedPeers", _data.pinnedPeers as Any), ("includePeers", _data.includePeers as Any)]) + case .dialogFilterDefault: return ("dialogFilterDefault", []) - } - } - + } + } + public static func parse_dialogFilter(_ reader: BufferReader) -> DialogFilter? { var _1: Int32? _1 = reader.readInt32() @@ -1322,9 +1780,13 @@ public extension Api { _3 = Api.parse(reader, signature: signature) as? Api.TextWithEntities } var _4: String? - if Int(_1!) & Int(1 << 25) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 25) != 0 { + _4 = parseString(reader) + } var _5: Int32? - if Int(_1!) & Int(1 << 27) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 27) != 0 { + _5 = reader.readInt32() + } var _6: [Api.InputPeer]? if let _ = reader.readInt32() { _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputPeer.self) @@ -1345,15 +1807,12 @@ public extension Api { let _c6 = _6 != nil let _c7 = _7 != nil let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.DialogFilter.dialogFilter(flags: _1!, id: _2!, title: _3!, emoticon: _4, color: _5, pinnedPeers: _6!, includePeers: _7!, excludePeers: _8!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.DialogFilter.dialogFilter(Cons_dialogFilter(flags: _1!, id: _2!, title: _3!, emoticon: _4, color: _5, pinnedPeers: _6!, includePeers: _7!, excludePeers: _8!)) + } + else { + return nil + } } public static func parse_dialogFilterChatlist(_ reader: BufferReader) -> DialogFilter? { var _1: Int32? @@ -1365,9 +1824,13 @@ public extension Api { _3 = Api.parse(reader, signature: signature) as? Api.TextWithEntities } var _4: String? - if Int(_1!) & Int(1 << 25) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 25) != 0 { + _4 = parseString(reader) + } var _5: Int32? - if Int(_1!) & Int(1 << 27) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 27) != 0 { + _5 = reader.readInt32() + } var _6: [Api.InputPeer]? if let _ = reader.readInt32() { _6 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputPeer.self) @@ -1383,44 +1846,49 @@ public extension Api { let _c5 = (Int(_1!) & Int(1 << 27) == 0) || _5 != nil let _c6 = _6 != nil let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.DialogFilter.dialogFilterChatlist(flags: _1!, id: _2!, title: _3!, emoticon: _4, color: _5, pinnedPeers: _6!, includePeers: _7!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.DialogFilter.dialogFilterChatlist(Cons_dialogFilterChatlist(flags: _1!, id: _2!, title: _3!, emoticon: _4, color: _5, pinnedPeers: _6!, includePeers: _7!)) + } + else { + return nil + } } public static func parse_dialogFilterDefault(_ reader: BufferReader) -> DialogFilter? { return Api.DialogFilter.dialogFilterDefault } - } } public extension Api { enum DialogFilterSuggested: TypeConstructorDescription { - case dialogFilterSuggested(filter: Api.DialogFilter, description: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .dialogFilterSuggested(let filter, let description): - if boxed { - buffer.appendInt32(2004110666) - } - filter.serialize(buffer, true) - serializeString(description, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .dialogFilterSuggested(let filter, let description): - return ("dialogFilterSuggested", [("filter", filter as Any), ("description", description as Any)]) - } - } - + public class Cons_dialogFilterSuggested { + public var filter: Api.DialogFilter + public var description: String + public init(filter: Api.DialogFilter, description: String) { + self.filter = filter + self.description = description + } + } + case dialogFilterSuggested(Cons_dialogFilterSuggested) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .dialogFilterSuggested(let _data): + if boxed { + buffer.appendInt32(2004110666) + } + _data.filter.serialize(buffer, true) + serializeString(_data.description, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .dialogFilterSuggested(let _data): + return ("dialogFilterSuggested", [("filter", _data.filter as Any), ("description", _data.description as Any)]) + } + } + public static func parse_dialogFilterSuggested(_ reader: BufferReader) -> DialogFilterSuggested? { var _1: Api.DialogFilter? if let signature = reader.readInt32() { @@ -1430,60 +1898,81 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.DialogFilterSuggested.dialogFilterSuggested(filter: _1!, description: _2!) + if _c1 && _c2 { + return Api.DialogFilterSuggested.dialogFilterSuggested(Cons_dialogFilterSuggested(filter: _1!, description: _2!)) + } + else { + return nil + } } - } } public extension Api { enum DialogPeer: TypeConstructorDescription { - case dialogPeer(peer: Api.Peer) - case dialogPeerFolder(folderId: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .dialogPeer(let peer): - if boxed { - buffer.appendInt32(-445792507) - } - peer.serialize(buffer, true) - break - case .dialogPeerFolder(let folderId): - if boxed { - buffer.appendInt32(1363483106) - } - serializeInt32(folderId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .dialogPeer(let peer): - return ("dialogPeer", [("peer", peer as Any)]) - case .dialogPeerFolder(let folderId): - return ("dialogPeerFolder", [("folderId", folderId as Any)]) - } - } - + public class Cons_dialogPeer { + public var peer: Api.Peer + public init(peer: Api.Peer) { + self.peer = peer + } + } + public class Cons_dialogPeerFolder { + public var folderId: Int32 + public init(folderId: Int32) { + self.folderId = folderId + } + } + case dialogPeer(Cons_dialogPeer) + case dialogPeerFolder(Cons_dialogPeerFolder) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .dialogPeer(let _data): + if boxed { + buffer.appendInt32(-445792507) + } + _data.peer.serialize(buffer, true) + break + case .dialogPeerFolder(let _data): + if boxed { + buffer.appendInt32(1363483106) + } + serializeInt32(_data.folderId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .dialogPeer(let _data): + return ("dialogPeer", [("peer", _data.peer as Any)]) + case .dialogPeerFolder(let _data): + return ("dialogPeerFolder", [("folderId", _data.folderId as Any)]) + } + } + public static func parse_dialogPeer(_ reader: BufferReader) -> DialogPeer? { var _1: Api.Peer? if let signature = reader.readInt32() { _1 = Api.parse(reader, signature: signature) as? Api.Peer } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.DialogPeer.dialogPeer(peer: _1!) + if _c1 { + return Api.DialogPeer.dialogPeer(Cons_dialogPeer(peer: _1!)) + } + else { + return nil + } } public static func parse_dialogPeerFolder(_ reader: BufferReader) -> DialogPeer? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.DialogPeer.dialogPeerFolder(folderId: _1!) + if _c1 { + return Api.DialogPeer.dialogPeerFolder(Cons_dialogPeerFolder(folderId: _1!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api6.swift b/submodules/TelegramApi/Sources/Api6.swift index 5cb12927..3683abb3 100644 --- a/submodules/TelegramApi/Sources/Api6.swift +++ b/submodules/TelegramApi/Sources/Api6.swift @@ -1,88 +1,133 @@ public extension Api { enum DisallowedGiftsSettings: TypeConstructorDescription { - case disallowedGiftsSettings(flags: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .disallowedGiftsSettings(let flags): - if boxed { - buffer.appendInt32(1911715524) - } - serializeInt32(flags, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .disallowedGiftsSettings(let flags): - return ("disallowedGiftsSettings", [("flags", flags as Any)]) - } - } - + public class Cons_disallowedGiftsSettings { + public var flags: Int32 + public init(flags: Int32) { + self.flags = flags + } + } + case disallowedGiftsSettings(Cons_disallowedGiftsSettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .disallowedGiftsSettings(let _data): + if boxed { + buffer.appendInt32(1911715524) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .disallowedGiftsSettings(let _data): + return ("disallowedGiftsSettings", [("flags", _data.flags as Any)]) + } + } + public static func parse_disallowedGiftsSettings(_ reader: BufferReader) -> DisallowedGiftsSettings? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.DisallowedGiftsSettings.disallowedGiftsSettings(flags: _1!) + if _c1 { + return Api.DisallowedGiftsSettings.disallowedGiftsSettings(Cons_disallowedGiftsSettings(flags: _1!)) + } + else { + return nil + } } - } } public extension Api { enum Document: TypeConstructorDescription { - case document(flags: Int32, id: Int64, accessHash: Int64, fileReference: Buffer, date: Int32, mimeType: String, size: Int64, thumbs: [Api.PhotoSize]?, videoThumbs: [Api.VideoSize]?, dcId: Int32, attributes: [Api.DocumentAttribute]) - case documentEmpty(id: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .document(let flags, let id, let accessHash, let fileReference, let date, let mimeType, let size, let thumbs, let videoThumbs, let dcId, let attributes): - if boxed { - buffer.appendInt32(-1881881384) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeBytes(fileReference, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeString(mimeType, buffer: buffer, boxed: false) - serializeInt64(size, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(thumbs!.count)) - for item in thumbs! { - item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(videoThumbs!.count)) - for item in videoThumbs! { - item.serialize(buffer, true) - }} - serializeInt32(dcId, buffer: buffer, boxed: false) + public class Cons_document { + public var flags: Int32 + public var id: Int64 + public var accessHash: Int64 + public var fileReference: Buffer + public var date: Int32 + public var mimeType: String + public var size: Int64 + public var thumbs: [Api.PhotoSize]? + public var videoThumbs: [Api.VideoSize]? + public var dcId: Int32 + public var attributes: [Api.DocumentAttribute] + public init(flags: Int32, id: Int64, accessHash: Int64, fileReference: Buffer, date: Int32, mimeType: String, size: Int64, thumbs: [Api.PhotoSize]?, videoThumbs: [Api.VideoSize]?, dcId: Int32, attributes: [Api.DocumentAttribute]) { + self.flags = flags + self.id = id + self.accessHash = accessHash + self.fileReference = fileReference + self.date = date + self.mimeType = mimeType + self.size = size + self.thumbs = thumbs + self.videoThumbs = videoThumbs + self.dcId = dcId + self.attributes = attributes + } + } + public class Cons_documentEmpty { + public var id: Int64 + public init(id: Int64) { + self.id = id + } + } + case document(Cons_document) + case documentEmpty(Cons_documentEmpty) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .document(let _data): + if boxed { + buffer.appendInt32(-1881881384) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeBytes(_data.fileReference, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeString(_data.mimeType, buffer: buffer, boxed: false) + serializeInt64(_data.size, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { buffer.appendInt32(481674261) - buffer.appendInt32(Int32(attributes.count)) - for item in attributes { + buffer.appendInt32(Int32(_data.thumbs!.count)) + for item in _data.thumbs! { item.serialize(buffer, true) } - break - case .documentEmpty(let id): - if boxed { - buffer.appendInt32(922273905) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.videoThumbs!.count)) + for item in _data.videoThumbs! { + item.serialize(buffer, true) } - serializeInt64(id, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .document(let flags, let id, let accessHash, let fileReference, let date, let mimeType, let size, let thumbs, let videoThumbs, let dcId, let attributes): - return ("document", [("flags", flags as Any), ("id", id as Any), ("accessHash", accessHash as Any), ("fileReference", fileReference as Any), ("date", date as Any), ("mimeType", mimeType as Any), ("size", size as Any), ("thumbs", thumbs as Any), ("videoThumbs", videoThumbs as Any), ("dcId", dcId as Any), ("attributes", attributes as Any)]) - case .documentEmpty(let id): - return ("documentEmpty", [("id", id as Any)]) - } - } - + } + serializeInt32(_data.dcId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.attributes.count)) + for item in _data.attributes { + item.serialize(buffer, true) + } + break + case .documentEmpty(let _data): + if boxed { + buffer.appendInt32(922273905) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .document(let _data): + return ("document", [("flags", _data.flags as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("fileReference", _data.fileReference as Any), ("date", _data.date as Any), ("mimeType", _data.mimeType as Any), ("size", _data.size as Any), ("thumbs", _data.thumbs as Any), ("videoThumbs", _data.videoThumbs as Any), ("dcId", _data.dcId as Any), ("attributes", _data.attributes as Any)]) + case .documentEmpty(let _data): + return ("documentEmpty", [("id", _data.id as Any)]) + } + } + public static func parse_document(_ reader: BufferReader) -> Document? { var _1: Int32? _1 = reader.readInt32() @@ -99,13 +144,17 @@ public extension Api { var _7: Int64? _7 = reader.readInt64() var _8: [Api.PhotoSize]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PhotoSize.self) - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _8 = Api.parseVector(reader, elementSignature: 0, elementType: Api.PhotoSize.self) + } + } var _9: [Api.VideoSize]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _9 = Api.parseVector(reader, elementSignature: 0, elementType: Api.VideoSize.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _9 = Api.parseVector(reader, elementSignature: 0, elementType: Api.VideoSize.self) + } + } var _10: Int32? _10 = reader.readInt32() var _11: [Api.DocumentAttribute]? @@ -123,130 +172,207 @@ public extension Api { let _c9 = (Int(_1!) & Int(1 << 1) == 0) || _9 != nil let _c10 = _10 != nil let _c11 = _11 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - return Api.Document.document(flags: _1!, id: _2!, accessHash: _3!, fileReference: _4!, date: _5!, mimeType: _6!, size: _7!, thumbs: _8, videoThumbs: _9, dcId: _10!, attributes: _11!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 { + return Api.Document.document(Cons_document(flags: _1!, id: _2!, accessHash: _3!, fileReference: _4!, date: _5!, mimeType: _6!, size: _7!, thumbs: _8, videoThumbs: _9, dcId: _10!, attributes: _11!)) + } + else { + return nil + } } public static func parse_documentEmpty(_ reader: BufferReader) -> Document? { var _1: Int64? _1 = reader.readInt64() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.Document.documentEmpty(id: _1!) + if _c1 { + return Api.Document.documentEmpty(Cons_documentEmpty(id: _1!)) + } + else { + return nil + } } - } } public extension Api { enum DocumentAttribute: TypeConstructorDescription { + public class Cons_documentAttributeAudio { + public var flags: Int32 + public var duration: Int32 + public var title: String? + public var performer: String? + public var waveform: Buffer? + public init(flags: Int32, duration: Int32, title: String?, performer: String?, waveform: Buffer?) { + self.flags = flags + self.duration = duration + self.title = title + self.performer = performer + self.waveform = waveform + } + } + public class Cons_documentAttributeCustomEmoji { + public var flags: Int32 + public var alt: String + public var stickerset: Api.InputStickerSet + public init(flags: Int32, alt: String, stickerset: Api.InputStickerSet) { + self.flags = flags + self.alt = alt + self.stickerset = stickerset + } + } + public class Cons_documentAttributeFilename { + public var fileName: String + public init(fileName: String) { + self.fileName = fileName + } + } + public class Cons_documentAttributeImageSize { + public var w: Int32 + public var h: Int32 + public init(w: Int32, h: Int32) { + self.w = w + self.h = h + } + } + public class Cons_documentAttributeSticker { + public var flags: Int32 + public var alt: String + public var stickerset: Api.InputStickerSet + public var maskCoords: Api.MaskCoords? + public init(flags: Int32, alt: String, stickerset: Api.InputStickerSet, maskCoords: Api.MaskCoords?) { + self.flags = flags + self.alt = alt + self.stickerset = stickerset + self.maskCoords = maskCoords + } + } + public class Cons_documentAttributeVideo { + public var flags: Int32 + public var duration: Double + public var w: Int32 + public var h: Int32 + public var preloadPrefixSize: Int32? + public var videoStartTs: Double? + public var videoCodec: String? + public init(flags: Int32, duration: Double, w: Int32, h: Int32, preloadPrefixSize: Int32?, videoStartTs: Double?, videoCodec: String?) { + self.flags = flags + self.duration = duration + self.w = w + self.h = h + self.preloadPrefixSize = preloadPrefixSize + self.videoStartTs = videoStartTs + self.videoCodec = videoCodec + } + } case documentAttributeAnimated - case documentAttributeAudio(flags: Int32, duration: Int32, title: String?, performer: String?, waveform: Buffer?) - case documentAttributeCustomEmoji(flags: Int32, alt: String, stickerset: Api.InputStickerSet) - case documentAttributeFilename(fileName: String) + case documentAttributeAudio(Cons_documentAttributeAudio) + case documentAttributeCustomEmoji(Cons_documentAttributeCustomEmoji) + case documentAttributeFilename(Cons_documentAttributeFilename) case documentAttributeHasStickers - case documentAttributeImageSize(w: Int32, h: Int32) - case documentAttributeSticker(flags: Int32, alt: String, stickerset: Api.InputStickerSet, maskCoords: Api.MaskCoords?) - case documentAttributeVideo(flags: Int32, duration: Double, w: Int32, h: Int32, preloadPrefixSize: Int32?, videoStartTs: Double?, videoCodec: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .documentAttributeAnimated: - if boxed { - buffer.appendInt32(297109817) - } - - break - case .documentAttributeAudio(let flags, let duration, let title, let performer, let waveform): - if boxed { - buffer.appendInt32(-1739392570) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(duration, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(performer!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeBytes(waveform!, buffer: buffer, boxed: false)} - break - case .documentAttributeCustomEmoji(let flags, let alt, let stickerset): - if boxed { - buffer.appendInt32(-48981863) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(alt, buffer: buffer, boxed: false) - stickerset.serialize(buffer, true) - break - case .documentAttributeFilename(let fileName): - if boxed { - buffer.appendInt32(358154344) - } - serializeString(fileName, buffer: buffer, boxed: false) - break - case .documentAttributeHasStickers: - if boxed { - buffer.appendInt32(-1744710921) - } - - break - case .documentAttributeImageSize(let w, let h): - if boxed { - buffer.appendInt32(1815593308) - } - serializeInt32(w, buffer: buffer, boxed: false) - serializeInt32(h, buffer: buffer, boxed: false) - break - case .documentAttributeSticker(let flags, let alt, let stickerset, let maskCoords): - if boxed { - buffer.appendInt32(1662637586) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(alt, buffer: buffer, boxed: false) - stickerset.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {maskCoords!.serialize(buffer, true)} - break - case .documentAttributeVideo(let flags, let duration, let w, let h, let preloadPrefixSize, let videoStartTs, let videoCodec): - if boxed { - buffer.appendInt32(1137015880) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeDouble(duration, buffer: buffer, boxed: false) - serializeInt32(w, buffer: buffer, boxed: false) - serializeInt32(h, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(preloadPrefixSize!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeDouble(videoStartTs!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeString(videoCodec!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .documentAttributeAnimated: + case documentAttributeImageSize(Cons_documentAttributeImageSize) + case documentAttributeSticker(Cons_documentAttributeSticker) + case documentAttributeVideo(Cons_documentAttributeVideo) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .documentAttributeAnimated: + if boxed { + buffer.appendInt32(297109817) + } + break + case .documentAttributeAudio(let _data): + if boxed { + buffer.appendInt32(-1739392570) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.duration, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.performer!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeBytes(_data.waveform!, buffer: buffer, boxed: false) + } + break + case .documentAttributeCustomEmoji(let _data): + if boxed { + buffer.appendInt32(-48981863) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.alt, buffer: buffer, boxed: false) + _data.stickerset.serialize(buffer, true) + break + case .documentAttributeFilename(let _data): + if boxed { + buffer.appendInt32(358154344) + } + serializeString(_data.fileName, buffer: buffer, boxed: false) + break + case .documentAttributeHasStickers: + if boxed { + buffer.appendInt32(-1744710921) + } + break + case .documentAttributeImageSize(let _data): + if boxed { + buffer.appendInt32(1815593308) + } + serializeInt32(_data.w, buffer: buffer, boxed: false) + serializeInt32(_data.h, buffer: buffer, boxed: false) + break + case .documentAttributeSticker(let _data): + if boxed { + buffer.appendInt32(1662637586) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.alt, buffer: buffer, boxed: false) + _data.stickerset.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.maskCoords!.serialize(buffer, true) + } + break + case .documentAttributeVideo(let _data): + if boxed { + buffer.appendInt32(1137015880) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeDouble(_data.duration, buffer: buffer, boxed: false) + serializeInt32(_data.w, buffer: buffer, boxed: false) + serializeInt32(_data.h, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.preloadPrefixSize!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeDouble(_data.videoStartTs!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeString(_data.videoCodec!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .documentAttributeAnimated: return ("documentAttributeAnimated", []) - case .documentAttributeAudio(let flags, let duration, let title, let performer, let waveform): - return ("documentAttributeAudio", [("flags", flags as Any), ("duration", duration as Any), ("title", title as Any), ("performer", performer as Any), ("waveform", waveform as Any)]) - case .documentAttributeCustomEmoji(let flags, let alt, let stickerset): - return ("documentAttributeCustomEmoji", [("flags", flags as Any), ("alt", alt as Any), ("stickerset", stickerset as Any)]) - case .documentAttributeFilename(let fileName): - return ("documentAttributeFilename", [("fileName", fileName as Any)]) - case .documentAttributeHasStickers: + case .documentAttributeAudio(let _data): + return ("documentAttributeAudio", [("flags", _data.flags as Any), ("duration", _data.duration as Any), ("title", _data.title as Any), ("performer", _data.performer as Any), ("waveform", _data.waveform as Any)]) + case .documentAttributeCustomEmoji(let _data): + return ("documentAttributeCustomEmoji", [("flags", _data.flags as Any), ("alt", _data.alt as Any), ("stickerset", _data.stickerset as Any)]) + case .documentAttributeFilename(let _data): + return ("documentAttributeFilename", [("fileName", _data.fileName as Any)]) + case .documentAttributeHasStickers: return ("documentAttributeHasStickers", []) - case .documentAttributeImageSize(let w, let h): - return ("documentAttributeImageSize", [("w", w as Any), ("h", h as Any)]) - case .documentAttributeSticker(let flags, let alt, let stickerset, let maskCoords): - return ("documentAttributeSticker", [("flags", flags as Any), ("alt", alt as Any), ("stickerset", stickerset as Any), ("maskCoords", maskCoords as Any)]) - case .documentAttributeVideo(let flags, let duration, let w, let h, let preloadPrefixSize, let videoStartTs, let videoCodec): - return ("documentAttributeVideo", [("flags", flags as Any), ("duration", duration as Any), ("w", w as Any), ("h", h as Any), ("preloadPrefixSize", preloadPrefixSize as Any), ("videoStartTs", videoStartTs as Any), ("videoCodec", videoCodec as Any)]) - } - } - + case .documentAttributeImageSize(let _data): + return ("documentAttributeImageSize", [("w", _data.w as Any), ("h", _data.h as Any)]) + case .documentAttributeSticker(let _data): + return ("documentAttributeSticker", [("flags", _data.flags as Any), ("alt", _data.alt as Any), ("stickerset", _data.stickerset as Any), ("maskCoords", _data.maskCoords as Any)]) + case .documentAttributeVideo(let _data): + return ("documentAttributeVideo", [("flags", _data.flags as Any), ("duration", _data.duration as Any), ("w", _data.w as Any), ("h", _data.h as Any), ("preloadPrefixSize", _data.preloadPrefixSize as Any), ("videoStartTs", _data.videoStartTs as Any), ("videoCodec", _data.videoCodec as Any)]) + } + } + public static func parse_documentAttributeAnimated(_ reader: BufferReader) -> DocumentAttribute? { return Api.DocumentAttribute.documentAttributeAnimated } @@ -256,22 +382,28 @@ public extension Api { var _2: Int32? _2 = reader.readInt32() var _3: String? - if Int(_1!) & Int(1 << 0) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = parseString(reader) + } var _4: String? - if Int(_1!) & Int(1 << 1) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = parseString(reader) + } var _5: Buffer? - if Int(_1!) & Int(1 << 2) != 0 {_5 = parseBytes(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _5 = parseBytes(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 2) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.DocumentAttribute.documentAttributeAudio(flags: _1!, duration: _2!, title: _3, performer: _4, waveform: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.DocumentAttribute.documentAttributeAudio(Cons_documentAttributeAudio(flags: _1!, duration: _2!, title: _3, performer: _4, waveform: _5)) + } + else { + return nil + } } public static func parse_documentAttributeCustomEmoji(_ reader: BufferReader) -> DocumentAttribute? { var _1: Int32? @@ -285,17 +417,23 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.DocumentAttribute.documentAttributeCustomEmoji(flags: _1!, alt: _2!, stickerset: _3!) + if _c1 && _c2 && _c3 { + return Api.DocumentAttribute.documentAttributeCustomEmoji(Cons_documentAttributeCustomEmoji(flags: _1!, alt: _2!, stickerset: _3!)) + } + else { + return nil + } } public static func parse_documentAttributeFilename(_ reader: BufferReader) -> DocumentAttribute? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.DocumentAttribute.documentAttributeFilename(fileName: _1!) + if _c1 { + return Api.DocumentAttribute.documentAttributeFilename(Cons_documentAttributeFilename(fileName: _1!)) + } + else { + return nil + } } public static func parse_documentAttributeHasStickers(_ reader: BufferReader) -> DocumentAttribute? { return Api.DocumentAttribute.documentAttributeHasStickers @@ -307,9 +445,12 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.DocumentAttribute.documentAttributeImageSize(w: _1!, h: _2!) + if _c1 && _c2 { + return Api.DocumentAttribute.documentAttributeImageSize(Cons_documentAttributeImageSize(w: _1!, h: _2!)) + } + else { + return nil + } } public static func parse_documentAttributeSticker(_ reader: BufferReader) -> DocumentAttribute? { var _1: Int32? @@ -321,18 +462,21 @@ public extension Api { _3 = Api.parse(reader, signature: signature) as? Api.InputStickerSet } var _4: Api.MaskCoords? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.MaskCoords - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.MaskCoords + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.DocumentAttribute.documentAttributeSticker(flags: _1!, alt: _2!, stickerset: _3!, maskCoords: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.DocumentAttribute.documentAttributeSticker(Cons_documentAttributeSticker(flags: _1!, alt: _2!, stickerset: _3!, maskCoords: _4)) + } + else { + return nil + } } public static func parse_documentAttributeVideo(_ reader: BufferReader) -> DocumentAttribute? { var _1: Int32? @@ -344,11 +488,17 @@ public extension Api { var _4: Int32? _4 = reader.readInt32() var _5: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _5 = reader.readInt32() + } var _6: Double? - if Int(_1!) & Int(1 << 4) != 0 {_6 = reader.readDouble() } + if Int(_1!) & Int(1 << 4) != 0 { + _6 = reader.readDouble() + } var _7: String? - if Int(_1!) & Int(1 << 5) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 5) != 0 { + _7 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -356,86 +506,133 @@ public extension Api { let _c5 = (Int(_1!) & Int(1 << 2) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 4) == 0) || _6 != nil let _c7 = (Int(_1!) & Int(1 << 5) == 0) || _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.DocumentAttribute.documentAttributeVideo(flags: _1!, duration: _2!, w: _3!, h: _4!, preloadPrefixSize: _5, videoStartTs: _6, videoCodec: _7) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.DocumentAttribute.documentAttributeVideo(Cons_documentAttributeVideo(flags: _1!, duration: _2!, w: _3!, h: _4!, preloadPrefixSize: _5, videoStartTs: _6, videoCodec: _7)) + } + else { + return nil + } } - } } public extension Api { indirect enum DraftMessage: TypeConstructorDescription { - case draftMessage(flags: Int32, replyTo: Api.InputReplyTo?, message: String, entities: [Api.MessageEntity]?, media: Api.InputMedia?, date: Int32, effect: Int64?, suggestedPost: Api.SuggestedPost?) - case draftMessageEmpty(flags: Int32, date: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .draftMessage(let flags, let replyTo, let message, let entities, let media, let date, let effect, let suggestedPost): - if boxed { - buffer.appendInt32(-1763006997) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {replyTo!.serialize(buffer, true)} - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { + public class Cons_draftMessage { + public var flags: Int32 + public var replyTo: Api.InputReplyTo? + public var message: String + public var entities: [Api.MessageEntity]? + public var media: Api.InputMedia? + public var date: Int32 + public var effect: Int64? + public var suggestedPost: Api.SuggestedPost? + public init(flags: Int32, replyTo: Api.InputReplyTo?, message: String, entities: [Api.MessageEntity]?, media: Api.InputMedia?, date: Int32, effect: Int64?, suggestedPost: Api.SuggestedPost?) { + self.flags = flags + self.replyTo = replyTo + self.message = message + self.entities = entities + self.media = media + self.date = date + self.effect = effect + self.suggestedPost = suggestedPost + } + } + public class Cons_draftMessageEmpty { + public var flags: Int32 + public var date: Int32? + public init(flags: Int32, date: Int32?) { + self.flags = flags + self.date = date + } + } + case draftMessage(Cons_draftMessage) + case draftMessageEmpty(Cons_draftMessageEmpty) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .draftMessage(let _data): + if boxed { + buffer.appendInt32(-1763006997) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 4) != 0 { + _data.replyTo!.serialize(buffer, true) + } + serializeString(_data.message, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 5) != 0 {media!.serialize(buffer, true)} - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 7) != 0 {serializeInt64(effect!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {suggestedPost!.serialize(buffer, true)} - break - case .draftMessageEmpty(let flags, let date): - if boxed { - buffer.appendInt32(453805082) } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(date!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .draftMessage(let flags, let replyTo, let message, let entities, let media, let date, let effect, let suggestedPost): - return ("draftMessage", [("flags", flags as Any), ("replyTo", replyTo as Any), ("message", message as Any), ("entities", entities as Any), ("media", media as Any), ("date", date as Any), ("effect", effect as Any), ("suggestedPost", suggestedPost as Any)]) - case .draftMessageEmpty(let flags, let date): - return ("draftMessageEmpty", [("flags", flags as Any), ("date", date as Any)]) - } - } - + } + if Int(_data.flags) & Int(1 << 5) != 0 { + _data.media!.serialize(buffer, true) + } + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 7) != 0 { + serializeInt64(_data.effect!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + _data.suggestedPost!.serialize(buffer, true) + } + break + case .draftMessageEmpty(let _data): + if boxed { + buffer.appendInt32(453805082) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.date!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .draftMessage(let _data): + return ("draftMessage", [("flags", _data.flags as Any), ("replyTo", _data.replyTo as Any), ("message", _data.message as Any), ("entities", _data.entities as Any), ("media", _data.media as Any), ("date", _data.date as Any), ("effect", _data.effect as Any), ("suggestedPost", _data.suggestedPost as Any)]) + case .draftMessageEmpty(let _data): + return ("draftMessageEmpty", [("flags", _data.flags as Any), ("date", _data.date as Any)]) + } + } + public static func parse_draftMessage(_ reader: BufferReader) -> DraftMessage? { var _1: Int32? _1 = reader.readInt32() var _2: Api.InputReplyTo? - if Int(_1!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.InputReplyTo - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.InputReplyTo + } + } var _3: String? _3 = parseString(reader) var _4: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 3) != 0 {if let _ = reader.readInt32() { - _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let _ = reader.readInt32() { + _4 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } var _5: Api.InputMedia? - if Int(_1!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.InputMedia - } } + if Int(_1!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.InputMedia + } + } var _6: Int32? _6 = reader.readInt32() var _7: Int64? - if Int(_1!) & Int(1 << 7) != 0 {_7 = reader.readInt64() } + if Int(_1!) & Int(1 << 7) != 0 { + _7 = reader.readInt64() + } var _8: Api.SuggestedPost? - if Int(_1!) & Int(1 << 8) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.SuggestedPost - } } + if Int(_1!) & Int(1 << 8) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.SuggestedPost + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 4) == 0) || _2 != nil let _c3 = _3 != nil @@ -444,135 +641,171 @@ public extension Api { let _c6 = _6 != nil let _c7 = (Int(_1!) & Int(1 << 7) == 0) || _7 != nil let _c8 = (Int(_1!) & Int(1 << 8) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.DraftMessage.draftMessage(flags: _1!, replyTo: _2, message: _3!, entities: _4, media: _5, date: _6!, effect: _7, suggestedPost: _8) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.DraftMessage.draftMessage(Cons_draftMessage(flags: _1!, replyTo: _2, message: _3!, entities: _4, media: _5, date: _6!, effect: _7, suggestedPost: _8)) + } + else { + return nil + } } public static func parse_draftMessageEmpty(_ reader: BufferReader) -> DraftMessage? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.DraftMessage.draftMessageEmpty(flags: _1!, date: _2) + if _c1 && _c2 { + return Api.DraftMessage.draftMessageEmpty(Cons_draftMessageEmpty(flags: _1!, date: _2)) + } + else { + return nil + } } - } } public extension Api { enum EmailVerification: TypeConstructorDescription { - case emailVerificationApple(token: String) - case emailVerificationCode(code: String) - case emailVerificationGoogle(token: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .emailVerificationApple(let token): - if boxed { - buffer.appendInt32(-1764723459) - } - serializeString(token, buffer: buffer, boxed: false) - break - case .emailVerificationCode(let code): - if boxed { - buffer.appendInt32(-1842457175) - } - serializeString(code, buffer: buffer, boxed: false) - break - case .emailVerificationGoogle(let token): - if boxed { - buffer.appendInt32(-611279166) - } - serializeString(token, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .emailVerificationApple(let token): - return ("emailVerificationApple", [("token", token as Any)]) - case .emailVerificationCode(let code): - return ("emailVerificationCode", [("code", code as Any)]) - case .emailVerificationGoogle(let token): - return ("emailVerificationGoogle", [("token", token as Any)]) - } - } - + public class Cons_emailVerificationApple { + public var token: String + public init(token: String) { + self.token = token + } + } + public class Cons_emailVerificationCode { + public var code: String + public init(code: String) { + self.code = code + } + } + public class Cons_emailVerificationGoogle { + public var token: String + public init(token: String) { + self.token = token + } + } + case emailVerificationApple(Cons_emailVerificationApple) + case emailVerificationCode(Cons_emailVerificationCode) + case emailVerificationGoogle(Cons_emailVerificationGoogle) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .emailVerificationApple(let _data): + if boxed { + buffer.appendInt32(-1764723459) + } + serializeString(_data.token, buffer: buffer, boxed: false) + break + case .emailVerificationCode(let _data): + if boxed { + buffer.appendInt32(-1842457175) + } + serializeString(_data.code, buffer: buffer, boxed: false) + break + case .emailVerificationGoogle(let _data): + if boxed { + buffer.appendInt32(-611279166) + } + serializeString(_data.token, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .emailVerificationApple(let _data): + return ("emailVerificationApple", [("token", _data.token as Any)]) + case .emailVerificationCode(let _data): + return ("emailVerificationCode", [("code", _data.code as Any)]) + case .emailVerificationGoogle(let _data): + return ("emailVerificationGoogle", [("token", _data.token as Any)]) + } + } + public static func parse_emailVerificationApple(_ reader: BufferReader) -> EmailVerification? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.EmailVerification.emailVerificationApple(token: _1!) + if _c1 { + return Api.EmailVerification.emailVerificationApple(Cons_emailVerificationApple(token: _1!)) + } + else { + return nil + } } public static func parse_emailVerificationCode(_ reader: BufferReader) -> EmailVerification? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.EmailVerification.emailVerificationCode(code: _1!) + if _c1 { + return Api.EmailVerification.emailVerificationCode(Cons_emailVerificationCode(code: _1!)) + } + else { + return nil + } } public static func parse_emailVerificationGoogle(_ reader: BufferReader) -> EmailVerification? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.EmailVerification.emailVerificationGoogle(token: _1!) + if _c1 { + return Api.EmailVerification.emailVerificationGoogle(Cons_emailVerificationGoogle(token: _1!)) + } + else { + return nil + } } - } } public extension Api { enum EmailVerifyPurpose: TypeConstructorDescription { + public class Cons_emailVerifyPurposeLoginSetup { + public var phoneNumber: String + public var phoneCodeHash: String + public init(phoneNumber: String, phoneCodeHash: String) { + self.phoneNumber = phoneNumber + self.phoneCodeHash = phoneCodeHash + } + } case emailVerifyPurposeLoginChange - case emailVerifyPurposeLoginSetup(phoneNumber: String, phoneCodeHash: String) + case emailVerifyPurposeLoginSetup(Cons_emailVerifyPurposeLoginSetup) case emailVerifyPurposePassport - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .emailVerifyPurposeLoginChange: - if boxed { - buffer.appendInt32(1383932651) - } - - break - case .emailVerifyPurposeLoginSetup(let phoneNumber, let phoneCodeHash): - if boxed { - buffer.appendInt32(1128644211) - } - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(phoneCodeHash, buffer: buffer, boxed: false) - break - case .emailVerifyPurposePassport: - if boxed { - buffer.appendInt32(-1141565819) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .emailVerifyPurposeLoginChange: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .emailVerifyPurposeLoginChange: + if boxed { + buffer.appendInt32(1383932651) + } + break + case .emailVerifyPurposeLoginSetup(let _data): + if boxed { + buffer.appendInt32(1128644211) + } + serializeString(_data.phoneNumber, buffer: buffer, boxed: false) + serializeString(_data.phoneCodeHash, buffer: buffer, boxed: false) + break + case .emailVerifyPurposePassport: + if boxed { + buffer.appendInt32(-1141565819) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .emailVerifyPurposeLoginChange: return ("emailVerifyPurposeLoginChange", []) - case .emailVerifyPurposeLoginSetup(let phoneNumber, let phoneCodeHash): - return ("emailVerifyPurposeLoginSetup", [("phoneNumber", phoneNumber as Any), ("phoneCodeHash", phoneCodeHash as Any)]) - case .emailVerifyPurposePassport: + case .emailVerifyPurposeLoginSetup(let _data): + return ("emailVerifyPurposeLoginSetup", [("phoneNumber", _data.phoneNumber as Any), ("phoneCodeHash", _data.phoneCodeHash as Any)]) + case .emailVerifyPurposePassport: return ("emailVerifyPurposePassport", []) - } - } - + } + } + public static func parse_emailVerifyPurposeLoginChange(_ reader: BufferReader) -> EmailVerifyPurpose? { return Api.EmailVerifyPurpose.emailVerifyPurposeLoginChange } @@ -583,69 +816,99 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.EmailVerifyPurpose.emailVerifyPurposeLoginSetup(phoneNumber: _1!, phoneCodeHash: _2!) + if _c1 && _c2 { + return Api.EmailVerifyPurpose.emailVerifyPurposeLoginSetup(Cons_emailVerifyPurposeLoginSetup(phoneNumber: _1!, phoneCodeHash: _2!)) + } + else { + return nil + } } public static func parse_emailVerifyPurposePassport(_ reader: BufferReader) -> EmailVerifyPurpose? { return Api.EmailVerifyPurpose.emailVerifyPurposePassport } - } } public extension Api { enum EmojiGroup: TypeConstructorDescription { - case emojiGroup(title: String, iconEmojiId: Int64, emoticons: [String]) - case emojiGroupGreeting(title: String, iconEmojiId: Int64, emoticons: [String]) - case emojiGroupPremium(title: String, iconEmojiId: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .emojiGroup(let title, let iconEmojiId, let emoticons): - if boxed { - buffer.appendInt32(2056961449) - } - serializeString(title, buffer: buffer, boxed: false) - serializeInt64(iconEmojiId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(emoticons.count)) - for item in emoticons { - serializeString(item, buffer: buffer, boxed: false) - } - break - case .emojiGroupGreeting(let title, let iconEmojiId, let emoticons): - if boxed { - buffer.appendInt32(-2133693241) - } - serializeString(title, buffer: buffer, boxed: false) - serializeInt64(iconEmojiId, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(emoticons.count)) - for item in emoticons { - serializeString(item, buffer: buffer, boxed: false) - } - break - case .emojiGroupPremium(let title, let iconEmojiId): - if boxed { - buffer.appendInt32(154914612) - } - serializeString(title, buffer: buffer, boxed: false) - serializeInt64(iconEmojiId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .emojiGroup(let title, let iconEmojiId, let emoticons): - return ("emojiGroup", [("title", title as Any), ("iconEmojiId", iconEmojiId as Any), ("emoticons", emoticons as Any)]) - case .emojiGroupGreeting(let title, let iconEmojiId, let emoticons): - return ("emojiGroupGreeting", [("title", title as Any), ("iconEmojiId", iconEmojiId as Any), ("emoticons", emoticons as Any)]) - case .emojiGroupPremium(let title, let iconEmojiId): - return ("emojiGroupPremium", [("title", title as Any), ("iconEmojiId", iconEmojiId as Any)]) - } - } - + public class Cons_emojiGroup { + public var title: String + public var iconEmojiId: Int64 + public var emoticons: [String] + public init(title: String, iconEmojiId: Int64, emoticons: [String]) { + self.title = title + self.iconEmojiId = iconEmojiId + self.emoticons = emoticons + } + } + public class Cons_emojiGroupGreeting { + public var title: String + public var iconEmojiId: Int64 + public var emoticons: [String] + public init(title: String, iconEmojiId: Int64, emoticons: [String]) { + self.title = title + self.iconEmojiId = iconEmojiId + self.emoticons = emoticons + } + } + public class Cons_emojiGroupPremium { + public var title: String + public var iconEmojiId: Int64 + public init(title: String, iconEmojiId: Int64) { + self.title = title + self.iconEmojiId = iconEmojiId + } + } + case emojiGroup(Cons_emojiGroup) + case emojiGroupGreeting(Cons_emojiGroupGreeting) + case emojiGroupPremium(Cons_emojiGroupPremium) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .emojiGroup(let _data): + if boxed { + buffer.appendInt32(2056961449) + } + serializeString(_data.title, buffer: buffer, boxed: false) + serializeInt64(_data.iconEmojiId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.emoticons.count)) + for item in _data.emoticons { + serializeString(item, buffer: buffer, boxed: false) + } + break + case .emojiGroupGreeting(let _data): + if boxed { + buffer.appendInt32(-2133693241) + } + serializeString(_data.title, buffer: buffer, boxed: false) + serializeInt64(_data.iconEmojiId, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.emoticons.count)) + for item in _data.emoticons { + serializeString(item, buffer: buffer, boxed: false) + } + break + case .emojiGroupPremium(let _data): + if boxed { + buffer.appendInt32(154914612) + } + serializeString(_data.title, buffer: buffer, boxed: false) + serializeInt64(_data.iconEmojiId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .emojiGroup(let _data): + return ("emojiGroup", [("title", _data.title as Any), ("iconEmojiId", _data.iconEmojiId as Any), ("emoticons", _data.emoticons as Any)]) + case .emojiGroupGreeting(let _data): + return ("emojiGroupGreeting", [("title", _data.title as Any), ("iconEmojiId", _data.iconEmojiId as Any), ("emoticons", _data.emoticons as Any)]) + case .emojiGroupPremium(let _data): + return ("emojiGroupPremium", [("title", _data.title as Any), ("iconEmojiId", _data.iconEmojiId as Any)]) + } + } + public static func parse_emojiGroup(_ reader: BufferReader) -> EmojiGroup? { var _1: String? _1 = parseString(reader) @@ -658,10 +921,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.EmojiGroup.emojiGroup(title: _1!, iconEmojiId: _2!, emoticons: _3!) + if _c1 && _c2 && _c3 { + return Api.EmojiGroup.emojiGroup(Cons_emojiGroup(title: _1!, iconEmojiId: _2!, emoticons: _3!)) + } + else { + return nil + } } public static func parse_emojiGroupGreeting(_ reader: BufferReader) -> EmojiGroup? { var _1: String? @@ -675,10 +940,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.EmojiGroup.emojiGroupGreeting(title: _1!, iconEmojiId: _2!, emoticons: _3!) + if _c1 && _c2 && _c3 { + return Api.EmojiGroup.emojiGroupGreeting(Cons_emojiGroupGreeting(title: _1!, iconEmojiId: _2!, emoticons: _3!)) + } + else { + return nil + } } public static func parse_emojiGroupPremium(_ reader: BufferReader) -> EmojiGroup? { var _1: String? @@ -687,54 +954,72 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.EmojiGroup.emojiGroupPremium(title: _1!, iconEmojiId: _2!) + if _c1 && _c2 { + return Api.EmojiGroup.emojiGroupPremium(Cons_emojiGroupPremium(title: _1!, iconEmojiId: _2!)) + } + else { + return nil + } } - } } public extension Api { enum EmojiKeyword: TypeConstructorDescription { - case emojiKeyword(keyword: String, emoticons: [String]) - case emojiKeywordDeleted(keyword: String, emoticons: [String]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .emojiKeyword(let keyword, let emoticons): - if boxed { - buffer.appendInt32(-709641735) - } - serializeString(keyword, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(emoticons.count)) - for item in emoticons { - serializeString(item, buffer: buffer, boxed: false) - } - break - case .emojiKeywordDeleted(let keyword, let emoticons): - if boxed { - buffer.appendInt32(594408994) - } - serializeString(keyword, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(emoticons.count)) - for item in emoticons { - serializeString(item, buffer: buffer, boxed: false) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .emojiKeyword(let keyword, let emoticons): - return ("emojiKeyword", [("keyword", keyword as Any), ("emoticons", emoticons as Any)]) - case .emojiKeywordDeleted(let keyword, let emoticons): - return ("emojiKeywordDeleted", [("keyword", keyword as Any), ("emoticons", emoticons as Any)]) - } - } - + public class Cons_emojiKeyword { + public var keyword: String + public var emoticons: [String] + public init(keyword: String, emoticons: [String]) { + self.keyword = keyword + self.emoticons = emoticons + } + } + public class Cons_emojiKeywordDeleted { + public var keyword: String + public var emoticons: [String] + public init(keyword: String, emoticons: [String]) { + self.keyword = keyword + self.emoticons = emoticons + } + } + case emojiKeyword(Cons_emojiKeyword) + case emojiKeywordDeleted(Cons_emojiKeywordDeleted) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .emojiKeyword(let _data): + if boxed { + buffer.appendInt32(-709641735) + } + serializeString(_data.keyword, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.emoticons.count)) + for item in _data.emoticons { + serializeString(item, buffer: buffer, boxed: false) + } + break + case .emojiKeywordDeleted(let _data): + if boxed { + buffer.appendInt32(594408994) + } + serializeString(_data.keyword, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.emoticons.count)) + for item in _data.emoticons { + serializeString(item, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .emojiKeyword(let _data): + return ("emojiKeyword", [("keyword", _data.keyword as Any), ("emoticons", _data.emoticons as Any)]) + case .emojiKeywordDeleted(let _data): + return ("emojiKeywordDeleted", [("keyword", _data.keyword as Any), ("emoticons", _data.emoticons as Any)]) + } + } + public static func parse_emojiKeyword(_ reader: BufferReader) -> EmojiKeyword? { var _1: String? _1 = parseString(reader) @@ -744,9 +1029,12 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.EmojiKeyword.emojiKeyword(keyword: _1!, emoticons: _2!) + if _c1 && _c2 { + return Api.EmojiKeyword.emojiKeyword(Cons_emojiKeyword(keyword: _1!, emoticons: _2!)) + } + else { + return nil + } } public static func parse_emojiKeywordDeleted(_ reader: BufferReader) -> EmojiKeyword? { var _1: String? @@ -757,42 +1045,56 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.EmojiKeyword.emojiKeywordDeleted(keyword: _1!, emoticons: _2!) + if _c1 && _c2 { + return Api.EmojiKeyword.emojiKeywordDeleted(Cons_emojiKeywordDeleted(keyword: _1!, emoticons: _2!)) + } + else { + return nil + } } - } } public extension Api { enum EmojiKeywordsDifference: TypeConstructorDescription { - case emojiKeywordsDifference(langCode: String, fromVersion: Int32, version: Int32, keywords: [Api.EmojiKeyword]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .emojiKeywordsDifference(let langCode, let fromVersion, let version, let keywords): - if boxed { - buffer.appendInt32(1556570557) - } - serializeString(langCode, buffer: buffer, boxed: false) - serializeInt32(fromVersion, buffer: buffer, boxed: false) - serializeInt32(version, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(keywords.count)) - for item in keywords { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .emojiKeywordsDifference(let langCode, let fromVersion, let version, let keywords): - return ("emojiKeywordsDifference", [("langCode", langCode as Any), ("fromVersion", fromVersion as Any), ("version", version as Any), ("keywords", keywords as Any)]) - } - } - + public class Cons_emojiKeywordsDifference { + public var langCode: String + public var fromVersion: Int32 + public var version: Int32 + public var keywords: [Api.EmojiKeyword] + public init(langCode: String, fromVersion: Int32, version: Int32, keywords: [Api.EmojiKeyword]) { + self.langCode = langCode + self.fromVersion = fromVersion + self.version = version + self.keywords = keywords + } + } + case emojiKeywordsDifference(Cons_emojiKeywordsDifference) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .emojiKeywordsDifference(let _data): + if boxed { + buffer.appendInt32(1556570557) + } + serializeString(_data.langCode, buffer: buffer, boxed: false) + serializeInt32(_data.fromVersion, buffer: buffer, boxed: false) + serializeInt32(_data.version, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.keywords.count)) + for item in _data.keywords { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .emojiKeywordsDifference(let _data): + return ("emojiKeywordsDifference", [("langCode", _data.langCode as Any), ("fromVersion", _data.fromVersion as Any), ("version", _data.version as Any), ("keywords", _data.keywords as Any)]) + } + } + public static func parse_emojiKeywordsDifference(_ reader: BufferReader) -> EmojiKeywordsDifference? { var _1: String? _1 = parseString(reader) @@ -808,83 +1110,99 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.EmojiKeywordsDifference.emojiKeywordsDifference(langCode: _1!, fromVersion: _2!, version: _3!, keywords: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.EmojiKeywordsDifference.emojiKeywordsDifference(Cons_emojiKeywordsDifference(langCode: _1!, fromVersion: _2!, version: _3!, keywords: _4!)) + } + else { + return nil + } } - } } public extension Api { enum EmojiLanguage: TypeConstructorDescription { - case emojiLanguage(langCode: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .emojiLanguage(let langCode): - if boxed { - buffer.appendInt32(-1275374751) - } - serializeString(langCode, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .emojiLanguage(let langCode): - return ("emojiLanguage", [("langCode", langCode as Any)]) - } - } - + public class Cons_emojiLanguage { + public var langCode: String + public init(langCode: String) { + self.langCode = langCode + } + } + case emojiLanguage(Cons_emojiLanguage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .emojiLanguage(let _data): + if boxed { + buffer.appendInt32(-1275374751) + } + serializeString(_data.langCode, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .emojiLanguage(let _data): + return ("emojiLanguage", [("langCode", _data.langCode as Any)]) + } + } + public static func parse_emojiLanguage(_ reader: BufferReader) -> EmojiLanguage? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.EmojiLanguage.emojiLanguage(langCode: _1!) + if _c1 { + return Api.EmojiLanguage.emojiLanguage(Cons_emojiLanguage(langCode: _1!)) + } + else { + return nil + } } - } } public extension Api { enum EmojiList: TypeConstructorDescription { - case emojiList(hash: Int64, documentId: [Int64]) + public class Cons_emojiList { + public var hash: Int64 + public var documentId: [Int64] + public init(hash: Int64, documentId: [Int64]) { + self.hash = hash + self.documentId = documentId + } + } + case emojiList(Cons_emojiList) case emojiListNotModified - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .emojiList(let hash, let documentId): - if boxed { - buffer.appendInt32(2048790993) - } - serializeInt64(hash, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(documentId.count)) - for item in documentId { - serializeInt64(item, buffer: buffer, boxed: false) - } - break - case .emojiListNotModified: - if boxed { - buffer.appendInt32(1209970170) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .emojiList(let hash, let documentId): - return ("emojiList", [("hash", hash as Any), ("documentId", documentId as Any)]) - case .emojiListNotModified: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .emojiList(let _data): + if boxed { + buffer.appendInt32(2048790993) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.documentId.count)) + for item in _data.documentId { + serializeInt64(item, buffer: buffer, boxed: false) + } + break + case .emojiListNotModified: + if boxed { + buffer.appendInt32(1209970170) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .emojiList(let _data): + return ("emojiList", [("hash", _data.hash as Any), ("documentId", _data.documentId as Any)]) + case .emojiListNotModified: return ("emojiListNotModified", []) - } - } - + } + } + public static func parse_emojiList(_ reader: BufferReader) -> EmojiList? { var _1: Int64? _1 = reader.readInt64() @@ -894,93 +1212,150 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.EmojiList.emojiList(hash: _1!, documentId: _2!) + if _c1 && _c2 { + return Api.EmojiList.emojiList(Cons_emojiList(hash: _1!, documentId: _2!)) + } + else { + return nil + } } public static func parse_emojiListNotModified(_ reader: BufferReader) -> EmojiList? { return Api.EmojiList.emojiListNotModified } - } } public extension Api { enum EmojiStatus: TypeConstructorDescription { - case emojiStatus(flags: Int32, documentId: Int64, until: Int32?) - case emojiStatusCollectible(flags: Int32, collectibleId: Int64, documentId: Int64, title: String, slug: String, patternDocumentId: Int64, centerColor: Int32, edgeColor: Int32, patternColor: Int32, textColor: Int32, until: Int32?) + public class Cons_emojiStatus { + public var flags: Int32 + public var documentId: Int64 + public var until: Int32? + public init(flags: Int32, documentId: Int64, until: Int32?) { + self.flags = flags + self.documentId = documentId + self.until = until + } + } + public class Cons_emojiStatusCollectible { + public var flags: Int32 + public var collectibleId: Int64 + public var documentId: Int64 + public var title: String + public var slug: String + public var patternDocumentId: Int64 + public var centerColor: Int32 + public var edgeColor: Int32 + public var patternColor: Int32 + public var textColor: Int32 + public var until: Int32? + public init(flags: Int32, collectibleId: Int64, documentId: Int64, title: String, slug: String, patternDocumentId: Int64, centerColor: Int32, edgeColor: Int32, patternColor: Int32, textColor: Int32, until: Int32?) { + self.flags = flags + self.collectibleId = collectibleId + self.documentId = documentId + self.title = title + self.slug = slug + self.patternDocumentId = patternDocumentId + self.centerColor = centerColor + self.edgeColor = edgeColor + self.patternColor = patternColor + self.textColor = textColor + self.until = until + } + } + public class Cons_inputEmojiStatusCollectible { + public var flags: Int32 + public var collectibleId: Int64 + public var until: Int32? + public init(flags: Int32, collectibleId: Int64, until: Int32?) { + self.flags = flags + self.collectibleId = collectibleId + self.until = until + } + } + case emojiStatus(Cons_emojiStatus) + case emojiStatusCollectible(Cons_emojiStatusCollectible) case emojiStatusEmpty - case inputEmojiStatusCollectible(flags: Int32, collectibleId: Int64, until: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .emojiStatus(let flags, let documentId, let until): - if boxed { - buffer.appendInt32(-402717046) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(documentId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(until!, buffer: buffer, boxed: false)} - break - case .emojiStatusCollectible(let flags, let collectibleId, let documentId, let title, let slug, let patternDocumentId, let centerColor, let edgeColor, let patternColor, let textColor, let until): - if boxed { - buffer.appendInt32(1904500795) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(collectibleId, buffer: buffer, boxed: false) - serializeInt64(documentId, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(slug, buffer: buffer, boxed: false) - serializeInt64(patternDocumentId, buffer: buffer, boxed: false) - serializeInt32(centerColor, buffer: buffer, boxed: false) - serializeInt32(edgeColor, buffer: buffer, boxed: false) - serializeInt32(patternColor, buffer: buffer, boxed: false) - serializeInt32(textColor, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(until!, buffer: buffer, boxed: false)} - break - case .emojiStatusEmpty: - if boxed { - buffer.appendInt32(769727150) - } - - break - case .inputEmojiStatusCollectible(let flags, let collectibleId, let until): - if boxed { - buffer.appendInt32(118758847) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(collectibleId, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(until!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .emojiStatus(let flags, let documentId, let until): - return ("emojiStatus", [("flags", flags as Any), ("documentId", documentId as Any), ("until", until as Any)]) - case .emojiStatusCollectible(let flags, let collectibleId, let documentId, let title, let slug, let patternDocumentId, let centerColor, let edgeColor, let patternColor, let textColor, let until): - return ("emojiStatusCollectible", [("flags", flags as Any), ("collectibleId", collectibleId as Any), ("documentId", documentId as Any), ("title", title as Any), ("slug", slug as Any), ("patternDocumentId", patternDocumentId as Any), ("centerColor", centerColor as Any), ("edgeColor", edgeColor as Any), ("patternColor", patternColor as Any), ("textColor", textColor as Any), ("until", until as Any)]) - case .emojiStatusEmpty: + case inputEmojiStatusCollectible(Cons_inputEmojiStatusCollectible) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .emojiStatus(let _data): + if boxed { + buffer.appendInt32(-402717046) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.documentId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.until!, buffer: buffer, boxed: false) + } + break + case .emojiStatusCollectible(let _data): + if boxed { + buffer.appendInt32(1904500795) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.collectibleId, buffer: buffer, boxed: false) + serializeInt64(_data.documentId, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.slug, buffer: buffer, boxed: false) + serializeInt64(_data.patternDocumentId, buffer: buffer, boxed: false) + serializeInt32(_data.centerColor, buffer: buffer, boxed: false) + serializeInt32(_data.edgeColor, buffer: buffer, boxed: false) + serializeInt32(_data.patternColor, buffer: buffer, boxed: false) + serializeInt32(_data.textColor, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.until!, buffer: buffer, boxed: false) + } + break + case .emojiStatusEmpty: + if boxed { + buffer.appendInt32(769727150) + } + break + case .inputEmojiStatusCollectible(let _data): + if boxed { + buffer.appendInt32(118758847) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.collectibleId, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.until!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .emojiStatus(let _data): + return ("emojiStatus", [("flags", _data.flags as Any), ("documentId", _data.documentId as Any), ("until", _data.until as Any)]) + case .emojiStatusCollectible(let _data): + return ("emojiStatusCollectible", [("flags", _data.flags as Any), ("collectibleId", _data.collectibleId as Any), ("documentId", _data.documentId as Any), ("title", _data.title as Any), ("slug", _data.slug as Any), ("patternDocumentId", _data.patternDocumentId as Any), ("centerColor", _data.centerColor as Any), ("edgeColor", _data.edgeColor as Any), ("patternColor", _data.patternColor as Any), ("textColor", _data.textColor as Any), ("until", _data.until as Any)]) + case .emojiStatusEmpty: return ("emojiStatusEmpty", []) - case .inputEmojiStatusCollectible(let flags, let collectibleId, let until): - return ("inputEmojiStatusCollectible", [("flags", flags as Any), ("collectibleId", collectibleId as Any), ("until", until as Any)]) - } - } - + case .inputEmojiStatusCollectible(let _data): + return ("inputEmojiStatusCollectible", [("flags", _data.flags as Any), ("collectibleId", _data.collectibleId as Any), ("until", _data.until as Any)]) + } + } + public static func parse_emojiStatus(_ reader: BufferReader) -> EmojiStatus? { var _1: Int32? _1 = reader.readInt32() var _2: Int64? _2 = reader.readInt64() var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.EmojiStatus.emojiStatus(flags: _1!, documentId: _2!, until: _3) + if _c1 && _c2 && _c3 { + return Api.EmojiStatus.emojiStatus(Cons_emojiStatus(flags: _1!, documentId: _2!, until: _3)) + } + else { + return nil + } } public static func parse_emojiStatusCollectible(_ reader: BufferReader) -> EmojiStatus? { var _1: Int32? @@ -1004,7 +1379,9 @@ public extension Api { var _10: Int32? _10 = reader.readInt32() var _11: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_11 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _11 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -1016,18 +1393,12 @@ public extension Api { let _c9 = _9 != nil let _c10 = _10 != nil let _c11 = (Int(_1!) & Int(1 << 0) == 0) || _11 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - return Api.EmojiStatus.emojiStatusCollectible(flags: _1!, collectibleId: _2!, documentId: _3!, title: _4!, slug: _5!, patternDocumentId: _6!, centerColor: _7!, edgeColor: _8!, patternColor: _9!, textColor: _10!, until: _11) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 { + return Api.EmojiStatus.emojiStatusCollectible(Cons_emojiStatusCollectible(flags: _1!, collectibleId: _2!, documentId: _3!, title: _4!, slug: _5!, patternDocumentId: _6!, centerColor: _7!, edgeColor: _8!, patternColor: _9!, textColor: _10!, until: _11)) + } + else { + return nil + } } public static func parse_emojiStatusEmpty(_ reader: BufferReader) -> EmojiStatus? { return Api.EmojiStatus.emojiStatusEmpty @@ -1038,15 +1409,18 @@ public extension Api { var _2: Int64? _2 = reader.readInt64() var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.EmojiStatus.inputEmojiStatusCollectible(flags: _1!, collectibleId: _2!, until: _3) + if _c1 && _c2 && _c3 { + return Api.EmojiStatus.inputEmojiStatusCollectible(Cons_inputEmojiStatusCollectible(flags: _1!, collectibleId: _2!, until: _3)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api7.swift b/submodules/TelegramApi/Sources/Api7.swift index 2a85bd69..aaa09d35 100644 --- a/submodules/TelegramApi/Sources/Api7.swift +++ b/submodules/TelegramApi/Sources/Api7.swift @@ -1,111 +1,188 @@ public extension Api { enum EmojiURL: TypeConstructorDescription { - case emojiURL(url: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .emojiURL(let url): - if boxed { - buffer.appendInt32(-1519029347) - } - serializeString(url, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .emojiURL(let url): - return ("emojiURL", [("url", url as Any)]) - } - } - + public class Cons_emojiURL { + public var url: String + public init(url: String) { + self.url = url + } + } + case emojiURL(Cons_emojiURL) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .emojiURL(let _data): + if boxed { + buffer.appendInt32(-1519029347) + } + serializeString(_data.url, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .emojiURL(let _data): + return ("emojiURL", [("url", _data.url as Any)]) + } + } + public static func parse_emojiURL(_ reader: BufferReader) -> EmojiURL? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.EmojiURL.emojiURL(url: _1!) + if _c1 { + return Api.EmojiURL.emojiURL(Cons_emojiURL(url: _1!)) + } + else { + return nil + } } - } } public extension Api { enum EncryptedChat: TypeConstructorDescription { - case encryptedChat(id: Int32, accessHash: Int64, date: Int32, adminId: Int64, participantId: Int64, gAOrB: Buffer, keyFingerprint: Int64) - case encryptedChatDiscarded(flags: Int32, id: Int32) - case encryptedChatEmpty(id: Int32) - case encryptedChatRequested(flags: Int32, folderId: Int32?, id: Int32, accessHash: Int64, date: Int32, adminId: Int64, participantId: Int64, gA: Buffer) - case encryptedChatWaiting(id: Int32, accessHash: Int64, date: Int32, adminId: Int64, participantId: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .encryptedChat(let id, let accessHash, let date, let adminId, let participantId, let gAOrB, let keyFingerprint): - if boxed { - buffer.appendInt32(1643173063) - } - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(adminId, buffer: buffer, boxed: false) - serializeInt64(participantId, buffer: buffer, boxed: false) - serializeBytes(gAOrB, buffer: buffer, boxed: false) - serializeInt64(keyFingerprint, buffer: buffer, boxed: false) - break - case .encryptedChatDiscarded(let flags, let id): - if boxed { - buffer.appendInt32(505183301) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - break - case .encryptedChatEmpty(let id): - if boxed { - buffer.appendInt32(-1417756512) - } - serializeInt32(id, buffer: buffer, boxed: false) - break - case .encryptedChatRequested(let flags, let folderId, let id, let accessHash, let date, let adminId, let participantId, let gA): - if boxed { - buffer.appendInt32(1223809356) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(folderId!, buffer: buffer, boxed: false)} - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(adminId, buffer: buffer, boxed: false) - serializeInt64(participantId, buffer: buffer, boxed: false) - serializeBytes(gA, buffer: buffer, boxed: false) - break - case .encryptedChatWaiting(let id, let accessHash, let date, let adminId, let participantId): - if boxed { - buffer.appendInt32(1722964307) - } - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeInt64(adminId, buffer: buffer, boxed: false) - serializeInt64(participantId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .encryptedChat(let id, let accessHash, let date, let adminId, let participantId, let gAOrB, let keyFingerprint): - return ("encryptedChat", [("id", id as Any), ("accessHash", accessHash as Any), ("date", date as Any), ("adminId", adminId as Any), ("participantId", participantId as Any), ("gAOrB", gAOrB as Any), ("keyFingerprint", keyFingerprint as Any)]) - case .encryptedChatDiscarded(let flags, let id): - return ("encryptedChatDiscarded", [("flags", flags as Any), ("id", id as Any)]) - case .encryptedChatEmpty(let id): - return ("encryptedChatEmpty", [("id", id as Any)]) - case .encryptedChatRequested(let flags, let folderId, let id, let accessHash, let date, let adminId, let participantId, let gA): - return ("encryptedChatRequested", [("flags", flags as Any), ("folderId", folderId as Any), ("id", id as Any), ("accessHash", accessHash as Any), ("date", date as Any), ("adminId", adminId as Any), ("participantId", participantId as Any), ("gA", gA as Any)]) - case .encryptedChatWaiting(let id, let accessHash, let date, let adminId, let participantId): - return ("encryptedChatWaiting", [("id", id as Any), ("accessHash", accessHash as Any), ("date", date as Any), ("adminId", adminId as Any), ("participantId", participantId as Any)]) - } - } - + public class Cons_encryptedChat { + public var id: Int32 + public var accessHash: Int64 + public var date: Int32 + public var adminId: Int64 + public var participantId: Int64 + public var gAOrB: Buffer + public var keyFingerprint: Int64 + public init(id: Int32, accessHash: Int64, date: Int32, adminId: Int64, participantId: Int64, gAOrB: Buffer, keyFingerprint: Int64) { + self.id = id + self.accessHash = accessHash + self.date = date + self.adminId = adminId + self.participantId = participantId + self.gAOrB = gAOrB + self.keyFingerprint = keyFingerprint + } + } + public class Cons_encryptedChatDiscarded { + public var flags: Int32 + public var id: Int32 + public init(flags: Int32, id: Int32) { + self.flags = flags + self.id = id + } + } + public class Cons_encryptedChatEmpty { + public var id: Int32 + public init(id: Int32) { + self.id = id + } + } + public class Cons_encryptedChatRequested { + public var flags: Int32 + public var folderId: Int32? + public var id: Int32 + public var accessHash: Int64 + public var date: Int32 + public var adminId: Int64 + public var participantId: Int64 + public var gA: Buffer + public init(flags: Int32, folderId: Int32?, id: Int32, accessHash: Int64, date: Int32, adminId: Int64, participantId: Int64, gA: Buffer) { + self.flags = flags + self.folderId = folderId + self.id = id + self.accessHash = accessHash + self.date = date + self.adminId = adminId + self.participantId = participantId + self.gA = gA + } + } + public class Cons_encryptedChatWaiting { + public var id: Int32 + public var accessHash: Int64 + public var date: Int32 + public var adminId: Int64 + public var participantId: Int64 + public init(id: Int32, accessHash: Int64, date: Int32, adminId: Int64, participantId: Int64) { + self.id = id + self.accessHash = accessHash + self.date = date + self.adminId = adminId + self.participantId = participantId + } + } + case encryptedChat(Cons_encryptedChat) + case encryptedChatDiscarded(Cons_encryptedChatDiscarded) + case encryptedChatEmpty(Cons_encryptedChatEmpty) + case encryptedChatRequested(Cons_encryptedChatRequested) + case encryptedChatWaiting(Cons_encryptedChatWaiting) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .encryptedChat(let _data): + if boxed { + buffer.appendInt32(1643173063) + } + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.adminId, buffer: buffer, boxed: false) + serializeInt64(_data.participantId, buffer: buffer, boxed: false) + serializeBytes(_data.gAOrB, buffer: buffer, boxed: false) + serializeInt64(_data.keyFingerprint, buffer: buffer, boxed: false) + break + case .encryptedChatDiscarded(let _data): + if boxed { + buffer.appendInt32(505183301) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + break + case .encryptedChatEmpty(let _data): + if boxed { + buffer.appendInt32(-1417756512) + } + serializeInt32(_data.id, buffer: buffer, boxed: false) + break + case .encryptedChatRequested(let _data): + if boxed { + buffer.appendInt32(1223809356) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.folderId!, buffer: buffer, boxed: false) + } + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.adminId, buffer: buffer, boxed: false) + serializeInt64(_data.participantId, buffer: buffer, boxed: false) + serializeBytes(_data.gA, buffer: buffer, boxed: false) + break + case .encryptedChatWaiting(let _data): + if boxed { + buffer.appendInt32(1722964307) + } + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeInt64(_data.adminId, buffer: buffer, boxed: false) + serializeInt64(_data.participantId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .encryptedChat(let _data): + return ("encryptedChat", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("date", _data.date as Any), ("adminId", _data.adminId as Any), ("participantId", _data.participantId as Any), ("gAOrB", _data.gAOrB as Any), ("keyFingerprint", _data.keyFingerprint as Any)]) + case .encryptedChatDiscarded(let _data): + return ("encryptedChatDiscarded", [("flags", _data.flags as Any), ("id", _data.id as Any)]) + case .encryptedChatEmpty(let _data): + return ("encryptedChatEmpty", [("id", _data.id as Any)]) + case .encryptedChatRequested(let _data): + return ("encryptedChatRequested", [("flags", _data.flags as Any), ("folderId", _data.folderId as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("date", _data.date as Any), ("adminId", _data.adminId as Any), ("participantId", _data.participantId as Any), ("gA", _data.gA as Any)]) + case .encryptedChatWaiting(let _data): + return ("encryptedChatWaiting", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("date", _data.date as Any), ("adminId", _data.adminId as Any), ("participantId", _data.participantId as Any)]) + } + } + public static func parse_encryptedChat(_ reader: BufferReader) -> EncryptedChat? { var _1: Int32? _1 = reader.readInt32() @@ -128,14 +205,12 @@ public extension Api { let _c5 = _5 != nil let _c6 = _6 != nil let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.EncryptedChat.encryptedChat(id: _1!, accessHash: _2!, date: _3!, adminId: _4!, participantId: _5!, gAOrB: _6!, keyFingerprint: _7!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.EncryptedChat.encryptedChat(Cons_encryptedChat(id: _1!, accessHash: _2!, date: _3!, adminId: _4!, participantId: _5!, gAOrB: _6!, keyFingerprint: _7!)) + } + else { + return nil + } } public static func parse_encryptedChatDiscarded(_ reader: BufferReader) -> EncryptedChat? { var _1: Int32? @@ -144,22 +219,31 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.EncryptedChat.encryptedChatDiscarded(flags: _1!, id: _2!) + if _c1 && _c2 { + return Api.EncryptedChat.encryptedChatDiscarded(Cons_encryptedChatDiscarded(flags: _1!, id: _2!)) + } + else { + return nil + } } public static func parse_encryptedChatEmpty(_ reader: BufferReader) -> EncryptedChat? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.EncryptedChat.encryptedChatEmpty(id: _1!) + if _c1 { + return Api.EncryptedChat.encryptedChatEmpty(Cons_encryptedChatEmpty(id: _1!)) + } + else { + return nil + } } public static func parse_encryptedChatRequested(_ reader: BufferReader) -> EncryptedChat? { var _1: Int32? _1 = reader.readInt32() var _2: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_2 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _2 = reader.readInt32() + } var _3: Int32? _3 = reader.readInt32() var _4: Int64? @@ -180,15 +264,12 @@ public extension Api { let _c6 = _6 != nil let _c7 = _7 != nil let _c8 = _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.EncryptedChat.encryptedChatRequested(flags: _1!, folderId: _2, id: _3!, accessHash: _4!, date: _5!, adminId: _6!, participantId: _7!, gA: _8!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.EncryptedChat.encryptedChatRequested(Cons_encryptedChatRequested(flags: _1!, folderId: _2, id: _3!, accessHash: _4!, date: _5!, adminId: _6!, participantId: _7!, gA: _8!)) + } + else { + return nil + } } public static func parse_encryptedChatWaiting(_ reader: BufferReader) -> EncryptedChat? { var _1: Int32? @@ -206,51 +287,63 @@ public extension Api { let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.EncryptedChat.encryptedChatWaiting(id: _1!, accessHash: _2!, date: _3!, adminId: _4!, participantId: _5!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.EncryptedChat.encryptedChatWaiting(Cons_encryptedChatWaiting(id: _1!, accessHash: _2!, date: _3!, adminId: _4!, participantId: _5!)) + } + else { + return nil + } } - } } public extension Api { enum EncryptedFile: TypeConstructorDescription { - case encryptedFile(id: Int64, accessHash: Int64, size: Int64, dcId: Int32, keyFingerprint: Int32) + public class Cons_encryptedFile { + public var id: Int64 + public var accessHash: Int64 + public var size: Int64 + public var dcId: Int32 + public var keyFingerprint: Int32 + public init(id: Int64, accessHash: Int64, size: Int64, dcId: Int32, keyFingerprint: Int32) { + self.id = id + self.accessHash = accessHash + self.size = size + self.dcId = dcId + self.keyFingerprint = keyFingerprint + } + } + case encryptedFile(Cons_encryptedFile) case encryptedFileEmpty - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .encryptedFile(let id, let accessHash, let size, let dcId, let keyFingerprint): - if boxed { - buffer.appendInt32(-1476358952) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeInt64(size, buffer: buffer, boxed: false) - serializeInt32(dcId, buffer: buffer, boxed: false) - serializeInt32(keyFingerprint, buffer: buffer, boxed: false) - break - case .encryptedFileEmpty: - if boxed { - buffer.appendInt32(-1038136962) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .encryptedFile(let id, let accessHash, let size, let dcId, let keyFingerprint): - return ("encryptedFile", [("id", id as Any), ("accessHash", accessHash as Any), ("size", size as Any), ("dcId", dcId as Any), ("keyFingerprint", keyFingerprint as Any)]) - case .encryptedFileEmpty: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .encryptedFile(let _data): + if boxed { + buffer.appendInt32(-1476358952) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeInt64(_data.size, buffer: buffer, boxed: false) + serializeInt32(_data.dcId, buffer: buffer, boxed: false) + serializeInt32(_data.keyFingerprint, buffer: buffer, boxed: false) + break + case .encryptedFileEmpty: + if boxed { + buffer.appendInt32(-1038136962) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .encryptedFile(let _data): + return ("encryptedFile", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("size", _data.size as Any), ("dcId", _data.dcId as Any), ("keyFingerprint", _data.keyFingerprint as Any)]) + case .encryptedFileEmpty: return ("encryptedFileEmpty", []) - } - } - + } + } + public static func parse_encryptedFile(_ reader: BufferReader) -> EncryptedFile? { var _1: Int64? _1 = reader.readInt64() @@ -267,57 +360,82 @@ public extension Api { let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.EncryptedFile.encryptedFile(id: _1!, accessHash: _2!, size: _3!, dcId: _4!, keyFingerprint: _5!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.EncryptedFile.encryptedFile(Cons_encryptedFile(id: _1!, accessHash: _2!, size: _3!, dcId: _4!, keyFingerprint: _5!)) + } + else { + return nil + } } public static func parse_encryptedFileEmpty(_ reader: BufferReader) -> EncryptedFile? { return Api.EncryptedFile.encryptedFileEmpty } - } } public extension Api { enum EncryptedMessage: TypeConstructorDescription { - case encryptedMessage(randomId: Int64, chatId: Int32, date: Int32, bytes: Buffer, file: Api.EncryptedFile) - case encryptedMessageService(randomId: Int64, chatId: Int32, date: Int32, bytes: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .encryptedMessage(let randomId, let chatId, let date, let bytes, let file): - if boxed { - buffer.appendInt32(-317144808) - } - serializeInt64(randomId, buffer: buffer, boxed: false) - serializeInt32(chatId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeBytes(bytes, buffer: buffer, boxed: false) - file.serialize(buffer, true) - break - case .encryptedMessageService(let randomId, let chatId, let date, let bytes): - if boxed { - buffer.appendInt32(594758406) - } - serializeInt64(randomId, buffer: buffer, boxed: false) - serializeInt32(chatId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - serializeBytes(bytes, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .encryptedMessage(let randomId, let chatId, let date, let bytes, let file): - return ("encryptedMessage", [("randomId", randomId as Any), ("chatId", chatId as Any), ("date", date as Any), ("bytes", bytes as Any), ("file", file as Any)]) - case .encryptedMessageService(let randomId, let chatId, let date, let bytes): - return ("encryptedMessageService", [("randomId", randomId as Any), ("chatId", chatId as Any), ("date", date as Any), ("bytes", bytes as Any)]) - } - } - + public class Cons_encryptedMessage { + public var randomId: Int64 + public var chatId: Int32 + public var date: Int32 + public var bytes: Buffer + public var file: Api.EncryptedFile + public init(randomId: Int64, chatId: Int32, date: Int32, bytes: Buffer, file: Api.EncryptedFile) { + self.randomId = randomId + self.chatId = chatId + self.date = date + self.bytes = bytes + self.file = file + } + } + public class Cons_encryptedMessageService { + public var randomId: Int64 + public var chatId: Int32 + public var date: Int32 + public var bytes: Buffer + public init(randomId: Int64, chatId: Int32, date: Int32, bytes: Buffer) { + self.randomId = randomId + self.chatId = chatId + self.date = date + self.bytes = bytes + } + } + case encryptedMessage(Cons_encryptedMessage) + case encryptedMessageService(Cons_encryptedMessageService) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .encryptedMessage(let _data): + if boxed { + buffer.appendInt32(-317144808) + } + serializeInt64(_data.randomId, buffer: buffer, boxed: false) + serializeInt32(_data.chatId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeBytes(_data.bytes, buffer: buffer, boxed: false) + _data.file.serialize(buffer, true) + break + case .encryptedMessageService(let _data): + if boxed { + buffer.appendInt32(594758406) + } + serializeInt64(_data.randomId, buffer: buffer, boxed: false) + serializeInt32(_data.chatId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + serializeBytes(_data.bytes, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .encryptedMessage(let _data): + return ("encryptedMessage", [("randomId", _data.randomId as Any), ("chatId", _data.chatId as Any), ("date", _data.date as Any), ("bytes", _data.bytes as Any), ("file", _data.file as Any)]) + case .encryptedMessageService(let _data): + return ("encryptedMessageService", [("randomId", _data.randomId as Any), ("chatId", _data.chatId as Any), ("date", _data.date as Any), ("bytes", _data.bytes as Any)]) + } + } + public static func parse_encryptedMessage(_ reader: BufferReader) -> EncryptedMessage? { var _1: Int64? _1 = reader.readInt64() @@ -336,12 +454,12 @@ public extension Api { let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.EncryptedMessage.encryptedMessage(randomId: _1!, chatId: _2!, date: _3!, bytes: _4!, file: _5!) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.EncryptedMessage.encryptedMessage(Cons_encryptedMessage(randomId: _1!, chatId: _2!, date: _3!, bytes: _4!, file: _5!)) + } + else { + return nil + } } public static func parse_encryptedMessageService(_ reader: BufferReader) -> EncryptedMessage? { var _1: Int64? @@ -356,57 +474,100 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.EncryptedMessage.encryptedMessageService(randomId: _1!, chatId: _2!, date: _3!, bytes: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.EncryptedMessage.encryptedMessageService(Cons_encryptedMessageService(randomId: _1!, chatId: _2!, date: _3!, bytes: _4!)) + } + else { + return nil + } } - } } public extension Api { enum ExportedChatInvite: TypeConstructorDescription { - case chatInviteExported(flags: Int32, link: String, adminId: Int64, date: Int32, startDate: Int32?, expireDate: Int32?, usageLimit: Int32?, usage: Int32?, requested: Int32?, subscriptionExpired: Int32?, title: String?, subscriptionPricing: Api.StarsSubscriptionPricing?) + public class Cons_chatInviteExported { + public var flags: Int32 + public var link: String + public var adminId: Int64 + public var date: Int32 + public var startDate: Int32? + public var expireDate: Int32? + public var usageLimit: Int32? + public var usage: Int32? + public var requested: Int32? + public var subscriptionExpired: Int32? + public var title: String? + public var subscriptionPricing: Api.StarsSubscriptionPricing? + public init(flags: Int32, link: String, adminId: Int64, date: Int32, startDate: Int32?, expireDate: Int32?, usageLimit: Int32?, usage: Int32?, requested: Int32?, subscriptionExpired: Int32?, title: String?, subscriptionPricing: Api.StarsSubscriptionPricing?) { + self.flags = flags + self.link = link + self.adminId = adminId + self.date = date + self.startDate = startDate + self.expireDate = expireDate + self.usageLimit = usageLimit + self.usage = usage + self.requested = requested + self.subscriptionExpired = subscriptionExpired + self.title = title + self.subscriptionPricing = subscriptionPricing + } + } + case chatInviteExported(Cons_chatInviteExported) case chatInvitePublicJoinRequests - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .chatInviteExported(let flags, let link, let adminId, let date, let startDate, let expireDate, let usageLimit, let usage, let requested, let subscriptionExpired, let title, let subscriptionPricing): - if boxed { - buffer.appendInt32(-1574126186) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(link, buffer: buffer, boxed: false) - serializeInt64(adminId, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(startDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(expireDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeInt32(usageLimit!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(usage!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 7) != 0 {serializeInt32(requested!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 10) != 0 {serializeInt32(subscriptionExpired!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 8) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 9) != 0 {subscriptionPricing!.serialize(buffer, true)} - break - case .chatInvitePublicJoinRequests: - if boxed { - buffer.appendInt32(-317687113) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .chatInviteExported(let flags, let link, let adminId, let date, let startDate, let expireDate, let usageLimit, let usage, let requested, let subscriptionExpired, let title, let subscriptionPricing): - return ("chatInviteExported", [("flags", flags as Any), ("link", link as Any), ("adminId", adminId as Any), ("date", date as Any), ("startDate", startDate as Any), ("expireDate", expireDate as Any), ("usageLimit", usageLimit as Any), ("usage", usage as Any), ("requested", requested as Any), ("subscriptionExpired", subscriptionExpired as Any), ("title", title as Any), ("subscriptionPricing", subscriptionPricing as Any)]) - case .chatInvitePublicJoinRequests: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .chatInviteExported(let _data): + if boxed { + buffer.appendInt32(-1574126186) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.link, buffer: buffer, boxed: false) + serializeInt64(_data.adminId, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.startDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.expireDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeInt32(_data.usageLimit!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.usage!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 7) != 0 { + serializeInt32(_data.requested!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 10) != 0 { + serializeInt32(_data.subscriptionExpired!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 8) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 9) != 0 { + _data.subscriptionPricing!.serialize(buffer, true) + } + break + case .chatInvitePublicJoinRequests: + if boxed { + buffer.appendInt32(-317687113) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .chatInviteExported(let _data): + return ("chatInviteExported", [("flags", _data.flags as Any), ("link", _data.link as Any), ("adminId", _data.adminId as Any), ("date", _data.date as Any), ("startDate", _data.startDate as Any), ("expireDate", _data.expireDate as Any), ("usageLimit", _data.usageLimit as Any), ("usage", _data.usage as Any), ("requested", _data.requested as Any), ("subscriptionExpired", _data.subscriptionExpired as Any), ("title", _data.title as Any), ("subscriptionPricing", _data.subscriptionPricing as Any)]) + case .chatInvitePublicJoinRequests: return ("chatInvitePublicJoinRequests", []) - } - } - + } + } + public static func parse_chatInviteExported(_ reader: BufferReader) -> ExportedChatInvite? { var _1: Int32? _1 = reader.readInt32() @@ -417,23 +578,39 @@ public extension Api { var _4: Int32? _4 = reader.readInt32() var _5: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _5 = reader.readInt32() + } var _6: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _6 = reader.readInt32() + } var _7: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_7 = reader.readInt32() } + if Int(_1!) & Int(1 << 2) != 0 { + _7 = reader.readInt32() + } var _8: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_8 = reader.readInt32() } + if Int(_1!) & Int(1 << 3) != 0 { + _8 = reader.readInt32() + } var _9: Int32? - if Int(_1!) & Int(1 << 7) != 0 {_9 = reader.readInt32() } + if Int(_1!) & Int(1 << 7) != 0 { + _9 = reader.readInt32() + } var _10: Int32? - if Int(_1!) & Int(1 << 10) != 0 {_10 = reader.readInt32() } + if Int(_1!) & Int(1 << 10) != 0 { + _10 = reader.readInt32() + } var _11: String? - if Int(_1!) & Int(1 << 8) != 0 {_11 = parseString(reader) } + if Int(_1!) & Int(1 << 8) != 0 { + _11 = parseString(reader) + } var _12: Api.StarsSubscriptionPricing? - if Int(_1!) & Int(1 << 9) != 0 {if let signature = reader.readInt32() { - _12 = Api.parse(reader, signature: signature) as? Api.StarsSubscriptionPricing - } } + if Int(_1!) & Int(1 << 9) != 0 { + if let signature = reader.readInt32() { + _12 = Api.parse(reader, signature: signature) as? Api.StarsSubscriptionPricing + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -446,55 +623,59 @@ public extension Api { let _c10 = (Int(_1!) & Int(1 << 10) == 0) || _10 != nil let _c11 = (Int(_1!) & Int(1 << 8) == 0) || _11 != nil let _c12 = (Int(_1!) & Int(1 << 9) == 0) || _12 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - return Api.ExportedChatInvite.chatInviteExported(flags: _1!, link: _2!, adminId: _3!, date: _4!, startDate: _5, expireDate: _6, usageLimit: _7, usage: _8, requested: _9, subscriptionExpired: _10, title: _11, subscriptionPricing: _12) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 { + return Api.ExportedChatInvite.chatInviteExported(Cons_chatInviteExported(flags: _1!, link: _2!, adminId: _3!, date: _4!, startDate: _5, expireDate: _6, usageLimit: _7, usage: _8, requested: _9, subscriptionExpired: _10, title: _11, subscriptionPricing: _12)) + } + else { + return nil + } } public static func parse_chatInvitePublicJoinRequests(_ reader: BufferReader) -> ExportedChatInvite? { return Api.ExportedChatInvite.chatInvitePublicJoinRequests } - } } public extension Api { enum ExportedChatlistInvite: TypeConstructorDescription { - case exportedChatlistInvite(flags: Int32, title: String, url: String, peers: [Api.Peer]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .exportedChatlistInvite(let flags, let title, let url, let peers): - if boxed { - buffer.appendInt32(206668204) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(peers.count)) - for item in peers { - item.serialize(buffer, true) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .exportedChatlistInvite(let flags, let title, let url, let peers): - return ("exportedChatlistInvite", [("flags", flags as Any), ("title", title as Any), ("url", url as Any), ("peers", peers as Any)]) - } - } - + public class Cons_exportedChatlistInvite { + public var flags: Int32 + public var title: String + public var url: String + public var peers: [Api.Peer] + public init(flags: Int32, title: String, url: String, peers: [Api.Peer]) { + self.flags = flags + self.title = title + self.url = url + self.peers = peers + } + } + case exportedChatlistInvite(Cons_exportedChatlistInvite) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .exportedChatlistInvite(let _data): + if boxed { + buffer.appendInt32(206668204) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.peers.count)) + for item in _data.peers { + item.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .exportedChatlistInvite(let _data): + return ("exportedChatlistInvite", [("flags", _data.flags as Any), ("title", _data.title as Any), ("url", _data.url as Any), ("peers", _data.peers as Any)]) + } + } + public static func parse_exportedChatlistInvite(_ reader: BufferReader) -> ExportedChatlistInvite? { var _1: Int32? _1 = reader.readInt32() @@ -510,38 +691,46 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.ExportedChatlistInvite.exportedChatlistInvite(flags: _1!, title: _2!, url: _3!, peers: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.ExportedChatlistInvite.exportedChatlistInvite(Cons_exportedChatlistInvite(flags: _1!, title: _2!, url: _3!, peers: _4!)) + } + else { + return nil + } } - } } public extension Api { enum ExportedContactToken: TypeConstructorDescription { - case exportedContactToken(url: String, expires: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .exportedContactToken(let url, let expires): - if boxed { - buffer.appendInt32(1103040667) - } - serializeString(url, buffer: buffer, boxed: false) - serializeInt32(expires, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .exportedContactToken(let url, let expires): - return ("exportedContactToken", [("url", url as Any), ("expires", expires as Any)]) - } - } - + public class Cons_exportedContactToken { + public var url: String + public var expires: Int32 + public init(url: String, expires: Int32) { + self.url = url + self.expires = expires + } + } + case exportedContactToken(Cons_exportedContactToken) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .exportedContactToken(let _data): + if boxed { + buffer.appendInt32(1103040667) + } + serializeString(_data.url, buffer: buffer, boxed: false) + serializeInt32(_data.expires, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .exportedContactToken(let _data): + return ("exportedContactToken", [("url", _data.url as Any), ("expires", _data.expires as Any)]) + } + } + public static func parse_exportedContactToken(_ reader: BufferReader) -> ExportedContactToken? { var _1: String? _1 = parseString(reader) @@ -549,36 +738,46 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ExportedContactToken.exportedContactToken(url: _1!, expires: _2!) + if _c1 && _c2 { + return Api.ExportedContactToken.exportedContactToken(Cons_exportedContactToken(url: _1!, expires: _2!)) + } + else { + return nil + } } - } } public extension Api { enum ExportedMessageLink: TypeConstructorDescription { - case exportedMessageLink(link: String, html: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .exportedMessageLink(let link, let html): - if boxed { - buffer.appendInt32(1571494644) - } - serializeString(link, buffer: buffer, boxed: false) - serializeString(html, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .exportedMessageLink(let link, let html): - return ("exportedMessageLink", [("link", link as Any), ("html", html as Any)]) - } - } - + public class Cons_exportedMessageLink { + public var link: String + public var html: String + public init(link: String, html: String) { + self.link = link + self.html = html + } + } + case exportedMessageLink(Cons_exportedMessageLink) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .exportedMessageLink(let _data): + if boxed { + buffer.appendInt32(1571494644) + } + serializeString(_data.link, buffer: buffer, boxed: false) + serializeString(_data.html, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .exportedMessageLink(let _data): + return ("exportedMessageLink", [("link", _data.link as Any), ("html", _data.html as Any)]) + } + } + public static func parse_exportedMessageLink(_ reader: BufferReader) -> ExportedMessageLink? { var _1: String? _1 = parseString(reader) @@ -586,118 +785,159 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ExportedMessageLink.exportedMessageLink(link: _1!, html: _2!) + if _c1 && _c2 { + return Api.ExportedMessageLink.exportedMessageLink(Cons_exportedMessageLink(link: _1!, html: _2!)) + } + else { + return nil + } } - } } public extension Api { enum ExportedStoryLink: TypeConstructorDescription { - case exportedStoryLink(link: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .exportedStoryLink(let link): - if boxed { - buffer.appendInt32(1070138683) - } - serializeString(link, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .exportedStoryLink(let link): - return ("exportedStoryLink", [("link", link as Any)]) - } - } - + public class Cons_exportedStoryLink { + public var link: String + public init(link: String) { + self.link = link + } + } + case exportedStoryLink(Cons_exportedStoryLink) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .exportedStoryLink(let _data): + if boxed { + buffer.appendInt32(1070138683) + } + serializeString(_data.link, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .exportedStoryLink(let _data): + return ("exportedStoryLink", [("link", _data.link as Any)]) + } + } + public static func parse_exportedStoryLink(_ reader: BufferReader) -> ExportedStoryLink? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ExportedStoryLink.exportedStoryLink(link: _1!) + if _c1 { + return Api.ExportedStoryLink.exportedStoryLink(Cons_exportedStoryLink(link: _1!)) + } + else { + return nil + } } - } } public extension Api { enum FactCheck: TypeConstructorDescription { - case factCheck(flags: Int32, country: String?, text: Api.TextWithEntities?, hash: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .factCheck(let flags, let country, let text, let hash): - if boxed { - buffer.appendInt32(-1197736753) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeString(country!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {text!.serialize(buffer, true)} - serializeInt64(hash, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .factCheck(let flags, let country, let text, let hash): - return ("factCheck", [("flags", flags as Any), ("country", country as Any), ("text", text as Any), ("hash", hash as Any)]) - } - } - + public class Cons_factCheck { + public var flags: Int32 + public var country: String? + public var text: Api.TextWithEntities? + public var hash: Int64 + public init(flags: Int32, country: String?, text: Api.TextWithEntities?, hash: Int64) { + self.flags = flags + self.country = country + self.text = text + self.hash = hash + } + } + case factCheck(Cons_factCheck) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .factCheck(let _data): + if boxed { + buffer.appendInt32(-1197736753) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.country!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.text!.serialize(buffer, true) + } + serializeInt64(_data.hash, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .factCheck(let _data): + return ("factCheck", [("flags", _data.flags as Any), ("country", _data.country as Any), ("text", _data.text as Any), ("hash", _data.hash as Any)]) + } + } + public static func parse_factCheck(_ reader: BufferReader) -> FactCheck? { var _1: Int32? _1 = reader.readInt32() var _2: String? - if Int(_1!) & Int(1 << 1) != 0 {_2 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _2 = parseString(reader) + } var _3: Api.TextWithEntities? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.TextWithEntities - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.TextWithEntities + } + } var _4: Int64? _4 = reader.readInt64() let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 1) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.FactCheck.factCheck(flags: _1!, country: _2, text: _3, hash: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.FactCheck.factCheck(Cons_factCheck(flags: _1!, country: _2, text: _3, hash: _4!)) + } + else { + return nil + } } - } } public extension Api { enum FileHash: TypeConstructorDescription { - case fileHash(offset: Int64, limit: Int32, hash: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .fileHash(let offset, let limit, let hash): - if boxed { - buffer.appendInt32(-207944868) - } - serializeInt64(offset, buffer: buffer, boxed: false) - serializeInt32(limit, buffer: buffer, boxed: false) - serializeBytes(hash, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .fileHash(let offset, let limit, let hash): - return ("fileHash", [("offset", offset as Any), ("limit", limit as Any), ("hash", hash as Any)]) - } - } - + public class Cons_fileHash { + public var offset: Int64 + public var limit: Int32 + public var hash: Buffer + public init(offset: Int64, limit: Int32, hash: Buffer) { + self.offset = offset + self.limit = limit + self.hash = hash + } + } + case fileHash(Cons_fileHash) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .fileHash(let _data): + if boxed { + buffer.appendInt32(-207944868) + } + serializeInt64(_data.offset, buffer: buffer, boxed: false) + serializeInt32(_data.limit, buffer: buffer, boxed: false) + serializeBytes(_data.hash, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .fileHash(let _data): + return ("fileHash", [("offset", _data.offset as Any), ("limit", _data.limit as Any), ("hash", _data.hash as Any)]) + } + } + public static func parse_fileHash(_ reader: BufferReader) -> FileHash? { var _1: Int64? _1 = reader.readInt64() @@ -708,39 +948,54 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.FileHash.fileHash(offset: _1!, limit: _2!, hash: _3!) + if _c1 && _c2 && _c3 { + return Api.FileHash.fileHash(Cons_fileHash(offset: _1!, limit: _2!, hash: _3!)) + } + else { + return nil + } } - } } public extension Api { enum Folder: TypeConstructorDescription { - case folder(flags: Int32, id: Int32, title: String, photo: Api.ChatPhoto?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .folder(let flags, let id, let title, let photo): - if boxed { - buffer.appendInt32(-11252123) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {photo!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .folder(let flags, let id, let title, let photo): - return ("folder", [("flags", flags as Any), ("id", id as Any), ("title", title as Any), ("photo", photo as Any)]) - } - } - + public class Cons_folder { + public var flags: Int32 + public var id: Int32 + public var title: String + public var photo: Api.ChatPhoto? + public init(flags: Int32, id: Int32, title: String, photo: Api.ChatPhoto?) { + self.flags = flags + self.id = id + self.title = title + self.photo = photo + } + } + case folder(Cons_folder) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .folder(let _data): + if boxed { + buffer.appendInt32(-11252123) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.photo!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .folder(let _data): + return ("folder", [("flags", _data.flags as Any), ("id", _data.id as Any), ("title", _data.title as Any), ("photo", _data.photo as Any)]) + } + } + public static func parse_folder(_ reader: BufferReader) -> Folder? { var _1: Int32? _1 = reader.readInt32() @@ -749,45 +1004,55 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: Api.ChatPhoto? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.ChatPhoto - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.ChatPhoto + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 3) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.Folder.folder(flags: _1!, id: _2!, title: _3!, photo: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.Folder.folder(Cons_folder(flags: _1!, id: _2!, title: _3!, photo: _4)) + } + else { + return nil + } } - } } public extension Api { enum FolderPeer: TypeConstructorDescription { - case folderPeer(peer: Api.Peer, folderId: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .folderPeer(let peer, let folderId): - if boxed { - buffer.appendInt32(-373643672) - } - peer.serialize(buffer, true) - serializeInt32(folderId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .folderPeer(let peer, let folderId): - return ("folderPeer", [("peer", peer as Any), ("folderId", folderId as Any)]) - } - } - + public class Cons_folderPeer { + public var peer: Api.Peer + public var folderId: Int32 + public init(peer: Api.Peer, folderId: Int32) { + self.peer = peer + self.folderId = folderId + } + } + case folderPeer(Cons_folderPeer) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .folderPeer(let _data): + if boxed { + buffer.appendInt32(-373643672) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.folderId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .folderPeer(let _data): + return ("folderPeer", [("peer", _data.peer as Any), ("folderId", _data.folderId as Any)]) + } + } + public static func parse_folderPeer(_ reader: BufferReader) -> FolderPeer? { var _1: Api.Peer? if let signature = reader.readInt32() { @@ -797,59 +1062,107 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.FolderPeer.folderPeer(peer: _1!, folderId: _2!) + if _c1 && _c2 { + return Api.FolderPeer.folderPeer(Cons_folderPeer(peer: _1!, folderId: _2!)) + } + else { + return nil + } } - } } public extension Api { indirect enum ForumTopic: TypeConstructorDescription { - case forumTopic(flags: Int32, id: Int32, date: Int32, peer: Api.Peer, title: String, iconColor: Int32, iconEmojiId: Int64?, topMessage: Int32, readInboxMaxId: Int32, readOutboxMaxId: Int32, unreadCount: Int32, unreadMentionsCount: Int32, unreadReactionsCount: Int32, fromId: Api.Peer, notifySettings: Api.PeerNotifySettings, draft: Api.DraftMessage?) - case forumTopicDeleted(id: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .forumTopic(let flags, let id, let date, let peer, let title, let iconColor, let iconEmojiId, let topMessage, let readInboxMaxId, let readOutboxMaxId, let unreadCount, let unreadMentionsCount, let unreadReactionsCount, let fromId, let notifySettings, let draft): - if boxed { - buffer.appendInt32(-838922550) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt32(date, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeString(title, buffer: buffer, boxed: false) - serializeInt32(iconColor, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(iconEmojiId!, buffer: buffer, boxed: false)} - serializeInt32(topMessage, buffer: buffer, boxed: false) - serializeInt32(readInboxMaxId, buffer: buffer, boxed: false) - serializeInt32(readOutboxMaxId, buffer: buffer, boxed: false) - serializeInt32(unreadCount, buffer: buffer, boxed: false) - serializeInt32(unreadMentionsCount, buffer: buffer, boxed: false) - serializeInt32(unreadReactionsCount, buffer: buffer, boxed: false) - fromId.serialize(buffer, true) - notifySettings.serialize(buffer, true) - if Int(flags) & Int(1 << 4) != 0 {draft!.serialize(buffer, true)} - break - case .forumTopicDeleted(let id): - if boxed { - buffer.appendInt32(37687451) - } - serializeInt32(id, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .forumTopic(let flags, let id, let date, let peer, let title, let iconColor, let iconEmojiId, let topMessage, let readInboxMaxId, let readOutboxMaxId, let unreadCount, let unreadMentionsCount, let unreadReactionsCount, let fromId, let notifySettings, let draft): - return ("forumTopic", [("flags", flags as Any), ("id", id as Any), ("date", date as Any), ("peer", peer as Any), ("title", title as Any), ("iconColor", iconColor as Any), ("iconEmojiId", iconEmojiId as Any), ("topMessage", topMessage as Any), ("readInboxMaxId", readInboxMaxId as Any), ("readOutboxMaxId", readOutboxMaxId as Any), ("unreadCount", unreadCount as Any), ("unreadMentionsCount", unreadMentionsCount as Any), ("unreadReactionsCount", unreadReactionsCount as Any), ("fromId", fromId as Any), ("notifySettings", notifySettings as Any), ("draft", draft as Any)]) - case .forumTopicDeleted(let id): - return ("forumTopicDeleted", [("id", id as Any)]) - } - } - + public class Cons_forumTopic { + public var flags: Int32 + public var id: Int32 + public var date: Int32 + public var peer: Api.Peer + public var title: String + public var iconColor: Int32 + public var iconEmojiId: Int64? + public var topMessage: Int32 + public var readInboxMaxId: Int32 + public var readOutboxMaxId: Int32 + public var unreadCount: Int32 + public var unreadMentionsCount: Int32 + public var unreadReactionsCount: Int32 + public var fromId: Api.Peer + public var notifySettings: Api.PeerNotifySettings + public var draft: Api.DraftMessage? + public init(flags: Int32, id: Int32, date: Int32, peer: Api.Peer, title: String, iconColor: Int32, iconEmojiId: Int64?, topMessage: Int32, readInboxMaxId: Int32, readOutboxMaxId: Int32, unreadCount: Int32, unreadMentionsCount: Int32, unreadReactionsCount: Int32, fromId: Api.Peer, notifySettings: Api.PeerNotifySettings, draft: Api.DraftMessage?) { + self.flags = flags + self.id = id + self.date = date + self.peer = peer + self.title = title + self.iconColor = iconColor + self.iconEmojiId = iconEmojiId + self.topMessage = topMessage + self.readInboxMaxId = readInboxMaxId + self.readOutboxMaxId = readOutboxMaxId + self.unreadCount = unreadCount + self.unreadMentionsCount = unreadMentionsCount + self.unreadReactionsCount = unreadReactionsCount + self.fromId = fromId + self.notifySettings = notifySettings + self.draft = draft + } + } + public class Cons_forumTopicDeleted { + public var id: Int32 + public init(id: Int32) { + self.id = id + } + } + case forumTopic(Cons_forumTopic) + case forumTopicDeleted(Cons_forumTopicDeleted) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .forumTopic(let _data): + if boxed { + buffer.appendInt32(-838922550) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.date, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeInt32(_data.iconColor, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.iconEmojiId!, buffer: buffer, boxed: false) + } + serializeInt32(_data.topMessage, buffer: buffer, boxed: false) + serializeInt32(_data.readInboxMaxId, buffer: buffer, boxed: false) + serializeInt32(_data.readOutboxMaxId, buffer: buffer, boxed: false) + serializeInt32(_data.unreadCount, buffer: buffer, boxed: false) + serializeInt32(_data.unreadMentionsCount, buffer: buffer, boxed: false) + serializeInt32(_data.unreadReactionsCount, buffer: buffer, boxed: false) + _data.fromId.serialize(buffer, true) + _data.notifySettings.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 4) != 0 { + _data.draft!.serialize(buffer, true) + } + break + case .forumTopicDeleted(let _data): + if boxed { + buffer.appendInt32(37687451) + } + serializeInt32(_data.id, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .forumTopic(let _data): + return ("forumTopic", [("flags", _data.flags as Any), ("id", _data.id as Any), ("date", _data.date as Any), ("peer", _data.peer as Any), ("title", _data.title as Any), ("iconColor", _data.iconColor as Any), ("iconEmojiId", _data.iconEmojiId as Any), ("topMessage", _data.topMessage as Any), ("readInboxMaxId", _data.readInboxMaxId as Any), ("readOutboxMaxId", _data.readOutboxMaxId as Any), ("unreadCount", _data.unreadCount as Any), ("unreadMentionsCount", _data.unreadMentionsCount as Any), ("unreadReactionsCount", _data.unreadReactionsCount as Any), ("fromId", _data.fromId as Any), ("notifySettings", _data.notifySettings as Any), ("draft", _data.draft as Any)]) + case .forumTopicDeleted(let _data): + return ("forumTopicDeleted", [("id", _data.id as Any)]) + } + } + public static func parse_forumTopic(_ reader: BufferReader) -> ForumTopic? { var _1: Int32? _1 = reader.readInt32() @@ -866,7 +1179,9 @@ public extension Api { var _6: Int32? _6 = reader.readInt32() var _7: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_7 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _7 = reader.readInt64() + } var _8: Int32? _8 = reader.readInt32() var _9: Int32? @@ -888,9 +1203,11 @@ public extension Api { _15 = Api.parse(reader, signature: signature) as? Api.PeerNotifySettings } var _16: Api.DraftMessage? - if Int(_1!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _16 = Api.parse(reader, signature: signature) as? Api.DraftMessage - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _16 = Api.parse(reader, signature: signature) as? Api.DraftMessage + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -907,57 +1224,57 @@ public extension Api { let _c14 = _14 != nil let _c15 = _15 != nil let _c16 = (Int(_1!) & Int(1 << 4) == 0) || _16 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - if !_c15 { return nil } - if !_c16 { return nil } - return Api.ForumTopic.forumTopic(flags: _1!, id: _2!, date: _3!, peer: _4!, title: _5!, iconColor: _6!, iconEmojiId: _7, topMessage: _8!, readInboxMaxId: _9!, readOutboxMaxId: _10!, unreadCount: _11!, unreadMentionsCount: _12!, unreadReactionsCount: _13!, fromId: _14!, notifySettings: _15!, draft: _16) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 { + return Api.ForumTopic.forumTopic(Cons_forumTopic(flags: _1!, id: _2!, date: _3!, peer: _4!, title: _5!, iconColor: _6!, iconEmojiId: _7, topMessage: _8!, readInboxMaxId: _9!, readOutboxMaxId: _10!, unreadCount: _11!, unreadMentionsCount: _12!, unreadReactionsCount: _13!, fromId: _14!, notifySettings: _15!, draft: _16)) + } + else { + return nil + } } public static func parse_forumTopicDeleted(_ reader: BufferReader) -> ForumTopic? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.ForumTopic.forumTopicDeleted(id: _1!) + if _c1 { + return Api.ForumTopic.forumTopicDeleted(Cons_forumTopicDeleted(id: _1!)) + } + else { + return nil + } } - } } public extension Api { indirect enum FoundStory: TypeConstructorDescription { - case foundStory(peer: Api.Peer, story: Api.StoryItem) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .foundStory(let peer, let story): - if boxed { - buffer.appendInt32(-394605632) - } - peer.serialize(buffer, true) - story.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .foundStory(let peer, let story): - return ("foundStory", [("peer", peer as Any), ("story", story as Any)]) - } - } - + public class Cons_foundStory { + public var peer: Api.Peer + public var story: Api.StoryItem + public init(peer: Api.Peer, story: Api.StoryItem) { + self.peer = peer + self.story = story + } + } + case foundStory(Cons_foundStory) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .foundStory(let _data): + if boxed { + buffer.appendInt32(-394605632) + } + _data.peer.serialize(buffer, true) + _data.story.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .foundStory(let _data): + return ("foundStory", [("peer", _data.peer as Any), ("story", _data.story as Any)]) + } + } + public static func parse_foundStory(_ reader: BufferReader) -> FoundStory? { var _1: Api.Peer? if let signature = reader.readInt32() { @@ -969,42 +1286,66 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.FoundStory.foundStory(peer: _1!, story: _2!) + if _c1 && _c2 { + return Api.FoundStory.foundStory(Cons_foundStory(peer: _1!, story: _2!)) + } + else { + return nil + } } - } } public extension Api { enum Game: TypeConstructorDescription { - case game(flags: Int32, id: Int64, accessHash: Int64, shortName: String, title: String, description: String, photo: Api.Photo, document: Api.Document?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .game(let flags, let id, let accessHash, let shortName, let title, let description, let photo, let document): - if boxed { - buffer.appendInt32(-1107729093) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeString(shortName, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(description, buffer: buffer, boxed: false) - photo.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {document!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .game(let flags, let id, let accessHash, let shortName, let title, let description, let photo, let document): - return ("game", [("flags", flags as Any), ("id", id as Any), ("accessHash", accessHash as Any), ("shortName", shortName as Any), ("title", title as Any), ("description", description as Any), ("photo", photo as Any), ("document", document as Any)]) - } - } - + public class Cons_game { + public var flags: Int32 + public var id: Int64 + public var accessHash: Int64 + public var shortName: String + public var title: String + public var description: String + public var photo: Api.Photo + public var document: Api.Document? + public init(flags: Int32, id: Int64, accessHash: Int64, shortName: String, title: String, description: String, photo: Api.Photo, document: Api.Document?) { + self.flags = flags + self.id = id + self.accessHash = accessHash + self.shortName = shortName + self.title = title + self.description = description + self.photo = photo + self.document = document + } + } + case game(Cons_game) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .game(let _data): + if boxed { + buffer.appendInt32(-1107729093) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeString(_data.shortName, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.description, buffer: buffer, boxed: false) + _data.photo.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.document!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .game(let _data): + return ("game", [("flags", _data.flags as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("shortName", _data.shortName as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("photo", _data.photo as Any), ("document", _data.document as Any)]) + } + } + public static func parse_game(_ reader: BufferReader) -> Game? { var _1: Int32? _1 = reader.readInt32() @@ -1023,9 +1364,11 @@ public extension Api { _7 = Api.parse(reader, signature: signature) as? Api.Photo } var _8: Api.Document? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.Document - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.Document + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -1034,54 +1377,65 @@ public extension Api { let _c6 = _6 != nil let _c7 = _7 != nil let _c8 = (Int(_1!) & Int(1 << 0) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.Game.game(flags: _1!, id: _2!, accessHash: _3!, shortName: _4!, title: _5!, description: _6!, photo: _7!, document: _8) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.Game.game(Cons_game(flags: _1!, id: _2!, accessHash: _3!, shortName: _4!, title: _5!, description: _6!, photo: _7!, document: _8)) + } + else { + return nil + } } - } } public extension Api { enum GeoPoint: TypeConstructorDescription { - case geoPoint(flags: Int32, long: Double, lat: Double, accessHash: Int64, accuracyRadius: Int32?) + public class Cons_geoPoint { + public var flags: Int32 + public var long: Double + public var lat: Double + public var accessHash: Int64 + public var accuracyRadius: Int32? + public init(flags: Int32, long: Double, lat: Double, accessHash: Int64, accuracyRadius: Int32?) { + self.flags = flags + self.long = long + self.lat = lat + self.accessHash = accessHash + self.accuracyRadius = accuracyRadius + } + } + case geoPoint(Cons_geoPoint) case geoPointEmpty - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .geoPoint(let flags, let long, let lat, let accessHash, let accuracyRadius): - if boxed { - buffer.appendInt32(-1297942941) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeDouble(long, buffer: buffer, boxed: false) - serializeDouble(lat, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(accuracyRadius!, buffer: buffer, boxed: false)} - break - case .geoPointEmpty: - if boxed { - buffer.appendInt32(286776671) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .geoPoint(let flags, let long, let lat, let accessHash, let accuracyRadius): - return ("geoPoint", [("flags", flags as Any), ("long", long as Any), ("lat", lat as Any), ("accessHash", accessHash as Any), ("accuracyRadius", accuracyRadius as Any)]) - case .geoPointEmpty: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .geoPoint(let _data): + if boxed { + buffer.appendInt32(-1297942941) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeDouble(_data.long, buffer: buffer, boxed: false) + serializeDouble(_data.lat, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.accuracyRadius!, buffer: buffer, boxed: false) + } + break + case .geoPointEmpty: + if boxed { + buffer.appendInt32(286776671) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .geoPoint(let _data): + return ("geoPoint", [("flags", _data.flags as Any), ("long", _data.long as Any), ("lat", _data.lat as Any), ("accessHash", _data.accessHash as Any), ("accuracyRadius", _data.accuracyRadius as Any)]) + case .geoPointEmpty: return ("geoPointEmpty", []) - } - } - + } + } + public static func parse_geoPoint(_ reader: BufferReader) -> GeoPoint? { var _1: Int32? _1 = reader.readInt32() @@ -1092,167 +1446,270 @@ public extension Api { var _4: Int64? _4 = reader.readInt64() var _5: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _5 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 0) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.GeoPoint.geoPoint(flags: _1!, long: _2!, lat: _3!, accessHash: _4!, accuracyRadius: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.GeoPoint.geoPoint(Cons_geoPoint(flags: _1!, long: _2!, lat: _3!, accessHash: _4!, accuracyRadius: _5)) + } + else { + return nil + } } public static func parse_geoPointEmpty(_ reader: BufferReader) -> GeoPoint? { return Api.GeoPoint.geoPointEmpty } - } } public extension Api { enum GeoPointAddress: TypeConstructorDescription { - case geoPointAddress(flags: Int32, countryIso2: String, state: String?, city: String?, street: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .geoPointAddress(let flags, let countryIso2, let state, let city, let street): - if boxed { - buffer.appendInt32(-565420653) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(countryIso2, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {serializeString(state!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeString(city!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(street!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .geoPointAddress(let flags, let countryIso2, let state, let city, let street): - return ("geoPointAddress", [("flags", flags as Any), ("countryIso2", countryIso2 as Any), ("state", state as Any), ("city", city as Any), ("street", street as Any)]) - } - } - + public class Cons_geoPointAddress { + public var flags: Int32 + public var countryIso2: String + public var state: String? + public var city: String? + public var street: String? + public init(flags: Int32, countryIso2: String, state: String?, city: String?, street: String?) { + self.flags = flags + self.countryIso2 = countryIso2 + self.state = state + self.city = city + self.street = street + } + } + case geoPointAddress(Cons_geoPointAddress) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .geoPointAddress(let _data): + if boxed { + buffer.appendInt32(-565420653) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.countryIso2, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeString(_data.state!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.city!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.street!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .geoPointAddress(let _data): + return ("geoPointAddress", [("flags", _data.flags as Any), ("countryIso2", _data.countryIso2 as Any), ("state", _data.state as Any), ("city", _data.city as Any), ("street", _data.street as Any)]) + } + } + public static func parse_geoPointAddress(_ reader: BufferReader) -> GeoPointAddress? { var _1: Int32? _1 = reader.readInt32() var _2: String? _2 = parseString(reader) var _3: String? - if Int(_1!) & Int(1 << 0) != 0 {_3 = parseString(reader) } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = parseString(reader) + } var _4: String? - if Int(_1!) & Int(1 << 1) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = parseString(reader) + } var _5: String? - if Int(_1!) & Int(1 << 2) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _5 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 2) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.GeoPointAddress.geoPointAddress(flags: _1!, countryIso2: _2!, state: _3, city: _4, street: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.GeoPointAddress.geoPointAddress(Cons_geoPointAddress(flags: _1!, countryIso2: _2!, state: _3, city: _4, street: _5)) + } + else { + return nil + } } - } } public extension Api { enum GlobalPrivacySettings: TypeConstructorDescription { - case globalPrivacySettings(flags: Int32, noncontactPeersPaidStars: Int64?, disallowedGifts: Api.DisallowedGiftsSettings?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .globalPrivacySettings(let flags, let noncontactPeersPaidStars, let disallowedGifts): - if boxed { - buffer.appendInt32(-29248689) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 5) != 0 {serializeInt64(noncontactPeersPaidStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 6) != 0 {disallowedGifts!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .globalPrivacySettings(let flags, let noncontactPeersPaidStars, let disallowedGifts): - return ("globalPrivacySettings", [("flags", flags as Any), ("noncontactPeersPaidStars", noncontactPeersPaidStars as Any), ("disallowedGifts", disallowedGifts as Any)]) - } - } - + public class Cons_globalPrivacySettings { + public var flags: Int32 + public var noncontactPeersPaidStars: Int64? + public var disallowedGifts: Api.DisallowedGiftsSettings? + public init(flags: Int32, noncontactPeersPaidStars: Int64?, disallowedGifts: Api.DisallowedGiftsSettings?) { + self.flags = flags + self.noncontactPeersPaidStars = noncontactPeersPaidStars + self.disallowedGifts = disallowedGifts + } + } + case globalPrivacySettings(Cons_globalPrivacySettings) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .globalPrivacySettings(let _data): + if boxed { + buffer.appendInt32(-29248689) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeInt64(_data.noncontactPeersPaidStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + _data.disallowedGifts!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .globalPrivacySettings(let _data): + return ("globalPrivacySettings", [("flags", _data.flags as Any), ("noncontactPeersPaidStars", _data.noncontactPeersPaidStars as Any), ("disallowedGifts", _data.disallowedGifts as Any)]) + } + } + public static func parse_globalPrivacySettings(_ reader: BufferReader) -> GlobalPrivacySettings? { var _1: Int32? _1 = reader.readInt32() var _2: Int64? - if Int(_1!) & Int(1 << 5) != 0 {_2 = reader.readInt64() } + if Int(_1!) & Int(1 << 5) != 0 { + _2 = reader.readInt64() + } var _3: Api.DisallowedGiftsSettings? - if Int(_1!) & Int(1 << 6) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.DisallowedGiftsSettings - } } + if Int(_1!) & Int(1 << 6) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.DisallowedGiftsSettings + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 5) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 6) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.GlobalPrivacySettings.globalPrivacySettings(flags: _1!, noncontactPeersPaidStars: _2, disallowedGifts: _3) + if _c1 && _c2 && _c3 { + return Api.GlobalPrivacySettings.globalPrivacySettings(Cons_globalPrivacySettings(flags: _1!, noncontactPeersPaidStars: _2, disallowedGifts: _3)) + } + else { + return nil + } } - } } public extension Api { enum GroupCall: TypeConstructorDescription { - case groupCall(flags: Int32, id: Int64, accessHash: Int64, participantsCount: Int32, title: String?, streamDcId: Int32?, recordStartDate: Int32?, scheduleDate: Int32?, unmutedVideoCount: Int32?, unmutedVideoLimit: Int32, version: Int32, inviteLink: String?, sendPaidMessagesStars: Int64?, defaultSendAs: Api.Peer?) - case groupCallDiscarded(id: Int64, accessHash: Int64, duration: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .groupCall(let flags, let id, let accessHash, let participantsCount, let title, let streamDcId, let recordStartDate, let scheduleDate, let unmutedVideoCount, let unmutedVideoLimit, let version, let inviteLink, let sendPaidMessagesStars, let defaultSendAs): - if boxed { - buffer.appendInt32(-273500649) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeInt32(participantsCount, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {serializeInt32(streamDcId!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 5) != 0 {serializeInt32(recordStartDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 7) != 0 {serializeInt32(scheduleDate!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 10) != 0 {serializeInt32(unmutedVideoCount!, buffer: buffer, boxed: false)} - serializeInt32(unmutedVideoLimit, buffer: buffer, boxed: false) - serializeInt32(version, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 16) != 0 {serializeString(inviteLink!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 20) != 0 {serializeInt64(sendPaidMessagesStars!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 21) != 0 {defaultSendAs!.serialize(buffer, true)} - break - case .groupCallDiscarded(let id, let accessHash, let duration): - if boxed { - buffer.appendInt32(2004925620) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeInt32(duration, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .groupCall(let flags, let id, let accessHash, let participantsCount, let title, let streamDcId, let recordStartDate, let scheduleDate, let unmutedVideoCount, let unmutedVideoLimit, let version, let inviteLink, let sendPaidMessagesStars, let defaultSendAs): - return ("groupCall", [("flags", flags as Any), ("id", id as Any), ("accessHash", accessHash as Any), ("participantsCount", participantsCount as Any), ("title", title as Any), ("streamDcId", streamDcId as Any), ("recordStartDate", recordStartDate as Any), ("scheduleDate", scheduleDate as Any), ("unmutedVideoCount", unmutedVideoCount as Any), ("unmutedVideoLimit", unmutedVideoLimit as Any), ("version", version as Any), ("inviteLink", inviteLink as Any), ("sendPaidMessagesStars", sendPaidMessagesStars as Any), ("defaultSendAs", defaultSendAs as Any)]) - case .groupCallDiscarded(let id, let accessHash, let duration): - return ("groupCallDiscarded", [("id", id as Any), ("accessHash", accessHash as Any), ("duration", duration as Any)]) - } - } - + public class Cons_groupCall { + public var flags: Int32 + public var id: Int64 + public var accessHash: Int64 + public var participantsCount: Int32 + public var title: String? + public var streamDcId: Int32? + public var recordStartDate: Int32? + public var scheduleDate: Int32? + public var unmutedVideoCount: Int32? + public var unmutedVideoLimit: Int32 + public var version: Int32 + public var inviteLink: String? + public var sendPaidMessagesStars: Int64? + public var defaultSendAs: Api.Peer? + public init(flags: Int32, id: Int64, accessHash: Int64, participantsCount: Int32, title: String?, streamDcId: Int32?, recordStartDate: Int32?, scheduleDate: Int32?, unmutedVideoCount: Int32?, unmutedVideoLimit: Int32, version: Int32, inviteLink: String?, sendPaidMessagesStars: Int64?, defaultSendAs: Api.Peer?) { + self.flags = flags + self.id = id + self.accessHash = accessHash + self.participantsCount = participantsCount + self.title = title + self.streamDcId = streamDcId + self.recordStartDate = recordStartDate + self.scheduleDate = scheduleDate + self.unmutedVideoCount = unmutedVideoCount + self.unmutedVideoLimit = unmutedVideoLimit + self.version = version + self.inviteLink = inviteLink + self.sendPaidMessagesStars = sendPaidMessagesStars + self.defaultSendAs = defaultSendAs + } + } + public class Cons_groupCallDiscarded { + public var id: Int64 + public var accessHash: Int64 + public var duration: Int32 + public init(id: Int64, accessHash: Int64, duration: Int32) { + self.id = id + self.accessHash = accessHash + self.duration = duration + } + } + case groupCall(Cons_groupCall) + case groupCallDiscarded(Cons_groupCallDiscarded) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .groupCall(let _data): + if boxed { + buffer.appendInt32(-273500649) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeInt32(_data.participantsCount, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + serializeInt32(_data.streamDcId!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + serializeInt32(_data.recordStartDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 7) != 0 { + serializeInt32(_data.scheduleDate!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 10) != 0 { + serializeInt32(_data.unmutedVideoCount!, buffer: buffer, boxed: false) + } + serializeInt32(_data.unmutedVideoLimit, buffer: buffer, boxed: false) + serializeInt32(_data.version, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 16) != 0 { + serializeString(_data.inviteLink!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 20) != 0 { + serializeInt64(_data.sendPaidMessagesStars!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 21) != 0 { + _data.defaultSendAs!.serialize(buffer, true) + } + break + case .groupCallDiscarded(let _data): + if boxed { + buffer.appendInt32(2004925620) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeInt32(_data.duration, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .groupCall(let _data): + return ("groupCall", [("flags", _data.flags as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("participantsCount", _data.participantsCount as Any), ("title", _data.title as Any), ("streamDcId", _data.streamDcId as Any), ("recordStartDate", _data.recordStartDate as Any), ("scheduleDate", _data.scheduleDate as Any), ("unmutedVideoCount", _data.unmutedVideoCount as Any), ("unmutedVideoLimit", _data.unmutedVideoLimit as Any), ("version", _data.version as Any), ("inviteLink", _data.inviteLink as Any), ("sendPaidMessagesStars", _data.sendPaidMessagesStars as Any), ("defaultSendAs", _data.defaultSendAs as Any)]) + case .groupCallDiscarded(let _data): + return ("groupCallDiscarded", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("duration", _data.duration as Any)]) + } + } + public static func parse_groupCall(_ reader: BufferReader) -> GroupCall? { var _1: Int32? _1 = reader.readInt32() @@ -1263,27 +1720,43 @@ public extension Api { var _4: Int32? _4 = reader.readInt32() var _5: String? - if Int(_1!) & Int(1 << 3) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 3) != 0 { + _5 = parseString(reader) + } var _6: Int32? - if Int(_1!) & Int(1 << 4) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 4) != 0 { + _6 = reader.readInt32() + } var _7: Int32? - if Int(_1!) & Int(1 << 5) != 0 {_7 = reader.readInt32() } + if Int(_1!) & Int(1 << 5) != 0 { + _7 = reader.readInt32() + } var _8: Int32? - if Int(_1!) & Int(1 << 7) != 0 {_8 = reader.readInt32() } + if Int(_1!) & Int(1 << 7) != 0 { + _8 = reader.readInt32() + } var _9: Int32? - if Int(_1!) & Int(1 << 10) != 0 {_9 = reader.readInt32() } + if Int(_1!) & Int(1 << 10) != 0 { + _9 = reader.readInt32() + } var _10: Int32? _10 = reader.readInt32() var _11: Int32? _11 = reader.readInt32() var _12: String? - if Int(_1!) & Int(1 << 16) != 0 {_12 = parseString(reader) } + if Int(_1!) & Int(1 << 16) != 0 { + _12 = parseString(reader) + } var _13: Int64? - if Int(_1!) & Int(1 << 20) != 0 {_13 = reader.readInt64() } + if Int(_1!) & Int(1 << 20) != 0 { + _13 = reader.readInt64() + } var _14: Api.Peer? - if Int(_1!) & Int(1 << 21) != 0 {if let signature = reader.readInt32() { - _14 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 21) != 0 { + if let signature = reader.readInt32() { + _14 = Api.parse(reader, signature: signature) as? Api.Peer + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -1298,21 +1771,12 @@ public extension Api { let _c12 = (Int(_1!) & Int(1 << 16) == 0) || _12 != nil let _c13 = (Int(_1!) & Int(1 << 20) == 0) || _13 != nil let _c14 = (Int(_1!) & Int(1 << 21) == 0) || _14 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - if !_c12 { return nil } - if !_c13 { return nil } - if !_c14 { return nil } - return Api.GroupCall.groupCall(flags: _1!, id: _2!, accessHash: _3!, participantsCount: _4!, title: _5, streamDcId: _6, recordStartDate: _7, scheduleDate: _8, unmutedVideoCount: _9, unmutedVideoLimit: _10!, version: _11!, inviteLink: _12, sendPaidMessagesStars: _13, defaultSendAs: _14) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 { + return Api.GroupCall.groupCall(Cons_groupCall(flags: _1!, id: _2!, accessHash: _3!, participantsCount: _4!, title: _5, streamDcId: _6, recordStartDate: _7, scheduleDate: _8, unmutedVideoCount: _9, unmutedVideoLimit: _10!, version: _11!, inviteLink: _12, sendPaidMessagesStars: _13, defaultSendAs: _14)) + } + else { + return nil + } } public static func parse_groupCallDiscarded(_ reader: BufferReader) -> GroupCall? { var _1: Int64? @@ -1324,85 +1788,119 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.GroupCall.groupCallDiscarded(id: _1!, accessHash: _2!, duration: _3!) + if _c1 && _c2 && _c3 { + return Api.GroupCall.groupCallDiscarded(Cons_groupCallDiscarded(id: _1!, accessHash: _2!, duration: _3!)) + } + else { + return nil + } } - } } public extension Api { enum GroupCallDonor: TypeConstructorDescription { - case groupCallDonor(flags: Int32, peerId: Api.Peer?, stars: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .groupCallDonor(let flags, let peerId, let stars): - if boxed { - buffer.appendInt32(-297595771) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {peerId!.serialize(buffer, true)} - serializeInt64(stars, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .groupCallDonor(let flags, let peerId, let stars): - return ("groupCallDonor", [("flags", flags as Any), ("peerId", peerId as Any), ("stars", stars as Any)]) - } - } - + public class Cons_groupCallDonor { + public var flags: Int32 + public var peerId: Api.Peer? + public var stars: Int64 + public init(flags: Int32, peerId: Api.Peer?, stars: Int64) { + self.flags = flags + self.peerId = peerId + self.stars = stars + } + } + case groupCallDonor(Cons_groupCallDonor) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .groupCallDonor(let _data): + if boxed { + buffer.appendInt32(-297595771) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.peerId!.serialize(buffer, true) + } + serializeInt64(_data.stars, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .groupCallDonor(let _data): + return ("groupCallDonor", [("flags", _data.flags as Any), ("peerId", _data.peerId as Any), ("stars", _data.stars as Any)]) + } + } + public static func parse_groupCallDonor(_ reader: BufferReader) -> GroupCallDonor? { var _1: Int32? _1 = reader.readInt32() var _2: Api.Peer? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.Peer - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.Peer + } + } var _3: Int64? _3 = reader.readInt64() let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 3) == 0) || _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.GroupCallDonor.groupCallDonor(flags: _1!, peerId: _2, stars: _3!) + if _c1 && _c2 && _c3 { + return Api.GroupCallDonor.groupCallDonor(Cons_groupCallDonor(flags: _1!, peerId: _2, stars: _3!)) + } + else { + return nil + } } - } } public extension Api { enum GroupCallMessage: TypeConstructorDescription { - case groupCallMessage(flags: Int32, id: Int32, fromId: Api.Peer, date: Int32, message: Api.TextWithEntities, paidMessageStars: Int64?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .groupCallMessage(let flags, let id, let fromId, let date, let message, let paidMessageStars): - if boxed { - buffer.appendInt32(445316222) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - fromId.serialize(buffer, true) - serializeInt32(date, buffer: buffer, boxed: false) - message.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt64(paidMessageStars!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .groupCallMessage(let flags, let id, let fromId, let date, let message, let paidMessageStars): - return ("groupCallMessage", [("flags", flags as Any), ("id", id as Any), ("fromId", fromId as Any), ("date", date as Any), ("message", message as Any), ("paidMessageStars", paidMessageStars as Any)]) - } - } - + public class Cons_groupCallMessage { + public var flags: Int32 + public var id: Int32 + public var fromId: Api.Peer + public var date: Int32 + public var message: Api.TextWithEntities + public var paidMessageStars: Int64? + public init(flags: Int32, id: Int32, fromId: Api.Peer, date: Int32, message: Api.TextWithEntities, paidMessageStars: Int64?) { + self.flags = flags + self.id = id + self.fromId = fromId + self.date = date + self.message = message + self.paidMessageStars = paidMessageStars + } + } + case groupCallMessage(Cons_groupCallMessage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .groupCallMessage(let _data): + if boxed { + buffer.appendInt32(445316222) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + _data.fromId.serialize(buffer, true) + serializeInt32(_data.date, buffer: buffer, boxed: false) + _data.message.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt64(_data.paidMessageStars!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .groupCallMessage(let _data): + return ("groupCallMessage", [("flags", _data.flags as Any), ("id", _data.id as Any), ("fromId", _data.fromId as Any), ("date", _data.date as Any), ("message", _data.message as Any), ("paidMessageStars", _data.paidMessageStars as Any)]) + } + } + public static func parse_groupCallMessage(_ reader: BufferReader) -> GroupCallMessage? { var _1: Int32? _1 = reader.readInt32() @@ -1419,21 +1917,21 @@ public extension Api { _5 = Api.parse(reader, signature: signature) as? Api.TextWithEntities } var _6: Int64? - if Int(_1!) & Int(1 << 0) != 0 {_6 = reader.readInt64() } + if Int(_1!) & Int(1 << 0) != 0 { + _6 = reader.readInt64() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.GroupCallMessage.groupCallMessage(flags: _1!, id: _2!, fromId: _3!, date: _4!, message: _5!, paidMessageStars: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.GroupCallMessage.groupCallMessage(Cons_groupCallMessage(flags: _1!, id: _2!, fromId: _3!, date: _4!, message: _5!, paidMessageStars: _6)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api8.swift b/submodules/TelegramApi/Sources/Api8.swift index 78862824..82026a74 100644 --- a/submodules/TelegramApi/Sources/Api8.swift +++ b/submodules/TelegramApi/Sources/Api8.swift @@ -1,35 +1,75 @@ public extension Api { enum GroupCallParticipant: TypeConstructorDescription { - case groupCallParticipant(flags: Int32, peer: Api.Peer, date: Int32, activeDate: Int32?, source: Int32, volume: Int32?, about: String?, raiseHandRating: Int64?, video: Api.GroupCallParticipantVideo?, presentation: Api.GroupCallParticipantVideo?, paidStarsTotal: Int64?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .groupCallParticipant(let flags, let peer, let date, let activeDate, let source, let volume, let about, let raiseHandRating, let video, let presentation, let paidStarsTotal): - if boxed { - buffer.appendInt32(708691884) - } - serializeInt32(flags, buffer: buffer, boxed: false) - peer.serialize(buffer, true) - serializeInt32(date, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(activeDate!, buffer: buffer, boxed: false)} - serializeInt32(source, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 7) != 0 {serializeInt32(volume!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 11) != 0 {serializeString(about!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 13) != 0 {serializeInt64(raiseHandRating!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 6) != 0 {video!.serialize(buffer, true)} - if Int(flags) & Int(1 << 14) != 0 {presentation!.serialize(buffer, true)} - if Int(flags) & Int(1 << 16) != 0 {serializeInt64(paidStarsTotal!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .groupCallParticipant(let flags, let peer, let date, let activeDate, let source, let volume, let about, let raiseHandRating, let video, let presentation, let paidStarsTotal): - return ("groupCallParticipant", [("flags", flags as Any), ("peer", peer as Any), ("date", date as Any), ("activeDate", activeDate as Any), ("source", source as Any), ("volume", volume as Any), ("about", about as Any), ("raiseHandRating", raiseHandRating as Any), ("video", video as Any), ("presentation", presentation as Any), ("paidStarsTotal", paidStarsTotal as Any)]) - } - } - + public class Cons_groupCallParticipant { + public var flags: Int32 + public var peer: Api.Peer + public var date: Int32 + public var activeDate: Int32? + public var source: Int32 + public var volume: Int32? + public var about: String? + public var raiseHandRating: Int64? + public var video: Api.GroupCallParticipantVideo? + public var presentation: Api.GroupCallParticipantVideo? + public var paidStarsTotal: Int64? + public init(flags: Int32, peer: Api.Peer, date: Int32, activeDate: Int32?, source: Int32, volume: Int32?, about: String?, raiseHandRating: Int64?, video: Api.GroupCallParticipantVideo?, presentation: Api.GroupCallParticipantVideo?, paidStarsTotal: Int64?) { + self.flags = flags + self.peer = peer + self.date = date + self.activeDate = activeDate + self.source = source + self.volume = volume + self.about = about + self.raiseHandRating = raiseHandRating + self.video = video + self.presentation = presentation + self.paidStarsTotal = paidStarsTotal + } + } + case groupCallParticipant(Cons_groupCallParticipant) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .groupCallParticipant(let _data): + if boxed { + buffer.appendInt32(708691884) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.peer.serialize(buffer, true) + serializeInt32(_data.date, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.activeDate!, buffer: buffer, boxed: false) + } + serializeInt32(_data.source, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 7) != 0 { + serializeInt32(_data.volume!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 11) != 0 { + serializeString(_data.about!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 13) != 0 { + serializeInt64(_data.raiseHandRating!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 6) != 0 { + _data.video!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 14) != 0 { + _data.presentation!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 16) != 0 { + serializeInt64(_data.paidStarsTotal!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .groupCallParticipant(let _data): + return ("groupCallParticipant", [("flags", _data.flags as Any), ("peer", _data.peer as Any), ("date", _data.date as Any), ("activeDate", _data.activeDate as Any), ("source", _data.source as Any), ("volume", _data.volume as Any), ("about", _data.about as Any), ("raiseHandRating", _data.raiseHandRating as Any), ("video", _data.video as Any), ("presentation", _data.presentation as Any), ("paidStarsTotal", _data.paidStarsTotal as Any)]) + } + } + public static func parse_groupCallParticipant(_ reader: BufferReader) -> GroupCallParticipant? { var _1: Int32? _1 = reader.readInt32() @@ -40,25 +80,39 @@ public extension Api { var _3: Int32? _3 = reader.readInt32() var _4: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 3) != 0 { + _4 = reader.readInt32() + } var _5: Int32? _5 = reader.readInt32() var _6: Int32? - if Int(_1!) & Int(1 << 7) != 0 {_6 = reader.readInt32() } + if Int(_1!) & Int(1 << 7) != 0 { + _6 = reader.readInt32() + } var _7: String? - if Int(_1!) & Int(1 << 11) != 0 {_7 = parseString(reader) } + if Int(_1!) & Int(1 << 11) != 0 { + _7 = parseString(reader) + } var _8: Int64? - if Int(_1!) & Int(1 << 13) != 0 {_8 = reader.readInt64() } + if Int(_1!) & Int(1 << 13) != 0 { + _8 = reader.readInt64() + } var _9: Api.GroupCallParticipantVideo? - if Int(_1!) & Int(1 << 6) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.GroupCallParticipantVideo - } } + if Int(_1!) & Int(1 << 6) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.GroupCallParticipantVideo + } + } var _10: Api.GroupCallParticipantVideo? - if Int(_1!) & Int(1 << 14) != 0 {if let signature = reader.readInt32() { - _10 = Api.parse(reader, signature: signature) as? Api.GroupCallParticipantVideo - } } + if Int(_1!) & Int(1 << 14) != 0 { + if let signature = reader.readInt32() { + _10 = Api.parse(reader, signature: signature) as? Api.GroupCallParticipantVideo + } + } var _11: Int64? - if Int(_1!) & Int(1 << 16) != 0 {_11 = reader.readInt64() } + if Int(_1!) & Int(1 << 16) != 0 { + _11 = reader.readInt64() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -70,51 +124,58 @@ public extension Api { let _c9 = (Int(_1!) & Int(1 << 6) == 0) || _9 != nil let _c10 = (Int(_1!) & Int(1 << 14) == 0) || _10 != nil let _c11 = (Int(_1!) & Int(1 << 16) == 0) || _11 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - if !_c10 { return nil } - if !_c11 { return nil } - return Api.GroupCallParticipant.groupCallParticipant(flags: _1!, peer: _2!, date: _3!, activeDate: _4, source: _5!, volume: _6, about: _7, raiseHandRating: _8, video: _9, presentation: _10, paidStarsTotal: _11) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 { + return Api.GroupCallParticipant.groupCallParticipant(Cons_groupCallParticipant(flags: _1!, peer: _2!, date: _3!, activeDate: _4, source: _5!, volume: _6, about: _7, raiseHandRating: _8, video: _9, presentation: _10, paidStarsTotal: _11)) + } + else { + return nil + } } - } } public extension Api { enum GroupCallParticipantVideo: TypeConstructorDescription { - case groupCallParticipantVideo(flags: Int32, endpoint: String, sourceGroups: [Api.GroupCallParticipantVideoSourceGroup], audioSource: Int32?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .groupCallParticipantVideo(let flags, let endpoint, let sourceGroups, let audioSource): - if boxed { - buffer.appendInt32(1735736008) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(endpoint, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(sourceGroups.count)) - for item in sourceGroups { - item.serialize(buffer, true) - } - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(audioSource!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .groupCallParticipantVideo(let flags, let endpoint, let sourceGroups, let audioSource): - return ("groupCallParticipantVideo", [("flags", flags as Any), ("endpoint", endpoint as Any), ("sourceGroups", sourceGroups as Any), ("audioSource", audioSource as Any)]) - } - } - + public class Cons_groupCallParticipantVideo { + public var flags: Int32 + public var endpoint: String + public var sourceGroups: [Api.GroupCallParticipantVideoSourceGroup] + public var audioSource: Int32? + public init(flags: Int32, endpoint: String, sourceGroups: [Api.GroupCallParticipantVideoSourceGroup], audioSource: Int32?) { + self.flags = flags + self.endpoint = endpoint + self.sourceGroups = sourceGroups + self.audioSource = audioSource + } + } + case groupCallParticipantVideo(Cons_groupCallParticipantVideo) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .groupCallParticipantVideo(let _data): + if boxed { + buffer.appendInt32(1735736008) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.endpoint, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.sourceGroups.count)) + for item in _data.sourceGroups { + item.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.audioSource!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .groupCallParticipantVideo(let _data): + return ("groupCallParticipantVideo", [("flags", _data.flags as Any), ("endpoint", _data.endpoint as Any), ("sourceGroups", _data.sourceGroups as Any), ("audioSource", _data.audioSource as Any)]) + } + } + public static func parse_groupCallParticipantVideo(_ reader: BufferReader) -> GroupCallParticipantVideo? { var _1: Int32? _1 = reader.readInt32() @@ -125,47 +186,57 @@ public extension Api { _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.GroupCallParticipantVideoSourceGroup.self) } var _4: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = reader.readInt32() + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.GroupCallParticipantVideo.groupCallParticipantVideo(flags: _1!, endpoint: _2!, sourceGroups: _3!, audioSource: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.GroupCallParticipantVideo.groupCallParticipantVideo(Cons_groupCallParticipantVideo(flags: _1!, endpoint: _2!, sourceGroups: _3!, audioSource: _4)) + } + else { + return nil + } } - } } public extension Api { enum GroupCallParticipantVideoSourceGroup: TypeConstructorDescription { - case groupCallParticipantVideoSourceGroup(semantics: String, sources: [Int32]) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .groupCallParticipantVideoSourceGroup(let semantics, let sources): - if boxed { - buffer.appendInt32(-592373577) - } - serializeString(semantics, buffer: buffer, boxed: false) - buffer.appendInt32(481674261) - buffer.appendInt32(Int32(sources.count)) - for item in sources { - serializeInt32(item, buffer: buffer, boxed: false) - } - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .groupCallParticipantVideoSourceGroup(let semantics, let sources): - return ("groupCallParticipantVideoSourceGroup", [("semantics", semantics as Any), ("sources", sources as Any)]) - } - } - + public class Cons_groupCallParticipantVideoSourceGroup { + public var semantics: String + public var sources: [Int32] + public init(semantics: String, sources: [Int32]) { + self.semantics = semantics + self.sources = sources + } + } + case groupCallParticipantVideoSourceGroup(Cons_groupCallParticipantVideoSourceGroup) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .groupCallParticipantVideoSourceGroup(let _data): + if boxed { + buffer.appendInt32(-592373577) + } + serializeString(_data.semantics, buffer: buffer, boxed: false) + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.sources.count)) + for item in _data.sources { + serializeInt32(item, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .groupCallParticipantVideoSourceGroup(let _data): + return ("groupCallParticipantVideoSourceGroup", [("semantics", _data.semantics as Any), ("sources", _data.sources as Any)]) + } + } + public static func parse_groupCallParticipantVideoSourceGroup(_ reader: BufferReader) -> GroupCallParticipantVideoSourceGroup? { var _1: String? _1 = parseString(reader) @@ -175,37 +246,49 @@ public extension Api { } let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.GroupCallParticipantVideoSourceGroup.groupCallParticipantVideoSourceGroup(semantics: _1!, sources: _2!) + if _c1 && _c2 { + return Api.GroupCallParticipantVideoSourceGroup.groupCallParticipantVideoSourceGroup(Cons_groupCallParticipantVideoSourceGroup(semantics: _1!, sources: _2!)) + } + else { + return nil + } } - } } public extension Api { enum GroupCallStreamChannel: TypeConstructorDescription { - case groupCallStreamChannel(channel: Int32, scale: Int32, lastTimestampMs: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .groupCallStreamChannel(let channel, let scale, let lastTimestampMs): - if boxed { - buffer.appendInt32(-2132064081) - } - serializeInt32(channel, buffer: buffer, boxed: false) - serializeInt32(scale, buffer: buffer, boxed: false) - serializeInt64(lastTimestampMs, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .groupCallStreamChannel(let channel, let scale, let lastTimestampMs): - return ("groupCallStreamChannel", [("channel", channel as Any), ("scale", scale as Any), ("lastTimestampMs", lastTimestampMs as Any)]) - } - } - + public class Cons_groupCallStreamChannel { + public var channel: Int32 + public var scale: Int32 + public var lastTimestampMs: Int64 + public init(channel: Int32, scale: Int32, lastTimestampMs: Int64) { + self.channel = channel + self.scale = scale + self.lastTimestampMs = lastTimestampMs + } + } + case groupCallStreamChannel(Cons_groupCallStreamChannel) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .groupCallStreamChannel(let _data): + if boxed { + buffer.appendInt32(-2132064081) + } + serializeInt32(_data.channel, buffer: buffer, boxed: false) + serializeInt32(_data.scale, buffer: buffer, boxed: false) + serializeInt64(_data.lastTimestampMs, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .groupCallStreamChannel(let _data): + return ("groupCallStreamChannel", [("channel", _data.channel as Any), ("scale", _data.scale as Any), ("lastTimestampMs", _data.lastTimestampMs as Any)]) + } + } + public static func parse_groupCallStreamChannel(_ reader: BufferReader) -> GroupCallStreamChannel? { var _1: Int32? _1 = reader.readInt32() @@ -216,38 +299,49 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.GroupCallStreamChannel.groupCallStreamChannel(channel: _1!, scale: _2!, lastTimestampMs: _3!) + if _c1 && _c2 && _c3 { + return Api.GroupCallStreamChannel.groupCallStreamChannel(Cons_groupCallStreamChannel(channel: _1!, scale: _2!, lastTimestampMs: _3!)) + } + else { + return nil + } } - } } public extension Api { enum HighScore: TypeConstructorDescription { - case highScore(pos: Int32, userId: Int64, score: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .highScore(let pos, let userId, let score): - if boxed { - buffer.appendInt32(1940093419) - } - serializeInt32(pos, buffer: buffer, boxed: false) - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt32(score, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .highScore(let pos, let userId, let score): - return ("highScore", [("pos", pos as Any), ("userId", userId as Any), ("score", score as Any)]) - } - } - + public class Cons_highScore { + public var pos: Int32 + public var userId: Int64 + public var score: Int32 + public init(pos: Int32, userId: Int64, score: Int32) { + self.pos = pos + self.userId = userId + self.score = score + } + } + case highScore(Cons_highScore) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .highScore(let _data): + if boxed { + buffer.appendInt32(1940093419) + } + serializeInt32(_data.pos, buffer: buffer, boxed: false) + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt32(_data.score, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .highScore(let _data): + return ("highScore", [("pos", _data.pos as Any), ("userId", _data.userId as Any), ("score", _data.score as Any)]) + } + } + public static func parse_highScore(_ reader: BufferReader) -> HighScore? { var _1: Int32? _1 = reader.readInt32() @@ -258,37 +352,46 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.HighScore.highScore(pos: _1!, userId: _2!, score: _3!) + if _c1 && _c2 && _c3 { + return Api.HighScore.highScore(Cons_highScore(pos: _1!, userId: _2!, score: _3!)) + } + else { + return nil + } } - } } public extension Api { enum ImportedContact: TypeConstructorDescription { - case importedContact(userId: Int64, clientId: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .importedContact(let userId, let clientId): - if boxed { - buffer.appendInt32(-1052885936) - } - serializeInt64(userId, buffer: buffer, boxed: false) - serializeInt64(clientId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .importedContact(let userId, let clientId): - return ("importedContact", [("userId", userId as Any), ("clientId", clientId as Any)]) - } - } - + public class Cons_importedContact { + public var userId: Int64 + public var clientId: Int64 + public init(userId: Int64, clientId: Int64) { + self.userId = userId + self.clientId = clientId + } + } + case importedContact(Cons_importedContact) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .importedContact(let _data): + if boxed { + buffer.appendInt32(-1052885936) + } + serializeInt64(_data.userId, buffer: buffer, boxed: false) + serializeInt64(_data.clientId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .importedContact(let _data): + return ("importedContact", [("userId", _data.userId as Any), ("clientId", _data.clientId as Any)]) + } + } + public static func parse_importedContact(_ reader: BufferReader) -> ImportedContact? { var _1: Int64? _1 = reader.readInt64() @@ -296,36 +399,46 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.ImportedContact.importedContact(userId: _1!, clientId: _2!) + if _c1 && _c2 { + return Api.ImportedContact.importedContact(Cons_importedContact(userId: _1!, clientId: _2!)) + } + else { + return nil + } } - } } public extension Api { enum InlineBotSwitchPM: TypeConstructorDescription { - case inlineBotSwitchPM(text: String, startParam: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inlineBotSwitchPM(let text, let startParam): - if boxed { - buffer.appendInt32(1008755359) - } - serializeString(text, buffer: buffer, boxed: false) - serializeString(startParam, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inlineBotSwitchPM(let text, let startParam): - return ("inlineBotSwitchPM", [("text", text as Any), ("startParam", startParam as Any)]) - } - } - + public class Cons_inlineBotSwitchPM { + public var text: String + public var startParam: String + public init(text: String, startParam: String) { + self.text = text + self.startParam = startParam + } + } + case inlineBotSwitchPM(Cons_inlineBotSwitchPM) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inlineBotSwitchPM(let _data): + if boxed { + buffer.appendInt32(1008755359) + } + serializeString(_data.text, buffer: buffer, boxed: false) + serializeString(_data.startParam, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inlineBotSwitchPM(let _data): + return ("inlineBotSwitchPM", [("text", _data.text as Any), ("startParam", _data.startParam as Any)]) + } + } + public static func parse_inlineBotSwitchPM(_ reader: BufferReader) -> InlineBotSwitchPM? { var _1: String? _1 = parseString(reader) @@ -333,36 +446,46 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InlineBotSwitchPM.inlineBotSwitchPM(text: _1!, startParam: _2!) + if _c1 && _c2 { + return Api.InlineBotSwitchPM.inlineBotSwitchPM(Cons_inlineBotSwitchPM(text: _1!, startParam: _2!)) + } + else { + return nil + } } - } } public extension Api { enum InlineBotWebView: TypeConstructorDescription { - case inlineBotWebView(text: String, url: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inlineBotWebView(let text, let url): - if boxed { - buffer.appendInt32(-1250781739) - } - serializeString(text, buffer: buffer, boxed: false) - serializeString(url, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inlineBotWebView(let text, let url): - return ("inlineBotWebView", [("text", text as Any), ("url", url as Any)]) - } - } - + public class Cons_inlineBotWebView { + public var text: String + public var url: String + public init(text: String, url: String) { + self.text = text + self.url = url + } + } + case inlineBotWebView(Cons_inlineBotWebView) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inlineBotWebView(let _data): + if boxed { + buffer.appendInt32(-1250781739) + } + serializeString(_data.text, buffer: buffer, boxed: false) + serializeString(_data.url, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inlineBotWebView(let _data): + return ("inlineBotWebView", [("text", _data.text as Any), ("url", _data.url as Any)]) + } + } + public static func parse_inlineBotWebView(_ reader: BufferReader) -> InlineBotWebView? { var _1: String? _1 = parseString(reader) @@ -370,11 +493,13 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InlineBotWebView.inlineBotWebView(text: _1!, url: _2!) + if _c1 && _c2 { + return Api.InlineBotWebView.inlineBotWebView(Cons_inlineBotWebView(text: _1!, url: _2!)) + } + else { + return nil + } } - } } public extension Api { @@ -385,65 +510,59 @@ public extension Api { case inlineQueryPeerTypeMegagroup case inlineQueryPeerTypePM case inlineQueryPeerTypeSameBotPM - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inlineQueryPeerTypeBotPM: - if boxed { - buffer.appendInt32(238759180) - } - - break - case .inlineQueryPeerTypeBroadcast: - if boxed { - buffer.appendInt32(1664413338) - } - - break - case .inlineQueryPeerTypeChat: - if boxed { - buffer.appendInt32(-681130742) - } - - break - case .inlineQueryPeerTypeMegagroup: - if boxed { - buffer.appendInt32(1589952067) - } - - break - case .inlineQueryPeerTypePM: - if boxed { - buffer.appendInt32(-2093215828) - } - - break - case .inlineQueryPeerTypeSameBotPM: - if boxed { - buffer.appendInt32(813821341) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inlineQueryPeerTypeBotPM: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inlineQueryPeerTypeBotPM: + if boxed { + buffer.appendInt32(238759180) + } + break + case .inlineQueryPeerTypeBroadcast: + if boxed { + buffer.appendInt32(1664413338) + } + break + case .inlineQueryPeerTypeChat: + if boxed { + buffer.appendInt32(-681130742) + } + break + case .inlineQueryPeerTypeMegagroup: + if boxed { + buffer.appendInt32(1589952067) + } + break + case .inlineQueryPeerTypePM: + if boxed { + buffer.appendInt32(-2093215828) + } + break + case .inlineQueryPeerTypeSameBotPM: + if boxed { + buffer.appendInt32(813821341) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inlineQueryPeerTypeBotPM: return ("inlineQueryPeerTypeBotPM", []) - case .inlineQueryPeerTypeBroadcast: + case .inlineQueryPeerTypeBroadcast: return ("inlineQueryPeerTypeBroadcast", []) - case .inlineQueryPeerTypeChat: + case .inlineQueryPeerTypeChat: return ("inlineQueryPeerTypeChat", []) - case .inlineQueryPeerTypeMegagroup: + case .inlineQueryPeerTypeMegagroup: return ("inlineQueryPeerTypeMegagroup", []) - case .inlineQueryPeerTypePM: + case .inlineQueryPeerTypePM: return ("inlineQueryPeerTypePM", []) - case .inlineQueryPeerTypeSameBotPM: + case .inlineQueryPeerTypeSameBotPM: return ("inlineQueryPeerTypeSameBotPM", []) - } - } - + } + } + public static func parse_inlineQueryPeerTypeBotPM(_ reader: BufferReader) -> InlineQueryPeerType? { return Api.InlineQueryPeerType.inlineQueryPeerTypeBotPM } @@ -462,34 +581,45 @@ public extension Api { public static func parse_inlineQueryPeerTypeSameBotPM(_ reader: BufferReader) -> InlineQueryPeerType? { return Api.InlineQueryPeerType.inlineQueryPeerTypeSameBotPM } - } } public extension Api { enum InputAppEvent: TypeConstructorDescription { - case inputAppEvent(time: Double, type: String, peer: Int64, data: Api.JSONValue) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputAppEvent(let time, let type, let peer, let data): - if boxed { - buffer.appendInt32(488313413) - } - serializeDouble(time, buffer: buffer, boxed: false) - serializeString(type, buffer: buffer, boxed: false) - serializeInt64(peer, buffer: buffer, boxed: false) - data.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputAppEvent(let time, let type, let peer, let data): - return ("inputAppEvent", [("time", time as Any), ("type", type as Any), ("peer", peer as Any), ("data", data as Any)]) - } - } - + public class Cons_inputAppEvent { + public var time: Double + public var type: String + public var peer: Int64 + public var data: Api.JSONValue + public init(time: Double, type: String, peer: Int64, data: Api.JSONValue) { + self.time = time + self.type = type + self.peer = peer + self.data = data + } + } + case inputAppEvent(Cons_inputAppEvent) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputAppEvent(let _data): + if boxed { + buffer.appendInt32(488313413) + } + serializeDouble(_data.time, buffer: buffer, boxed: false) + serializeString(_data.type, buffer: buffer, boxed: false) + serializeInt64(_data.peer, buffer: buffer, boxed: false) + _data.data.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputAppEvent(let _data): + return ("inputAppEvent", [("time", _data.time as Any), ("type", _data.type as Any), ("peer", _data.peer as Any), ("data", _data.data as Any)]) + } + } + public static func parse_inputAppEvent(_ reader: BufferReader) -> InputAppEvent? { var _1: Double? _1 = reader.readDouble() @@ -505,48 +635,64 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputAppEvent.inputAppEvent(time: _1!, type: _2!, peer: _3!, data: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputAppEvent.inputAppEvent(Cons_inputAppEvent(time: _1!, type: _2!, peer: _3!, data: _4!)) + } + else { + return nil + } } - } } public extension Api { indirect enum InputBotApp: TypeConstructorDescription { - case inputBotAppID(id: Int64, accessHash: Int64) - case inputBotAppShortName(botId: Api.InputUser, shortName: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputBotAppID(let id, let accessHash): - if boxed { - buffer.appendInt32(-1457472134) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - case .inputBotAppShortName(let botId, let shortName): - if boxed { - buffer.appendInt32(-1869872121) - } - botId.serialize(buffer, true) - serializeString(shortName, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputBotAppID(let id, let accessHash): - return ("inputBotAppID", [("id", id as Any), ("accessHash", accessHash as Any)]) - case .inputBotAppShortName(let botId, let shortName): - return ("inputBotAppShortName", [("botId", botId as Any), ("shortName", shortName as Any)]) - } - } - + public class Cons_inputBotAppID { + public var id: Int64 + public var accessHash: Int64 + public init(id: Int64, accessHash: Int64) { + self.id = id + self.accessHash = accessHash + } + } + public class Cons_inputBotAppShortName { + public var botId: Api.InputUser + public var shortName: String + public init(botId: Api.InputUser, shortName: String) { + self.botId = botId + self.shortName = shortName + } + } + case inputBotAppID(Cons_inputBotAppID) + case inputBotAppShortName(Cons_inputBotAppShortName) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputBotAppID(let _data): + if boxed { + buffer.appendInt32(-1457472134) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + case .inputBotAppShortName(let _data): + if boxed { + buffer.appendInt32(-1869872121) + } + _data.botId.serialize(buffer, true) + serializeString(_data.shortName, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputBotAppID(let _data): + return ("inputBotAppID", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any)]) + case .inputBotAppShortName(let _data): + return ("inputBotAppShortName", [("botId", _data.botId as Any), ("shortName", _data.shortName as Any)]) + } + } + public static func parse_inputBotAppID(_ reader: BufferReader) -> InputBotApp? { var _1: Int64? _1 = reader.readInt64() @@ -554,9 +700,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputBotApp.inputBotAppID(id: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputBotApp.inputBotAppID(Cons_inputBotAppID(id: _1!, accessHash: _2!)) + } + else { + return nil + } } public static func parse_inputBotAppShortName(_ reader: BufferReader) -> InputBotApp? { var _1: Api.InputUser? @@ -567,158 +716,315 @@ public extension Api { _2 = parseString(reader) let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputBotApp.inputBotAppShortName(botId: _1!, shortName: _2!) + if _c1 && _c2 { + return Api.InputBotApp.inputBotAppShortName(Cons_inputBotAppShortName(botId: _1!, shortName: _2!)) + } + else { + return nil + } } - } } public extension Api { enum InputBotInlineMessage: TypeConstructorDescription { - case inputBotInlineMessageGame(flags: Int32, replyMarkup: Api.ReplyMarkup?) - case inputBotInlineMessageMediaAuto(flags: Int32, message: String, entities: [Api.MessageEntity]?, replyMarkup: Api.ReplyMarkup?) - case inputBotInlineMessageMediaContact(flags: Int32, phoneNumber: String, firstName: String, lastName: String, vcard: String, replyMarkup: Api.ReplyMarkup?) - case inputBotInlineMessageMediaGeo(flags: Int32, geoPoint: Api.InputGeoPoint, heading: Int32?, period: Int32?, proximityNotificationRadius: Int32?, replyMarkup: Api.ReplyMarkup?) - case inputBotInlineMessageMediaInvoice(flags: Int32, title: String, description: String, photo: Api.InputWebDocument?, invoice: Api.Invoice, payload: Buffer, provider: String, providerData: Api.DataJSON, replyMarkup: Api.ReplyMarkup?) - case inputBotInlineMessageMediaVenue(flags: Int32, geoPoint: Api.InputGeoPoint, title: String, address: String, provider: String, venueId: String, venueType: String, replyMarkup: Api.ReplyMarkup?) - case inputBotInlineMessageMediaWebPage(flags: Int32, message: String, entities: [Api.MessageEntity]?, url: String, replyMarkup: Api.ReplyMarkup?) - case inputBotInlineMessageText(flags: Int32, message: String, entities: [Api.MessageEntity]?, replyMarkup: Api.ReplyMarkup?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputBotInlineMessageGame(let flags, let replyMarkup): - if boxed { - buffer.appendInt32(1262639204) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - break - case .inputBotInlineMessageMediaAuto(let flags, let message, let entities, let replyMarkup): - if boxed { - buffer.appendInt32(864077702) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { + public class Cons_inputBotInlineMessageGame { + public var flags: Int32 + public var replyMarkup: Api.ReplyMarkup? + public init(flags: Int32, replyMarkup: Api.ReplyMarkup?) { + self.flags = flags + self.replyMarkup = replyMarkup + } + } + public class Cons_inputBotInlineMessageMediaAuto { + public var flags: Int32 + public var message: String + public var entities: [Api.MessageEntity]? + public var replyMarkup: Api.ReplyMarkup? + public init(flags: Int32, message: String, entities: [Api.MessageEntity]?, replyMarkup: Api.ReplyMarkup?) { + self.flags = flags + self.message = message + self.entities = entities + self.replyMarkup = replyMarkup + } + } + public class Cons_inputBotInlineMessageMediaContact { + public var flags: Int32 + public var phoneNumber: String + public var firstName: String + public var lastName: String + public var vcard: String + public var replyMarkup: Api.ReplyMarkup? + public init(flags: Int32, phoneNumber: String, firstName: String, lastName: String, vcard: String, replyMarkup: Api.ReplyMarkup?) { + self.flags = flags + self.phoneNumber = phoneNumber + self.firstName = firstName + self.lastName = lastName + self.vcard = vcard + self.replyMarkup = replyMarkup + } + } + public class Cons_inputBotInlineMessageMediaGeo { + public var flags: Int32 + public var geoPoint: Api.InputGeoPoint + public var heading: Int32? + public var period: Int32? + public var proximityNotificationRadius: Int32? + public var replyMarkup: Api.ReplyMarkup? + public init(flags: Int32, geoPoint: Api.InputGeoPoint, heading: Int32?, period: Int32?, proximityNotificationRadius: Int32?, replyMarkup: Api.ReplyMarkup?) { + self.flags = flags + self.geoPoint = geoPoint + self.heading = heading + self.period = period + self.proximityNotificationRadius = proximityNotificationRadius + self.replyMarkup = replyMarkup + } + } + public class Cons_inputBotInlineMessageMediaInvoice { + public var flags: Int32 + public var title: String + public var description: String + public var photo: Api.InputWebDocument? + public var invoice: Api.Invoice + public var payload: Buffer + public var provider: String + public var providerData: Api.DataJSON + public var replyMarkup: Api.ReplyMarkup? + public init(flags: Int32, title: String, description: String, photo: Api.InputWebDocument?, invoice: Api.Invoice, payload: Buffer, provider: String, providerData: Api.DataJSON, replyMarkup: Api.ReplyMarkup?) { + self.flags = flags + self.title = title + self.description = description + self.photo = photo + self.invoice = invoice + self.payload = payload + self.provider = provider + self.providerData = providerData + self.replyMarkup = replyMarkup + } + } + public class Cons_inputBotInlineMessageMediaVenue { + public var flags: Int32 + public var geoPoint: Api.InputGeoPoint + public var title: String + public var address: String + public var provider: String + public var venueId: String + public var venueType: String + public var replyMarkup: Api.ReplyMarkup? + public init(flags: Int32, geoPoint: Api.InputGeoPoint, title: String, address: String, provider: String, venueId: String, venueType: String, replyMarkup: Api.ReplyMarkup?) { + self.flags = flags + self.geoPoint = geoPoint + self.title = title + self.address = address + self.provider = provider + self.venueId = venueId + self.venueType = venueType + self.replyMarkup = replyMarkup + } + } + public class Cons_inputBotInlineMessageMediaWebPage { + public var flags: Int32 + public var message: String + public var entities: [Api.MessageEntity]? + public var url: String + public var replyMarkup: Api.ReplyMarkup? + public init(flags: Int32, message: String, entities: [Api.MessageEntity]?, url: String, replyMarkup: Api.ReplyMarkup?) { + self.flags = flags + self.message = message + self.entities = entities + self.url = url + self.replyMarkup = replyMarkup + } + } + public class Cons_inputBotInlineMessageText { + public var flags: Int32 + public var message: String + public var entities: [Api.MessageEntity]? + public var replyMarkup: Api.ReplyMarkup? + public init(flags: Int32, message: String, entities: [Api.MessageEntity]?, replyMarkup: Api.ReplyMarkup?) { + self.flags = flags + self.message = message + self.entities = entities + self.replyMarkup = replyMarkup + } + } + case inputBotInlineMessageGame(Cons_inputBotInlineMessageGame) + case inputBotInlineMessageMediaAuto(Cons_inputBotInlineMessageMediaAuto) + case inputBotInlineMessageMediaContact(Cons_inputBotInlineMessageMediaContact) + case inputBotInlineMessageMediaGeo(Cons_inputBotInlineMessageMediaGeo) + case inputBotInlineMessageMediaInvoice(Cons_inputBotInlineMessageMediaInvoice) + case inputBotInlineMessageMediaVenue(Cons_inputBotInlineMessageMediaVenue) + case inputBotInlineMessageMediaWebPage(Cons_inputBotInlineMessageMediaWebPage) + case inputBotInlineMessageText(Cons_inputBotInlineMessageText) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputBotInlineMessageGame(let _data): + if boxed { + buffer.appendInt32(1262639204) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + break + case .inputBotInlineMessageMediaAuto(let _data): + if boxed { + buffer.appendInt32(864077702) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.message, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - break - case .inputBotInlineMessageMediaContact(let flags, let phoneNumber, let firstName, let lastName, let vcard, let replyMarkup): - if boxed { - buffer.appendInt32(-1494368259) } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(phoneNumber, buffer: buffer, boxed: false) - serializeString(firstName, buffer: buffer, boxed: false) - serializeString(lastName, buffer: buffer, boxed: false) - serializeString(vcard, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - break - case .inputBotInlineMessageMediaGeo(let flags, let geoPoint, let heading, let period, let proximityNotificationRadius, let replyMarkup): - if boxed { - buffer.appendInt32(-1768777083) - } - serializeInt32(flags, buffer: buffer, boxed: false) - geoPoint.serialize(buffer, true) - if Int(flags) & Int(1 << 0) != 0 {serializeInt32(heading!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 1) != 0 {serializeInt32(period!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeInt32(proximityNotificationRadius!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - break - case .inputBotInlineMessageMediaInvoice(let flags, let title, let description, let photo, let invoice, let payload, let provider, let providerData, let replyMarkup): - if boxed { - buffer.appendInt32(-672693723) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(description, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {photo!.serialize(buffer, true)} - invoice.serialize(buffer, true) - serializeBytes(payload, buffer: buffer, boxed: false) - serializeString(provider, buffer: buffer, boxed: false) - providerData.serialize(buffer, true) - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - break - case .inputBotInlineMessageMediaVenue(let flags, let geoPoint, let title, let address, let provider, let venueId, let venueType, let replyMarkup): - if boxed { - buffer.appendInt32(1098628881) - } - serializeInt32(flags, buffer: buffer, boxed: false) - geoPoint.serialize(buffer, true) - serializeString(title, buffer: buffer, boxed: false) - serializeString(address, buffer: buffer, boxed: false) - serializeString(provider, buffer: buffer, boxed: false) - serializeString(venueId, buffer: buffer, boxed: false) - serializeString(venueType, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - break - case .inputBotInlineMessageMediaWebPage(let flags, let message, let entities, let url, let replyMarkup): - if boxed { - buffer.appendInt32(-1109605104) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + break + case .inputBotInlineMessageMediaContact(let _data): + if boxed { + buffer.appendInt32(-1494368259) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.phoneNumber, buffer: buffer, boxed: false) + serializeString(_data.firstName, buffer: buffer, boxed: false) + serializeString(_data.lastName, buffer: buffer, boxed: false) + serializeString(_data.vcard, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + break + case .inputBotInlineMessageMediaGeo(let _data): + if boxed { + buffer.appendInt32(-1768777083) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.geoPoint.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 0) != 0 { + serializeInt32(_data.heading!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeInt32(_data.period!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeInt32(_data.proximityNotificationRadius!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + break + case .inputBotInlineMessageMediaInvoice(let _data): + if boxed { + buffer.appendInt32(-672693723) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.description, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.photo!.serialize(buffer, true) + } + _data.invoice.serialize(buffer, true) + serializeBytes(_data.payload, buffer: buffer, boxed: false) + serializeString(_data.provider, buffer: buffer, boxed: false) + _data.providerData.serialize(buffer, true) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + break + case .inputBotInlineMessageMediaVenue(let _data): + if boxed { + buffer.appendInt32(1098628881) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + _data.geoPoint.serialize(buffer, true) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.address, buffer: buffer, boxed: false) + serializeString(_data.provider, buffer: buffer, boxed: false) + serializeString(_data.venueId, buffer: buffer, boxed: false) + serializeString(_data.venueType, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + break + case .inputBotInlineMessageMediaWebPage(let _data): + if boxed { + buffer.appendInt32(-1109605104) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.message, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { item.serialize(buffer, true) - }} - serializeString(url, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - break - case .inputBotInlineMessageText(let flags, let message, let entities, let replyMarkup): - if boxed { - buffer.appendInt32(1036876423) } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { + } + serializeString(_data.url, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + break + case .inputBotInlineMessageText(let _data): + if boxed { + buffer.appendInt32(1036876423) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.message, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 2) != 0 {replyMarkup!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputBotInlineMessageGame(let flags, let replyMarkup): - return ("inputBotInlineMessageGame", [("flags", flags as Any), ("replyMarkup", replyMarkup as Any)]) - case .inputBotInlineMessageMediaAuto(let flags, let message, let entities, let replyMarkup): - return ("inputBotInlineMessageMediaAuto", [("flags", flags as Any), ("message", message as Any), ("entities", entities as Any), ("replyMarkup", replyMarkup as Any)]) - case .inputBotInlineMessageMediaContact(let flags, let phoneNumber, let firstName, let lastName, let vcard, let replyMarkup): - return ("inputBotInlineMessageMediaContact", [("flags", flags as Any), ("phoneNumber", phoneNumber as Any), ("firstName", firstName as Any), ("lastName", lastName as Any), ("vcard", vcard as Any), ("replyMarkup", replyMarkup as Any)]) - case .inputBotInlineMessageMediaGeo(let flags, let geoPoint, let heading, let period, let proximityNotificationRadius, let replyMarkup): - return ("inputBotInlineMessageMediaGeo", [("flags", flags as Any), ("geoPoint", geoPoint as Any), ("heading", heading as Any), ("period", period as Any), ("proximityNotificationRadius", proximityNotificationRadius as Any), ("replyMarkup", replyMarkup as Any)]) - case .inputBotInlineMessageMediaInvoice(let flags, let title, let description, let photo, let invoice, let payload, let provider, let providerData, let replyMarkup): - return ("inputBotInlineMessageMediaInvoice", [("flags", flags as Any), ("title", title as Any), ("description", description as Any), ("photo", photo as Any), ("invoice", invoice as Any), ("payload", payload as Any), ("provider", provider as Any), ("providerData", providerData as Any), ("replyMarkup", replyMarkup as Any)]) - case .inputBotInlineMessageMediaVenue(let flags, let geoPoint, let title, let address, let provider, let venueId, let venueType, let replyMarkup): - return ("inputBotInlineMessageMediaVenue", [("flags", flags as Any), ("geoPoint", geoPoint as Any), ("title", title as Any), ("address", address as Any), ("provider", provider as Any), ("venueId", venueId as Any), ("venueType", venueType as Any), ("replyMarkup", replyMarkup as Any)]) - case .inputBotInlineMessageMediaWebPage(let flags, let message, let entities, let url, let replyMarkup): - return ("inputBotInlineMessageMediaWebPage", [("flags", flags as Any), ("message", message as Any), ("entities", entities as Any), ("url", url as Any), ("replyMarkup", replyMarkup as Any)]) - case .inputBotInlineMessageText(let flags, let message, let entities, let replyMarkup): - return ("inputBotInlineMessageText", [("flags", flags as Any), ("message", message as Any), ("entities", entities as Any), ("replyMarkup", replyMarkup as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 2) != 0 { + _data.replyMarkup!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputBotInlineMessageGame(let _data): + return ("inputBotInlineMessageGame", [("flags", _data.flags as Any), ("replyMarkup", _data.replyMarkup as Any)]) + case .inputBotInlineMessageMediaAuto(let _data): + return ("inputBotInlineMessageMediaAuto", [("flags", _data.flags as Any), ("message", _data.message as Any), ("entities", _data.entities as Any), ("replyMarkup", _data.replyMarkup as Any)]) + case .inputBotInlineMessageMediaContact(let _data): + return ("inputBotInlineMessageMediaContact", [("flags", _data.flags as Any), ("phoneNumber", _data.phoneNumber as Any), ("firstName", _data.firstName as Any), ("lastName", _data.lastName as Any), ("vcard", _data.vcard as Any), ("replyMarkup", _data.replyMarkup as Any)]) + case .inputBotInlineMessageMediaGeo(let _data): + return ("inputBotInlineMessageMediaGeo", [("flags", _data.flags as Any), ("geoPoint", _data.geoPoint as Any), ("heading", _data.heading as Any), ("period", _data.period as Any), ("proximityNotificationRadius", _data.proximityNotificationRadius as Any), ("replyMarkup", _data.replyMarkup as Any)]) + case .inputBotInlineMessageMediaInvoice(let _data): + return ("inputBotInlineMessageMediaInvoice", [("flags", _data.flags as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("photo", _data.photo as Any), ("invoice", _data.invoice as Any), ("payload", _data.payload as Any), ("provider", _data.provider as Any), ("providerData", _data.providerData as Any), ("replyMarkup", _data.replyMarkup as Any)]) + case .inputBotInlineMessageMediaVenue(let _data): + return ("inputBotInlineMessageMediaVenue", [("flags", _data.flags as Any), ("geoPoint", _data.geoPoint as Any), ("title", _data.title as Any), ("address", _data.address as Any), ("provider", _data.provider as Any), ("venueId", _data.venueId as Any), ("venueType", _data.venueType as Any), ("replyMarkup", _data.replyMarkup as Any)]) + case .inputBotInlineMessageMediaWebPage(let _data): + return ("inputBotInlineMessageMediaWebPage", [("flags", _data.flags as Any), ("message", _data.message as Any), ("entities", _data.entities as Any), ("url", _data.url as Any), ("replyMarkup", _data.replyMarkup as Any)]) + case .inputBotInlineMessageText(let _data): + return ("inputBotInlineMessageText", [("flags", _data.flags as Any), ("message", _data.message as Any), ("entities", _data.entities as Any), ("replyMarkup", _data.replyMarkup as Any)]) + } + } + public static func parse_inputBotInlineMessageGame(_ reader: BufferReader) -> InputBotInlineMessage? { var _1: Int32? _1 = reader.readInt32() var _2: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 2) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputBotInlineMessage.inputBotInlineMessageGame(flags: _1!, replyMarkup: _2) + if _c1 && _c2 { + return Api.InputBotInlineMessage.inputBotInlineMessageGame(Cons_inputBotInlineMessageGame(flags: _1!, replyMarkup: _2)) + } + else { + return nil + } } public static func parse_inputBotInlineMessageMediaAuto(_ reader: BufferReader) -> InputBotInlineMessage? { var _1: Int32? @@ -726,22 +1032,27 @@ public extension Api { var _2: String? _2 = parseString(reader) var _3: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } var _4: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputBotInlineMessage.inputBotInlineMessageMediaAuto(flags: _1!, message: _2!, entities: _3, replyMarkup: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputBotInlineMessage.inputBotInlineMessageMediaAuto(Cons_inputBotInlineMessageMediaAuto(flags: _1!, message: _2!, entities: _3, replyMarkup: _4)) + } + else { + return nil + } } public static func parse_inputBotInlineMessageMediaContact(_ reader: BufferReader) -> InputBotInlineMessage? { var _1: Int32? @@ -755,22 +1066,23 @@ public extension Api { var _5: String? _5 = parseString(reader) var _6: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.InputBotInlineMessage.inputBotInlineMessageMediaContact(flags: _1!, phoneNumber: _2!, firstName: _3!, lastName: _4!, vcard: _5!, replyMarkup: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.InputBotInlineMessage.inputBotInlineMessageMediaContact(Cons_inputBotInlineMessageMediaContact(flags: _1!, phoneNumber: _2!, firstName: _3!, lastName: _4!, vcard: _5!, replyMarkup: _6)) + } + else { + return nil + } } public static func parse_inputBotInlineMessageMediaGeo(_ reader: BufferReader) -> InputBotInlineMessage? { var _1: Int32? @@ -780,28 +1092,35 @@ public extension Api { _2 = Api.parse(reader, signature: signature) as? Api.InputGeoPoint } var _3: Int32? - if Int(_1!) & Int(1 << 0) != 0 {_3 = reader.readInt32() } + if Int(_1!) & Int(1 << 0) != 0 { + _3 = reader.readInt32() + } var _4: Int32? - if Int(_1!) & Int(1 << 1) != 0 {_4 = reader.readInt32() } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = reader.readInt32() + } var _5: Int32? - if Int(_1!) & Int(1 << 3) != 0 {_5 = reader.readInt32() } + if Int(_1!) & Int(1 << 3) != 0 { + _5 = reader.readInt32() + } var _6: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 3) == 0) || _5 != nil let _c6 = (Int(_1!) & Int(1 << 2) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.InputBotInlineMessage.inputBotInlineMessageMediaGeo(flags: _1!, geoPoint: _2!, heading: _3, period: _4, proximityNotificationRadius: _5, replyMarkup: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.InputBotInlineMessage.inputBotInlineMessageMediaGeo(Cons_inputBotInlineMessageMediaGeo(flags: _1!, geoPoint: _2!, heading: _3, period: _4, proximityNotificationRadius: _5, replyMarkup: _6)) + } + else { + return nil + } } public static func parse_inputBotInlineMessageMediaInvoice(_ reader: BufferReader) -> InputBotInlineMessage? { var _1: Int32? @@ -811,9 +1130,11 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: Api.InputWebDocument? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.InputWebDocument - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.InputWebDocument + } + } var _5: Api.Invoice? if let signature = reader.readInt32() { _5 = Api.parse(reader, signature: signature) as? Api.Invoice @@ -827,9 +1148,11 @@ public extension Api { _8 = Api.parse(reader, signature: signature) as? Api.DataJSON } var _9: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _9 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _9 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -839,16 +1162,12 @@ public extension Api { let _c7 = _7 != nil let _c8 = _8 != nil let _c9 = (Int(_1!) & Int(1 << 2) == 0) || _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.InputBotInlineMessage.inputBotInlineMessageMediaInvoice(flags: _1!, title: _2!, description: _3!, photo: _4, invoice: _5!, payload: _6!, provider: _7!, providerData: _8!, replyMarkup: _9) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.InputBotInlineMessage.inputBotInlineMessageMediaInvoice(Cons_inputBotInlineMessageMediaInvoice(flags: _1!, title: _2!, description: _3!, photo: _4, invoice: _5!, payload: _6!, provider: _7!, providerData: _8!, replyMarkup: _9)) + } + else { + return nil + } } public static func parse_inputBotInlineMessageMediaVenue(_ reader: BufferReader) -> InputBotInlineMessage? { var _1: Int32? @@ -868,9 +1187,11 @@ public extension Api { var _7: String? _7 = parseString(reader) var _8: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -879,15 +1200,12 @@ public extension Api { let _c6 = _6 != nil let _c7 = _7 != nil let _c8 = (Int(_1!) & Int(1 << 2) == 0) || _8 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - return Api.InputBotInlineMessage.inputBotInlineMessageMediaVenue(flags: _1!, geoPoint: _2!, title: _3!, address: _4!, provider: _5!, venueId: _6!, venueType: _7!, replyMarkup: _8) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 { + return Api.InputBotInlineMessage.inputBotInlineMessageMediaVenue(Cons_inputBotInlineMessageMediaVenue(flags: _1!, geoPoint: _2!, title: _3!, address: _4!, provider: _5!, venueId: _6!, venueType: _7!, replyMarkup: _8)) + } + else { + return nil + } } public static func parse_inputBotInlineMessageMediaWebPage(_ reader: BufferReader) -> InputBotInlineMessage? { var _1: Int32? @@ -895,26 +1213,30 @@ public extension Api { var _2: String? _2 = parseString(reader) var _3: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } var _4: String? _4 = parseString(reader) var _5: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = _4 != nil let _c5 = (Int(_1!) & Int(1 << 2) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.InputBotInlineMessage.inputBotInlineMessageMediaWebPage(flags: _1!, message: _2!, entities: _3, url: _4!, replyMarkup: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.InputBotInlineMessage.inputBotInlineMessageMediaWebPage(Cons_inputBotInlineMessageMediaWebPage(flags: _1!, message: _2!, entities: _3, url: _4!, replyMarkup: _5)) + } + else { + return nil + } } public static func parse_inputBotInlineMessageText(_ reader: BufferReader) -> InputBotInlineMessage? { var _1: Int32? @@ -922,62 +1244,88 @@ public extension Api { var _2: String? _2 = parseString(reader) var _3: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 1) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } var _4: Api.ReplyMarkup? - if Int(_1!) & Int(1 << 2) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup - } } + if Int(_1!) & Int(1 << 2) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.ReplyMarkup + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputBotInlineMessage.inputBotInlineMessageText(flags: _1!, message: _2!, entities: _3, replyMarkup: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputBotInlineMessage.inputBotInlineMessageText(Cons_inputBotInlineMessageText(flags: _1!, message: _2!, entities: _3, replyMarkup: _4)) + } + else { + return nil + } } - } } public extension Api { enum InputBotInlineMessageID: TypeConstructorDescription { - case inputBotInlineMessageID(dcId: Int32, id: Int64, accessHash: Int64) - case inputBotInlineMessageID64(dcId: Int32, ownerId: Int64, id: Int32, accessHash: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputBotInlineMessageID(let dcId, let id, let accessHash): - if boxed { - buffer.appendInt32(-1995686519) - } - serializeInt32(dcId, buffer: buffer, boxed: false) - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - case .inputBotInlineMessageID64(let dcId, let ownerId, let id, let accessHash): - if boxed { - buffer.appendInt32(-1227287081) - } - serializeInt32(dcId, buffer: buffer, boxed: false) - serializeInt64(ownerId, buffer: buffer, boxed: false) - serializeInt32(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputBotInlineMessageID(let dcId, let id, let accessHash): - return ("inputBotInlineMessageID", [("dcId", dcId as Any), ("id", id as Any), ("accessHash", accessHash as Any)]) - case .inputBotInlineMessageID64(let dcId, let ownerId, let id, let accessHash): - return ("inputBotInlineMessageID64", [("dcId", dcId as Any), ("ownerId", ownerId as Any), ("id", id as Any), ("accessHash", accessHash as Any)]) - } - } - + public class Cons_inputBotInlineMessageID { + public var dcId: Int32 + public var id: Int64 + public var accessHash: Int64 + public init(dcId: Int32, id: Int64, accessHash: Int64) { + self.dcId = dcId + self.id = id + self.accessHash = accessHash + } + } + public class Cons_inputBotInlineMessageID64 { + public var dcId: Int32 + public var ownerId: Int64 + public var id: Int32 + public var accessHash: Int64 + public init(dcId: Int32, ownerId: Int64, id: Int32, accessHash: Int64) { + self.dcId = dcId + self.ownerId = ownerId + self.id = id + self.accessHash = accessHash + } + } + case inputBotInlineMessageID(Cons_inputBotInlineMessageID) + case inputBotInlineMessageID64(Cons_inputBotInlineMessageID64) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputBotInlineMessageID(let _data): + if boxed { + buffer.appendInt32(-1995686519) + } + serializeInt32(_data.dcId, buffer: buffer, boxed: false) + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + case .inputBotInlineMessageID64(let _data): + if boxed { + buffer.appendInt32(-1227287081) + } + serializeInt32(_data.dcId, buffer: buffer, boxed: false) + serializeInt64(_data.ownerId, buffer: buffer, boxed: false) + serializeInt32(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputBotInlineMessageID(let _data): + return ("inputBotInlineMessageID", [("dcId", _data.dcId as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any)]) + case .inputBotInlineMessageID64(let _data): + return ("inputBotInlineMessageID64", [("dcId", _data.dcId as Any), ("ownerId", _data.ownerId as Any), ("id", _data.id as Any), ("accessHash", _data.accessHash as Any)]) + } + } + public static func parse_inputBotInlineMessageID(_ reader: BufferReader) -> InputBotInlineMessageID? { var _1: Int32? _1 = reader.readInt32() @@ -988,10 +1336,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputBotInlineMessageID.inputBotInlineMessageID(dcId: _1!, id: _2!, accessHash: _3!) + if _c1 && _c2 && _c3 { + return Api.InputBotInlineMessageID.inputBotInlineMessageID(Cons_inputBotInlineMessageID(dcId: _1!, id: _2!, accessHash: _3!)) + } + else { + return nil + } } public static func parse_inputBotInlineMessageID64(_ reader: BufferReader) -> InputBotInlineMessageID? { var _1: Int32? @@ -1006,83 +1356,159 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputBotInlineMessageID.inputBotInlineMessageID64(dcId: _1!, ownerId: _2!, id: _3!, accessHash: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputBotInlineMessageID.inputBotInlineMessageID64(Cons_inputBotInlineMessageID64(dcId: _1!, ownerId: _2!, id: _3!, accessHash: _4!)) + } + else { + return nil + } } - } } public extension Api { enum InputBotInlineResult: TypeConstructorDescription { - case inputBotInlineResult(flags: Int32, id: String, type: String, title: String?, description: String?, url: String?, thumb: Api.InputWebDocument?, content: Api.InputWebDocument?, sendMessage: Api.InputBotInlineMessage) - case inputBotInlineResultDocument(flags: Int32, id: String, type: String, title: String?, description: String?, document: Api.InputDocument, sendMessage: Api.InputBotInlineMessage) - case inputBotInlineResultGame(id: String, shortName: String, sendMessage: Api.InputBotInlineMessage) - case inputBotInlineResultPhoto(id: String, type: String, photo: Api.InputPhoto, sendMessage: Api.InputBotInlineMessage) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputBotInlineResult(let flags, let id, let type, let title, let description, let url, let thumb, let content, let sendMessage): - if boxed { - buffer.appendInt32(-2000710887) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(id, buffer: buffer, boxed: false) - serializeString(type, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(description!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {serializeString(url!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 4) != 0 {thumb!.serialize(buffer, true)} - if Int(flags) & Int(1 << 5) != 0 {content!.serialize(buffer, true)} - sendMessage.serialize(buffer, true) - break - case .inputBotInlineResultDocument(let flags, let id, let type, let title, let description, let document, let sendMessage): - if boxed { - buffer.appendInt32(-459324) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(id, buffer: buffer, boxed: false) - serializeString(type, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 1) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 2) != 0 {serializeString(description!, buffer: buffer, boxed: false)} - document.serialize(buffer, true) - sendMessage.serialize(buffer, true) - break - case .inputBotInlineResultGame(let id, let shortName, let sendMessage): - if boxed { - buffer.appendInt32(1336154098) - } - serializeString(id, buffer: buffer, boxed: false) - serializeString(shortName, buffer: buffer, boxed: false) - sendMessage.serialize(buffer, true) - break - case .inputBotInlineResultPhoto(let id, let type, let photo, let sendMessage): - if boxed { - buffer.appendInt32(-1462213465) - } - serializeString(id, buffer: buffer, boxed: false) - serializeString(type, buffer: buffer, boxed: false) - photo.serialize(buffer, true) - sendMessage.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputBotInlineResult(let flags, let id, let type, let title, let description, let url, let thumb, let content, let sendMessage): - return ("inputBotInlineResult", [("flags", flags as Any), ("id", id as Any), ("type", type as Any), ("title", title as Any), ("description", description as Any), ("url", url as Any), ("thumb", thumb as Any), ("content", content as Any), ("sendMessage", sendMessage as Any)]) - case .inputBotInlineResultDocument(let flags, let id, let type, let title, let description, let document, let sendMessage): - return ("inputBotInlineResultDocument", [("flags", flags as Any), ("id", id as Any), ("type", type as Any), ("title", title as Any), ("description", description as Any), ("document", document as Any), ("sendMessage", sendMessage as Any)]) - case .inputBotInlineResultGame(let id, let shortName, let sendMessage): - return ("inputBotInlineResultGame", [("id", id as Any), ("shortName", shortName as Any), ("sendMessage", sendMessage as Any)]) - case .inputBotInlineResultPhoto(let id, let type, let photo, let sendMessage): - return ("inputBotInlineResultPhoto", [("id", id as Any), ("type", type as Any), ("photo", photo as Any), ("sendMessage", sendMessage as Any)]) - } - } - + public class Cons_inputBotInlineResult { + public var flags: Int32 + public var id: String + public var type: String + public var title: String? + public var description: String? + public var url: String? + public var thumb: Api.InputWebDocument? + public var content: Api.InputWebDocument? + public var sendMessage: Api.InputBotInlineMessage + public init(flags: Int32, id: String, type: String, title: String?, description: String?, url: String?, thumb: Api.InputWebDocument?, content: Api.InputWebDocument?, sendMessage: Api.InputBotInlineMessage) { + self.flags = flags + self.id = id + self.type = type + self.title = title + self.description = description + self.url = url + self.thumb = thumb + self.content = content + self.sendMessage = sendMessage + } + } + public class Cons_inputBotInlineResultDocument { + public var flags: Int32 + public var id: String + public var type: String + public var title: String? + public var description: String? + public var document: Api.InputDocument + public var sendMessage: Api.InputBotInlineMessage + public init(flags: Int32, id: String, type: String, title: String?, description: String?, document: Api.InputDocument, sendMessage: Api.InputBotInlineMessage) { + self.flags = flags + self.id = id + self.type = type + self.title = title + self.description = description + self.document = document + self.sendMessage = sendMessage + } + } + public class Cons_inputBotInlineResultGame { + public var id: String + public var shortName: String + public var sendMessage: Api.InputBotInlineMessage + public init(id: String, shortName: String, sendMessage: Api.InputBotInlineMessage) { + self.id = id + self.shortName = shortName + self.sendMessage = sendMessage + } + } + public class Cons_inputBotInlineResultPhoto { + public var id: String + public var type: String + public var photo: Api.InputPhoto + public var sendMessage: Api.InputBotInlineMessage + public init(id: String, type: String, photo: Api.InputPhoto, sendMessage: Api.InputBotInlineMessage) { + self.id = id + self.type = type + self.photo = photo + self.sendMessage = sendMessage + } + } + case inputBotInlineResult(Cons_inputBotInlineResult) + case inputBotInlineResultDocument(Cons_inputBotInlineResultDocument) + case inputBotInlineResultGame(Cons_inputBotInlineResultGame) + case inputBotInlineResultPhoto(Cons_inputBotInlineResultPhoto) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputBotInlineResult(let _data): + if boxed { + buffer.appendInt32(-2000710887) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.id, buffer: buffer, boxed: false) + serializeString(_data.type, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.description!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + serializeString(_data.url!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 4) != 0 { + _data.thumb!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 5) != 0 { + _data.content!.serialize(buffer, true) + } + _data.sendMessage.serialize(buffer, true) + break + case .inputBotInlineResultDocument(let _data): + if boxed { + buffer.appendInt32(-459324) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.id, buffer: buffer, boxed: false) + serializeString(_data.type, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeString(_data.description!, buffer: buffer, boxed: false) + } + _data.document.serialize(buffer, true) + _data.sendMessage.serialize(buffer, true) + break + case .inputBotInlineResultGame(let _data): + if boxed { + buffer.appendInt32(1336154098) + } + serializeString(_data.id, buffer: buffer, boxed: false) + serializeString(_data.shortName, buffer: buffer, boxed: false) + _data.sendMessage.serialize(buffer, true) + break + case .inputBotInlineResultPhoto(let _data): + if boxed { + buffer.appendInt32(-1462213465) + } + serializeString(_data.id, buffer: buffer, boxed: false) + serializeString(_data.type, buffer: buffer, boxed: false) + _data.photo.serialize(buffer, true) + _data.sendMessage.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputBotInlineResult(let _data): + return ("inputBotInlineResult", [("flags", _data.flags as Any), ("id", _data.id as Any), ("type", _data.type as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("url", _data.url as Any), ("thumb", _data.thumb as Any), ("content", _data.content as Any), ("sendMessage", _data.sendMessage as Any)]) + case .inputBotInlineResultDocument(let _data): + return ("inputBotInlineResultDocument", [("flags", _data.flags as Any), ("id", _data.id as Any), ("type", _data.type as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("document", _data.document as Any), ("sendMessage", _data.sendMessage as Any)]) + case .inputBotInlineResultGame(let _data): + return ("inputBotInlineResultGame", [("id", _data.id as Any), ("shortName", _data.shortName as Any), ("sendMessage", _data.sendMessage as Any)]) + case .inputBotInlineResultPhoto(let _data): + return ("inputBotInlineResultPhoto", [("id", _data.id as Any), ("type", _data.type as Any), ("photo", _data.photo as Any), ("sendMessage", _data.sendMessage as Any)]) + } + } + public static func parse_inputBotInlineResult(_ reader: BufferReader) -> InputBotInlineResult? { var _1: Int32? _1 = reader.readInt32() @@ -1091,19 +1517,29 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: String? - if Int(_1!) & Int(1 << 1) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = parseString(reader) + } var _5: String? - if Int(_1!) & Int(1 << 2) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _5 = parseString(reader) + } var _6: String? - if Int(_1!) & Int(1 << 3) != 0 {_6 = parseString(reader) } + if Int(_1!) & Int(1 << 3) != 0 { + _6 = parseString(reader) + } var _7: Api.InputWebDocument? - if Int(_1!) & Int(1 << 4) != 0 {if let signature = reader.readInt32() { - _7 = Api.parse(reader, signature: signature) as? Api.InputWebDocument - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let signature = reader.readInt32() { + _7 = Api.parse(reader, signature: signature) as? Api.InputWebDocument + } + } var _8: Api.InputWebDocument? - if Int(_1!) & Int(1 << 5) != 0 {if let signature = reader.readInt32() { - _8 = Api.parse(reader, signature: signature) as? Api.InputWebDocument - } } + if Int(_1!) & Int(1 << 5) != 0 { + if let signature = reader.readInt32() { + _8 = Api.parse(reader, signature: signature) as? Api.InputWebDocument + } + } var _9: Api.InputBotInlineMessage? if let signature = reader.readInt32() { _9 = Api.parse(reader, signature: signature) as? Api.InputBotInlineMessage @@ -1117,16 +1553,12 @@ public extension Api { let _c7 = (Int(_1!) & Int(1 << 4) == 0) || _7 != nil let _c8 = (Int(_1!) & Int(1 << 5) == 0) || _8 != nil let _c9 = _9 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - if !_c8 { return nil } - if !_c9 { return nil } - return Api.InputBotInlineResult.inputBotInlineResult(flags: _1!, id: _2!, type: _3!, title: _4, description: _5, url: _6, thumb: _7, content: _8, sendMessage: _9!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 { + return Api.InputBotInlineResult.inputBotInlineResult(Cons_inputBotInlineResult(flags: _1!, id: _2!, type: _3!, title: _4, description: _5, url: _6, thumb: _7, content: _8, sendMessage: _9!)) + } + else { + return nil + } } public static func parse_inputBotInlineResultDocument(_ reader: BufferReader) -> InputBotInlineResult? { var _1: Int32? @@ -1136,9 +1568,13 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: String? - if Int(_1!) & Int(1 << 1) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = parseString(reader) + } var _5: String? - if Int(_1!) & Int(1 << 2) != 0 {_5 = parseString(reader) } + if Int(_1!) & Int(1 << 2) != 0 { + _5 = parseString(reader) + } var _6: Api.InputDocument? if let signature = reader.readInt32() { _6 = Api.parse(reader, signature: signature) as? Api.InputDocument @@ -1154,14 +1590,12 @@ public extension Api { let _c5 = (Int(_1!) & Int(1 << 2) == 0) || _5 != nil let _c6 = _6 != nil let _c7 = _7 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - if !_c7 { return nil } - return Api.InputBotInlineResult.inputBotInlineResultDocument(flags: _1!, id: _2!, type: _3!, title: _4, description: _5, document: _6!, sendMessage: _7!) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 { + return Api.InputBotInlineResult.inputBotInlineResultDocument(Cons_inputBotInlineResultDocument(flags: _1!, id: _2!, type: _3!, title: _4, description: _5, document: _6!, sendMessage: _7!)) + } + else { + return nil + } } public static func parse_inputBotInlineResultGame(_ reader: BufferReader) -> InputBotInlineResult? { var _1: String? @@ -1175,10 +1609,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputBotInlineResult.inputBotInlineResultGame(id: _1!, shortName: _2!, sendMessage: _3!) + if _c1 && _c2 && _c3 { + return Api.InputBotInlineResult.inputBotInlineResultGame(Cons_inputBotInlineResultGame(id: _1!, shortName: _2!, sendMessage: _3!)) + } + else { + return nil + } } public static func parse_inputBotInlineResultPhoto(_ reader: BufferReader) -> InputBotInlineResult? { var _1: String? @@ -1197,40 +1633,52 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputBotInlineResult.inputBotInlineResultPhoto(id: _1!, type: _2!, photo: _3!, sendMessage: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputBotInlineResult.inputBotInlineResultPhoto(Cons_inputBotInlineResultPhoto(id: _1!, type: _2!, photo: _3!, sendMessage: _4!)) + } + else { + return nil + } } - } } public extension Api { enum InputBusinessAwayMessage: TypeConstructorDescription { - case inputBusinessAwayMessage(flags: Int32, shortcutId: Int32, schedule: Api.BusinessAwayMessageSchedule, recipients: Api.InputBusinessRecipients) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputBusinessAwayMessage(let flags, let shortcutId, let schedule, let recipients): - if boxed { - buffer.appendInt32(-2094959136) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt32(shortcutId, buffer: buffer, boxed: false) - schedule.serialize(buffer, true) - recipients.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputBusinessAwayMessage(let flags, let shortcutId, let schedule, let recipients): - return ("inputBusinessAwayMessage", [("flags", flags as Any), ("shortcutId", shortcutId as Any), ("schedule", schedule as Any), ("recipients", recipients as Any)]) - } - } - + public class Cons_inputBusinessAwayMessage { + public var flags: Int32 + public var shortcutId: Int32 + public var schedule: Api.BusinessAwayMessageSchedule + public var recipients: Api.InputBusinessRecipients + public init(flags: Int32, shortcutId: Int32, schedule: Api.BusinessAwayMessageSchedule, recipients: Api.InputBusinessRecipients) { + self.flags = flags + self.shortcutId = shortcutId + self.schedule = schedule + self.recipients = recipients + } + } + case inputBusinessAwayMessage(Cons_inputBusinessAwayMessage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputBusinessAwayMessage(let _data): + if boxed { + buffer.appendInt32(-2094959136) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt32(_data.shortcutId, buffer: buffer, boxed: false) + _data.schedule.serialize(buffer, true) + _data.recipients.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputBusinessAwayMessage(let _data): + return ("inputBusinessAwayMessage", [("flags", _data.flags as Any), ("shortcutId", _data.shortcutId as Any), ("schedule", _data.schedule as Any), ("recipients", _data.recipients as Any)]) + } + } + public static func parse_inputBusinessAwayMessage(_ reader: BufferReader) -> InputBusinessAwayMessage? { var _1: Int32? _1 = reader.readInt32() @@ -1248,12 +1696,12 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputBusinessAwayMessage.inputBusinessAwayMessage(flags: _1!, shortcutId: _2!, schedule: _3!, recipients: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputBusinessAwayMessage.inputBusinessAwayMessage(Cons_inputBusinessAwayMessage(flags: _1!, shortcutId: _2!, schedule: _3!, recipients: _4!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Api9.swift b/submodules/TelegramApi/Sources/Api9.swift index 2bdcfb3e..34ea7cd8 100644 --- a/submodules/TelegramApi/Sources/Api9.swift +++ b/submodules/TelegramApi/Sources/Api9.swift @@ -1,134 +1,183 @@ public extension Api { enum InputBusinessBotRecipients: TypeConstructorDescription { - case inputBusinessBotRecipients(flags: Int32, users: [Api.InputUser]?, excludeUsers: [Api.InputUser]?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputBusinessBotRecipients(let flags, let users, let excludeUsers): - if boxed { - buffer.appendInt32(-991587810) + public class Cons_inputBusinessBotRecipients { + public var flags: Int32 + public var users: [Api.InputUser]? + public var excludeUsers: [Api.InputUser]? + public init(flags: Int32, users: [Api.InputUser]?, excludeUsers: [Api.InputUser]?) { + self.flags = flags + self.users = users + self.excludeUsers = excludeUsers + } + } + case inputBusinessBotRecipients(Cons_inputBusinessBotRecipients) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputBusinessBotRecipients(let _data): + if boxed { + buffer.appendInt32(-991587810) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 4) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users!.count)) + for item in _data.users! { + item.serialize(buffer, true) } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users!.count)) - for item in users! { + } + if Int(_data.flags) & Int(1 << 6) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.excludeUsers!.count)) + for item in _data.excludeUsers! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 6) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(excludeUsers!.count)) - for item in excludeUsers! { - item.serialize(buffer, true) - }} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputBusinessBotRecipients(let flags, let users, let excludeUsers): - return ("inputBusinessBotRecipients", [("flags", flags as Any), ("users", users as Any), ("excludeUsers", excludeUsers as Any)]) - } - } - + } + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputBusinessBotRecipients(let _data): + return ("inputBusinessBotRecipients", [("flags", _data.flags as Any), ("users", _data.users as Any), ("excludeUsers", _data.excludeUsers as Any)]) + } + } + public static func parse_inputBusinessBotRecipients(_ reader: BufferReader) -> InputBusinessBotRecipients? { var _1: Int32? _1 = reader.readInt32() var _2: [Api.InputUser]? - if Int(_1!) & Int(1 << 4) != 0 {if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputUser.self) - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputUser.self) + } + } var _3: [Api.InputUser]? - if Int(_1!) & Int(1 << 6) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputUser.self) - } } + if Int(_1!) & Int(1 << 6) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputUser.self) + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 4) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 6) == 0) || _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputBusinessBotRecipients.inputBusinessBotRecipients(flags: _1!, users: _2, excludeUsers: _3) + if _c1 && _c2 && _c3 { + return Api.InputBusinessBotRecipients.inputBusinessBotRecipients(Cons_inputBusinessBotRecipients(flags: _1!, users: _2, excludeUsers: _3)) + } + else { + return nil + } } - } } public extension Api { enum InputBusinessChatLink: TypeConstructorDescription { - case inputBusinessChatLink(flags: Int32, message: String, entities: [Api.MessageEntity]?, title: String?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputBusinessChatLink(let flags, let message, let entities, let title): - if boxed { - buffer.appendInt32(292003751) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(message, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(entities!.count)) - for item in entities! { + public class Cons_inputBusinessChatLink { + public var flags: Int32 + public var message: String + public var entities: [Api.MessageEntity]? + public var title: String? + public init(flags: Int32, message: String, entities: [Api.MessageEntity]?, title: String?) { + self.flags = flags + self.message = message + self.entities = entities + self.title = title + } + } + case inputBusinessChatLink(Cons_inputBusinessChatLink) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputBusinessChatLink(let _data): + if boxed { + buffer.appendInt32(292003751) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.message, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.entities!.count)) + for item in _data.entities! { item.serialize(buffer, true) - }} - if Int(flags) & Int(1 << 1) != 0 {serializeString(title!, buffer: buffer, boxed: false)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputBusinessChatLink(let flags, let message, let entities, let title): - return ("inputBusinessChatLink", [("flags", flags as Any), ("message", message as Any), ("entities", entities as Any), ("title", title as Any)]) - } - } - + } + } + if Int(_data.flags) & Int(1 << 1) != 0 { + serializeString(_data.title!, buffer: buffer, boxed: false) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputBusinessChatLink(let _data): + return ("inputBusinessChatLink", [("flags", _data.flags as Any), ("message", _data.message as Any), ("entities", _data.entities as Any), ("title", _data.title as Any)]) + } + } + public static func parse_inputBusinessChatLink(_ reader: BufferReader) -> InputBusinessChatLink? { var _1: Int32? _1 = reader.readInt32() var _2: String? _2 = parseString(reader) var _3: [Api.MessageEntity]? - if Int(_1!) & Int(1 << 0) != 0 {if let _ = reader.readInt32() { - _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let _ = reader.readInt32() { + _3 = Api.parseVector(reader, elementSignature: 0, elementType: Api.MessageEntity.self) + } + } var _4: String? - if Int(_1!) & Int(1 << 1) != 0 {_4 = parseString(reader) } + if Int(_1!) & Int(1 << 1) != 0 { + _4 = parseString(reader) + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = (Int(_1!) & Int(1 << 0) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 1) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputBusinessChatLink.inputBusinessChatLink(flags: _1!, message: _2!, entities: _3, title: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputBusinessChatLink.inputBusinessChatLink(Cons_inputBusinessChatLink(flags: _1!, message: _2!, entities: _3, title: _4)) + } + else { + return nil + } } - } } public extension Api { enum InputBusinessGreetingMessage: TypeConstructorDescription { - case inputBusinessGreetingMessage(shortcutId: Int32, recipients: Api.InputBusinessRecipients, noActivityDays: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputBusinessGreetingMessage(let shortcutId, let recipients, let noActivityDays): - if boxed { - buffer.appendInt32(26528571) - } - serializeInt32(shortcutId, buffer: buffer, boxed: false) - recipients.serialize(buffer, true) - serializeInt32(noActivityDays, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputBusinessGreetingMessage(let shortcutId, let recipients, let noActivityDays): - return ("inputBusinessGreetingMessage", [("shortcutId", shortcutId as Any), ("recipients", recipients as Any), ("noActivityDays", noActivityDays as Any)]) - } - } - + public class Cons_inputBusinessGreetingMessage { + public var shortcutId: Int32 + public var recipients: Api.InputBusinessRecipients + public var noActivityDays: Int32 + public init(shortcutId: Int32, recipients: Api.InputBusinessRecipients, noActivityDays: Int32) { + self.shortcutId = shortcutId + self.recipients = recipients + self.noActivityDays = noActivityDays + } + } + case inputBusinessGreetingMessage(Cons_inputBusinessGreetingMessage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputBusinessGreetingMessage(let _data): + if boxed { + buffer.appendInt32(26528571) + } + serializeInt32(_data.shortcutId, buffer: buffer, boxed: false) + _data.recipients.serialize(buffer, true) + serializeInt32(_data.noActivityDays, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputBusinessGreetingMessage(let _data): + return ("inputBusinessGreetingMessage", [("shortcutId", _data.shortcutId as Any), ("recipients", _data.recipients as Any), ("noActivityDays", _data.noActivityDays as Any)]) + } + } + public static func parse_inputBusinessGreetingMessage(_ reader: BufferReader) -> InputBusinessGreetingMessage? { var _1: Int32? _1 = reader.readInt32() @@ -141,39 +190,54 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputBusinessGreetingMessage.inputBusinessGreetingMessage(shortcutId: _1!, recipients: _2!, noActivityDays: _3!) + if _c1 && _c2 && _c3 { + return Api.InputBusinessGreetingMessage.inputBusinessGreetingMessage(Cons_inputBusinessGreetingMessage(shortcutId: _1!, recipients: _2!, noActivityDays: _3!)) + } + else { + return nil + } } - } } public extension Api { enum InputBusinessIntro: TypeConstructorDescription { - case inputBusinessIntro(flags: Int32, title: String, description: String, sticker: Api.InputDocument?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputBusinessIntro(let flags, let title, let description, let sticker): - if boxed { - buffer.appendInt32(163867085) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeString(title, buffer: buffer, boxed: false) - serializeString(description, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {sticker!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputBusinessIntro(let flags, let title, let description, let sticker): - return ("inputBusinessIntro", [("flags", flags as Any), ("title", title as Any), ("description", description as Any), ("sticker", sticker as Any)]) - } - } - + public class Cons_inputBusinessIntro { + public var flags: Int32 + public var title: String + public var description: String + public var sticker: Api.InputDocument? + public init(flags: Int32, title: String, description: String, sticker: Api.InputDocument?) { + self.flags = flags + self.title = title + self.description = description + self.sticker = sticker + } + } + case inputBusinessIntro(Cons_inputBusinessIntro) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputBusinessIntro(let _data): + if boxed { + buffer.appendInt32(163867085) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeString(_data.title, buffer: buffer, boxed: false) + serializeString(_data.description, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.sticker!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputBusinessIntro(let _data): + return ("inputBusinessIntro", [("flags", _data.flags as Any), ("title", _data.title as Any), ("description", _data.description as Any), ("sticker", _data.sticker as Any)]) + } + } + public static func parse_inputBusinessIntro(_ reader: BufferReader) -> InputBusinessIntro? { var _1: Int32? _1 = reader.readInt32() @@ -182,108 +246,141 @@ public extension Api { var _3: String? _3 = parseString(reader) var _4: Api.InputDocument? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _4 = Api.parse(reader, signature: signature) as? Api.InputDocument - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _4 = Api.parse(reader, signature: signature) as? Api.InputDocument + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = (Int(_1!) & Int(1 << 0) == 0) || _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputBusinessIntro.inputBusinessIntro(flags: _1!, title: _2!, description: _3!, sticker: _4) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputBusinessIntro.inputBusinessIntro(Cons_inputBusinessIntro(flags: _1!, title: _2!, description: _3!, sticker: _4)) + } + else { + return nil + } } - } } public extension Api { enum InputBusinessRecipients: TypeConstructorDescription { - case inputBusinessRecipients(flags: Int32, users: [Api.InputUser]?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputBusinessRecipients(let flags, let users): - if boxed { - buffer.appendInt32(1871393450) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 4) != 0 {buffer.appendInt32(481674261) - buffer.appendInt32(Int32(users!.count)) - for item in users! { + public class Cons_inputBusinessRecipients { + public var flags: Int32 + public var users: [Api.InputUser]? + public init(flags: Int32, users: [Api.InputUser]?) { + self.flags = flags + self.users = users + } + } + case inputBusinessRecipients(Cons_inputBusinessRecipients) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputBusinessRecipients(let _data): + if boxed { + buffer.appendInt32(1871393450) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 4) != 0 { + buffer.appendInt32(481674261) + buffer.appendInt32(Int32(_data.users!.count)) + for item in _data.users! { item.serialize(buffer, true) - }} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputBusinessRecipients(let flags, let users): - return ("inputBusinessRecipients", [("flags", flags as Any), ("users", users as Any)]) - } - } - + } + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputBusinessRecipients(let _data): + return ("inputBusinessRecipients", [("flags", _data.flags as Any), ("users", _data.users as Any)]) + } + } + public static func parse_inputBusinessRecipients(_ reader: BufferReader) -> InputBusinessRecipients? { var _1: Int32? _1 = reader.readInt32() var _2: [Api.InputUser]? - if Int(_1!) & Int(1 << 4) != 0 {if let _ = reader.readInt32() { - _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputUser.self) - } } + if Int(_1!) & Int(1 << 4) != 0 { + if let _ = reader.readInt32() { + _2 = Api.parseVector(reader, elementSignature: 0, elementType: Api.InputUser.self) + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 4) == 0) || _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputBusinessRecipients.inputBusinessRecipients(flags: _1!, users: _2) + if _c1 && _c2 { + return Api.InputBusinessRecipients.inputBusinessRecipients(Cons_inputBusinessRecipients(flags: _1!, users: _2)) + } + else { + return nil + } } - } } public extension Api { indirect enum InputChannel: TypeConstructorDescription { - case inputChannel(channelId: Int64, accessHash: Int64) + public class Cons_inputChannel { + public var channelId: Int64 + public var accessHash: Int64 + public init(channelId: Int64, accessHash: Int64) { + self.channelId = channelId + self.accessHash = accessHash + } + } + public class Cons_inputChannelFromMessage { + public var peer: Api.InputPeer + public var msgId: Int32 + public var channelId: Int64 + public init(peer: Api.InputPeer, msgId: Int32, channelId: Int64) { + self.peer = peer + self.msgId = msgId + self.channelId = channelId + } + } + case inputChannel(Cons_inputChannel) case inputChannelEmpty - case inputChannelFromMessage(peer: Api.InputPeer, msgId: Int32, channelId: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputChannel(let channelId, let accessHash): - if boxed { - buffer.appendInt32(-212145112) - } - serializeInt64(channelId, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - case .inputChannelEmpty: - if boxed { - buffer.appendInt32(-292807034) - } - - break - case .inputChannelFromMessage(let peer, let msgId, let channelId): - if boxed { - buffer.appendInt32(1536380829) - } - peer.serialize(buffer, true) - serializeInt32(msgId, buffer: buffer, boxed: false) - serializeInt64(channelId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputChannel(let channelId, let accessHash): - return ("inputChannel", [("channelId", channelId as Any), ("accessHash", accessHash as Any)]) - case .inputChannelEmpty: + case inputChannelFromMessage(Cons_inputChannelFromMessage) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputChannel(let _data): + if boxed { + buffer.appendInt32(-212145112) + } + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + case .inputChannelEmpty: + if boxed { + buffer.appendInt32(-292807034) + } + break + case .inputChannelFromMessage(let _data): + if boxed { + buffer.appendInt32(1536380829) + } + _data.peer.serialize(buffer, true) + serializeInt32(_data.msgId, buffer: buffer, boxed: false) + serializeInt64(_data.channelId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputChannel(let _data): + return ("inputChannel", [("channelId", _data.channelId as Any), ("accessHash", _data.accessHash as Any)]) + case .inputChannelEmpty: return ("inputChannelEmpty", []) - case .inputChannelFromMessage(let peer, let msgId, let channelId): - return ("inputChannelFromMessage", [("peer", peer as Any), ("msgId", msgId as Any), ("channelId", channelId as Any)]) - } - } - + case .inputChannelFromMessage(let _data): + return ("inputChannelFromMessage", [("peer", _data.peer as Any), ("msgId", _data.msgId as Any), ("channelId", _data.channelId as Any)]) + } + } + public static func parse_inputChannel(_ reader: BufferReader) -> InputChannel? { var _1: Int64? _1 = reader.readInt64() @@ -291,9 +388,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputChannel.inputChannel(channelId: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputChannel.inputChannel(Cons_inputChannel(channelId: _1!, accessHash: _2!)) + } + else { + return nil + } } public static func parse_inputChannelEmpty(_ reader: BufferReader) -> InputChannel? { return Api.InputChannel.inputChannelEmpty @@ -310,66 +410,98 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputChannel.inputChannelFromMessage(peer: _1!, msgId: _2!, channelId: _3!) + if _c1 && _c2 && _c3 { + return Api.InputChannel.inputChannelFromMessage(Cons_inputChannelFromMessage(peer: _1!, msgId: _2!, channelId: _3!)) + } + else { + return nil + } } - } } public extension Api { enum InputChatPhoto: TypeConstructorDescription { - case inputChatPhoto(id: Api.InputPhoto) + public class Cons_inputChatPhoto { + public var id: Api.InputPhoto + public init(id: Api.InputPhoto) { + self.id = id + } + } + public class Cons_inputChatUploadedPhoto { + public var flags: Int32 + public var file: Api.InputFile? + public var video: Api.InputFile? + public var videoStartTs: Double? + public var videoEmojiMarkup: Api.VideoSize? + public init(flags: Int32, file: Api.InputFile?, video: Api.InputFile?, videoStartTs: Double?, videoEmojiMarkup: Api.VideoSize?) { + self.flags = flags + self.file = file + self.video = video + self.videoStartTs = videoStartTs + self.videoEmojiMarkup = videoEmojiMarkup + } + } + case inputChatPhoto(Cons_inputChatPhoto) case inputChatPhotoEmpty - case inputChatUploadedPhoto(flags: Int32, file: Api.InputFile?, video: Api.InputFile?, videoStartTs: Double?, videoEmojiMarkup: Api.VideoSize?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputChatPhoto(let id): - if boxed { - buffer.appendInt32(-1991004873) - } - id.serialize(buffer, true) - break - case .inputChatPhotoEmpty: - if boxed { - buffer.appendInt32(480546647) - } - - break - case .inputChatUploadedPhoto(let flags, let file, let video, let videoStartTs, let videoEmojiMarkup): - if boxed { - buffer.appendInt32(-1110593856) - } - serializeInt32(flags, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {file!.serialize(buffer, true)} - if Int(flags) & Int(1 << 1) != 0 {video!.serialize(buffer, true)} - if Int(flags) & Int(1 << 2) != 0 {serializeDouble(videoStartTs!, buffer: buffer, boxed: false)} - if Int(flags) & Int(1 << 3) != 0 {videoEmojiMarkup!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputChatPhoto(let id): - return ("inputChatPhoto", [("id", id as Any)]) - case .inputChatPhotoEmpty: + case inputChatUploadedPhoto(Cons_inputChatUploadedPhoto) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputChatPhoto(let _data): + if boxed { + buffer.appendInt32(-1991004873) + } + _data.id.serialize(buffer, true) + break + case .inputChatPhotoEmpty: + if boxed { + buffer.appendInt32(480546647) + } + break + case .inputChatUploadedPhoto(let _data): + if boxed { + buffer.appendInt32(-1110593856) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.file!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 1) != 0 { + _data.video!.serialize(buffer, true) + } + if Int(_data.flags) & Int(1 << 2) != 0 { + serializeDouble(_data.videoStartTs!, buffer: buffer, boxed: false) + } + if Int(_data.flags) & Int(1 << 3) != 0 { + _data.videoEmojiMarkup!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputChatPhoto(let _data): + return ("inputChatPhoto", [("id", _data.id as Any)]) + case .inputChatPhotoEmpty: return ("inputChatPhotoEmpty", []) - case .inputChatUploadedPhoto(let flags, let file, let video, let videoStartTs, let videoEmojiMarkup): - return ("inputChatUploadedPhoto", [("flags", flags as Any), ("file", file as Any), ("video", video as Any), ("videoStartTs", videoStartTs as Any), ("videoEmojiMarkup", videoEmojiMarkup as Any)]) - } - } - + case .inputChatUploadedPhoto(let _data): + return ("inputChatUploadedPhoto", [("flags", _data.flags as Any), ("file", _data.file as Any), ("video", _data.video as Any), ("videoStartTs", _data.videoStartTs as Any), ("videoEmojiMarkup", _data.videoEmojiMarkup as Any)]) + } + } + public static func parse_inputChatPhoto(_ reader: BufferReader) -> InputChatPhoto? { var _1: Api.InputPhoto? if let signature = reader.readInt32() { _1 = Api.parse(reader, signature: signature) as? Api.InputPhoto } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputChatPhoto.inputChatPhoto(id: _1!) + if _c1 { + return Api.InputChatPhoto.inputChatPhoto(Cons_inputChatPhoto(id: _1!)) + } + else { + return nil + } } public static func parse_inputChatPhotoEmpty(_ reader: BufferReader) -> InputChatPhoto? { return Api.InputChatPhoto.inputChatPhotoEmpty @@ -378,80 +510,102 @@ public extension Api { var _1: Int32? _1 = reader.readInt32() var _2: Api.InputFile? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _2 = Api.parse(reader, signature: signature) as? Api.InputFile - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _2 = Api.parse(reader, signature: signature) as? Api.InputFile + } + } var _3: Api.InputFile? - if Int(_1!) & Int(1 << 1) != 0 {if let signature = reader.readInt32() { - _3 = Api.parse(reader, signature: signature) as? Api.InputFile - } } + if Int(_1!) & Int(1 << 1) != 0 { + if let signature = reader.readInt32() { + _3 = Api.parse(reader, signature: signature) as? Api.InputFile + } + } var _4: Double? - if Int(_1!) & Int(1 << 2) != 0 {_4 = reader.readDouble() } + if Int(_1!) & Int(1 << 2) != 0 { + _4 = reader.readDouble() + } var _5: Api.VideoSize? - if Int(_1!) & Int(1 << 3) != 0 {if let signature = reader.readInt32() { - _5 = Api.parse(reader, signature: signature) as? Api.VideoSize - } } + if Int(_1!) & Int(1 << 3) != 0 { + if let signature = reader.readInt32() { + _5 = Api.parse(reader, signature: signature) as? Api.VideoSize + } + } let _c1 = _1 != nil let _c2 = (Int(_1!) & Int(1 << 0) == 0) || _2 != nil let _c3 = (Int(_1!) & Int(1 << 1) == 0) || _3 != nil let _c4 = (Int(_1!) & Int(1 << 2) == 0) || _4 != nil let _c5 = (Int(_1!) & Int(1 << 3) == 0) || _5 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - return Api.InputChatPhoto.inputChatUploadedPhoto(flags: _1!, file: _2, video: _3, videoStartTs: _4, videoEmojiMarkup: _5) + if _c1 && _c2 && _c3 && _c4 && _c5 { + return Api.InputChatPhoto.inputChatUploadedPhoto(Cons_inputChatUploadedPhoto(flags: _1!, file: _2, video: _3, videoStartTs: _4, videoEmojiMarkup: _5)) + } + else { + return nil + } } - } } public extension Api { enum InputChatTheme: TypeConstructorDescription { - case inputChatTheme(emoticon: String) + public class Cons_inputChatTheme { + public var emoticon: String + public init(emoticon: String) { + self.emoticon = emoticon + } + } + public class Cons_inputChatThemeUniqueGift { + public var slug: String + public init(slug: String) { + self.slug = slug + } + } + case inputChatTheme(Cons_inputChatTheme) case inputChatThemeEmpty - case inputChatThemeUniqueGift(slug: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputChatTheme(let emoticon): - if boxed { - buffer.appendInt32(-918689444) - } - serializeString(emoticon, buffer: buffer, boxed: false) - break - case .inputChatThemeEmpty: - if boxed { - buffer.appendInt32(-2094627709) - } - - break - case .inputChatThemeUniqueGift(let slug): - if boxed { - buffer.appendInt32(-2014978076) - } - serializeString(slug, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputChatTheme(let emoticon): - return ("inputChatTheme", [("emoticon", emoticon as Any)]) - case .inputChatThemeEmpty: + case inputChatThemeUniqueGift(Cons_inputChatThemeUniqueGift) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputChatTheme(let _data): + if boxed { + buffer.appendInt32(-918689444) + } + serializeString(_data.emoticon, buffer: buffer, boxed: false) + break + case .inputChatThemeEmpty: + if boxed { + buffer.appendInt32(-2094627709) + } + break + case .inputChatThemeUniqueGift(let _data): + if boxed { + buffer.appendInt32(-2014978076) + } + serializeString(_data.slug, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputChatTheme(let _data): + return ("inputChatTheme", [("emoticon", _data.emoticon as Any)]) + case .inputChatThemeEmpty: return ("inputChatThemeEmpty", []) - case .inputChatThemeUniqueGift(let slug): - return ("inputChatThemeUniqueGift", [("slug", slug as Any)]) - } - } - + case .inputChatThemeUniqueGift(let _data): + return ("inputChatThemeUniqueGift", [("slug", _data.slug as Any)]) + } + } + public static func parse_inputChatTheme(_ reader: BufferReader) -> InputChatTheme? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputChatTheme.inputChatTheme(emoticon: _1!) + if _c1 { + return Api.InputChatTheme.inputChatTheme(Cons_inputChatTheme(emoticon: _1!)) + } + else { + return nil + } } public static func parse_inputChatThemeEmpty(_ reader: BufferReader) -> InputChatTheme? { return Api.InputChatTheme.inputChatThemeEmpty @@ -460,77 +614,98 @@ public extension Api { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputChatTheme.inputChatThemeUniqueGift(slug: _1!) + if _c1 { + return Api.InputChatTheme.inputChatThemeUniqueGift(Cons_inputChatThemeUniqueGift(slug: _1!)) + } + else { + return nil + } } - } } public extension Api { enum InputChatlist: TypeConstructorDescription { - case inputChatlistDialogFilter(filterId: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputChatlistDialogFilter(let filterId): - if boxed { - buffer.appendInt32(-203367885) - } - serializeInt32(filterId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputChatlistDialogFilter(let filterId): - return ("inputChatlistDialogFilter", [("filterId", filterId as Any)]) - } - } - + public class Cons_inputChatlistDialogFilter { + public var filterId: Int32 + public init(filterId: Int32) { + self.filterId = filterId + } + } + case inputChatlistDialogFilter(Cons_inputChatlistDialogFilter) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputChatlistDialogFilter(let _data): + if boxed { + buffer.appendInt32(-203367885) + } + serializeInt32(_data.filterId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputChatlistDialogFilter(let _data): + return ("inputChatlistDialogFilter", [("filterId", _data.filterId as Any)]) + } + } + public static func parse_inputChatlistDialogFilter(_ reader: BufferReader) -> InputChatlist? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputChatlist.inputChatlistDialogFilter(filterId: _1!) + if _c1 { + return Api.InputChatlist.inputChatlistDialogFilter(Cons_inputChatlistDialogFilter(filterId: _1!)) + } + else { + return nil + } } - } } public extension Api { enum InputCheckPasswordSRP: TypeConstructorDescription { + public class Cons_inputCheckPasswordSRP { + public var srpId: Int64 + public var A: Buffer + public var M1: Buffer + public init(srpId: Int64, A: Buffer, M1: Buffer) { + self.srpId = srpId + self.A = A + self.M1 = M1 + } + } case inputCheckPasswordEmpty - case inputCheckPasswordSRP(srpId: Int64, A: Buffer, M1: Buffer) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputCheckPasswordEmpty: - if boxed { - buffer.appendInt32(-1736378792) - } - - break - case .inputCheckPasswordSRP(let srpId, let A, let M1): - if boxed { - buffer.appendInt32(-763367294) - } - serializeInt64(srpId, buffer: buffer, boxed: false) - serializeBytes(A, buffer: buffer, boxed: false) - serializeBytes(M1, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputCheckPasswordEmpty: + case inputCheckPasswordSRP(Cons_inputCheckPasswordSRP) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputCheckPasswordEmpty: + if boxed { + buffer.appendInt32(-1736378792) + } + break + case .inputCheckPasswordSRP(let _data): + if boxed { + buffer.appendInt32(-763367294) + } + serializeInt64(_data.srpId, buffer: buffer, boxed: false) + serializeBytes(_data.A, buffer: buffer, boxed: false) + serializeBytes(_data.M1, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputCheckPasswordEmpty: return ("inputCheckPasswordEmpty", []) - case .inputCheckPasswordSRP(let srpId, let A, let M1): - return ("inputCheckPasswordSRP", [("srpId", srpId as Any), ("A", A as Any), ("M1", M1 as Any)]) - } - } - + case .inputCheckPasswordSRP(let _data): + return ("inputCheckPasswordSRP", [("srpId", _data.srpId as Any), ("A", _data.A as Any), ("M1", _data.M1 as Any)]) + } + } + public static func parse_inputCheckPasswordEmpty(_ reader: BufferReader) -> InputCheckPasswordSRP? { return Api.InputCheckPasswordSRP.inputCheckPasswordEmpty } @@ -544,37 +719,46 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputCheckPasswordSRP.inputCheckPasswordSRP(srpId: _1!, A: _2!, M1: _3!) + if _c1 && _c2 && _c3 { + return Api.InputCheckPasswordSRP.inputCheckPasswordSRP(Cons_inputCheckPasswordSRP(srpId: _1!, A: _2!, M1: _3!)) + } + else { + return nil + } } - } } public extension Api { enum InputClientProxy: TypeConstructorDescription { - case inputClientProxy(address: String, port: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputClientProxy(let address, let port): - if boxed { - buffer.appendInt32(1968737087) - } - serializeString(address, buffer: buffer, boxed: false) - serializeInt32(port, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputClientProxy(let address, let port): - return ("inputClientProxy", [("address", address as Any), ("port", port as Any)]) - } - } - + public class Cons_inputClientProxy { + public var address: String + public var port: Int32 + public init(address: String, port: Int32) { + self.address = address + self.port = port + } + } + case inputClientProxy(Cons_inputClientProxy) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputClientProxy(let _data): + if boxed { + buffer.appendInt32(1968737087) + } + serializeString(_data.address, buffer: buffer, boxed: false) + serializeInt32(_data.port, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputClientProxy(let _data): + return ("inputClientProxy", [("address", _data.address as Any), ("port", _data.port as Any)]) + } + } + public static func parse_inputClientProxy(_ reader: BufferReader) -> InputClientProxy? { var _1: String? _1 = parseString(reader) @@ -582,88 +766,127 @@ public extension Api { _2 = reader.readInt32() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputClientProxy.inputClientProxy(address: _1!, port: _2!) + if _c1 && _c2 { + return Api.InputClientProxy.inputClientProxy(Cons_inputClientProxy(address: _1!, port: _2!)) + } + else { + return nil + } } - } } public extension Api { enum InputCollectible: TypeConstructorDescription { - case inputCollectiblePhone(phone: String) - case inputCollectibleUsername(username: String) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputCollectiblePhone(let phone): - if boxed { - buffer.appendInt32(-1562241884) - } - serializeString(phone, buffer: buffer, boxed: false) - break - case .inputCollectibleUsername(let username): - if boxed { - buffer.appendInt32(-476815191) - } - serializeString(username, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputCollectiblePhone(let phone): - return ("inputCollectiblePhone", [("phone", phone as Any)]) - case .inputCollectibleUsername(let username): - return ("inputCollectibleUsername", [("username", username as Any)]) - } - } - + public class Cons_inputCollectiblePhone { + public var phone: String + public init(phone: String) { + self.phone = phone + } + } + public class Cons_inputCollectibleUsername { + public var username: String + public init(username: String) { + self.username = username + } + } + case inputCollectiblePhone(Cons_inputCollectiblePhone) + case inputCollectibleUsername(Cons_inputCollectibleUsername) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputCollectiblePhone(let _data): + if boxed { + buffer.appendInt32(-1562241884) + } + serializeString(_data.phone, buffer: buffer, boxed: false) + break + case .inputCollectibleUsername(let _data): + if boxed { + buffer.appendInt32(-476815191) + } + serializeString(_data.username, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputCollectiblePhone(let _data): + return ("inputCollectiblePhone", [("phone", _data.phone as Any)]) + case .inputCollectibleUsername(let _data): + return ("inputCollectibleUsername", [("username", _data.username as Any)]) + } + } + public static func parse_inputCollectiblePhone(_ reader: BufferReader) -> InputCollectible? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputCollectible.inputCollectiblePhone(phone: _1!) + if _c1 { + return Api.InputCollectible.inputCollectiblePhone(Cons_inputCollectiblePhone(phone: _1!)) + } + else { + return nil + } } public static func parse_inputCollectibleUsername(_ reader: BufferReader) -> InputCollectible? { var _1: String? _1 = parseString(reader) let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputCollectible.inputCollectibleUsername(username: _1!) + if _c1 { + return Api.InputCollectible.inputCollectibleUsername(Cons_inputCollectibleUsername(username: _1!)) + } + else { + return nil + } } - } } public extension Api { enum InputContact: TypeConstructorDescription { - case inputPhoneContact(flags: Int32, clientId: Int64, phone: String, firstName: String, lastName: String, note: Api.TextWithEntities?) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputPhoneContact(let flags, let clientId, let phone, let firstName, let lastName, let note): - if boxed { - buffer.appendInt32(1780335806) - } - serializeInt32(flags, buffer: buffer, boxed: false) - serializeInt64(clientId, buffer: buffer, boxed: false) - serializeString(phone, buffer: buffer, boxed: false) - serializeString(firstName, buffer: buffer, boxed: false) - serializeString(lastName, buffer: buffer, boxed: false) - if Int(flags) & Int(1 << 0) != 0 {note!.serialize(buffer, true)} - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputPhoneContact(let flags, let clientId, let phone, let firstName, let lastName, let note): - return ("inputPhoneContact", [("flags", flags as Any), ("clientId", clientId as Any), ("phone", phone as Any), ("firstName", firstName as Any), ("lastName", lastName as Any), ("note", note as Any)]) - } - } - + public class Cons_inputPhoneContact { + public var flags: Int32 + public var clientId: Int64 + public var phone: String + public var firstName: String + public var lastName: String + public var note: Api.TextWithEntities? + public init(flags: Int32, clientId: Int64, phone: String, firstName: String, lastName: String, note: Api.TextWithEntities?) { + self.flags = flags + self.clientId = clientId + self.phone = phone + self.firstName = firstName + self.lastName = lastName + self.note = note + } + } + case inputPhoneContact(Cons_inputPhoneContact) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputPhoneContact(let _data): + if boxed { + buffer.appendInt32(1780335806) + } + serializeInt32(_data.flags, buffer: buffer, boxed: false) + serializeInt64(_data.clientId, buffer: buffer, boxed: false) + serializeString(_data.phone, buffer: buffer, boxed: false) + serializeString(_data.firstName, buffer: buffer, boxed: false) + serializeString(_data.lastName, buffer: buffer, boxed: false) + if Int(_data.flags) & Int(1 << 0) != 0 { + _data.note!.serialize(buffer, true) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputPhoneContact(let _data): + return ("inputPhoneContact", [("flags", _data.flags as Any), ("clientId", _data.clientId as Any), ("phone", _data.phone as Any), ("firstName", _data.firstName as Any), ("lastName", _data.lastName as Any), ("note", _data.note as Any)]) + } + } + public static func parse_inputPhoneContact(_ reader: BufferReader) -> InputContact? { var _1: Int32? _1 = reader.readInt32() @@ -676,109 +899,137 @@ public extension Api { var _5: String? _5 = parseString(reader) var _6: Api.TextWithEntities? - if Int(_1!) & Int(1 << 0) != 0 {if let signature = reader.readInt32() { - _6 = Api.parse(reader, signature: signature) as? Api.TextWithEntities - } } + if Int(_1!) & Int(1 << 0) != 0 { + if let signature = reader.readInt32() { + _6 = Api.parse(reader, signature: signature) as? Api.TextWithEntities + } + } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil let _c5 = _5 != nil let _c6 = (Int(_1!) & Int(1 << 0) == 0) || _6 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - if !_c5 { return nil } - if !_c6 { return nil } - return Api.InputContact.inputPhoneContact(flags: _1!, clientId: _2!, phone: _3!, firstName: _4!, lastName: _5!, note: _6) + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 { + return Api.InputContact.inputPhoneContact(Cons_inputPhoneContact(flags: _1!, clientId: _2!, phone: _3!, firstName: _4!, lastName: _5!, note: _6)) + } + else { + return nil + } } - } } public extension Api { indirect enum InputDialogPeer: TypeConstructorDescription { - case inputDialogPeer(peer: Api.InputPeer) - case inputDialogPeerFolder(folderId: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputDialogPeer(let peer): - if boxed { - buffer.appendInt32(-55902537) - } - peer.serialize(buffer, true) - break - case .inputDialogPeerFolder(let folderId): - if boxed { - buffer.appendInt32(1684014375) - } - serializeInt32(folderId, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputDialogPeer(let peer): - return ("inputDialogPeer", [("peer", peer as Any)]) - case .inputDialogPeerFolder(let folderId): - return ("inputDialogPeerFolder", [("folderId", folderId as Any)]) - } - } - + public class Cons_inputDialogPeer { + public var peer: Api.InputPeer + public init(peer: Api.InputPeer) { + self.peer = peer + } + } + public class Cons_inputDialogPeerFolder { + public var folderId: Int32 + public init(folderId: Int32) { + self.folderId = folderId + } + } + case inputDialogPeer(Cons_inputDialogPeer) + case inputDialogPeerFolder(Cons_inputDialogPeerFolder) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputDialogPeer(let _data): + if boxed { + buffer.appendInt32(-55902537) + } + _data.peer.serialize(buffer, true) + break + case .inputDialogPeerFolder(let _data): + if boxed { + buffer.appendInt32(1684014375) + } + serializeInt32(_data.folderId, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputDialogPeer(let _data): + return ("inputDialogPeer", [("peer", _data.peer as Any)]) + case .inputDialogPeerFolder(let _data): + return ("inputDialogPeerFolder", [("folderId", _data.folderId as Any)]) + } + } + public static func parse_inputDialogPeer(_ reader: BufferReader) -> InputDialogPeer? { var _1: Api.InputPeer? if let signature = reader.readInt32() { _1 = Api.parse(reader, signature: signature) as? Api.InputPeer } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputDialogPeer.inputDialogPeer(peer: _1!) + if _c1 { + return Api.InputDialogPeer.inputDialogPeer(Cons_inputDialogPeer(peer: _1!)) + } + else { + return nil + } } public static func parse_inputDialogPeerFolder(_ reader: BufferReader) -> InputDialogPeer? { var _1: Int32? _1 = reader.readInt32() let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputDialogPeer.inputDialogPeerFolder(folderId: _1!) + if _c1 { + return Api.InputDialogPeer.inputDialogPeerFolder(Cons_inputDialogPeerFolder(folderId: _1!)) + } + else { + return nil + } } - } } public extension Api { enum InputDocument: TypeConstructorDescription { - case inputDocument(id: Int64, accessHash: Int64, fileReference: Buffer) + public class Cons_inputDocument { + public var id: Int64 + public var accessHash: Int64 + public var fileReference: Buffer + public init(id: Int64, accessHash: Int64, fileReference: Buffer) { + self.id = id + self.accessHash = accessHash + self.fileReference = fileReference + } + } + case inputDocument(Cons_inputDocument) case inputDocumentEmpty - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputDocument(let id, let accessHash, let fileReference): - if boxed { - buffer.appendInt32(448771445) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - serializeBytes(fileReference, buffer: buffer, boxed: false) - break - case .inputDocumentEmpty: - if boxed { - buffer.appendInt32(1928391342) - } - - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputDocument(let id, let accessHash, let fileReference): - return ("inputDocument", [("id", id as Any), ("accessHash", accessHash as Any), ("fileReference", fileReference as Any)]) - case .inputDocumentEmpty: + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputDocument(let _data): + if boxed { + buffer.appendInt32(448771445) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + serializeBytes(_data.fileReference, buffer: buffer, boxed: false) + break + case .inputDocumentEmpty: + if boxed { + buffer.appendInt32(1928391342) + } + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputDocument(let _data): + return ("inputDocument", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any), ("fileReference", _data.fileReference as Any)]) + case .inputDocumentEmpty: return ("inputDocumentEmpty", []) - } - } - + } + } + public static func parse_inputDocument(_ reader: BufferReader) -> InputDocument? { var _1: Int64? _1 = reader.readInt64() @@ -789,40 +1040,49 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputDocument.inputDocument(id: _1!, accessHash: _2!, fileReference: _3!) + if _c1 && _c2 && _c3 { + return Api.InputDocument.inputDocument(Cons_inputDocument(id: _1!, accessHash: _2!, fileReference: _3!)) + } + else { + return nil + } } public static func parse_inputDocumentEmpty(_ reader: BufferReader) -> InputDocument? { return Api.InputDocument.inputDocumentEmpty } - } } public extension Api { enum InputEncryptedChat: TypeConstructorDescription { - case inputEncryptedChat(chatId: Int32, accessHash: Int64) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputEncryptedChat(let chatId, let accessHash): - if boxed { - buffer.appendInt32(-247351839) - } - serializeInt32(chatId, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputEncryptedChat(let chatId, let accessHash): - return ("inputEncryptedChat", [("chatId", chatId as Any), ("accessHash", accessHash as Any)]) - } - } - + public class Cons_inputEncryptedChat { + public var chatId: Int32 + public var accessHash: Int64 + public init(chatId: Int32, accessHash: Int64) { + self.chatId = chatId + self.accessHash = accessHash + } + } + case inputEncryptedChat(Cons_inputEncryptedChat) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputEncryptedChat(let _data): + if boxed { + buffer.appendInt32(-247351839) + } + serializeInt32(_data.chatId, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputEncryptedChat(let _data): + return ("inputEncryptedChat", [("chatId", _data.chatId as Any), ("accessHash", _data.accessHash as Any)]) + } + } + public static func parse_inputEncryptedChat(_ reader: BufferReader) -> InputEncryptedChat? { var _1: Int32? _1 = reader.readInt32() @@ -830,68 +1090,99 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputEncryptedChat.inputEncryptedChat(chatId: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputEncryptedChat.inputEncryptedChat(Cons_inputEncryptedChat(chatId: _1!, accessHash: _2!)) + } + else { + return nil + } } - } } public extension Api { enum InputEncryptedFile: TypeConstructorDescription { - case inputEncryptedFile(id: Int64, accessHash: Int64) - case inputEncryptedFileBigUploaded(id: Int64, parts: Int32, keyFingerprint: Int32) + public class Cons_inputEncryptedFile { + public var id: Int64 + public var accessHash: Int64 + public init(id: Int64, accessHash: Int64) { + self.id = id + self.accessHash = accessHash + } + } + public class Cons_inputEncryptedFileBigUploaded { + public var id: Int64 + public var parts: Int32 + public var keyFingerprint: Int32 + public init(id: Int64, parts: Int32, keyFingerprint: Int32) { + self.id = id + self.parts = parts + self.keyFingerprint = keyFingerprint + } + } + public class Cons_inputEncryptedFileUploaded { + public var id: Int64 + public var parts: Int32 + public var md5Checksum: String + public var keyFingerprint: Int32 + public init(id: Int64, parts: Int32, md5Checksum: String, keyFingerprint: Int32) { + self.id = id + self.parts = parts + self.md5Checksum = md5Checksum + self.keyFingerprint = keyFingerprint + } + } + case inputEncryptedFile(Cons_inputEncryptedFile) + case inputEncryptedFileBigUploaded(Cons_inputEncryptedFileBigUploaded) case inputEncryptedFileEmpty - case inputEncryptedFileUploaded(id: Int64, parts: Int32, md5Checksum: String, keyFingerprint: Int32) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputEncryptedFile(let id, let accessHash): - if boxed { - buffer.appendInt32(1511503333) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt64(accessHash, buffer: buffer, boxed: false) - break - case .inputEncryptedFileBigUploaded(let id, let parts, let keyFingerprint): - if boxed { - buffer.appendInt32(767652808) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt32(parts, buffer: buffer, boxed: false) - serializeInt32(keyFingerprint, buffer: buffer, boxed: false) - break - case .inputEncryptedFileEmpty: - if boxed { - buffer.appendInt32(406307684) - } - - break - case .inputEncryptedFileUploaded(let id, let parts, let md5Checksum, let keyFingerprint): - if boxed { - buffer.appendInt32(1690108678) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt32(parts, buffer: buffer, boxed: false) - serializeString(md5Checksum, buffer: buffer, boxed: false) - serializeInt32(keyFingerprint, buffer: buffer, boxed: false) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputEncryptedFile(let id, let accessHash): - return ("inputEncryptedFile", [("id", id as Any), ("accessHash", accessHash as Any)]) - case .inputEncryptedFileBigUploaded(let id, let parts, let keyFingerprint): - return ("inputEncryptedFileBigUploaded", [("id", id as Any), ("parts", parts as Any), ("keyFingerprint", keyFingerprint as Any)]) - case .inputEncryptedFileEmpty: + case inputEncryptedFileUploaded(Cons_inputEncryptedFileUploaded) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputEncryptedFile(let _data): + if boxed { + buffer.appendInt32(1511503333) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt64(_data.accessHash, buffer: buffer, boxed: false) + break + case .inputEncryptedFileBigUploaded(let _data): + if boxed { + buffer.appendInt32(767652808) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.parts, buffer: buffer, boxed: false) + serializeInt32(_data.keyFingerprint, buffer: buffer, boxed: false) + break + case .inputEncryptedFileEmpty: + if boxed { + buffer.appendInt32(406307684) + } + break + case .inputEncryptedFileUploaded(let _data): + if boxed { + buffer.appendInt32(1690108678) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.parts, buffer: buffer, boxed: false) + serializeString(_data.md5Checksum, buffer: buffer, boxed: false) + serializeInt32(_data.keyFingerprint, buffer: buffer, boxed: false) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputEncryptedFile(let _data): + return ("inputEncryptedFile", [("id", _data.id as Any), ("accessHash", _data.accessHash as Any)]) + case .inputEncryptedFileBigUploaded(let _data): + return ("inputEncryptedFileBigUploaded", [("id", _data.id as Any), ("parts", _data.parts as Any), ("keyFingerprint", _data.keyFingerprint as Any)]) + case .inputEncryptedFileEmpty: return ("inputEncryptedFileEmpty", []) - case .inputEncryptedFileUploaded(let id, let parts, let md5Checksum, let keyFingerprint): - return ("inputEncryptedFileUploaded", [("id", id as Any), ("parts", parts as Any), ("md5Checksum", md5Checksum as Any), ("keyFingerprint", keyFingerprint as Any)]) - } - } - + case .inputEncryptedFileUploaded(let _data): + return ("inputEncryptedFileUploaded", [("id", _data.id as Any), ("parts", _data.parts as Any), ("md5Checksum", _data.md5Checksum as Any), ("keyFingerprint", _data.keyFingerprint as Any)]) + } + } + public static func parse_inputEncryptedFile(_ reader: BufferReader) -> InputEncryptedFile? { var _1: Int64? _1 = reader.readInt64() @@ -899,9 +1190,12 @@ public extension Api { _2 = reader.readInt64() let _c1 = _1 != nil let _c2 = _2 != nil - if !_c1 { return nil } - if !_c2 { return nil } - return Api.InputEncryptedFile.inputEncryptedFile(id: _1!, accessHash: _2!) + if _c1 && _c2 { + return Api.InputEncryptedFile.inputEncryptedFile(Cons_inputEncryptedFile(id: _1!, accessHash: _2!)) + } + else { + return nil + } } public static func parse_inputEncryptedFileBigUploaded(_ reader: BufferReader) -> InputEncryptedFile? { var _1: Int64? @@ -913,10 +1207,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputEncryptedFile.inputEncryptedFileBigUploaded(id: _1!, parts: _2!, keyFingerprint: _3!) + if _c1 && _c2 && _c3 { + return Api.InputEncryptedFile.inputEncryptedFileBigUploaded(Cons_inputEncryptedFileBigUploaded(id: _1!, parts: _2!, keyFingerprint: _3!)) + } + else { + return nil + } } public static func parse_inputEncryptedFileEmpty(_ reader: BufferReader) -> InputEncryptedFile? { return Api.InputEncryptedFile.inputEncryptedFileEmpty @@ -934,60 +1230,88 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputEncryptedFile.inputEncryptedFileUploaded(id: _1!, parts: _2!, md5Checksum: _3!, keyFingerprint: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputEncryptedFile.inputEncryptedFileUploaded(Cons_inputEncryptedFileUploaded(id: _1!, parts: _2!, md5Checksum: _3!, keyFingerprint: _4!)) + } + else { + return nil + } } - } } public extension Api { enum InputFile: TypeConstructorDescription { - case inputFile(id: Int64, parts: Int32, name: String, md5Checksum: String) - case inputFileBig(id: Int64, parts: Int32, name: String) - case inputFileStoryDocument(id: Api.InputDocument) - - public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { - switch self { - case .inputFile(let id, let parts, let name, let md5Checksum): - if boxed { - buffer.appendInt32(-181407105) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt32(parts, buffer: buffer, boxed: false) - serializeString(name, buffer: buffer, boxed: false) - serializeString(md5Checksum, buffer: buffer, boxed: false) - break - case .inputFileBig(let id, let parts, let name): - if boxed { - buffer.appendInt32(-95482955) - } - serializeInt64(id, buffer: buffer, boxed: false) - serializeInt32(parts, buffer: buffer, boxed: false) - serializeString(name, buffer: buffer, boxed: false) - break - case .inputFileStoryDocument(let id): - if boxed { - buffer.appendInt32(1658620744) - } - id.serialize(buffer, true) - break - } - } - - public func descriptionFields() -> (String, [(String, Any)]) { - switch self { - case .inputFile(let id, let parts, let name, let md5Checksum): - return ("inputFile", [("id", id as Any), ("parts", parts as Any), ("name", name as Any), ("md5Checksum", md5Checksum as Any)]) - case .inputFileBig(let id, let parts, let name): - return ("inputFileBig", [("id", id as Any), ("parts", parts as Any), ("name", name as Any)]) - case .inputFileStoryDocument(let id): - return ("inputFileStoryDocument", [("id", id as Any)]) - } - } - + public class Cons_inputFile { + public var id: Int64 + public var parts: Int32 + public var name: String + public var md5Checksum: String + public init(id: Int64, parts: Int32, name: String, md5Checksum: String) { + self.id = id + self.parts = parts + self.name = name + self.md5Checksum = md5Checksum + } + } + public class Cons_inputFileBig { + public var id: Int64 + public var parts: Int32 + public var name: String + public init(id: Int64, parts: Int32, name: String) { + self.id = id + self.parts = parts + self.name = name + } + } + public class Cons_inputFileStoryDocument { + public var id: Api.InputDocument + public init(id: Api.InputDocument) { + self.id = id + } + } + case inputFile(Cons_inputFile) + case inputFileBig(Cons_inputFileBig) + case inputFileStoryDocument(Cons_inputFileStoryDocument) + + public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { + switch self { + case .inputFile(let _data): + if boxed { + buffer.appendInt32(-181407105) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.parts, buffer: buffer, boxed: false) + serializeString(_data.name, buffer: buffer, boxed: false) + serializeString(_data.md5Checksum, buffer: buffer, boxed: false) + break + case .inputFileBig(let _data): + if boxed { + buffer.appendInt32(-95482955) + } + serializeInt64(_data.id, buffer: buffer, boxed: false) + serializeInt32(_data.parts, buffer: buffer, boxed: false) + serializeString(_data.name, buffer: buffer, boxed: false) + break + case .inputFileStoryDocument(let _data): + if boxed { + buffer.appendInt32(1658620744) + } + _data.id.serialize(buffer, true) + break + } + } + + public func descriptionFields() -> (String, [(String, Any)]) { + switch self { + case .inputFile(let _data): + return ("inputFile", [("id", _data.id as Any), ("parts", _data.parts as Any), ("name", _data.name as Any), ("md5Checksum", _data.md5Checksum as Any)]) + case .inputFileBig(let _data): + return ("inputFileBig", [("id", _data.id as Any), ("parts", _data.parts as Any), ("name", _data.name as Any)]) + case .inputFileStoryDocument(let _data): + return ("inputFileStoryDocument", [("id", _data.id as Any)]) + } + } + public static func parse_inputFile(_ reader: BufferReader) -> InputFile? { var _1: Int64? _1 = reader.readInt64() @@ -1001,11 +1325,12 @@ public extension Api { let _c2 = _2 != nil let _c3 = _3 != nil let _c4 = _4 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - if !_c4 { return nil } - return Api.InputFile.inputFile(id: _1!, parts: _2!, name: _3!, md5Checksum: _4!) + if _c1 && _c2 && _c3 && _c4 { + return Api.InputFile.inputFile(Cons_inputFile(id: _1!, parts: _2!, name: _3!, md5Checksum: _4!)) + } + else { + return nil + } } public static func parse_inputFileBig(_ reader: BufferReader) -> InputFile? { var _1: Int64? @@ -1017,10 +1342,12 @@ public extension Api { let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil - if !_c1 { return nil } - if !_c2 { return nil } - if !_c3 { return nil } - return Api.InputFile.inputFileBig(id: _1!, parts: _2!, name: _3!) + if _c1 && _c2 && _c3 { + return Api.InputFile.inputFileBig(Cons_inputFileBig(id: _1!, parts: _2!, name: _3!)) + } + else { + return nil + } } public static func parse_inputFileStoryDocument(_ reader: BufferReader) -> InputFile? { var _1: Api.InputDocument? @@ -1028,9 +1355,12 @@ public extension Api { _1 = Api.parse(reader, signature: signature) as? Api.InputDocument } let _c1 = _1 != nil - if !_c1 { return nil } - return Api.InputFile.inputFileStoryDocument(id: _1!) + if _c1 { + return Api.InputFile.inputFileStoryDocument(Cons_inputFileStoryDocument(id: _1!)) + } + else { + return nil + } } - } } diff --git a/submodules/TelegramApi/Sources/Buffer.swift b/submodules/TelegramApi/Sources/Buffer.swift index 4a58e1f7..8ec5a23b 100644 --- a/submodules/TelegramApi/Sources/Buffer.swift +++ b/submodules/TelegramApi/Sources/Buffer.swift @@ -363,13 +363,16 @@ public class BufferReader { if count == 0 { return 0 } - else if count > 0 && count <= 4 || self.offset + UInt(count) <= self.buffer._size { - var value: Int32 = 0 - memcpy(&value, self.buffer.data?.advanced(by: Int(self.offset)), count) - self.offset += UInt(count) - return value + guard count > 0, count <= 4, self.offset + UInt(count) <= self.buffer._size else { + return nil } - return nil + guard let bufferData = self.buffer.data else { + return nil + } + var value: Int32 = 0 + memcpy(&value, bufferData.advanced(by: Int(self.offset)), count) + self.offset += UInt(count) + return value } public func readBuffer(_ count: Int) -> Buffer? { diff --git a/submodules/TelegramAudio/BUILD b/submodules/TelegramAudio/BUILD index 31972298..091fa789 100644 --- a/submodules/TelegramAudio/BUILD +++ b/submodules/TelegramAudio/BUILD @@ -1,5 +1,9 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + swift_library( name = "TelegramAudio", module_name = "TelegramAudio", @@ -9,7 +13,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", ], visibility = [ diff --git a/submodules/TelegramAudio/Sources/ManagedAudioSession.swift b/submodules/TelegramAudio/Sources/ManagedAudioSession.swift index ab694dfc..ebe91816 100644 --- a/submodules/TelegramAudio/Sources/ManagedAudioSession.swift +++ b/submodules/TelegramAudio/Sources/ManagedAudioSession.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import SwiftSignalKit @@ -1071,6 +1072,10 @@ public final class ManagedAudioSessionImpl: NSObject, ManagedAudioSession { var alreadySet = false if self.isHeadsetPluggedInValue { if case .voiceCall = updatedType, case .custom(.builtin) = outputMode { + } else if SGSimpleSettings.shared.forceBuiltInMic { + let _ = try? AVAudioSession.sharedInstance().setPreferredInput( + routes.first { $0.portType == .builtInMic } + ) } else { loop: for route in routes { switch route.portType { diff --git a/submodules/TelegramCallsUI/Sources/CallKitIntegration.swift b/submodules/TelegramCallsUI/Sources/CallKitIntegration.swift index 74dc2a80..be26322e 100644 --- a/submodules/TelegramCallsUI/Sources/CallKitIntegration.swift +++ b/submodules/TelegramCallsUI/Sources/CallKitIntegration.swift @@ -1,3 +1,4 @@ +import SGAppGroupIdentifier import Foundation import UIKit import CallKit @@ -20,7 +21,7 @@ public final class CallKitIntegration { return false #else if #available(iOSApplicationExtension 10.0, iOS 10.0, *) { - return Locale.current.regionCode?.lowercased() != "cn" + return Locale.current.regionCode?.lowercased() != "cn" && !(UserDefaults(suiteName: sgAppGroupIdentifier())?.bool(forKey: "legacyNotificationsFix") ?? false) } else { return false } @@ -158,7 +159,8 @@ class CallKitProviderDelegate: NSObject, CXProviderDelegate { } private static func providerConfiguration() -> CXProviderConfiguration { - let providerConfiguration = CXProviderConfiguration(localizedName: "Telegram") + // MARK: Swiftgram + let providerConfiguration = CXProviderConfiguration(localizedName: "Swiftgram") providerConfiguration.supportsVideo = true providerConfiguration.maximumCallsPerCallGroup = 1 diff --git a/submodules/TelegramCallsUI/Sources/VideoChatScreen.swift b/submodules/TelegramCallsUI/Sources/VideoChatScreen.swift index fcf96a12..4f094167 100644 --- a/submodules/TelegramCallsUI/Sources/VideoChatScreen.swift +++ b/submodules/TelegramCallsUI/Sources/VideoChatScreen.swift @@ -3433,6 +3433,7 @@ final class VideoChatScreenComponent: Component { let presentationInterfaceState = ChatPresentationInterfaceState( chatWallpaper: .builtin(WallpaperSettings()), theme: presentationData.theme, + preferredGlassType: .default, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameDisplayOrder: presentationData.nameDisplayOrder, diff --git a/submodules/TelegramCore/BUILD b/submodules/TelegramCore/BUILD index 53c9a721..ef770a0b 100644 --- a/submodules/TelegramCore/BUILD +++ b/submodules/TelegramCore/BUILD @@ -1,15 +1,29 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SwiftSoup:SwiftSoup", + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//Swiftgram/SGTranslationLangFix:SGTranslationLangFix", + "//Swiftgram/SGWebSettingsScheme:SGWebSettingsScheme", + "//Swiftgram/SGGHSettingsScheme:SGGHSettingsScheme", + "//Swiftgram/SGConfig:SGConfig", + "//Swiftgram/SGLogging:SGLogging", +] + +sgsrc = [ + "//Swiftgram/SGIQTP:SGIQTP", +] + swift_library( name = "TelegramCore", module_name = "TelegramCore", - srcs = glob([ + srcs = sgsrc + glob([ "Sources/**/*.swift", ]), copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/TelegramApi:TelegramApi", "//submodules/MtProtoKit:MtProtoKit", "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", diff --git a/submodules/TelegramCore/FlatSerialization/.gitignore b/submodules/TelegramCore/FlatSerialization/.gitignore new file mode 100644 index 00000000..4fb5eb19 --- /dev/null +++ b/submodules/TelegramCore/FlatSerialization/.gitignore @@ -0,0 +1 @@ +Sources/ \ No newline at end of file diff --git a/submodules/TelegramCore/Package.swift b/submodules/TelegramCore/Package.swift index 9060a52b..91fb3410 100644 --- a/submodules/TelegramCore/Package.swift +++ b/submodules/TelegramCore/Package.swift @@ -45,6 +45,7 @@ let package = Package( .product(name: "FlatBuffers", package: "FlatBuffers", condition: nil), .product(name: "FlatSerialization", package: "FlatSerialization", condition: nil), .product(name: "EncryptionProvider", package: "EncryptionProvider", condition: nil)], - path: "Sources"), + path: "Sources", + swiftSettings: [.unsafeFlags(["-warnings-as-errors"])]), ] ) diff --git a/submodules/TelegramCore/Sources/Account/Account.swift b/submodules/TelegramCore/Sources/Account/Account.swift index 262176da..3719c1f7 100644 --- a/submodules/TelegramCore/Sources/Account/Account.swift +++ b/submodules/TelegramCore/Sources/Account/Account.swift @@ -121,7 +121,8 @@ public class UnauthorizedAccount { switch sentCode { case .sentCodePaymentRequired: break - case let .sentCode(_, type, phoneCodeHash, nextType, codeTimeout): + case let .sentCode(sentCodeData): + let (type, phoneCodeHash, nextType, codeTimeout) = (sentCodeData.type, sentCodeData.phoneCodeHash, sentCodeData.nextType, sentCodeData.timeout) let _ = postbox.transaction({ transaction in var parsedNextType: AuthorizationCodeNextType? if let nextType = nextType { @@ -131,20 +132,22 @@ public class UnauthorizedAccount { transaction.setState(UnauthorizedAccountState(isTestingEnvironment: testingEnvironment, masterDatacenterId: masterDatacenterId, contents: .confirmationCodeEntry(number: phoneNumber, type: SentAuthorizationCodeType(apiType: type), hash: phoneCodeHash, timeout: codeTimeout, nextType: parsedNextType, syncContacts: syncContacts, previousCodeEntry: nil, usePrevious: false))) } }).start() - case let .sentCodeSuccess(authorization): + case let .sentCodeSuccess(sentCodeSuccessData): + let authorization = sentCodeSuccessData.authorization switch authorization { - case let .authorization(_, _, _, futureAuthToken, user): + case let .authorization(authorizationData): + let (futureAuthToken, apiUser) = (authorizationData.futureAuthToken, authorizationData.user) let _ = postbox.transaction({ [weak self] transaction in var syncContacts = true if let state = transaction.getState() as? UnauthorizedAccountState, case let .payment(_, _, _, _, _, syncContactsValue) = state.contents { syncContacts = syncContactsValue } - + if let futureAuthToken = futureAuthToken { storeFutureLoginToken(accountManager: accountManager, token: futureAuthToken.makeData()) } - - let user = TelegramUser(user: user) + + let user = TelegramUser(user: apiUser) var isSupportUser = false if let phone = user.phone, phone.hasPrefix("42"), phone.count <= 5 { isSupportUser = true @@ -159,7 +162,8 @@ public class UnauthorizedAccount { return .loggedIn } }).start() - case let .authorizationSignUpRequired(_, termsOfService): + case let .authorizationSignUpRequired(authorizationSignUpRequiredData): + let termsOfService = authorizationSignUpRequiredData.termsOfService let _ = postbox.transaction({ [weak self] transaction in if let self { if let state = transaction.getState() as? UnauthorizedAccountState, case let .payment(number, codeHash, _, _, _, syncContacts) = state.contents { @@ -364,7 +368,8 @@ public enum TwoStepPasswordDerivation { switch apiAlgo { case .passwordKdfAlgoUnknown: self = .unknown - case let .passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow(salt1, salt2, g, p): + case let .passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow(passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPowData): + let (salt1, salt2, g, p) = (passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPowData.salt1, passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPowData.salt2, passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPowData.g, passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPowData.p) self = .sha256_sha256_PBKDF2_HMAC_sha512_sha256_srp(salt1: salt1.makeData(), salt2: salt2.makeData(), iterations: 100000, g: g, p: p.makeData()) } } @@ -375,7 +380,7 @@ public enum TwoStepPasswordDerivation { return .passwordKdfAlgoUnknown case let .sha256_sha256_PBKDF2_HMAC_sha512_sha256_srp(salt1, salt2, iterations, g, p): precondition(iterations == 100000) - return .passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow(salt1: Buffer(data: salt1), salt2: Buffer(data: salt2), g: g, p: Buffer(data: p)) + return .passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow(.init(salt1: Buffer(data: salt1), salt2: Buffer(data: salt2), g: g, p: Buffer(data: p))) } } } @@ -389,9 +394,11 @@ public enum TwoStepSecurePasswordDerivation { switch apiAlgo { case .securePasswordKdfAlgoUnknown: self = .unknown - case let .securePasswordKdfAlgoPBKDF2HMACSHA512iter100000(salt): + case let .securePasswordKdfAlgoPBKDF2HMACSHA512iter100000(securePasswordKdfAlgoPBKDF2HMACSHA512iter100000Data): + let (salt) = (securePasswordKdfAlgoPBKDF2HMACSHA512iter100000Data.salt) self = .PBKDF2_HMAC_sha512(salt: salt.makeData(), iterations: 100000) - case let .securePasswordKdfAlgoSHA512(salt): + case let .securePasswordKdfAlgoSHA512(securePasswordKdfAlgoSHA512Data): + let (salt) = (securePasswordKdfAlgoSHA512Data.salt) self = .sha512(salt: salt.makeData()) } } @@ -402,9 +409,9 @@ public enum TwoStepSecurePasswordDerivation { return .securePasswordKdfAlgoUnknown case let .PBKDF2_HMAC_sha512(salt, iterations): precondition(iterations == 100000) - return .securePasswordKdfAlgoPBKDF2HMACSHA512iter100000(salt: Buffer(data: salt)) + return .securePasswordKdfAlgoPBKDF2HMACSHA512iter100000(.init(salt: Buffer(data: salt))) case let .sha512(salt): - return .securePasswordKdfAlgoSHA512(salt: Buffer(data: salt)) + return .securePasswordKdfAlgoSHA512(.init(salt: Buffer(data: salt))) } } } @@ -432,7 +439,8 @@ func _internal_twoStepAuthData(_ network: Network) -> Signal map { config -> TwoStepAuthData in switch config { - case let .password(flags, currentAlgo, srpB, srpId, hint, emailUnconfirmedPattern, newAlgo, newSecureAlgo, secureRandom, pendingResetDate, loginEmailPattern): + case let .password(passwordData): + let (flags, currentAlgo, srpB, srpId, hint, emailUnconfirmedPattern, newAlgo, newSecureAlgo, secureRandom, pendingResetDate, loginEmailPattern) = (passwordData.flags, passwordData.currentAlgo, passwordData.srpB, passwordData.srpId, passwordData.hint, passwordData.emailUnconfirmedPattern, passwordData.newAlgo, passwordData.newSecureAlgo, passwordData.secureRandom, passwordData.pendingResetDate, passwordData.loginEmailPattern) let hasRecovery = (flags & (1 << 0)) != 0 let hasSecureValues = (flags & (1 << 1)) != 0 @@ -497,7 +505,8 @@ public final class TelegramPasskey: Equatable { extension TelegramPasskey { convenience init(apiPasskey: Api.Passkey) { switch apiPasskey { - case let .passkey(_, id, name, date, softwareEmojiId, lastUsageDate): + case let .passkey(passkeyData): + let (id, name, date, softwareEmojiId, lastUsageDate) = (passkeyData.id, passkeyData.name, passkeyData.date, passkeyData.softwareEmojiId, passkeyData.lastUsageDate) self.init(id: id, name: name, date: date, emojiId: softwareEmojiId, lastUsageDate: lastUsageDate) } } @@ -514,7 +523,8 @@ func _internal_passkeysData(network: Network) -> Signal<[TelegramPasskey], NoErr return [] } switch passkeys { - case let .passkeys(passkeys): + case let .passkeys(passkeysData): + let passkeys = passkeysData.passkeys return passkeys.map { passkey in return TelegramPasskey(apiPasskey: passkey) } @@ -533,9 +543,11 @@ func _internal_requestPasskeyRegistration(network: Network) -> Signal Signal Signal { - return network.request(Api.functions.account.registerPasskey(credential: .inputPasskeyCredentialPublicKey(id: id, rawId: id, response: .inputPasskeyResponseRegister(clientData: .dataJSON(data: clientData), attestationData: Buffer(data: attestationObject))))) + return network.request(Api.functions.account.registerPasskey(credential: .inputPasskeyCredentialPublicKey(.init(id: id, rawId: id, response: .inputPasskeyResponseRegister(.init(clientData: .dataJSON(.init(data: clientData)), attestationData: Buffer(data: attestationObject))))))) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -575,9 +587,11 @@ func _internal_requestPasskeyLoginData(network: Network, apiId: Int32, apiHash: return nil } switch result { - case let .passkeyLoginOptions(options): + case let .passkeyLoginOptions(passkeyLoginOptionsData): + let options = passkeyLoginOptionsData.options switch options { - case let .dataJSON(data): + case let .dataJSON(dataJSONData): + let data = dataJSONData.data return data } } @@ -864,7 +878,7 @@ func verifyPassword(_ account: UnauthorizedAccount, password: String) -> Signal< let kdfResult = passwordKDF(encryptionProvider: account.network.encryptionProvider, password: password, derivation: currentPasswordDerivation, srpSessionData: srpSessionData) if let kdfResult = kdfResult { - return account.network.request(Api.functions.auth.checkPassword(password: .inputCheckPasswordSRP(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1))), automaticFloodWait: false) + return account.network.request(Api.functions.auth.checkPassword(password: .inputCheckPasswordSRP(.init(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1)))), automaticFloodWait: false) } else { return .fail(MTRpcError(errorCode: 400, errorDescription: "KDF_ERROR")) } @@ -1523,7 +1537,7 @@ public class Account { return .complete() } else { return network.request(Api.functions.help.saveAppLog(events: events.map { event -> Api.InputAppEvent in - return .inputAppEvent(time: event.0, type: "", peer: 0, data: .jsonString(value: event.1)) + return .inputAppEvent(.init(time: event.0, type: "", peer: 0, data: .jsonString(.init(value: event.1)))) })) |> ignoreValues |> `catch` { _ -> Signal in diff --git a/submodules/TelegramCore/Sources/Account/AccountIntermediateState.swift b/submodules/TelegramCore/Sources/Account/AccountIntermediateState.swift index fbc85e9e..207d05b1 100644 --- a/submodules/TelegramCore/Sources/Account/AccountIntermediateState.swift +++ b/submodules/TelegramCore/Sources/Account/AccountIntermediateState.swift @@ -508,7 +508,8 @@ struct AccountMutableState { for chat in chats { switch chat { - case let .channel(_, _, _, _, _, _, _, _, _, _, _, _, participantsCount, _, _, _, _, _, _, _, _, _, _): + case let .channel(channelData): + let participantsCount = channelData.participantsCount if let participantsCount = participantsCount { self.addOperation(.UpdateCachedPeerData(chat.peerId, { current in var previous: CachedChannelData @@ -572,7 +573,8 @@ struct AccountMutableState { var presences: [PeerId: Api.UserStatus] = [:] for user in users { switch user { - case let .user(_, _, id, _, _, _, _, _, _, status, _, _, _, _, _, _, _, _, _, _, _, _): + case let .user(userData): + let (id, status) = (userData.id, userData.status) if let status = status { presences[PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(id))] = status } diff --git a/submodules/TelegramCore/Sources/Account/AccountManager.swift b/submodules/TelegramCore/Sources/Account/AccountManager.swift index 9897b02c..0f0aeb7c 100644 --- a/submodules/TelegramCore/Sources/Account/AccountManager.swift +++ b/submodules/TelegramCore/Sources/Account/AccountManager.swift @@ -215,6 +215,8 @@ private var declaredEncodables: Void = { declareEncodable(AuthSessionInfoAttribute.self, f: { AuthSessionInfoAttribute(decoder: $0) }) declareEncodable(TranslationMessageAttribute.self, f: { TranslationMessageAttribute(decoder: $0) }) declareEncodable(TranslationMessageAttribute.Additional.self, f: { TranslationMessageAttribute.Additional(decoder: $0) }) + // MARK: Swiftgram + declareEncodable(QuickTranslationMessageAttribute.self, f: { QuickTranslationMessageAttribute(decoder: $0) }) declareEncodable(SynchronizeAutosaveItemOperation.self, f: { SynchronizeAutosaveItemOperation(decoder: $0) }) declareEncodable(TelegramMediaStory.self, f: { TelegramMediaStory(decoder: $0) }) declareEncodable(SynchronizeViewStoriesOperation.self, f: { SynchronizeViewStoriesOperation(decoder: $0) }) @@ -502,7 +504,8 @@ private func cleanupAccount(networkArguments: NetworkInitializationArguments, ac } |> mapToSignal { result -> Signal in switch result { - case let .loggedOut(_, futureAuthToken): + case let .loggedOut(loggedOutData): + let futureAuthToken = loggedOutData.futureAuthToken if let futureAuthToken = futureAuthToken { storeFutureLoginToken(accountManager: accountManager, token: futureAuthToken.makeData()) } diff --git a/submodules/TelegramCore/Sources/AntiDelete/DeletedMessageAttribute.swift b/submodules/TelegramCore/Sources/AntiDelete/DeletedMessageAttribute.swift index 7e80867d..c2d622f8 100644 --- a/submodules/TelegramCore/Sources/AntiDelete/DeletedMessageAttribute.swift +++ b/submodules/TelegramCore/Sources/AntiDelete/DeletedMessageAttribute.swift @@ -44,4 +44,14 @@ public extension Message { var deletedMessageAttribute: DeletedMessageAttribute? { return self.attributes.first(where: { $0 is DeletedMessageAttribute }) as? DeletedMessageAttribute } + + var ghostgramIsDeleted: Bool { + if self.isDeletedButVisible { + return true + } + if AntiDeleteManager.shared.isMessageDeleted(peerId: self.id.peerId.toInt64(), messageId: self.id.id) { + return true + } + return AntiDeleteManager.shared.isMessageDeleted(text: self.text) + } } diff --git a/submodules/TelegramCore/Sources/ApiUtils/ApiGroupOrChannel.swift b/submodules/TelegramCore/Sources/ApiUtils/ApiGroupOrChannel.swift index d8e49deb..7ddee04d 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/ApiGroupOrChannel.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/ApiGroupOrChannel.swift @@ -6,7 +6,8 @@ import TelegramApi func imageRepresentationsForApiChatPhoto(_ photo: Api.ChatPhoto) -> [TelegramMediaImageRepresentation] { var representations: [TelegramMediaImageRepresentation] = [] switch photo { - case let .chatPhoto(flags, photoId, strippedThumb, dcId): + case let .chatPhoto(chatPhotoData): + let (flags, photoId, strippedThumb, dcId) = (chatPhotoData.flags, chatPhotoData.photoId, chatPhotoData.strippedThumb, chatPhotoData.dcId) let hasVideo = (flags & (1 << 0)) != 0 let smallResource: TelegramMediaResource let fullSizeResource: TelegramMediaResource @@ -24,12 +25,14 @@ func imageRepresentationsForApiChatPhoto(_ photo: Api.ChatPhoto) -> [TelegramMed func parseTelegramGroupOrChannel(chat: Api.Chat) -> Peer? { switch chat { - case let .chat(flags, id, title, photo, participantsCount, date, version, migratedTo, adminRights, defaultBannedRights): + case let .chat(chatData): + let (flags, id, title, photo, participantsCount, date, version, migratedTo, adminRights, defaultBannedRights) = (chatData.flags, chatData.id, chatData.title, chatData.photo, chatData.participantsCount, chatData.date, chatData.version, chatData.migratedTo, chatData.adminRights, chatData.defaultBannedRights) let left = (flags & ((1 << 1) | (1 << 2))) != 0 var migrationReference: TelegramGroupToChannelMigrationReference? if let migratedTo = migratedTo { switch migratedTo { - case let .inputChannel(channelId, accessHash): + case let .inputChannel(inputChannelData): + let (channelId, accessHash) = (inputChannelData.channelId, inputChannelData.accessHash) migrationReference = TelegramGroupToChannelMigrationReference(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)), accessHash: accessHash) case .inputChannelEmpty: break @@ -57,11 +60,14 @@ func parseTelegramGroupOrChannel(chat: Api.Chat) -> Peer? { groupFlags.insert(.copyProtectionEnabled) } return TelegramGroup(id: PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(id)), title: title, photo: imageRepresentationsForApiChatPhoto(photo), participantCount: Int(participantsCount), role: role, membership: left ? .Left : .Member, flags: groupFlags, defaultBannedRights: defaultBannedRights.flatMap(TelegramChatBannedRights.init(apiBannedRights:)), migrationReference: migrationReference, creationDate: date, version: Int(version)) - case let .chatEmpty(id): + case let .chatEmpty(chatEmptyData): + let id = chatEmptyData.id return TelegramGroup(id: PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(id)), title: "", photo: [], participantCount: 0, role: .member, membership: .Removed, flags: [], defaultBannedRights: nil, migrationReference: nil, creationDate: 0, version: 0) - case let .chatForbidden(id, title): + case let .chatForbidden(chatForbiddenData): + let (id, title) = (chatForbiddenData.id, chatForbiddenData.title) return TelegramGroup(id: PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(id)), title: title, photo: [], participantCount: 0, role: .member, membership: .Removed, flags: [], defaultBannedRights: nil, migrationReference: nil, creationDate: 0, version: 0) - case let .channel(flags, flags2, id, accessHash, title, username, photo, date, restrictionReason, adminRights, bannedRights, defaultBannedRights, _, usernames, _, color, profileColor, emojiStatus, boostLevel, subscriptionUntilDate, verificationIconFileId, sendPaidMessageStars, linkedMonoforumId): + case let .channel(channelData): + let (flags, flags2, id, accessHash, title, username, photo, date, restrictionReason, adminRights, bannedRights, defaultBannedRights, usernames, color, profileColor, emojiStatus, boostLevel, subscriptionUntilDate, verificationIconFileId, sendPaidMessageStars, linkedMonoforumId) = (channelData.flags, channelData.flags2, channelData.id, channelData.accessHash, channelData.title, channelData.username, channelData.photo, channelData.date, channelData.restrictionReason, channelData.adminRights, channelData.bannedRights, channelData.defaultBannedRights, channelData.usernames, channelData.color, channelData.profileColor, channelData.emojiStatus, channelData.level, channelData.subscriptionUntilDate, channelData.botVerificationIcon, channelData.sendPaidMessagesStars, channelData.linkedMonoforumId) let isMin = (flags & (1 << 12)) != 0 let participationStatus: TelegramChannelParticipationStatus @@ -172,7 +178,8 @@ func parseTelegramGroupOrChannel(chat: Api.Chat) -> Peer? { var backgroundEmojiId: Int64? if let color = color { switch color { - case let .peerColor(_, color, backgroundEmojiIdValue): + case let .peerColor(peerColorData): + let (_, color, backgroundEmojiIdValue) = (peerColorData.flags, peerColorData.color, peerColorData.backgroundEmojiId) nameColorIndex = color backgroundEmojiId = backgroundEmojiIdValue case .peerColorCollectible: @@ -181,21 +188,23 @@ func parseTelegramGroupOrChannel(chat: Api.Chat) -> Peer? { break } } - + var profileColorIndex: Int32? var profileBackgroundEmojiId: Int64? if let profileColor = profileColor { switch profileColor { - case let .peerColor(_, color, backgroundEmojiIdValue): + case let .peerColor(peerColorData): + let (_, color, backgroundEmojiIdValue) = (peerColorData.flags, peerColorData.color, peerColorData.backgroundEmojiId) profileColorIndex = color profileBackgroundEmojiId = backgroundEmojiIdValue default: break } } - + return TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(id)), accessHash: accessHashValue, title: title, username: username, photo: imageRepresentationsForApiChatPhoto(photo), creationDate: date, version: 0, participationStatus: participationStatus, info: info, flags: channelFlags, restrictionInfo: restrictionInfo, adminRights: adminRights.flatMap(TelegramChatAdminRights.init), bannedRights: bannedRights.flatMap(TelegramChatBannedRights.init), defaultBannedRights: defaultBannedRights.flatMap(TelegramChatBannedRights.init), usernames: usernames?.map(TelegramPeerUsername.init(apiUsername:)) ?? [], storiesHidden: storiesHidden, nameColor: nameColorIndex.flatMap { PeerNameColor(rawValue: $0) }, backgroundEmojiId: backgroundEmojiId, profileColor: profileColorIndex.flatMap { PeerNameColor(rawValue: $0) }, profileBackgroundEmojiId: profileBackgroundEmojiId, emojiStatus: emojiStatus.flatMap(PeerEmojiStatus.init(apiStatus:)), approximateBoostLevel: boostLevel, subscriptionUntilDate: subscriptionUntilDate, verificationIconFileId: verificationIconFileId, sendPaidMessageStars: sendPaidMessageStars.flatMap { StarsAmount(value: $0, nanos: 0) }, linkedMonoforumId: linkedMonoforumId.flatMap { PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value($0)) }) - case let .channelForbidden(flags, id, accessHash, title, untilDate): + case let .channelForbidden(channelForbiddenData): + let (flags, id, accessHash, title, untilDate) = (channelForbiddenData.flags, channelForbiddenData.id, channelForbiddenData.accessHash, channelForbiddenData.title, channelForbiddenData.untilDate) let info: TelegramChannelInfo if (flags & Int32(1 << 8)) != 0 { info = .group(TelegramChannelGroupInfo(flags: [])) @@ -203,7 +212,12 @@ func parseTelegramGroupOrChannel(chat: Api.Chat) -> Peer? { info = .broadcast(TelegramChannelBroadcastInfo(flags: [])) } - return TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(id)), accessHash: .personal(accessHash), title: title, username: nil, photo: [], creationDate: 0, version: 0, participationStatus: .kicked, info: info, flags: TelegramChannelFlags(), restrictionInfo: nil, adminRights: nil, bannedRights: TelegramChatBannedRights(flags: [.banReadMessages], untilDate: untilDate ?? Int32.max), defaultBannedRights: nil, usernames: [], storiesHidden: nil, nameColor: nil, backgroundEmojiId: nil, profileColor: nil, profileBackgroundEmojiId: nil, emojiStatus: nil, approximateBoostLevel: nil, subscriptionUntilDate: nil, verificationIconFileId: nil, sendPaidMessageStars: nil, linkedMonoforumId: nil) + var channelFlags = TelegramChannelFlags() + if (flags & (1 << 10)) != 0 { + channelFlags.insert(.isMonoforum) + } + + return TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(id)), accessHash: .personal(accessHash), title: title, username: nil, photo: [], creationDate: 0, version: 0, participationStatus: .kicked, info: info, flags: channelFlags, restrictionInfo: nil, adminRights: nil, bannedRights: TelegramChatBannedRights(flags: [.banReadMessages], untilDate: untilDate ?? Int32.max), defaultBannedRights: nil, usernames: [], storiesHidden: nil, nameColor: nil, backgroundEmojiId: nil, profileColor: nil, profileBackgroundEmojiId: nil, emojiStatus: nil, approximateBoostLevel: nil, subscriptionUntilDate: nil, verificationIconFileId: nil, sendPaidMessageStars: nil, linkedMonoforumId: nil) } } @@ -211,7 +225,8 @@ func mergeGroupOrChannel(lhs: Peer?, rhs: Api.Chat) -> Peer? { switch rhs { case .chat, .chatEmpty, .chatForbidden, .channelForbidden: return parseTelegramGroupOrChannel(chat: rhs) - case let .channel(flags, flags2, _, accessHash, title, username, photo, _, _, _, _, defaultBannedRights, _, usernames, _, color, profileColor, emojiStatus, boostLevel, subscriptionUntilDate, verificationIconFileId, sendPaidMessageStars, linkedMonoforumIdValue): + case let .channel(channelData): + let (flags, flags2, accessHash, title, username, photo, defaultBannedRights, usernames, color, profileColor, emojiStatus, boostLevel, subscriptionUntilDate, verificationIconFileId, sendPaidMessageStars, linkedMonoforumIdValue) = (channelData.flags, channelData.flags2, channelData.accessHash, channelData.title, channelData.username, channelData.photo, channelData.defaultBannedRights, channelData.usernames, channelData.color, channelData.profileColor, channelData.emojiStatus, channelData.level, channelData.subscriptionUntilDate, channelData.botVerificationIcon, channelData.sendPaidMessagesStars, channelData.linkedMonoforumId) let isMin = (flags & (1 << 12)) != 0 if accessHash != nil && !isMin { return parseTelegramGroupOrChannel(chat: rhs) @@ -257,7 +272,8 @@ func mergeGroupOrChannel(lhs: Peer?, rhs: Api.Chat) -> Peer? { var backgroundEmojiId: Int64? if let color = color { switch color { - case let .peerColor(_, color, backgroundEmojiIdValue): + case let .peerColor(peerColorData): + let (_, color, backgroundEmojiIdValue) = (peerColorData.flags, peerColorData.color, peerColorData.backgroundEmojiId) nameColorIndex = color backgroundEmojiId = backgroundEmojiIdValue case .peerColorCollectible: @@ -266,19 +282,20 @@ func mergeGroupOrChannel(lhs: Peer?, rhs: Api.Chat) -> Peer? { break } } - + var profileColorIndex: Int32? var profileBackgroundEmojiId: Int64? if let profileColor = profileColor { switch profileColor { - case let .peerColor(_, color, backgroundEmojiIdValue): + case let .peerColor(peerColorData): + let (_, color, backgroundEmojiIdValue) = (peerColorData.flags, peerColorData.color, peerColorData.backgroundEmojiId) profileColorIndex = color profileBackgroundEmojiId = backgroundEmojiIdValue default: break } } - + let parsedEmojiStatus = emojiStatus.flatMap(PeerEmojiStatus.init(apiStatus:)) let linkedMonoforumId = linkedMonoforumIdValue.flatMap({ PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value($0)) }) ?? lhs.linkedMonoforumId diff --git a/submodules/TelegramCore/Sources/ApiUtils/ApiUtils.swift b/submodules/TelegramCore/Sources/ApiUtils/ApiUtils.swift index dfeb3a34..43a8d691 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/ApiUtils.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/ApiUtils.swift @@ -20,17 +20,17 @@ extension PeerReference { var inputPeer: Api.InputPeer { switch self { case let .user(id, accessHash): - return .inputPeerUser(userId: id, accessHash: accessHash) + return .inputPeerUser(.init(userId: id, accessHash: accessHash)) case let .group(id): - return .inputPeerChat(chatId: id) + return .inputPeerChat(.init(chatId: id)) case let .channel(id, accessHash): - return .inputPeerChannel(channelId: id, accessHash: accessHash) + return .inputPeerChannel(.init(channelId: id, accessHash: accessHash)) } } var inputUser: Api.InputUser? { if case let .user(id, accessHash) = self { - return .inputUser(userId: id, accessHash: accessHash) + return .inputUser(.init(userId: id, accessHash: accessHash)) } else { return nil } @@ -38,7 +38,7 @@ extension PeerReference { var inputChannel: Api.InputChannel? { if case let .channel(id, accessHash) = self { - return .inputChannel(channelId: id, accessHash: accessHash) + return .inputChannel(.init(channelId: id, accessHash: accessHash)) } else { return nil } @@ -48,12 +48,12 @@ extension PeerReference { func forceApiInputPeer(_ peer: Peer) -> Api.InputPeer? { switch peer { case let user as TelegramUser: - return Api.InputPeer.inputPeerUser(userId: user.id.id._internalGetInt64Value(), accessHash: user.accessHash?.value ?? 0) + return Api.InputPeer.inputPeerUser(.init(userId: user.id.id._internalGetInt64Value(), accessHash: user.accessHash?.value ?? 0)) case let group as TelegramGroup: - return Api.InputPeer.inputPeerChat(chatId: group.id.id._internalGetInt64Value()) + return Api.InputPeer.inputPeerChat(.init(chatId: group.id.id._internalGetInt64Value())) case let channel as TelegramChannel: if let accessHash = channel.accessHash { - return Api.InputPeer.inputPeerChannel(channelId: channel.id.id._internalGetInt64Value(), accessHash: accessHash.value) + return Api.InputPeer.inputPeerChannel(.init(channelId: channel.id.id._internalGetInt64Value(), accessHash: accessHash.value)) } else { return nil } @@ -65,12 +65,12 @@ func forceApiInputPeer(_ peer: Peer) -> Api.InputPeer? { func apiInputPeer(_ peer: Peer) -> Api.InputPeer? { switch peer { case let user as TelegramUser where user.accessHash != nil: - return Api.InputPeer.inputPeerUser(userId: user.id.id._internalGetInt64Value(), accessHash: user.accessHash!.value) + return Api.InputPeer.inputPeerUser(.init(userId: user.id.id._internalGetInt64Value(), accessHash: user.accessHash!.value)) case let group as TelegramGroup: - return Api.InputPeer.inputPeerChat(chatId: group.id.id._internalGetInt64Value()) + return Api.InputPeer.inputPeerChat(.init(chatId: group.id.id._internalGetInt64Value())) case let channel as TelegramChannel: if let accessHash = channel.accessHash { - return Api.InputPeer.inputPeerChannel(channelId: channel.id.id._internalGetInt64Value(), accessHash: accessHash.value) + return Api.InputPeer.inputPeerChannel(.init(channelId: channel.id.id._internalGetInt64Value(), accessHash: accessHash.value)) } else { return nil } @@ -88,7 +88,7 @@ func apiInputPeerOrSelf(_ peer: Peer, accountPeerId: PeerId) -> Api.InputPeer? { func apiInputChannel(_ peer: Peer) -> Api.InputChannel? { if let channel = peer as? TelegramChannel, let accessHash = channel.accessHash { - return Api.InputChannel.inputChannel(channelId: channel.id.id._internalGetInt64Value(), accessHash: accessHash.value) + return Api.InputChannel.inputChannel(.init(channelId: channel.id.id._internalGetInt64Value(), accessHash: accessHash.value)) } else { return nil } @@ -96,7 +96,7 @@ func apiInputChannel(_ peer: Peer) -> Api.InputChannel? { func apiInputUser(_ peer: Peer) -> Api.InputUser? { if let user = peer as? TelegramUser, let accessHash = user.accessHash { - return Api.InputUser.inputUser(userId: user.id.id._internalGetInt64Value(), accessHash: accessHash.value) + return Api.InputUser.inputUser(.init(userId: user.id.id._internalGetInt64Value(), accessHash: accessHash.value)) } else { return nil } @@ -104,7 +104,7 @@ func apiInputUser(_ peer: Peer) -> Api.InputUser? { func apiInputSecretChat(_ peer: Peer) -> Api.InputEncryptedChat? { if let chat = peer as? TelegramSecretChat { - return Api.InputEncryptedChat.inputEncryptedChat(chatId: Int32(peer.id.id._internalGetInt64Value()), accessHash: chat.accessHash) + return Api.InputEncryptedChat.inputEncryptedChat(.init(chatId: Int32(peer.id.id._internalGetInt64Value()), accessHash: chat.accessHash)) } else { return nil } diff --git a/submodules/TelegramCore/Sources/ApiUtils/BotInfo.swift b/submodules/TelegramCore/Sources/ApiUtils/BotInfo.swift index b12c38fa..327ae0b2 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/BotInfo.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/BotInfo.swift @@ -7,7 +7,8 @@ extension BotMenuButton { switch apiBotMenuButton { case .botMenuButtonCommands, .botMenuButtonDefault: self = .commands - case let .botMenuButton(text, url): + case let .botMenuButton(botMenuButtonData): + let (text, url) = (botMenuButtonData.text, botMenuButtonData.url) self = .webView(text: text, url: url) } } @@ -16,7 +17,8 @@ extension BotMenuButton { extension BotAppSettings { init(apiBotAppSettings: Api.BotAppSettings) { switch apiBotAppSettings { - case let .botAppSettings(_, placeholder, backgroundColor, backgroundDarkColor, headerColor, headerDarkColor): + case let .botAppSettings(botAppSettingsData): + let (_, placeholder, backgroundColor, backgroundDarkColor, headerColor, headerDarkColor) = (botAppSettingsData.flags, botAppSettingsData.placeholderPath, botAppSettingsData.backgroundColor, botAppSettingsData.backgroundDarkColor, botAppSettingsData.headerColor, botAppSettingsData.headerDarkColor) self.init( placeholderData: placeholder.flatMap { $0.makeData() }, backgroundColor: backgroundColor, @@ -31,7 +33,8 @@ extension BotAppSettings { extension BotVerifierSettings { init(apiBotVerifierSettings: Api.BotVerifierSettings) { switch apiBotVerifierSettings { - case let .botVerifierSettings(flags, iconFileId, companyName, customDescription): + case let .botVerifierSettings(botVerifierSettingsData): + let (flags, iconFileId, companyName, customDescription) = (botVerifierSettingsData.flags, botVerifierSettingsData.icon, botVerifierSettingsData.company, botVerifierSettingsData.customDescription) self.init( iconFileId: iconFileId, companyName: companyName, @@ -45,14 +48,16 @@ extension BotVerifierSettings { extension BotInfo { convenience init(apiBotInfo: Api.BotInfo) { switch apiBotInfo { - case let .botInfo(_, _, description, descriptionPhoto, descriptionDocument, apiCommands, apiMenuButton, privacyPolicyUrl, appSettings, verifierSettings): + case let .botInfo(botInfoData): + let (_, _, description, descriptionPhoto, descriptionDocument, apiCommands, apiMenuButton, privacyPolicyUrl, appSettings, verifierSettings) = (botInfoData.flags, botInfoData.userId, botInfoData.description, botInfoData.descriptionPhoto, botInfoData.descriptionDocument, botInfoData.commands, botInfoData.menuButton, botInfoData.privacyPolicyUrl, botInfoData.appSettings, botInfoData.verifierSettings) let photo: TelegramMediaImage? = descriptionPhoto.flatMap(telegramMediaImageFromApiPhoto) let video: TelegramMediaFile? = descriptionDocument.flatMap { telegramMediaFileFromApiDocument($0, altDocuments: []) } var commands: [BotCommand] = [] if let apiCommands = apiCommands { commands = apiCommands.map { command in switch command { - case let .botCommand(command, description): + case let .botCommand(botCommandData): + let (command, description) = (botCommandData.command, botCommandData.description) return BotCommand(text: command, description: description) } } diff --git a/submodules/TelegramCore/Sources/ApiUtils/CachedChannelParticipants.swift b/submodules/TelegramCore/Sources/ApiUtils/CachedChannelParticipants.swift index 2adf13b3..b2db354f 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/CachedChannelParticipants.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/CachedChannelParticipants.swift @@ -205,19 +205,25 @@ public final class CachedChannelParticipants: PostboxCoding, Equatable { extension ChannelParticipant { init(apiParticipant: Api.ChannelParticipant) { switch apiParticipant { - case let .channelParticipant(_, userId, date, subscriptionUntilDate): + case let .channelParticipant(channelParticipantData): + let (_, userId, date, subscriptionUntilDate) = (channelParticipantData.flags, channelParticipantData.userId, channelParticipantData.date, channelParticipantData.subscriptionUntilDate) self = .member(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), invitedAt: date, adminInfo: nil, banInfo: nil, rank: nil, subscriptionUntilDate: subscriptionUntilDate) - case let .channelParticipantCreator(_, userId, adminRights, rank): + case let .channelParticipantCreator(channelParticipantCreatorData): + let (_, userId, adminRights, rank) = (channelParticipantCreatorData.flags, channelParticipantCreatorData.userId, channelParticipantCreatorData.adminRights, channelParticipantCreatorData.rank) self = .creator(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(apiAdminRights: adminRights) ?? TelegramChatAdminRights(rights: []), promotedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), canBeEditedByAccountPeer: true), rank: rank) - case let .channelParticipantBanned(flags, userId, restrictedBy, date, bannedRights): + case let .channelParticipantBanned(channelParticipantBannedData): + let (flags, userId, restrictedBy, date, bannedRights) = (channelParticipantBannedData.flags, channelParticipantBannedData.peer, channelParticipantBannedData.kickedBy, channelParticipantBannedData.date, channelParticipantBannedData.bannedRights) let hasLeft = (flags & (1 << 0)) != 0 let banInfo = ChannelParticipantBannedInfo(rights: TelegramChatBannedRights(apiBannedRights: bannedRights), restrictedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(restrictedBy)), timestamp: date, isMember: !hasLeft) self = .member(id: userId.peerId, invitedAt: date, adminInfo: nil, banInfo: banInfo, rank: nil, subscriptionUntilDate: nil) - case let .channelParticipantAdmin(flags, userId, _, promotedBy, date, adminRights, rank: rank): + case let .channelParticipantAdmin(channelParticipantAdminData): + let (flags, userId, _, promotedBy, date, adminRights, rank) = (channelParticipantAdminData.flags, channelParticipantAdminData.userId, channelParticipantAdminData.inviterId, channelParticipantAdminData.promotedBy, channelParticipantAdminData.date, channelParticipantAdminData.adminRights, channelParticipantAdminData.rank) self = .member(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), invitedAt: date, adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(apiAdminRights: adminRights) ?? TelegramChatAdminRights(rights: []), promotedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(promotedBy)), canBeEditedByAccountPeer: (flags & (1 << 0)) != 0), banInfo: nil, rank: rank, subscriptionUntilDate: nil) - case let .channelParticipantSelf(_, userId, _, date, subscriptionUntilDate): + case let .channelParticipantSelf(channelParticipantSelfData): + let (_, userId, _, date, subscriptionUntilDate) = (channelParticipantSelfData.flags, channelParticipantSelfData.userId, channelParticipantSelfData.inviterId, channelParticipantSelfData.date, channelParticipantSelfData.subscriptionUntilDate) self = .member(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), invitedAt: date, adminInfo: nil, banInfo: nil, rank: nil, subscriptionUntilDate: subscriptionUntilDate) - case let .channelParticipantLeft(userId): + case let .channelParticipantLeft(channelParticipantLeftData): + let (userId) = (channelParticipantLeftData.peer) self = .member(id: userId.peerId, invitedAt: 0, adminInfo: nil, banInfo: nil, rank: nil, subscriptionUntilDate: nil) } } diff --git a/submodules/TelegramCore/Sources/ApiUtils/CachedGroupParticipants.swift b/submodules/TelegramCore/Sources/ApiUtils/CachedGroupParticipants.swift index 3dc21954..8d9098a8 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/CachedGroupParticipants.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/CachedGroupParticipants.swift @@ -6,11 +6,14 @@ import TelegramApi extension GroupParticipant { init(apiParticipant: Api.ChatParticipant) { switch apiParticipant { - case let .chatParticipantCreator(userId): + case let .chatParticipantCreator(chatParticipantCreatorData): + let userId = chatParticipantCreatorData.userId self = .creator(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))) - case let .chatParticipantAdmin(userId, inviterId, date): + case let .chatParticipantAdmin(chatParticipantAdminData): + let (userId, inviterId, date) = (chatParticipantAdminData.userId, chatParticipantAdminData.inviterId, chatParticipantAdminData.date) self = .admin(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), invitedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(inviterId)), invitedAt: date) - case let .chatParticipant(userId, inviterId, date): + case let .chatParticipant(chatParticipantData): + let (userId, inviterId, date) = (chatParticipantData.userId, chatParticipantData.inviterId, chatParticipantData.date) self = .member(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), invitedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(inviterId)), invitedAt: date) } } @@ -19,7 +22,8 @@ extension GroupParticipant { extension CachedGroupParticipants { convenience init?(apiParticipants: Api.ChatParticipants) { switch apiParticipants { - case let .chatParticipants(_, participants, version): + case let .chatParticipants(chatParticipantsData): + let (participants, version) = (chatParticipantsData.participants, chatParticipantsData.version) self.init(participants: participants.map { GroupParticipant(apiParticipant: $0) }, version: version) case .chatParticipantsForbidden: return nil diff --git a/submodules/TelegramCore/Sources/ApiUtils/ChatContextResult.swift b/submodules/TelegramCore/Sources/ApiUtils/ChatContextResult.swift index 6e133a7a..2a561512 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/ChatContextResult.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/ChatContextResult.swift @@ -490,7 +490,8 @@ public final class ChatContextResultCollection: Equatable, Codable { extension ChatContextResultMessage { init(apiMessage: Api.BotInlineMessage) { switch apiMessage { - case let .botInlineMessageMediaAuto(_, message, entities, replyMarkup): + case let .botInlineMessageMediaAuto(botInlineMessageMediaAutoData): + let (_, message, entities, replyMarkup) = (botInlineMessageMediaAutoData.flags, botInlineMessageMediaAutoData.message, botInlineMessageMediaAutoData.entities, botInlineMessageMediaAutoData.replyMarkup) var parsedEntities: TextEntitiesMessageAttribute? if let entities = entities, !entities.isEmpty { parsedEntities = TextEntitiesMessageAttribute(entities: messageTextEntitiesFromApiEntities(entities)) @@ -500,7 +501,8 @@ extension ChatContextResultMessage { parsedReplyMarkup = ReplyMarkupMessageAttribute(apiMarkup: replyMarkup) } self = .auto(caption: message, entities: parsedEntities, replyMarkup: parsedReplyMarkup) - case let .botInlineMessageText(flags, message, entities, replyMarkup): + case let .botInlineMessageText(botInlineMessageTextData): + let (flags, message, entities, replyMarkup) = (botInlineMessageTextData.flags, botInlineMessageTextData.message, botInlineMessageTextData.entities, botInlineMessageTextData.replyMarkup) var parsedEntities: TextEntitiesMessageAttribute? if let entities = entities, !entities.isEmpty { parsedEntities = TextEntitiesMessageAttribute(entities: messageTextEntitiesFromApiEntities(entities)) @@ -516,28 +518,32 @@ extension ChatContextResultMessage { isManuallyAdded: false, isSafe: false ), replyMarkup: parsedReplyMarkup) - case let .botInlineMessageMediaGeo(_, geo, heading, period, proximityNotificationRadius, replyMarkup): + case let .botInlineMessageMediaGeo(botInlineMessageMediaGeoData): + let (_, geo, heading, period, proximityNotificationRadius, replyMarkup) = (botInlineMessageMediaGeoData.flags, botInlineMessageMediaGeoData.geo, botInlineMessageMediaGeoData.heading, botInlineMessageMediaGeoData.period, botInlineMessageMediaGeoData.proximityNotificationRadius, botInlineMessageMediaGeoData.replyMarkup) let media = telegramMediaMapFromApiGeoPoint(geo, title: nil, address: nil, provider: nil, venueId: nil, venueType: nil, liveBroadcastingTimeout: period, liveProximityNotificationRadius: proximityNotificationRadius, heading: heading) var parsedReplyMarkup: ReplyMarkupMessageAttribute? if let replyMarkup = replyMarkup { parsedReplyMarkup = ReplyMarkupMessageAttribute(apiMarkup: replyMarkup) } self = .mapLocation(media: media, replyMarkup: parsedReplyMarkup) - case let .botInlineMessageMediaVenue(_, geo, title, address, provider, venueId, venueType, replyMarkup): + case let .botInlineMessageMediaVenue(botInlineMessageMediaVenueData): + let (_, geo, title, address, provider, venueId, venueType, replyMarkup) = (botInlineMessageMediaVenueData.flags, botInlineMessageMediaVenueData.geo, botInlineMessageMediaVenueData.title, botInlineMessageMediaVenueData.address, botInlineMessageMediaVenueData.provider, botInlineMessageMediaVenueData.venueId, botInlineMessageMediaVenueData.venueType, botInlineMessageMediaVenueData.replyMarkup) let media = telegramMediaMapFromApiGeoPoint(geo, title: title, address: address, provider: provider, venueId: venueId, venueType: venueType, liveBroadcastingTimeout: nil, liveProximityNotificationRadius: nil, heading: nil) var parsedReplyMarkup: ReplyMarkupMessageAttribute? if let replyMarkup = replyMarkup { parsedReplyMarkup = ReplyMarkupMessageAttribute(apiMarkup: replyMarkup) } self = .mapLocation(media: media, replyMarkup: parsedReplyMarkup) - case let .botInlineMessageMediaContact(_, phoneNumber, firstName, lastName, vcard, replyMarkup): + case let .botInlineMessageMediaContact(botInlineMessageMediaContactData): + let (_, phoneNumber, firstName, lastName, vcard, replyMarkup) = (botInlineMessageMediaContactData.flags, botInlineMessageMediaContactData.phoneNumber, botInlineMessageMediaContactData.firstName, botInlineMessageMediaContactData.lastName, botInlineMessageMediaContactData.vcard, botInlineMessageMediaContactData.replyMarkup) let media = TelegramMediaContact(firstName: firstName, lastName: lastName, phoneNumber: phoneNumber, peerId: nil, vCardData: vcard.isEmpty ? nil : vcard) var parsedReplyMarkup: ReplyMarkupMessageAttribute? if let replyMarkup = replyMarkup { parsedReplyMarkup = ReplyMarkupMessageAttribute(apiMarkup: replyMarkup) } self = .contact(media: media, replyMarkup: parsedReplyMarkup) - case let .botInlineMessageMediaInvoice(flags, title, description, photo, currency, totalAmount, replyMarkup): + case let .botInlineMessageMediaInvoice(botInlineMessageMediaInvoiceData): + let (flags, title, description, photo, currency, totalAmount, replyMarkup) = (botInlineMessageMediaInvoiceData.flags, botInlineMessageMediaInvoiceData.title, botInlineMessageMediaInvoiceData.description, botInlineMessageMediaInvoiceData.photo, botInlineMessageMediaInvoiceData.currency, botInlineMessageMediaInvoiceData.totalAmount, botInlineMessageMediaInvoiceData.replyMarkup) var parsedFlags = TelegramMediaInvoiceFlags() if (flags & (1 << 3)) != 0 { parsedFlags.insert(.isTest) @@ -550,7 +556,8 @@ extension ChatContextResultMessage { parsedReplyMarkup = ReplyMarkupMessageAttribute(apiMarkup: replyMarkup) } self = .invoice(media: TelegramMediaInvoice(title: title, description: description, photo: photo.flatMap(TelegramMediaWebFile.init), receiptMessageId: nil, currency: currency, totalAmount: totalAmount, startParam: "", extendedMedia: nil, subscriptionPeriod: nil, flags: parsedFlags, version: TelegramMediaInvoice.lastVersion), replyMarkup: parsedReplyMarkup) - case let .botInlineMessageMediaWebPage(flags, message, entities, url, replyMarkup): + case let .botInlineMessageMediaWebPage(botInlineMessageMediaWebPageData): + let (flags, message, entities, url, replyMarkup) = (botInlineMessageMediaWebPageData.flags, botInlineMessageMediaWebPageData.message, botInlineMessageMediaWebPageData.entities, botInlineMessageMediaWebPageData.url, botInlineMessageMediaWebPageData.replyMarkup) var parsedReplyMarkup: ReplyMarkupMessageAttribute? if let replyMarkup = replyMarkup { parsedReplyMarkup = ReplyMarkupMessageAttribute(apiMarkup: replyMarkup) @@ -590,9 +597,11 @@ extension ChatContextResultMessage { extension ChatContextResult { init(apiResult: Api.BotInlineResult, queryId: Int64) { switch apiResult { - case let .botInlineResult(_, id, type, title, description, url, thumb, content, sendMessage): + case let .botInlineResult(botInlineResultData): + let (_, id, type, title, description, url, thumb, content, sendMessage) = (botInlineResultData.flags, botInlineResultData.id, botInlineResultData.type, botInlineResultData.title, botInlineResultData.description, botInlineResultData.url, botInlineResultData.thumb, botInlineResultData.content, botInlineResultData.sendMessage) self = .externalReference(ChatContextResult.ExternalReference(queryId: queryId, id: id, type: type, title: title, description: description, url: url, content: content.flatMap(TelegramMediaWebFile.init), thumbnail: thumb.flatMap(TelegramMediaWebFile.init), message: ChatContextResultMessage(apiMessage: sendMessage))) - case let .botInlineMediaResult(_, id, type, photo, document, title, description, sendMessage): + case let .botInlineMediaResult(botInlineMediaResultData): + let (_, id, type, photo, document, title, description, sendMessage) = (botInlineMediaResultData.flags, botInlineMediaResultData.id, botInlineMediaResultData.type, botInlineMediaResultData.photo, botInlineMediaResultData.document, botInlineMediaResultData.title, botInlineMediaResultData.description, botInlineMediaResultData.sendMessage) var image: TelegramMediaImage? var file: TelegramMediaFile? if let photo = photo, let parsedImage = telegramMediaImageFromApiPhoto(photo) { @@ -609,7 +618,8 @@ extension ChatContextResult { extension ChatContextResultSwitchPeer { init(apiSwitchPeer: Api.InlineBotSwitchPM) { switch apiSwitchPeer { - case let .inlineBotSwitchPM(text, startParam): + case let .inlineBotSwitchPM(inlineBotSwitchPMData): + let (text, startParam) = (inlineBotSwitchPMData.text, inlineBotSwitchPMData.startParam) self.init(text: text, startParam: startParam) } } @@ -618,7 +628,8 @@ extension ChatContextResultSwitchPeer { extension ChatContextResultWebView { init(apiSwitchWebView: Api.InlineBotWebView) { switch apiSwitchWebView { - case let .inlineBotWebView(text, url): + case let .inlineBotWebView(inlineBotWebViewData): + let (text, url) = (inlineBotWebViewData.text, inlineBotWebViewData.url) self.init(text: text, url: url) } } @@ -627,7 +638,8 @@ extension ChatContextResultWebView { extension ChatContextResultCollection { convenience init(apiResults: Api.messages.BotResults, botId: PeerId, peerId: PeerId, query: String, geoPoint: (Double, Double)?) { switch apiResults { - case let .botResults(flags, queryId, nextOffset, switchPm, switchWebView, results, cacheTime, _): + case let .botResults(botResultsData): + let (flags, queryId, nextOffset, switchPm, switchWebView, results, cacheTime, _) = (botResultsData.flags, botResultsData.queryId, botResultsData.nextOffset, botResultsData.switchPm, botResultsData.switchWebview, botResultsData.results, botResultsData.cacheTime, botResultsData.users) var switchPeer: ChatContextResultSwitchPeer? if let switchPm = switchPm { switchPeer = ChatContextResultSwitchPeer(apiSwitchPeer: switchPm) diff --git a/submodules/TelegramCore/Sources/ApiUtils/CloudFileMediaResource.swift b/submodules/TelegramCore/Sources/ApiUtils/CloudFileMediaResource.swift index 4f57b1ef..f3bc3fcb 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/CloudFileMediaResource.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/CloudFileMediaResource.swift @@ -28,19 +28,19 @@ public protocol TelegramCloudMediaResourceWithFileReference { extension CloudFileMediaResource: TelegramCloudMediaResource, TelegramMultipartFetchableResource, TelegramCloudMediaResourceWithFileReference { func apiInputLocation(fileReference: Data?) -> Api.InputFileLocation? { - return Api.InputFileLocation.inputFileLocation(volumeId: self.volumeId, localId: self.localId, secret: self.secret, fileReference: Buffer(data: fileReference ?? Data())) + return Api.InputFileLocation.inputFileLocation(.init(volumeId: self.volumeId, localId: self.localId, secret: self.secret, fileReference: Buffer(data: fileReference ?? Data()))) } } extension CloudPhotoSizeMediaResource: TelegramCloudMediaResource, TelegramMultipartFetchableResource, TelegramCloudMediaResourceWithFileReference { func apiInputLocation(fileReference: Data?) -> Api.InputFileLocation? { - return Api.InputFileLocation.inputPhotoFileLocation(id: self.photoId, accessHash: self.accessHash, fileReference: Buffer(data: fileReference ?? Data()), thumbSize: self.sizeSpec) + return Api.InputFileLocation.inputPhotoFileLocation(.init(id: self.photoId, accessHash: self.accessHash, fileReference: Buffer(data: fileReference ?? Data()), thumbSize: self.sizeSpec)) } } extension CloudDocumentSizeMediaResource: TelegramCloudMediaResource, TelegramMultipartFetchableResource, TelegramCloudMediaResourceWithFileReference { func apiInputLocation(fileReference: Data?) -> Api.InputFileLocation? { - return Api.InputFileLocation.inputDocumentFileLocation(id: self.documentId, accessHash: self.accessHash, fileReference: Buffer(data: fileReference ?? Data()), thumbSize: self.sizeSpec) + return Api.InputFileLocation.inputDocumentFileLocation(.init(id: self.documentId, accessHash: self.accessHash, fileReference: Buffer(data: fileReference ?? Data()), thumbSize: self.sizeSpec)) } } @@ -54,7 +54,7 @@ extension CloudPeerPhotoSizeMediaResource: TelegramMultipartFetchableResource { flags = 1 << 0 } if let photoId = self.photoId { - return Api.InputFileLocation.inputPeerPhotoFileLocation(flags: flags, peer: peerReference.inputPeer, photoId: photoId) + return Api.InputFileLocation.inputPeerPhotoFileLocation(.init(flags: flags, peer: peerReference.inputPeer, photoId: photoId)) } else { return nil } @@ -64,7 +64,7 @@ extension CloudPeerPhotoSizeMediaResource: TelegramMultipartFetchableResource { extension CloudStickerPackThumbnailMediaResource: TelegramMultipartFetchableResource { func apiInputLocation(packReference: StickerPackReference) -> Api.InputFileLocation? { if let thumbVersion = self.thumbVersion { - return Api.InputFileLocation.inputStickerSetThumb(stickerset: packReference.apiInputStickerSet, thumbVersion: thumbVersion) + return Api.InputFileLocation.inputStickerSetThumb(.init(stickerset: packReference.apiInputStickerSet, thumbVersion: thumbVersion)) } else { return nil } @@ -73,12 +73,12 @@ extension CloudStickerPackThumbnailMediaResource: TelegramMultipartFetchableReso extension CloudDocumentMediaResource: TelegramCloudMediaResource, TelegramMultipartFetchableResource, TelegramCloudMediaResourceWithFileReference { func apiInputLocation(fileReference: Data?) -> Api.InputFileLocation? { - return Api.InputFileLocation.inputDocumentFileLocation(id: self.fileId, accessHash: self.accessHash, fileReference: Buffer(data: fileReference ?? Data()), thumbSize: "") + return Api.InputFileLocation.inputDocumentFileLocation(.init(id: self.fileId, accessHash: self.accessHash, fileReference: Buffer(data: fileReference ?? Data()), thumbSize: "")) } } extension SecretFileMediaResource: TelegramCloudMediaResource, TelegramMultipartFetchableResource { func apiInputLocation(fileReference: Data?) -> Api.InputFileLocation? { - return .inputEncryptedFileLocation(id: self.fileId, accessHash: self.accessHash) + return .inputEncryptedFileLocation(.init(id: self.fileId, accessHash: self.accessHash)) } } diff --git a/submodules/TelegramCore/Sources/ApiUtils/ExportedInvitation.swift b/submodules/TelegramCore/Sources/ApiUtils/ExportedInvitation.swift index e3584576..ab88147c 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/ExportedInvitation.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/ExportedInvitation.swift @@ -6,7 +6,8 @@ import TelegramApi extension ExportedInvitation { init(apiExportedInvite: Api.ExportedChatInvite) { switch apiExportedInvite { - case let .chatInviteExported(flags, link, adminId, date, startDate, expireDate, usageLimit, usage, requested, subscriptionExpired, title, pricing): + case let .chatInviteExported(chatInviteExportedData): + let (flags, link, adminId, date, startDate, expireDate, usageLimit, usage, requested, subscriptionExpired, title, pricing) = (chatInviteExportedData.flags, chatInviteExportedData.link, chatInviteExportedData.adminId, chatInviteExportedData.date, chatInviteExportedData.startDate, chatInviteExportedData.expireDate, chatInviteExportedData.usageLimit, chatInviteExportedData.usage, chatInviteExportedData.requested, chatInviteExportedData.subscriptionExpired, chatInviteExportedData.title, chatInviteExportedData.subscriptionPricing) let _ = subscriptionExpired self = .link(link: link, title: title, isPermanent: (flags & (1 << 5)) != 0, requestApproval: (flags & (1 << 6)) != 0, isRevoked: (flags & (1 << 0)) != 0, adminId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(adminId)), date: date, startDate: startDate, expireDate: expireDate, usageLimit: usageLimit, count: usage, requestedCount: requested, pricing: pricing.flatMap { StarsSubscriptionPricing(apiStarsSubscriptionPricing: $0) }) case .chatInvitePublicJoinRequests: diff --git a/submodules/TelegramCore/Sources/ApiUtils/InstantPage.swift b/submodules/TelegramCore/Sources/ApiUtils/InstantPage.swift index ea4bf38b..262901d2 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/InstantPage.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/InstantPage.swift @@ -6,7 +6,8 @@ import TelegramApi extension InstantPageCaption { convenience init(apiCaption: Api.PageCaption) { switch apiCaption { - case let .pageCaption(text, credit): + case let .pageCaption(pageCaptionData): + let (text, credit) = (pageCaptionData.text, pageCaptionData.credit) self.init(text: RichText(apiText: text), credit: RichText(apiText: credit)) } } @@ -28,18 +29,22 @@ public extension InstantPageListItem { extension InstantPageListItem { init(apiListItem: Api.PageListItem) { switch apiListItem { - case let .pageListItemText(text): + case let .pageListItemText(pageListItemTextData): + let text = pageListItemTextData.text self = .text(RichText(apiText: text), nil) - case let .pageListItemBlocks(blocks): + case let .pageListItemBlocks(pageListItemBlocksData): + let blocks = pageListItemBlocksData.blocks self = .blocks(blocks.map({ InstantPageBlock(apiBlock: $0) }), nil) } } init(apiListOrderedItem: Api.PageListOrderedItem) { switch apiListOrderedItem { - case let .pageListOrderedItemText(num, text): + case let .pageListOrderedItemText(pageListOrderedItemTextData): + let (num, text) = (pageListOrderedItemTextData.num, pageListOrderedItemTextData.text) self = .text(RichText(apiText: text), num) - case let .pageListOrderedItemBlocks(num, blocks): + case let .pageListOrderedItemBlocks(pageListOrderedItemBlocksData): + let (num, blocks) = (pageListOrderedItemBlocksData.num, pageListOrderedItemBlocksData.blocks) self = .blocks(blocks.map({ InstantPageBlock(apiBlock: $0) }), num) } } @@ -48,7 +53,8 @@ extension InstantPageListItem { extension InstantPageTableCell { convenience init(apiTableCell: Api.PageTableCell) { switch apiTableCell { - case let .pageTableCell(flags, text, colspan, rowspan): + case let .pageTableCell(pageTableCellData): + let (flags, text, colspan, rowspan) = (pageTableCellData.flags, pageTableCellData.text, pageTableCellData.colspan, pageTableCellData.rowspan) var alignment = TableHorizontalAlignment.left if (flags & (1 << 3)) != 0 { alignment = .center @@ -69,7 +75,8 @@ extension InstantPageTableCell { extension InstantPageTableRow { convenience init(apiTableRow: Api.PageTableRow) { switch apiTableRow { - case let .pageTableRow(cells): + case let .pageTableRow(pageTableRowData): + let cells = pageTableRowData.cells self.init(cells: cells.map({ InstantPageTableCell(apiTableCell: $0) })) } } @@ -78,7 +85,8 @@ extension InstantPageTableRow { extension InstantPageRelatedArticle { convenience init(apiRelatedArticle: Api.PageRelatedArticle) { switch apiRelatedArticle { - case let .pageRelatedArticle(_, url, webpageId, title, description, photoId, author, publishedDate): + case let .pageRelatedArticle(pageRelatedArticleData): + let (url, webpageId, title, description, photoId, author, publishedDate) = (pageRelatedArticleData.url, pageRelatedArticleData.webpageId, pageRelatedArticleData.title, pageRelatedArticleData.description, pageRelatedArticleData.photoId, pageRelatedArticleData.author, pageRelatedArticleData.publishedDate) var posterPhotoId: MediaId? if let photoId = photoId { posterPhotoId = MediaId(namespace: Namespaces.Media.CloudImage, id: photoId) @@ -93,71 +101,99 @@ extension InstantPageBlock { switch apiBlock { case .pageBlockUnsupported: self = .unsupported - case let .pageBlockTitle(text): + case let .pageBlockTitle(pageBlockTitleData): + let text = pageBlockTitleData.text self = .title(RichText(apiText: text)) - case let .pageBlockSubtitle(text): + case let .pageBlockSubtitle(pageBlockSubtitleData): + let text = pageBlockSubtitleData.text self = .subtitle(RichText(apiText: text)) - case let .pageBlockAuthorDate(author, publishedDate): + case let .pageBlockAuthorDate(pageBlockAuthorDateData): + let (author, publishedDate) = (pageBlockAuthorDateData.author, pageBlockAuthorDateData.publishedDate) self = .authorDate(author: RichText(apiText: author), date: publishedDate) - case let .pageBlockHeader(text): + case let .pageBlockHeader(pageBlockHeaderData): + let text = pageBlockHeaderData.text self = .header(RichText(apiText: text)) - case let .pageBlockSubheader(text): + case let .pageBlockSubheader(pageBlockSubheaderData): + let text = pageBlockSubheaderData.text self = .subheader(RichText(apiText: text)) - case let .pageBlockParagraph(text): + case let .pageBlockParagraph(pageBlockParagraphData): + let text = pageBlockParagraphData.text self = .paragraph(RichText(apiText: text)) - case let .pageBlockPreformatted(text, _): + case let .pageBlockPreformatted(pageBlockPreformattedData): + let text = pageBlockPreformattedData.text self = .preformatted(RichText(apiText: text)) - case let .pageBlockFooter(text): + case let .pageBlockFooter(pageBlockFooterData): + let text = pageBlockFooterData.text self = .footer(RichText(apiText: text)) case .pageBlockDivider: self = .divider - case let .pageBlockAnchor(name): + case let .pageBlockAnchor(pageBlockAnchorData): + let name = pageBlockAnchorData.name self = .anchor(name) - case let .pageBlockBlockquote(text, caption): + case let .pageBlockBlockquote(pageBlockBlockquoteData): + let (text, caption) = (pageBlockBlockquoteData.text, pageBlockBlockquoteData.caption) self = .blockQuote(text: RichText(apiText: text), caption: RichText(apiText: caption)) - case let .pageBlockPullquote(text, caption): + case let .pageBlockPullquote(pageBlockPullquoteData): + let (text, caption) = (pageBlockPullquoteData.text, pageBlockPullquoteData.caption) self = .pullQuote(text: RichText(apiText: text), caption: RichText(apiText: caption)) - case let .pageBlockPhoto(flags, photoId, caption, url, webpageId): + case let .pageBlockPhoto(pageBlockPhotoData): + let (flags, photoId, caption, url, webpageId) = (pageBlockPhotoData.flags, pageBlockPhotoData.photoId, pageBlockPhotoData.caption, pageBlockPhotoData.url, pageBlockPhotoData.webpageId) var webpageMediaId: MediaId? if (flags & (1 << 0)) != 0, let webpageId = webpageId, webpageId != 0 { webpageMediaId = MediaId(namespace: Namespaces.Media.CloudWebpage, id: webpageId) } self = .image(id: MediaId(namespace: Namespaces.Media.CloudImage, id: photoId), caption: InstantPageCaption(apiCaption: caption), url: url, webpageId: webpageMediaId) - case let .pageBlockVideo(flags, videoId, caption): + case let .pageBlockVideo(pageBlockVideoData): + let (flags, videoId, caption) = (pageBlockVideoData.flags, pageBlockVideoData.videoId, pageBlockVideoData.caption) self = .video(id: MediaId(namespace: Namespaces.Media.CloudFile, id: videoId), caption: InstantPageCaption(apiCaption: caption), autoplay: (flags & (1 << 0)) != 0, loop: (flags & (1 << 1)) != 0) - case let .pageBlockCover(cover): + case let .pageBlockCover(pageBlockCoverData): + let cover = pageBlockCoverData.cover self = .cover(InstantPageBlock(apiBlock: cover)) - case let .pageBlockEmbed(flags, url, html, posterPhotoId, w, h, caption): + case let .pageBlockEmbed(pageBlockEmbedData): + let (flags, url, html, posterPhotoId, w, h, caption) = (pageBlockEmbedData.flags, pageBlockEmbedData.url, pageBlockEmbedData.html, pageBlockEmbedData.posterPhotoId, pageBlockEmbedData.w, pageBlockEmbedData.h, pageBlockEmbedData.caption) var dimensions: PixelDimensions? if let w = w, let h = h { dimensions = PixelDimensions(width: w, height: h) } self = .webEmbed(url: url, html: html, dimensions: dimensions, caption: InstantPageCaption(apiCaption: caption), stretchToWidth: (flags & (1 << 0)) != 0, allowScrolling: (flags & (1 << 3)) != 0, coverId: posterPhotoId.flatMap { MediaId(namespace: Namespaces.Media.CloudImage, id: $0) }) - case let .pageBlockEmbedPost(url, webpageId, authorPhotoId, author, date, blocks, caption): + case let .pageBlockEmbedPost(pageBlockEmbedPostData): + let (url, webpageId, authorPhotoId, author, date, blocks, caption) = (pageBlockEmbedPostData.url, pageBlockEmbedPostData.webpageId, pageBlockEmbedPostData.authorPhotoId, pageBlockEmbedPostData.author, pageBlockEmbedPostData.date, pageBlockEmbedPostData.blocks, pageBlockEmbedPostData.caption) self = .postEmbed(url: url, webpageId: webpageId == 0 ? nil : MediaId(namespace: Namespaces.Media.CloudWebpage, id: webpageId), avatarId: authorPhotoId == 0 ? nil : MediaId(namespace: Namespaces.Media.CloudImage, id: authorPhotoId), author: author, date: date, blocks: blocks.map({ InstantPageBlock(apiBlock: $0) }), caption: InstantPageCaption(apiCaption: caption)) - case let .pageBlockCollage(items, caption): + case let .pageBlockCollage(pageBlockCollageData): + let (items, caption) = (pageBlockCollageData.items, pageBlockCollageData.caption) self = .collage(items: items.map({ InstantPageBlock(apiBlock: $0) }), caption: InstantPageCaption(apiCaption: caption)) - case let .pageBlockSlideshow(items, caption): + case let .pageBlockSlideshow(pageBlockSlideshowData): + let (items, caption) = (pageBlockSlideshowData.items, pageBlockSlideshowData.caption) self = .slideshow(items: items.map({ InstantPageBlock(apiBlock: $0) }), caption: InstantPageCaption(apiCaption: caption)) - case let .pageBlockChannel(channel: apiChat): + case let .pageBlockChannel(pageBlockChannelData): + let apiChat = pageBlockChannelData.channel self = .channelBanner(parseTelegramGroupOrChannel(chat: apiChat) as? TelegramChannel) - case let .pageBlockAudio(audioId, caption): + case let .pageBlockAudio(pageBlockAudioData): + let (audioId, caption) = (pageBlockAudioData.audioId, pageBlockAudioData.caption) self = .audio(id: MediaId(namespace: Namespaces.Media.CloudFile, id: audioId), caption: InstantPageCaption(apiCaption: caption)) - case let .pageBlockKicker(text): + case let .pageBlockKicker(pageBlockKickerData): + let text = pageBlockKickerData.text self = .kicker(RichText(apiText: text)) - case let .pageBlockTable(flags, title, rows): + case let .pageBlockTable(pageBlockTableData): + let (flags, title, rows) = (pageBlockTableData.flags, pageBlockTableData.title, pageBlockTableData.rows) self = .table(title: RichText(apiText: title), rows: rows.map({ InstantPageTableRow(apiTableRow: $0) }), bordered: (flags & (1 << 0)) != 0, striped: (flags & (1 << 1)) != 0) - case let .pageBlockList(items): + case let .pageBlockList(pageBlockListData): + let items = pageBlockListData.items self = .list(items: items.map({ InstantPageListItem(apiListItem: $0) }), ordered: false) - case let .pageBlockOrderedList(items): + case let .pageBlockOrderedList(pageBlockOrderedListData): + let items = pageBlockOrderedListData.items self = .list(items: items.map({ InstantPageListItem(apiListOrderedItem: $0) }), ordered: true) - case let .pageBlockDetails(flags, blocks, title): + case let .pageBlockDetails(pageBlockDetailsData): + let (flags, blocks, title) = (pageBlockDetailsData.flags, pageBlockDetailsData.blocks, pageBlockDetailsData.title) self = .details(title: RichText(apiText: title), blocks: blocks.map({ InstantPageBlock(apiBlock: $0) }), expanded: (flags & (1 << 0)) != 0) - case let .pageBlockRelatedArticles(title, articles): + case let .pageBlockRelatedArticles(pageBlockRelatedArticlesData): + let (title, articles) = (pageBlockRelatedArticlesData.title, pageBlockRelatedArticlesData.articles) self = .relatedArticles(title: RichText(apiText: title), articles: articles.map({ InstantPageRelatedArticle(apiRelatedArticle: $0) })) - case let .pageBlockMap(geo, zoom, w, h, caption): + case let .pageBlockMap(pageBlockMapData): + let (geo, zoom, w, h, caption) = (pageBlockMapData.geo, pageBlockMapData.zoom, pageBlockMapData.w, pageBlockMapData.h, pageBlockMapData.caption) switch geo { - case let .geoPoint(_, long, lat, _, _): + case let .geoPoint(geoPointData): + let (long, lat) = (geoPointData.long, geoPointData.lat) self = .map(latitude: lat, longitude: long, zoom: zoom, dimensions: PixelDimensions(width: w, height: h), caption: InstantPageCaption(apiCaption: caption)) default: self = .unsupported @@ -176,7 +212,8 @@ extension InstantPage { let url: String let views: Int32? switch apiPage { - case let .page(flags, pageUrl, pageBlocks, pagePhotos, pageDocuments, pageViews): + case let .page(pageData): + let (flags, pageUrl, pageBlocks, pagePhotos, pageDocuments, pageViews) = (pageData.flags, pageData.url, pageData.blocks, pageData.photos, pageData.documents, pageData.views) url = pageUrl blocks = pageBlocks photos = pagePhotos diff --git a/submodules/TelegramCore/Sources/ApiUtils/PeerAccessRestrictionInfo.swift b/submodules/TelegramCore/Sources/ApiUtils/PeerAccessRestrictionInfo.swift index ec42c803..7fd4cbf7 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/PeerAccessRestrictionInfo.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/PeerAccessRestrictionInfo.swift @@ -6,7 +6,8 @@ import TelegramApi extension RestrictionRule { convenience init(apiReason: Api.RestrictionReason) { switch apiReason { - case let .restrictionReason(platform, reason, text): + case let .restrictionReason(restrictionReasonData): + let (platform, reason, text) = (restrictionReasonData.platform, restrictionReasonData.reason, restrictionReasonData.text) self.init(platform: platform, reason: reason, text: text) } } diff --git a/submodules/TelegramCore/Sources/ApiUtils/PeerGeoLocation.swift b/submodules/TelegramCore/Sources/ApiUtils/PeerGeoLocation.swift index 7461a50e..53ffd849 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/PeerGeoLocation.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/PeerGeoLocation.swift @@ -6,8 +6,10 @@ import TelegramApi extension PeerGeoLocation { init?(apiLocation: Api.ChannelLocation) { switch apiLocation { - case let .channelLocation(geopoint, address): - if case let .geoPoint(_, longitude, latitude, _, _) = geopoint { + case let .channelLocation(channelLocationData): + let (geopoint, address) = (channelLocationData.geoPoint, channelLocationData.address) + if case let .geoPoint(geoPointData) = geopoint { + let (longitude, latitude) = (geoPointData.long, geoPointData.lat) self.init(latitude: latitude, longitude: longitude, address: address) } else { return nil diff --git a/submodules/TelegramCore/Sources/ApiUtils/ReactionsMessageAttribute.swift b/submodules/TelegramCore/Sources/ApiUtils/ReactionsMessageAttribute.swift index c282b7dc..38df7832 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/ReactionsMessageAttribute.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/ReactionsMessageAttribute.swift @@ -5,13 +5,15 @@ import TelegramApi extension ReactionsMessageAttribute { func withUpdatedResults(_ reactions: Api.MessageReactions) -> ReactionsMessageAttribute { switch reactions { - case let .messageReactions(flags, results, recentReactions, topReactors): + case let .messageReactions(messageReactionsData): + let (flags, results, recentReactions, topReactors) = (messageReactionsData.flags, messageReactionsData.results, messageReactionsData.recentReactions, messageReactionsData.topReactors) let min = (flags & (1 << 0)) != 0 let canViewList = (flags & (1 << 2)) != 0 let isTags = (flags & (1 << 3)) != 0 var reactions = results.compactMap { result -> MessageReaction? in switch result { - case let .reactionCount(_, chosenOrder, reaction, count): + case let .reactionCount(reactionCountData): + let (_, chosenOrder, reaction, count) = (reactionCountData.flags, reactionCountData.chosenOrder, reactionCountData.reaction, reactionCountData.count) if let reaction = MessageReaction.Reaction(apiReaction: reaction) { return MessageReaction(value: reaction, count: count, chosenOrder: chosenOrder.flatMap(Int.init)) } else { @@ -23,7 +25,8 @@ extension ReactionsMessageAttribute { if let recentReactions = recentReactions { parsedRecentReactions = recentReactions.compactMap { recentReaction -> ReactionsMessageAttribute.RecentPeer? in switch recentReaction { - case let .messagePeerReaction(flags, peerId, date, reaction): + case let .messagePeerReaction(messagePeerReactionData): + let (flags, peerId, date, reaction) = (messagePeerReactionData.flags, messagePeerReactionData.peerId, messagePeerReactionData.date, messagePeerReactionData.reaction) let isLarge = (flags & (1 << 0)) != 0 let isUnseen = (flags & (1 << 1)) != 0 let isMy = (flags & (1 << 2)) != 0 @@ -37,7 +40,7 @@ extension ReactionsMessageAttribute { } else { parsedRecentReactions = [] } - + if min { var currentSelectedReactions: [MessageReaction.Reaction: Int] = [:] for reaction in self.reactions { @@ -59,7 +62,8 @@ extension ReactionsMessageAttribute { if let topReactors { for item in topReactors { switch item { - case let .messageReactor(flags, peerId, count): + case let .messageReactor(messageReactorData): + let (flags, peerId, count) = (messageReactorData.flags, messageReactorData.peerId, messageReactorData.count) topPeers.append(ReactionsMessageAttribute.TopPeer( peerId: peerId?.peerId, count: count, @@ -70,7 +74,7 @@ extension ReactionsMessageAttribute { } } } - + return ReactionsMessageAttribute(canViewList: canViewList, isTags: isTags, reactions: reactions, recentPeers: parsedRecentReactions, topPeers: topPeers) } } @@ -258,14 +262,16 @@ public func mergedMessageReactions(attributes: [MessageAttribute], isTags: Bool) extension ReactionsMessageAttribute { convenience init(apiReactions: Api.MessageReactions) { switch apiReactions { - case let .messageReactions(flags, results, recentReactions, topReactors): + case let .messageReactions(messageReactionsData): + let (flags, results, recentReactions, topReactors) = (messageReactionsData.flags, messageReactionsData.results, messageReactionsData.recentReactions, messageReactionsData.topReactors) let canViewList = (flags & (1 << 2)) != 0 let isTags = (flags & (1 << 3)) != 0 let parsedRecentReactions: [ReactionsMessageAttribute.RecentPeer] if let recentReactions = recentReactions { parsedRecentReactions = recentReactions.compactMap { recentReaction -> ReactionsMessageAttribute.RecentPeer? in switch recentReaction { - case let .messagePeerReaction(flags, peerId, date, reaction): + case let .messagePeerReaction(messagePeerReactionData): + let (flags, peerId, date, reaction) = (messagePeerReactionData.flags, messagePeerReactionData.peerId, messagePeerReactionData.date, messagePeerReactionData.reaction) let isLarge = (flags & (1 << 0)) != 0 let isUnseen = (flags & (1 << 1)) != 0 let isMy = (flags & (1 << 2)) != 0 @@ -279,12 +285,13 @@ extension ReactionsMessageAttribute { } else { parsedRecentReactions = [] } - + var topPeers: [ReactionsMessageAttribute.TopPeer] = [] if let topReactors { for item in topReactors { switch item { - case let .messageReactor(flags, peerId, count): + case let .messageReactor(messageReactorData): + let (flags, peerId, count) = (messageReactorData.flags, messageReactorData.peerId, messageReactorData.count) topPeers.append(ReactionsMessageAttribute.TopPeer( peerId: peerId?.peerId, count: count, @@ -295,13 +302,14 @@ extension ReactionsMessageAttribute { } } } - + self.init( canViewList: canViewList, isTags: isTags, reactions: results.compactMap { result -> MessageReaction? in switch result { - case let .reactionCount(_, chosenOrder, reaction, count): + case let .reactionCount(reactionCountData): + let (_, chosenOrder, reaction, count) = (reactionCountData.flags, reactionCountData.chosenOrder, reactionCountData.reaction, reactionCountData.count) if let reaction = MessageReaction.Reaction(apiReaction: reaction) { return MessageReaction(value: reaction, count: count, chosenOrder: chosenOrder.flatMap(Int.init)) } else { diff --git a/submodules/TelegramCore/Sources/ApiUtils/ReplyMarkupMessageAttribute.swift b/submodules/TelegramCore/Sources/ApiUtils/ReplyMarkupMessageAttribute.swift index 36021a7e..030b49a9 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/ReplyMarkupMessageAttribute.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/ReplyMarkupMessageAttribute.swift @@ -26,91 +26,141 @@ extension ReplyMarkupButtonAction.PeerTypes { extension ReplyMarkupButton { init(apiButton: Api.KeyboardButton) { switch apiButton { - case let .keyboardButton(text): - self.init(title: text, titleWhenForwarded: nil, action: .text) - case let .keyboardButtonCallback(flags, text, data): - let memory = malloc(data.size)! - memcpy(memory, data.data, data.size) - let dataBuffer = MemoryBuffer(memory: memory, capacity: data.size, length: data.size, freeWhenDone: true) - self.init(title: text, titleWhenForwarded: nil, action: .callback(requiresPassword: (flags & (1 << 0)) != 0, data: dataBuffer)) - case let .keyboardButtonRequestGeoLocation(text): - self.init(title: text, titleWhenForwarded: nil, action: .requestMap) - case let .keyboardButtonRequestPhone(text): - self.init(title: text, titleWhenForwarded: nil, action: .requestPhone) - case let .keyboardButtonSwitchInline(flags, text, query, types): - var peerTypes = ReplyMarkupButtonAction.PeerTypes() - if let types = types { - for type in types { - switch type { - case .inlineQueryPeerTypePM: - peerTypes.insert(.users) - case .inlineQueryPeerTypeBotPM: - peerTypes.insert(.bots) - case .inlineQueryPeerTypeBroadcast: - peerTypes.insert(.channels) - case .inlineQueryPeerTypeChat, .inlineQueryPeerTypeMegagroup: - peerTypes.insert(.groups) - case .inlineQueryPeerTypeSameBotPM: - break - } + case let .keyboardButton(keyboardButtonData): + let text = keyboardButtonData.text + self.init(title: text, titleWhenForwarded: nil, action: .text, style: keyboardButtonData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .keyboardButtonCallback(keyboardButtonCallbackData): + let (flags, text, data) = (keyboardButtonCallbackData.flags, keyboardButtonCallbackData.text, keyboardButtonCallbackData.data) + let memory = malloc(data.size)! + memcpy(memory, data.data, data.size) + let dataBuffer = MemoryBuffer(memory: memory, capacity: data.size, length: data.size, freeWhenDone: true) + self.init(title: text, titleWhenForwarded: nil, action: .callback(requiresPassword: (flags & (1 << 0)) != 0, data: dataBuffer), style: keyboardButtonCallbackData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .keyboardButtonRequestGeoLocation(keyboardButtonRequestGeoLocationData): + let text = keyboardButtonRequestGeoLocationData.text + self.init(title: text, titleWhenForwarded: nil, action: .requestMap, style: keyboardButtonRequestGeoLocationData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .keyboardButtonRequestPhone(keyboardButtonRequestPhoneData): + let text = keyboardButtonRequestPhoneData.text + self.init(title: text, titleWhenForwarded: nil, action: .requestPhone, style: keyboardButtonRequestPhoneData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .keyboardButtonSwitchInline(keyboardButtonSwitchInlineData): + let (flags, text, query, types) = (keyboardButtonSwitchInlineData.flags, keyboardButtonSwitchInlineData.text, keyboardButtonSwitchInlineData.query, keyboardButtonSwitchInlineData.peerTypes) + var peerTypes = ReplyMarkupButtonAction.PeerTypes() + if let types = types { + for type in types { + switch type { + case .inlineQueryPeerTypePM: + peerTypes.insert(.users) + case .inlineQueryPeerTypeBotPM: + peerTypes.insert(.bots) + case .inlineQueryPeerTypeBroadcast: + peerTypes.insert(.channels) + case .inlineQueryPeerTypeChat, .inlineQueryPeerTypeMegagroup: + peerTypes.insert(.groups) + case .inlineQueryPeerTypeSameBotPM: + break } } - self.init(title: text, titleWhenForwarded: nil, action: .switchInline(samePeer: (flags & (1 << 0)) != 0, query: query, peerTypes: peerTypes)) - case let .keyboardButtonUrl(text, url): - self.init(title: text, titleWhenForwarded: nil, action: .url(url)) - case let .keyboardButtonGame(text): - self.init(title: text, titleWhenForwarded: nil, action: .openWebApp) - case let .keyboardButtonBuy(text): - self.init(title: text, titleWhenForwarded: nil, action: .payment) - case let .keyboardButtonUrlAuth(_, text, fwdText, url, buttonId): - self.init(title: text, titleWhenForwarded: fwdText, action: .urlAuth(url: url, buttonId: buttonId)) - case let .inputKeyboardButtonUrlAuth(_, text, fwdText, url, _): - self.init(title: text, titleWhenForwarded: fwdText, action: .urlAuth(url: url, buttonId: 0)) - case let .keyboardButtonRequestPoll(_, quiz, text): - let isQuiz: Bool? = quiz.flatMap { quiz in - if case .boolTrue = quiz { - return true - } else { - return false - } + } + self.init(title: text, titleWhenForwarded: nil, action: .switchInline(samePeer: (flags & (1 << 0)) != 0, query: query, peerTypes: peerTypes), style: keyboardButtonSwitchInlineData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .keyboardButtonUrl(keyboardButtonUrlData): + let (text, url) = (keyboardButtonUrlData.text, keyboardButtonUrlData.url) + self.init(title: text, titleWhenForwarded: nil, action: .url(url), style: keyboardButtonUrlData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .keyboardButtonGame(keyboardButtonGameData): + let text = keyboardButtonGameData.text + self.init(title: text, titleWhenForwarded: nil, action: .openWebApp, style: keyboardButtonGameData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .keyboardButtonBuy(keyboardButtonBuyData): + let text = keyboardButtonBuyData.text + self.init(title: text, titleWhenForwarded: nil, action: .payment, style: keyboardButtonBuyData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .keyboardButtonUrlAuth(keyboardButtonUrlAuthData): + let (text, fwdText, url, buttonId) = (keyboardButtonUrlAuthData.text, keyboardButtonUrlAuthData.fwdText, keyboardButtonUrlAuthData.url, keyboardButtonUrlAuthData.buttonId) + self.init(title: text, titleWhenForwarded: fwdText, action: .urlAuth(url: url, buttonId: buttonId), style: keyboardButtonUrlAuthData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .inputKeyboardButtonUrlAuth(inputKeyboardButtonUrlAuthData): + let (text, fwdText, url) = (inputKeyboardButtonUrlAuthData.text, inputKeyboardButtonUrlAuthData.fwdText, inputKeyboardButtonUrlAuthData.url) + self.init(title: text, titleWhenForwarded: fwdText, action: .urlAuth(url: url, buttonId: 0), style: inputKeyboardButtonUrlAuthData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .keyboardButtonRequestPoll(keyboardButtonRequestPollData): + let (quiz, text) = (keyboardButtonRequestPollData.quiz, keyboardButtonRequestPollData.text) + let isQuiz: Bool? = quiz.flatMap { quiz in + if case .boolTrue = quiz { + return true + } else { + return false } - self.init(title: text, titleWhenForwarded: nil, action: .setupPoll(isQuiz: isQuiz)) - case let .keyboardButtonUserProfile(text, userId): - self.init(title: text, titleWhenForwarded: nil, action: .openUserProfile(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)))) - case let .inputKeyboardButtonUserProfile(text, _): - self.init(title: text, titleWhenForwarded: nil, action: .openUserProfile(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(0)))) - case let .keyboardButtonWebView(text, url): - self.init(title: text, titleWhenForwarded: nil, action: .openWebView(url: url, simple: false)) - case let .keyboardButtonSimpleWebView(text, url): - self.init(title: text, titleWhenForwarded: nil, action: .openWebView(url: url, simple: true)) - case let .keyboardButtonRequestPeer(text, buttonId, peerType, maxQuantity), let .inputKeyboardButtonRequestPeer(_, text, buttonId, peerType, maxQuantity): - let mappedPeerType: ReplyMarkupButtonRequestPeerType - switch peerType { - case let .requestPeerTypeUser(_, bot, premium): - mappedPeerType = .user(ReplyMarkupButtonRequestPeerType.User( - isBot: bot.flatMap({ $0 == .boolTrue }), - isPremium: premium.flatMap({ $0 == .boolTrue }) - )) - case let .requestPeerTypeChat(flags, hasUsername, forum, userAdminRights, botAdminRights): - mappedPeerType = .group(ReplyMarkupButtonRequestPeerType.Group( - isCreator: (flags & (1 << 0)) != 0, - hasUsername: hasUsername.flatMap({ $0 == .boolTrue }), - isForum: forum.flatMap({ $0 == .boolTrue }), - botParticipant: (flags & (1 << 5)) != 0, - userAdminRights: userAdminRights.flatMap(TelegramChatAdminRights.init(apiAdminRights:)), - botAdminRights: botAdminRights.flatMap(TelegramChatAdminRights.init(apiAdminRights:)) - )) - case let .requestPeerTypeBroadcast(flags, hasUsername, userAdminRights, botAdminRights): - mappedPeerType = .channel(ReplyMarkupButtonRequestPeerType.Channel( - isCreator: (flags & (1 << 0)) != 0, - hasUsername: hasUsername.flatMap({ $0 == .boolTrue }), - userAdminRights: userAdminRights.flatMap(TelegramChatAdminRights.init(apiAdminRights:)), - botAdminRights: botAdminRights.flatMap(TelegramChatAdminRights.init(apiAdminRights:)) - )) - } - self.init(title: text, titleWhenForwarded: nil, action: .requestPeer(peerType: mappedPeerType, buttonId: buttonId, maxQuantity: maxQuantity)) - case let .keyboardButtonCopy(text, payload): - self.init(title: text, titleWhenForwarded: nil, action: .copyText(payload: payload)) + } + self.init(title: text, titleWhenForwarded: nil, action: .setupPoll(isQuiz: isQuiz), style: keyboardButtonRequestPollData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .keyboardButtonUserProfile(keyboardButtonUserProfileData): + let (text, userId) = (keyboardButtonUserProfileData.text, keyboardButtonUserProfileData.userId) + self.init(title: text, titleWhenForwarded: nil, action: .openUserProfile(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))), style: keyboardButtonUserProfileData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .inputKeyboardButtonUserProfile(inputKeyboardButtonUserProfileData): + let text = inputKeyboardButtonUserProfileData.text + self.init(title: text, titleWhenForwarded: nil, action: .openUserProfile(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(0))), style: inputKeyboardButtonUserProfileData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .keyboardButtonWebView(keyboardButtonWebViewData): + let (text, url) = (keyboardButtonWebViewData.text, keyboardButtonWebViewData.url) + self.init(title: text, titleWhenForwarded: nil, action: .openWebView(url: url, simple: false), style: keyboardButtonWebViewData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .keyboardButtonSimpleWebView(keyboardButtonSimpleWebViewData): + let (text, url) = (keyboardButtonSimpleWebViewData.text, keyboardButtonSimpleWebViewData.url) + self.init(title: text, titleWhenForwarded: nil, action: .openWebView(url: url, simple: true), style: keyboardButtonSimpleWebViewData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .keyboardButtonRequestPeer(keyboardButtonRequestPeerData): + let (text, buttonId, peerType, maxQuantity) = (keyboardButtonRequestPeerData.text, keyboardButtonRequestPeerData.buttonId, keyboardButtonRequestPeerData.peerType, keyboardButtonRequestPeerData.maxQuantity) + let mappedPeerType: ReplyMarkupButtonRequestPeerType + switch peerType { + case let .requestPeerTypeUser(requestPeerTypeUserData): + let (bot, premium) = (requestPeerTypeUserData.bot, requestPeerTypeUserData.premium) + mappedPeerType = .user(ReplyMarkupButtonRequestPeerType.User( + isBot: bot.flatMap({ $0 == .boolTrue }), + isPremium: premium.flatMap({ $0 == .boolTrue }) + )) + case let .requestPeerTypeChat(requestPeerTypeChatData): + let (flags, hasUsername, forum, userAdminRights, botAdminRights) = (requestPeerTypeChatData.flags, requestPeerTypeChatData.hasUsername, requestPeerTypeChatData.forum, requestPeerTypeChatData.userAdminRights, requestPeerTypeChatData.botAdminRights) + mappedPeerType = .group(ReplyMarkupButtonRequestPeerType.Group( + isCreator: (flags & (1 << 0)) != 0, + hasUsername: hasUsername.flatMap({ $0 == .boolTrue }), + isForum: forum.flatMap({ $0 == .boolTrue }), + botParticipant: (flags & (1 << 5)) != 0, + userAdminRights: userAdminRights.flatMap(TelegramChatAdminRights.init(apiAdminRights:)), + botAdminRights: botAdminRights.flatMap(TelegramChatAdminRights.init(apiAdminRights:)) + )) + case let .requestPeerTypeBroadcast(requestPeerTypeBroadcastData): + let (flags, hasUsername, userAdminRights, botAdminRights) = (requestPeerTypeBroadcastData.flags, requestPeerTypeBroadcastData.hasUsername, requestPeerTypeBroadcastData.userAdminRights, requestPeerTypeBroadcastData.botAdminRights) + mappedPeerType = .channel(ReplyMarkupButtonRequestPeerType.Channel( + isCreator: (flags & (1 << 0)) != 0, + hasUsername: hasUsername.flatMap({ $0 == .boolTrue }), + userAdminRights: userAdminRights.flatMap(TelegramChatAdminRights.init(apiAdminRights:)), + botAdminRights: botAdminRights.flatMap(TelegramChatAdminRights.init(apiAdminRights:)) + )) + } + self.init(title: text, titleWhenForwarded: nil, action: .requestPeer(peerType: mappedPeerType, buttonId: buttonId, maxQuantity: maxQuantity), style: keyboardButtonRequestPeerData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .inputKeyboardButtonRequestPeer(inputKeyboardButtonRequestPeerData): + let (text, buttonId, peerType, maxQuantity) = (inputKeyboardButtonRequestPeerData.text, inputKeyboardButtonRequestPeerData.buttonId, inputKeyboardButtonRequestPeerData.peerType, inputKeyboardButtonRequestPeerData.maxQuantity) + let mappedPeerType: ReplyMarkupButtonRequestPeerType + switch peerType { + case let .requestPeerTypeUser(requestPeerTypeUserData): + let (bot, premium) = (requestPeerTypeUserData.bot, requestPeerTypeUserData.premium) + mappedPeerType = .user(ReplyMarkupButtonRequestPeerType.User( + isBot: bot.flatMap({ $0 == .boolTrue }), + isPremium: premium.flatMap({ $0 == .boolTrue }) + )) + case let .requestPeerTypeChat(requestPeerTypeChatData): + let (flags, hasUsername, forum, userAdminRights, botAdminRights) = (requestPeerTypeChatData.flags, requestPeerTypeChatData.hasUsername, requestPeerTypeChatData.forum, requestPeerTypeChatData.userAdminRights, requestPeerTypeChatData.botAdminRights) + mappedPeerType = .group(ReplyMarkupButtonRequestPeerType.Group( + isCreator: (flags & (1 << 0)) != 0, + hasUsername: hasUsername.flatMap({ $0 == .boolTrue }), + isForum: forum.flatMap({ $0 == .boolTrue }), + botParticipant: (flags & (1 << 5)) != 0, + userAdminRights: userAdminRights.flatMap(TelegramChatAdminRights.init(apiAdminRights:)), + botAdminRights: botAdminRights.flatMap(TelegramChatAdminRights.init(apiAdminRights:)) + )) + case let .requestPeerTypeBroadcast(requestPeerTypeBroadcastData): + let (flags, hasUsername, userAdminRights, botAdminRights) = (requestPeerTypeBroadcastData.flags, requestPeerTypeBroadcastData.hasUsername, requestPeerTypeBroadcastData.userAdminRights, requestPeerTypeBroadcastData.botAdminRights) + mappedPeerType = .channel(ReplyMarkupButtonRequestPeerType.Channel( + isCreator: (flags & (1 << 0)) != 0, + hasUsername: hasUsername.flatMap({ $0 == .boolTrue }), + userAdminRights: userAdminRights.flatMap(TelegramChatAdminRights.init(apiAdminRights:)), + botAdminRights: botAdminRights.flatMap(TelegramChatAdminRights.init(apiAdminRights:)) + )) + } + self.init(title: text, titleWhenForwarded: nil, action: .requestPeer(peerType: mappedPeerType, buttonId: buttonId, maxQuantity: maxQuantity), style: inputKeyboardButtonRequestPeerData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) + case let .keyboardButtonCopy(keyboardButtonCopyData): + let (text, payload) = (keyboardButtonCopyData.text, keyboardButtonCopyData.copyText) + self.init(title: text, titleWhenForwarded: nil, action: .copyText(payload: payload), style: keyboardButtonCopyData.style.flatMap(ReplyMarkupButton.Style.init(apiStyle:))) } } } @@ -118,7 +168,8 @@ extension ReplyMarkupButton { extension ReplyMarkupRow { init(apiRow: Api.KeyboardButtonRow) { switch apiRow { - case let .keyboardButtonRow(buttons): + case let .keyboardButtonRow(keyboardButtonRowData): + let buttons = keyboardButtonRowData.buttons self.init(buttons: buttons.map { ReplyMarkupButton(apiButton: $0) }) } } @@ -130,7 +181,8 @@ extension ReplyMarkupMessageAttribute { var flags = ReplyMarkupMessageFlags() var placeholder: String? switch apiMarkup { - case let .replyKeyboardMarkup(markupFlags, apiRows, apiPlaceholder): + case let .replyKeyboardMarkup(replyKeyboardMarkupData): + let (markupFlags, apiRows, apiPlaceholder) = (replyKeyboardMarkupData.flags, replyKeyboardMarkupData.rows, replyKeyboardMarkupData.placeholder) rows = apiRows.map { ReplyMarkupRow(apiRow: $0) } if (markupFlags & (1 << 0)) != 0 { flags.insert(.fit) @@ -145,10 +197,12 @@ extension ReplyMarkupMessageAttribute { flags.insert(.persistent) } placeholder = apiPlaceholder - case let .replyInlineMarkup(apiRows): + case let .replyInlineMarkup(replyInlineMarkupData): + let apiRows = replyInlineMarkupData.rows rows = apiRows.map { ReplyMarkupRow(apiRow: $0) } flags.insert(.inline) - case let .replyKeyboardForceReply(forceReplyFlags, apiPlaceholder): + case let .replyKeyboardForceReply(replyKeyboardForceReplyData): + let (forceReplyFlags, apiPlaceholder) = (replyKeyboardForceReplyData.flags, replyKeyboardForceReplyData.placeholder) if (forceReplyFlags & (1 << 1)) != 0 { flags.insert(.once) } @@ -157,7 +211,8 @@ extension ReplyMarkupMessageAttribute { } flags.insert(.setupReply) placeholder = apiPlaceholder - case let .replyKeyboardHide(hideFlags): + case let .replyKeyboardHide(replyKeyboardHideData): + let hideFlags = replyKeyboardHideData.flags if (hideFlags & (1 << 2)) != 0 { flags.insert(.personal) } diff --git a/submodules/TelegramCore/Sources/ApiUtils/RichText.swift b/submodules/TelegramCore/Sources/ApiUtils/RichText.swift index 04fb00e7..1bb3c1d9 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/RichText.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/RichText.swift @@ -8,35 +8,50 @@ extension RichText { switch apiText { case .textEmpty: self = .empty - case let .textPlain(text): + case let .textPlain(textPlainData): + let text = textPlainData.text self = .plain(text) - case let .textBold(text): + case let .textBold(textBoldData): + let text = textBoldData.text self = .bold(RichText(apiText: text)) - case let .textItalic(text): + case let .textItalic(textItalicData): + let text = textItalicData.text self = .italic(RichText(apiText: text)) - case let .textUnderline(text): + case let .textUnderline(textUnderlineData): + let text = textUnderlineData.text self = .underline(RichText(apiText: text)) - case let .textStrike(text): + case let .textStrike(textStrikeData): + let text = textStrikeData.text self = .strikethrough(RichText(apiText: text)) - case let .textFixed(text): + case let .textFixed(textFixedData): + let text = textFixedData.text self = .fixed(RichText(apiText: text)) - case let .textUrl(text, url, webpageId): + case let .textUrl(textUrlData): + let (text, url, webpageId) = (textUrlData.text, textUrlData.url, textUrlData.webpageId) self = .url(text: RichText(apiText: text), url: url, webpageId: webpageId == 0 ? nil : MediaId(namespace: Namespaces.Media.CloudWebpage, id: webpageId)) - case let .textEmail(text, email): + case let .textEmail(textEmailData): + let (text, email) = (textEmailData.text, textEmailData.email) self = .email(text: RichText(apiText: text), email: email) - case let .textConcat(texts): + case let .textConcat(textConcatData): + let texts = textConcatData.texts self = .concat(texts.map({ RichText(apiText: $0) })) - case let .textSubscript(text): + case let .textSubscript(textSubscriptData): + let text = textSubscriptData.text self = .subscript(RichText(apiText: text)) - case let .textSuperscript(text): + case let .textSuperscript(textSuperscriptData): + let text = textSuperscriptData.text self = .superscript(RichText(apiText: text)) - case let .textMarked(text): + case let .textMarked(textMarkedData): + let text = textMarkedData.text self = .marked(RichText(apiText: text)) - case let .textPhone(text, phone): + case let .textPhone(textPhoneData): + let (text, phone) = (textPhoneData.text, textPhoneData.phone) self = .phone(text: RichText(apiText: text), phone: phone) - case let .textImage(documentId, w, h): + case let .textImage(textImageData): + let (documentId, w, h) = (textImageData.documentId, textImageData.w, textImageData.h) self = .image(id: MediaId(namespace: Namespaces.Media.CloudFile, id: documentId), dimensions: PixelDimensions(width: w, height: h)) - case let .textAnchor(text, name): + case let .textAnchor(textAnchorData): + let (text, name) = (textAnchorData.text, textAnchorData.name) self = .anchor(text: RichText(apiText: text), name: name) } } diff --git a/submodules/TelegramCore/Sources/ApiUtils/StoreMessage_Telegram.swift b/submodules/TelegramCore/Sources/ApiUtils/StoreMessage_Telegram.swift index ca8956b5..0d197d09 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/StoreMessage_Telegram.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/StoreMessage_Telegram.swift @@ -81,6 +81,7 @@ public func tagsForStoreMessage(incoming: Bool, attributes: [MessageAttribute], } } if isAnimated { + // TODO(swiftgram): refinedTag = [.photoOrVideo, .video, .gif] refinedTag = .gif } if file.isAnimatedSticker { @@ -128,27 +129,30 @@ public func tagsForStoreMessage(incoming: Bool, attributes: [MessageAttribute], func apiMessagePeerId(_ messsage: Api.Message) -> PeerId? { switch messsage { - case let .message(_, _, _, _, _, messagePeerId, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): - let chatPeerId = messagePeerId + case let .message(messageData): + let chatPeerId = messageData.peerId return chatPeerId.peerId - case let .messageEmpty(_, _, peerId): + case let .messageEmpty(messageEmptyData): + let (_, _, peerId) = (messageEmptyData.flags, messageEmptyData.id, messageEmptyData.peerId) if let peerId = peerId { return peerId.peerId } else { return nil } - case let .messageService(_, _, _, chatPeerId, _, _, _, _, _, _): + case let .messageService(messageServiceData): + let chatPeerId = messageServiceData.peerId return chatPeerId.peerId } } func apiMessagePeerIds(_ message: Api.Message) -> [PeerId] { switch message { - case let .message(_, _, _, fromId, _, chatPeerId, savedPeerId, fwdHeader, viaBotId, viaBusinessBotId, replyTo, _, _, media, _, entities, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + case let .message(messageData): + let (fromId, chatPeerId, savedPeerId, fwdHeader, viaBotId, viaBusinessBotId, replyTo, media, entities) = (messageData.fromId, messageData.peerId, messageData.savedPeerId, messageData.fwdFrom, messageData.viaBotId, messageData.viaBusinessBotId, messageData.replyTo, messageData.media, messageData.entities) let peerId: PeerId = chatPeerId.peerId - + var result = [peerId] - + let resolvedFromId = fromId?.peerId ?? chatPeerId.peerId if resolvedFromId != peerId { @@ -157,7 +161,8 @@ func apiMessagePeerIds(_ message: Api.Message) -> [PeerId] { if let fwdHeader = fwdHeader { switch fwdHeader { - case let .messageFwdHeader(_, fromId, _, _, _, _, savedFromPeer, _, savedFromId, _, _, _): + case let .messageFwdHeader(messageFwdHeaderData): + let (fromId, savedFromPeer, savedFromId) = (messageFwdHeaderData.fromId, messageFwdHeaderData.savedFromPeer, messageFwdHeaderData.savedFromId) if let fromId = fromId { result.append(fromId.peerId) } @@ -183,7 +188,8 @@ func apiMessagePeerIds(_ message: Api.Message) -> [PeerId] { if let media = media { switch media { - case let .messageMediaContact(_, _, _, _, userId): + case let .messageMediaContact(messageMediaContactData): + let userId = messageMediaContactData.userId if userId != 0 { result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))) } @@ -195,7 +201,8 @@ func apiMessagePeerIds(_ message: Api.Message) -> [PeerId] { if let entities = entities { for entity in entities { switch entity { - case let .messageEntityMentionName(_, _, userId): + case let .messageEntityMentionName(messageEntityMentionNameData): + let userId = messageEntityMentionNameData.userId result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))) default: break @@ -205,7 +212,8 @@ func apiMessagePeerIds(_ message: Api.Message) -> [PeerId] { if let replyTo = replyTo { switch replyTo { - case let .messageReplyStoryHeader(peer, _): + case let .messageReplyStoryHeader(messageReplyStoryHeaderData): + let peer = messageReplyStoryHeaderData.peer let storyPeerId = peer.peerId if !result.contains(storyPeerId) { result.append(storyPeerId) @@ -218,12 +226,13 @@ func apiMessagePeerIds(_ message: Api.Message) -> [PeerId] { return result case .messageEmpty: return [] - case let .messageService(_, _, fromId, chatPeerId, savedPeerId, _, _, action, _, _): + case let .messageService(messageServiceData): + let (fromId, chatPeerId, savedPeerId, action) = (messageServiceData.fromId, messageServiceData.peerId, messageServiceData.savedPeerId, messageServiceData.action) let peerId: PeerId = chatPeerId.peerId var result = [peerId] - + let resolvedFromId = fromId?.peerId ?? chatPeerId.peerId - + if resolvedFromId != peerId { result.append(resolvedFromId) } @@ -234,43 +243,60 @@ func apiMessagePeerIds(_ message: Api.Message) -> [PeerId] { switch action { case .messageActionChannelCreate, .messageActionChatDeletePhoto, .messageActionChatEditPhoto, .messageActionChatEditTitle, .messageActionEmpty, .messageActionPinMessage, .messageActionHistoryClear, .messageActionGameScore, .messageActionPaymentSent, .messageActionPaymentSentMe, .messageActionPhoneCall, .messageActionScreenshotTaken, .messageActionCustomAction, .messageActionBotAllowed, .messageActionSecureValuesSent, .messageActionSecureValuesSentMe, .messageActionContactSignUp, .messageActionGroupCall, .messageActionSetMessagesTTL, .messageActionGroupCallScheduled, .messageActionSetChatTheme, .messageActionChatJoinedByRequest, .messageActionWebViewDataSent, .messageActionWebViewDataSentMe, .messageActionGiftPremium, .messageActionGiftStars, .messageActionTopicCreate, .messageActionTopicEdit, .messageActionSuggestProfilePhoto, .messageActionSetChatWallPaper, .messageActionGiveawayLaunch, .messageActionGiveawayResults, .messageActionBoostApply, .messageActionRequestedPeerSentMe, .messageActionStarGift, .messageActionStarGiftUnique, .messageActionPaidMessagesRefunded, .messageActionPaidMessagesPrice, .messageActionTodoCompletions, .messageActionTodoAppendTasks, .messageActionSuggestedPostApproval, .messageActionGiftTon, .messageActionSuggestedPostSuccess, .messageActionSuggestedPostRefund, .messageActionSuggestBirthday, .messageActionStarGiftPurchaseOffer, .messageActionStarGiftPurchaseOfferDeclined: break - case let .messageActionChannelMigrateFrom(_, chatId): + case let .messageActionChannelMigrateFrom(messageActionChannelMigrateFromData): + let chatId = messageActionChannelMigrateFromData.chatId result.append(PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId))) - case let .messageActionChatAddUser(users): + case let .messageActionChatAddUser(messageActionChatAddUserData): + let users = messageActionChatAddUserData.users for id in users { result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(id))) } - case let .messageActionChatCreate(_, users): + case let .messageActionChatCreate(messageActionChatCreateData): + let users = messageActionChatCreateData.users for id in users { result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(id))) } - case let .messageActionChatDeleteUser(userId): + case let .messageActionChatDeleteUser(messageActionChatDeleteUserData): + let userId = messageActionChatDeleteUserData.userId result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))) - case let .messageActionChatJoinedByLink(inviterId): + case let .messageActionChatJoinedByLink(messageActionChatJoinedByLinkData): + let inviterId = messageActionChatJoinedByLinkData.inviterId result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(inviterId))) - case let .messageActionChatMigrateTo(channelId): + case let .messageActionChatMigrateTo(messageActionChatMigrateToData): + let channelId = messageActionChatMigrateToData.channelId result.append(PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))) - case let .messageActionGeoProximityReached(fromId, toId, _): + case let .messageActionGeoProximityReached(messageActionGeoProximityReachedData): + let (fromId, toId) = (messageActionGeoProximityReachedData.fromId, messageActionGeoProximityReachedData.toId) result.append(fromId.peerId) result.append(toId.peerId) - case let .messageActionInviteToGroupCall(_, userIds): + case let .messageActionInviteToGroupCall(messageActionInviteToGroupCallData): + let userIds = messageActionInviteToGroupCallData.users for id in userIds { result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(id))) } - case let .messageActionRequestedPeer(_, peers): + case let .messageActionRequestedPeer(messageActionRequestedPeerData): + let peers = messageActionRequestedPeerData.peers result.append(contentsOf: peers.map(\.peerId)) - case let .messageActionGiftCode(_, boostPeer, _, _, _, _, _, _, _): + case let .messageActionGiftCode(messageActionGiftCodeData): + let boostPeer = messageActionGiftCodeData.boostPeer if let boostPeer = boostPeer { result.append(boostPeer.peerId) } - case let .messageActionPrizeStars(_, _, _, boostPeer, _): + case let .messageActionPrizeStars(messageActionPrizeStarsData): + let boostPeer = messageActionPrizeStarsData.boostPeer result.append(boostPeer.peerId) - case let .messageActionPaymentRefunded(_, peer, _, _, _, _): + case let .messageActionPaymentRefunded(messageActionPaymentRefundedData): + let peer = messageActionPaymentRefundedData.peer result.append(peer.peerId) - case let .messageActionConferenceCall(_, _, _, otherParticipants): + case let .messageActionConferenceCall(messageActionConferenceCallData): + let otherParticipants = messageActionConferenceCallData.otherParticipants if let otherParticipants { result.append(contentsOf: otherParticipants.map(\.peerId)) } + case let .messageActionNewCreatorPending(messageActionNewCreatorPending): + result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(messageActionNewCreatorPending.newCreatorId))) + case let .messageActionChangeCreator(messageActionChangeCreator): + result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(messageActionChangeCreator.newCreatorId))) } return result @@ -279,12 +305,14 @@ func apiMessagePeerIds(_ message: Api.Message) -> [PeerId] { func apiMessageAssociatedMessageIds(_ message: Api.Message) -> (replyIds: ReferencedReplyMessageIds, generalIds: [MessageId])? { switch message { - case let .message(_, _, id, _, _, chatPeerId, _, _, _, _, replyTo, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + case let .message(messageData): + let (id, chatPeerId, replyTo) = (messageData.id, messageData.peerId, messageData.replyTo) if let replyTo = replyTo { let peerId: PeerId = chatPeerId.peerId - + switch replyTo { - case let .messageReplyHeader(_, replyToMsgId, replyToPeerId, replyHeader, replyMedia, replyToTopId, quoteText, quoteEntities, quoteOffset, todoItemId): + case let .messageReplyHeader(messageReplyHeaderData): + let (replyToMsgId, replyToPeerId, replyHeader, replyMedia, replyToTopId, quoteText, quoteEntities, quoteOffset, todoItemId) = (messageReplyHeaderData.replyToMsgId, messageReplyHeaderData.replyToPeerId, messageReplyHeaderData.replyFrom, messageReplyHeaderData.replyMedia, messageReplyHeaderData.replyToTopId, messageReplyHeaderData.quoteText, messageReplyHeaderData.quoteEntities, messageReplyHeaderData.quoteOffset, messageReplyHeaderData.todoItemId) let _ = replyHeader let _ = replyMedia let _ = replyToTopId @@ -292,7 +320,7 @@ func apiMessageAssociatedMessageIds(_ message: Api.Message) -> (replyIds: Refere let _ = quoteEntities let _ = quoteOffset let _ = todoItemId - + if let replyToMsgId = replyToMsgId { let targetId = MessageId(peerId: replyToPeerId?.peerId ?? peerId, namespace: Namespaces.Message.Cloud, id: replyToMsgId) var replyIds = ReferencedReplyMessageIds() @@ -305,10 +333,12 @@ func apiMessageAssociatedMessageIds(_ message: Api.Message) -> (replyIds: Refere } case .messageEmpty: break - case let .messageService(_, id, _, chatPeerId, _, replyHeader, _, _, _, _): + case let .messageService(messageServiceData): + let (id, chatPeerId, replyHeader) = (messageServiceData.id, messageServiceData.peerId, messageServiceData.replyTo) if let replyHeader = replyHeader { switch replyHeader { - case let .messageReplyHeader(_, replyToMsgId, replyToPeerId, replyHeader, replyMedia, replyToTopId, quoteText, quoteEntities, quoteOffset, todoItemId): + case let .messageReplyHeader(messageReplyHeaderData): + let (replyToMsgId, replyToPeerId, replyHeader, replyMedia, replyToTopId, quoteText, quoteEntities, quoteOffset, todoItemId) = (messageReplyHeaderData.replyToMsgId, messageReplyHeaderData.replyToPeerId, messageReplyHeaderData.replyFrom, messageReplyHeaderData.replyMedia, messageReplyHeaderData.replyToTopId, messageReplyHeaderData.quoteText, messageReplyHeaderData.quoteEntities, messageReplyHeaderData.quoteOffset, messageReplyHeaderData.todoItemId) let _ = replyHeader let _ = replyMedia let _ = replyToTopId @@ -316,7 +346,7 @@ func apiMessageAssociatedMessageIds(_ message: Api.Message) -> (replyIds: Refere let _ = quoteEntities let _ = quoteOffset let _ = todoItemId - + if let replyToMsgId = replyToMsgId { let targetId = MessageId(peerId: replyToPeerId?.peerId ?? chatPeerId.peerId, namespace: Namespaces.Message.Cloud, id: replyToMsgId) var replyIds = ReferencedReplyMessageIds() @@ -340,7 +370,8 @@ struct ParsedMessageWebpageAttributes { func textMediaAndExpirationTimerFromApiMedia(_ media: Api.MessageMedia?, _ peerId: PeerId) -> (media: Media?, expirationTimer: Int32?, nonPremium: Bool?, hasSpoiler: Bool?, webpageAttributes: ParsedMessageWebpageAttributes?, videoTimestamp: Int32?) { if let media = media { switch media { - case let .messageMediaPhoto(flags, photo, ttlSeconds): + case let .messageMediaPhoto(messageMediaPhotoData): + let (flags, photo, ttlSeconds) = (messageMediaPhotoData.flags, messageMediaPhotoData.photo, messageMediaPhotoData.ttlSeconds) if let photo = photo { if let mediaImage = telegramMediaImageFromApiPhoto(photo) { return (mediaImage, ttlSeconds, nil, (flags & (1 << 3)) != 0, nil, nil) @@ -348,20 +379,25 @@ func textMediaAndExpirationTimerFromApiMedia(_ media: Api.MessageMedia?, _ peerI } else { return (TelegramMediaExpiredContent(data: .image), nil, nil, nil, nil, nil) } - case let .messageMediaContact(phoneNumber, firstName, lastName, vcard, userId): + case let .messageMediaContact(messageMediaContactData): + let (phoneNumber, firstName, lastName, vcard, userId) = (messageMediaContactData.phoneNumber, messageMediaContactData.firstName, messageMediaContactData.lastName, messageMediaContactData.vcard, messageMediaContactData.userId) let contactPeerId: PeerId? = userId == 0 ? nil : PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)) let mediaContact = TelegramMediaContact(firstName: firstName, lastName: lastName, phoneNumber: phoneNumber, peerId: contactPeerId, vCardData: vcard.isEmpty ? nil : vcard) return (mediaContact, nil, nil, nil, nil, nil) - case let .messageMediaGeo(geo): + case let .messageMediaGeo(messageMediaGeoData): + let geo = messageMediaGeoData.geo let mediaMap = telegramMediaMapFromApiGeoPoint(geo, title: nil, address: nil, provider: nil, venueId: nil, venueType: nil, liveBroadcastingTimeout: nil, liveProximityNotificationRadius: nil, heading: nil) return (mediaMap, nil, nil, nil, nil, nil) - case let .messageMediaVenue(geo, title, address, provider, venueId, venueType): + case let .messageMediaVenue(messageMediaVenueData): + let (geo, title, address, provider, venueId, venueType) = (messageMediaVenueData.geo, messageMediaVenueData.title, messageMediaVenueData.address, messageMediaVenueData.provider, messageMediaVenueData.venueId, messageMediaVenueData.venueType) let mediaMap = telegramMediaMapFromApiGeoPoint(geo, title: title, address: address, provider: provider, venueId: venueId, venueType: venueType, liveBroadcastingTimeout: nil, liveProximityNotificationRadius: nil, heading: nil) return (mediaMap, nil, nil, nil, nil, nil) - case let .messageMediaGeoLive(_, geo, heading, period, proximityNotificationRadius): + case let .messageMediaGeoLive(messageMediaGeoLiveData): + let (geo, heading, period, proximityNotificationRadius) = (messageMediaGeoLiveData.geo, messageMediaGeoLiveData.heading, messageMediaGeoLiveData.period, messageMediaGeoLiveData.proximityNotificationRadius) let mediaMap = telegramMediaMapFromApiGeoPoint(geo, title: nil, address: nil, provider: nil, venueId: nil, venueType: nil, liveBroadcastingTimeout: period, liveProximityNotificationRadius: proximityNotificationRadius, heading: heading) return (mediaMap, nil, nil, nil, nil, nil) - case let .messageMediaDocument(flags, document, altDocuments, coverPhoto, videoTimestamp, ttlSeconds): + case let .messageMediaDocument(messageMediaDocumentData): + let (flags, document, altDocuments, coverPhoto, videoTimestamp, ttlSeconds) = (messageMediaDocumentData.flags, messageMediaDocumentData.document, messageMediaDocumentData.altDocuments, messageMediaDocumentData.videoCover, messageMediaDocumentData.videoTimestamp, messageMediaDocumentData.ttlSeconds) if let document = document { if let mediaFile = telegramMediaFileFromApiDocument(document, altDocuments: altDocuments, videoCover: coverPhoto) { return (mediaFile, ttlSeconds, (flags & (1 << 3)) != 0, (flags & (1 << 4)) != 0, nil, videoTimestamp) @@ -377,7 +413,8 @@ func textMediaAndExpirationTimerFromApiMedia(_ media: Api.MessageMedia?, _ peerI } return (TelegramMediaExpiredContent(data: data), nil, nil, nil, nil, nil) } - case let .messageMediaWebPage(flags, webpage): + case let .messageMediaWebPage(messageMediaWebPageData): + let (flags, webpage) = (messageMediaWebPageData.flags, messageMediaWebPageData.webpage) if let mediaWebpage = telegramMediaWebpageFromApiWebpage(webpage) { var webpageForceLargeMedia: Bool? if (flags & (1 << 0)) != 0 { @@ -385,7 +422,7 @@ func textMediaAndExpirationTimerFromApiMedia(_ media: Api.MessageMedia?, _ peerI } else if (flags & (1 << 1)) != 0 { webpageForceLargeMedia = false } - + return (mediaWebpage, nil, nil, nil, ParsedMessageWebpageAttributes( forceLargeMedia: webpageForceLargeMedia, isManuallyAdded: (flags & (1 << 3)) != 0, @@ -396,9 +433,11 @@ func textMediaAndExpirationTimerFromApiMedia(_ media: Api.MessageMedia?, _ peerI return (TelegramMediaUnsupported(), nil, nil, nil, nil, nil) case .messageMediaEmpty: break - case let .messageMediaGame(game): + case let .messageMediaGame(messageMediaGameData): + let game = messageMediaGameData.game return (TelegramMediaGame(apiGame: game), nil, nil, nil, nil, nil) - case let .messageMediaInvoice(flags, title, description, photo, receiptMsgId, currency, totalAmount, startParam, apiExtendedMedia): + case let .messageMediaInvoice(messageMediaInvoiceData): + let (flags, title, description, photo, receiptMsgId, currency, totalAmount, startParam, apiExtendedMedia) = (messageMediaInvoiceData.flags, messageMediaInvoiceData.title, messageMediaInvoiceData.description, messageMediaInvoiceData.photo, messageMediaInvoiceData.receiptMsgId, messageMediaInvoiceData.currency, messageMediaInvoiceData.totalAmount, messageMediaInvoiceData.startParam, messageMediaInvoiceData.extendedMedia) var parsedFlags = TelegramMediaInvoiceFlags() if (flags & (1 << 3)) != 0 { parsedFlags.insert(.isTest) @@ -407,9 +446,11 @@ func textMediaAndExpirationTimerFromApiMedia(_ media: Api.MessageMedia?, _ peerI parsedFlags.insert(.shippingAddressRequested) } return (TelegramMediaInvoice(title: title, description: description, photo: photo.flatMap(TelegramMediaWebFile.init), receiptMessageId: receiptMsgId.flatMap { MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: $0) }, currency: currency, totalAmount: totalAmount, startParam: startParam, extendedMedia: apiExtendedMedia.flatMap({ TelegramExtendedMedia(apiExtendedMedia: $0, peerId: peerId) }), subscriptionPeriod: nil, flags: parsedFlags, version: TelegramMediaInvoice.lastVersion), nil, nil, nil, nil, nil) - case let .messageMediaPoll(poll, results): + case let .messageMediaPoll(messageMediaPollData): + let (poll, results) = (messageMediaPollData.poll, messageMediaPollData.results) switch poll { - case let .poll(id, flags, question, answers, closePeriod, _): + case let .poll(pollData): + let (id, flags, question, answers, closePeriod, _) = (pollData.id, pollData.flags, pollData.question, pollData.answers, pollData.closePeriod, pollData.closeDate) let publicity: TelegramMediaPollPublicity if (flags & (1 << 1)) != 0 { publicity = .public @@ -426,16 +467,19 @@ func textMediaAndExpirationTimerFromApiMedia(_ media: Api.MessageMedia?, _ peerI 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) } return (TelegramMediaPoll(pollId: MediaId(namespace: Namespaces.Media.CloudPoll, id: id), publicity: publicity, kind: kind, text: questionText, textEntities: questionEntities, options: answers.map(TelegramMediaPollOption.init(apiOption:)), correctAnswers: nil, results: TelegramMediaPollResults(apiResults: results), isClosed: (flags & (1 << 0)) != 0, deadlineTimeout: closePeriod), nil, nil, nil, nil, nil) } - case let .messageMediaToDo(_, todo, completions): + case let .messageMediaToDo(messageMediaToDoData): + let (todo, completions) = (messageMediaToDoData.todo, messageMediaToDoData.completions) switch todo { - case let .todoList(apiFlags, title, list): + case let .todoList(todoListData): + let (apiFlags, title, list) = (todoListData.flags, todoListData.title, todoListData.list) var flags: TelegramMediaTodo.Flags = [] if (apiFlags & (1 << 0)) != 0 { flags.insert(.othersCanAppend) @@ -443,11 +487,12 @@ func textMediaAndExpirationTimerFromApiMedia(_ media: Api.MessageMedia?, _ peerI if (apiFlags & (1 << 1)) != 0 { flags.insert(.othersCanComplete) } - + let todoText: String let todoEntities: [MessageTextEntity] switch title { - case let .textWithEntities(text, entities): + case let .textWithEntities(textWithEntitiesData): + let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities) todoText = text todoEntities = messageTextEntitiesFromApiEntities(entities) } @@ -457,21 +502,25 @@ func textMediaAndExpirationTimerFromApiMedia(_ media: Api.MessageMedia?, _ peerI } return (TelegramMediaTodo(flags: flags, text: todoText, textEntities: todoEntities, items: list.map(TelegramMediaTodo.Item.init(apiItem:)), completions: todoCompletions), nil, nil, nil, nil, nil) } - case let .messageMediaDice(_, value, emoticon, apiGameOutcome): + case let .messageMediaDice(messageMediaDiceData): + let (value, emoticon, apiGameOutcome) = (messageMediaDiceData.value, messageMediaDiceData.emoticon, messageMediaDiceData.gameOutcome) var gameOutcome: TelegramMediaDice.GameOutcome? var tonAmount: Int64? switch apiGameOutcome { - case let .emojiGameOutcome(seed, stakeTonAmount, outcomeTonAmount): + case let .emojiGameOutcome(emojiGameOutcomeData): + let (seed, stakeTonAmount, outcomeTonAmount) = (emojiGameOutcomeData.seed, emojiGameOutcomeData.stakeTonAmount, emojiGameOutcomeData.tonAmount) gameOutcome = TelegramMediaDice.GameOutcome(seed: seed.makeData(), tonAmount: outcomeTonAmount) tonAmount = stakeTonAmount default: break } return (TelegramMediaDice(emoji: emoticon, tonAmount: tonAmount, value: value, gameOutcome: gameOutcome), nil, nil, nil, nil, nil) - case let .messageMediaStory(flags, peerId, id, _): + case let .messageMediaStory(messageMediaStoryData): + let (flags, peerId, id) = (messageMediaStoryData.flags, messageMediaStoryData.peer, messageMediaStoryData.id) let isMention = (flags & (1 << 1)) != 0 return (TelegramMediaStory(storyId: StoryId(peerId: peerId.peerId, id: id), isMention: isMention), nil, nil, nil, nil, nil) - case let .messageMediaGiveaway(apiFlags, channels, countries, prizeDescription, quantity, months, stars, untilDate): + case let .messageMediaGiveaway(messageMediaGiveawayData): + let (apiFlags, channels, countries, prizeDescription, quantity, months, stars, untilDate) = (messageMediaGiveawayData.flags, messageMediaGiveawayData.channels, messageMediaGiveawayData.countriesIso2, messageMediaGiveawayData.prizeDescription, messageMediaGiveawayData.quantity, messageMediaGiveawayData.months, messageMediaGiveawayData.stars, messageMediaGiveawayData.untilDate) var flags: TelegramMediaGiveaway.Flags = [] if (apiFlags & (1 << 0)) != 0 { flags.insert(.onlyNewSubscribers) @@ -485,7 +534,8 @@ func textMediaAndExpirationTimerFromApiMedia(_ media: Api.MessageMedia?, _ peerI return (nil, nil, nil, nil, nil, nil) } return (TelegramMediaGiveaway(flags: flags, channelPeerIds: channels.map { PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value($0)) }, countries: countries ?? [], quantity: quantity, prize: prize, untilDate: untilDate, prizeDescription: prizeDescription), nil, nil, nil, nil, nil) - case let .messageMediaGiveawayResults(apiFlags, channelId, additionalPeersCount, launchMsgId, winnersCount, unclaimedCount, winners, months, stars, prizeDescription, untilDate): + case let .messageMediaGiveawayResults(messageMediaGiveawayResultsData): + let (apiFlags, channelId, additionalPeersCount, launchMsgId, winnersCount, unclaimedCount, winners, months, stars, prizeDescription, untilDate) = (messageMediaGiveawayResultsData.flags, messageMediaGiveawayResultsData.channelId, messageMediaGiveawayResultsData.additionalPeersCount, messageMediaGiveawayResultsData.launchMsgId, messageMediaGiveawayResultsData.winnersCount, messageMediaGiveawayResultsData.unclaimedCount, messageMediaGiveawayResultsData.winners, messageMediaGiveawayResultsData.months, messageMediaGiveawayResultsData.stars, messageMediaGiveawayResultsData.prizeDescription, messageMediaGiveawayResultsData.untilDate) var flags: TelegramMediaGiveawayResults.Flags = [] if (apiFlags & (1 << 0)) != 0 { flags.insert(.onlyNewSubscribers) @@ -502,9 +552,11 @@ func textMediaAndExpirationTimerFromApiMedia(_ media: Api.MessageMedia?, _ peerI return (nil, nil, nil, nil, nil, nil) } return (TelegramMediaGiveawayResults(flags: flags, launchMessageId: MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)), namespace: Namespaces.Message.Cloud, id: launchMsgId), additionalChannelsCount: additionalPeersCount ?? 0, winnersPeerIds: winners.map { PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value($0)) }, winnersCount: winnersCount, unclaimedCount: unclaimedCount, prize: prize, untilDate: untilDate, prizeDescription: prizeDescription), nil, nil, nil, nil, nil) - case let .messageMediaPaidMedia(starsAmount, apiExtendedMedia): + case let .messageMediaPaidMedia(messageMediaPaidMediaData): + let (starsAmount, apiExtendedMedia) = (messageMediaPaidMediaData.starsAmount, messageMediaPaidMediaData.extendedMedia) return (TelegramMediaPaidContent(amount: starsAmount, extendedMedia: apiExtendedMedia.compactMap({ TelegramExtendedMedia(apiExtendedMedia: $0, peerId: peerId) })), nil, nil, nil, nil, nil) - case let .messageMediaVideoStream(flags, call): + case let .messageMediaVideoStream(messageMediaVideoStreamData): + let (flags, call) = (messageMediaVideoStreamData.flags, messageMediaVideoStreamData.call) if let call = GroupCallReference(call) { let kind: TelegramMediaLiveStream.Kind if (flags & (1 << 0)) != 0 { @@ -523,7 +575,8 @@ func textMediaAndExpirationTimerFromApiMedia(_ media: Api.MessageMedia?, _ peerI func mediaAreaFromApiMediaArea(_ mediaArea: Api.MediaArea) -> MediaArea? { func coodinatesFromApiMediaAreaCoordinates(_ coordinates: Api.MediaAreaCoordinates) -> MediaArea.Coordinates { switch coordinates { - case let .mediaAreaCoordinates(_, x, y, width, height, rotation, radius): + case let .mediaAreaCoordinates(mediaAreaCoordinatesData): + let (_, x, y, width, height, rotation, radius) = (mediaAreaCoordinatesData.flags, mediaAreaCoordinatesData.x, mediaAreaCoordinatesData.y, mediaAreaCoordinatesData.w, mediaAreaCoordinatesData.h, mediaAreaCoordinatesData.rotation, mediaAreaCoordinatesData.radius) return MediaArea.Coordinates(x: x, y: y, width: width, height: height, rotation: rotation, cornerRadius: radius) } } @@ -532,22 +585,25 @@ func mediaAreaFromApiMediaArea(_ mediaArea: Api.MediaArea) -> MediaArea? { return nil case .inputMediaAreaVenue: return nil - case let .mediaAreaGeoPoint(_, coordinates, geo, address): + case let .mediaAreaGeoPoint(mediaAreaGeoPointData): + let (_, coordinates, geo, address) = (mediaAreaGeoPointData.flags, mediaAreaGeoPointData.coordinates, mediaAreaGeoPointData.geo, mediaAreaGeoPointData.address) let latitude: Double let longitude: Double switch geo { - case let .geoPoint(_, long, lat, _, _): + case let .geoPoint(geoPointData): + let (_, long, lat, _, _) = (geoPointData.flags, geoPointData.long, geoPointData.lat, geoPointData.accessHash, geoPointData.accuracyRadius) latitude = lat longitude = long case .geoPointEmpty: latitude = 0.0 longitude = 0.0 } - + var mappedAddress: MapGeoAddress? if let address { switch address { - case let .geoPointAddress(_, countryIso2, state, city, street): + case let .geoPointAddress(geoPointAddressData): + let (_, countryIso2, state, city, street) = (geoPointAddressData.flags, geoPointAddressData.countryIso2, geoPointAddressData.state, geoPointAddressData.city, geoPointAddressData.street) mappedAddress = MapGeoAddress( country: countryIso2, state: state, @@ -556,7 +612,7 @@ func mediaAreaFromApiMediaArea(_ mediaArea: Api.MediaArea) -> MediaArea? { ) } } - + return .venue(coordinates: coodinatesFromApiMediaAreaCoordinates(coordinates), venue: MediaArea.Venue( latitude: latitude, longitude: longitude, @@ -565,11 +621,13 @@ func mediaAreaFromApiMediaArea(_ mediaArea: Api.MediaArea) -> MediaArea? { queryId: nil, resultId: nil )) - case let .mediaAreaVenue(coordinates, geo, title, address, provider, venueId, venueType): + case let .mediaAreaVenue(mediaAreaVenueData): + let (coordinates, geo, title, address, provider, venueId, venueType) = (mediaAreaVenueData.coordinates, mediaAreaVenueData.geo, mediaAreaVenueData.title, mediaAreaVenueData.address, mediaAreaVenueData.provider, mediaAreaVenueData.venueId, mediaAreaVenueData.venueType) let latitude: Double let longitude: Double switch geo { - case let .geoPoint(_, long, lat, _, _): + case let .geoPoint(geoPointData): + let (_, long, lat, _, _) = (geoPointData.flags, geoPointData.long, geoPointData.lat, geoPointData.accessHash, geoPointData.accuracyRadius) latitude = lat longitude = long case .geoPointEmpty: @@ -577,7 +635,8 @@ func mediaAreaFromApiMediaArea(_ mediaArea: Api.MediaArea) -> MediaArea? { longitude = 0.0 } return .venue(coordinates: coodinatesFromApiMediaAreaCoordinates(coordinates), venue: MediaArea.Venue(latitude: latitude, longitude: longitude, venue: MapVenue(title: title, address: address, provider: provider, id: venueId, type: venueType), address: nil, queryId: nil, resultId: nil)) - case let .mediaAreaSuggestedReaction(flags, coordinates, reaction): + case let .mediaAreaSuggestedReaction(mediaAreaSuggestedReactionData): + let (flags, coordinates, reaction) = (mediaAreaSuggestedReactionData.flags, mediaAreaSuggestedReactionData.coordinates, mediaAreaSuggestedReactionData.reaction) if let reaction = MessageReaction.Reaction(apiReaction: reaction) { var parsedFlags = MediaArea.ReactionFlags() if (flags & (1 << 0)) != 0 { @@ -590,13 +649,17 @@ func mediaAreaFromApiMediaArea(_ mediaArea: Api.MediaArea) -> MediaArea? { } else { return nil } - case let .mediaAreaUrl(coordinates, url): + case let .mediaAreaUrl(mediaAreaUrlData): + let (coordinates, url) = (mediaAreaUrlData.coordinates, mediaAreaUrlData.url) return .link(coordinates: coodinatesFromApiMediaAreaCoordinates(coordinates), url: url) - case let .mediaAreaChannelPost(coordinates, channelId, messageId): + case let .mediaAreaChannelPost(mediaAreaChannelPostData): + let (coordinates, channelId, messageId) = (mediaAreaChannelPostData.coordinates, mediaAreaChannelPostData.channelId, mediaAreaChannelPostData.msgId) return .channelMessage(coordinates: coodinatesFromApiMediaAreaCoordinates(coordinates), messageId: EngineMessage.Id(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)), namespace: Namespaces.Message.Cloud, id: messageId)) - case let .mediaAreaWeather(coordinates, emoji, temperatureC, color): + case let .mediaAreaWeather(mediaAreaWeatherData): + let (coordinates, emoji, temperatureC, color) = (mediaAreaWeatherData.coordinates, mediaAreaWeatherData.emoji, mediaAreaWeatherData.temperatureC, mediaAreaWeatherData.color) return .weather(coordinates: coodinatesFromApiMediaAreaCoordinates(coordinates), emoji: emoji, temperature: temperatureC, color: color) - case let .mediaAreaStarGift(coordinates, slug): + case let .mediaAreaStarGift(mediaAreaStarGiftData): + let (coordinates, slug) = (mediaAreaStarGiftData.coordinates, mediaAreaStarGiftData.slug) return .starGift(coordinates: coodinatesFromApiMediaAreaCoordinates(coordinates), slug: slug) } } @@ -609,13 +672,13 @@ func apiMediaAreasFromMediaAreas(_ mediaAreas: [MediaArea], transaction: Transac if let _ = coordinates.cornerRadius { flags |= (1 << 0) } - let inputCoordinates = Api.MediaAreaCoordinates.mediaAreaCoordinates(flags: flags, x: coordinates.x, y: coordinates.y, w: coordinates.width, h: coordinates.height, rotation: coordinates.rotation, radius: coordinates.cornerRadius) + let inputCoordinates = Api.MediaAreaCoordinates.mediaAreaCoordinates(.init(flags: flags, x: coordinates.x, y: coordinates.y, w: coordinates.width, h: coordinates.height, rotation: coordinates.rotation, radius: coordinates.cornerRadius)) switch area { case let .venue(_, venue): if let queryId = venue.queryId, let resultId = venue.resultId { - apiMediaAreas.append(.inputMediaAreaVenue(coordinates: inputCoordinates, queryId: queryId, resultId: resultId)) + apiMediaAreas.append(.inputMediaAreaVenue(.init(coordinates: inputCoordinates, queryId: queryId, resultId: resultId))) } else if let venueInfo = venue.venue { - apiMediaAreas.append(.mediaAreaVenue(coordinates: inputCoordinates, geo: .geoPoint(flags: 0, long: venue.longitude, lat: venue.latitude, accessHash: 0, accuracyRadius: nil), title: venueInfo.title, address: venueInfo.address ?? "", provider: venueInfo.provider ?? "", venueId: venueInfo.id ?? "", venueType: venueInfo.type ?? "")) + apiMediaAreas.append(.mediaAreaVenue(.init(coordinates: inputCoordinates, geo: .geoPoint(.init(flags: 0, long: venue.longitude, lat: venue.latitude, accessHash: 0, accuracyRadius: nil)), title: venueInfo.title, address: venueInfo.address ?? "", provider: venueInfo.provider ?? "", venueId: venueInfo.id ?? "", venueType: venueInfo.type ?? ""))) } else { var flags: Int32 = 0 var inputAddress: Api.GeoPointAddress? @@ -630,10 +693,10 @@ func apiMediaAreasFromMediaAreas(_ mediaAreas: [MediaArea], transaction: Transac if let _ = address.street { addressFlags |= (1 << 2) } - inputAddress = .geoPointAddress(flags: addressFlags, countryIso2: address.country, state: address.state, city: address.city, street: address.street) + inputAddress = .geoPointAddress(.init(flags: addressFlags, countryIso2: address.country, state: address.state, city: address.city, street: address.street)) flags |= (1 << 0) } - apiMediaAreas.append(.mediaAreaGeoPoint(flags: flags, coordinates: inputCoordinates, geo: .geoPoint(flags: 0, long: venue.longitude, lat: venue.latitude, accessHash: 0, accuracyRadius: nil), address: inputAddress)) + apiMediaAreas.append(.mediaAreaGeoPoint(.init(flags: flags, coordinates: inputCoordinates, geo: .geoPoint(.init(flags: 0, long: venue.longitude, lat: venue.latitude, accessHash: 0, accuracyRadius: nil)), address: inputAddress))) } case let .reaction(_, reaction, flags): var apiFlags: Int32 = 0 @@ -643,17 +706,17 @@ func apiMediaAreasFromMediaAreas(_ mediaAreas: [MediaArea], transaction: Transac if flags.contains(.isFlipped) { apiFlags |= (1 << 1) } - apiMediaAreas.append(.mediaAreaSuggestedReaction(flags: apiFlags, coordinates: inputCoordinates, reaction: reaction.apiReaction)) + apiMediaAreas.append(.mediaAreaSuggestedReaction(.init(flags: apiFlags, coordinates: inputCoordinates, reaction: reaction.apiReaction))) case let .channelMessage(_, messageId): if let transaction, let peer = transaction.getPeer(messageId.peerId), let inputChannel = apiInputChannel(peer) { - apiMediaAreas.append(.inputMediaAreaChannelPost(coordinates: inputCoordinates, channel: inputChannel, msgId: messageId.id)) + apiMediaAreas.append(.inputMediaAreaChannelPost(.init(coordinates: inputCoordinates, channel: inputChannel, msgId: messageId.id))) } case let .link(_, url): - apiMediaAreas.append(.mediaAreaUrl(coordinates: inputCoordinates, url: url)) + apiMediaAreas.append(.mediaAreaUrl(.init(coordinates: inputCoordinates, url: url))) case let .weather(_, emoji, temperature, color): - apiMediaAreas.append(.mediaAreaWeather(coordinates: inputCoordinates, emoji: emoji, temperatureC: temperature, color: color)) + apiMediaAreas.append(.mediaAreaWeather(.init(coordinates: inputCoordinates, emoji: emoji, temperatureC: temperature, color: color))) case let .starGift(_, slug): - apiMediaAreas.append(.mediaAreaStarGift(coordinates: inputCoordinates, slug: slug)) + apiMediaAreas.append(.mediaAreaStarGift(.init(coordinates: inputCoordinates, slug: slug))) } } return apiMediaAreas @@ -666,43 +729,62 @@ func messageTextEntitiesFromApiEntities(_ entities: [Api.MessageEntity]) -> [Mes switch entity { case .messageEntityUnknown, .inputMessageEntityMentionName: break - case let .messageEntityMention(offset, length): + case let .messageEntityMention(messageEntityMentionData): + let (offset, length) = (messageEntityMentionData.offset, messageEntityMentionData.length) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Mention)) - case let .messageEntityHashtag(offset, length): + case let .messageEntityHashtag(messageEntityHashtagData): + let (offset, length) = (messageEntityHashtagData.offset, messageEntityHashtagData.length) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Hashtag)) - case let .messageEntityBotCommand(offset, length): + case let .messageEntityBotCommand(messageEntityBotCommandData): + let (offset, length) = (messageEntityBotCommandData.offset, messageEntityBotCommandData.length) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .BotCommand)) - case let .messageEntityUrl(offset, length): + case let .messageEntityUrl(messageEntityUrlData): + let (offset, length) = (messageEntityUrlData.offset, messageEntityUrlData.length) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Url)) - case let .messageEntityEmail(offset, length): + case let .messageEntityEmail(messageEntityEmailData): + let (offset, length) = (messageEntityEmailData.offset, messageEntityEmailData.length) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Email)) - case let .messageEntityBold(offset, length): + case let .messageEntityBold(messageEntityBoldData): + let (offset, length) = (messageEntityBoldData.offset, messageEntityBoldData.length) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Bold)) - case let .messageEntityItalic(offset, length): + case let .messageEntityItalic(messageEntityItalicData): + let (offset, length) = (messageEntityItalicData.offset, messageEntityItalicData.length) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Italic)) - case let .messageEntityCode(offset, length): + case let .messageEntityCode(messageEntityCodeData): + let (offset, length) = (messageEntityCodeData.offset, messageEntityCodeData.length) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Code)) - case let .messageEntityPre(offset, length, language): + case let .messageEntityPre(messageEntityPreData): + let (offset, length, language) = (messageEntityPreData.offset, messageEntityPreData.length, messageEntityPreData.language) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Pre(language: language))) - case let .messageEntityTextUrl(offset, length, url): + case let .messageEntityTextUrl(messageEntityTextUrlData): + let (offset, length, url) = (messageEntityTextUrlData.offset, messageEntityTextUrlData.length, messageEntityTextUrlData.url) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .TextUrl(url: url))) - case let .messageEntityMentionName(offset, length, userId): + case let .messageEntityMentionName(messageEntityMentionNameData): + let (offset, length, userId) = (messageEntityMentionNameData.offset, messageEntityMentionNameData.length, messageEntityMentionNameData.userId) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .TextMention(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))))) - case let .messageEntityPhone(offset, length): + case let .messageEntityPhone(messageEntityPhoneData): + let (offset, length) = (messageEntityPhoneData.offset, messageEntityPhoneData.length) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .PhoneNumber)) - case let .messageEntityCashtag(offset, length): + case let .messageEntityCashtag(messageEntityCashtagData): + let (offset, length) = (messageEntityCashtagData.offset, messageEntityCashtagData.length) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Hashtag)) - case let .messageEntityUnderline(offset, length): + case let .messageEntityUnderline(messageEntityUnderlineData): + let (offset, length) = (messageEntityUnderlineData.offset, messageEntityUnderlineData.length) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Underline)) - case let .messageEntityStrike(offset, length): + case let .messageEntityStrike(messageEntityStrikeData): + let (offset, length) = (messageEntityStrikeData.offset, messageEntityStrikeData.length) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Strikethrough)) - case let .messageEntityBlockquote(flags, offset, length): + case let .messageEntityBlockquote(messageEntityBlockquoteData): + let (flags, offset, length) = (messageEntityBlockquoteData.flags, messageEntityBlockquoteData.offset, messageEntityBlockquoteData.length) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .BlockQuote(isCollapsed: (flags & (1 << 0)) != 0))) - case let .messageEntityBankCard(offset, length): + case let .messageEntityBankCard(messageEntityBankCardData): + let (offset, length) = (messageEntityBankCardData.offset, messageEntityBankCardData.length) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .BankCard)) - case let .messageEntitySpoiler(offset, length): + case let .messageEntitySpoiler(messageEntitySpoilerData): + let (offset, length) = (messageEntitySpoilerData.offset, messageEntitySpoilerData.length) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Spoiler)) - case let .messageEntityCustomEmoji(offset, length, documentId): + case let .messageEntityCustomEmoji(messageEntityCustomEmojiData): + let (offset, length, documentId) = (messageEntityCustomEmojiData.offset, messageEntityCustomEmojiData.length, messageEntityCustomEmojiData.documentId) result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .CustomEmoji(stickerPack: nil, fileId: documentId))) } } @@ -712,13 +794,14 @@ func messageTextEntitiesFromApiEntities(_ entities: [Api.MessageEntity]) -> [Mes extension StoreMessage { convenience init?(apiMessage: Api.Message, accountPeerId: PeerId, peerIsForum: Bool, namespace: MessageId.Namespace = Namespaces.Message.Cloud) { switch apiMessage { - case let .message(flags, flags2, id, fromId, boosts, chatPeerId, savedPeerId, fwdFrom, viaBotId, viaBusinessBotId, replyTo, date, message, media, replyMarkup, entities, views, forwards, replies, editDate, postAuthor, groupingId, reactions, restrictionReason, ttlPeriod, quickReplyShortcutId, messageEffectId, factCheck, reportDeliveryUntilDate, paidMessageStars, suggestedPost, scheduledRepeatPeriod, summaryFromLanguage): + case let .message(messageData): + let (flags, flags2, id, fromId, boosts, chatPeerId, savedPeerId, fwdFrom, viaBotId, viaBusinessBotId, replyTo, date, message, media, replyMarkup, entities, views, forwards, replies, editDate, postAuthor, groupingId, reactions, restrictionReason, ttlPeriod, quickReplyShortcutId, messageEffectId, factCheck, reportDeliveryUntilDate, paidMessageStars, suggestedPost, scheduledRepeatPeriod, summaryFromLanguage) = (messageData.flags, messageData.flags2, messageData.id, messageData.fromId, messageData.fromBoostsApplied, messageData.peerId, messageData.savedPeerId, messageData.fwdFrom, messageData.viaBotId, messageData.viaBusinessBotId, messageData.replyTo, messageData.date, messageData.message, messageData.media, messageData.replyMarkup, messageData.entities, messageData.views, messageData.forwards, messageData.replies, messageData.editDate, messageData.postAuthor, messageData.groupedId, messageData.reactions, messageData.restrictionReason, messageData.ttlPeriod, messageData.quickReplyShortcutId, messageData.effect, messageData.factcheck, messageData.reportDeliveryUntilDate, messageData.paidMessageStars, messageData.suggestedPost, messageData.scheduleRepeatPeriod, messageData.summaryFromLanguage) var attributes: [MessageAttribute] = [] - + if (flags2 & (1 << 4)) != 0 { attributes.append(PendingProcessingMessageAttribute(approximateCompletionTime: date)) } - + let resolvedFromId = fromId?.peerId ?? chatPeerId.peerId var namespace = namespace @@ -732,10 +815,12 @@ extension StoreMessage { case .peerUser: peerId = chatPeerId.peerId authorId = resolvedFromId - case let .peerChat(chatId): + case let .peerChat(peerChatData): + let chatId = peerChatData.chatId peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId)) authorId = resolvedFromId - case let .peerChannel(channelId): + case let .peerChannel(peerChannelData): + let channelId = peerChannelData.channelId peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) authorId = resolvedFromId } @@ -744,7 +829,8 @@ extension StoreMessage { if let replyTo = replyTo { var threadMessageId: MessageId? switch replyTo { - case let .messageReplyHeader(innerFlags, replyToMsgId, replyToPeerId, replyHeader, replyMedia, replyToTopId, quoteText, quoteEntities, quoteOffset, todoItemId): + case let .messageReplyHeader(messageReplyHeaderData): + let (innerFlags, replyToMsgId, replyToPeerId, replyHeader, replyMedia, replyToTopId, quoteText, quoteEntities, quoteOffset, todoItemId) = (messageReplyHeaderData.flags, messageReplyHeaderData.replyToMsgId, messageReplyHeaderData.replyToPeerId, messageReplyHeaderData.replyFrom, messageReplyHeaderData.replyMedia, messageReplyHeaderData.replyToTopId, messageReplyHeaderData.quoteText, messageReplyHeaderData.quoteEntities, messageReplyHeaderData.quoteOffset, messageReplyHeaderData.todoItemId) let isForumTopic = (innerFlags & (1 << 3)) != 0 var quote: EngineMessageReplyQuote? @@ -800,35 +886,37 @@ extension StoreMessage { if let replyHeader = replyHeader { attributes.append(QuotedReplyMessageAttribute(apiHeader: replyHeader, quote: quote, isQuote: isQuote)) } - case let .messageReplyStoryHeader(peer, storyId): + case let .messageReplyStoryHeader(messageReplyStoryHeaderData): + let (peer, storyId) = (messageReplyStoryHeaderData.peer, messageReplyStoryHeaderData.storyId) attributes.append(ReplyStoryAttribute(storyId: StoryId(peerId: peer.peerId, id: storyId))) } } - + if threadId == nil && peerId.namespace == Namespaces.Peer.CloudChannel { threadId = 1 } - + var forwardInfo: StoreMessageForwardInfo? if let fwdFrom = fwdFrom { switch fwdFrom { - case let .messageFwdHeader(flags, fromId, fromName, date, channelPost, postAuthor, savedFromPeer, savedFromMsgId, savedFromId, savedFromName, savedDate, psaType): + case let .messageFwdHeader(messageFwdHeaderData): + let (flags, fromId, fromName, date, channelPost, postAuthor, savedFromPeer, savedFromMsgId, savedFromId, savedFromName, savedDate, psaType) = (messageFwdHeaderData.flags, messageFwdHeaderData.fromId, messageFwdHeaderData.fromName, messageFwdHeaderData.date, messageFwdHeaderData.channelPost, messageFwdHeaderData.postAuthor, messageFwdHeaderData.savedFromPeer, messageFwdHeaderData.savedFromMsgId, messageFwdHeaderData.savedFromId, messageFwdHeaderData.savedFromName, messageFwdHeaderData.savedDate, messageFwdHeaderData.psaType) var forwardInfoFlags: MessageForwardInfo.Flags = [] let isImported = (flags & (1 << 7)) != 0 if isImported { forwardInfoFlags.insert(.isImported) } - + var authorId: PeerId? var sourceId: PeerId? var sourceMessageId: MessageId? - + if let fromId = fromId { switch fromId { case .peerChannel: let peerId = fromId.peerId sourceId = peerId - + if let channelPost = channelPost { sourceMessageId = MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: channelPost) } @@ -836,9 +924,9 @@ extension StoreMessage { authorId = fromId.peerId } } - + let originalOutgoing = (flags & (1 << 11)) != 0 - + if let savedFromPeer = savedFromPeer, let savedFromMsgId = savedFromMsgId { let peerId: PeerId = savedFromPeer.peerId let messageId: MessageId = MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: savedFromMsgId) @@ -847,7 +935,7 @@ extension StoreMessage { if savedFromId != nil || savedFromName != nil || savedDate != nil || originalOutgoing { attributes.append(SourceAuthorInfoMessageAttribute(originalAuthor: savedFromId?.peerId, originalAuthorName: savedFromName, orignalDate: savedDate, originalOutgoing: originalOutgoing)) } - + if let authorId = authorId { forwardInfo = StoreMessageForwardInfo(authorId: authorId, sourceId: sourceId, sourceMessageId: sourceMessageId, date: date, authorSignature: postAuthor, psaType: psaType, flags: forwardInfoFlags) } else if let sourceId = sourceId { @@ -1012,7 +1100,8 @@ extension StoreMessage { if let replies = replies { let recentRepliersPeerIds: [PeerId]? switch replies { - case let .messageReplies(_, repliesCount, _, recentRepliers, channelId, maxId, readMaxId): + case let .messageReplies(messageRepliesData): + let (repliesCount, recentRepliers, channelId, maxId, readMaxId) = (messageRepliesData.replies, messageRepliesData.recentRepliers, messageRepliesData.channelId, messageRepliesData.maxId, messageRepliesData.readMaxId) if let recentRepliers = recentRepliers { recentRepliersPeerIds = recentRepliers.map { $0.peerId } } else { @@ -1035,11 +1124,13 @@ extension StoreMessage { if let factCheck { switch factCheck { - 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 { @@ -1109,39 +1200,43 @@ extension StoreMessage { self.init(id: MessageId(peerId: peerId, namespace: namespace, id: id), customStableId: nil, globallyUniqueId: nil, groupingKey: groupingId, threadId: threadId, timestamp: date, flags: storeFlags, tags: tags, globalTags: globalTags, localTags: [], forwardInfo: forwardInfo, authorId: authorId, text: messageText, attributes: attributes, media: medias) case .messageEmpty: return nil - case let .messageService(flags, id, fromId, chatPeerId, savedPeerId, replyTo, date, action, reactions, ttlPeriod): + case let .messageService(messageServiceData): + let (flags, id, fromId, chatPeerId, savedPeerId, replyTo, date, action, reactions, ttlPeriod) = (messageServiceData.flags, messageServiceData.id, messageServiceData.fromId, messageServiceData.peerId, messageServiceData.savedPeerId, messageServiceData.replyTo, messageServiceData.date, messageServiceData.action, messageServiceData.reactions, messageServiceData.ttlPeriod) let peerId: PeerId = chatPeerId.peerId let authorId: PeerId? = fromId?.peerId ?? chatPeerId.peerId - + var attributes: [MessageAttribute] = [] - + var threadId: Int64? if let savedPeerId { threadId = savedPeerId.peerId.toInt64() if chatPeerId.peerId.namespace == Namespaces.Peer.CloudChannel, let replyTo { switch replyTo { - case let .messageReplyHeader(innerFlags, replyToMsgId, replyToPeerId, replyHeader, replyMedia, _, quoteText, quoteEntities, quoteOffset, todoItemId): + case let .messageReplyHeader(messageReplyHeaderData): + let (innerFlags, replyToMsgId, replyToPeerId, replyHeader, replyMedia, quoteText, quoteEntities, quoteOffset, todoItemId) = (messageReplyHeaderData.flags, messageReplyHeaderData.replyToMsgId, messageReplyHeaderData.replyToPeerId, messageReplyHeaderData.replyFrom, messageReplyHeaderData.replyMedia, messageReplyHeaderData.quoteText, messageReplyHeaderData.quoteEntities, messageReplyHeaderData.quoteOffset, messageReplyHeaderData.todoItemId) var quote: EngineMessageReplyQuote? let isQuote = (innerFlags & (1 << 9)) != 0 if quoteText != nil || replyMedia != nil { quote = EngineMessageReplyQuote(text: quoteText ?? "", offset: quoteOffset.flatMap(Int.init), entities: messageTextEntitiesFromApiEntities(quoteEntities ?? []), media: textMediaAndExpirationTimerFromApiMedia(replyMedia, peerId).media) } - + if let replyToMsgId = replyToMsgId { let replyPeerId = replyToPeerId?.peerId ?? peerId attributes.append(ReplyMessageAttribute(messageId: MessageId(peerId: replyPeerId, namespace: Namespaces.Message.Cloud, id: replyToMsgId), threadMessageId: nil, quote: quote, isQuote: isQuote, todoItemId: todoItemId)) } else if let replyHeader = replyHeader { attributes.append(QuotedReplyMessageAttribute(apiHeader: replyHeader, quote: quote, isQuote: isQuote)) } - case let .messageReplyStoryHeader(peer, storyId): + case let .messageReplyStoryHeader(messageReplyStoryHeaderData): + let (peer, storyId) = (messageReplyStoryHeaderData.peer, messageReplyStoryHeaderData.storyId) attributes.append(ReplyStoryAttribute(storyId: StoryId(peerId: peer.peerId, id: storyId))) } } } else if let replyTo = replyTo { var threadMessageId: MessageId? switch replyTo { - case let .messageReplyHeader(innerFlags, replyToMsgId, replyToPeerId, replyHeader, replyMedia, replyToTopId, quoteText, quoteEntities, quoteOffset, todoItemId): + case let .messageReplyHeader(messageReplyHeaderData): + let (innerFlags, replyToMsgId, replyToPeerId, replyHeader, replyMedia, replyToTopId, quoteText, quoteEntities, quoteOffset, todoItemId) = (messageReplyHeaderData.flags, messageReplyHeaderData.replyToMsgId, messageReplyHeaderData.replyToPeerId, messageReplyHeaderData.replyFrom, messageReplyHeaderData.replyMedia, messageReplyHeaderData.replyToTopId, messageReplyHeaderData.quoteText, messageReplyHeaderData.quoteEntities, messageReplyHeaderData.quoteOffset, messageReplyHeaderData.todoItemId) var quote: EngineMessageReplyQuote? let isQuote = (innerFlags & (1 << 9)) != 0 if quoteText != nil || replyMedia != nil { @@ -1171,7 +1266,8 @@ extension StoreMessage { } else if let replyHeader = replyHeader { attributes.append(QuotedReplyMessageAttribute(apiHeader: replyHeader, quote: quote, isQuote: isQuote)) } - case let .messageReplyStoryHeader(peer, storyId): + case let .messageReplyStoryHeader(messageReplyStoryHeaderData): + let (peer, storyId) = (messageReplyStoryHeaderData.peer, messageReplyStoryHeaderData.storyId) attributes.append(ReplyStoryAttribute(storyId: StoryId(peerId: peer.peerId, id: storyId))) } } else { diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramChannelAdminRights.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramChannelAdminRights.swift index d31969cd..9f3fe6e8 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramChannelAdminRights.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramChannelAdminRights.swift @@ -6,7 +6,8 @@ import TelegramApi extension TelegramChatAdminRights { init?(apiAdminRights: Api.ChatAdminRights) { switch apiAdminRights { - case let .chatAdminRights(flags): + case let .chatAdminRights(chatAdminRightsData): + let flags = chatAdminRightsData.flags if flags == 0 { return nil } @@ -18,6 +19,6 @@ extension TelegramChatAdminRights { var apiAdminRights: Api.ChatAdminRights { var filteredFlags = self.rights.rawValue filteredFlags |= 1 << 12 - return .chatAdminRights(flags: filteredFlags) + return .chatAdminRights(Api.ChatAdminRights.Cons_chatAdminRights(flags: filteredFlags)) } } diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramChannelBannedRights.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramChannelBannedRights.swift index 8e2a362c..0565841a 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramChannelBannedRights.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramChannelBannedRights.swift @@ -5,7 +5,8 @@ import TelegramApi extension TelegramChatBannedRights { init(apiBannedRights: Api.ChatBannedRights) { switch apiBannedRights { - case let .chatBannedRights(flags, untilDate): + case let .chatBannedRights(chatBannedRightsData): + let (flags, untilDate) = (chatBannedRightsData.flags, chatBannedRightsData.untilDate) var effectiveFlags = TelegramChatBannedRightsFlags(rawValue: flags) effectiveFlags.remove(.banSendMedia) effectiveFlags.remove(TelegramChatBannedRightsFlags(rawValue: 1 << 1)) @@ -18,6 +19,6 @@ extension TelegramChatBannedRights { effectiveFlags.remove(.banSendMedia) effectiveFlags.remove(TelegramChatBannedRightsFlags(rawValue: 1 << 1)) - return .chatBannedRights(flags: effectiveFlags.rawValue, untilDate: self.untilDate) + return .chatBannedRights(.init(flags: effectiveFlags.rawValue, untilDate: self.untilDate)) } } diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramExtendedMedia.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramExtendedMedia.swift index 4a6200ae..fb3b2283 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramExtendedMedia.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramExtendedMedia.swift @@ -5,17 +5,20 @@ import TelegramApi extension TelegramExtendedMedia { init?(apiExtendedMedia: Api.MessageExtendedMedia, peerId: PeerId) { switch apiExtendedMedia { - case let .messageExtendedMediaPreview(_, width, height, thumb, videoDuration): + case let .messageExtendedMediaPreview(messageExtendedMediaPreviewData): + let (width, height, thumb, videoDuration) = (messageExtendedMediaPreviewData.w, messageExtendedMediaPreviewData.h, messageExtendedMediaPreviewData.thumb, messageExtendedMediaPreviewData.videoDuration) var dimensions: PixelDimensions? if let width = width, let height = height { dimensions = PixelDimensions(width: width, height: height) } var immediateThumbnailData: Data? - if let thumb = thumb, case let .photoStrippedSize(_, bytes) = thumb { + if let thumb = thumb, case let .photoStrippedSize(photoStrippedSizeData) = thumb { + let bytes = photoStrippedSizeData.bytes immediateThumbnailData = bytes.makeData() } self = .preview(dimensions: dimensions, immediateThumbnailData: immediateThumbnailData, videoDuration: videoDuration) - case let .messageExtendedMedia(apiMedia): + case let .messageExtendedMedia(messageExtendedMediaData): + let apiMedia = messageExtendedMediaData.media if let media = textMediaAndExpirationTimerFromApiMedia(apiMedia, peerId).media { self = .full(media: media) } else { diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaAction.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaAction.swift index e92c2872..3c7cf235 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaAction.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaAction.swift @@ -5,33 +5,44 @@ import TelegramApi func telegramMediaActionFromApiAction(_ action: Api.MessageAction) -> TelegramMediaAction? { switch action { - case let .messageActionChannelCreate(title): + case let .messageActionChannelCreate(messageActionChannelCreateData): + let title = messageActionChannelCreateData.title return TelegramMediaAction(action: .groupCreated(title: title)) - case let .messageActionChannelMigrateFrom(title, chatId): + case let .messageActionChannelMigrateFrom(messageActionChannelMigrateFromData): + let (title, chatId) = (messageActionChannelMigrateFromData.title, messageActionChannelMigrateFromData.chatId) return TelegramMediaAction(action: .channelMigratedFromGroup(title: title, groupId: PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId)))) - case let .messageActionChatAddUser(users): + case let .messageActionChatAddUser(messageActionChatAddUserData): + let users = messageActionChatAddUserData.users return TelegramMediaAction(action: .addedMembers(peerIds: users.map({ PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value($0)) }))) - case let .messageActionChatCreate(title, _): + case let .messageActionChatCreate(messageActionChatCreateData): + let title = messageActionChatCreateData.title return TelegramMediaAction(action: .groupCreated(title: title)) case .messageActionChatDeletePhoto: return TelegramMediaAction(action: .photoUpdated(image: nil)) - case let .messageActionChatDeleteUser(userId): + case let .messageActionChatDeleteUser(messageActionChatDeleteUserData): + let userId = messageActionChatDeleteUserData.userId return TelegramMediaAction(action: .removedMembers(peerIds: [PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))])) - case let .messageActionChatEditPhoto(photo): + case let .messageActionChatEditPhoto(messageActionChatEditPhotoData): + let photo = messageActionChatEditPhotoData.photo return TelegramMediaAction(action: .photoUpdated(image: telegramMediaImageFromApiPhoto(photo))) - case let .messageActionChatEditTitle(title): + case let .messageActionChatEditTitle(messageActionChatEditTitleData): + let title = messageActionChatEditTitleData.title return TelegramMediaAction(action: .titleUpdated(title: title)) - case let .messageActionChatJoinedByLink(inviterId): + case let .messageActionChatJoinedByLink(messageActionChatJoinedByLinkData): + let inviterId = messageActionChatJoinedByLinkData.inviterId return TelegramMediaAction(action: .joinedByLink(inviter: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(inviterId)))) - case let .messageActionChatMigrateTo(channelId): + case let .messageActionChatMigrateTo(messageActionChatMigrateToData): + let channelId = messageActionChatMigrateToData.channelId return TelegramMediaAction(action: .groupMigratedToChannel(channelId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)))) case .messageActionHistoryClear: return TelegramMediaAction(action: .historyCleared) case .messageActionPinMessage: return TelegramMediaAction(action: .pinnedMessageUpdated) - case let .messageActionGameScore(gameId, score): + case let .messageActionGameScore(messageActionGameScoreData): + let (gameId, score) = (messageActionGameScoreData.gameId, messageActionGameScoreData.score) return TelegramMediaAction(action: .gameScore(gameId: gameId, score: score)) - case let .messageActionPhoneCall(flags, callId, reason, duration): + case let .messageActionPhoneCall(messageActionPhoneCallData): + let (flags, callId, reason, duration) = (messageActionPhoneCallData.flags, messageActionPhoneCallData.callId, messageActionPhoneCallData.reason, messageActionPhoneCallData.duration) var discardReason: PhoneCallDiscardReason? if let reason = reason { discardReason = PhoneCallDiscardReason(apiReason: reason) @@ -40,7 +51,8 @@ func telegramMediaActionFromApiAction(_ action: Api.MessageAction) -> TelegramMe return TelegramMediaAction(action: .phoneCall(callId: callId, discardReason: discardReason, duration: duration, isVideo: isVideo)) case .messageActionEmpty: return nil - case let .messageActionPaymentSent(flags, currency, totalAmount, invoiceSlug, subscriptionUntilDate): + case let .messageActionPaymentSent(messageActionPaymentSentData): + let (flags, currency, totalAmount, invoiceSlug, subscriptionUntilDate) = (messageActionPaymentSentData.flags, messageActionPaymentSentData.currency, messageActionPaymentSentData.totalAmount, messageActionPaymentSentData.invoiceSlug, messageActionPaymentSentData.subscriptionUntilDate) let _ = subscriptionUntilDate let isRecurringInit = (flags & (1 << 2)) != 0 let isRecurringUsed = (flags & (1 << 3)) != 0 @@ -49,14 +61,17 @@ func telegramMediaActionFromApiAction(_ action: Api.MessageAction) -> TelegramMe return nil case .messageActionScreenshotTaken: return TelegramMediaAction(action: .historyScreenshot) - case let .messageActionCustomAction(message): + case let .messageActionCustomAction(messageActionCustomActionData): + let message = messageActionCustomActionData.message return TelegramMediaAction(action: .customText(text: message, entities: [], additionalAttributes: nil)) - case let .messageActionBotAllowed(flags, domain, app): + case let .messageActionBotAllowed(messageActionBotAllowedData): + let (flags, domain, app) = (messageActionBotAllowedData.flags, messageActionBotAllowedData.domain, messageActionBotAllowedData.app) if let domain = domain { return TelegramMediaAction(action: .botDomainAccessGranted(domain: domain)) } else { var appName: String? - if case let .botApp(_, _, _, _, appNameValue, _, _, _, _) = app { + if case let .botApp(botAppData) = app { + let appNameValue = botAppData.title appName = appNameValue } var type: BotSendMessageAccessGrantedType? @@ -70,38 +85,48 @@ func telegramMediaActionFromApiAction(_ action: Api.MessageAction) -> TelegramMe } case .messageActionSecureValuesSentMe: return nil - case let .messageActionSecureValuesSent(types): + case let .messageActionSecureValuesSent(messageActionSecureValuesSentData): + let types = messageActionSecureValuesSentData.types return TelegramMediaAction(action: .botSentSecureValues(types: types.map(SentSecureValueType.init))) case .messageActionContactSignUp: return TelegramMediaAction(action: .peerJoined) - case let .messageActionGeoProximityReached(fromId, toId, distance): + case let .messageActionGeoProximityReached(messageActionGeoProximityReachedData): + let (fromId, toId, distance) = (messageActionGeoProximityReachedData.fromId, messageActionGeoProximityReachedData.toId, messageActionGeoProximityReachedData.distance) return TelegramMediaAction(action: .geoProximityReached(from: fromId.peerId, to: toId.peerId, distance: distance)) - case let .messageActionGroupCall(_, call, duration): + case let .messageActionGroupCall(messageActionGroupCallData): + let (call, duration) = (messageActionGroupCallData.call, messageActionGroupCallData.duration) switch call { - case let .inputGroupCall(id, accessHash): + case let .inputGroupCall(inputGroupCallData): + let (id, accessHash) = (inputGroupCallData.id, inputGroupCallData.accessHash) return TelegramMediaAction(action: .groupPhoneCall(callId: id, accessHash: accessHash, scheduleDate: nil, duration: duration)) case .inputGroupCallSlug, .inputGroupCallInviteMessage: return nil } - case let .messageActionInviteToGroupCall(call, userIds): + case let .messageActionInviteToGroupCall(messageActionInviteToGroupCallData): + let (call, userIds) = (messageActionInviteToGroupCallData.call, messageActionInviteToGroupCallData.users) switch call { - case let .inputGroupCall(id, accessHash): + case let .inputGroupCall(inputGroupCallData): + let (id, accessHash) = (inputGroupCallData.id, inputGroupCallData.accessHash) return TelegramMediaAction(action: .inviteToGroupPhoneCall(callId: id, accessHash: accessHash, peerIds: userIds.map { userId in PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)) })) case .inputGroupCallSlug, .inputGroupCallInviteMessage: return nil } - case let .messageActionSetMessagesTTL(_, period, autoSettingFrom): + case let .messageActionSetMessagesTTL(messageActionSetMessagesTTLData): + let (period, autoSettingFrom) = (messageActionSetMessagesTTLData.period, messageActionSetMessagesTTLData.autoSettingFrom) return TelegramMediaAction(action: .messageAutoremoveTimeoutUpdated(period: period, autoSettingSource: autoSettingFrom.flatMap { PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value($0)) })) - case let .messageActionGroupCallScheduled(call, scheduleDate): + case let .messageActionGroupCallScheduled(messageActionGroupCallScheduledData): + let (call, scheduleDate) = (messageActionGroupCallScheduledData.call, messageActionGroupCallScheduledData.scheduleDate) switch call { - case let .inputGroupCall(id, accessHash): + case let .inputGroupCall(inputGroupCallData): + let (id, accessHash) = (inputGroupCallData.id, inputGroupCallData.accessHash) return TelegramMediaAction(action: .groupPhoneCall(callId: id, accessHash: accessHash, scheduleDate: scheduleDate, duration: nil)) case .inputGroupCallSlug, .inputGroupCallInviteMessage: return nil } - case let .messageActionSetChatTheme(chatTheme): + case let .messageActionSetChatTheme(messageActionSetChatThemeData): + let chatTheme = messageActionSetChatThemeData.theme if let chatTheme = ChatTheme(apiChatTheme: chatTheme) { return TelegramMediaAction(action: .setChatTheme(chatTheme: chatTheme)) } else { @@ -109,13 +134,19 @@ func telegramMediaActionFromApiAction(_ action: Api.MessageAction) -> TelegramMe } case .messageActionChatJoinedByRequest: return TelegramMediaAction(action: .joinedByRequest) - case let .messageActionWebViewDataSentMe(text, _), let .messageActionWebViewDataSent(text): + case let .messageActionWebViewDataSentMe(messageActionWebViewDataSentMeData): + let text = messageActionWebViewDataSentMeData.text return TelegramMediaAction(action: .webViewData(text)) - case let .messageActionGiftPremium(_, currency, amount, days, cryptoCurrency, cryptoAmount, message): + case let .messageActionWebViewDataSent(messageActionWebViewDataSentData): + let text = messageActionWebViewDataSentData.text + return TelegramMediaAction(action: .webViewData(text)) + case let .messageActionGiftPremium(messageActionGiftPremiumData): + let (currency, amount, days, cryptoCurrency, cryptoAmount, message) = (messageActionGiftPremiumData.currency, messageActionGiftPremiumData.amount, messageActionGiftPremiumData.days, messageActionGiftPremiumData.cryptoCurrency, messageActionGiftPremiumData.cryptoAmount, messageActionGiftPremiumData.message) let text: String? let 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: @@ -123,11 +154,14 @@ func telegramMediaActionFromApiAction(_ action: Api.MessageAction) -> TelegramMe entities = nil } return TelegramMediaAction(action: .giftPremium(currency: currency, amount: amount, days: days, cryptoCurrency: cryptoCurrency, cryptoAmount: cryptoAmount, text: text, entities: entities)) - case let .messageActionGiftStars(_, currency, amount, stars, cryptoCurrency, cryptoAmount, transactionId): + case let .messageActionGiftStars(messageActionGiftStarsData): + let (currency, amount, stars, cryptoCurrency, cryptoAmount, transactionId) = (messageActionGiftStarsData.currency, messageActionGiftStarsData.amount, messageActionGiftStarsData.stars, messageActionGiftStarsData.cryptoCurrency, messageActionGiftStarsData.cryptoAmount, messageActionGiftStarsData.transactionId) return TelegramMediaAction(action: .giftStars(currency: currency, amount: amount, count: stars, cryptoCurrency: cryptoCurrency, cryptoAmount: cryptoAmount, transactionId: transactionId)) - case let .messageActionTopicCreate(_, title, iconColor, iconEmojiId): + case let .messageActionTopicCreate(messageActionTopicCreateData): + let (title, iconColor, iconEmojiId) = (messageActionTopicCreateData.title, messageActionTopicCreateData.iconColor, messageActionTopicCreateData.iconEmojiId) return TelegramMediaAction(action: .topicCreated(title: title, iconColor: iconColor, iconFileId: iconEmojiId)) - case let .messageActionTopicEdit(flags, title, iconEmojiId, closed, hidden): + case let .messageActionTopicEdit(messageActionTopicEditData): + let (flags, title, iconEmojiId, closed, hidden) = (messageActionTopicEditData.flags, messageActionTopicEditData.title, messageActionTopicEditData.iconEmojiId, messageActionTopicEditData.closed, messageActionTopicEditData.hidden) var components: [TelegramMediaActionType.ForumTopicEditComponent] = [] if let title = title { components.append(.title(title)) @@ -142,50 +176,63 @@ func telegramMediaActionFromApiAction(_ action: Api.MessageAction) -> TelegramMe components.append(.isHidden(hidden == .boolTrue)) } return TelegramMediaAction(action: .topicEdited(components: components)) - case let .messageActionSuggestProfilePhoto(photo): + case let .messageActionSuggestProfilePhoto(messageActionSuggestProfilePhotoData): + let photo = messageActionSuggestProfilePhotoData.photo return TelegramMediaAction(action: .suggestedProfilePhoto(image: telegramMediaImageFromApiPhoto(photo))) - case let .messageActionRequestedPeer(buttonId, peers): + case let .messageActionRequestedPeer(messageActionRequestedPeerData): + let (buttonId, peers) = (messageActionRequestedPeerData.buttonId, messageActionRequestedPeerData.peers) return TelegramMediaAction(action: .requestedPeer(buttonId: buttonId, peerIds: peers.map { $0.peerId })) - case let .messageActionRequestedPeerSentMe(buttonId, _): + case let .messageActionRequestedPeerSentMe(messageActionRequestedPeerSentMeData): + let buttonId = messageActionRequestedPeerSentMeData.buttonId return TelegramMediaAction(action: .requestedPeer(buttonId: buttonId, peerIds: [])) - case let .messageActionSetChatWallPaper(flags, wallpaper): + case let .messageActionSetChatWallPaper(messageActionSetChatWallPaperData): + let (flags, wallpaper) = (messageActionSetChatWallPaperData.flags, messageActionSetChatWallPaperData.wallpaper) if (flags & (1 << 0)) != 0 { return TelegramMediaAction(action: .setSameChatWallpaper(wallpaper: TelegramWallpaper(apiWallpaper: wallpaper))) } else { return TelegramMediaAction(action: .setChatWallpaper(wallpaper: TelegramWallpaper(apiWallpaper: wallpaper), forBoth: (flags & (1 << 1)) != 0)) } - case let .messageActionGiftCode(flags, boostPeer, months, slug, currency, amount, cryptoCurrency, cryptoAmount, message): + case let .messageActionGiftCode(messageActionGiftCodeData): + let (flags, boostPeer, days, slug, currency, amount, cryptoCurrency, cryptoAmount, message) = (messageActionGiftCodeData.flags, messageActionGiftCodeData.boostPeer, messageActionGiftCodeData.days, messageActionGiftCodeData.slug, messageActionGiftCodeData.currency, messageActionGiftCodeData.amount, messageActionGiftCodeData.cryptoCurrency, messageActionGiftCodeData.cryptoAmount, messageActionGiftCodeData.message) let text: String? let 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: text = nil entities = nil } - return TelegramMediaAction(action: .giftCode(slug: slug, fromGiveaway: (flags & (1 << 0)) != 0, isUnclaimed: (flags & (1 << 5)) != 0, boostPeerId: boostPeer?.peerId, months: months, currency: currency, amount: amount, cryptoCurrency: cryptoCurrency, cryptoAmount: cryptoAmount, text: text, entities: entities)) - case let .messageActionGiveawayLaunch(_, stars): - return TelegramMediaAction(action: .giveawayLaunched(stars: stars)) - case let .messageActionGiveawayResults(flags, winners, unclaimed): + return TelegramMediaAction(action: .giftCode(slug: slug, fromGiveaway: (flags & (1 << 0)) != 0, isUnclaimed: (flags & (1 << 5)) != 0, boostPeerId: boostPeer?.peerId, months: days, currency: currency, amount: amount, cryptoCurrency: cryptoCurrency, cryptoAmount: cryptoAmount, text: text, entities: entities)) + case let .messageActionGiveawayLaunch(messageActionGiveawayLaunchData): + return TelegramMediaAction(action: .giveawayLaunched(stars: messageActionGiveawayLaunchData.stars)) + case let .messageActionGiveawayResults(messageActionGiveawayResultsData): + let (flags, winners, unclaimed) = (messageActionGiveawayResultsData.flags, messageActionGiveawayResultsData.winnersCount, messageActionGiveawayResultsData.unclaimedCount) return TelegramMediaAction(action: .giveawayResults(winners: winners, unclaimed: unclaimed, stars: (flags & (1 << 0)) != 0)) - case let .messageActionBoostApply(boosts): + case let .messageActionBoostApply(messageActionBoostApplyData): + let boosts = messageActionBoostApplyData.boosts return TelegramMediaAction(action: .boostsApplied(boosts: boosts)) - case let .messageActionPaymentRefunded(_, peer, currency, totalAmount, payload, charge): + case let .messageActionPaymentRefunded(messageActionPaymentRefundedData): + let (peer, currency, totalAmount, payload, charge) = (messageActionPaymentRefundedData.peer, messageActionPaymentRefundedData.currency, messageActionPaymentRefundedData.totalAmount, messageActionPaymentRefundedData.payload, messageActionPaymentRefundedData.charge) let transactionId: String switch charge { - case let .paymentCharge(id, _): + case let .paymentCharge(paymentChargeData): + let id = paymentChargeData.id transactionId = id } return TelegramMediaAction(action: .paymentRefunded(peerId: peer.peerId, currency: currency, totalAmount: totalAmount, payload: payload?.makeData(), transactionId: transactionId)) - case let .messageActionPrizeStars(flags, stars, transactionId, boostPeer, giveawayMsgId): + case let .messageActionPrizeStars(messageActionPrizeStarsData): + let (flags, stars, transactionId, boostPeer, giveawayMsgId) = (messageActionPrizeStarsData.flags, messageActionPrizeStarsData.stars, messageActionPrizeStarsData.transactionId, messageActionPrizeStarsData.boostPeer, messageActionPrizeStarsData.giveawayMsgId) return TelegramMediaAction(action: .prizeStars(amount: stars, isUnclaimed: (flags & (1 << 2)) != 0, boostPeerId: boostPeer.peerId, transactionId: transactionId, giveawayMessageId: MessageId(peerId: boostPeer.peerId, namespace: Namespaces.Message.Cloud, id: giveawayMsgId))) - case let .messageActionStarGift(flags, apiGift, message, convertStars, upgradeMessageId, upgradeStars, fromId, peer, savedId, prepaidUpgradeHash, giftMessageId, toId, number): + case let .messageActionStarGift(messageActionStarGiftData): + let (flags, apiGift, message, convertStars, upgradeMessageId, upgradeStars, fromId, peer, savedId, prepaidUpgradeHash, giftMessageId, toId, number) = (messageActionStarGiftData.flags, messageActionStarGiftData.gift, messageActionStarGiftData.message, messageActionStarGiftData.convertStars, messageActionStarGiftData.upgradeMsgId, messageActionStarGiftData.upgradeStars, messageActionStarGiftData.fromId, messageActionStarGiftData.peer, messageActionStarGiftData.savedId, messageActionStarGiftData.prepaidUpgradeHash, messageActionStarGiftData.giftMsgId, messageActionStarGiftData.toId, messageActionStarGiftData.giftNum) let text: String? let 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: @@ -196,21 +243,25 @@ func telegramMediaActionFromApiAction(_ action: Api.MessageAction) -> TelegramMe return nil } return TelegramMediaAction(action: .starGift(gift: gift, convertStars: convertStars, text: text, entities: entities, nameHidden: (flags & (1 << 0)) != 0, savedToProfile: (flags & (1 << 2)) != 0, converted: (flags & (1 << 3)) != 0, upgraded: (flags & (1 << 5)) != 0, canUpgrade: (flags & (1 << 10)) != 0, upgradeStars: upgradeStars, isRefunded: (flags & (1 << 9)) != 0, isPrepaidUpgrade: (flags & (1 << 13)) != 0, upgradeMessageId: upgradeMessageId, peerId: peer?.peerId, senderId: fromId?.peerId, savedId: savedId, prepaidUpgradeHash: prepaidUpgradeHash, giftMessageId: giftMessageId, upgradeSeparate: (flags & (1 << 16)) != 0, isAuctionAcquired: (flags & (1 << 17)) != 0, toPeerId: toId?.peerId, number: number)) - case let .messageActionStarGiftUnique(flags, apiGift, canExportAt, transferStars, fromId, peer, savedId, resaleAmount, canTransferDate, canResaleDate, dropOriginalDetailsStars): + case let .messageActionStarGiftUnique(messageActionStarGiftUniqueData): + let (flags, apiGift, canExportAt, transferStars, fromId, peer, savedId, resaleAmount, canTransferDate, canResaleDate, dropOriginalDetailsStars, canCraftAt) = (messageActionStarGiftUniqueData.flags, messageActionStarGiftUniqueData.gift, messageActionStarGiftUniqueData.canExportAt, messageActionStarGiftUniqueData.transferStars, messageActionStarGiftUniqueData.fromId, messageActionStarGiftUniqueData.peer, messageActionStarGiftUniqueData.savedId, messageActionStarGiftUniqueData.resaleAmount, messageActionStarGiftUniqueData.canTransferAt, messageActionStarGiftUniqueData.canResellAt, messageActionStarGiftUniqueData.dropOriginalDetailsStars, messageActionStarGiftUniqueData.canCraftAt) guard let gift = StarGift(apiStarGift: apiGift) else { return nil } - return TelegramMediaAction(action: .starGiftUnique(gift: gift, isUpgrade: (flags & (1 << 0)) != 0, isTransferred: (flags & (1 << 1)) != 0, savedToProfile: (flags & (1 << 2)) != 0, canExportDate: canExportAt, transferStars: transferStars, isRefunded: (flags & (1 << 5)) != 0, isPrepaidUpgrade: (flags & (1 << 11)) != 0, peerId: peer?.peerId, senderId: fromId?.peerId, savedId: savedId, resaleAmount: resaleAmount.flatMap { CurrencyAmount(apiAmount: $0) }, canTransferDate: canTransferDate, canResaleDate: canResaleDate, dropOriginalDetailsStars: dropOriginalDetailsStars, assigned: (flags & (1 << 13)) != 0, fromOffer: (flags & (1 << 14)) != 0)) - case let .messageActionPaidMessagesRefunded(count, stars): + return TelegramMediaAction(action: .starGiftUnique(gift: gift, isUpgrade: (flags & (1 << 0)) != 0, isTransferred: (flags & (1 << 1)) != 0, savedToProfile: (flags & (1 << 2)) != 0, canExportDate: canExportAt, transferStars: transferStars, isRefunded: (flags & (1 << 5)) != 0, isPrepaidUpgrade: (flags & (1 << 11)) != 0, peerId: peer?.peerId, senderId: fromId?.peerId, savedId: savedId, resaleAmount: resaleAmount.flatMap { CurrencyAmount(apiAmount: $0) }, canTransferDate: canTransferDate, canResaleDate: canResaleDate, dropOriginalDetailsStars: dropOriginalDetailsStars, assigned: (flags & (1 << 13)) != 0, fromOffer: (flags & (1 << 14)) != 0, canCraftAt: canCraftAt, isCrafted: (flags & (1 << 16)) != 0)) + case let .messageActionPaidMessagesRefunded(messageActionPaidMessagesRefundedData): + let (count, stars) = (messageActionPaidMessagesRefundedData.count, messageActionPaidMessagesRefundedData.stars) return TelegramMediaAction(action: .paidMessagesRefunded(count: count, stars: stars)) - case let .messageActionPaidMessagesPrice(flags, stars): + case let .messageActionPaidMessagesPrice(messageActionPaidMessagesPriceData): + let (flags, stars) = (messageActionPaidMessagesPriceData.flags, messageActionPaidMessagesPriceData.stars) let broadcastMessagesAllowed = (flags & (1 << 0)) != 0 return TelegramMediaAction(action: .paidMessagesPriceEdited(stars: stars, broadcastMessagesAllowed: broadcastMessagesAllowed)) - case let .messageActionConferenceCall(flags, callId, duration, otherParticipants): + case let .messageActionConferenceCall(messageActionConferenceCallData): + let (flags, callId, duration, otherParticipants) = (messageActionConferenceCallData.flags, messageActionConferenceCallData.callId, messageActionConferenceCallData.duration, messageActionConferenceCallData.otherParticipants) let isMissed = (flags & (1 << 0)) != 0 let isActive = (flags & (1 << 1)) != 0 let isVideo = (flags & (1 << 4)) != 0 - + var mappedFlags = TelegramMediaActionType.ConferenceCall.Flags() if isMissed { mappedFlags.insert(.isMissed) @@ -221,18 +272,21 @@ func telegramMediaActionFromApiAction(_ action: Api.MessageAction) -> TelegramMe if isVideo { mappedFlags.insert(.isVideo) } - + return TelegramMediaAction(action: .conferenceCall(TelegramMediaActionType.ConferenceCall( callId: callId, duration: duration, flags: mappedFlags, otherParticipants: otherParticipants.flatMap({ return $0.map(\.peerId) }) ?? [] ))) - case let .messageActionTodoCompletions(completed, incompleted): + case let .messageActionTodoCompletions(messageActionTodoCompletionsData): + let (completed, incompleted) = (messageActionTodoCompletionsData.completed, messageActionTodoCompletionsData.incompleted) return TelegramMediaAction(action: .todoCompletions(completed: completed, incompleted: incompleted)) - case let .messageActionTodoAppendTasks(list): + case let .messageActionTodoAppendTasks(messageActionTodoAppendTasksData): + let list = messageActionTodoAppendTasksData.list return TelegramMediaAction(action: .todoAppendTasks(list.map { TelegramMediaTodo.Item(apiItem: $0) })) - case let .messageActionSuggestedPostApproval(flags, rejectComment, scheduleDate, starsAmount): + case let .messageActionSuggestedPostApproval(messageActionSuggestedPostApprovalData): + let (flags, rejectComment, scheduleDate, starsAmount) = (messageActionSuggestedPostApprovalData.flags, messageActionSuggestedPostApprovalData.rejectComment, messageActionSuggestedPostApprovalData.scheduleDate, messageActionSuggestedPostApprovalData.price) let status: TelegramMediaActionType.SuggestedPostApprovalStatus if (flags & (1 << 0)) != 0 { let reason: TelegramMediaActionType.SuggestedPostApprovalStatus.RejectionReason @@ -241,9 +295,11 @@ func telegramMediaActionFromApiAction(_ action: Api.MessageAction) -> TelegramMe switch starsAmount { case .none: balanceNeeded = CurrencyAmount(amount: .zero, currency: .stars) - case let .starsAmount(amount, nanos): + case let .starsAmount(starsAmountData): + let (amount, nanos) = (starsAmountData.amount, starsAmountData.nanos) balanceNeeded = CurrencyAmount(amount: StarsAmount(value: amount, nanos: nanos), currency: .stars) - case let .starsTonAmount(amount): + case let .starsTonAmount(starsTonAmountData): + let amount = starsTonAmountData.amount balanceNeeded = CurrencyAmount(amount: StarsAmount(value: amount, nanos: 0), currency: .ton) } reason = .lowBalance(balanceNeeded: balanceNeeded) @@ -256,9 +312,11 @@ func telegramMediaActionFromApiAction(_ action: Api.MessageAction) -> TelegramMe switch starsAmount { case .none: amountValue = CurrencyAmount(amount: .zero, currency: .stars) - case let .starsAmount(amount, nanos): + case let .starsAmount(starsAmountData): + let (amount, nanos) = (starsAmountData.amount, starsAmountData.nanos) amountValue = CurrencyAmount(amount: StarsAmount(value: amount, nanos: nanos), currency: .stars) - case let .starsTonAmount(amount): + case let .starsTonAmount(starsTonAmountData): + let amount = starsTonAmountData.amount amountValue = CurrencyAmount(amount: StarsAmount(value: amount, nanos: 0), currency: .ton) } status = .rejected(reason: .lowBalance(balanceNeeded: amountValue), comment: nil) @@ -266,25 +324,41 @@ func telegramMediaActionFromApiAction(_ action: Api.MessageAction) -> TelegramMe status = .approved(timestamp: scheduleDate, amount: starsAmount.flatMap(CurrencyAmount.init(apiAmount:))) } return TelegramMediaAction(action: .suggestedPostApprovalStatus(status: status)) - case let .messageActionGiftTon(_, currency, amount, cryptoCurrency, cryptoAmount, transactionId): + case let .messageActionGiftTon(messageActionGiftTonData): + let (currency, amount, cryptoCurrency, cryptoAmount, transactionId) = (messageActionGiftTonData.currency, messageActionGiftTonData.amount, messageActionGiftTonData.cryptoCurrency, messageActionGiftTonData.cryptoAmount, messageActionGiftTonData.transactionId) return TelegramMediaAction(action: .giftTon(currency: currency, amount: amount, cryptoCurrency: cryptoCurrency, cryptoAmount: cryptoAmount, transactionId: transactionId)) - case let .messageActionSuggestedPostSuccess(price): + case let .messageActionSuggestedPostSuccess(messageActionSuggestedPostSuccessData): + let price = messageActionSuggestedPostSuccessData.price return TelegramMediaAction(action: .suggestedPostSuccess(amount: CurrencyAmount(apiAmount: price))) - case let .messageActionSuggestedPostRefund(flags): + case let .messageActionSuggestedPostRefund(messageActionSuggestedPostRefundData): + let flags = messageActionSuggestedPostRefundData.flags return TelegramMediaAction(action: .suggestedPostRefund(TelegramMediaActionType.SuggestedPostRefund(isUserInitiated: (flags & (1 << 0)) != 0))) - case let .messageActionSuggestBirthday(birthday): + case let .messageActionSuggestBirthday(messageActionSuggestBirthdayData): + let birthday = messageActionSuggestBirthdayData.birthday return TelegramMediaAction(action: .suggestedBirthday(TelegramBirthday(apiBirthday: birthday))) - case let .messageActionStarGiftPurchaseOffer(flags, apiGift, price, expiresAt): + case let .messageActionStarGiftPurchaseOffer(messageActionStarGiftPurchaseOfferData): + let (flags, apiGift, price, expiresAt) = (messageActionStarGiftPurchaseOfferData.flags, messageActionStarGiftPurchaseOfferData.gift, messageActionStarGiftPurchaseOfferData.price, messageActionStarGiftPurchaseOfferData.expiresAt) guard let gift = StarGift(apiStarGift: apiGift) else { return nil } return TelegramMediaAction(action: .starGiftPurchaseOffer(gift: gift, amount: CurrencyAmount(apiAmount: price), expireDate: expiresAt, isAccepted: (flags & (1 << 0)) != 0, isDeclined: (flags & (1 << 1)) != 0)) - case let .messageActionStarGiftPurchaseOfferDeclined(flags, apiGift, price): + case let .messageActionStarGiftPurchaseOfferDeclined(messageActionStarGiftPurchaseOfferDeclinedData): + let (flags, apiGift, price) = (messageActionStarGiftPurchaseOfferDeclinedData.flags, messageActionStarGiftPurchaseOfferDeclinedData.gift, messageActionStarGiftPurchaseOfferDeclinedData.price) guard let gift = StarGift(apiStarGift: apiGift) else { return nil } return TelegramMediaAction(action: .starGiftPurchaseOfferDeclined(gift: gift, amount: CurrencyAmount(apiAmount: price), hasExpired: (flags & (1 << 0)) != 0)) + case let .messageActionNewCreatorPending(messageActionNewCreatorPending): + return TelegramMediaAction(action: .groupCreatorChange(TelegramMediaActionType.GroupCreatorChange( + kind: .pending, + targetPeerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(messageActionNewCreatorPending.newCreatorId)) + ))) + case let .messageActionChangeCreator(messageActionChangeCreator): + return TelegramMediaAction(action: .groupCreatorChange(TelegramMediaActionType.GroupCreatorChange( + kind: .applied, + targetPeerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(messageActionChangeCreator.newCreatorId)) + ))) } } diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaFile.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaFile.swift index 4dbcafd5..42954883 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaFile.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaFile.swift @@ -69,13 +69,16 @@ extension StickerPackReference { switch apiInputSet { case .inputStickerSetEmpty: return nil - case let .inputStickerSetID(id, accessHash): + case let .inputStickerSetID(inputStickerSetIDData): + let (id, accessHash) = (inputStickerSetIDData.id, inputStickerSetIDData.accessHash) self = .id(id: id, accessHash: accessHash) - case let .inputStickerSetShortName(shortName): + case let .inputStickerSetShortName(inputStickerSetShortNameData): + let shortName = inputStickerSetShortNameData.shortName self = .name(shortName) case .inputStickerSetAnimatedEmoji: self = .animatedEmoji - case let .inputStickerSetDice(emoticon): + case let .inputStickerSetDice(inputStickerSetDiceData): + let emoticon = inputStickerSetDiceData.emoticon self = .dice(emoticon) case .inputStickerSetAnimatedEmojiAnimations: self = .animatedEmojiAnimations @@ -98,7 +101,8 @@ extension StickerPackReference { extension StickerMaskCoords { init(apiMaskCoords: Api.MaskCoords) { switch apiMaskCoords { - case let .maskCoords(n, x, y, zoom): + case let .maskCoords(maskCoordsData): + let (n, x, y, zoom) = (maskCoordsData.n, maskCoordsData.x, maskCoordsData.y, maskCoordsData.zoom) self.init(n: n, x: x, y: y, zoom: zoom) } } @@ -108,17 +112,21 @@ func telegramMediaFileAttributesFromApiAttributes(_ attributes: [Api.DocumentAtt var result: [TelegramMediaFileAttribute] = [] for attribute in attributes { switch attribute { - case let .documentAttributeFilename(fileName): + case let .documentAttributeFilename(documentAttributeFilenameData): + let fileName = documentAttributeFilenameData.fileName result.append(.FileName(fileName: fileName)) - case let .documentAttributeSticker(_, alt, stickerSet, maskCoords): + case let .documentAttributeSticker(documentAttributeStickerData): + let (alt, stickerSet, maskCoords) = (documentAttributeStickerData.alt, documentAttributeStickerData.stickerset, documentAttributeStickerData.maskCoords) result.append(.Sticker(displayText: alt, packReference: StickerPackReference(apiInputSet: stickerSet), maskData: maskCoords.flatMap(StickerMaskCoords.init))) case .documentAttributeHasStickers: result.append(.HasLinkedStickers) - case let .documentAttributeImageSize(w, h): + case let .documentAttributeImageSize(documentAttributeImageSizeData): + let (w, h) = (documentAttributeImageSizeData.w, documentAttributeImageSizeData.h) result.append(.ImageSize(size: PixelDimensions(width: w, height: h))) case .documentAttributeAnimated: result.append(.Animated) - case let .documentAttributeVideo(flags, duration, w, h, preloadSize, videoStart, videoCodec): + case let .documentAttributeVideo(documentAttributeVideoData): + let (flags, duration, w, h, preloadSize, videoStart, videoCodec) = (documentAttributeVideoData.flags, documentAttributeVideoData.duration, documentAttributeVideoData.w, documentAttributeVideoData.h, documentAttributeVideoData.preloadPrefixSize, documentAttributeVideoData.videoStartTs, documentAttributeVideoData.videoCodec) var videoFlags = TelegramMediaVideoFlags() if (flags & (1 << 0)) != 0 { videoFlags.insert(.instantRoundVideo) @@ -130,11 +138,13 @@ func telegramMediaFileAttributesFromApiAttributes(_ attributes: [Api.DocumentAtt videoFlags.insert(.isSilent) } result.append(.Video(duration: Double(duration), size: PixelDimensions(width: w, height: h), flags: videoFlags, preloadSize: preloadSize, coverTime: videoStart, videoCodec: videoCodec)) - case let .documentAttributeAudio(flags, duration, title, performer, waveform): + case let .documentAttributeAudio(documentAttributeAudioData): + let (flags, duration, title, performer, waveform) = (documentAttributeAudioData.flags, documentAttributeAudioData.duration, documentAttributeAudioData.title, documentAttributeAudioData.performer, documentAttributeAudioData.waveform) let isVoice = (flags & (1 << 10)) != 0 let waveformBuffer: Data? = waveform?.makeData() result.append(.Audio(isVoice: isVoice, duration: Int(duration), title: title, performer: performer, waveform: waveformBuffer)) - case let .documentAttributeCustomEmoji(flags, alt, stickerSet): + case let .documentAttributeCustomEmoji(documentAttributeCustomEmojiData): + let (flags, alt, stickerSet) = (documentAttributeCustomEmojiData.flags, documentAttributeCustomEmojiData.alt, documentAttributeCustomEmojiData.stickerset) let isFree = (flags & (1 << 0)) != 0 let isSingleColor = (flags & (1 << 1)) != 0 result.append(.CustomEmoji(isPremium: !isFree, isSingleColor: isSingleColor, alt: alt, packReference: StickerPackReference(apiInputSet: stickerSet))) @@ -157,18 +167,23 @@ func telegramMediaFileThumbnailRepresentationsFromApiSizes(datacenterId: Int32, var representations: [TelegramMediaImageRepresentation] = [] for size in sizes { switch size { - case let .photoCachedSize(type, w, h, _): + case let .photoCachedSize(photoCachedSizeData): + let (type, w, h, _) = (photoCachedSizeData.type, photoCachedSizeData.w, photoCachedSizeData.h, photoCachedSizeData.bytes) let resource = CloudDocumentSizeMediaResource(datacenterId: datacenterId, documentId: documentId, accessHash: accessHash, sizeSpec: type, fileReference: fileReference) representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: resource, progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false, isPersonal: false)) - case let .photoSize(type, w, h, _): + case let .photoSize(photoSizeData): + let (type, w, h, _) = (photoSizeData.type, photoSizeData.w, photoSizeData.h, photoSizeData.size) let resource = CloudDocumentSizeMediaResource(datacenterId: datacenterId, documentId: documentId, accessHash: accessHash, sizeSpec: type, fileReference: fileReference) representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: resource, progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false, isPersonal: false)) - case let .photoSizeProgressive(type, w, h, sizes): + case let .photoSizeProgressive(photoSizeProgressiveData): + let (type, w, h, sizes) = (photoSizeProgressiveData.type, photoSizeProgressiveData.w, photoSizeProgressiveData.h, photoSizeProgressiveData.sizes) let resource = CloudDocumentSizeMediaResource(datacenterId: datacenterId, documentId: documentId, accessHash: accessHash, sizeSpec: type, fileReference: fileReference) representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: resource, progressiveSizes: sizes, immediateThumbnailData: nil, hasVideo: false, isPersonal: false)) - case let .photoPathSize(_, data): + case let .photoPathSize(photoPathSizeData): + let (_, data) = (photoPathSizeData.type, photoPathSizeData.bytes) immediateThumbnailData = data.makeData() - case let .photoStrippedSize(_, data): + case let .photoStrippedSize(photoStrippedSizeData): + let (_, data) = (photoStrippedSizeData.type, photoStrippedSizeData.bytes) immediateThumbnailData = data.makeData() case .photoSizeEmpty: break @@ -179,7 +194,8 @@ func telegramMediaFileThumbnailRepresentationsFromApiSizes(datacenterId: Int32, func telegramMediaFileFromApiDocument(_ document: Api.Document, altDocuments: [Api.Document]?, videoCover: Api.Photo? = nil) -> TelegramMediaFile? { switch document { - case let .document(_, id, accessHash, fileReference, _, mimeType, size, thumbs, videoThumbs, dcId, attributes): + case let .document(documentData): + let (id, accessHash, fileReference, mimeType, size, thumbs, videoThumbs, dcId, attributes) = (documentData.id, documentData.accessHash, documentData.fileReference, documentData.mimeType, documentData.size, documentData.thumbs, documentData.videoThumbs, documentData.dcId, documentData.attributes) var parsedAttributes = telegramMediaFileAttributesFromApiAttributes(attributes) var isSticker = false var isAnimated = false @@ -203,7 +219,8 @@ func telegramMediaFileFromApiDocument(_ document: Api.Document, altDocuments: [A if let videoThumbs = videoThumbs { for thumb in videoThumbs { switch thumb { - case let .videoSize(_, type, w, h, _, _): + case let .videoSize(videoSizeData): + let (_, type, w, h, _, _) = (videoSizeData.flags, videoSizeData.type, videoSizeData.w, videoSizeData.h, videoSizeData.size, videoSizeData.videoStartTs) let resource: TelegramMediaResource resource = CloudDocumentSizeMediaResource(datacenterId: dcId, documentId: id, accessHash: accessHash, sizeSpec: type, fileReference: fileReference.makeData()) diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaGame.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaGame.swift index e4365a2a..4e55f1f6 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaGame.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaGame.swift @@ -6,7 +6,8 @@ import TelegramApi extension TelegramMediaGame { convenience init(apiGame: Api.Game) { switch apiGame { - case let .game(_, id, accessHash, shortName, title, description, photo, document): + case let .game(gameData): + let (id, accessHash, shortName, title, description, photo, document) = (gameData.id, gameData.accessHash, gameData.shortName, gameData.title, gameData.description, gameData.photo, gameData.document) var file: TelegramMediaFile? if let document = document { file = telegramMediaFileFromApiDocument(document, altDocuments: []) diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaImage.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaImage.swift index c0fbc2fe..3ab34d18 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaImage.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaImage.swift @@ -8,18 +8,22 @@ func telegramMediaImageRepresentationsFromApiSizes(datacenterId: Int32, photoId: var representations: [TelegramMediaImageRepresentation] = [] for size in sizes { switch size { - case let .photoCachedSize(type, w, h, _): + case let .photoCachedSize(photoCachedSizeData): + let (type, w, h) = (photoCachedSizeData.type, photoCachedSizeData.w, photoCachedSizeData.h) let resource = CloudPhotoSizeMediaResource(datacenterId: datacenterId, photoId: photoId, accessHash: accessHash, sizeSpec: type, size: nil, fileReference: fileReference) representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: resource, progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false, isPersonal: false)) - case let .photoSize(type, w, h, size): + case let .photoSize(photoSizeData): + let (type, w, h, size) = (photoSizeData.type, photoSizeData.w, photoSizeData.h, photoSizeData.size) let resource = CloudPhotoSizeMediaResource(datacenterId: datacenterId, photoId: photoId, accessHash: accessHash, sizeSpec: type, size: Int64(size), fileReference: fileReference) representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: resource, progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false, isPersonal: false)) - case let .photoSizeProgressive(type, w, h, sizes): + case let .photoSizeProgressive(photoSizeProgressiveData): + let (type, w, h, sizes) = (photoSizeProgressiveData.type, photoSizeProgressiveData.w, photoSizeProgressiveData.h, photoSizeProgressiveData.sizes) if !sizes.isEmpty { let resource = CloudPhotoSizeMediaResource(datacenterId: datacenterId, photoId: photoId, accessHash: accessHash, sizeSpec: type, size: Int64(sizes[sizes.count - 1]), fileReference: fileReference) representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: resource, progressiveSizes: sizes, immediateThumbnailData: nil, hasVideo: false, isPersonal: false)) } - case let .photoStrippedSize(_, data): + case let .photoStrippedSize(photoStrippedSizeData): + let data = photoStrippedSizeData.bytes immediateThumbnailData = data.makeData() case .photoPathSize: break @@ -32,7 +36,8 @@ func telegramMediaImageRepresentationsFromApiSizes(datacenterId: Int32, photoId: func telegramMediaImageFromApiPhoto(_ photo: Api.Photo) -> TelegramMediaImage? { switch photo { - case let .photo(flags, id, accessHash, fileReference, _, sizes, videoSizes, dcId): + case let .photo(photoData): + let (flags, id, accessHash, fileReference, sizes, videoSizes, dcId) = (photoData.flags, photoData.id, photoData.accessHash, photoData.fileReference, photoData.sizes, photoData.videoSizes, photoData.dcId) let (immediateThumbnailData, representations) = telegramMediaImageRepresentationsFromApiSizes(datacenterId: dcId, photoId: id, accessHash: accessHash, fileReference: fileReference.makeData(), sizes: sizes) var imageFlags: TelegramMediaImageFlags = [] let hasStickers = (flags & (1 << 0)) != 0 @@ -45,14 +50,17 @@ func telegramMediaImageFromApiPhoto(_ photo: Api.Photo) -> TelegramMediaImage? { 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 let .videoSizeEmojiMarkup(fileId, backgroundColors): + case let .videoSizeEmojiMarkup(videoSizeEmojiMarkupData): + let (fileId, backgroundColors) = (videoSizeEmojiMarkupData.emojiId, videoSizeEmojiMarkupData.backgroundColors) emojiMarkup = TelegramMediaImage.EmojiMarkup(content: .emoji(fileId: fileId), backgroundColors: backgroundColors) - case let .videoSizeStickerMarkup(stickerSet, fileId, backgroundColors): + case let .videoSizeStickerMarkup(videoSizeStickerMarkupData): + let (stickerSet, fileId, backgroundColors) = (videoSizeStickerMarkupData.stickerset, videoSizeStickerMarkupData.stickerId, videoSizeStickerMarkupData.backgroundColors) if let packReference = StickerPackReference(apiInputSet: stickerSet) { emojiMarkup = TelegramMediaImage.EmojiMarkup(content: .sticker(packReference: packReference, fileId: fileId), backgroundColors: backgroundColors) } diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaMap.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaMap.swift index 84d935b8..650727e7 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaMap.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaMap.swift @@ -9,7 +9,8 @@ func telegramMediaMapFromApiGeoPoint(_ geo: Api.GeoPoint, title: String?, addres venue = MapVenue(title: title, address: address, provider: provider, id: venueId, type: venueType) } switch geo { - case let .geoPoint(_, long, lat, _, accuracyRadius): + case let .geoPoint(geoPointData): + let (_, long, lat, _, accuracyRadius) = (geoPointData.flags, geoPointData.long, geoPointData.lat, geoPointData.accessHash, geoPointData.accuracyRadius) return TelegramMediaMap(latitude: lat, longitude: long, heading: heading, accuracyRadius: accuracyRadius.flatMap { Double($0) }, venue: venue, liveBroadcastingTimeout: liveBroadcastingTimeout, liveProximityNotificationRadius: liveProximityNotificationRadius) case .geoPointEmpty: return TelegramMediaMap(latitude: 0.0, longitude: 0.0, heading: nil, accuracyRadius: nil, venue: venue, liveBroadcastingTimeout: liveBroadcastingTimeout, liveProximityNotificationRadius: liveProximityNotificationRadius) @@ -19,7 +20,8 @@ func telegramMediaMapFromApiGeoPoint(_ geo: Api.GeoPoint, title: String?, addres func mapGeoAddressFromApiGeoPointAddress(_ geo: Api.GeoPointAddress) -> MapGeoAddress { switch geo { - case let .geoPointAddress(_, countryIso2, state, city, street): + case let .geoPointAddress(geoPointAddressData): + let (countryIso2, state, city, street) = (geoPointAddressData.countryIso2, geoPointAddressData.state, geoPointAddressData.city, geoPointAddressData.street) return MapGeoAddress(country: countryIso2, state: state, city: city, street: street) } } diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaPoll.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaPoll.swift index 6fb59331..b9e3fb77 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaPoll.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaPoll.swift @@ -6,11 +6,13 @@ import TelegramApi extension TelegramMediaPollOption { init(apiOption: Api.PollAnswer) { switch apiOption { - case let .pollAnswer(text, option): + case let .pollAnswer(pollAnswerData): + let (text, option) = (pollAnswerData.text, pollAnswerData.option) let answerText: String let answerEntities: [MessageTextEntity] switch text { - case let .textWithEntities(text, entities): + case let .textWithEntities(textWithEntitiesData): + let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities) answerText = text answerEntities = messageTextEntitiesFromApiEntities(entities) } @@ -20,14 +22,15 @@ extension TelegramMediaPollOption { } var apiOption: Api.PollAnswer { - return .pollAnswer(text: .textWithEntities(text: self.text, entities: apiEntitiesFromMessageTextEntities(self.entities, associatedPeers: SimpleDictionary())), option: Buffer(data: self.opaqueIdentifier)) + return .pollAnswer(.init(text: .textWithEntities(.init(text: self.text, entities: apiEntitiesFromMessageTextEntities(self.entities, associatedPeers: SimpleDictionary()))), option: Buffer(data: self.opaqueIdentifier))) } } extension TelegramMediaPollOptionVoters { init(apiVoters: Api.PollAnswerVoters) { switch apiVoters { - case let .pollAnswerVoters(flags, option, voters): + case let .pollAnswerVoters(pollAnswerVotersData): + let (flags, option, voters) = (pollAnswerVotersData.flags, pollAnswerVotersData.option, pollAnswerVotersData.voters) self.init(selected: (flags & (1 << 0)) != 0, opaqueIdentifier: option.makeData(), count: voters, isCorrect: (flags & (1 << 1)) != 0) } } @@ -36,7 +39,8 @@ extension TelegramMediaPollOptionVoters { extension TelegramMediaPollResults { init(apiResults: Api.PollResults) { switch apiResults { - case let .pollResults(_, results, totalVoters, recentVoters, solution, solutionEntities): + case let .pollResults(pollResultsData): + let (results, totalVoters, recentVoters, solution, solutionEntities) = (pollResultsData.results, pollResultsData.totalVoters, pollResultsData.recentVoters, pollResultsData.solution, pollResultsData.solutionEntities) var parsedSolution: TelegramMediaPollResults.Solution? if let solution = solution, let solutionEntities = solutionEntities, !solution.isEmpty { parsedSolution = TelegramMediaPollResults.Solution(text: solution, entities: messageTextEntitiesFromApiEntities(solutionEntities)) diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaTodo.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaTodo.swift index 073b9697..30e3907d 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaTodo.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaTodo.swift @@ -6,11 +6,13 @@ import TelegramApi extension TelegramMediaTodo.Item { init(apiItem: Api.TodoItem) { switch apiItem { - case let .todoItem(id, title): + case let .todoItem(todoItemData): + let (id, title) = (todoItemData.id, todoItemData.title) let itemText: String let itemEntities: [MessageTextEntity] switch title { - case let .textWithEntities(text, entities): + case let .textWithEntities(textWithEntitiesData): + let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities) itemText = text itemEntities = messageTextEntitiesFromApiEntities(entities) } @@ -19,14 +21,15 @@ extension TelegramMediaTodo.Item { } var apiItem: Api.TodoItem { - return .todoItem(id: self.id, title: .textWithEntities(text: self.text, entities: apiEntitiesFromMessageTextEntities(self.entities, associatedPeers: SimpleDictionary()))) + return .todoItem(.init(id: self.id, title: .textWithEntities(.init(text: self.text, entities: apiEntitiesFromMessageTextEntities(self.entities, associatedPeers: SimpleDictionary()))))) } } extension TelegramMediaTodo.Completion { init(apiCompletion: Api.TodoCompletion) { switch apiCompletion { - case let .todoCompletion(id, completedBy, date): + case let .todoCompletion(todoCompletionData): + let (id, completedBy, date) = (todoCompletionData.id, todoCompletionData.completedBy, todoCompletionData.date) self.init(id: id, date: date, completedBy: completedBy.peerId) } } diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaWebDocument.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaWebDocument.swift index 1de43ff1..d2ca668e 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaWebDocument.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaWebDocument.swift @@ -6,9 +6,11 @@ import TelegramApi extension TelegramMediaWebFile { convenience init(_ document: Api.WebDocument) { switch document { - case let .webDocument(url, accessHash, size, mimeType, attributes): + case let .webDocument(webDocumentData): + let (url, accessHash, size, mimeType, attributes) = (webDocumentData.url, webDocumentData.accessHash, webDocumentData.size, webDocumentData.mimeType, webDocumentData.attributes) self.init(resource: WebFileReferenceMediaResource(url: url, size: Int64(size), accessHash: accessHash), mimeType: mimeType, size: size, attributes: telegramMediaFileAttributesFromApiAttributes(attributes)) - case let .webDocumentNoProxy(url, size, mimeType, attributes): + case let .webDocumentNoProxy(webDocumentNoProxyData): + let (url, size, mimeType, attributes) = (webDocumentNoProxyData.url, webDocumentNoProxyData.size, webDocumentNoProxyData.mimeType, webDocumentNoProxyData.attributes) self.init(resource: HttpReferenceMediaResource(url: url, size: Int64(size)), mimeType: mimeType, size: size, attributes: telegramMediaFileAttributesFromApiAttributes(attributes)) } } diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaWebpage.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaWebpage.swift index 02bc8034..37327ac1 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaWebpage.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaWebpage.swift @@ -6,13 +6,15 @@ import TelegramApi func telegramMediaWebpageAttributeFromApiWebpageAttribute(_ attribute: Api.WebPageAttribute) -> TelegramMediaWebpageAttribute? { switch attribute { - case let .webPageAttributeTheme(_, documents, settings): + case let .webPageAttributeTheme(webPageAttributeThemeData): + let (_, documents, settings) = (webPageAttributeThemeData.flags, webPageAttributeThemeData.documents, webPageAttributeThemeData.settings) var files: [TelegramMediaFile] = [] if let documents = documents { files = documents.compactMap { telegramMediaFileFromApiDocument($0, altDocuments: []) } } return .theme(TelegraMediaWebpageThemeAttribute(files: files, settings: settings.flatMap { TelegramThemeSettings(apiThemeSettings: $0) })) - case let .webPageAttributeStickerSet(apiFlags, stickers): + case let .webPageAttributeStickerSet(webPageAttributeStickerSetData): + let (apiFlags, stickers) = (webPageAttributeStickerSetData.flags, webPageAttributeStickerSetData.stickers) var flags = TelegramMediaWebpageStickerPackAttribute.Flags() if (apiFlags & (1 << 0)) != 0 { flags.insert(.isEmoji) @@ -23,16 +25,19 @@ func telegramMediaWebpageAttributeFromApiWebpageAttribute(_ attribute: Api.WebPa var files: [TelegramMediaFile] = [] files = stickers.compactMap { telegramMediaFileFromApiDocument($0, altDocuments: []) } return .stickerPack(TelegramMediaWebpageStickerPackAttribute(flags: flags, files: files)) - case let .webPageAttributeUniqueStarGift(gift): + case let .webPageAttributeUniqueStarGift(webPageAttributeUniqueStarGiftData): + let gift = webPageAttributeUniqueStarGiftData.gift if let starGift = StarGift(apiStarGift: gift) { return .starGift(TelegramMediaWebpageStarGiftAttribute(gift: starGift)) } return nil - case let .webPageAttributeStarGiftCollection(icons): + case let .webPageAttributeStarGiftCollection(webPageAttributeStarGiftCollectionData): + let icons = webPageAttributeStarGiftCollectionData.icons var files: [TelegramMediaFile] = [] files = icons.compactMap { telegramMediaFileFromApiDocument($0, altDocuments: []) } return .giftCollection(TelegramMediaWebpageGiftCollectionAttribute(files: files)) - case let .webPageAttributeStarGiftAuction(apiGift, endDate): + case let .webPageAttributeStarGiftAuction(webPageAttributeStarGiftAuctionData): + let (apiGift, endDate) = (webPageAttributeStarGiftAuctionData.gift, webPageAttributeStarGiftAuctionData.endDate) guard let gift = StarGift(apiStarGift: apiGift) else { return nil } @@ -46,10 +51,12 @@ func telegramMediaWebpageFromApiWebpage(_ webpage: Api.WebPage) -> TelegramMedia switch webpage { case .webPageNotModified: return nil - case let .webPagePending(flags, id, url, date): + case let .webPagePending(webPagePendingData): + let (flags, id, url, date) = (webPagePendingData.flags, webPagePendingData.id, webPagePendingData.url, webPagePendingData.date) let _ = flags return TelegramMediaWebpage(webpageId: MediaId(namespace: Namespaces.Media.CloudWebpage, id: id), content: .Pending(date, url)) - case let .webPage(flags, id, url, displayUrl, hash, type, siteName, title, description, photo, embedUrl, embedType, embedWidth, embedHeight, duration, author, document, cachedPage, attributes): + case let .webPage(webPageData): + let (flags, id, url, displayUrl, hash, type, siteName, title, description, photo, embedUrl, embedType, embedWidth, embedHeight, duration, author, document, cachedPage, attributes) = (webPageData.flags, webPageData.id, webPageData.url, webPageData.displayUrl, webPageData.hash, webPageData.type, webPageData.siteName, webPageData.title, webPageData.description, webPageData.photo, webPageData.embedUrl, webPageData.embedType, webPageData.embedWidth, webPageData.embedHeight, webPageData.duration, webPageData.author, webPageData.document, webPageData.cachedPage, webPageData.attributes) var embedSize: PixelDimensions? if let embedWidth = embedWidth, let embedHeight = embedHeight { embedSize = PixelDimensions(width: embedWidth, height: embedHeight) @@ -71,20 +78,21 @@ func telegramMediaWebpageFromApiWebpage(_ webpage: Api.WebPage) -> TelegramMedia if let attributes = attributes { webpageAttributes = attributes.compactMap(telegramMediaWebpageAttributeFromApiWebpageAttribute) for attribute in attributes { - if case let .webPageAttributeStory(_, peerId, id, _) = attribute { + if case let .webPageAttributeStory(webPageAttributeStoryData) = attribute { + let (_, peerId, id, _) = (webPageAttributeStoryData.flags, webPageAttributeStoryData.peer, webPageAttributeStoryData.id, webPageAttributeStoryData.story) story = TelegramMediaStory(storyId: StoryId(peerId: peerId.peerId, id: id), isMention: false) } } } - + var instantPage: InstantPage? if let cachedPage = cachedPage { instantPage = InstantPage(apiPage: cachedPage) } - + let isMediaLargeByDefault = (flags & (1 << 13)) != 0 let imageIsVideoCover = (flags & (1 << 14)) != 0 - + return TelegramMediaWebpage(webpageId: MediaId(namespace: Namespaces.Media.CloudWebpage, id: id), content: .Loaded(TelegramMediaWebpageLoadedContent(url: url, displayUrl: displayUrl, hash: hash, type: type, websiteName: siteName, title: title, text: description, embedUrl: embedUrl, embedType: embedType, embedSize: embedSize, duration: webpageDuration, author: author, isMediaLargeByDefault: isMediaLargeByDefault, imageIsVideoCover: imageIsVideoCover, image: image, file: file, story: story, attributes: webpageAttributes, instantPage: instantPage))) case .webPageEmpty: return nil diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramPeerNotificationSettings.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramPeerNotificationSettings.swift index 32bec8e1..88ea1068 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramPeerNotificationSettings.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramPeerNotificationSettings.swift @@ -6,7 +6,8 @@ import TelegramApi extension TelegramPeerNotificationSettings { convenience init(apiSettings: Api.PeerNotifySettings) { switch apiSettings { - case let .peerNotifySettings(_, showPreviews, _, muteUntil, iosSound, _, desktopSound, storiesMuted, storiesHideSender, storiesIosSound, _, storiesDesktopSound): + case let .peerNotifySettings(peerNotifySettingsData): + let (showPreviews, muteUntil, iosSound, desktopSound, storiesMuted, storiesHideSender, storiesIosSound, storiesDesktopSound) = (peerNotifySettingsData.showPreviews, peerNotifySettingsData.muteUntil, peerNotifySettingsData.iosSound, peerNotifySettingsData.otherSound, peerNotifySettingsData.storiesMuted, peerNotifySettingsData.storiesHideSender, peerNotifySettingsData.storiesIosSound, peerNotifySettingsData.storiesOtherSound) let sound: Api.NotificationSound? let storiesSound: Api.NotificationSound? #if os(iOS) @@ -68,7 +69,8 @@ extension PeerMessageSound { self = .default case .notificationSoundNone: self = .none - case let .notificationSoundLocal(_, data): + case let .notificationSoundLocal(notificationSoundLocalData): + let (_, data) = (notificationSoundLocalData.title, notificationSoundLocalData.data) var rawApiSound = data if let index = rawApiSound.firstIndex(of: ".") { rawApiSound = String(rawApiSound[.. [TelegramMediaImageRepresentation] { var representations: [TelegramMediaImageRepresentation] = [] switch photo { - case let .userProfilePhoto(flags, id, strippedThumb, dcId): + case let .userProfilePhoto(userProfilePhotoData): + let (flags, id, strippedThumb, dcId) = (userProfilePhotoData.flags, userProfilePhotoData.photoId, userProfilePhotoData.strippedThumb, userProfilePhotoData.dcId) let hasVideo = (flags & (1 << 0)) != 0 let isPersonal = (flags & (1 << 2)) != 0 @@ -26,7 +27,8 @@ func parsedTelegramProfilePhoto(_ photo: Api.UserProfilePhoto) -> [TelegramMedia extension TelegramPeerUsername { init(apiUsername: Api.Username) { switch apiUsername { - case let .username(flags, username): + case let .username(usernameData): + let (flags, username) = (usernameData.flags, usernameData.username) self.init(flags: Flags(rawValue: flags), username: username) } } @@ -35,10 +37,11 @@ extension TelegramPeerUsername { extension PeerVerification { init(apiBotVerification: Api.BotVerification) { switch apiBotVerification { - case let .botVerification(botId, iconFileId, description): + case let .botVerification(botVerificationData): + let (botId, icon, description) = (botVerificationData.botId, botVerificationData.icon, botVerificationData.description) self.init( botId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(botId)), - iconFileId: iconFileId, + iconFileId: icon, description: description ) } @@ -49,7 +52,8 @@ extension PeerVerification { extension TelegramUser { convenience init(user: Api.User) { switch user { - case let .user(flags, flags2, id, accessHash, firstName, lastName, username, phone, photo, _, _, restrictionReason, botInlinePlaceholder, _, emojiStatus, usernames, _, color, profileColor, subscriberCount, verificationIconFileId, _): + case let .user(userData): + let (flags, flags2, id, accessHash, firstName, lastName, username, phone, photo, _, _, restrictionReason, botInlinePlaceholder, _, emojiStatus, usernames, _, color, profileColor, subscriberCount, verificationIconFileId, _) = (userData.flags, userData.flags2, userData.id, userData.accessHash, userData.firstName, userData.lastName, userData.username, userData.phone, userData.photo, userData.status, userData.botInfoVersion, userData.restrictionReason, userData.botInlinePlaceholder, userData.langCode, userData.emojiStatus, userData.usernames, userData.storiesMaxId, userData.color, userData.profileColor, userData.botActiveUsers, userData.botVerificationIcon, userData.sendPaidMessagesStars) let representations: [TelegramMediaImageRepresentation] = photo.flatMap(parsedTelegramProfilePhoto) ?? [] let isMin = (flags & (1 << 20)) != 0 @@ -121,6 +125,9 @@ extension TelegramUser { if (flags2 & (1 << 16)) != 0 { botFlags.insert(.hasForum) } + if (flags2 & (1 << 17)) != 0 { + botFlags.insert(.forumManagedByUser) + } botInfo = BotUserInfo(flags: botFlags, inlinePlaceholder: botInlinePlaceholder) } @@ -130,12 +137,14 @@ extension TelegramUser { var backgroundEmojiId: Int64? if let color = color { switch color { - case let .peerColor(_, color, backgroundEmojiIdValue): + case let .peerColor(peerColorData): + let (_, color, backgroundEmojiIdValue) = (peerColorData.flags, peerColorData.color, peerColorData.backgroundEmojiId) if let color { nameColor = .preset(PeerNameColor(rawValue: color)) } backgroundEmojiId = backgroundEmojiIdValue - case let .peerColorCollectible(_, collectibleId, giftEmojiId, backgroundEmojiIdValue, accentColor, colors, darkAccentColor, darkColors): + case let .peerColorCollectible(peerColorCollectibleData): + let (_, collectibleId, giftEmojiId, backgroundEmojiIdValue, accentColor, colors, darkAccentColor, darkColors) = (peerColorCollectibleData.flags, peerColorCollectibleData.collectibleId, peerColorCollectibleData.giftEmojiId, peerColorCollectibleData.backgroundEmojiId, peerColorCollectibleData.accentColor, peerColorCollectibleData.colors, peerColorCollectibleData.darkAccentColor, peerColorCollectibleData.darkColors) nameColor = .collectible(PeerCollectibleColor( collectibleId: collectibleId, giftEmojiFileId: giftEmojiId, @@ -150,12 +159,13 @@ extension TelegramUser { break } } - + var profileColorIndex: Int32? var profileBackgroundEmojiId: Int64? if let profileColor = profileColor { switch profileColor { - case let .peerColor(_, color, backgroundEmojiIdValue): + case let .peerColor(peerColorData): + let (_, color, backgroundEmojiIdValue) = (peerColorData.flags, peerColorData.color, peerColorData.backgroundEmojiId) profileColorIndex = color profileBackgroundEmojiId = backgroundEmojiIdValue default: @@ -164,14 +174,16 @@ extension TelegramUser { } self.init(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(id)), accessHash: accessHashValue, firstName: firstName, lastName: lastName, username: username, phone: phone, photo: representations, botInfo: botInfo, restrictionInfo: restrictionInfo, flags: userFlags, emojiStatus: emojiStatus.flatMap(PeerEmojiStatus.init(apiStatus:)), usernames: usernames?.map(TelegramPeerUsername.init(apiUsername:)) ?? [], storiesHidden: storiesHidden, nameColor: nameColor, backgroundEmojiId: backgroundEmojiId, profileColor: profileColorIndex.flatMap { PeerNameColor(rawValue: $0) }, profileBackgroundEmojiId: profileBackgroundEmojiId, subscriberCount: subscriberCount, verificationIconFileId: verificationIconFileId) - case let .userEmpty(id): + case let .userEmpty(userEmptyData): + let id = userEmptyData.id self.init(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(id)), accessHash: nil, firstName: nil, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: [], emojiStatus: nil, usernames: [], storiesHidden: nil, nameColor: nil, backgroundEmojiId: nil, profileColor: nil, profileBackgroundEmojiId: nil, subscriberCount: nil, verificationIconFileId: nil) } } static func merge(_ lhs: TelegramUser?, rhs: Api.User) -> TelegramUser? { switch rhs { - case let .user(flags, _, _, rhsAccessHash, _, _, _, _, photo, _, _, restrictionReason, botInlinePlaceholder, _, emojiStatus, _, _, color, profileColor, subscriberCount, _, _): + case let .user(userData): + let (flags, _, _, rhsAccessHash, _, _, _, _, photo, _, _, restrictionReason, botInlinePlaceholder, _, emojiStatus, _, _, color, profileColor, subscriberCount, _, _) = (userData.flags, userData.flags2, userData.id, userData.accessHash, userData.firstName, userData.lastName, userData.username, userData.phone, userData.photo, userData.status, userData.botInfoVersion, userData.restrictionReason, userData.botInlinePlaceholder, userData.langCode, userData.emojiStatus, userData.usernames, userData.storiesMaxId, userData.color, userData.profileColor, userData.botActiveUsers, userData.botVerificationIcon, userData.sendPaidMessagesStars) let isMin = (flags & (1 << 20)) != 0 if !isMin { return TelegramUser(user: rhs) @@ -256,12 +268,14 @@ extension TelegramUser { var backgroundEmojiId: Int64? if let color { switch color { - case let .peerColor(_, color, backgroundEmojiIdValue): + case let .peerColor(peerColorData): + let (_, color, backgroundEmojiIdValue) = (peerColorData.flags, peerColorData.color, peerColorData.backgroundEmojiId) if let color { nameColor = .preset(PeerNameColor(rawValue: color)) } backgroundEmojiId = backgroundEmojiIdValue - case let .peerColorCollectible(_, collectibleId, giftEmojiId, backgroundEmojiIdValue, accentColor, colors, darkAccentColor, darkColors): + case let .peerColorCollectible(peerColorCollectibleData): + let (_, collectibleId, giftEmojiId, backgroundEmojiIdValue, accentColor, colors, darkAccentColor, darkColors) = (peerColorCollectibleData.flags, peerColorCollectibleData.collectibleId, peerColorCollectibleData.giftEmojiId, peerColorCollectibleData.backgroundEmojiId, peerColorCollectibleData.accentColor, peerColorCollectibleData.colors, peerColorCollectibleData.darkAccentColor, peerColorCollectibleData.darkColors) nameColor = .collectible(PeerCollectibleColor( collectibleId: collectibleId, giftEmojiFileId: giftEmojiId, @@ -276,12 +290,13 @@ extension TelegramUser { break } } - + var profileColorIndex: Int32? var profileBackgroundEmojiId: Int64? if let profileColor = profileColor { switch profileColor { - case let .peerColor(_, color, backgroundEmojiIdValue): + case let .peerColor(peerColorData): + let (_, color, backgroundEmojiIdValue) = (peerColorData.flags, peerColorData.color, peerColorData.backgroundEmojiId) profileColorIndex = color profileBackgroundEmojiId = backgroundEmojiIdValue default: diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramUserPresence.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramUserPresence.swift index cb099f4b..a0599f1b 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramUserPresence.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramUserPresence.swift @@ -8,17 +8,22 @@ extension TelegramUserPresence { switch apiStatus { case .userStatusEmpty: self.init(status: .none, lastActivity: 0) - case let .userStatusOnline(expires): + case let .userStatusOnline(userStatusOnlineData): + let (expires) = (userStatusOnlineData.expires) self.init(status: .present(until: expires), lastActivity: 0) - case let .userStatusOffline(wasOnline): + case let .userStatusOffline(userStatusOfflineData): + let (wasOnline) = (userStatusOfflineData.wasOnline) self.init(status: .present(until: wasOnline), lastActivity: 0) - case let .userStatusRecently(flags): + case let .userStatusRecently(userStatusRecentlyData): + let (flags) = (userStatusRecentlyData.flags) let isHidden = (flags & (1 << 0)) != 0 self.init(status: .recently(isHidden: isHidden), lastActivity: 0) - case let .userStatusLastWeek(flags): + case let .userStatusLastWeek(userStatusLastWeekData): + let (flags) = (userStatusLastWeekData.flags) let isHidden = (flags & (1 << 0)) != 0 self.init(status: .lastWeek(isHidden: isHidden), lastActivity: 0) - case let .userStatusLastMonth(flags): + case let .userStatusLastMonth(userStatusLastMonthData): + let (flags) = (userStatusLastMonthData.flags) let isHidden = (flags & (1 << 0)) != 0 self.init(status: .lastMonth(isHidden: isHidden), lastActivity: 0) } @@ -26,7 +31,8 @@ extension TelegramUserPresence { convenience init?(apiUser: Api.User) { switch apiUser { - case let .user(_, _, _, _, _, _, _, _, _, status, _, _, _, _, _, _, _, _, _, _, _, _): + case let .user(userData): + let status = userData.status if let status = status { self.init(apiStatus: status) } else { diff --git a/submodules/TelegramCore/Sources/ApiUtils/TextEntitiesMessageAttribute.swift b/submodules/TelegramCore/Sources/ApiUtils/TextEntitiesMessageAttribute.swift index b2ce7048..11ed9a64 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TextEntitiesMessageAttribute.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TextEntitiesMessageAttribute.swift @@ -13,47 +13,47 @@ func apiEntitiesFromMessageTextEntities(_ entities: [MessageTextEntity], associa case .Unknown: break case .Mention: - apiEntities.append(.messageEntityMention(offset: offset, length: length)) + apiEntities.append(.messageEntityMention(.init(offset: offset, length: length))) case .Hashtag: - apiEntities.append(.messageEntityHashtag(offset: offset, length: length)) + apiEntities.append(.messageEntityHashtag(.init(offset: offset, length: length))) case .BotCommand: - apiEntities.append(.messageEntityBotCommand(offset: offset, length: length)) + apiEntities.append(.messageEntityBotCommand(.init(offset: offset, length: length))) case .Url: - apiEntities.append(.messageEntityUrl(offset: offset, length: length)) + apiEntities.append(.messageEntityUrl(.init(offset: offset, length: length))) case .Email: - apiEntities.append(.messageEntityEmail(offset: offset, length: length)) + apiEntities.append(.messageEntityEmail(.init(offset: offset, length: length))) case .Bold: - apiEntities.append(.messageEntityBold(offset: offset, length: length)) + apiEntities.append(.messageEntityBold(.init(offset: offset, length: length))) case .Italic: - apiEntities.append(.messageEntityItalic(offset: offset, length: length)) + apiEntities.append(.messageEntityItalic(.init(offset: offset, length: length))) case .Code: - apiEntities.append(.messageEntityCode(offset: offset, length: length)) + apiEntities.append(.messageEntityCode(.init(offset: offset, length: length))) case let .Pre(language): - apiEntities.append(.messageEntityPre(offset: offset, length: length, language: language ?? "")) + apiEntities.append(.messageEntityPre(.init(offset: offset, length: length, language: language ?? ""))) case let .TextUrl(url): - apiEntities.append(.messageEntityTextUrl(offset: offset, length: length, url: url)) + apiEntities.append(.messageEntityTextUrl(.init(offset: offset, length: length, url: url))) case let .TextMention(peerId): if let peer = associatedPeers[peerId], let inputUser = apiInputUser(peer) { - apiEntities.append(.inputMessageEntityMentionName(offset: offset, length: length, userId: inputUser)) + apiEntities.append(.inputMessageEntityMentionName(.init(offset: offset, length: length, userId: inputUser))) } case .PhoneNumber: break case .Strikethrough: - apiEntities.append(.messageEntityStrike(offset: offset, length: length)) + apiEntities.append(.messageEntityStrike(.init(offset: offset, length: length))) case let .BlockQuote(isCollapsed): var flags: Int32 = 0 if isCollapsed { flags |= 1 << 0 } - apiEntities.append(.messageEntityBlockquote(flags: flags, offset: offset, length: length)) + apiEntities.append(.messageEntityBlockquote(.init(flags: flags, offset: offset, length: length))) case .Underline: - apiEntities.append(.messageEntityUnderline(offset: offset, length: length)) + apiEntities.append(.messageEntityUnderline(.init(offset: offset, length: length))) case .BankCard: - apiEntities.append(.messageEntityBankCard(offset: offset, length: length)) + apiEntities.append(.messageEntityBankCard(.init(offset: offset, length: length))) case .Spoiler: - apiEntities.append(.messageEntitySpoiler(offset: offset, length: length)) + apiEntities.append(.messageEntitySpoiler(.init(offset: offset, length: length))) case let .CustomEmoji(_, fileId): - apiEntities.append(.messageEntityCustomEmoji(offset: offset, length: length, documentId: fileId)) + apiEntities.append(.messageEntityCustomEmoji(.init(offset: offset, length: length, documentId: fileId))) case .Custom: break } diff --git a/submodules/TelegramCore/Sources/ApiUtils/Theme.swift b/submodules/TelegramCore/Sources/ApiUtils/Theme.swift index 01feb7b6..698873d4 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/Theme.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/Theme.swift @@ -7,7 +7,8 @@ import TelegramApi extension TelegramTheme { convenience init(apiTheme: Api.Theme) { switch apiTheme { - case let .theme(flags, id, accessHash, slug, title, document, settings, emoticon, installCount): + case let .theme(themeData): + let (flags, id, accessHash, slug, title, document, settings, emoticon, installCount) = (themeData.flags, themeData.id, themeData.accessHash, themeData.slug, themeData.title, themeData.document, themeData.settings, themeData.emoticon, themeData.installsCount) self.init(id: id, accessHash: accessHash, slug: slug, emoticon: emoticon, title: title, file: document.flatMap { telegramMediaFileFromApiDocument($0, altDocuments: []) }, settings: settings?.compactMap(TelegramThemeSettings.init(apiThemeSettings:)), isCreator: (flags & 1 << 0) != 0, isDefault: (flags & 1 << 1) != 0, installCount: installCount) } } @@ -46,7 +47,8 @@ extension TelegramBaseTheme { extension TelegramThemeSettings { convenience init?(apiThemeSettings: Api.ThemeSettings) { switch apiThemeSettings { - case let .themeSettings(flags, baseTheme, accentColor, outboxAccentColor, messageColors, wallpaper): + case let .themeSettings(themeSettingsData): + let (flags, baseTheme, accentColor, outboxAccentColor, messageColors, wallpaper) = (themeSettingsData.flags, themeSettingsData.baseTheme, themeSettingsData.accentColor, themeSettingsData.outboxAccentColor, themeSettingsData.messageColors, themeSettingsData.wallpaper) self.init(baseTheme: TelegramBaseTheme(apiBaseTheme: baseTheme), accentColor: UInt32(bitPattern: accentColor), outgoingAccentColor: outboxAccentColor.flatMap { UInt32(bitPattern: $0) }, messageColors: messageColors?.map(UInt32.init(bitPattern:)) ?? [], animateMessageColors: (flags & 1 << 2) != 0, wallpaper: wallpaper.flatMap(TelegramWallpaper.init(apiWallpaper:))) } } @@ -73,6 +75,6 @@ extension TelegramThemeSettings { flags |= 1 << 1 } - return .inputThemeSettings(flags: flags, baseTheme: self.baseTheme.apiBaseTheme, accentColor: Int32(bitPattern: self.accentColor), outboxAccentColor: self.outgoingAccentColor.flatMap { Int32(bitPattern: $0) }, messageColors: self.messageColors.isEmpty ? nil : self.messageColors.map(Int32.init(bitPattern:)), wallpaper: inputWallpaper, wallpaperSettings: inputWallpaperSettings) + return .inputThemeSettings(.init(flags: flags, baseTheme: self.baseTheme.apiBaseTheme, accentColor: Int32(bitPattern: self.accentColor), outboxAccentColor: self.outgoingAccentColor.flatMap { Int32(bitPattern: $0) }, messageColors: self.messageColors.isEmpty ? nil : self.messageColors.map(Int32.init(bitPattern:)), wallpaper: inputWallpaper, wallpaperSettings: inputWallpaperSettings)) } } diff --git a/submodules/TelegramCore/Sources/ApiUtils/Wallpaper.swift b/submodules/TelegramCore/Sources/ApiUtils/Wallpaper.swift index a7eebe38..44c69296 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/Wallpaper.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/Wallpaper.swift @@ -7,7 +7,8 @@ import TelegramApi extension WallpaperSettings { init(apiWallpaperSettings: Api.WallPaperSettings) { switch apiWallpaperSettings { - case let .wallPaperSettings(flags, backgroundColor, secondBackgroundColor, thirdBackgroundColor, fourthBackgroundColor, intensity, rotation, emoticon): + case let .wallPaperSettings(wallPaperSettingsData): + let (flags, backgroundColor, secondBackgroundColor, thirdBackgroundColor, fourthBackgroundColor, intensity, rotation, emoticon) = (wallPaperSettingsData.flags, wallPaperSettingsData.backgroundColor, wallPaperSettingsData.secondBackgroundColor, wallPaperSettingsData.thirdBackgroundColor, wallPaperSettingsData.fourthBackgroundColor, wallPaperSettingsData.intensity, wallPaperSettingsData.rotation, wallPaperSettingsData.emoticon) var colors: [UInt32] = [] if let backgroundColor = backgroundColor { colors.append(UInt32(bitPattern: backgroundColor)) @@ -60,13 +61,14 @@ func apiWallpaperSettings(_ wallpaperSettings: WallpaperSettings) -> Api.WallPap flags |= (1 << 6) fourthBackgroundColor = Int32(bitPattern: wallpaperSettings.colors[3]) } - return .wallPaperSettings(flags: flags, backgroundColor: backgroundColor, secondBackgroundColor: secondBackgroundColor, thirdBackgroundColor: thirdBackgroundColor, fourthBackgroundColor: fourthBackgroundColor, intensity: wallpaperSettings.intensity, rotation: wallpaperSettings.rotation ?? 0, emoticon: wallpaperSettings.emoticon) + return .wallPaperSettings(.init(flags: flags, backgroundColor: backgroundColor, secondBackgroundColor: secondBackgroundColor, thirdBackgroundColor: thirdBackgroundColor, fourthBackgroundColor: fourthBackgroundColor, intensity: wallpaperSettings.intensity, rotation: wallpaperSettings.rotation ?? 0, emoticon: wallpaperSettings.emoticon)) } extension TelegramWallpaper { init(apiWallpaper: Api.WallPaper) { switch apiWallpaper { - case let .wallPaper(id, flags, accessHash, slug, document, settings): + case let .wallPaper(wallPaperData): + let (id, flags, accessHash, slug, document, settings) = (wallPaperData.id, wallPaperData.flags, wallPaperData.accessHash, wallPaperData.slug, wallPaperData.document, wallPaperData.settings) if let file = telegramMediaFileFromApiDocument(document, altDocuments: []) { let wallpaperSettings: WallpaperSettings if let settings = settings { @@ -79,8 +81,10 @@ extension TelegramWallpaper { //assertionFailure() self = .color(0xffffff) } - case let .wallPaperNoFile(id, _, settings): - if let settings = settings, case let .wallPaperSettings(_, backgroundColor, secondBackgroundColor, thirdBackgroundColor, fourthBackgroundColor, _, rotation, emoticon) = settings { + case let .wallPaperNoFile(wallPaperNoFileData): + let (id, _, settings) = (wallPaperNoFileData.id, wallPaperNoFileData.flags, wallPaperNoFileData.settings) + if let settings = settings, case let .wallPaperSettings(wallPaperSettingsData) = settings { + let (_, backgroundColor, secondBackgroundColor, thirdBackgroundColor, fourthBackgroundColor, _, rotation, emoticon) = (wallPaperSettingsData.flags, wallPaperSettingsData.backgroundColor, wallPaperSettingsData.secondBackgroundColor, wallPaperSettingsData.thirdBackgroundColor, wallPaperSettingsData.fourthBackgroundColor, wallPaperSettingsData.intensity, wallPaperSettingsData.rotation, wallPaperSettingsData.emoticon) if id == 0, let emoticon = emoticon { self = .emoticon(emoticon) return @@ -107,13 +111,13 @@ extension TelegramWallpaper { case .builtin: return nil case let .file(file): - return (.inputWallPaperSlug(slug: file.slug), apiWallpaperSettings(file.settings)) + return (.inputWallPaperSlug(.init(slug: file.slug)), apiWallpaperSettings(file.settings)) case let .color(color): - return (.inputWallPaperNoFile(id: 0), apiWallpaperSettings(WallpaperSettings(colors: [color]))) + return (.inputWallPaperNoFile(.init(id: 0)), apiWallpaperSettings(WallpaperSettings(colors: [color]))) case let .gradient(gradient): - return (.inputWallPaperNoFile(id: gradient.id ?? 0), apiWallpaperSettings(WallpaperSettings(colors: gradient.colors, rotation: gradient.settings.rotation))) + return (.inputWallPaperNoFile(.init(id: gradient.id ?? 0)), apiWallpaperSettings(WallpaperSettings(colors: gradient.colors, rotation: gradient.settings.rotation))) case let .emoticon(emoticon): - return (.inputWallPaperNoFile(id: 0), apiWallpaperSettings(WallpaperSettings(emoticon: emoticon))) + return (.inputWallPaperNoFile(.init(id: 0)), apiWallpaperSettings(WallpaperSettings(emoticon: emoticon))) default: return nil } diff --git a/submodules/TelegramCore/Sources/Authorization.swift b/submodules/TelegramCore/Sources/Authorization.swift index db7ce4dd..b3703ada 100644 --- a/submodules/TelegramCore/Sources/Authorization.swift +++ b/submodules/TelegramCore/Sources/Authorization.swift @@ -185,7 +185,7 @@ public func sendAuthorizationCode(accountManager: AccountManager mapToSignal { result -> Signal<(SendCodeResult, UnauthorizedAccount), MTRpcError> in switch result { - case let .password(_, _, _, _, hint, _, _, _, _, _, _): + case let .password(passwordData): + let hint = passwordData.hint return .single((.password(hint: hint), updatedAccount)) } } @@ -248,7 +249,8 @@ public func sendAuthorizationCode(accountManager: AccountManager mapToSignal { result -> Signal<(SendCodeResult, UnauthorizedAccount), AuthorizationCodeRequestError> in switch result { - case let .password(_, _, _, _, hint, _, _, _, _, _, _): + case let .password(passwordData): + let hint = passwordData.hint return .single((.password(hint: hint), account)) } } @@ -267,14 +269,16 @@ public func sendAuthorizationCode(accountManager: AccountManager map { mapping -> String? in guard let receipt = receipt else { @@ -358,14 +362,16 @@ public func sendAuthorizationCode(accountManager: AccountManager mapToSignal { sentCode -> Signal in return account.postbox.transaction { transaction -> Signal 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) let parsedType = SentAuthorizationCodeType(apiType: type) 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 { @@ -518,7 +526,8 @@ private func internalResendAuthorizationCode(accountManager: AccountManager mapToSignal { sentCode -> Signal in return account.postbox.transaction { transaction -> Signal in switch sentCode { - case let .sentCode(_, newType, phoneCodeHash, nextType, codeTimeout): + case let .sentCode(sentCodeData): + let (newType, phoneCodeHash, nextType, codeTimeout) = (sentCodeData.type, sentCodeData.phoneCodeHash, sentCodeData.nextType, sentCodeData.timeout) let parsedType = SentAuthorizationCodeType(apiType: newType) var previousCodeEntry: UnauthorizedAccountStateContents? if let previousCodeEntryValue { @@ -579,7 +589,8 @@ public func resendAuthorizationCode(accountManager: AccountManager map { mapping -> String? in guard let receipt = receipt else { @@ -626,7 +637,8 @@ public func resendAuthorizationCode(accountManager: AccountManager Signal< } |> map { result -> ChangeLoginEmailData in switch result { - case let .sentEmailCode(_, length): + case let .sentEmailCode(sentEmailCodeData): + let length = sentEmailCodeData.length return ChangeLoginEmailData(email: email, length: length) } } @@ -787,7 +800,7 @@ public func sendLoginEmailCode(account: UnauthorizedAccount, email: String) -> S if let state = transaction.getState() as? UnauthorizedAccountState { switch state.contents { case let .confirmationCodeEntry(phoneNumber, _, phoneCodeHash, _, _, syncContacts, _, _): - return account.network.request(Api.functions.account.sendVerifyEmailCode(purpose: .emailVerifyPurposeLoginSetup(phoneNumber: phoneNumber, phoneCodeHash: phoneCodeHash), email: email), automaticFloodWait: false) + return account.network.request(Api.functions.account.sendVerifyEmailCode(purpose: .emailVerifyPurposeLoginSetup(.init(phoneNumber: phoneNumber, phoneCodeHash: phoneCodeHash)), email: email), automaticFloodWait: false) |> `catch` { error -> Signal in let errorDescription = error.errorDescription ?? "" if errorDescription.hasPrefix("FLOOD_WAIT") { @@ -805,7 +818,8 @@ public func sendLoginEmailCode(account: UnauthorizedAccount, email: String) -> S |> mapToSignal { result -> Signal in return account.postbox.transaction { transaction -> Signal in switch result { - case let .sentEmailCode(emailPattern, length): + case let .sentEmailCode(sentEmailCodeData): + let (emailPattern, length) = (sentEmailCodeData.emailPattern, sentEmailCodeData.length) transaction.setState(UnauthorizedAccountState(isTestingEnvironment: account.testingEnvironment, masterDatacenterId: account.masterDatacenterId, contents: .confirmationCodeEntry(number: phoneNumber, type: .email(emailPattern: emailPattern, length: length, resetAvailablePeriod: nil, resetPendingDate: nil, appleSignInAllowed: false, setup: true), hash: phoneCodeHash, timeout: nil, nextType: nil, syncContacts: syncContacts, previousCodeEntry: nil, usePrevious: false))) } return .complete() @@ -832,11 +846,11 @@ public func verifyLoginEmailChange(account: Account, code: AuthorizationCode.Ema let verification: Api.EmailVerification switch code { case let .emailCode(code): - verification = .emailVerificationCode(code: code) + verification = .emailVerificationCode(.init(code: code)) case let .appleToken(token): - verification = .emailVerificationApple(token: token) + verification = .emailVerificationApple(.init(token: token)) case let .googleToken(token): - verification = .emailVerificationGoogle(token: token) + verification = .emailVerificationGoogle(.init(token: token)) } return account.network.request(Api.functions.account.verifyEmail(purpose: .emailVerifyPurposeLoginChange, verification: verification), automaticFloodWait: false) @@ -869,14 +883,14 @@ public func verifyLoginEmailSetup(account: UnauthorizedAccount, code: Authorizat let verification: Api.EmailVerification switch code { case let .emailCode(code): - verification = .emailVerificationCode(code: code) + verification = .emailVerificationCode(.init(code: code)) case let .appleToken(token): - verification = .emailVerificationApple(token: token) + verification = .emailVerificationApple(.init(token: token)) case let .googleToken(token): - verification = .emailVerificationGoogle(token: token) + verification = .emailVerificationGoogle(.init(token: token)) } - return account.network.request(Api.functions.account.verifyEmail(purpose: .emailVerifyPurposeLoginSetup(phoneNumber: phoneNumber, phoneCodeHash: phoneCodeHash), verification: verification), automaticFloodWait: false) + return account.network.request(Api.functions.account.verifyEmail(purpose: .emailVerifyPurposeLoginSetup(.init(phoneNumber: phoneNumber, phoneCodeHash: phoneCodeHash)), verification: verification), automaticFloodWait: false) |> `catch` { error -> Signal in let errorDescription = error.errorDescription ?? "" if errorDescription.hasPrefix("FLOOD_WAIT") { @@ -896,16 +910,19 @@ public func verifyLoginEmailSetup(account: UnauthorizedAccount, code: Authorizat |> mapToSignal { result -> Signal in return account.postbox.transaction { transaction -> Signal in switch result { - case let .emailVerifiedLogin(_, sentCode): + case let .emailVerifiedLogin(emailVerifiedLoginData): + let sentCode = emailVerifiedLoginData.sentCode 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) } - + transaction.setState(UnauthorizedAccountState(isTestingEnvironment: account.testingEnvironment, masterDatacenterId: account.masterDatacenterId, contents: .confirmationCodeEntry(number: phoneNumber, type: SentAuthorizationCodeType(apiType: type), hash: phoneCodeHash, timeout: timeout, nextType: parsedNextType, syncContacts: syncContacts, previousCodeEntry: nil, usePrevious: false))) - case let .sentCodePaymentRequired(storeProduct, codeHash, supportEmailAddress, supportEmailSubject, _, _): + case let .sentCodePaymentRequired(sentCodePaymentRequiredData): + let (storeProduct, codeHash, supportEmailAddress, supportEmailSubject) = (sentCodePaymentRequiredData.storeProduct, sentCodePaymentRequiredData.phoneCodeHash, sentCodePaymentRequiredData.supportEmailAddress, sentCodePaymentRequiredData.supportEmailSubject) transaction.setState(UnauthorizedAccountState(isTestingEnvironment: account.testingEnvironment, masterDatacenterId: account.masterDatacenterId, contents: .payment(number: phoneNumber, codeHash: codeHash, storeProduct: storeProduct, supportEmailAddress: supportEmailAddress, supportEmailSubject: supportEmailSubject, syncContacts: syncContacts))) case .sentCodeSuccess: break @@ -961,16 +978,18 @@ public func resetLoginEmail(account: UnauthorizedAccount, phoneNumber: String, p |> mapToSignal { sentCode -> Signal in return account.postbox.transaction { transaction -> Signal 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) } - + transaction.setState(UnauthorizedAccountState(isTestingEnvironment: account.testingEnvironment, masterDatacenterId: account.masterDatacenterId, contents: .confirmationCodeEntry(number: phoneNumber, type: SentAuthorizationCodeType(apiType: type), hash: phoneCodeHash, timeout: codeTimeout, nextType: parsedNextType, syncContacts: syncContacts, previousCodeEntry: nil, usePrevious: false))) - + return .complete() - case let .sentCodePaymentRequired(storeProduct, codeHash, supportEmailAddress, supportEmailSubject, _, _): + case let .sentCodePaymentRequired(sentCodePaymentRequiredData): + let (storeProduct, codeHash, supportEmailAddress, supportEmailSubject) = (sentCodePaymentRequiredData.storeProduct, sentCodePaymentRequiredData.phoneCodeHash, sentCodePaymentRequiredData.supportEmailAddress, sentCodePaymentRequiredData.supportEmailSubject) transaction.setState(UnauthorizedAccountState(isTestingEnvironment: account.testingEnvironment, masterDatacenterId: account.masterDatacenterId, contents: .payment(number: phoneNumber, codeHash: codeHash, storeProduct: storeProduct, supportEmailAddress: supportEmailAddress, supportEmailSubject: supportEmailSubject, syncContacts: syncContacts))) return .complete() case .sentCodeSuccess: @@ -1012,11 +1031,11 @@ public func authorizeWithCode(accountManager: AccountManager mapToSignal { result -> Signal in switch result { - case let .password(_, _, _, _, hint, _, _, _, _, _, _): + case let .password(passwordData): + let hint = passwordData.hint return .single(.password(hint: hint ?? "")) } } @@ -1067,14 +1087,15 @@ public func authorizeWithCode(accountManager: AccountManager mapToSignal { result -> Signal in return account.postbox.transaction { transaction -> Signal in switch result { - 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()) } - - 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: []) /*transaction.updatePeersInternal([user], update: { current, peer -> Peer? in return peer @@ -1215,7 +1238,7 @@ public func authorizeWithPasskey(accountManager: AccountManager map { authorization in return .authorization(authorization) } @@ -1232,7 +1255,8 @@ public func authorizeWithPasskey(accountManager: AccountManager mapToSignal { result -> Signal in switch result { - case let .password(_, _, _, _, hint, _, _, _, _, _, _): + case let .password(passwordData): + let hint = passwordData.hint return .single(.password(hint: hint ?? "")) } } @@ -1262,14 +1286,15 @@ public func authorizeWithPasskey(accountManager: AccountManager, account: UnauthorizedAccount, recoveredAccountData: RecoveredAccountData, syncContacts: Bool) -> Signal { return account.postbox.transaction { transaction -> Signal in switch recoveredAccountData.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()) } - - let user = TelegramUser(user: user) + + let user = TelegramUser(user: apiUser) var isSupportUser = false if let phone = user.phone, phone.hasPrefix("42") { isSupportUser = true @@ -1385,7 +1411,7 @@ func _internal_performPasswordRecovery(network: Network, code: String, updatedPa return .fail(.invalidCode) } - newSettings = Api.account.PasswordInputSettings.passwordInputSettings(flags: flags, newAlgo: updatedPasswordDerivation.apiAlgo, newPasswordHash: Buffer(data: updatedPasswordHash), hint: hint, email: email, newSecureSettings: nil) + newSettings = Api.account.PasswordInputSettings.passwordInputSettings(.init(flags: flags, newAlgo: updatedPasswordDerivation.apiAlgo, newPasswordHash: Buffer(data: updatedPasswordHash), hint: hint, email: email, newSecureSettings: nil)) } var flags: Int32 = 0 @@ -1496,12 +1522,13 @@ public func signUpWithName(accountManager: AccountManager mapToSignal { result -> Signal in switch result { - case let .authorization(_, otherwiseReloginDays, _, futureAuthToken, user): + case let .authorization(authorizationData): + let (otherwiseReloginDays, futureAuthToken, apiUser) = (authorizationData.otherwiseReloginDays, authorizationData.futureAuthToken, authorizationData.user) if let futureAuthToken = futureAuthToken { storeFutureLoginToken(accountManager: accountManager, token: futureAuthToken.makeData()) } - - let user = TelegramUser(user: user) + + let user = TelegramUser(user: apiUser) var isSupportUser = false if let phone = user.phone, phone.hasPrefix("42") { isSupportUser = true @@ -1518,7 +1545,7 @@ public func signUpWithName(accountManager: AccountManager castError(SignUpError.self) - + let switchedAccounts = accountManager.transaction { transaction -> Void in switchToAuthorizedAccount(transaction: transaction, account: account, isSupportUser: isSupportUser) } diff --git a/submodules/TelegramCore/Sources/DeviceSpoof/DeviceSpoofBridge.m b/submodules/TelegramCore/Sources/DeviceSpoof/DeviceSpoofBridge.m index 981ec412..841d231b 100644 --- a/submodules/TelegramCore/Sources/DeviceSpoof/DeviceSpoofBridge.m +++ b/submodules/TelegramCore/Sources/DeviceSpoof/DeviceSpoofBridge.m @@ -5,6 +5,8 @@ // to avoid Swift/ObjC bridging complexities in MtProtoKit static NSString *const kDeviceSpoofIsEnabled = @"DeviceSpoof.isEnabled"; +static NSString *const kDeviceSpoofHasExplicitConfiguration = + @"DeviceSpoof.hasExplicitConfiguration"; static NSString *const kDeviceSpoofSelectedProfileId = @"DeviceSpoof.selectedProfileId"; static NSString *const kDeviceSpoofCustomDeviceModel = @@ -12,89 +14,132 @@ static NSString *const kDeviceSpoofCustomDeviceModel = static NSString *const kDeviceSpoofCustomSystemVersion = @"DeviceSpoof.customSystemVersion"; +static NSDictionary *> * +DeviceSpoofProfiles(void) { + static NSDictionary *> + *profiles; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + profiles = @{ + @1 : @{ + @"deviceModel" : @"iPhone 14 Pro", + @"systemVersion" : @"iOS 17.2" + }, + @2 : @{ + @"deviceModel" : @"iPhone 15 Pro Max", + @"systemVersion" : @"iOS 17.4" + }, + @3 : @{ + @"deviceModel" : @"Samsung SM-S918B", + @"systemVersion" : @"Android 14" + }, + @4 : @{ + @"deviceModel" : @"Google Pixel 8 Pro", + @"systemVersion" : @"Android 14" + }, + @5 : @{ + @"deviceModel" : @"PC 64bit", + @"systemVersion" : @"Windows 11" + }, + @6 : @{ + @"deviceModel" : @"MacBook Pro", + @"systemVersion" : @"macOS 14.3" + }, + @7 : @{ + @"deviceModel" : @"Web", + @"systemVersion" : @"Chrome 121" + }, + @8 : @{ + @"deviceModel" : @"HUAWEI MNA-LX9", + @"systemVersion" : @"HarmonyOS 4.0" + }, + @9 : @{ + @"deviceModel" : @"Xiaomi 2311DRK48G", + @"systemVersion" : @"Android 14" + } + }; + }); + return profiles; +} + +static NSString *DeviceSpoofTrimmedString(NSString *value) { + if (value == nil) { + return @""; + } + return + [value stringByTrimmingCharactersInSet: + [NSCharacterSet whitespaceAndNewlineCharacterSet]]; +} + +static NSInteger DeviceSpoofSanitizedProfileId(NSUserDefaults *defaults) { + NSInteger profileId = + [defaults integerForKey:kDeviceSpoofSelectedProfileId]; + if (profileId == 0 || profileId == 100 || + DeviceSpoofProfiles()[@(profileId)] != nil) { + return profileId; + } + [defaults setInteger:0 forKey:kDeviceSpoofSelectedProfileId]; + return 0; +} + +static BOOL DeviceSpoofIsEnabled(NSUserDefaults *defaults) { + return [defaults boolForKey:kDeviceSpoofHasExplicitConfiguration] && + [defaults boolForKey:kDeviceSpoofIsEnabled]; +} + +static void DeviceSpoofResolveValues(NSUserDefaults *defaults, + NSString *__autoreleasing *deviceModel, + NSString *__autoreleasing *systemVersion) { + *deviceModel = nil; + *systemVersion = nil; + + if (!DeviceSpoofIsEnabled(defaults)) { + return; + } + + NSInteger profileId = DeviceSpoofSanitizedProfileId(defaults); + if (profileId == 0) { + return; + } + + if (profileId == 100) { + NSString *customDeviceModel = + DeviceSpoofTrimmedString([defaults stringForKey:kDeviceSpoofCustomDeviceModel]); + NSString *customSystemVersion = + DeviceSpoofTrimmedString([defaults stringForKey:kDeviceSpoofCustomSystemVersion]); + if (customDeviceModel.length == 0 || customSystemVersion.length == 0) { + return; + } + *deviceModel = customDeviceModel; + *systemVersion = customSystemVersion; + return; + } + + NSDictionary *profile = DeviceSpoofProfiles()[@(profileId)]; + *deviceModel = profile[@"deviceModel"]; + *systemVersion = profile[@"systemVersion"]; +} + @implementation DeviceSpoofBridge + (BOOL)isEnabled { - return - [[NSUserDefaults standardUserDefaults] boolForKey:kDeviceSpoofIsEnabled]; + return DeviceSpoofIsEnabled([NSUserDefaults standardUserDefaults]); } + (NSString *)spoofedDeviceModel { - if (![self isEnabled]) { - return nil; - } - - NSInteger profileId = [[NSUserDefaults standardUserDefaults] - integerForKey:kDeviceSpoofSelectedProfileId]; - - // Profile ID 0 = real device - if (profileId == 0) { - return nil; - } - - // Profile ID 100 = custom - if (profileId == 100) { - NSString *custom = [[NSUserDefaults standardUserDefaults] - stringForKey:kDeviceSpoofCustomDeviceModel]; - if (custom.length > 0) { - return custom; - } - return nil; - } - - // Preset profiles - NSDictionary *profiles = @{ - @1 : @"iPhone 14 Pro", - @2 : @"iPhone 15 Pro Max", - @3 : @"Samsung SM-S918B", - @4 : @"Google Pixel 8 Pro", - @5 : @"PC 64bit", - @6 : @"MacBook Pro", - @7 : @"Web", - @8 : @"HUAWEI MNA-LX9", - @9 : @"Xiaomi 2311DRK48G" - }; - - return profiles[@(profileId)]; + NSString *deviceModel = nil; + NSString *systemVersion = nil; + DeviceSpoofResolveValues([NSUserDefaults standardUserDefaults], &deviceModel, + &systemVersion); + return deviceModel; } + (NSString *)spoofedSystemVersion { - if (![self isEnabled]) { - return nil; - } - - NSInteger profileId = [[NSUserDefaults standardUserDefaults] - integerForKey:kDeviceSpoofSelectedProfileId]; - - // Profile ID 0 = real device - if (profileId == 0) { - return nil; - } - - // Profile ID 100 = custom - if (profileId == 100) { - NSString *custom = [[NSUserDefaults standardUserDefaults] - stringForKey:kDeviceSpoofCustomSystemVersion]; - if (custom.length > 0) { - return custom; - } - return nil; - } - - // Preset profiles - NSDictionary *versions = @{ - @1 : @"iOS 17.2", - @2 : @"iOS 17.4", - @3 : @"Android 14", - @4 : @"Android 14", - @5 : @"Windows 11", - @6 : @"macOS 14.3", - @7 : @"Chrome 121", - @8 : @"HarmonyOS 4.0", - @9 : @"Android 14" - }; - - return versions[@(profileId)]; + NSString *deviceModel = nil; + NSString *systemVersion = nil; + DeviceSpoofResolveValues([NSUserDefaults standardUserDefaults], &deviceModel, + &systemVersion); + return systemVersion; } @end diff --git a/submodules/TelegramCore/Sources/DeviceSpoof/DeviceSpoofManager.swift b/submodules/TelegramCore/Sources/DeviceSpoof/DeviceSpoofManager.swift index 73d8d5ff..f4839745 100644 --- a/submodules/TelegramCore/Sources/DeviceSpoof/DeviceSpoofManager.swift +++ b/submodules/TelegramCore/Sources/DeviceSpoof/DeviceSpoofManager.swift @@ -41,10 +41,20 @@ public final class DeviceSpoofManager { private enum Keys { static let isEnabled = "DeviceSpoof.isEnabled" + static let hasExplicitConfiguration = "DeviceSpoof.hasExplicitConfiguration" static let selectedProfileId = "DeviceSpoof.selectedProfileId" static let customDeviceModel = "DeviceSpoof.customDeviceModel" static let customSystemVersion = "DeviceSpoof.customSystemVersion" } + + private struct ResolvedConfiguration { + let isEnabled: Bool + let selectedProfileId: Int + let customDeviceModel: String + let customSystemVersion: String + } + + private static let validProfileIds = Set(profiles.map { $0.id }) private let defaults = UserDefaults.standard @@ -52,18 +62,34 @@ public final class DeviceSpoofManager { /// Whether device spoofing is enabled public var isEnabled: Bool { - get { defaults.bool(forKey: Keys.isEnabled) } + get { + let configuration = resolvedConfiguration() + return configuration.isEnabled + } set { defaults.set(newValue, forKey: Keys.isEnabled) notifyChanged() } } + + /// Whether the current spoofing configuration was explicitly set by the user + public var hasExplicitConfiguration: Bool { + get { defaults.bool(forKey: Keys.hasExplicitConfiguration) } + set { + defaults.set(newValue, forKey: Keys.hasExplicitConfiguration) + notifyChanged() + } + } /// Selected profile ID (0 = real device, 100 = custom) public var selectedProfileId: Int { - get { defaults.integer(forKey: Keys.selectedProfileId) } + get { + sanitizeStoredConfiguration() + return defaults.integer(forKey: Keys.selectedProfileId) + } set { defaults.set(newValue, forKey: Keys.selectedProfileId) + sanitizeStoredConfiguration() notifyChanged() } } @@ -90,15 +116,19 @@ public final class DeviceSpoofManager { /// Get the currently effective device model public var effectiveDeviceModel: String? { - guard isEnabled else { return nil } - - if selectedProfileId == 100 { - // Custom profile - let custom = customDeviceModel.trimmingCharacters(in: .whitespacesAndNewlines) - return custom.isEmpty ? nil : custom + let configuration = resolvedConfiguration() + guard configuration.isEnabled else { + return nil } - - if let profile = Self.profiles.first(where: { $0.id == selectedProfileId }), profile.id != 0 { + + if configuration.selectedProfileId == 100 { + guard !configuration.customDeviceModel.isEmpty, !configuration.customSystemVersion.isEmpty else { + return nil + } + return configuration.customDeviceModel + } + + if let profile = Self.profiles.first(where: { $0.id == configuration.selectedProfileId }), profile.id != 0 { return profile.deviceModel.isEmpty ? nil : profile.deviceModel } @@ -107,15 +137,19 @@ public final class DeviceSpoofManager { /// Get the currently effective system version public var effectiveSystemVersion: String? { - guard isEnabled else { return nil } - - if selectedProfileId == 100 { - // Custom profile - let custom = customSystemVersion.trimmingCharacters(in: .whitespacesAndNewlines) - return custom.isEmpty ? nil : custom + let configuration = resolvedConfiguration() + guard configuration.isEnabled else { + return nil } - - if let profile = Self.profiles.first(where: { $0.id == selectedProfileId }), profile.id != 0 { + + if configuration.selectedProfileId == 100 { + guard !configuration.customDeviceModel.isEmpty, !configuration.customSystemVersion.isEmpty else { + return nil + } + return configuration.customSystemVersion + } + + if let profile = Self.profiles.first(where: { $0.id == configuration.selectedProfileId }), profile.id != 0 { return profile.systemVersion.isEmpty ? nil : profile.systemVersion } @@ -134,8 +168,40 @@ public final class DeviceSpoofManager { private func notifyChanged() { NotificationCenter.default.post(name: Self.settingsChangedNotification, object: nil) } + + private func sanitizeStoredConfiguration() { + let rawSelectedProfileId = defaults.integer(forKey: Keys.selectedProfileId) + if !Self.validProfileIds.contains(rawSelectedProfileId) { + defaults.set(0, forKey: Keys.selectedProfileId) + } + + let rawCustomDeviceModel = defaults.string(forKey: Keys.customDeviceModel) ?? "" + let trimmedCustomDeviceModel = rawCustomDeviceModel.trimmingCharacters(in: .whitespacesAndNewlines) + if rawCustomDeviceModel != trimmedCustomDeviceModel { + defaults.set(trimmedCustomDeviceModel, forKey: Keys.customDeviceModel) + } + + let rawCustomSystemVersion = defaults.string(forKey: Keys.customSystemVersion) ?? "" + let trimmedCustomSystemVersion = rawCustomSystemVersion.trimmingCharacters(in: .whitespacesAndNewlines) + if rawCustomSystemVersion != trimmedCustomSystemVersion { + defaults.set(trimmedCustomSystemVersion, forKey: Keys.customSystemVersion) + } + } + + private func resolvedConfiguration() -> ResolvedConfiguration { + sanitizeStoredConfiguration() + + return ResolvedConfiguration( + isEnabled: defaults.bool(forKey: Keys.hasExplicitConfiguration) && defaults.bool(forKey: Keys.isEnabled), + selectedProfileId: defaults.integer(forKey: Keys.selectedProfileId), + customDeviceModel: defaults.string(forKey: Keys.customDeviceModel) ?? "", + customSystemVersion: defaults.string(forKey: Keys.customSystemVersion) ?? "" + ) + } // MARK: - Init - private init() {} + private init() { + sanitizeStoredConfiguration() + } } diff --git a/submodules/TelegramCore/Sources/ForumChannels.swift b/submodules/TelegramCore/Sources/ForumChannels.swift index b5ee397d..6bfdef66 100644 --- a/submodules/TelegramCore/Sources/ForumChannels.swift +++ b/submodules/TelegramCore/Sources/ForumChannels.swift @@ -244,13 +244,15 @@ func _internal_createForumChannelTopic(postbox: Postbox, network: Network, state topicId = nil for update in result.allUpdates { switch update { - case let .updateNewChannelMessage(message, _, _): + case let .updateNewChannelMessage(updateNewChannelMessageData): + let (message, _, _) = (updateNewChannelMessageData.message, updateNewChannelMessageData.pts, updateNewChannelMessageData.ptsCount) if let message = StoreMessage(apiMessage: message, accountPeerId: accountPeerId, peerIsForum: peer.isForum) { if case let .Id(id) = message.id { topicId = Int64(id.id) } } - case let .updateNewMessage(message, _, _): + case let .updateNewMessage(updateNewMessageData): + let (message, _, _) = (updateNewMessageData.message, updateNewMessageData.pts, updateNewMessageData.ptsCount) if let message = StoreMessage(apiMessage: message, accountPeerId: accountPeerId, peerIsForum: peer.isForum) { if case let .Id(id) = message.id { topicId = Int64(id.id) @@ -489,7 +491,7 @@ func _internal_setForumChannelPinnedTopics(account: Account, id: EnginePeer.Id, return account.postbox.transaction { transaction -> [Api.InputDialogPeer] in transaction.setPeerPinnedThreads(peerId: id, threadIds: threadIds) - return threadIds.compactMap { transaction.getPeer(PeerId($0)).flatMap(apiInputPeer).flatMap({ .inputDialogPeer(peer: $0) }) } + return threadIds.compactMap { transaction.getPeer(PeerId($0)).flatMap(apiInputPeer).flatMap({ .inputDialogPeer(.init(peer: $0)) }) } } |> castError(SetForumChannelTopicPinnedError.self) |> mapToSignal { inputPeers -> Signal in @@ -773,7 +775,8 @@ func _internal_requestMessageHistoryThreads(accountPeerId: PeerId, postbox: Post } |> mapToSignal { result -> Signal in switch result { - case .savedDialogs(let dialogs, let messages, let chats, let users), .savedDialogsSlice(_, let dialogs, let messages, let chats, let users): + case let .savedDialogs(savedDialogsData): + let (dialogs, messages, chats, users) = (savedDialogsData.dialogs, savedDialogsData.messages, savedDialogsData.chats, savedDialogsData.users) var items: [LoadMessageHistoryThreadsResult.Item] = [] var pinnedIds: [Int64] = [] @@ -785,7 +788,8 @@ func _internal_requestMessageHistoryThreads(accountPeerId: PeerId, postbox: Post for dialog in dialogs { switch dialog { - case let .savedDialog(flags, peer, topMessage): + case let .savedDialog(savedDialogData): + let (flags, peer, topMessage) = (savedDialogData.flags, savedDialogData.peer, savedDialogData.topMessage) if (flags & (1 << 2)) != 0 { pinnedIds.append(peer.peerId.toInt64()) } @@ -843,7 +847,8 @@ func _internal_requestMessageHistoryThreads(accountPeerId: PeerId, postbox: Post index: topicIndex, threadPeer: threadPeer )) - case let .monoForumDialog(flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadReactionsCount, _): + case let .monoForumDialog(monoForumDialogData): + let (flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadReactionsCount) = (monoForumDialogData.flags, monoForumDialogData.peer, monoForumDialogData.topMessage, monoForumDialogData.readInboxMaxId, monoForumDialogData.readOutboxMaxId, monoForumDialogData.unreadCount, monoForumDialogData.unreadReactionsCount) let isMarkedUnread = (flags & (1 << 3)) != 0 let data = MessageHistoryThreadData( creationDate: 0, @@ -918,6 +923,163 @@ func _internal_requestMessageHistoryThreads(accountPeerId: PeerId, postbox: Post let combinedState = PeerThreadCombinedState(validIndexBoundary: nextIndex) + return .single(LoadMessageHistoryThreadsResult( + peerId: peerId, + items: items, + messages: addedMessages, + pinnedThreadIds: pinnedThreadIds, + combinedState: combinedState, + users: users, + chats: chats + )) + case let .savedDialogsSlice(savedDialogsSliceData): + let (dialogs, messages, chats, users) = (savedDialogsSliceData.dialogs, savedDialogsSliceData.messages, savedDialogsSliceData.chats, savedDialogsSliceData.users) + var items: [LoadMessageHistoryThreadsResult.Item] = [] + var pinnedIds: [Int64] = [] + + let addedMessages = messages.compactMap { message -> StoreMessage? in + return StoreMessage(apiMessage: message, accountPeerId: accountPeerId, peerIsForum: false) + } + + var minIndex: StoredPeerThreadCombinedState.Index? + + for dialog in dialogs { + switch dialog { + case let .savedDialog(savedDialogData): + let (flags, peer, topMessage) = (savedDialogData.flags, savedDialogData.peer, savedDialogData.topMessage) + if (flags & (1 << 2)) != 0 { + pinnedIds.append(peer.peerId.toInt64()) + } + + let data = MessageHistoryThreadData( + creationDate: 0, + isOwnedByMe: true, + author: peer.peerId, + info: EngineMessageHistoryThread.Info( + title: "", + icon: nil, + iconColor: 0 + ), + incomingUnreadCount: 0, + isMarkedUnread: false, + maxIncomingReadId: 0, + maxKnownMessageId: topMessage, + maxOutgoingReadId: 0, + isClosed: false, + isHidden: false, + notificationSettings: TelegramPeerNotificationSettings.defaultSettings, + isMessageFeeRemoved: false + ) + + var topTimestamp: Int32 = 1 + for message in addedMessages { + if message.id.peerId == peerId && message.threadId == peer.peerId.toInt64() { + topTimestamp = max(topTimestamp, message.timestamp) + } + } + + let topicIndex = StoredPeerThreadCombinedState.Index(timestamp: topTimestamp, threadId: peer.peerId.toInt64(), messageId: topMessage) + if let minIndexValue = minIndex { + if topicIndex < minIndexValue { + minIndex = topicIndex + } + } else { + minIndex = topicIndex + } + + var threadPeer: Peer? + for user in users { + if user.peerId == peer.peerId { + threadPeer = TelegramUser(user: user) + break + } + } + + items.append(LoadMessageHistoryThreadsResult.Item( + threadId: peer.peerId.toInt64(), + data: data, + topMessage: topMessage, + unreadMentionsCount: 0, + unreadReactionsCount: 0, + index: topicIndex, + threadPeer: threadPeer + )) + case let .monoForumDialog(monoForumDialogData): + let (flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadReactionsCount) = (monoForumDialogData.flags, monoForumDialogData.peer, monoForumDialogData.topMessage, monoForumDialogData.readInboxMaxId, monoForumDialogData.readOutboxMaxId, monoForumDialogData.unreadCount, monoForumDialogData.unreadReactionsCount) + let isMarkedUnread = (flags & (1 << 3)) != 0 + let data = MessageHistoryThreadData( + creationDate: 0, + isOwnedByMe: true, + author: accountPeerId, + info: EngineMessageHistoryThread.Info( + title: "", + icon: nil, + iconColor: 0 + ), + incomingUnreadCount: unreadCount, + isMarkedUnread: isMarkedUnread, + maxIncomingReadId: readInboxMaxId, + maxKnownMessageId: topMessage, + maxOutgoingReadId: readOutboxMaxId, + isClosed: false, + isHidden: false, + notificationSettings: TelegramPeerNotificationSettings.defaultSettings, + isMessageFeeRemoved: (flags & (1 << 4)) != 0 + ) + + var topTimestamp: Int32 = 1 + for message in addedMessages { + if message.id.peerId == peerId && message.threadId == peer.peerId.toInt64() { + topTimestamp = max(topTimestamp, message.timestamp) + } + } + + let topicIndex = StoredPeerThreadCombinedState.Index(timestamp: topTimestamp, threadId: peer.peerId.toInt64(), messageId: topMessage) + if let minIndexValue = minIndex { + if topicIndex < minIndexValue { + minIndex = topicIndex + } + } else { + minIndex = topicIndex + } + + var threadPeer: Peer? + for user in users { + if user.peerId == peer.peerId { + threadPeer = TelegramUser(user: user) + break + } + } + + items.append(LoadMessageHistoryThreadsResult.Item( + threadId: peer.peerId.toInt64(), + data: data, + topMessage: topMessage, + unreadMentionsCount: 0, + unreadReactionsCount: unreadReactionsCount, + index: topicIndex, + threadPeer: threadPeer + )) + } + } + + var pinnedThreadIds: [Int64]? + if offsetIndex == nil { + pinnedThreadIds = pinnedIds + } + + var nextIndex: StoredPeerThreadCombinedState.Index + if dialogs.count != 0 { + nextIndex = minIndex ?? StoredPeerThreadCombinedState.Index(timestamp: 0, threadId: 0, messageId: 1) + } else { + nextIndex = StoredPeerThreadCombinedState.Index(timestamp: 0, threadId: 0, messageId: 1) + } + if let offsetIndex = offsetIndex, nextIndex == offsetIndex { + nextIndex = StoredPeerThreadCombinedState.Index(timestamp: 0, threadId: 0, messageId: 1) + } + + let combinedState = PeerThreadCombinedState(validIndexBoundary: nextIndex) + return .single(LoadMessageHistoryThreadsResult( peerId: peerId, items: items, @@ -981,7 +1143,8 @@ func _internal_requestMessageHistoryThreads(accountPeerId: PeerId, postbox: Post } |> mapToSignal { result -> Signal in switch result { - case let .forumTopics(_, _, topics, messages, chats, users, pts): + case let .forumTopics(forumTopicsData): + let (topics, messages, chats, users, pts) = (forumTopicsData.topics, forumTopicsData.messages, forumTopicsData.chats, forumTopicsData.users, forumTopicsData.pts) var items: [LoadMessageHistoryThreadsResult.Item] = [] var pinnedIds: [Int64] = [] @@ -994,7 +1157,8 @@ func _internal_requestMessageHistoryThreads(accountPeerId: PeerId, postbox: Post for topic in topics { switch topic { - case let .forumTopic(flags, id, date, peer, title, iconColor, iconEmojiId, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, fromId, notifySettings, draft): + case let .forumTopic(forumTopicData): + let (flags, id, date, peer, title, iconColor, iconEmojiId, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, fromId, notifySettings, draft) = (forumTopicData.flags, forumTopicData.id, forumTopicData.date, forumTopicData.peer, forumTopicData.title, forumTopicData.iconColor, forumTopicData.iconEmojiId, forumTopicData.topMessage, forumTopicData.readInboxMaxId, forumTopicData.readOutboxMaxId, forumTopicData.unreadCount, forumTopicData.unreadMentionsCount, forumTopicData.unreadReactionsCount, forumTopicData.fromId, forumTopicData.notifySettings, forumTopicData.draft) let _ = draft let _ = peer @@ -1167,7 +1331,7 @@ func _internal_forumChannelTopicNotificationExceptions(account: Account, id: Eng return .single([]) } - return account.network.request(Api.functions.account.getNotifyExceptions(flags: 1 << 0, peer: Api.InputNotifyPeer.inputNotifyPeer(peer: inputPeer))) + return account.network.request(Api.functions.account.getNotifyExceptions(flags: 1 << 0, peer: Api.InputNotifyPeer.inputNotifyPeer(.init(peer: inputPeer)))) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -1180,9 +1344,11 @@ func _internal_forumChannelTopicNotificationExceptions(account: Account, id: Eng var list: [(threadId: Int64, notificationSettings: EnginePeer.NotificationSettings)] = [] for update in result.allUpdates { switch update { - case let .updateNotifySettings(peer, notifySettings): + case let .updateNotifySettings(updateNotifySettingsData): + let (peer, notifySettings) = (updateNotifySettingsData.peer, updateNotifySettingsData.notifySettings) switch peer { - case let .notifyForumTopic(_, topMsgId): + case let .notifyForumTopic(notifyForumTopicData): + let topMsgId = notifyForumTopicData.topMsgId list.append((Int64(topMsgId), EnginePeer.NotificationSettings(TelegramPeerNotificationSettings(apiSettings: notifySettings)))) default: break @@ -1199,10 +1365,12 @@ func _internal_forumChannelTopicNotificationExceptions(account: Account, id: Eng var infoMapping: [Int64: EngineMessageHistoryThread.Info] = [:] switch result { - case let .forumTopics(_, _, topics, _, _, _, _): + case let .forumTopics(forumTopicsData): + let topics = forumTopicsData.topics for topic in topics { switch topic { - case let .forumTopic(_, id, _, _, title, iconColor, iconEmojiId, _, _, _, _, _, _, _, _, _): + case let .forumTopic(forumTopicData): + let (id, title, iconColor, iconEmojiId) = (forumTopicData.id, forumTopicData.title, forumTopicData.iconColor, forumTopicData.iconEmojiId) infoMapping[Int64(id)] = EngineMessageHistoryThread.Info(title: title, icon: iconEmojiId, iconColor: iconColor) case .forumTopicDeleted: break diff --git a/submodules/TelegramCore/Sources/LoadedPeer.swift b/submodules/TelegramCore/Sources/LoadedPeer.swift index b5b98dd7..fc482298 100644 --- a/submodules/TelegramCore/Sources/LoadedPeer.swift +++ b/submodules/TelegramCore/Sources/LoadedPeer.swift @@ -35,9 +35,11 @@ public func actualizedPeer(accountPeerId: PeerId, postbox: Postbox, network: Net if let result = result { 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.chats chats = apiChats } let parsedPeersValue = AccumulatedPeers(transaction: transaction, chats: chats, users: []) diff --git a/submodules/TelegramCore/Sources/LoadedPeerFromMessage.swift b/submodules/TelegramCore/Sources/LoadedPeerFromMessage.swift index 870d08ef..549873d0 100644 --- a/submodules/TelegramCore/Sources/LoadedPeerFromMessage.swift +++ b/submodules/TelegramCore/Sources/LoadedPeerFromMessage.swift @@ -14,13 +14,13 @@ public func loadedPeerFromMessage(account: Account, peerId: PeerId, messageId: M } else { let messageSignal: Signal? if messageId.peerId.namespace == Namespaces.Peer.CloudUser || messageId.peerId.namespace == Namespaces.Peer.CloudGroup { - messageSignal = account.network.request(Api.functions.messages.getMessages(id: [Api.InputMessage.inputMessageID(id: messageId.id)])) + messageSignal = account.network.request(Api.functions.messages.getMessages(id: [Api.InputMessage.inputMessageID(.init(id: messageId.id))])) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) } } else if messageId.peerId.namespace == Namespaces.Peer.CloudChannel, let channelPeer = transaction.getPeer(messageId.peerId), let inputChannel = apiInputChannel(channelPeer) { - messageSignal = account.network.request(Api.functions.channels.getMessages(channel: inputChannel, id: [Api.InputMessage.inputMessageID(id: messageId.id)])) + messageSignal = account.network.request(Api.functions.channels.getMessages(channel: inputChannel, id: [Api.InputMessage.inputMessageID(.init(id: messageId.id))])) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -35,11 +35,14 @@ public func loadedPeerFromMessage(account: Account, peerId: PeerId, messageId: M if let result = result { let apiUsers: [Api.User] switch result { - case let .messages(_, _, _, users): + case let .messages(messagesData): + let users = messagesData.users apiUsers = users - case let .messagesSlice(_, _, _, _, _, _, _, _, users): + case let .messagesSlice(messagesSliceData): + let users = messagesSliceData.users apiUsers = users - case let .channelMessages(_, _, _, _, _, _, _, users): + case let .channelMessages(channelMessagesData): + let users = channelMessagesData.users apiUsers = users case .messagesNotModified: apiUsers = [] diff --git a/submodules/TelegramCore/Sources/MacOS/MacInternal.swift b/submodules/TelegramCore/Sources/MacOS/MacInternal.swift index 9fc5a710..480beb7a 100644 --- a/submodules/TelegramCore/Sources/MacOS/MacInternal.swift +++ b/submodules/TelegramCore/Sources/MacOS/MacInternal.swift @@ -28,7 +28,8 @@ public func requestUpdatesXml(account: Account, source: String) -> Signal castError(InternalUpdaterError.self) |> mapToSignal { result in switch result { - case let .channelMessages(_, _, _, _, apiMessages, _, apiChats, apiUsers): + case let .channelMessages(channelMessagesData): + let (apiMessages, apiChats, apiUsers) = (channelMessagesData.messages, channelMessagesData.chats, channelMessagesData.users) if let apiMessage = apiMessages.first, let storeMessage = StoreMessage(apiMessage: apiMessage, accountPeerId: account.peerId, peerIsForum: peer.isForum) { var peers: [PeerId: Peer] = [:] @@ -93,13 +94,14 @@ public func downloadAppUpdate(account: Account, source: String, messageId: Int32 } |> mapToSignal { peer in if let peer = peer, let inputChannel = apiInputChannel(peer) { - return account.network.request(Api.functions.channels.getMessages(channel: inputChannel, id: [Api.InputMessage.inputMessageID(id: messageId)])) + return account.network.request(Api.functions.channels.getMessages(channel: inputChannel, id: [Api.InputMessage.inputMessageID(.init(id: messageId))])) |> retryRequest |> castError(InternalUpdaterError.self) |> mapToSignal { messages in switch messages { - case let .channelMessages(_, _, _, _, apiMessages, _, apiChats, apiUsers): - + case let .channelMessages(channelMessagesData): + let (apiMessages, apiChats, apiUsers) = (channelMessagesData.messages, channelMessagesData.chats, channelMessagesData.users) + var peers: [PeerId: Peer] = [:] for chat in apiChats { if let groupOrChannel = parseTelegramGroupOrChannel(chat: chat) { @@ -110,7 +112,7 @@ public func downloadAppUpdate(account: Account, source: String, messageId: Int32 let telegramUser = TelegramUser(user: user) peers[telegramUser.id] = telegramUser } - + let messageAndFile:(Message, TelegramMediaFile)? = apiMessages.compactMap { value in return StoreMessage(apiMessage: value, accountPeerId: account.peerId, peerIsForum: peer.isForum) }.compactMap { value in @@ -192,7 +194,8 @@ public func requestApplicationIcons(engine: TelegramEngine, source: String = "ma |> mapToSignal { result in switch result { - case let .channelMessages(_, _, _, _, apiMessages, _, apiChats, apiUsers): + case let .channelMessages(channelMessagesData): + let (apiMessages, apiChats, apiUsers) = (channelMessagesData.messages, channelMessagesData.chats, channelMessagesData.users) var icons: [TelegramApplicationIcons.Icon] = [] for apiMessage in apiMessages.reversed() { if let storeMessage = StoreMessage(apiMessage: apiMessage, accountPeerId: engine.account.peerId, peerIsForum: peer.isForum) { diff --git a/submodules/TelegramCore/Sources/Network/Download.swift b/submodules/TelegramCore/Sources/Network/Download.swift index 7966a994..ab16e78e 100644 --- a/submodules/TelegramCore/Sources/Network/Download.swift +++ b/submodules/TelegramCore/Sources/Network/Download.swift @@ -225,7 +225,8 @@ class Download: NSObject, MTRequestMessageServiceDelegate { } else { if let result = (boxedResponse as! BoxedMessage).body as? Api.upload.WebFile { switch result { - case .webFile(_, _, _, _, let bytes): + case let .webFile(webFileData): + let bytes = webFileData.bytes subscriber.putNext(bytes.makeData()) } subscriber.putCompletion() @@ -278,7 +279,8 @@ class Download: NSObject, MTRequestMessageServiceDelegate { } else { if let result = (boxedResponse as! BoxedMessage).body as? Api.upload.File { switch result { - case let .file(_, _, bytes): + case let .file(fileData): + let bytes = fileData.bytes subscriber.putNext(bytes.makeData()) case .fileCdnRedirect: break diff --git a/submodules/TelegramCore/Sources/Network/FetchV2.swift b/submodules/TelegramCore/Sources/Network/FetchV2.swift index 702c5609..94d6bd92 100644 --- a/submodules/TelegramCore/Sources/Network/FetchV2.swift +++ b/submodules/TelegramCore/Sources/Network/FetchV2.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import Postbox import SwiftSignalKit @@ -388,9 +389,9 @@ private final class FetchImpl { } if isStory { - self.defaultPartSize = 512 * 1024 + self.defaultPartSize = getSGDownloadPartSize(512 * 1024, fileSize: self.size) } else { - self.defaultPartSize = 128 * 1024 + self.defaultPartSize = getSGDownloadPartSize(128 * 1024, fileSize: self.size) } self.cdnPartSize = 128 * 1024 @@ -440,7 +441,7 @@ private final class FetchImpl { maxPartSize: 1 * 1024 * 1024, partAlignment: 4 * 1024, partDivision: 1 * 1024 * 1024, - maxPendingParts: 6, + maxPendingParts: getSGMaxPendingParts(6), decryptionState: decryptionState )) } @@ -696,7 +697,7 @@ private final class FetchImpl { maxPartSize: self.cdnPartSize * 2, partAlignment: self.cdnPartSize, partDivision: 1 * 1024 * 1024, - maxPendingParts: 6, + maxPendingParts: getSGMaxPendingParts(6), decryptionState: nil )) self.update() @@ -745,7 +746,7 @@ private final class FetchImpl { maxPartSize: self.defaultPartSize, partAlignment: 4 * 1024, partDivision: 1 * 1024 * 1024, - maxPendingParts: 6, + maxPendingParts: getSGMaxPendingParts(6), decryptionState: nil )) @@ -801,7 +802,8 @@ private final class FetchImpl { ) |> map { result -> FilePartResult in switch result { - case let .cdnFile(bytes): + case let .cdnFile(cdnFileData): + let bytes = cdnFileData.bytes if bytes.size == 0 { return .data(data: Data(), verifyPartHashData: nil) } else { @@ -819,7 +821,8 @@ private final class FetchImpl { verifyPartHashData: VerifyPartHashData(fetchRange: fetchRange, fetchedData: fetchedData) ) } - case let .cdnFileReuploadNeeded(requestToken): + case let .cdnFileReuploadNeeded(cdnFileReuploadNeededData): + let requestToken = cdnFileReuploadNeededData.requestToken return .cdnRefresh(cdnData: cdnData, refreshToken: requestToken.makeData()) } } @@ -858,9 +861,11 @@ private final class FetchImpl { ) |> map { result -> FilePartResult in switch result { - case let .file(_, _, bytes): + case let .file(fileData): + let bytes = fileData.bytes return .data(data: bytes.makeData(), verifyPartHashData: nil) - case let .fileCdnRedirect(dcId, fileToken, encryptionKey, encryptionIv, fileHashes): + case let .fileCdnRedirect(fileCdnRedirectData): + let (dcId, fileToken, encryptionKey, encryptionIv, fileHashes) = (fileCdnRedirectData.dcId, fileCdnRedirectData.fileToken, fileCdnRedirectData.encryptionKey, fileCdnRedirectData.encryptionIv, fileCdnRedirectData.fileHashes) let _ = fileHashes return .cdnRedirect(CdnData( id: Int(dcId), @@ -931,7 +936,7 @@ private final class FetchImpl { maxPartSize: self.cdnPartSize * 2, partAlignment: self.cdnPartSize, partDivision: 1 * 1024 * 1024, - maxPendingParts: 6, + maxPendingParts: getSGMaxPendingParts(6), decryptionState: nil )) case let .cdnRefresh(cdnData, refreshToken): @@ -995,7 +1000,8 @@ private final class FetchImpl { var filledRange = RangeSet() for hashItem in result { switch hashItem { - case let .fileHash(offset, limit, hash): + case let .fileHash(fileHashData): + let (offset, limit, hash) = (fileHashData.offset, fileHashData.limit, fileHashData.hash) let rangeValue: Range = offset ..< (offset + Int64(limit)) filledRange.formUnion(RangeSet(rangeValue)) state.hashRanges[rangeValue.lowerBound] = HashRangeData( diff --git a/submodules/TelegramCore/Sources/Network/MultipartFetch.swift b/submodules/TelegramCore/Sources/Network/MultipartFetch.swift index ed3d1028..c972fd1b 100644 --- a/submodules/TelegramCore/Sources/Network/MultipartFetch.swift +++ b/submodules/TelegramCore/Sources/Network/MultipartFetch.swift @@ -197,7 +197,8 @@ private final class MultipartCdnHashSource { var parsedPartHashes: [Int64: Data] = [:] for part in partHashes { switch part { - case let .fileHash(offset, limit, bytes): + case let .fileHash(fileHashData): + let (offset, limit, bytes) = (fileHashData.offset, fileHashData.limit, fileHashData.hash) assert(limit == 128 * 1024) parsedPartHashes[offset] = bytes.makeData() } @@ -361,17 +362,20 @@ private enum MultipartFetchSource { } |> mapToSignal { result, info -> Signal<(Data, NetworkResponseInfo), MultipartFetchDownloadError> in switch result { - case let .file(_, _, bytes): + case let .file(fileData): + let bytes = fileData.bytes var resultData = bytes.makeData() if resultData.count > Int(limit) { resultData.count = Int(limit) } return .single((resultData, info)) - case let .fileCdnRedirect(dcId, fileToken, encryptionKey, encryptionIv, partHashes): + case let .fileCdnRedirect(fileCdnRedirectData): + let (dcId, fileToken, encryptionKey, encryptionIv, partHashes) = (fileCdnRedirectData.dcId, fileCdnRedirectData.fileToken, fileCdnRedirectData.encryptionKey, fileCdnRedirectData.encryptionIv, fileCdnRedirectData.fileHashes) var parsedPartHashes: [Int64: Data] = [:] for part in partHashes { switch part { - case let .fileHash(offset, limit, bytes): + case let .fileHash(fileHashData): + let (offset, limit, bytes) = (fileHashData.offset, fileHashData.limit, fileHashData.hash) assert(limit == 128 * 1024) parsedPartHashes[offset] = bytes.makeData() } @@ -395,7 +399,8 @@ private enum MultipartFetchSource { } |> mapToSignal { result, info -> Signal<(Data, NetworkResponseInfo), MultipartFetchDownloadError> in switch result { - case let .webFile(_, _, _, _, bytes): + case let .webFile(webFileData): + let bytes = webFileData.bytes var resultData = bytes.makeData() if resultData.count > Int(limit) { resultData.count = Int(limit) @@ -418,9 +423,11 @@ private enum MultipartFetchSource { } |> mapToSignal { result, info -> Signal<(Data, NetworkResponseInfo), MultipartFetchDownloadError> in switch result { - case let .cdnFileReuploadNeeded(token): + case let .cdnFileReuploadNeeded(cdnFileReuploadNeededData): + let token = cdnFileReuploadNeededData.requestToken return .fail(.reuploadToCdn(masterDatacenterId: masterDatacenterId, token: token.makeData())) - case let .cdnFile(bytes): + case let .cdnFile(cdnFileData): + let bytes = cdnFileData.bytes if bytes.size == 0 { return .single((bytes.makeData(), info)) } else { diff --git a/submodules/TelegramCore/Sources/Network/MultipartUpload.swift b/submodules/TelegramCore/Sources/Network/MultipartUpload.swift index 3f07e3bb..5d0a83cc 100644 --- a/submodules/TelegramCore/Sources/Network/MultipartUpload.swift +++ b/submodules/TelegramCore/Sources/Network/MultipartUpload.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import Postbox import TelegramApi @@ -479,7 +480,8 @@ func multipartUpload(network: Network, postbox: Postbox, source: MultipartUpload } } - let manager = MultipartUploadManager(headerSize: headerSize, data: dataSignal, encryptionKey: encryptionKey, hintFileSize: hintFileSize, hintFileIsLarge: hintFileIsLarge, forceNoBigParts: forceNoBigParts, useLargerParts: useLargerParts, increaseParallelParts: increaseParallelParts, uploadPart: { part in + // TODO(swiftgram): Change other variables for uploadSpeedBoost + let manager = MultipartUploadManager(headerSize: headerSize, data: dataSignal, encryptionKey: encryptionKey, hintFileSize: hintFileSize, hintFileIsLarge: hintFileIsLarge, forceNoBigParts: forceNoBigParts, useLargerParts: useLargerParts || SGSimpleSettings.shared.uploadSpeedBoost, increaseParallelParts: increaseParallelParts || SGSimpleSettings.shared.uploadSpeedBoost, uploadPart: { part in switch uploadInterface { case let .download(download): return download.uploadPart(fileId: part.fileId, index: part.index, data: part.data, asBigPart: part.bigPart, bigTotalParts: part.bigTotalParts, useCompression: useCompression, onFloodWaitError: onFloodWaitError) @@ -505,18 +507,18 @@ func multipartUpload(network: Network, postbox: Postbox, source: MultipartUpload }) } if let _ = result.bigTotalParts { - let inputFile = Api.InputEncryptedFile.inputEncryptedFileBigUploaded(id: result.id, parts: result.partCount, keyFingerprint: fingerprint) + let inputFile = Api.InputEncryptedFile.inputEncryptedFileBigUploaded(.init(id: result.id, parts: result.partCount, keyFingerprint: fingerprint)) subscriber.putNext(.inputSecretFile(inputFile, result.size, encryptionKey)) } else { - let inputFile = Api.InputEncryptedFile.inputEncryptedFileUploaded(id: result.id, parts: result.partCount, md5Checksum: result.md5Digest, keyFingerprint: fingerprint) + let inputFile = Api.InputEncryptedFile.inputEncryptedFileUploaded(.init(id: result.id, parts: result.partCount, md5Checksum: result.md5Digest, keyFingerprint: fingerprint)) subscriber.putNext(.inputSecretFile(inputFile, result.size, encryptionKey)) } } else { if let _ = result.bigTotalParts { - let inputFile = Api.InputFile.inputFileBig(id: result.id, parts: result.partCount, name: "file.jpg") + let inputFile = Api.InputFile.inputFileBig(.init(id: result.id, parts: result.partCount, name: "file.jpg")) subscriber.putNext(.inputFile(inputFile)) } else { - let inputFile = Api.InputFile.inputFile(id: result.id, parts: result.partCount, name: "file.jpg", md5Checksum: result.md5Digest) + let inputFile = Api.InputFile.inputFile(.init(id: result.id, parts: result.partCount, name: "file.jpg", md5Checksum: result.md5Digest)) subscriber.putNext(.inputFile(inputFile)) } } diff --git a/submodules/TelegramCore/Sources/Network/Network.swift b/submodules/TelegramCore/Sources/Network/Network.swift index 75e53aa7..f62f892f 100644 --- a/submodules/TelegramCore/Sources/Network/Network.swift +++ b/submodules/TelegramCore/Sources/Network/Network.swift @@ -1,3 +1,6 @@ +// MARK: Swiftgram +import SGSimpleSettings + import Foundation import Postbox import TelegramApi @@ -504,7 +507,6 @@ func initializedNetwork(accountId: AccountRecordId, arguments: NetworkInitializa } let useTempAuthKeys: Bool = true - let context = MTContext(serialization: serialization, encryptionProvider: arguments.encryptionProvider, apiEnvironment: apiEnvironment, isTestingEnvironment: testingEnvironment, useTempAuthKeys: useTempAuthKeys) if let networkSettings = networkSettings { @@ -899,10 +901,12 @@ public final class Network: NSObject, MTRequestMessageServiceDelegate { let array = NSMutableArray() if let result = result { switch result { - case let .cdnConfig(publicKeys): + case let .cdnConfig(cdnConfigData): + let publicKeys = cdnConfigData.publicKeys for key in publicKeys { switch key { - case let .cdnPublicKey(dcId, publicKey): + case let .cdnPublicKey(cdnPublicKeyData): + let (dcId, publicKey) = (cdnPublicKeyData.dcId, cdnPublicKeyData.publicKey) if id == Int(dcId) { let dict = NSMutableDictionary() dict["key"] = publicKey diff --git a/submodules/TelegramCore/Sources/PendingMessages/EnqueueMessage.swift b/submodules/TelegramCore/Sources/PendingMessages/EnqueueMessage.swift index 3b1f7165..c22d0d36 100644 --- a/submodules/TelegramCore/Sources/PendingMessages/EnqueueMessage.swift +++ b/submodules/TelegramCore/Sources/PendingMessages/EnqueueMessage.swift @@ -964,7 +964,7 @@ func enqueueMessages(transaction: Transaction, account: Account, peerId: PeerId, buttons.append(button) } else if case let .switchInline(samePeer, query, peerTypes) = button.action, sourceSentViaBot { let samePeer = samePeer && peerId == sourceMessage.id.peerId - let updatedButton = ReplyMarkupButton(title: button.titleWhenForwarded ?? button.title, titleWhenForwarded: button.titleWhenForwarded, action: .switchInline(samePeer: samePeer, query: query, peerTypes: peerTypes)) + let updatedButton = ReplyMarkupButton(title: button.titleWhenForwarded ?? button.title, titleWhenForwarded: button.titleWhenForwarded, action: .switchInline(samePeer: samePeer, query: query, peerTypes: peerTypes), style: button.style) buttons.append(updatedButton) } else { rows.removeAll() diff --git a/submodules/TelegramCore/Sources/PendingMessages/PendingMessageUploadedContent.swift b/submodules/TelegramCore/Sources/PendingMessages/PendingMessageUploadedContent.swift index 4f78188e..50e7eae7 100644 --- a/submodules/TelegramCore/Sources/PendingMessages/PendingMessageUploadedContent.swift +++ b/submodules/TelegramCore/Sources/PendingMessages/PendingMessageUploadedContent.swift @@ -103,7 +103,7 @@ func messageContentToUpload(accountPeerId: PeerId, network: Network, postbox: Po guard let inputPeer = transaction.getPeer(media.storyId.peerId).flatMap(apiInputPeer) else { return .progress(PendingMessageUploadedContentProgress(progress: 0.0)) } - return .content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaStory(peer: inputPeer, id: media.storyId.id), ""), reuploadInfo: nil, cacheReferenceKey: nil)) + return .content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaStory(.init(peer: inputPeer, id: media.storyId.id)), ""), reuploadInfo: nil, cacheReferenceKey: nil)) } |> castError(PendingMessageUploadError.self), .text) } else if let media = media.first as? TelegramMediaWebpage, case let .Loaded(content) = media.content { @@ -119,7 +119,7 @@ func messageContentToUpload(accountPeerId: PeerId, network: Network, postbox: Po } } } - return .content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaWebPage(flags: flags, url: content.url), text), reuploadInfo: nil, cacheReferenceKey: nil)) + return .content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaWebPage(.init(flags: flags, url: content.url)), text), reuploadInfo: nil, cacheReferenceKey: nil)) } |> castError(PendingMessageUploadError.self), .text) } else if let media = media.first, let mediaResult = mediaContentToUpload(accountPeerId: accountPeerId, network: network, postbox: postbox, auxiliaryMethods: auxiliaryMethods, transformOutgoingMessageMedia: transformOutgoingMessageMedia, messageMediaPreuploadManager: messageMediaPreuploadManager, revalidationContext: revalidationContext, forceReupload: forceReupload, isGrouped: isGrouped, passFetchProgress: passFetchProgress, forceNoBigParts: forceNoBigParts, peerId: peerId, media: media, text: text, autoremoveMessageAttribute: autoremoveMessageAttribute, autoclearMessageAttribute: autoclearMessageAttribute, messageId: messageId, attributes: attributes, mediaReference: mediaReference, explicitPartialReference: explicitPartialReference) { @@ -165,12 +165,12 @@ func mediaContentToUpload(accountPeerId: PeerId, network: Network, postbox: Post let normalizedProgress = currentProgress / Float(results.count) if media.count == results.count { return .content(PendingMessageUploadedContentAndReuploadInfo( - content: .media(.inputMediaPaidMedia( + content: .media(.inputMediaPaidMedia(.init( flags: 0, starsAmount: paidContent.amount, extendedMedia: media, payload: nil - ), text), + )), text), reuploadInfo: nil, cacheReferenceKey: nil )) @@ -181,10 +181,10 @@ func mediaContentToUpload(accountPeerId: PeerId, network: Network, postbox: Post } if let image = media as? TelegramMediaImage, let largest = largestImageRepresentation(image.representations) { if peerId.namespace == Namespaces.Peer.SecretChat, let resource = largest.resource as? SecretFileMediaResource { - return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .secretMedia(.inputEncryptedFile(id: resource.fileId, accessHash: resource.accessHash), resource.decryptedSize, resource.key), reuploadInfo: nil, cacheReferenceKey: nil))) + return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .secretMedia(.inputEncryptedFile(.init(id: resource.fileId, accessHash: resource.accessHash)), resource.decryptedSize, resource.key), reuploadInfo: nil, cacheReferenceKey: nil))) } if peerId.namespace != Namespaces.Peer.SecretChat, let reference = image.reference, case let .cloud(id, accessHash, maybeFileReference) = reference, let fileReference = maybeFileReference { - return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(Api.InputMedia.inputMediaPhoto(flags: 0, id: Api.InputPhoto.inputPhoto(id: id, accessHash: accessHash, fileReference: Buffer(data: fileReference)), ttlSeconds: nil), text), reuploadInfo: nil, cacheReferenceKey: nil))) + return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(Api.InputMedia.inputMediaPhoto(.init(flags: 0, id: Api.InputPhoto.inputPhoto(.init(id: id, accessHash: accessHash, fileReference: Buffer(data: fileReference))), ttlSeconds: nil)), text), reuploadInfo: nil, cacheReferenceKey: nil))) } else { return uploadedMediaImageContent(network: network, postbox: postbox, transformOutgoingMessageMedia: transformOutgoingMessageMedia, forceReupload: forceReupload, isGrouped: isGrouped, peerId: peerId, image: image, messageId: messageId, text: text, attributes: attributes, autoremoveMessageAttribute: autoremoveMessageAttribute, autoclearMessageAttribute: autoclearMessageAttribute, auxiliaryMethods: auxiliaryMethods) } @@ -244,7 +244,7 @@ func mediaContentToUpload(accountPeerId: PeerId, network: Network, postbox: Post flags |= 1 << 4 } - return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(Api.InputMedia.inputMediaDocument(flags: flags, id: Api.InputDocument.inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: reference)), videoCover: nil, videoTimestamp: videoTimestamp, ttlSeconds: nil, query: nil), text), reuploadInfo: nil, cacheReferenceKey: nil))) + return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(Api.InputMedia.inputMediaDocument(.init(flags: flags, id: Api.InputDocument.inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: reference))), videoCover: nil, videoTimestamp: videoTimestamp, ttlSeconds: nil, query: nil)), text), reuploadInfo: nil, cacheReferenceKey: nil))) } else { return .fail(.generic) } @@ -265,13 +265,13 @@ func mediaContentToUpload(accountPeerId: PeerId, network: Network, postbox: Post } } - return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(Api.InputMedia.inputMediaDocument(flags: flags, id: Api.InputDocument.inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data())), videoCover: nil, videoTimestamp: videoTimestamp, ttlSeconds: nil, query: emojiSearchQuery), text), reuploadInfo: nil, cacheReferenceKey: nil))) + return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(Api.InputMedia.inputMediaDocument(.init(flags: flags, id: Api.InputDocument.inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data()))), videoCover: nil, videoTimestamp: videoTimestamp, ttlSeconds: nil, query: emojiSearchQuery)), text), reuploadInfo: nil, cacheReferenceKey: nil))) } } else { return uploadedMediaFileContent(network: network, postbox: postbox, auxiliaryMethods: auxiliaryMethods, transformOutgoingMessageMedia: transformOutgoingMessageMedia, messageMediaPreuploadManager: messageMediaPreuploadManager, forceReupload: forceReupload, isGrouped: isGrouped, isPaid: false, passFetchProgress: passFetchProgress, forceNoBigParts: forceNoBigParts, peerId: peerId, messageId: messageId, text: text, attributes: attributes, autoremoveMessageAttribute: autoremoveMessageAttribute, autoclearMessageAttribute: autoclearMessageAttribute, file: file) } } else if let contact = media as? TelegramMediaContact { - let input = Api.InputMedia.inputMediaContact(phoneNumber: contact.phoneNumber, firstName: contact.firstName, lastName: contact.lastName, vcard: contact.vCardData ?? "") + let input = Api.InputMedia.inputMediaContact(.init(phoneNumber: contact.phoneNumber, firstName: contact.firstName, lastName: contact.lastName, vcard: contact.vCardData ?? "")) return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(input, text), reuploadInfo: nil, cacheReferenceKey: nil))) } else if let map = media as? TelegramMediaMap { let input: Api.InputMedia @@ -287,11 +287,11 @@ func mediaContentToUpload(accountPeerId: PeerId, network: Network, postbox: Post geoFlags |= 1 << 0 } if let liveBroadcastingTimeout = map.liveBroadcastingTimeout { - input = .inputMediaGeoLive(flags: flags, geoPoint: Api.InputGeoPoint.inputGeoPoint(flags: geoFlags, lat: map.latitude, long: map.longitude, accuracyRadius: map.accuracyRadius.flatMap({ Int32($0) })), heading: map.heading, period: liveBroadcastingTimeout, proximityNotificationRadius: map.liveProximityNotificationRadius.flatMap({ Int32($0) })) + input = .inputMediaGeoLive(.init(flags: flags, geoPoint: Api.InputGeoPoint.inputGeoPoint(.init(flags: geoFlags, lat: map.latitude, long: map.longitude, accuracyRadius: map.accuracyRadius.flatMap({ Int32($0) }))), heading: map.heading, period: liveBroadcastingTimeout, proximityNotificationRadius: map.liveProximityNotificationRadius.flatMap({ Int32($0) }))) } else if let venue = map.venue { - input = .inputMediaVenue(geoPoint: Api.InputGeoPoint.inputGeoPoint(flags: geoFlags, lat: map.latitude, long: map.longitude, accuracyRadius: map.accuracyRadius.flatMap({ Int32($0) })), title: venue.title, address: venue.address ?? "", provider: venue.provider ?? "", venueId: venue.id ?? "", venueType: venue.type ?? "") + input = .inputMediaVenue(.init(geoPoint: Api.InputGeoPoint.inputGeoPoint(.init(flags: geoFlags, lat: map.latitude, long: map.longitude, accuracyRadius: map.accuracyRadius.flatMap({ Int32($0) }))), title: venue.title, address: venue.address ?? "", provider: venue.provider ?? "", venueId: venue.id ?? "", venueType: venue.type ?? "")) } else { - input = .inputMediaGeoPoint(geoPoint: Api.InputGeoPoint.inputGeoPoint(flags: geoFlags, lat: map.latitude, long: map.longitude, accuracyRadius: map.accuracyRadius.flatMap({ Int32($0) }))) + input = .inputMediaGeoPoint(.init(geoPoint: Api.InputGeoPoint.inputGeoPoint(.init(flags: geoFlags, lat: map.latitude, long: map.longitude, accuracyRadius: map.accuracyRadius.flatMap({ Int32($0) }))))) } return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(input, text), reuploadInfo: nil, cacheReferenceKey: nil))) } else if let poll = media as? TelegramMediaPoll { @@ -330,7 +330,7 @@ func mediaContentToUpload(accountPeerId: PeerId, network: Network, postbox: Post mappedSolutionEntities = apiTextAttributeEntities(TextEntitiesMessageAttribute(entities: solution.entities), associatedPeers: SimpleDictionary()) pollMediaFlags |= 1 << 1 } - let inputPoll = Api.InputMedia.inputMediaPoll(flags: pollMediaFlags, poll: Api.Poll.poll(id: 0, 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) + let inputPoll = Api.InputMedia.inputMediaPoll(.init(flags: pollMediaFlags, poll: Api.Poll.poll(.init(id: 0, 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)) return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(inputPoll, text), reuploadInfo: nil, cacheReferenceKey: nil))) } else if let todo = media as? TelegramMediaTodo { var flags: Int32 = 0 @@ -340,7 +340,7 @@ func mediaContentToUpload(accountPeerId: PeerId, network: Network, postbox: Post if todo.flags.contains(.othersCanComplete) { flags |= 1 << 1 } - let inputTodo = Api.InputMedia.inputMediaTodo(todo: .todoList(flags: flags, title: .textWithEntities(text: todo.text, entities: apiEntitiesFromMessageTextEntities(todo.textEntities, associatedPeers: SimpleDictionary())), list: todo.items.map { $0.apiItem })) + let inputTodo = Api.InputMedia.inputMediaTodo(.init(todo: .todoList(.init(flags: flags, title: .textWithEntities(.init(text: todo.text, entities: apiEntitiesFromMessageTextEntities(todo.textEntities, associatedPeers: SimpleDictionary()))), list: todo.items.map { $0.apiItem })))) return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(inputTodo, text), reuploadInfo: nil, cacheReferenceKey: nil))) } else if let dice = media as? TelegramMediaDice { if let tonAmount = dice.tonAmount { @@ -351,7 +351,7 @@ func mediaContentToUpload(accountPeerId: PeerId, network: Network, postbox: Post return postbox.transaction { transaction -> Signal in let gameInfo = currentEmojiGameInfo(transaction: transaction) if case let .available(info) = gameInfo { - let inputStakeDice = Api.InputMedia.inputMediaStakeDice(gameHash: info.gameHash, tonAmount: tonAmount, clientSeed: Buffer(buffer: clientSeed)) + let inputStakeDice = Api.InputMedia.inputMediaStakeDice(.init(gameHash: info.gameHash, tonAmount: tonAmount, clientSeed: Buffer(buffer: clientSeed))) return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(inputStakeDice, text), reuploadInfo: nil, cacheReferenceKey: nil))) } else { return .fail(.generic) @@ -360,7 +360,7 @@ func mediaContentToUpload(accountPeerId: PeerId, network: Network, postbox: Post |> castError(PendingMessageUploadError.self) |> switchToLatest } else { - let inputDice = Api.InputMedia.inputMediaDice(emoticon: dice.emoji) + let inputDice = Api.InputMedia.inputMediaDice(.init(emoticon: dice.emoji)) return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(inputDice, text), reuploadInfo: nil, cacheReferenceKey: nil))) } } else if let webPage = media as? TelegramMediaWebpage, case let .Loaded(content) = webPage.content { @@ -375,7 +375,7 @@ func mediaContentToUpload(accountPeerId: PeerId, network: Network, postbox: Post } } } - return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaWebPage(flags: flags, url: content.url), text), reuploadInfo: nil, cacheReferenceKey: nil))) + return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaWebPage(.init(flags: flags, url: content.url)), text), reuploadInfo: nil, cacheReferenceKey: nil))) } else { return nil } @@ -535,7 +535,7 @@ if "".isEmpty { } return .single(.progress(PendingMessageUploadedContentProgress(progress: 1.0))) |> then( - .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaPhoto(flags: flags, id: .inputPhoto(id: id, accessHash: accessHash, fileReference: Buffer(data: fileReference)), ttlSeconds: ttlSeconds), text), reuploadInfo: nil, cacheReferenceKey: nil))) + .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaPhoto(.init(flags: flags, id: .inputPhoto(.init(id: id, accessHash: accessHash, fileReference: Buffer(data: fileReference))), ttlSeconds: ttlSeconds)), text), reuploadInfo: nil, cacheReferenceKey: nil))) ) } referenceKey = key @@ -657,7 +657,7 @@ if "".isEmpty { var stickersValue: [Api.InputDocument] = [] for file in attribute.files { if let resource = file.resource as? CloudDocumentMediaResource, let fileReference = resource.fileReference { - stickersValue.append(Api.InputDocument.inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: fileReference))) + stickersValue.append(Api.InputDocument.inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: fileReference)))) } } if !stickersValue.isEmpty { @@ -676,14 +676,15 @@ if "".isEmpty { |> mapToSignal { inputPeer -> Signal in if let inputPeer = inputPeer { if autoclearMessageAttribute != nil { - return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaUploadedPhoto(flags: flags, file: file, stickers: stickers, ttlSeconds: ttlSeconds), text), reuploadInfo: nil, cacheReferenceKey: nil))) + return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaUploadedPhoto(.init(flags: flags, file: file, stickers: stickers, ttlSeconds: ttlSeconds)), text), reuploadInfo: nil, cacheReferenceKey: nil))) } - return network.request(Api.functions.messages.uploadMedia(flags: 0, businessConnectionId: nil, peer: inputPeer, media: Api.InputMedia.inputMediaUploadedPhoto(flags: flags, file: file, stickers: stickers, ttlSeconds: ttlSeconds))) + return network.request(Api.functions.messages.uploadMedia(flags: 0, businessConnectionId: nil, peer: inputPeer, media: Api.InputMedia.inputMediaUploadedPhoto(.init(flags: flags, file: file, stickers: stickers, ttlSeconds: ttlSeconds)))) |> mapError { _ -> PendingMessageUploadError in return .generic } |> mapToSignal { result -> Signal in switch result { - case let .messageMediaPhoto(_, photo, _): + case let .messageMediaPhoto(messageMediaPhotoData): + let photo = messageMediaPhotoData.photo if let photo = photo, let mediaImage = telegramMediaImageFromApiPhoto(photo), let reference = mediaImage.reference, case let .cloud(id, accessHash, maybeFileReference) = reference, let fileReference = maybeFileReference { var flags: Int32 = 0 var ttlSeconds: Int32? @@ -695,7 +696,7 @@ if "".isEmpty { flags |= 1 << 1 } - let result: PendingMessageUploadedContentResult = .content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaPhoto(flags: flags, id: .inputPhoto(id: id, accessHash: accessHash, fileReference: Buffer(data: fileReference)), ttlSeconds: ttlSeconds), text), reuploadInfo: nil, cacheReferenceKey: nil)) + let result: PendingMessageUploadedContentResult = .content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaPhoto(.init(flags: flags, id: .inputPhoto(.init(id: id, accessHash: accessHash, fileReference: Buffer(data: fileReference))), ttlSeconds: ttlSeconds)), text), reuploadInfo: nil, cacheReferenceKey: nil)) if let _ = ttlSeconds { return .single(result) } else { @@ -727,18 +728,18 @@ func inputDocumentAttributesFromFileAttributes(_ fileAttributes: [TelegramMediaF case .Animated: attributes.append(.documentAttributeAnimated) case let .FileName(fileName): - attributes.append(.documentAttributeFilename(fileName: fileName)) + attributes.append(.documentAttributeFilename(.init(fileName: fileName))) case let .ImageSize(size): - attributes.append(.documentAttributeImageSize(w: Int32(size.width), h: Int32(size.height))) + attributes.append(.documentAttributeImageSize(.init(w: Int32(size.width), h: Int32(size.height)))) case let .Sticker(displayText, packReference, maskCoords): var stickerSet: Api.InputStickerSet = .inputStickerSetEmpty var flags: Int32 = 0 if let packReference = packReference { switch packReference { case let .id(id, accessHash): - stickerSet = .inputStickerSetID(id: id, accessHash: accessHash) + stickerSet = .inputStickerSetID(.init(id: id, accessHash: accessHash)) case let .name(name): - stickerSet = .inputStickerSetShortName(shortName: name) + stickerSet = .inputStickerSetShortName(.init(shortName: name)) default: stickerSet = .inputStickerSetEmpty } @@ -746,9 +747,9 @@ func inputDocumentAttributesFromFileAttributes(_ fileAttributes: [TelegramMediaF var inputMaskCoords: Api.MaskCoords? if let maskCoords = maskCoords { flags |= 1 << 0 - inputMaskCoords = .maskCoords(n: maskCoords.n, x: maskCoords.x, y: maskCoords.y, zoom: maskCoords.zoom) + inputMaskCoords = .maskCoords(.init(n: maskCoords.n, x: maskCoords.x, y: maskCoords.y, zoom: maskCoords.zoom)) } - attributes.append(.documentAttributeSticker(flags: flags, alt: displayText, stickerset: stickerSet, maskCoords: inputMaskCoords)) + attributes.append(.documentAttributeSticker(.init(flags: flags, alt: displayText, stickerset: stickerSet, maskCoords: inputMaskCoords))) case .HasLinkedStickers: attributes.append(.documentAttributeHasStickers) case let .Video(duration, size, videoFlags, preloadSize, coverTime, videoCodec): @@ -771,7 +772,7 @@ func inputDocumentAttributesFromFileAttributes(_ fileAttributes: [TelegramMediaF if videoCodec != nil { flags |= (1 << 5) } - attributes.append(.documentAttributeVideo(flags: flags, duration: duration, w: Int32(size.width), h: Int32(size.height), preloadPrefixSize: preloadSize, videoStartTs: coverTime, videoCodec: videoCodec)) + attributes.append(.documentAttributeVideo(.init(flags: flags, duration: duration, w: Int32(size.width), h: Int32(size.height), preloadPrefixSize: preloadSize, videoStartTs: coverTime, videoCodec: videoCodec))) case let .Audio(isVoice, duration, title, performer, waveform): var flags: Int32 = 0 if isVoice { @@ -788,7 +789,7 @@ func inputDocumentAttributesFromFileAttributes(_ fileAttributes: [TelegramMediaF flags |= Int32(1 << 2) waveformBuffer = Buffer(data: waveform) } - attributes.append(.documentAttributeAudio(flags: flags, duration: Int32(duration), title: title, performer: performer, waveform: waveformBuffer)) + attributes.append(.documentAttributeAudio(.init(flags: flags, duration: Int32(duration), title: title, performer: performer, waveform: waveformBuffer))) case .hintFileIsLarge: break case .hintIsValidated: @@ -849,13 +850,15 @@ private func uploadedVideoCover(network: Network, postbox: Postbox, resourceRefe case .progress: return .complete() case let .inputFile(file): - return network.request(Api.functions.messages.uploadMedia(flags: 0, businessConnectionId: nil, peer: inputPeer, media: Api.InputMedia.inputMediaUploadedPhoto(flags: 0, file: file, stickers: [], ttlSeconds: nil))) + return network.request(Api.functions.messages.uploadMedia(flags: 0, businessConnectionId: nil, peer: inputPeer, media: Api.InputMedia.inputMediaUploadedPhoto(.init(flags: 0, file: file, stickers: [], ttlSeconds: nil)))) |> mapError { _ -> PendingMessageUploadError in return .generic } |> map { uploadResult in switch uploadResult { - case let .messageMediaPhoto(_, photo, _): - if case let .photo(_, id, accessHash, fileReference, _, _, _, _) = photo { - return .inputPhoto(id: id, accessHash: accessHash, fileReference: fileReference) + case let .messageMediaPhoto(messageMediaPhotoData): + let photo = messageMediaPhotoData.photo + if case let .photo(photoData) = photo { + let (id, accessHash, fileReference) = (photoData.id, photoData.accessHash, photoData.fileReference) + return .inputPhoto(.init(id: id, accessHash: accessHash, fileReference: fileReference)) } else { return .inputPhotoEmpty } @@ -947,7 +950,7 @@ private func uploadedMediaFileContent(network: Network, postbox: Postbox, auxili return .single(.progress(PendingMessageUploadedContentProgress(progress: 1.0))) |> then( - .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(Api.InputMedia.inputMediaDocument(flags: flags, id: Api.InputDocument.inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: fileReference)), videoCover: videoCoverPhoto, videoTimestamp: videoTimestamp, ttlSeconds: ttlSeconds, query: nil), text), reuploadInfo: nil, cacheReferenceKey: nil))) + .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(Api.InputMedia.inputMediaDocument(.init(flags: flags, id: Api.InputDocument.inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: fileReference))), videoCover: videoCoverPhoto, videoTimestamp: videoTimestamp, ttlSeconds: ttlSeconds, query: nil)), text), reuploadInfo: nil, cacheReferenceKey: nil))) ) } } @@ -1195,7 +1198,7 @@ private func uploadedMediaFileContent(network: Network, postbox: Postbox, auxili var stickersValue: [Api.InputDocument] = [] for file in attribute.files { if let resource = file.resource as? CloudDocumentMediaResource, let fileReference = resource.fileReference { - stickersValue.append(Api.InputDocument.inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: fileReference))) + stickersValue.append(Api.InputDocument.inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: fileReference)))) } } if !stickersValue.isEmpty { @@ -1211,11 +1214,11 @@ private func uploadedMediaFileContent(network: Network, postbox: Postbox, auxili } if ttlSeconds != nil { - return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaUploadedDocument(flags: flags, file: inputFile, thumb: thumbnailFile, mimeType: file.mimeType, attributes: inputDocumentAttributesFromFileAttributes(file.attributes), stickers: stickers, videoCover: videoCoverPhoto, videoTimestamp: videoTimestamp, ttlSeconds: ttlSeconds), text), reuploadInfo: nil, cacheReferenceKey: referenceKey))) + return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaUploadedDocument(.init(flags: flags, file: inputFile, thumb: thumbnailFile, mimeType: file.mimeType, attributes: inputDocumentAttributesFromFileAttributes(file.attributes), stickers: stickers, videoCover: videoCoverPhoto, videoTimestamp: videoTimestamp, ttlSeconds: ttlSeconds)), text), reuploadInfo: nil, cacheReferenceKey: referenceKey))) } - + if !isGrouped { - let resultInfo = PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaUploadedDocument(flags: flags, file: inputFile, thumb: thumbnailFile, mimeType: file.mimeType, attributes: inputDocumentAttributesFromFileAttributes(file.attributes), stickers: stickers, videoCover: videoCoverPhoto, videoTimestamp: videoTimestamp, ttlSeconds: ttlSeconds), text), reuploadInfo: nil, cacheReferenceKey: referenceKey) + let resultInfo = PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaUploadedDocument(.init(flags: flags, file: inputFile, thumb: thumbnailFile, mimeType: file.mimeType, attributes: inputDocumentAttributesFromFileAttributes(file.attributes), stickers: stickers, videoCover: videoCoverPhoto, videoTimestamp: videoTimestamp, ttlSeconds: ttlSeconds)), text), reuploadInfo: nil, cacheReferenceKey: referenceKey) return .single(.content(resultInfo)) } @@ -1226,11 +1229,12 @@ private func uploadedMediaFileContent(network: Network, postbox: Postbox, auxili |> mapError { _ -> PendingMessageUploadError in } |> mapToSignal { inputPeer -> Signal in if let inputPeer = inputPeer { - return network.request(Api.functions.messages.uploadMedia(flags: 0, businessConnectionId: nil, peer: inputPeer, media: .inputMediaUploadedDocument(flags: flags, file: inputFile, thumb: thumbnailFile, mimeType: file.mimeType, attributes: inputDocumentAttributesFromFileAttributes(file.attributes), stickers: stickers, videoCover: videoCoverPhoto, videoTimestamp: videoTimestamp, ttlSeconds: ttlSeconds))) + return network.request(Api.functions.messages.uploadMedia(flags: 0, businessConnectionId: nil, peer: inputPeer, media: .inputMediaUploadedDocument(.init(flags: flags, file: inputFile, thumb: thumbnailFile, mimeType: file.mimeType, attributes: inputDocumentAttributesFromFileAttributes(file.attributes), stickers: stickers, videoCover: videoCoverPhoto, videoTimestamp: videoTimestamp, ttlSeconds: ttlSeconds)))) |> mapError { _ -> PendingMessageUploadError in return .generic } |> mapToSignal { result -> Signal in switch result { - case let .messageMediaDocument(_, document, altDocuments, _, _, _): + case let .messageMediaDocument(messageMediaDocumentData): + let (document, altDocuments) = (messageMediaDocumentData.document, messageMediaDocumentData.altDocuments) if let document = document, let mediaFile = telegramMediaFileFromApiDocument(document, altDocuments: altDocuments), let resource = mediaFile.resource as? CloudDocumentMediaResource, let fileReference = resource.fileReference { var flags: Int32 = 0 var ttlSeconds: Int32? @@ -1248,7 +1252,7 @@ private func uploadedMediaFileContent(network: Network, postbox: Postbox, auxili flags |= (1 << 4) } - let result: PendingMessageUploadedContentResult = .content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaDocument(flags: flags, id: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: fileReference)), videoCover: videoCoverPhoto, videoTimestamp: videoTimestamp, ttlSeconds: ttlSeconds, query: nil), text), reuploadInfo: nil, cacheReferenceKey: nil)) + let result: PendingMessageUploadedContentResult = .content(PendingMessageUploadedContentAndReuploadInfo(content: .media(.inputMediaDocument(.init(flags: flags, id: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: fileReference))), videoCover: videoCoverPhoto, videoTimestamp: videoTimestamp, ttlSeconds: ttlSeconds, query: nil)), text), reuploadInfo: nil, cacheReferenceKey: nil)) if let _ = ttlSeconds { return .single(result) } else { diff --git a/submodules/TelegramCore/Sources/PendingMessages/RequestEditMessage.swift b/submodules/TelegramCore/Sources/PendingMessages/RequestEditMessage.swift index da41fcca..7df68a08 100644 --- a/submodules/TelegramCore/Sources/PendingMessages/RequestEditMessage.swift +++ b/submodules/TelegramCore/Sources/PendingMessages/RequestEditMessage.swift @@ -76,7 +76,7 @@ private func requestEditMessageInternal(accountPeerId: PeerId, postbox: Postbox, if todo.flags.contains(.othersCanComplete) { flags |= 1 << 1 } - let inputTodo = Api.InputMedia.inputMediaTodo(todo: .todoList(flags: flags, title: .textWithEntities(text: todo.text, entities: apiEntitiesFromMessageTextEntities(todo.textEntities, associatedPeers: SimpleDictionary())), list: todo.items.map { $0.apiItem })) + let inputTodo = Api.InputMedia.inputMediaTodo(.init(todo: .todoList(.init(flags: flags, title: .textWithEntities(.init(text: todo.text, entities: apiEntitiesFromMessageTextEntities(todo.textEntities, associatedPeers: SimpleDictionary()))), list: todo.items.map { $0.apiItem })))) uploadedMedia = .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: .media(inputTodo, text), reuploadInfo: nil, cacheReferenceKey: nil))) } else if let uploadSignal = generateUploadSignal(forceReupload) { @@ -234,10 +234,90 @@ private func requestEditMessageInternal(accountPeerId: PeerId, postbox: Postbox, } switch result { - case let .updates(updates, users, chats, _, _): + case let .updates(updatesData): + let (updates, users, chats) = (updatesData.updates, updatesData.users, updatesData.chats) for update in updates { switch update { - case .updateEditMessage(let message, _, _), .updateNewMessage(let message, _, _), .updateEditChannelMessage(let message, _, _), .updateNewChannelMessage(let message, _, _): + case .updateEditMessage(let data): + let message = data.message + let peers = AccumulatedPeers(transaction: transaction, chats: chats, users: users) + updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: peers) + + if let message = StoreMessage(apiMessage: message, accountPeerId: accountPeerId, peerIsForum: peer.isForumOrMonoForum), case let .Id(id) = message.id { + transaction.updateMessage(id, update: { previousMessage in + var updatedFlags = message.flags + var updatedLocalTags = message.localTags + if previousMessage.localTags.contains(.OutgoingLiveLocation) { + updatedLocalTags.insert(.OutgoingLiveLocation) + } + if previousMessage.flags.contains(.Incoming) { + updatedFlags.insert(.Incoming) + } else { + updatedFlags.remove(.Incoming) + } + + var updatedMedia = message.media + if let previousPaidContent = previousMessage.media.first(where: { $0 is TelegramMediaPaidContent }) as? TelegramMediaPaidContent, case .full = previousPaidContent.extendedMedia.first { + updatedMedia = previousMessage.media + } + + return .update(message.withUpdatedLocalTags(updatedLocalTags).withUpdatedFlags(updatedFlags).withUpdatedMedia(updatedMedia)) + }) + } + case .updateNewMessage(let data): + let message = data.message + let peers = AccumulatedPeers(transaction: transaction, chats: chats, users: users) + updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: peers) + + if let message = StoreMessage(apiMessage: message, accountPeerId: accountPeerId, peerIsForum: peer.isForumOrMonoForum), case let .Id(id) = message.id { + transaction.updateMessage(id, update: { previousMessage in + var updatedFlags = message.flags + var updatedLocalTags = message.localTags + if previousMessage.localTags.contains(.OutgoingLiveLocation) { + updatedLocalTags.insert(.OutgoingLiveLocation) + } + if previousMessage.flags.contains(.Incoming) { + updatedFlags.insert(.Incoming) + } else { + updatedFlags.remove(.Incoming) + } + + var updatedMedia = message.media + if let previousPaidContent = previousMessage.media.first(where: { $0 is TelegramMediaPaidContent }) as? TelegramMediaPaidContent, case .full = previousPaidContent.extendedMedia.first { + updatedMedia = previousMessage.media + } + + return .update(message.withUpdatedLocalTags(updatedLocalTags).withUpdatedFlags(updatedFlags).withUpdatedMedia(updatedMedia)) + }) + } + case .updateEditChannelMessage(let data): + let message = data.message + let peers = AccumulatedPeers(transaction: transaction, chats: chats, users: users) + updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: peers) + + if let message = StoreMessage(apiMessage: message, accountPeerId: accountPeerId, peerIsForum: peer.isForumOrMonoForum), case let .Id(id) = message.id { + transaction.updateMessage(id, update: { previousMessage in + var updatedFlags = message.flags + var updatedLocalTags = message.localTags + if previousMessage.localTags.contains(.OutgoingLiveLocation) { + updatedLocalTags.insert(.OutgoingLiveLocation) + } + if previousMessage.flags.contains(.Incoming) { + updatedFlags.insert(.Incoming) + } else { + updatedFlags.remove(.Incoming) + } + + var updatedMedia = message.media + if let previousPaidContent = previousMessage.media.first(where: { $0 is TelegramMediaPaidContent }) as? TelegramMediaPaidContent, case .full = previousPaidContent.extendedMedia.first { + updatedMedia = previousMessage.media + } + + return .update(message.withUpdatedLocalTags(updatedLocalTags).withUpdatedFlags(updatedFlags).withUpdatedMedia(updatedMedia)) + }) + } + case .updateNewChannelMessage(let data): + let message = data.message let peers = AccumulatedPeers(transaction: transaction, chats: chats, users: users) updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: peers) @@ -315,13 +395,13 @@ func _internal_requestEditLiveLocation(postbox: Postbox, network: Network, state if let _ = coordinate.accuracyRadius { geoFlags |= 1 << 0 } - inputGeoPoint = .inputGeoPoint(flags: geoFlags, lat: coordinate.latitude, long: coordinate.longitude, accuracyRadius: coordinate.accuracyRadius.flatMap({ Int32($0) })) + inputGeoPoint = .inputGeoPoint(.init(flags: geoFlags, lat: coordinate.latitude, long: coordinate.longitude, accuracyRadius: coordinate.accuracyRadius.flatMap({ Int32($0) }))) } else { var geoFlags: Int32 = 0 if let _ = media.accuracyRadius { geoFlags |= 1 << 0 } - inputGeoPoint = .inputGeoPoint(flags: geoFlags, lat: media.latitude, long: media.longitude, accuracyRadius: media.accuracyRadius.flatMap({ Int32($0) })) + inputGeoPoint = .inputGeoPoint(.init(flags: geoFlags, lat: media.latitude, long: media.longitude, accuracyRadius: media.accuracyRadius.flatMap({ Int32($0) }))) } if let _ = heading { flags |= 1 << 2 @@ -341,9 +421,9 @@ func _internal_requestEditLiveLocation(postbox: Postbox, network: Network, state period = liveBroadcastingTimeout } - inputMedia = .inputMediaGeoLive(flags: flags, geoPoint: inputGeoPoint, heading: heading, period: period, proximityNotificationRadius: proximityNotificationRadius) + inputMedia = .inputMediaGeoLive(.init(flags: flags, geoPoint: inputGeoPoint, heading: heading, period: period, proximityNotificationRadius: proximityNotificationRadius)) } else { - inputMedia = .inputMediaGeoLive(flags: 1 << 0, geoPoint: .inputGeoPoint(flags: 0, lat: media.latitude, long: media.longitude, accuracyRadius: nil), heading: nil, period: nil, proximityNotificationRadius: nil) + inputMedia = .inputMediaGeoLive(.init(flags: 1 << 0, geoPoint: .inputGeoPoint(.init(flags: 0, lat: media.latitude, long: media.longitude, accuracyRadius: nil)), heading: nil, period: nil, proximityNotificationRadius: nil)) } return network.request(Api.functions.messages.editMessage(flags: 1 << 14, peer: inputPeer, id: messageId.id, message: nil, media: inputMedia, replyMarkup: nil, entities: nil, scheduleDate: nil, scheduleRepeatPeriod: nil, quickReplyShortcutId: nil)) diff --git a/submodules/TelegramCore/Sources/PendingMessages/StandaloneSendMessage.swift b/submodules/TelegramCore/Sources/PendingMessages/StandaloneSendMessage.swift index c4a52df9..2a22aa54 100644 --- a/submodules/TelegramCore/Sources/PendingMessages/StandaloneSendMessage.swift +++ b/submodules/TelegramCore/Sources/PendingMessages/StandaloneSendMessage.swift @@ -445,14 +445,14 @@ private func sendUploadedMessageContent( if let _ = replyTodoItemId { replyFlags |= 1 << 6 } - replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: topMsgId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: monoforumPeerId, todoItemId: replyTodoItemId) + replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: topMsgId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: monoforumPeerId, todoItemId: replyTodoItemId)) } else if let replyToStoryId { if let inputPeer = transaction.getPeer(replyToStoryId.peerId).flatMap(apiInputPeer) { flags |= 1 << 0 - replyTo = .inputReplyToStory(peer: inputPeer, storyId: replyToStoryId.id) + replyTo = .inputReplyToStory(.init(peer: inputPeer, storyId: replyToStoryId.id)) } } else if let monoforumPeerId { - replyTo = .inputReplyToMonoForum(monoforumPeerId: monoforumPeerId) + replyTo = .inputReplyToMonoForum(.init(monoforumPeerId: monoforumPeerId)) } if suggestedPost != nil { @@ -479,11 +479,11 @@ private func sendUploadedMessageContent( if let _ = replyTodoItemId { replyFlags |= 1 << 6 } - replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: topMsgId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: monoforumPeerId, todoItemId: replyTodoItemId) + replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: topMsgId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: monoforumPeerId, todoItemId: replyTodoItemId)) } else if let replyToStoryId = replyToStoryId { if let inputPeer = transaction.getPeer(replyToStoryId.peerId).flatMap(apiInputPeer) { flags |= 1 << 0 - replyTo = .inputReplyToStory(peer: inputPeer, storyId: replyToStoryId.id) + replyTo = .inputReplyToStory(.init(peer: inputPeer, storyId: replyToStoryId.id)) } } @@ -520,33 +520,33 @@ private func sendUploadedMessageContent( if monoforumPeerId != nil { replyFlags |= 1 << 5 } - replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: topMsgId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: monoforumPeerId, todoItemId: nil) + replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: topMsgId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: monoforumPeerId, todoItemId: nil)) } else if let replyToStoryId = replyToStoryId { if let inputPeer = transaction.getPeer(replyToStoryId.peerId).flatMap(apiInputPeer) { flags |= 1 << 0 - replyTo = .inputReplyToStory(peer: inputPeer, storyId: replyToStoryId.id) + replyTo = .inputReplyToStory(.init(peer: inputPeer, storyId: replyToStoryId.id)) } } - + sendMessageRequest = network.request(Api.functions.messages.sendInlineBotResult(flags: flags, peer: inputPeer, replyTo: replyTo, randomId: uniqueId, queryId: chatContextResult.queryId, id: chatContextResult.id, scheduleDate: scheduleTime, sendAs: sendAsInputPeer, quickReplyShortcut: nil, allowPaidStars: allowPaidStars)) |> map(NetworkRequestResult.result) case .messageScreenshot: let replyTo: Api.InputReplyTo - + if let replyMessageId = replyMessageId { let replyFlags: Int32 = 0 - replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil) + replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil)) } else if let replyToStoryId = replyToStoryId { if let inputPeer = transaction.getPeer(replyToStoryId.peerId).flatMap(apiInputPeer) { flags |= 1 << 0 - replyTo = .inputReplyToStory(peer: inputPeer, storyId: replyToStoryId.id) + replyTo = .inputReplyToStory(.init(peer: inputPeer, storyId: replyToStoryId.id)) } else { let replyFlags: Int32 = 0 - replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: 0, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil) + replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: 0, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil)) } } else { let replyFlags: Int32 = 0 - replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: 0, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil) + replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: 0, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil)) } sendMessageRequest = network.request(Api.functions.messages.sendScreenshotNotification(peer: inputPeer, replyTo: replyTo, randomId: uniqueId)) @@ -698,19 +698,19 @@ private func sendMessageContent(account: Account, peerId: PeerId, attributes: [M var replyTo: Api.InputReplyTo? if let replyMessageId = replyMessageId { flags |= 1 << 0 - + let replyFlags: Int32 = 0 - replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil) + replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil)) } else if let replyToStoryId = replyToStoryId { if let inputPeer = transaction.getPeer(replyToStoryId.peerId).flatMap(apiInputPeer) { flags |= 1 << 0 - replyTo = .inputReplyToStory(peer: inputPeer, storyId: replyToStoryId.id) + replyTo = .inputReplyToStory(.init(peer: inputPeer, storyId: replyToStoryId.id)) } } else if let threadId { flags |= 1 << 0 - replyTo = .inputReplyToMessage(flags: flags, replyToMsgId: threadId, topMsgId: threadId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil) + replyTo = .inputReplyToMessage(.init(flags: flags, replyToMsgId: threadId, topMsgId: threadId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil)) } - + sendMessageRequest = account.network.request(Api.functions.messages.sendMessage(flags: flags, peer: inputPeer, replyTo: replyTo, message: text, randomId: uniqueId, replyMarkup: nil, entities: messageEntities, scheduleDate: scheduleTime, scheduleRepeatPeriod: scheduleRepeatPeriod, sendAs: sendAsInputPeer, quickReplyShortcut: nil, effect: nil, allowPaidStars: allowPaidStars, suggestedPost: nil)) |> `catch` { _ -> Signal in return .complete() @@ -719,17 +719,17 @@ private func sendMessageContent(account: Account, peerId: PeerId, attributes: [M var replyTo: Api.InputReplyTo? if let replyMessageId = replyMessageId { flags |= 1 << 0 - + let replyFlags: Int32 = 0 - replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil) + replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil)) } else if let replyToStoryId = replyToStoryId { if let inputPeer = transaction.getPeer(replyToStoryId.peerId).flatMap(apiInputPeer) { flags |= 1 << 0 - replyTo = .inputReplyToStory(peer: inputPeer, storyId: replyToStoryId.id) + replyTo = .inputReplyToStory(.init(peer: inputPeer, storyId: replyToStoryId.id)) } } else if let threadId { flags |= 1 << 0 - replyTo = .inputReplyToMessage(flags: flags, replyToMsgId: threadId, topMsgId: threadId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil) + replyTo = .inputReplyToMessage(.init(flags: flags, replyToMsgId: threadId, topMsgId: threadId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil)) } if suggestedPost != nil { @@ -765,8 +765,9 @@ private func uploadedImage(account: Account, data: Data) -> Signal mapError { _ -> StandaloneSendMessageError in return .generic } |> map { next -> UploadMediaEvent in switch next { - case let .inputFile(inputFile): - return .result(Api.InputMedia.inputMediaUploadedPhoto(flags: 0, file: inputFile, stickers: nil, ttlSeconds: nil)) + case let .inputFile(inputFileData): + let inputFile = inputFileData + return .result(Api.InputMedia.inputMediaUploadedPhoto(.init(flags: 0, file: inputFile, stickers: nil, ttlSeconds: nil))) case .inputSecretFile: preconditionFailure() case let .progress(progress): @@ -780,8 +781,9 @@ private func uploadedFile(account: Account, data: Data, mimeType: String, attrib |> mapError { _ -> PendingMessageUploadError in return .generic } |> map { next -> UploadMediaEvent in switch next { - case let .inputFile(inputFile): - return .result(Api.InputMedia.inputMediaUploadedDocument(flags: 0, file: inputFile, thumb: nil, mimeType: mimeType, attributes: inputDocumentAttributesFromFileAttributes(attributes), stickers: nil, videoCover: nil, videoTimestamp: nil, ttlSeconds: nil)) + case let .inputFile(inputFileData): + let inputFile = inputFileData + return .result(Api.InputMedia.inputMediaUploadedDocument(.init(flags: 0, file: inputFile, thumb: nil, mimeType: mimeType, attributes: inputDocumentAttributesFromFileAttributes(attributes), stickers: nil, videoCover: nil, videoTimestamp: nil, ttlSeconds: nil))) case .inputSecretFile: preconditionFailure() case let .progress(progress): diff --git a/submodules/TelegramCore/Sources/PendingMessages/StandaloneUploadedMedia.swift b/submodules/TelegramCore/Sources/PendingMessages/StandaloneUploadedMedia.swift index c10fa752..c6e7ffde 100644 --- a/submodules/TelegramCore/Sources/PendingMessages/StandaloneUploadedMedia.swift +++ b/submodules/TelegramCore/Sources/PendingMessages/StandaloneUploadedMedia.swift @@ -64,11 +64,12 @@ public func standaloneUploadedImage(postbox: Postbox, network: Network, peerId: |> mapError { _ -> StandaloneUploadMediaError in } |> mapToSignal { inputPeer -> Signal in if let inputPeer = inputPeer { - return network.request(Api.functions.messages.uploadMedia(flags: 0, businessConnectionId: nil, peer: inputPeer, media: Api.InputMedia.inputMediaUploadedPhoto(flags: 0, file: inputFile, stickers: nil, ttlSeconds: nil))) + return network.request(Api.functions.messages.uploadMedia(flags: 0, businessConnectionId: nil, peer: inputPeer, media: Api.InputMedia.inputMediaUploadedPhoto(.init(flags: 0, file: inputFile, stickers: nil, ttlSeconds: nil)))) |> mapError { _ -> StandaloneUploadMediaError in return .generic } |> mapToSignal { media -> Signal in switch media { - case let .messageMediaPhoto(_, photo, _): + case let .messageMediaPhoto(messageMediaPhotoData): + let photo = messageMediaPhotoData.photo if let photo = photo { if let mediaImage = telegramMediaImageFromApiPhoto(photo) { return .single(.result(.media(.standalone(media: mediaImage)))) @@ -86,7 +87,7 @@ public func standaloneUploadedImage(postbox: Postbox, network: Network, peerId: case let .inputSecretFile(file, _, key): return postbox.transaction { transaction -> Api.InputEncryptedChat? in if let peer = transaction.getPeer(peerId) as? TelegramSecretChat { - return Api.InputEncryptedChat.inputEncryptedChat(chatId: Int32(peer.id.id._internalGetInt64Value()), accessHash: peer.accessHash) + return Api.InputEncryptedChat.inputEncryptedChat(.init(chatId: Int32(peer.id.id._internalGetInt64Value()), accessHash: peer.accessHash)) } return nil } @@ -100,7 +101,8 @@ public func standaloneUploadedImage(postbox: Postbox, network: Network, peerId: } |> mapToSignal { result -> Signal in switch result { - case let .encryptedFile(id, accessHash, size, dcId, _): + case let .encryptedFile(encryptedFileData): + let (id, accessHash, size, dcId) = (encryptedFileData.id, encryptedFileData.accessHash, encryptedFileData.size, encryptedFileData.dcId) return .single(.result(.media(.standalone(media: TelegramMediaImage(imageId: MediaId(namespace: Namespaces.Media.LocalImage, id: Int64.random(in: Int64.min ... Int64.max)), representations: [TelegramMediaImageRepresentation(dimensions: dimensions, resource: SecretFileMediaResource(fileId: id, accessHash: accessHash, containerSize: size, decryptedSize: Int64(data.count), datacenterId: Int(dcId), key: key), progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false, isPersonal: false)], immediateThumbnailData: nil, reference: nil, partialReference: nil, flags: []))))) case .encryptedFileEmpty: return .fail(.generic) @@ -158,11 +160,12 @@ public func standaloneUploadedFile(postbox: Postbox, network: Network, peerId: P if let _ = thumbnailFile { flags |= 1 << 2 } - return network.request(Api.functions.messages.uploadMedia(flags: 0, businessConnectionId: nil, peer: inputPeer, media: Api.InputMedia.inputMediaUploadedDocument(flags: flags, file: inputFile, thumb: thumbnailFile, mimeType: mimeType, attributes: inputDocumentAttributesFromFileAttributes(attributes), stickers: nil, videoCover: nil, videoTimestamp: nil, ttlSeconds: nil))) + return network.request(Api.functions.messages.uploadMedia(flags: 0, businessConnectionId: nil, peer: inputPeer, media: Api.InputMedia.inputMediaUploadedDocument(.init(flags: flags, file: inputFile, thumb: thumbnailFile, mimeType: mimeType, attributes: inputDocumentAttributesFromFileAttributes(attributes), stickers: nil, videoCover: nil, videoTimestamp: nil, ttlSeconds: nil)))) |> mapError { _ -> StandaloneUploadMediaError in return .generic } |> mapToSignal { media -> Signal in switch media { - case let .messageMediaDocument(_, document, altDocuments, _, _, _): + case let .messageMediaDocument(messageMediaDocumentData): + let (document, altDocuments) = (messageMediaDocumentData.document, messageMediaDocumentData.altDocuments) if let document = document { if let mediaFile = telegramMediaFileFromApiDocument(document, altDocuments: altDocuments) { return .single(.result(.media(.standalone(media: mediaFile)))) @@ -180,7 +183,7 @@ public func standaloneUploadedFile(postbox: Postbox, network: Network, peerId: P case let .inputSecretFile(file, _, key): return postbox.transaction { transaction -> Api.InputEncryptedChat? in if let peer = transaction.getPeer(peerId) as? TelegramSecretChat { - return Api.InputEncryptedChat.inputEncryptedChat(chatId: Int32(peer.id.id._internalGetInt64Value()), accessHash: peer.accessHash) + return Api.InputEncryptedChat.inputEncryptedChat(.init(chatId: Int32(peer.id.id._internalGetInt64Value()), accessHash: peer.accessHash)) } return nil } @@ -193,7 +196,8 @@ public func standaloneUploadedFile(postbox: Postbox, network: Network, peerId: P |> mapError { _ -> StandaloneUploadMediaError in return .generic } |> mapToSignal { result -> Signal in switch result { - case let .encryptedFile(id, accessHash, size, dcId, _): + case let .encryptedFile(encryptedFileData): + let (id, accessHash, size, dcId) = (encryptedFileData.id, encryptedFileData.accessHash, encryptedFileData.size, encryptedFileData.dcId) let media = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: Int64.random(in: Int64.min ... Int64.max)), partialReference: nil, resource: SecretFileMediaResource(fileId: id, accessHash: accessHash, containerSize: size, decryptedSize: size, datacenterId: Int(dcId), key: key), previewRepresentations: [], videoThumbnails: [], immediateThumbnailData: nil, mimeType: mimeType, size: size, attributes: attributes, alternativeRepresentations: []) return .single(.result(.media(.standalone(media: media)))) diff --git a/submodules/TelegramCore/Sources/SecretChats/SecretChatEncryptionConfig.swift b/submodules/TelegramCore/Sources/SecretChats/SecretChatEncryptionConfig.swift index 934a4df8..22c0543a 100644 --- a/submodules/TelegramCore/Sources/SecretChats/SecretChatEncryptionConfig.swift +++ b/submodules/TelegramCore/Sources/SecretChats/SecretChatEncryptionConfig.swift @@ -10,7 +10,8 @@ func validatedEncryptionConfig(postbox: Postbox, network: Network) -> Signal retryRequest |> mapToSignal { result -> Signal in switch result { - case let .dhConfig(g, p, version, _): + case let .dhConfig(dhConfigData): + let (g, p, version) = (dhConfigData.g, dhConfigData.p, dhConfigData.version) if !MTCheckIsSafeG(UInt32(g)) { Logger.shared.log("SecretChatEncryptionConfig", "Invalid g") return .complete() @@ -26,7 +27,7 @@ func validatedEncryptionConfig(postbox: Postbox, network: Network) -> Signal Int64 { extension SecretChatIncomingEncryptedOperation { convenience init(message: Api.EncryptedMessage) { switch message { - case let .encryptedMessage(randomId, chatId, date, bytes, file): + case let .encryptedMessage(encryptedMessageData): + let (randomId, chatId, date, bytes, file) = (encryptedMessageData.randomId, encryptedMessageData.chatId, encryptedMessageData.date, encryptedMessageData.bytes, encryptedMessageData.file) self.init(peerId: PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt64Value(Int64(chatId))), globallyUniqueId: randomId, timestamp: date, type: .message, keyFingerprint: keyFingerprintFromBytes(bytes), contents: MemoryBuffer(bytes), mediaFileReference: SecretChatFileReference(file)) - case let .encryptedMessageService(randomId, chatId, date, bytes): + case let .encryptedMessageService(encryptedMessageServiceData): + let (randomId, chatId, date, bytes) = (encryptedMessageServiceData.randomId, encryptedMessageServiceData.chatId, encryptedMessageServiceData.date, encryptedMessageServiceData.bytes) self.init(peerId: PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt64Value(Int64(chatId))), globallyUniqueId: randomId, timestamp: date, type: .service, keyFingerprint: keyFingerprintFromBytes(bytes), contents: MemoryBuffer(bytes), mediaFileReference: nil) } } diff --git a/submodules/TelegramCore/Sources/SecretChats/SecretChatOutgoingOperation.swift b/submodules/TelegramCore/Sources/SecretChats/SecretChatOutgoingOperation.swift index 42f3c2ee..4cf56876 100644 --- a/submodules/TelegramCore/Sources/SecretChats/SecretChatOutgoingOperation.swift +++ b/submodules/TelegramCore/Sources/SecretChats/SecretChatOutgoingOperation.swift @@ -6,11 +6,14 @@ import TelegramApi extension SecretChatOutgoingFileReference { init?(_ apiFile: Api.InputEncryptedFile) { switch apiFile { - case let .inputEncryptedFile(id, accessHash): + case let .inputEncryptedFile(inputEncryptedFileData): + let (id, accessHash) = (inputEncryptedFileData.id, inputEncryptedFileData.accessHash) self = .remote(id: id, accessHash: accessHash) - case let .inputEncryptedFileBigUploaded(id, parts, keyFingerprint): + case let .inputEncryptedFileBigUploaded(inputEncryptedFileBigUploadedData): + let (id, parts, keyFingerprint) = (inputEncryptedFileBigUploadedData.id, inputEncryptedFileBigUploadedData.parts, inputEncryptedFileBigUploadedData.keyFingerprint) self = .uploadedLarge(id: id, partCount: parts, keyFingerprint: keyFingerprint) - case let .inputEncryptedFileUploaded(id, parts, md5Checksum, keyFingerprint): + case let .inputEncryptedFileUploaded(inputEncryptedFileUploadedData): + let (id, parts, md5Checksum, keyFingerprint) = (inputEncryptedFileUploadedData.id, inputEncryptedFileUploadedData.parts, inputEncryptedFileUploadedData.md5Checksum, inputEncryptedFileUploadedData.keyFingerprint) self = .uploadedRegular(id: id, partCount: parts, md5Digest: md5Checksum, keyFingerprint: keyFingerprint) case .inputEncryptedFileEmpty: return nil @@ -20,11 +23,11 @@ extension SecretChatOutgoingFileReference { var apiInputFile: Api.InputEncryptedFile { switch self { case let .remote(id, accessHash): - return .inputEncryptedFile(id: id, accessHash: accessHash) + return .inputEncryptedFile(.init(id: id, accessHash: accessHash)) case let .uploadedRegular(id, partCount, md5Digest, keyFingerprint): - return .inputEncryptedFileUploaded(id: id, parts: partCount, md5Checksum: md5Digest, keyFingerprint: keyFingerprint) + return .inputEncryptedFileUploaded(.init(id: id, parts: partCount, md5Checksum: md5Digest, keyFingerprint: keyFingerprint)) case let .uploadedLarge(id, partCount, keyFingerprint): - return .inputEncryptedFileBigUploaded(id: id, parts: partCount, keyFingerprint: keyFingerprint) + return .inputEncryptedFileBigUploaded(.init(id: id, parts: partCount, keyFingerprint: keyFingerprint)) } } } diff --git a/submodules/TelegramCore/Sources/SecretChats/SetSecretChatMessageAutoremoveTimeoutInteractively.swift b/submodules/TelegramCore/Sources/SecretChats/SetSecretChatMessageAutoremoveTimeoutInteractively.swift index 1474df55..8158f56e 100644 --- a/submodules/TelegramCore/Sources/SecretChats/SetSecretChatMessageAutoremoveTimeoutInteractively.swift +++ b/submodules/TelegramCore/Sources/SecretChats/SetSecretChatMessageAutoremoveTimeoutInteractively.swift @@ -26,6 +26,11 @@ func _internal_setSecretChatMessageAutoremoveTimeoutInteractively(transaction: T } func _internal_addSecretChatMessageScreenshot(account: Account, peerId: PeerId) -> Signal { + // MISC: Bypass screenshot notifications in secret chats when enabled + if MiscSettingsManager.shared.shouldBypassScreenshotProtection { + return .complete() + } + return account.postbox.transaction { transaction -> Void in if let _ = transaction.getPeer(peerId) as? TelegramSecretChat, let state = transaction.getPeerChatState(peerId) as? SecretChatState { switch state.embeddedState { diff --git a/submodules/TelegramCore/Sources/SecretChats/UpdateSecretChat.swift b/submodules/TelegramCore/Sources/SecretChats/UpdateSecretChat.swift index 27ba3f60..db39e639 100644 --- a/submodules/TelegramCore/Sources/SecretChats/UpdateSecretChat.swift +++ b/submodules/TelegramCore/Sources/SecretChats/UpdateSecretChat.swift @@ -17,7 +17,8 @@ func updateSecretChat(encryptionProvider: EncryptionProvider, accountPeerId: Pee let settings = transaction.getPreferencesEntry(key: PreferencesKeys.secretChatSettings)?.get(SecretChatSettings.self) ?? SecretChatSettings.defaultSettings assert((currentPeer == nil) == (currentState == nil)) switch chat { - case let .encryptedChat(_, _, _, adminId, _, gAOrB, _): + case let .encryptedChat(encryptedChatData): + let (adminId, gAOrB) = (encryptedChatData.adminId, encryptedChatData.gAOrB) if let currentPeer = currentPeer, let currentState = currentState, adminId == accountPeerId.id._internalGetInt64Value() { if case let .handshake(handshakeState) = currentState.embeddedState, case let .requested(_, p, a) = handshakeState { let pData = p.makeData() @@ -67,7 +68,8 @@ func updateSecretChat(encryptionProvider: EncryptionProvider, accountPeerId: Pee } else { Logger.shared.log("State", "got encryptedChat, but peer or state don't exist or account is not creator") } - case let .encryptedChatDiscarded(flags, _): + case let .encryptedChatDiscarded(encryptedChatDiscardedData): + let flags = encryptedChatDiscardedData.flags if let currentPeer = currentPeer, let currentState = currentState { let isRemoved = (flags & (1 << 0)) != 0 @@ -86,9 +88,10 @@ func updateSecretChat(encryptionProvider: EncryptionProvider, accountPeerId: Pee } else { Logger.shared.log("State", "got encryptedChatDiscarded, but peer doesn't exist") } - case .encryptedChatEmpty(_): + case .encryptedChatEmpty: break - case let .encryptedChatRequested(_, folderId, _, accessHash, date, adminId, participantId, gA): + case let .encryptedChatRequested(encryptedChatRequestedData): + let (folderId, accessHash, date, adminId, participantId, gA) = (encryptedChatRequestedData.folderId, encryptedChatRequestedData.accessHash, encryptedChatRequestedData.date, encryptedChatRequestedData.adminId, encryptedChatRequestedData.participantId, encryptedChatRequestedData.gA) if currentPeer == nil && participantId == accountPeerId.id._internalGetInt64Value() { if settings.acceptOnThisDevice { let state = SecretChatState(role: .participant, embeddedState: .handshake(.accepting), keychain: SecretChatKeychain(keys: []), keyFingerprint: nil, messageAutoremoveTimeout: nil) @@ -122,7 +125,8 @@ func updateSecretChat(encryptionProvider: EncryptionProvider, accountPeerId: Pee } else { Logger.shared.log("State", "got encryptedChatRequested, but peer already exists or this account is creator") } - case let .encryptedChatWaiting(_, accessHash, date, adminId, participantId): + case let .encryptedChatWaiting(encryptedChatWaitingData): + let (accessHash, date, adminId, participantId) = (encryptedChatWaitingData.accessHash, encryptedChatWaitingData.date, encryptedChatWaitingData.adminId, encryptedChatWaitingData.participantId) if let requestData = requestData, currentPeer == nil && adminId == accountPeerId.id._internalGetInt64Value() { let state = SecretChatState(role: .creator, embeddedState: .handshake(.requested(g: requestData.g, p: requestData.p, a: requestData.a)), keychain: SecretChatKeychain(keys: []), keyFingerprint: nil, messageAutoremoveTimeout: nil) let peer = TelegramSecretChat(id: chat.peerId, creationDate: date, regularPeerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(participantId)), accessHash: accessHash, role: state.role, embeddedState: state.embeddedState.peerState, messageAutoremoveTimeout: nil) diff --git a/submodules/TelegramCore/Sources/Settings/AutodownloadSettings.swift b/submodules/TelegramCore/Sources/Settings/AutodownloadSettings.swift index 93daeb39..803303a4 100644 --- a/submodules/TelegramCore/Sources/Settings/AutodownloadSettings.swift +++ b/submodules/TelegramCore/Sources/Settings/AutodownloadSettings.swift @@ -21,7 +21,8 @@ public func updateAutodownloadSettingsInteractively(accountManager: AccountManag extension AutodownloadPresetSettings { init(apiAutodownloadSettings: Api.AutoDownloadSettings) { switch apiAutodownloadSettings { - case let .autoDownloadSettings(flags, photoSizeMax, videoSizeMax, fileSizeMax, videoUploadMaxbitrate, _, _): + case let .autoDownloadSettings(autoDownloadSettingsData): + let (flags, photoSizeMax, videoSizeMax, fileSizeMax, videoUploadMaxbitrate, _, _) = (autoDownloadSettingsData.flags, autoDownloadSettingsData.photoSizeMax, autoDownloadSettingsData.videoSizeMax, autoDownloadSettingsData.fileSizeMax, autoDownloadSettingsData.videoUploadMaxbitrate, autoDownloadSettingsData.smallQueueActiveOperationsMax, autoDownloadSettingsData.largeQueueActiveOperationsMax) self.init(disabled: (flags & (1 << 0)) != 0, photoSizeMax: Int64(photoSizeMax), videoSizeMax: videoSizeMax, fileSizeMax: fileSizeMax, preloadLargeVideo: (flags & (1 << 1)) != 0, lessDataForPhoneCalls: (flags & (1 << 3)) != 0, videoUploadMaxbitrate: videoUploadMaxbitrate) } } @@ -30,7 +31,8 @@ extension AutodownloadPresetSettings { extension AutodownloadSettings { init(apiAutodownloadSettings: Api.account.AutoDownloadSettings) { switch apiAutodownloadSettings { - case let .autoDownloadSettings(low, medium, high): + case let .autoDownloadSettings(autoDownloadSettingsData): + let (low, medium, high) = (autoDownloadSettingsData.low, autoDownloadSettingsData.medium, autoDownloadSettingsData.high) self.init(lowPreset: AutodownloadPresetSettings(apiAutodownloadSettings: low), mediumPreset: AutodownloadPresetSettings(apiAutodownloadSettings: medium), highPreset: AutodownloadPresetSettings(apiAutodownloadSettings: high)) } } @@ -47,6 +49,6 @@ func apiAutodownloadPresetSettings(_ autodownloadPresetSettings: AutodownloadPre if autodownloadPresetSettings.lessDataForPhoneCalls { flags |= (1 << 3) } - return .autoDownloadSettings(flags: flags, photoSizeMax: Int32(autodownloadPresetSettings.photoSizeMax), videoSizeMax: autodownloadPresetSettings.videoSizeMax, fileSizeMax: autodownloadPresetSettings.fileSizeMax, videoUploadMaxbitrate: autodownloadPresetSettings.videoUploadMaxbitrate, smallQueueActiveOperationsMax: 0, largeQueueActiveOperationsMax: 0) + return .autoDownloadSettings(Api.AutoDownloadSettings.Cons_autoDownloadSettings(flags: flags, photoSizeMax: Int32(autodownloadPresetSettings.photoSizeMax), videoSizeMax: autodownloadPresetSettings.videoSizeMax, fileSizeMax: autodownloadPresetSettings.fileSizeMax, videoUploadMaxbitrate: autodownloadPresetSettings.videoUploadMaxbitrate, smallQueueActiveOperationsMax: 0, largeQueueActiveOperationsMax: 0)) } diff --git a/submodules/TelegramCore/Sources/Settings/ContentSettings.swift b/submodules/TelegramCore/Sources/Settings/ContentSettings.swift index 204fc799..6fb7fbcc 100644 --- a/submodules/TelegramCore/Sources/Settings/ContentSettings.swift +++ b/submodules/TelegramCore/Sources/Settings/ContentSettings.swift @@ -4,14 +4,16 @@ import TelegramApi import SwiftSignalKit public struct ContentSettings: Equatable { - public static var `default` = ContentSettings(ignoreContentRestrictionReasons: [], addContentRestrictionReasons: []) + public static var `default` = ContentSettings(ignoreContentRestrictionReasons: [], addContentRestrictionReasons: [], appConfiguration: AppConfiguration.defaultValue) public var ignoreContentRestrictionReasons: Set public var addContentRestrictionReasons: [String] + public var appConfiguration: AppConfiguration - public init(ignoreContentRestrictionReasons: Set, addContentRestrictionReasons: [String]) { + public init(ignoreContentRestrictionReasons: Set, addContentRestrictionReasons: [String], appConfiguration: AppConfiguration) { self.ignoreContentRestrictionReasons = ignoreContentRestrictionReasons self.addContentRestrictionReasons = addContentRestrictionReasons + self.appConfiguration = appConfiguration } } @@ -27,7 +29,9 @@ extension ContentSettings { addContentRestrictionReasons = addContentRestrictionReasonsData } } - self.init(ignoreContentRestrictionReasons: Set(reasons), addContentRestrictionReasons: addContentRestrictionReasons) + // MARK: Swiftgram + reasons += appConfiguration.sgWebSettings.user.expandedContentReasons() + self.init(ignoreContentRestrictionReasons: Set(reasons), addContentRestrictionReasons: addContentRestrictionReasons, appConfiguration: appConfiguration) } } @@ -61,7 +65,8 @@ public func contentSettingsConfiguration(network: Network) -> Signal map { result -> ContentSettingsConfiguration in switch result { - case let .contentSettings(flags): + case let .contentSettings(contentSettingsData): + let flags = contentSettingsData.flags return ContentSettingsConfiguration(sensitiveContentEnabled: (flags & (1 << 0)) != 0, canAdjustSensitiveContent: (flags & (1 << 1)) != 0) } } diff --git a/submodules/TelegramCore/Sources/Settings/GlobalNotificationSettings.swift b/submodules/TelegramCore/Sources/Settings/GlobalNotificationSettings.swift index 5503641a..0703514f 100644 --- a/submodules/TelegramCore/Sources/Settings/GlobalNotificationSettings.swift +++ b/submodules/TelegramCore/Sources/Settings/GlobalNotificationSettings.swift @@ -6,7 +6,8 @@ import TelegramApi extension MessageNotificationSettings { init(apiSettings: Api.PeerNotifySettings) { switch apiSettings { - case let .peerNotifySettings(_, showPreviews, _, muteUntil, iosSound, _, desktopSound, storiesMuted, storiesHideSender, storiesIosSound, _, storiesDesktopSound): + case let .peerNotifySettings(peerNotifySettingsData): + let (showPreviews, muteUntil, iosSound, desktopSound, storiesMuted, storiesHideSender, storiesIosSound, storiesDesktopSound) = (peerNotifySettingsData.showPreviews, peerNotifySettingsData.muteUntil, peerNotifySettingsData.iosSound, peerNotifySettingsData.otherSound, peerNotifySettingsData.storiesMuted, peerNotifySettingsData.storiesHideSender, peerNotifySettingsData.storiesIosSound, peerNotifySettingsData.storiesOtherSound) let sound: Api.NotificationSound? let storiesSound: Api.NotificationSound? #if os(iOS) diff --git a/submodules/TelegramCore/Sources/Settings/PeerContactSettings.swift b/submodules/TelegramCore/Sources/Settings/PeerContactSettings.swift index 52ff5d11..8b4d19f0 100644 --- a/submodules/TelegramCore/Sources/Settings/PeerContactSettings.swift +++ b/submodules/TelegramCore/Sources/Settings/PeerContactSettings.swift @@ -6,7 +6,8 @@ import SwiftSignalKit extension PeerStatusSettings { init(apiSettings: Api.PeerSettings) { switch apiSettings { - case let .peerSettings(flags, geoDistance, requestChatTitle, requestChatDate, businessBotId, businessBotManageUrl, chargePaidMessageStars, registrationMonth, phoneCountry, nameChangeDate, photoChangeDate): + case let .peerSettings(peerSettingsData): + let (flags, geoDistance, requestChatTitle, requestChatDate, businessBotId, businessBotManageUrl, chargePaidMessageStars, registrationMonth, phoneCountry, nameChangeDate, photoChangeDate) = (peerSettingsData.flags, peerSettingsData.geoDistance, peerSettingsData.requestChatTitle, peerSettingsData.requestChatDate, peerSettingsData.businessBotId, peerSettingsData.businessBotManageUrl, peerSettingsData.chargePaidMessageStars, peerSettingsData.registrationMonth, peerSettingsData.phoneCountry, peerSettingsData.nameChangeDate, peerSettingsData.photoChangeDate) var result = PeerStatusSettings.Flags() if (flags & (1 << 1)) != 0 { result.insert(.canAddContact) diff --git a/submodules/TelegramCore/Sources/Settings/PrivacySettings.swift b/submodules/TelegramCore/Sources/Settings/PrivacySettings.swift index 484c7810..e8495e3b 100644 --- a/submodules/TelegramCore/Sources/Settings/PrivacySettings.swift +++ b/submodules/TelegramCore/Sources/Settings/PrivacySettings.swift @@ -230,7 +230,8 @@ extension SelectivePrivacySettings { current = .enableEveryone(disableFor: [:]) case .privacyValueAllowContacts: current = .enableContacts(enableFor: [:], disableFor: [:], enableForPremium: false, enableForBots: false) - case let .privacyValueAllowUsers(users): + case let .privacyValueAllowUsers(privacyValueAllowUsersData): + let users = privacyValueAllowUsersData.users for id in users { if let peer = peers[PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(id))] { enableFor[peer.peer.id] = peer @@ -240,13 +241,15 @@ extension SelectivePrivacySettings { break case .privacyValueDisallowContacts: break - case let .privacyValueDisallowUsers(users): + case let .privacyValueDisallowUsers(privacyValueDisallowUsersData): + let users = privacyValueDisallowUsersData.users for id in users { if let peer = peers[PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(id))] { disableFor[peer.peer.id] = peer } } - case let .privacyValueAllowChatParticipants(chats): + case let .privacyValueAllowChatParticipants(privacyValueAllowChatParticipantsData): + let chats = privacyValueAllowChatParticipantsData.chats for id in chats { for possibleId in [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(id)), PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(id))] { if let peer = peers[possibleId] { @@ -254,7 +257,8 @@ extension SelectivePrivacySettings { } } } - case let .privacyValueDisallowChatParticipants(chats): + case let .privacyValueDisallowChatParticipants(privacyValueDisallowChatParticipantsData): + let chats = privacyValueDisallowChatParticipantsData.chats for id in chats { for possibleId in [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(id)), PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(id))] { if let peer = peers[possibleId] { @@ -337,7 +341,8 @@ extension TelegramDisallowedGifts { init(apiDisallowedGifts: Api.DisallowedGiftsSettings?) { var disallowedGifts: TelegramDisallowedGifts = [] switch apiDisallowedGifts { - case let .disallowedGiftsSettings(giftFlags): + case let .disallowedGiftsSettings(disallowedGiftsSettingsData): + let giftFlags = disallowedGiftsSettingsData.flags if (giftFlags & (1 << 0)) != 0 { disallowedGifts.insert(.unlimited) } diff --git a/submodules/TelegramCore/Sources/State/AccountState.swift b/submodules/TelegramCore/Sources/State/AccountState.swift index 844ad827..6d9572af 100644 --- a/submodules/TelegramCore/Sources/State/AccountState.swift +++ b/submodules/TelegramCore/Sources/State/AccountState.swift @@ -6,10 +6,12 @@ import TelegramApi extension UnauthorizedAccountTermsOfService { 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) @@ -20,27 +22,38 @@ extension UnauthorizedAccountTermsOfService { extension SentAuthorizationCodeType { init(apiType: Api.auth.SentCodeType) { switch apiType { - case let .sentCodeTypeApp(length): + case let .sentCodeTypeApp(sentCodeTypeAppData): + let length = sentCodeTypeAppData.length self = .otherSession(length: length) - case let .sentCodeTypeSms(length): + case let .sentCodeTypeSms(sentCodeTypeSmsData): + let length = sentCodeTypeSmsData.length self = .sms(length: length) - case let .sentCodeTypeCall(length): + case let .sentCodeTypeCall(sentCodeTypeCallData): + let length = sentCodeTypeCallData.length self = .call(length: length) - case let .sentCodeTypeFlashCall(pattern): + case let .sentCodeTypeFlashCall(sentCodeTypeFlashCallData): + let pattern = sentCodeTypeFlashCallData.pattern self = .flashCall(pattern: pattern) - case let .sentCodeTypeMissedCall(prefix, length): + case let .sentCodeTypeMissedCall(sentCodeTypeMissedCallData): + let (prefix, length) = (sentCodeTypeMissedCallData.prefix, sentCodeTypeMissedCallData.length) self = .missedCall(numberPrefix: prefix, length: length) - case let .sentCodeTypeEmailCode(flags, emailPattern, length, resetAvailablePeriod, resetPendingDate): + case let .sentCodeTypeEmailCode(sentCodeTypeEmailCodeData): + let (flags, emailPattern, length, resetAvailablePeriod, resetPendingDate) = (sentCodeTypeEmailCodeData.flags, sentCodeTypeEmailCodeData.emailPattern, sentCodeTypeEmailCodeData.length, sentCodeTypeEmailCodeData.resetAvailablePeriod, sentCodeTypeEmailCodeData.resetPendingDate) self = .email(emailPattern: emailPattern, length: length, resetAvailablePeriod: resetAvailablePeriod, resetPendingDate: resetPendingDate, appleSignInAllowed: (flags & (1 << 0)) != 0, setup: false) - case let .sentCodeTypeSetUpEmailRequired(flags): + case let .sentCodeTypeSetUpEmailRequired(sentCodeTypeSetUpEmailRequiredData): + let flags = sentCodeTypeSetUpEmailRequiredData.flags self = .emailSetupRequired(appleSignInAllowed: (flags & (1 << 0)) != 0) - case let .sentCodeTypeFragmentSms(url, length): + case let .sentCodeTypeFragmentSms(sentCodeTypeFragmentSmsData): + let (url, length) = (sentCodeTypeFragmentSmsData.url, sentCodeTypeFragmentSmsData.length) self = .fragment(url: url, length: length) - case let .sentCodeTypeFirebaseSms(_, _, _, _, _, pushTimeout, length): + case let .sentCodeTypeFirebaseSms(sentCodeTypeFirebaseSmsData): + let (pushTimeout, length) = (sentCodeTypeFirebaseSmsData.pushTimeout, sentCodeTypeFirebaseSmsData.length) self = .firebase(pushTimeout: pushTimeout, length: length) - case let .sentCodeTypeSmsWord(_, beginning): + case let .sentCodeTypeSmsWord(sentCodeTypeSmsWordData): + let beginning = sentCodeTypeSmsWordData.beginning self = .word(startsWith: beginning) - case let .sentCodeTypeSmsPhrase(_, beginning): + case let .sentCodeTypeSmsPhrase(sentCodeTypeSmsPhraseData): + let beginning = sentCodeTypeSmsPhraseData.beginning self = .phrase(startsWith: beginning) } } diff --git a/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift b/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift index 5215a042..a4dcec95 100644 --- a/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift +++ b/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift @@ -112,28 +112,29 @@ private func peerIdsRequiringLocalChatStateFromUpdates(_ updates: [Api.Update]) peerIds.insert(messageId.peerId) } switch update { - case let .updateChannelTooLong(_, channelId, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) + case let .updateChannelTooLong(updateChannelTooLongData): + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(updateChannelTooLongData.channelId)) peerIds.insert(peerId) - case let .updatePinnedForumTopics(_, peerId, order): - if order == nil { - peerIds.insert(peerId.peerId) + case let .updatePinnedForumTopics(updatePinnedForumTopicsData): + if updatePinnedForumTopicsData.order == nil { + peerIds.insert(updatePinnedForumTopicsData.peer.peerId) } - case let .updateFolderPeers(folderPeers, _, _): - for peer in folderPeers { + case let .updateFolderPeers(updateFolderPeersData): + for peer in updateFolderPeersData.folderPeers { switch peer { - case let .folderPeer(peer, _): + case let .folderPeer(folderPeerData): + let peer = folderPeerData.peer peerIds.insert(peer.peerId) } } - case let .updateReadChannelInbox(_, _, channelId, _, _, _): - peerIds.insert(PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))) - case let .updateReadHistoryInbox(_, _, peer, _, _, _, _, _): - peerIds.insert(peer.peerId) - case let .updateDraftMessage(_, peer, _, _, draft): - switch draft { + case let .updateReadChannelInbox(updateReadChannelInboxData): + peerIds.insert(PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(updateReadChannelInboxData.channelId))) + case let .updateReadHistoryInbox(updateReadHistoryInboxData): + peerIds.insert(updateReadHistoryInboxData.peer.peerId) + case let .updateDraftMessage(updateDraftMessageData): + switch updateDraftMessageData.draft { case .draftMessage: - peerIds.insert(peer.peerId) + peerIds.insert(updateDraftMessageData.peer.peerId) case .draftMessageEmpty: break } @@ -153,8 +154,8 @@ private func peerIdsRequiringLocalChatStateFromUpdateGroups(_ groups: [UpdateGro var channelUpdates = Set() for update in group.updates { switch update { - case let .updateChannel(channelId): - channelUpdates.insert(PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))) + case let .updateChannel(updateChannelData): + channelUpdates.insert(PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(updateChannelData.channelId))) default: break } @@ -185,8 +186,8 @@ private func locallyGeneratedMessageTimestampsFromUpdateGroups(_ groups: [Update for group in groups { for update in group.updates { switch update { - case let .updateServiceNotification(_, date, _, _, _, _): - if let date = date { + case let .updateServiceNotification(updateServiceNotificationData): + if let date = updateServiceNotificationData.inboxDate { let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(777000)) if messageTimestamps[peerId] == nil { messageTimestamps[peerId] = [(Namespaces.Message.Local, date)] @@ -221,7 +222,8 @@ private func peerIdsFromDifference(_ difference: Api.updates.Difference) -> Set< var peerIds = Set() switch difference { - case let .difference(newMessages, _, otherUpdates, chats, users, _): + case let .difference(differenceData): + let (newMessages, _, otherUpdates, chats, users, _) = (differenceData.newMessages, differenceData.newEncryptedMessages, differenceData.otherUpdates, differenceData.chats, differenceData.users, differenceData.state) for message in newMessages { for peerId in apiMessagePeerIds(message) { peerIds.insert(peerId) @@ -240,7 +242,8 @@ private func peerIdsFromDifference(_ difference: Api.updates.Difference) -> Set< } case .differenceEmpty: break - case let .differenceSlice(newMessages, _, otherUpdates, chats, users, _): + case let .differenceSlice(differenceSliceData): + let (newMessages, _, otherUpdates, chats, users, _) = (differenceSliceData.newMessages, differenceSliceData.newEncryptedMessages, differenceSliceData.otherUpdates, differenceSliceData.chats, differenceSliceData.users, differenceSliceData.intermediateState) for message in newMessages { for peerId in apiMessagePeerIds(message) { peerIds.insert(peerId) @@ -270,11 +273,13 @@ private func activeChannelsFromDifference(_ difference: Api.updates.Difference) var chats: [Api.Chat] = [] switch difference { - case let .difference(_, _, _, differenceChats, _, _): + case let .difference(differenceData): + let (_, _, _, differenceChats, _, _) = (differenceData.newMessages, differenceData.newEncryptedMessages, differenceData.otherUpdates, differenceData.chats, differenceData.users, differenceData.state) chats = differenceChats case .differenceEmpty: break - case let .differenceSlice(_, _, _, differenceChats, _, _): + case let .differenceSlice(differenceSliceData): + let (_, _, _, differenceChats, _, _) = (differenceSliceData.newMessages, differenceSliceData.newEncryptedMessages, differenceSliceData.otherUpdates, differenceSliceData.chats, differenceSliceData.users, differenceSliceData.intermediateState) chats = differenceChats case .differenceTooLong: break @@ -301,7 +306,8 @@ private func associatedMessageIdsFromDifference(_ difference: Api.updates.Differ var generalIds = Set() switch difference { - case let .difference(newMessages, _, otherUpdates, _, _, _): + case let .difference(differenceData): + let (newMessages, _, otherUpdates, _, _, _) = (differenceData.newMessages, differenceData.newEncryptedMessages, differenceData.otherUpdates, differenceData.chats, differenceData.users, differenceData.state) for message in newMessages { if let associatedMessageIds = apiMessageAssociatedMessageIds(message) { replyIds.formUnion(associatedMessageIds.replyIds) @@ -316,14 +322,15 @@ private func associatedMessageIdsFromDifference(_ difference: Api.updates.Differ } case .differenceEmpty: break - case let .differenceSlice(newMessages, _, otherUpdates, _, _, _): + case let .differenceSlice(differenceSliceData): + let (newMessages, _, otherUpdates, _, _, _) = (differenceSliceData.newMessages, differenceSliceData.newEncryptedMessages, differenceSliceData.otherUpdates, differenceSliceData.chats, differenceSliceData.users, differenceSliceData.intermediateState) for message in newMessages { if let associatedMessageIds = apiMessageAssociatedMessageIds(message) { replyIds.formUnion(associatedMessageIds.replyIds) generalIds.formUnion(associatedMessageIds.generalIds) } } - + for update in otherUpdates { if let associatedMessageIds = update.associatedMessageIds { replyIds.formUnion(associatedMessageIds.replyIds) @@ -333,7 +340,7 @@ private func associatedMessageIdsFromDifference(_ difference: Api.updates.Differ case .differenceTooLong: break } - + return (replyIds, generalIds) } @@ -341,7 +348,8 @@ private func peerIdsRequiringLocalChatStateFromDifference(_ difference: Api.upda var peerIds = Set() switch difference { - case let .difference(newMessages, _, otherUpdates, _, _, _): + case let .difference(differenceData): + let (newMessages, _, otherUpdates, _, _, _) = (differenceData.newMessages, differenceData.newEncryptedMessages, differenceData.otherUpdates, differenceData.chats, differenceData.users, differenceData.state) for message in newMessages { if let messageId = message.id() { peerIds.insert(messageId.peerId) @@ -353,12 +361,12 @@ private func peerIdsRequiringLocalChatStateFromDifference(_ difference: Api.upda peerIds.insert(messageId.peerId) } switch update { - case let .updateChannelTooLong(_, channelId, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) + case let .updateChannelTooLong(updateChannelTooLongData): + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(updateChannelTooLongData.channelId)) peerIds.insert(peerId) - case let .updatePinnedForumTopics(_, peerId, order): - if order == nil { - peerIds.insert(peerId.peerId) + case let .updatePinnedForumTopics(updatePinnedForumTopicsData): + if updatePinnedForumTopicsData.order == nil { + peerIds.insert(updatePinnedForumTopicsData.peer.peerId) } default: break @@ -366,25 +374,26 @@ private func peerIdsRequiringLocalChatStateFromDifference(_ difference: Api.upda } case .differenceEmpty: break - case let .differenceSlice(newMessages, _, otherUpdates, _, _, _): + case let .differenceSlice(differenceSliceData): + let (newMessages, _, otherUpdates, _, _, _) = (differenceSliceData.newMessages, differenceSliceData.newEncryptedMessages, differenceSliceData.otherUpdates, differenceSliceData.chats, differenceSliceData.users, differenceSliceData.intermediateState) for message in newMessages { if let messageId = message.id() { peerIds.insert(messageId.peerId) } } - + peerIds.formUnion(peerIdsRequiringLocalChatStateFromUpdates(otherUpdates)) for update in otherUpdates { if let messageId = update.messageId { peerIds.insert(messageId.peerId) } switch update { - case let .updateChannelTooLong(_, channelId, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) + case let .updateChannelTooLong(updateChannelTooLongData): + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(updateChannelTooLongData.channelId)) peerIds.insert(peerId) - case let .updatePinnedForumTopics(_, peerId, order): - if order == nil { - peerIds.insert(peerId.peerId) + case let .updatePinnedForumTopics(updatePinnedForumTopicsData): + if updatePinnedForumTopicsData.order == nil { + peerIds.insert(updatePinnedForumTopicsData.peer.peerId) } default: break @@ -402,11 +411,13 @@ private func locallyGeneratedMessageTimestampsFromDifference(_ difference: Api.u var otherUpdates: [Api.Update]? switch difference { - case let .difference(_, _, apiOtherUpdates, _, _, _): + case let .difference(differenceData): + let (_, _, apiOtherUpdates, _, _, _) = (differenceData.newMessages, differenceData.newEncryptedMessages, differenceData.otherUpdates, differenceData.chats, differenceData.users, differenceData.state) otherUpdates = apiOtherUpdates case .differenceEmpty: break - case let .differenceSlice(_, _, apiOtherUpdates, _, _, _): + case let .differenceSlice(differenceSliceData): + let (_, _, apiOtherUpdates, _, _, _) = (differenceSliceData.newMessages, differenceSliceData.newEncryptedMessages, differenceSliceData.otherUpdates, differenceSliceData.chats, differenceSliceData.users, differenceSliceData.intermediateState) otherUpdates = apiOtherUpdates case .differenceTooLong: break @@ -415,8 +426,8 @@ private func locallyGeneratedMessageTimestampsFromDifference(_ difference: Api.u if let otherUpdates = otherUpdates { for update in otherUpdates { switch update { - case let .updateServiceNotification(_, date, _, _, _, _): - if let date = date { + case let .updateServiceNotification(updateServiceNotificationData): + if let date = updateServiceNotificationData.inboxDate { let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(777000)) if messageTimestamps[peerId] == nil { messageTimestamps[peerId] = [(Namespaces.Message.Local, date)] @@ -673,7 +684,7 @@ func finalStateWithUpdateGroups(accountPeerId: PeerId, postbox: Postbox, network } for case let .updateChannelPts(channelId, pts, ptsCount) in groups { - collectedUpdates.append(Api.Update.updateDeleteChannelMessages(channelId: channelId, messages: [], pts: pts, ptsCount: ptsCount)) + collectedUpdates.append(Api.Update.updateDeleteChannelMessages(.init(channelId: channelId, messages: [], pts: pts, ptsCount: ptsCount))) } return finalStateWithUpdates(accountPeerId: accountPeerId, postbox: postbox, network: network, state: updatedState, updates: collectedUpdates, shouldPoll: hadReset, missingUpdates: !ptsUpdatesAfterHole.isEmpty || !qtsUpdatesAfterHole.isEmpty || !seqGroupsAfterHole.isEmpty, shouldResetChannels: false, updatesDate: updatesDate, asyncResetChannels: asyncResetChannels) @@ -689,26 +700,31 @@ func finalStateWithDifference(accountPeerId: PeerId, postbox: Postbox, network: var users: [Api.User] = [] switch difference { - case let .difference(newMessages, newEncryptedMessages, otherUpdates, apiChats, apiUsers, apiState): + case let .difference(differenceData): + let (newMessages, newEncryptedMessages, otherUpdates, apiChats, apiUsers, apiState) = (differenceData.newMessages, differenceData.newEncryptedMessages, differenceData.otherUpdates, differenceData.chats, differenceData.users, differenceData.state) messages = newMessages encryptedMessages = newEncryptedMessages updates = otherUpdates chats = apiChats users = apiUsers switch apiState { - case let .state(pts, qts, date, seq, _): + case let .state(stateData): + let (pts, qts, date, seq, _) = (stateData.pts, stateData.qts, stateData.date, stateData.seq, stateData.unreadCount) updatedState.updateState(AuthorizedAccountState.State(pts: pts, qts: qts, date: date, seq: seq)) } - case let .differenceEmpty(date, seq): + case let .differenceEmpty(differenceEmptyData): + let (date, seq) = (differenceEmptyData.date, differenceEmptyData.seq) updatedState.updateState(AuthorizedAccountState.State(pts: updatedState.state.pts, qts: updatedState.state.qts, date: date, seq: seq)) - case let .differenceSlice(newMessages, newEncryptedMessages, otherUpdates, apiChats, apiUsers, apiState): + case let .differenceSlice(differenceSliceData): + let (newMessages, newEncryptedMessages, otherUpdates, apiChats, apiUsers, apiState) = (differenceSliceData.newMessages, differenceSliceData.newEncryptedMessages, differenceSliceData.otherUpdates, differenceSliceData.chats, differenceSliceData.users, differenceSliceData.intermediateState) messages = newMessages encryptedMessages = newEncryptedMessages updates = otherUpdates chats = apiChats users = apiUsers switch apiState { - case let .state(pts, qts, date, seq, _): + case let .state(stateData): + let (pts, qts, date, seq, _) = (stateData.pts, stateData.qts, stateData.date, stateData.seq, stateData.unreadCount) updatedState.updateState(AuthorizedAccountState.State(pts: pts, qts: qts, date: date, seq: seq)) } case .differenceTooLong: @@ -757,43 +773,43 @@ private func sortedUpdates(_ updates: [Api.Update]) -> [Api.Update] { for update in updates { switch update { - case let .updateChannelTooLong(_, channelId, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) + case let .updateChannelTooLong(updateChannelTooLongData): + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(updateChannelTooLongData.channelId)) if updatesByChannel[peerId] == nil { updatesByChannel[peerId] = [update] } else { updatesByChannel[peerId]!.append(update) } - case let .updatePinnedForumTopic(_, peerId, _): - let peerId = peerId.peerId + case let .updatePinnedForumTopic(updatePinnedForumTopicData): + let peerId = updatePinnedForumTopicData.peer.peerId if updatesByChannel[peerId] == nil { updatesByChannel[peerId] = [update] } else { updatesByChannel[peerId]!.append(update) } - case let .updatePinnedForumTopics(_, peerId, _): - let peerId = peerId.peerId + case let .updatePinnedForumTopics(updatePinnedForumTopicsData): + let peerId = updatePinnedForumTopicsData.peer.peerId if updatesByChannel[peerId] == nil { updatesByChannel[peerId] = [update] } else { updatesByChannel[peerId]!.append(update) } - case let .updateDeleteChannelMessages(channelId, _, _, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) + case let .updateDeleteChannelMessages(updateDeleteChannelMessagesData): + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(updateDeleteChannelMessagesData.channelId)) if updatesByChannel[peerId] == nil { updatesByChannel[peerId] = [update] } else { updatesByChannel[peerId]!.append(update) } - case let .updatePinnedChannelMessages(_, channelId, _, _, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) + case let .updatePinnedChannelMessages(updatePinnedChannelMessagesData): + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(updatePinnedChannelMessagesData.channelId)) if updatesByChannel[peerId] == nil { updatesByChannel[peerId] = [update] } else { updatesByChannel[peerId]!.append(update) } - case let .updateNewChannelMessage(message, _, _): - if let peerId = apiMessagePeerId(message) { + case let .updateNewChannelMessage(updateNewChannelMessageData): + if let peerId = apiMessagePeerId(updateNewChannelMessageData.message) { if updatesByChannel[peerId] == nil { updatesByChannel[peerId] = [update] } else { @@ -802,8 +818,8 @@ private func sortedUpdates(_ updates: [Api.Update]) -> [Api.Update] { } else { otherUpdates.append(update) } - case let .updateEditChannelMessage(message, _, _): - if let peerId = apiMessagePeerId(message) { + case let .updateEditChannelMessage(updateEditChannelMessageData): + if let peerId = apiMessagePeerId(updateEditChannelMessageData.message) { if updatesByChannel[peerId] == nil { updatesByChannel[peerId] = [update] } else { @@ -812,15 +828,15 @@ private func sortedUpdates(_ updates: [Api.Update]) -> [Api.Update] { } else { otherUpdates.append(update) } - case let .updateChannelWebPage(channelId, _, _, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) + case let .updateChannelWebPage(updateChannelWebPageData): + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(updateChannelWebPageData.channelId)) if updatesByChannel[peerId] == nil { updatesByChannel[peerId] = [update] } else { updatesByChannel[peerId]!.append(update) } - case let .updateChannelAvailableMessages(channelId, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) + case let .updateChannelAvailableMessages(updateChannelAvailableMessagesData): + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(updateChannelAvailableMessagesData.channelId)) if updatesByChannel[peerId] == nil { updatesByChannel[peerId] = [update] } else { @@ -839,31 +855,31 @@ private func sortedUpdates(_ updates: [Api.Update]) -> [Api.Update] { var rhsPts: Int32? switch lhs { - case let .updateDeleteChannelMessages(_, _, pts, _): - lhsPts = pts - case let .updateNewChannelMessage(_, pts, _): - lhsPts = pts - case let .updateChannelWebPage(_, _, pts, _): - lhsPts = pts - case let .updateEditChannelMessage(_, pts, _): - lhsPts = pts - case let .updatePinnedChannelMessages(_, _, _, pts, _): - lhsPts = pts + case let .updateDeleteChannelMessages(updateDeleteChannelMessagesData): + lhsPts = updateDeleteChannelMessagesData.pts + case let .updateNewChannelMessage(updateNewChannelMessageData): + lhsPts = updateNewChannelMessageData.pts + case let .updateChannelWebPage(updateChannelWebPageData): + lhsPts = updateChannelWebPageData.pts + case let .updateEditChannelMessage(updateEditChannelMessageData): + lhsPts = updateEditChannelMessageData.pts + case let .updatePinnedChannelMessages(updatePinnedChannelMessagesData): + lhsPts = updatePinnedChannelMessagesData.pts default: break } switch rhs { - case let .updateDeleteChannelMessages(_, _, pts, _): - rhsPts = pts - case let .updateNewChannelMessage(_, pts, _): - rhsPts = pts - case let .updateChannelWebPage(_, _, pts, _): - rhsPts = pts - case let .updateEditChannelMessage(_, pts, _): - rhsPts = pts - case let .updatePinnedChannelMessages(_, _, _, pts, _): - rhsPts = pts + case let .updateDeleteChannelMessages(updateDeleteChannelMessagesData): + rhsPts = updateDeleteChannelMessagesData.pts + case let .updateNewChannelMessage(updateNewChannelMessageData): + rhsPts = updateNewChannelMessageData.pts + case let .updateChannelWebPage(updateChannelWebPageData): + rhsPts = updateChannelWebPageData.pts + case let .updateEditChannelMessage(updateEditChannelMessageData): + rhsPts = updateEditChannelMessageData.pts + case let .updatePinnedChannelMessages(updatePinnedChannelMessagesData): + rhsPts = updatePinnedChannelMessagesData.pts default: break } @@ -910,7 +926,8 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: for update in sortedUpdates(updates) { switch update { - case let .updateChannelTooLong(_, channelId, channelPts): + case let .updateChannelTooLong(updateChannelTooLongData): + let (channelId, channelPts) = (updateChannelTooLongData.channelId, updateChannelTooLongData.pts) let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) if case .none = channelsToPoll[peerId] { if let channelPts = channelPts, let channelState = state.channelStates[peerId], channelState.pts >= channelPts { @@ -919,16 +936,17 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: channelsToPoll[peerId] = channelPts } } - case let .updatePinnedForumTopics(_, peerId, order): - if let order = order { - updatedState.addUpdatePinnedTopicOrder(peerId: peerId.peerId, threadIds: order.map(Int64.init)) + case let .updatePinnedForumTopics(updatePinnedForumTopicsData): + if let order = updatePinnedForumTopicsData.order { + updatedState.addUpdatePinnedTopicOrder(peerId: updatePinnedForumTopicsData.peer.peerId, threadIds: order.map(Int64.init)) } else { - let peerId = peerId.peerId + let peerId = updatePinnedForumTopicsData.peer.peerId if case .none = channelsToPoll[peerId] { channelsToPoll[peerId] = nil } } - case let .updateDeleteChannelMessages(channelId, messages, pts: pts, ptsCount): + case let .updateDeleteChannelMessages(updateDeleteChannelMessagesData): + let (channelId, messages, pts: pts, ptsCount) = (updateDeleteChannelMessagesData.channelId, updateDeleteChannelMessagesData.messages, updateDeleteChannelMessagesData.pts, updateDeleteChannelMessagesData.ptsCount) let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) if let previousState = updatedState.channelStates[peerId] { if previousState.pts >= pts { @@ -948,7 +966,8 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: channelsToPoll[peerId] = nil } } - case let .updateEditChannelMessage(apiMessage, pts, ptsCount): + case let .updateEditChannelMessage(updateEditChannelMessageData): + let (apiMessage, pts, ptsCount) = (updateEditChannelMessageData.message, updateEditChannelMessageData.pts, updateEditChannelMessageData.ptsCount) var peerIsForum = false if let peerId = apiMessage.peerId { peerIsForum = updatedState.isPeerForum(peerId: peerId) @@ -988,13 +1007,15 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: } else { Logger.shared.log("State", "Invalid updateEditChannelMessage") } - case let .updateChannelWebPage(channelId, apiWebpage, pts, ptsCount): + case let .updateChannelWebPage(updateChannelWebPageData): + let (channelId, apiWebpage, pts, ptsCount) = (updateChannelWebPageData.channelId, updateChannelWebPageData.webpage, updateChannelWebPageData.pts, updateChannelWebPageData.ptsCount) let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) if let previousState = updatedState.channelStates[peerId] { if previousState.pts >= pts { } else if previousState.pts + ptsCount == pts { switch apiWebpage { - case let .webPageEmpty(flags, id, url): + case let .webPageEmpty(webPageEmptyData): + let (flags, id, url) = (webPageEmptyData.flags, webPageEmptyData.id, webPageEmptyData.url) let _ = flags let _ = url updatedState.updateMedia(MediaId(namespace: Namespaces.Media.CloudWebpage, id: id), media: nil) @@ -1016,19 +1037,20 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: channelsToPoll[peerId] = nil } } - case let .updateChannelAvailableMessages(channelId, minId): + case let .updateChannelAvailableMessages(updateChannelAvailableMessagesData): + let (channelId, minId) = (updateChannelAvailableMessagesData.channelId, updateChannelAvailableMessagesData.availableMinId) let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) updatedState.updateMinAvailableMessage(MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: minId)) - case let .updateDeleteMessages(messages, _, _): - // Note: Actual archiving happens in DeleteMessagesWithGlobalIds handler - // where we have access to transaction and can get full message content - updatedState.deleteMessagesWithGlobalIds(messages) - case let .updatePinnedMessages(flags, peer, messages, _, _): + case let .updateDeleteMessages(updateDeleteMessagesData): + updatedState.deleteMessagesWithGlobalIds(updateDeleteMessagesData.messages) + case let .updatePinnedMessages(updatePinnedMessagesData): + let (flags, peer, messages) = (updatePinnedMessagesData.flags, updatePinnedMessagesData.peer, updatePinnedMessagesData.messages) let peerId = peer.peerId updatedState.updateMessagesPinned(ids: messages.map { id in MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: id) }, pinned: (flags & (1 << 0)) != 0) - case let .updateEditMessage(apiMessage, _, _): + case let .updateEditMessage(updateEditMessageData): + let apiMessage = updateEditMessageData.message var peerIsForum = false if let peerId = apiMessage.peerId { peerIsForum = updatedState.isPeerForum(peerId: peerId) @@ -1053,7 +1075,8 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: } } } - case let .updateNewChannelMessage(apiMessage, pts, ptsCount): + case let .updateNewChannelMessage(updateNewChannelMessageData): + let (apiMessage, pts, ptsCount) = (updateNewChannelMessageData.message, updateNewChannelMessageData.pts, updateNewChannelMessageData.ptsCount) var peerIsForum = false if let peerId = apiMessage.peerId { peerIsForum = updatedState.isPeerForum(peerId: peerId) @@ -1100,7 +1123,8 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: } } } - case let .updateNewMessage(apiMessage, _, _): + case let .updateNewMessage(updateNewMessageData): + let apiMessage = updateNewMessageData.message var peerIsForum = false if let peerId = apiMessage.peerId { peerIsForum = updatedState.isPeerForum(peerId: peerId) @@ -1122,7 +1146,8 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: updatedState.addReportMessageDelivery(messageIds: [id]) } } - case let .updateServiceNotification(flags, date, type, text, media, entities): + case let .updateServiceNotification(updateServiceNotificationData): + let (flags, date, type, text, media, entities) = (updateServiceNotificationData.flags, updateServiceNotificationData.inboxDate, updateServiceNotificationData.type, updateServiceNotificationData.message, updateServiceNotificationData.media, updateServiceNotificationData.entities) let popup = (flags & (1 << 0)) != 0 if popup { updatedState.addDisplayAlert(text, isDropAuth: type.hasPrefix("AUTH_KEY_DROP_")) @@ -1196,37 +1221,45 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: updatedState.addMessages([message], location: .UpperHistoryBlock) } } - case let .updateReadChannelInbox(_, folderId, channelId, maxId, stillUnreadCount, pts): + case let .updateReadChannelInbox(updateReadChannelInboxData): + let (folderId, channelId, maxId, stillUnreadCount, pts) = (updateReadChannelInboxData.folderId, updateReadChannelInboxData.channelId, updateReadChannelInboxData.maxId, updateReadChannelInboxData.stillUnreadCount, updateReadChannelInboxData.pts) updatedState.resetIncomingReadState(groupId: PeerGroupId(rawValue: folderId ?? 0), peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)), namespace: Namespaces.Message.Cloud, maxIncomingReadId: maxId, count: stillUnreadCount, pts: pts) - case let .updateReadChannelOutbox(channelId, maxId): - updatedState.readOutbox(MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)), namespace: Namespaces.Message.Cloud, id: maxId), timestamp: nil) - case let .updateChannel(channelId): - updatedState.addExternallyUpdatedPeerId(PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))) - case let .updateChat(chatId): - updatedState.addExternallyUpdatedPeerId(PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId))) - case let .updateReadHistoryInbox(_, folderId, peer, topMsgId, maxId, stillUnreadCount, pts, _): + case let .updateReadChannelOutbox(updateReadChannelOutboxData): + updatedState.readOutbox(MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(updateReadChannelOutboxData.channelId)), namespace: Namespaces.Message.Cloud, id: updateReadChannelOutboxData.maxId), timestamp: nil) + case let .updateChannel(updateChannelData): + updatedState.addExternallyUpdatedPeerId(PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(updateChannelData.channelId))) + case let .updateChat(updateChatData): + updatedState.addExternallyUpdatedPeerId(PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(updateChatData.chatId))) + case let .updateReadHistoryInbox(updateReadHistoryInboxData): + let (folderId, peer, topMsgId, maxId, stillUnreadCount, pts) = (updateReadHistoryInboxData.folderId, updateReadHistoryInboxData.peer, updateReadHistoryInboxData.topMsgId, updateReadHistoryInboxData.maxId, updateReadHistoryInboxData.stillUnreadCount, updateReadHistoryInboxData.pts) if let topMsgId { updatedState.readThread(peerId: peer.peerId, threadId: Int64(topMsgId), readMaxId: maxId, isIncoming: true, mainChannelMessage: nil) } else { updatedState.resetIncomingReadState(groupId: PeerGroupId(rawValue: folderId ?? 0), peerId: peer.peerId, namespace: Namespaces.Message.Cloud, maxIncomingReadId: maxId, count: stillUnreadCount, pts: pts) } - case let .updateReadHistoryOutbox(peer, maxId, _, _): - updatedState.readOutbox(MessageId(peerId: peer.peerId, namespace: Namespaces.Message.Cloud, id: maxId), timestamp: updatesDate) - case let .updateReadChannelDiscussionInbox(_, channelId, topMsgId, readMaxId, mainChannelId, mainChannelPost): + case let .updateReadHistoryOutbox(updateReadHistoryOutboxData): + updatedState.readOutbox(MessageId(peerId: updateReadHistoryOutboxData.peer.peerId, namespace: Namespaces.Message.Cloud, id: updateReadHistoryOutboxData.maxId), timestamp: updatesDate) + case let .updateReadChannelDiscussionInbox(updateReadChannelDiscussionInboxData): + let (channelId, topMsgId, readMaxId, mainChannelId, mainChannelPost) = (updateReadChannelDiscussionInboxData.channelId, updateReadChannelDiscussionInboxData.topMsgId, updateReadChannelDiscussionInboxData.readMaxId, updateReadChannelDiscussionInboxData.broadcastId, updateReadChannelDiscussionInboxData.broadcastPost) var mainChannelMessage: MessageId? if let mainChannelId = mainChannelId, let mainChannelPost = mainChannelPost { mainChannelMessage = MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(mainChannelId)), namespace: Namespaces.Message.Cloud, id: mainChannelPost) } updatedState.readThread(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)), threadId: Int64(topMsgId), readMaxId: readMaxId, isIncoming: true, mainChannelMessage: mainChannelMessage) - case let .updateReadChannelDiscussionOutbox(channelId, topMsgId, readMaxId): + case let .updateReadChannelDiscussionOutbox(updateReadChannelDiscussionOutboxData): + let (channelId, topMsgId, readMaxId) = (updateReadChannelDiscussionOutboxData.channelId, updateReadChannelDiscussionOutboxData.topMsgId, updateReadChannelDiscussionOutboxData.readMaxId) updatedState.readThread(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)), threadId: Int64(topMsgId), readMaxId: readMaxId, isIncoming: false, mainChannelMessage: nil) - case let .updateReadMonoForumInbox(channelId, savedPeerId, readMaxId): + case let .updateReadMonoForumInbox(updateReadMonoForumInboxData): + let (channelId, savedPeerId, readMaxId) = (updateReadMonoForumInboxData.channelId, updateReadMonoForumInboxData.savedPeerId, updateReadMonoForumInboxData.readMaxId) updatedState.readThread(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)), threadId: savedPeerId.peerId.toInt64(), readMaxId: readMaxId, isIncoming: true, mainChannelMessage: nil) - case let .updateReadMonoForumOutbox(channelId, savedPeerId, readMaxId): + case let .updateReadMonoForumOutbox(updateReadMonoForumOutboxData): + let (channelId, savedPeerId, readMaxId) = (updateReadMonoForumOutboxData.channelId, updateReadMonoForumOutboxData.savedPeerId, updateReadMonoForumOutboxData.readMaxId) updatedState.readThread(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)), threadId: savedPeerId.peerId.toInt64(), readMaxId: readMaxId, isIncoming: false, mainChannelMessage: nil) - case let .updateDialogUnreadMark(flags, peer, savedPeerId): + case let .updateDialogUnreadMark(updateDialogUnreadMarkData): + let (flags, peer, savedPeerId) = (updateDialogUnreadMarkData.flags, updateDialogUnreadMarkData.peer, updateDialogUnreadMarkData.savedPeerId) switch peer { - case let .dialogPeer(peer): + case let .dialogPeer(dialogPeerData): + let peer = dialogPeerData.peer let peerId = peer.peerId if let savedPeerId { updatedState.updatePeerChatUnreadMark(peerId, threadId: savedPeerId.peerId.toInt64(), namespace: Namespaces.Message.Cloud, value: (flags & (1 << 0)) != 0) @@ -1237,26 +1270,31 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: case .dialogPeerFolder: break } - case let .updateWebPage(apiWebpage, _, _): - switch apiWebpage { - case let .webPageEmpty(flags, id, url): + case let .updateWebPage(updateWebPageData): + switch updateWebPageData.webpage { + case let .webPageEmpty(webPageEmptyData): + let (flags, id, url) = (webPageEmptyData.flags, webPageEmptyData.id, webPageEmptyData.url) let _ = flags let _ = url updatedState.updateMedia(MediaId(namespace: Namespaces.Media.CloudWebpage, id: id), media: nil) default: - if let webpage = telegramMediaWebpageFromApiWebpage(apiWebpage) { + if let webpage = telegramMediaWebpageFromApiWebpage(updateWebPageData.webpage) { updatedState.updateMedia(webpage.webpageId, media: webpage) } } - case let .updateTranscribedAudio(flags, peer, msgId, transcriptionId, text): + case let .updateTranscribedAudio(updateTranscribedAudioData): + let (flags, peer, msgId, transcriptionId, text) = (updateTranscribedAudioData.flags, updateTranscribedAudioData.peer, updateTranscribedAudioData.msgId, updateTranscribedAudioData.transcriptionId, updateTranscribedAudioData.text) let isPending = (flags & (1 << 0)) != 0 updatedState.updateAudioTranscription(messageId: MessageId(peerId: peer.peerId, namespace: Namespaces.Message.Cloud, id: msgId), id: transcriptionId, isPending: isPending, text: text) - case let .updateNotifySettings(apiPeer, apiNotificationSettings): + case let .updateNotifySettings(updateNotifySettingsData): + let (apiPeer, apiNotificationSettings) = (updateNotifySettingsData.peer, updateNotifySettingsData.notifySettings) switch apiPeer { - case let .notifyPeer(peer): + case let .notifyPeer(notifyPeerData): + let peer = notifyPeerData.peer let notificationSettings = TelegramPeerNotificationSettings(apiSettings: apiNotificationSettings) updatedState.updateNotificationSettings(.peer(peerId: peer.peerId, threadId: nil), notificationSettings: notificationSettings) - case let .notifyForumTopic(peer, topMsgId): + case let .notifyForumTopic(notifyForumTopicData): + let (peer, topMsgId) = (notifyForumTopicData.peer, notifyForumTopicData.topMsgId) let notificationSettings = TelegramPeerNotificationSettings(apiSettings: apiNotificationSettings) updatedState.updateNotificationSettings(.peer(peerId: peer.peerId, threadId: Int64(topMsgId)), notificationSettings: notificationSettings) case .notifyUsers: @@ -1266,12 +1304,14 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: case .notifyBroadcasts: updatedState.updateGlobalNotificationSettings(.channels, notificationSettings: MessageNotificationSettings(apiSettings: apiNotificationSettings)) } - case let .updateChatParticipants(participants): + case let .updateChatParticipants(updateChatParticipantsData): let groupPeerId: PeerId - switch participants { - case let .chatParticipants(chatId, _, _): + switch updateChatParticipantsData.participants { + case let .chatParticipants(chatParticipantsData): + let chatId = chatParticipantsData.chatId groupPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId)) - case let .chatParticipantsForbidden(_, chatId, _): + case let .chatParticipantsForbidden(chatParticipantsForbiddenData): + let chatId = chatParticipantsForbiddenData.chatId groupPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId)) } updatedState.updateCachedPeerData(groupPeerId, { current in @@ -1281,9 +1321,10 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: } else { previous = CachedGroupData() } - return previous.withUpdatedParticipants(CachedGroupParticipants(apiParticipants: participants)) + return previous.withUpdatedParticipants(CachedGroupParticipants(apiParticipants: updateChatParticipantsData.participants)) }) - case let .updateChatParticipantAdd(chatId, userId, inviterId, date, _): + case let .updateChatParticipantAdd(updateChatParticipantAddData): + let (chatId, userId, inviterId, date) = (updateChatParticipantAddData.chatId, updateChatParticipantAddData.userId, updateChatParticipantAddData.inviterId, updateChatParticipantAddData.date) let groupPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId)) let userPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)) let inviterPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(inviterId)) @@ -1298,7 +1339,8 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: return current } }) - case let .updateChatParticipantDelete(chatId, userId, _): + case let .updateChatParticipantDelete(updateChatParticipantDeleteData): + let (chatId, userId) = (updateChatParticipantDeleteData.chatId, updateChatParticipantDeleteData.userId) let groupPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId)) let userPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)) updatedState.updateCachedPeerData(groupPeerId, { current in @@ -1312,7 +1354,8 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: return current } }) - case let .updateChatParticipantAdmin(chatId, userId, isAdmin, _): + case let .updateChatParticipantAdmin(updateChatParticipantAdminData): + let (chatId, userId, isAdmin) = (updateChatParticipantAdminData.chatId, updateChatParticipantAdminData.userId, updateChatParticipantAdminData.isAdmin) let groupPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId)) let userPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)) updatedState.updateCachedPeerData(groupPeerId, { current in @@ -1334,7 +1377,8 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: return current } }) - case let .updateChatDefaultBannedRights(peer, defaultBannedRights, version): + case let .updateChatDefaultBannedRights(updateChatDefaultBannedRightsData): + let (peer, defaultBannedRights, version) = (updateChatDefaultBannedRightsData.peer, updateChatDefaultBannedRightsData.defaultBannedRights, updateChatDefaultBannedRightsData.version) updatedState.updatePeer(peer.peerId, { peer in if let group = peer as? TelegramGroup {//, group.version == version - 1 { return group.updateDefaultBannedRights(TelegramChatBannedRights(apiBannedRights: defaultBannedRights), version: max(group.version, Int(version))) @@ -1344,7 +1388,8 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: return peer } }) - case let .updatePinnedChannelMessages(flags, channelId, messages, pts, ptsCount): + case let .updatePinnedChannelMessages(updatePinnedChannelMessagesData): + let (flags, channelId, messages, pts, ptsCount) = (updatePinnedChannelMessagesData.flags, updatePinnedChannelMessagesData.channelId, updatePinnedChannelMessagesData.messages, updatePinnedChannelMessagesData.pts, updatePinnedChannelMessagesData.ptsCount) let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) if let previousState = updatedState.channelStates[peerId] { if previousState.pts >= pts { @@ -1367,8 +1412,8 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: channelsToPoll[peerId] = nil } } - case let .updatePeerBlocked(flags, peerId): - let userPeerId = peerId.peerId + case let .updatePeerBlocked(updatePeerBlockedData): + let userPeerId = updatePeerBlockedData.peerId.peerId updatedState.updateCachedPeerData(userPeerId, { current in let previous: CachedUserData if let current = current as? CachedUserData { @@ -1377,16 +1422,17 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: previous = CachedUserData() } var userFlags = previous.flags - if (flags & (1 << 1)) != 0 { + if (updatePeerBlockedData.flags & (1 << 1)) != 0 { userFlags.insert(.isBlockedFromStories) } else { userFlags.remove(.isBlockedFromStories) } - return previous.withUpdatedIsBlocked((flags & (1 << 0)) != 0).withUpdatedFlags(userFlags) + return previous.withUpdatedIsBlocked((updatePeerBlockedData.flags & (1 << 0)) != 0).withUpdatedFlags(userFlags) }) - case let .updateUserStatus(userId, status): - updatedState.mergePeerPresences([PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)): status], explicit: true) - case let .updateUserName(userId, _, _, usernames): + case let .updateUserStatus(updateUserStatusData): + updatedState.mergePeerPresences([PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(updateUserStatusData.userId)): updateUserStatusData.status], explicit: true) + case let .updateUserName(updateUserNameData): + let (userId, usernames) = (updateUserNameData.userId, updateUserNameData.usernames) //TODO add contact checking for apply first and last name updatedState.updatePeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), { peer in if let user = peer as? TelegramUser { @@ -1395,23 +1441,24 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: return peer } }) - case let .updateUserPhone(userId, phone): - updatedState.updatePeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), { peer in + case let .updateUserPhone(updateUserPhoneData): + updatedState.updatePeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(updateUserPhoneData.userId)), { peer in if let user = peer as? TelegramUser { - return user.withUpdatedPhone(phone.isEmpty ? nil : phone) + return user.withUpdatedPhone(updateUserPhoneData.phone.isEmpty ? nil : updateUserPhoneData.phone) } else { return peer } }) - case let .updateUserEmojiStatus(userId, emojiStatus): - updatedState.updatePeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), { peer in + case let .updateUserEmojiStatus(updateUserEmojiStatusData): + updatedState.updatePeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(updateUserEmojiStatusData.userId)), { peer in if let user = peer as? TelegramUser { - return user.withUpdatedEmojiStatus(PeerEmojiStatus(apiStatus: emojiStatus)) + return user.withUpdatedEmojiStatus(PeerEmojiStatus(apiStatus: updateUserEmojiStatusData.emojiStatus)) } else { return peer } }) - case let .updatePeerSettings(peer, settings): + case let .updatePeerSettings(updatePeerSettingsData): + let (peer, settings) = (updatePeerSettingsData.peer, updatePeerSettingsData.settings) let peerStatusSettings = PeerStatusSettings(apiSettings: settings) updatedState.updateCachedPeerData(peer.peerId, { current in if peer.peerId.namespace == Namespaces.Peer.CloudUser { @@ -1442,19 +1489,23 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: return current } }) - case let .updateEncryption(chat, date): - updatedState.updateSecretChat(chat: chat, timestamp: date) - case let .updateNewEncryptedMessage(message, _): - updatedState.addSecretMessages([message]) - case let .updateEncryptedMessagesRead(chatId, maxDate, date): + case let .updateEncryption(updateEncryptionData): + updatedState.updateSecretChat(chat: updateEncryptionData.chat, timestamp: updateEncryptionData.date) + case let .updateNewEncryptedMessage(updateNewEncryptedMessageData): + updatedState.addSecretMessages([updateNewEncryptedMessageData.message]) + case let .updateEncryptedMessagesRead(updateEncryptedMessagesReadData): + let (chatId, maxDate, date) = (updateEncryptedMessagesReadData.chatId, updateEncryptedMessagesReadData.maxDate, updateEncryptedMessagesReadData.date) updatedState.readSecretOutbox(peerId: PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt64Value(Int64(chatId))), timestamp: maxDate, actionTimestamp: date) - case let .updateUserTyping(_, userId, topMsgId, type): + case let .updateUserTyping(updateUserTypingData): + let (userId, topMsgId, type) = (updateUserTypingData.userId, updateUserTypingData.topMsgId, updateUserTypingData.action) let threadId = topMsgId.flatMap { Int64($0) } if let date = updatesDate, date + 60 > serverTime { - if case let .sendMessageTextDraftAction(randomId, text) = type { + if case let .sendMessageTextDraftAction(sendMessageTextDraftActionData) = type { + let (randomId, text) = (sendMessageTextDraftActionData.randomId, sendMessageTextDraftActionData.text) switch text { - case let .textWithEntities(text, entities): + case let .textWithEntities(textWithEntitiesData): + let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities) updatedState.addPeerLiveTypingDraftUpdate(peerAndThreadId: PeerAndThreadId(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), threadId: threadId), id: randomId, timestamp: date, peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), text: text, entities: messageTextEntitiesFromApiEntities(entities)) } } else { @@ -1467,7 +1518,8 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: updatedState.addPeerInputActivity(chatPeerId: PeerActivitySpace(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), category: category), peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), activity: activity) } } - case let .updateChatUserTyping(chatId, userId, type): + case let .updateChatUserTyping(updateChatUserTyping): + let (chatId, userId, type) = (updateChatUserTyping.chatId, updateChatUserTyping.fromId, updateChatUserTyping.action) if let date = updatesDate, date + 60 > serverTime { let activity = PeerInputActivity(apiType: type, peerId: nil, timestamp: date) var category: PeerActivitySpace.Category = .global @@ -1477,14 +1529,17 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: updatedState.addPeerInputActivity(chatPeerId: PeerActivitySpace(peerId: PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId)), category: category), peerId: userId.peerId, activity: activity) } - case let .updateChannelUserTyping(_, channelId, topMsgId, userId, type): + case let .updateChannelUserTyping(updateChannelUserTypingData): + let (channelId, topMsgId, userId, type) = (updateChannelUserTypingData.channelId, updateChannelUserTypingData.topMsgId, updateChannelUserTypingData.fromId, updateChannelUserTypingData.action) if let date = updatesDate, date + 60 > serverTime { let channelPeerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) let threadId = topMsgId.flatMap { Int64($0) } - - if case let .sendMessageTextDraftAction(randomId, text) = type { + + if case let .sendMessageTextDraftAction(sendMessageTextDraftActionData) = type { + let (randomId, text) = (sendMessageTextDraftActionData.randomId, sendMessageTextDraftActionData.text) switch text { - case let .textWithEntities(text, entities): + case let .textWithEntities(textWithEntitiesData): + let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities) updatedState.addPeerLiveTypingDraftUpdate(peerAndThreadId: PeerAndThreadId(peerId: channelPeerId, threadId: threadId), id: randomId, timestamp: date, peerId: userId.peerId, text: text, entities: messageTextEntitiesFromApiEntities(entities)) } } else { @@ -1499,15 +1554,17 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: updatedState.addPeerInputActivity(chatPeerId: PeerActivitySpace(peerId: channelPeerId, category: category), peerId: userId.peerId, activity: activity) } } - case let .updateEncryptedChatTyping(chatId): + case let .updateEncryptedChatTyping(updateEncryptedChatTypingData): if let date = updatesDate, date + 60 > serverTime { - updatedState.addPeerInputActivity(chatPeerId: PeerActivitySpace(peerId: PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt64Value(Int64(chatId))), category: .global), peerId: nil, activity: .typingText) + updatedState.addPeerInputActivity(chatPeerId: PeerActivitySpace(peerId: PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt64Value(Int64(updateEncryptedChatTypingData.chatId))), category: .global), peerId: nil, activity: .typingText) } - case let .updateDialogPinned(flags, folderId, peer): + case let .updateDialogPinned(updateDialogPinnedData): + let (flags, folderId, peer) = (updateDialogPinnedData.flags, updateDialogPinnedData.folderId, updateDialogPinnedData.peer) let groupId: PeerGroupId = folderId.flatMap(PeerGroupId.init(rawValue:)) ?? .root let item: PinnedItemId switch peer { - case let .dialogPeer(peer): + case let .dialogPeer(dialogPeerData): + let peer = dialogPeerData.peer item = .peer(peer.peerId) case .dialogPeerFolder: preconditionFailure() @@ -1517,13 +1574,15 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: } else { updatedState.addUpdatePinnedItemIds(groupId: groupId, operation: .unpin(item)) } - case let .updatePinnedDialogs(_, folderId, order): + case let .updatePinnedDialogs(updatePinnedDialogsData): + let (folderId, order) = (updatePinnedDialogsData.folderId, updatePinnedDialogsData.order) let groupId: PeerGroupId = folderId.flatMap(PeerGroupId.init(rawValue:)) ?? .root if let order = order { updatedState.addUpdatePinnedItemIds(groupId: groupId, operation: .reorder(order.map { let item: PinnedItemId switch $0 { - case let .dialogPeer(peer): + case let .dialogPeer(dialogPeerData): + let peer = dialogPeerData.peer item = .peer(peer.peerId) case .dialogPeerFolder: preconditionFailure() @@ -1533,19 +1592,21 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: } else { updatedState.addUpdatePinnedItemIds(groupId: groupId, operation: .sync) } - case let .updateSavedDialogPinned(flags, peer): - if case let .dialogPeer(peer) = peer { - if (flags & (1 << 0)) != 0 { + case let .updateSavedDialogPinned(updateSavedDialogPinnedData): + if case let .dialogPeer(dialogPeerData) = updateSavedDialogPinnedData.peer { + let peer = dialogPeerData.peer + if (updateSavedDialogPinnedData.flags & (1 << 0)) != 0 { updatedState.addUpdatePinnedSavedItemIds(operation: .pin(.peer(peer.peerId))) } else { updatedState.addUpdatePinnedSavedItemIds(operation: .unpin(.peer(peer.peerId))) } } - case let .updatePinnedSavedDialogs(_, order): - if let order = order { + case let .updatePinnedSavedDialogs(updatePinnedSavedDialogsData): + if let order = updatePinnedSavedDialogsData.order { updatedState.addUpdatePinnedSavedItemIds(operation: .reorder(order.compactMap { switch $0 { - case let .dialogPeer(peer): + case let .dialogPeer(dialogPeerData): + let peer = dialogPeerData.peer return .peer(peer.peerId) case .dialogPeerFolder: return nil @@ -1554,12 +1615,13 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: } else { updatedState.addUpdatePinnedSavedItemIds(operation: .sync) } - case let .updatePinnedForumTopic(flags, peerId, topicId): - let isPinned = (flags & (1 << 0)) != 0 - updatedState.addUpdatePinnedTopic(peerId: peerId.peerId, threadId: Int64(topicId), isPinned: isPinned) - case let .updateReadMessagesContents(_, messages, _, _, date): - updatedState.addReadMessagesContents((nil, nil, messages), date: date) - case let .updateChannelReadMessagesContents(_, channelId, topMsgId, savedPeerId, messages): + case let .updatePinnedForumTopic(updatePinnedForumTopicData): + let isPinned = (updatePinnedForumTopicData.flags & (1 << 0)) != 0 + updatedState.addUpdatePinnedTopic(peerId: updatePinnedForumTopicData.peer.peerId, threadId: Int64(updatePinnedForumTopicData.topicId), isPinned: isPinned) + case let .updateReadMessagesContents(updateReadMessagesContentsData): + updatedState.addReadMessagesContents((nil, nil, updateReadMessagesContentsData.messages), date: updateReadMessagesContentsData.date) + case let .updateChannelReadMessagesContents(updateChannelReadMessagesContentsData): + let (channelId, topMsgId, savedPeerId, messages) = (updateChannelReadMessagesContentsData.channelId, updateChannelReadMessagesContentsData.topMsgId, updateChannelReadMessagesContentsData.savedPeerId, updateChannelReadMessagesContentsData.messages) var threadId: Int64? if let savedPeerId { threadId = savedPeerId.peerId.toInt64() @@ -1567,54 +1629,57 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: threadId = Int64(topMsgId) } updatedState.addReadMessagesContents((PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)), threadId, messages), date: nil) - case let .updateChannelMessageViews(channelId, id, views): - updatedState.addUpdateMessageImpressionCount(id: MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)), namespace: Namespaces.Message.Cloud, id: id), count: views) + case let .updateChannelMessageViews(updateChannelMessageViewsData): + updatedState.addUpdateMessageImpressionCount(id: MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(updateChannelMessageViewsData.channelId)), namespace: Namespaces.Message.Cloud, id: updateChannelMessageViewsData.id), count: updateChannelMessageViewsData.views) /*case let .updateChannelMessageForwards(channelId, id, forwards): updatedState.addUpdateMessageForwardsCount(id: MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId), namespace: Namespaces.Message.Cloud, id: id), count: forwards)*/ - case let .updateNewStickerSet(stickerset): - updatedState.addUpdateInstalledStickerPacks(.add(stickerset)) - case let .updateStickerSetsOrder(flags, order): + case let .updateNewStickerSet(updateNewStickerSetData): + updatedState.addUpdateInstalledStickerPacks(.add(updateNewStickerSetData.stickerset)) + case let .updateStickerSetsOrder(updateStickerSetsOrderData): let namespace: SynchronizeInstalledStickerPacksOperationNamespace - if (flags & (1 << 0)) != 0 { + if (updateStickerSetsOrderData.flags & (1 << 0)) != 0 { namespace = .masks - } else if (flags & (1 << 1)) != 0 { + } else if (updateStickerSetsOrderData.flags & (1 << 1)) != 0 { namespace = .emoji } else { namespace = .stickers } - updatedState.addUpdateInstalledStickerPacks(.reorder(namespace, order)) - case let .updateMoveStickerSetToTop(flags, stickerset): + updatedState.addUpdateInstalledStickerPacks(.reorder(namespace, updateStickerSetsOrderData.order)) + case let .updateMoveStickerSetToTop(updateMoveStickerSetToTopData): let namespace: SynchronizeInstalledStickerPacksOperationNamespace - if (flags & (1 << 0)) != 0 { + if (updateMoveStickerSetToTopData.flags & (1 << 0)) != 0 { namespace = .masks - } else if (flags & (1 << 1)) != 0 { + } else if (updateMoveStickerSetToTopData.flags & (1 << 1)) != 0 { namespace = .emoji } else { namespace = .stickers } - updatedState.addUpdateInstalledStickerPacks(.reorderToTop(namespace, [stickerset])) + updatedState.addUpdateInstalledStickerPacks(.reorderToTop(namespace, [updateMoveStickerSetToTopData.stickerset])) case .updateStickerSets: updatedState.addUpdateInstalledStickerPacks(.sync) case .updateSavedGifs: updatedState.addUpdateRecentGifs() - case let .updateDraftMessage(_, peer, topMsgId, savedPeerId, draft): + case let .updateDraftMessage(updateDraftMessageData): + let (peer, topMsgId, savedPeerId, draft) = (updateDraftMessageData.peer, updateDraftMessageData.topMsgId, updateDraftMessageData.savedPeerId, updateDraftMessageData.draft) let inputState: SynchronizeableChatInputState? switch draft { case .draftMessageEmpty: inputState = nil - case let .draftMessage(_, replyToMsgHeader, message, entities, media, date, messageEffectId, suggestedPost): + case let .draftMessage(draftMessageData): + let (replyToMsgHeader, message, entities, media, date, messageEffectId, suggestedPost) = (draftMessageData.replyTo, draftMessageData.message, draftMessageData.entities, draftMessageData.media, draftMessageData.date, draftMessageData.effect, draftMessageData.suggestedPost) let _ = media var replySubject: EngineMessageReplySubject? var parsedSuggestedPost: SynchronizeableChatInputState.SuggestedPost? if let suggestedPost { switch suggestedPost { - case let .suggestedPost(_, starsAmount, scheduleDate): - parsedSuggestedPost = SynchronizeableChatInputState.SuggestedPost(price: starsAmount.flatMap(CurrencyAmount.init(apiAmount:)), timestamp: scheduleDate) + case let .suggestedPost(suggestedPostData): + parsedSuggestedPost = SynchronizeableChatInputState.SuggestedPost(price: suggestedPostData.price.flatMap(CurrencyAmount.init(apiAmount:)), timestamp: suggestedPostData.scheduleDate) } } if let replyToMsgHeader { switch replyToMsgHeader { - case let .inputReplyToMessage(_, replyToMsgId, topMsgId, replyToPeerId, quoteText, quoteEntities, quoteOffset, monoforumPeerId, todoItemId): + case let .inputReplyToMessage(inputReplyToMessageData): + let (replyToMsgId, topMsgId, replyToPeerId, quoteText, quoteEntities, quoteOffset, monoforumPeerId, todoItemId) = (inputReplyToMessageData.replyToMsgId, inputReplyToMessageData.topMsgId, inputReplyToMessageData.replyToPeerId, inputReplyToMessageData.quoteText, inputReplyToMessageData.quoteEntities, inputReplyToMessageData.quoteOffset, inputReplyToMessageData.monoforumPeerId, inputReplyToMessageData.todoItemId) let _ = topMsgId let _ = monoforumPeerId @@ -1630,19 +1695,24 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: var parsedReplyToPeerId: PeerId? switch replyToPeerId { - case let .inputPeerChannel(channelId, _): + case let .inputPeerChannel(inputPeerChannelData): + let channelId = inputPeerChannelData.channelId parsedReplyToPeerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) - case let .inputPeerChannelFromMessage(_, _, channelId): + case let .inputPeerChannelFromMessage(inputPeerChannelFromMessageData): + let channelId = inputPeerChannelFromMessageData.channelId parsedReplyToPeerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) - case let .inputPeerChat(chatId): + case let .inputPeerChat(inputPeerChatData): + let chatId = inputPeerChatData.chatId parsedReplyToPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId)) case .inputPeerEmpty: break case .inputPeerSelf: parsedReplyToPeerId = accountPeerId - case let .inputPeerUser(userId, _): + case let .inputPeerUser(inputPeerUserData): + let userId = inputPeerUserData.userId parsedReplyToPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)) - case let .inputPeerUserFromMessage(_, _, userId): + case let .inputPeerUserFromMessage(inputPeerUserFromMessageData): + let userId = inputPeerUserFromMessageData.userId parsedReplyToPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)) case .none: break @@ -1668,82 +1738,96 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: threadId = Int64(topMsgId) } updatedState.addUpdateChatInputState(peerId: peer.peerId, threadId: threadId, state: inputState) - case let .updatePhoneCall(phoneCall): - updatedState.addUpdateCall(phoneCall) - case let .updatePhoneCallSignalingData(phoneCallId, data): - updatedState.addCallSignalingData(callId: phoneCallId, data: data.makeData()) - case let .updateGroupCallParticipants(call, participants, version): + case let .updatePhoneCall(updatePhoneCallData): + updatedState.addUpdateCall(updatePhoneCallData.phoneCall) + case let .updatePhoneCallSignalingData(updatePhoneCallSignalingData): + updatedState.addCallSignalingData(callId: updatePhoneCallSignalingData.phoneCallId, data: updatePhoneCallSignalingData.data.makeData()) + case let .updateGroupCallParticipants(updateGroupCallParticipantsData): + let (call, participants, version) = (updateGroupCallParticipantsData.call, updateGroupCallParticipantsData.participants, updateGroupCallParticipantsData.version) switch call { - case let .inputGroupCall(id, accessHash): + case let .inputGroupCall(inputGroupCallData): + let (id, accessHash) = (inputGroupCallData.id, inputGroupCallData.accessHash) updatedState.updateGroupCallParticipants(id: id, accessHash: accessHash, participants: participants, version: version) case .inputGroupCallSlug, .inputGroupCallInviteMessage: break } - case let .updateGroupCall(_, channelId, call): - updatedState.updateGroupCall(peerId: channelId?.peerId, call: call) - case let .updateGroupCallChainBlocks(call, subChainId, blocks, nextOffset): - if case let .inputGroupCall(id, accessHash) = call { + case let .updateGroupCall(updateGroupCallData): + updatedState.updateGroupCall(peerId: updateGroupCallData.peer?.peerId, call: updateGroupCallData.call) + case let .updateGroupCallChainBlocks(updateGroupCallChainBlocksData): + let (call, subChainId, blocks, nextOffset) = (updateGroupCallChainBlocksData.call, updateGroupCallChainBlocksData.subChainId, updateGroupCallChainBlocksData.blocks, updateGroupCallChainBlocksData.nextOffset) + if case let .inputGroupCall(inputGroupCallData) = call { + let (id, accessHash) = (inputGroupCallData.id, inputGroupCallData.accessHash) updatedState.updateGroupCallChainBlocks(id: id, accessHash: accessHash, subChainId: subChainId, blocks: blocks.map { $0.makeData() }, nextOffset: nextOffset) } - case let .updateGroupCallMessage(call, message): - if case let .inputGroupCall(id, _) = call { + case let .updateGroupCallMessage(updateGroupCallMessageData): + let (call, message) = (updateGroupCallMessageData.call, updateGroupCallMessageData.message) + if case let .inputGroupCall(inputGroupCallData) = call { + let id = inputGroupCallData.id switch message { - case let .groupCallMessage(flags, messageId, fromId, date, message, paidMessageStars): + case let .groupCallMessage(groupCallMessageData): + let (flags, messageId, fromId, date, message, paidMessageStars) = (groupCallMessageData.flags, groupCallMessageData.id, groupCallMessageData.fromId, groupCallMessageData.date, groupCallMessageData.message, groupCallMessageData.paidMessageStars) updatedState.updateGroupCallMessage(id: id, authorId: fromId.peerId, isFromAdmin: (flags & (1 << 1)) != 0, messageId: messageId, text: message, date: date, paidMessageStars: paidMessageStars) } } - case let .updateGroupCallEncryptedMessage(call, fromId, encryptedMessage): - if case let .inputGroupCall(id, _) = call { + case let .updateGroupCallEncryptedMessage(updateGroupCallEncryptedMessageData): + let (call, fromId, encryptedMessage) = (updateGroupCallEncryptedMessageData.call, updateGroupCallEncryptedMessageData.fromId, updateGroupCallEncryptedMessageData.encryptedMessage) + if case let .inputGroupCall(inputGroupCallData) = call { + let id = inputGroupCallData.id updatedState.updateGroupCallOpaqueMessage(id: id, authorId: fromId.peerId, data: encryptedMessage.makeData()) } - case let .updatePeerHistoryTTL(_, peer, ttl): - updatedState.updateAutoremoveTimeout(peer: peer, value: CachedPeerAutoremoveTimeout.Value(ttl)) - case let .updateLangPackTooLong(langCode): - updatedState.updateLangPack(langCode: langCode, difference: nil) - case let .updateLangPack(difference): + case let .updatePeerHistoryTTL(updatePeerHistoryTTLData): + updatedState.updateAutoremoveTimeout(peer: updatePeerHistoryTTLData.peer, value: CachedPeerAutoremoveTimeout.Value(updatePeerHistoryTTLData.ttlPeriod)) + case let .updateLangPackTooLong(updateLangPackTooLongData): + updatedState.updateLangPack(langCode: updateLangPackTooLongData.langCode, difference: nil) + case let .updateLangPack(updateLangPackData): let langCode: String - switch difference { - case let .langPackDifference(langCodeValue, _, _, _): + switch updateLangPackData.difference { + case let .langPackDifference(langPackDifferenceData): + let (langCodeValue) = (langPackDifferenceData.langCode) langCode = langCodeValue } - updatedState.updateLangPack(langCode: langCode, difference: difference) - case let .updateMessagePoll(_, pollId, poll, results): - updatedState.updateMessagePoll(MediaId(namespace: Namespaces.Media.CloudPoll, id: pollId), poll: poll, results: results) - case let .updateFolderPeers(folderPeers, _, _): - for folderPeer in folderPeers { + updatedState.updateLangPack(langCode: langCode, difference: updateLangPackData.difference) + case let .updateMessagePoll(updateMessagePollData): + updatedState.updateMessagePoll(MediaId(namespace: Namespaces.Media.CloudPoll, id: updateMessagePollData.pollId), poll: updateMessagePollData.poll, results: updateMessagePollData.results) + case let .updateFolderPeers(updateFolderPeersData): + for folderPeer in updateFolderPeersData.folderPeers { switch folderPeer { - case let .folderPeer(peer, folderId): + case let .folderPeer(folderPeerData): + let (peer, folderId) = (folderPeerData.peer, folderPeerData.folderId) updatedState.updatePeerChatInclusion(peerId: peer.peerId, groupId: PeerGroupId(rawValue: folderId), changedGroup: true) } } - case let .updatePeerLocated(peers): + case let .updatePeerLocated(updatePeerLocatedData): var peersNearby: [PeerNearby] = [] - for peer in peers { + for peer in updatePeerLocatedData.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)) } } updatedState.updatePeersNearby(peersNearby) - case let .updateNewScheduledMessage(apiMessage): + case let .updateNewScheduledMessage(updateNewScheduledMessageData): var peerIsForum = false - if let peerId = apiMessage.peerId { + if let peerId = updateNewScheduledMessageData.message.peerId { peerIsForum = updatedState.isPeerForum(peerId: peerId) } - if let message = StoreMessage(apiMessage: apiMessage, accountPeerId: accountPeerId, peerIsForum: peerIsForum, namespace: Namespaces.Message.ScheduledCloud) { + if let message = StoreMessage(apiMessage: updateNewScheduledMessageData.message, accountPeerId: accountPeerId, peerIsForum: peerIsForum, namespace: Namespaces.Message.ScheduledCloud) { updatedState.addScheduledMessages([message]) } - case let .updateQuickReplyMessage(apiMessage): + case let .updateQuickReplyMessage(updateQuickReplyMessageData): var peerIsForum = false - if let peerId = apiMessage.peerId { + if let peerId = updateQuickReplyMessageData.message.peerId { peerIsForum = updatedState.isPeerForum(peerId: peerId) } - if let message = StoreMessage(apiMessage: apiMessage, accountPeerId: accountPeerId, peerIsForum: peerIsForum, namespace: Namespaces.Message.QuickReplyCloud) { + if let message = StoreMessage(apiMessage: updateQuickReplyMessageData.message, accountPeerId: accountPeerId, peerIsForum: peerIsForum, namespace: Namespaces.Message.QuickReplyCloud) { updatedState.addQuickReplyMessages([message]) } - case let .updateDeleteScheduledMessages(_, peer, messages, sentMessages): + case let .updateDeleteScheduledMessages(updateDeleteScheduledMessagesData): + let (peer, messages, sentMessages) = (updateDeleteScheduledMessagesData.peer, updateDeleteScheduledMessagesData.messages, updateDeleteScheduledMessagesData.sentMessages) var messageIds: [MessageId] = [] var sentMessageIds: [MessageId] = [] for message in messages { @@ -1756,27 +1840,29 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: } updatedState.deleteMessages(messageIds) updatedState.addSentScheduledMessageIds(sentMessageIds) - case let .updateDeleteQuickReplyMessages(_, messages): + case let .updateDeleteQuickReplyMessages(updateDeleteQuickReplyMessagesData): var messageIds: [MessageId] = [] - for message in messages { + for message in updateDeleteQuickReplyMessagesData.messages { messageIds.append(MessageId(peerId: accountPeerId, namespace: Namespaces.Message.QuickReplyCloud, id: message)) } updatedState.deleteMessages(messageIds) - case let .updateTheme(theme): - updatedState.updateTheme(TelegramTheme(apiTheme: theme)) - case let .updateMessageID(id, randomId): - updatedState.updatedOutgoingUniqueMessageIds[randomId] = id + case let .updateTheme(updateThemeData): + updatedState.updateTheme(TelegramTheme(apiTheme: updateThemeData.theme)) + case let .updateMessageID(updateMessageIDData): + updatedState.updatedOutgoingUniqueMessageIds[updateMessageIDData.randomId] = updateMessageIDData.id case .updateDialogFilters: updatedState.addSyncChatListFilters() - case let .updateDialogFilterOrder(order): - updatedState.addUpdateChatListFilterOrder(order: order) - case let .updateDialogFilter(_, id, filter): - updatedState.addUpdateChatListFilter(id: id, filter: filter) - case let .updateBotCommands(peer, botId, apiCommands): + case let .updateDialogFilterOrder(updateDialogFilterOrderData): + updatedState.addUpdateChatListFilterOrder(order: updateDialogFilterOrderData.order) + case let .updateDialogFilter(updateDialogFilterData): + updatedState.addUpdateChatListFilter(id: updateDialogFilterData.id, filter: updateDialogFilterData.filter) + case let .updateBotCommands(updateBotCommandsData): + let (peer, botId, apiCommands) = (updateBotCommandsData.peer, updateBotCommandsData.botId, updateBotCommandsData.commands) let botPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(botId)) let commands: [BotCommand] = apiCommands.map { command in switch command { - case let .botCommand(command, description): + case let .botCommand(botCommandData): + let (command, description) = (botCommandData.command, botCommandData.description) return BotCommand(text: command, description: description) } } @@ -1804,7 +1890,8 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: } return current }) - case let .updateBotMenuButton(botId, button): + case let .updateBotMenuButton(updateBotMenuButtonData): + let (botId, button) = (updateBotMenuButtonData.botId, updateBotMenuButtonData.button) let botPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(botId)) let menuButton = BotMenuButton(apiBotMenuButton: button) updatedState.updateCachedPeerData(botPeerId, { current in @@ -1815,7 +1902,8 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: } return current }) - case let .updatePendingJoinRequests(peer, requestsPending, _): + case let .updatePendingJoinRequests(updatePendingJoinRequestsData): + let (peer, requestsPending) = (updatePendingJoinRequestsData.peer, updatePendingJoinRequestsData.requestsPending) updatedState.updateCachedPeerData(peer.peerId, { current in if peer.peerId.namespace == Namespaces.Peer.CloudGroup { let previous: CachedGroupData @@ -1837,7 +1925,8 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: return current } }) - case let .updateMessageReactions(_, peer, msgId, topMsgId, savedPeerId, reactions): + case let .updateMessageReactions(updateMessageReactionsData): + let (peer, msgId, topMsgId, savedPeerId, reactions) = (updateMessageReactionsData.peer, updateMessageReactionsData.msgId, updateMessageReactionsData.topMsgId, updateMessageReactionsData.savedPeerId, updateMessageReactionsData.reactions) var threadId: Int64? if let savedPeerId { threadId = savedPeerId.peerId.toInt64() @@ -1848,68 +1937,79 @@ private func finalStateWithUpdatesAndServerTime(accountPeerId: PeerId, postbox: updatedState.updateMessageReactions(MessageId(peerId: peer.peerId, namespace: Namespaces.Message.Cloud, id: msgId), threadId: threadId, reactions: reactions, eventTimestamp: updatesDate) case .updateAttachMenuBots: updatedState.addUpdateAttachMenuBots() - case let .updateWebViewResultSent(queryId): - updatedState.addDismissWebView(queryId) + case let .updateWebViewResultSent(updateWebViewResultSentData): + updatedState.addDismissWebView(updateWebViewResultSentData.queryId) case .updateConfig: updatedState.reloadConfig() - case let .updateMessageExtendedMedia(peer, msgId, extendedMedia): + case let .updateMessageExtendedMedia(updateMessageExtendedMediaData): + let (peer, msgId, extendedMedia) = (updateMessageExtendedMediaData.peer, updateMessageExtendedMediaData.msgId, updateMessageExtendedMediaData.extendedMedia) updatedState.updateExtendedMedia(MessageId(peerId: peer.peerId, namespace: Namespaces.Message.Cloud, id: msgId), extendedMedia: extendedMedia) - case let .updateStory(peerId, story): - updatedState.updateStory(peerId: peerId.peerId, story: story) - case let .updateReadStories(peerId, id): - updatedState.readStories(peerId: peerId.peerId, maxId: id) - case let .updateStoriesStealthMode(stealthMode): - updatedState.updateStoryStealthMode(stealthMode) - case let .updateSentStoryReaction(peerId, storyId, reaction): - updatedState.updateStorySentReaction(peerId: peerId.peerId, id: storyId, reaction: reaction) - case let .updateNewAuthorization(flags, hash, date, device, location): + case let .updateStory(updateStoryData): + updatedState.updateStory(peerId: updateStoryData.peer.peerId, story: updateStoryData.story) + case let .updateReadStories(updateReadStoriesData): + updatedState.readStories(peerId: updateReadStoriesData.peer.peerId, maxId: updateReadStoriesData.maxId) + case let .updateStoriesStealthMode(updateStoriesStealthModeData): + updatedState.updateStoryStealthMode(updateStoriesStealthModeData.stealthMode) + case let .updateSentStoryReaction(updateSentStoryReactionData): + updatedState.updateStorySentReaction(peerId: updateSentStoryReactionData.peer.peerId, id: updateSentStoryReactionData.storyId, reaction: updateSentStoryReactionData.reaction) + case let .updateNewAuthorization(updateNewAuthorizationData): + let (flags, hash, date, device, location) = (updateNewAuthorizationData.flags, updateNewAuthorizationData.hash, updateNewAuthorizationData.date, updateNewAuthorizationData.device, updateNewAuthorizationData.location) let isUnconfirmed = (flags & (1 << 0)) != 0 updatedState.updateNewAuthorization(isUnconfirmed: isUnconfirmed, hash: hash, date: date ?? 0, device: device ?? "", location: location ?? "") - case let .updatePeerWallpaper(_, peer, wallpaper): - updatedState.updateWallpaper(peerId: peer.peerId, wallpaper: wallpaper.flatMap { TelegramWallpaper(apiWallpaper: $0) }) - case let .updateStarsBalance(balance): - let amount = CurrencyAmount(apiAmount: balance) + case let .updatePeerWallpaper(updatePeerWallpaperData): + updatedState.updateWallpaper(peerId: updatePeerWallpaperData.peer.peerId, wallpaper: updatePeerWallpaperData.wallpaper.flatMap { TelegramWallpaper(apiWallpaper: $0) }) + case let .updateStarsBalance(updateStarsBalanceData): + let amount = CurrencyAmount(apiAmount: updateStarsBalanceData.balance) updatedState.updateStarsBalance(peerId: accountPeerId, currency: amount.currency, balance: amount.amount) - case let .updateStarsRevenueStatus(peer, status): - updatedState.updateStarsRevenueStatus(peerId: peer.peerId, status: StarsRevenueStats.Balances(apiStarsRevenueStatus: status)) - case let .updatePaidReactionPrivacy(privacy): + case let .updateStarsRevenueStatus(updateStarsRevenueStatusData): + updatedState.updateStarsRevenueStatus(peerId: updateStarsRevenueStatusData.peer.peerId, status: StarsRevenueStats.Balances(apiStarsRevenueStatus: updateStarsRevenueStatusData.status)) + case let .updatePaidReactionPrivacy(updatePaidReactionPrivacyData): let mappedPrivacy: TelegramPaidReactionPrivacy - switch privacy { + switch updatePaidReactionPrivacyData.private { case .paidReactionPrivacyDefault: mappedPrivacy = .default case .paidReactionPrivacyAnonymous: mappedPrivacy = .anonymous - case let .paidReactionPrivacyPeer(peer): + case let .paidReactionPrivacyPeer(paidReactionPrivacyPeerData): + let peer = paidReactionPrivacyPeerData.peer let peerId: PeerId switch peer { - case let .inputPeerChannel(channelId, _): + case let .inputPeerChannel(inputPeerChannelData): + let channelId = inputPeerChannelData.channelId peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) - case let .inputPeerChannelFromMessage(_, _, channelId): + case let .inputPeerChannelFromMessage(inputPeerChannelFromMessageData): + let channelId = inputPeerChannelFromMessageData.channelId peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) - case let .inputPeerChat(chatId): + case let .inputPeerChat(inputPeerChatData): + let chatId = inputPeerChatData.chatId peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId)) case .inputPeerEmpty: peerId = accountPeerId case .inputPeerSelf: peerId = accountPeerId - 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 .inputPeerUserFromMessage(_, _, userId): + case let .inputPeerUserFromMessage(inputPeerUserFromMessageData): + let userId = inputPeerUserFromMessageData.userId peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)) } mappedPrivacy = .peer(peerId) } updatedState.updateStarsReactionsDefaultPrivacy(privacy: mappedPrivacy) - case let .updateMonoForumNoPaidException(flags, channelId, savedPeerId): + case let .updateMonoForumNoPaidException(updateMonoForumNoPaidExceptionData): + let (flags, channelId, savedPeerId) = (updateMonoForumNoPaidExceptionData.flags, updateMonoForumNoPaidExceptionData.channelId, updateMonoForumNoPaidExceptionData.savedPeerId) updatedState.updateMonoForumNoPaidException(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)), threadId: savedPeerId.peerId.toInt64(), isFree: (flags & (1 << 0)) != 0) - case let .updateStarGiftAuctionState(giftId, state): + case let .updateStarGiftAuctionState(updateStarGiftAuctionStateData): + let (giftId, state) = (updateStarGiftAuctionStateData.giftId, updateStarGiftAuctionStateData.state) if let state = GiftAuctionContext.State.AuctionState(apiAuctionState: state, peers: updatedState.peers) { updatedState.updateStarGiftAuctionState(giftId: giftId, state: state) } - case let .updateStarGiftAuctionUserState(giftId, userState): + case let .updateStarGiftAuctionUserState(updateStarGiftAuctionUserStateData): + let (giftId, userState) = (updateStarGiftAuctionUserStateData.giftId, updateStarGiftAuctionUserStateData.userState) updatedState.updateStarGiftAuctionMyState(giftId: giftId, state: GiftAuctionContext.State.MyState(apiAuctionUserState: userState)) - case let .updateEmojiGameInfo(info): - updatedState.updateEmojiGameInfo(info: EmojiGameInfo(apiEmojiGameInfo: info)) + case let .updateEmojiGameInfo(updateEmojiGameInfoData): + updatedState.updateEmojiGameInfo(info: EmojiGameInfo(apiEmojiGameInfo: updateEmojiGameInfoData.info)) default: break } @@ -2017,7 +2117,8 @@ final class FetchedForumThreads { convenience init(forumTopics: Api.messages.ForumTopics) { switch forumTopics { - case let .forumTopics(flags, count, topics, messages, chats, users, pts): + case let .forumTopics(forumTopicsData): + let (flags, count, topics, messages, chats, users, pts) = (forumTopicsData.flags, forumTopicsData.count, forumTopicsData.topics, forumTopicsData.messages, forumTopicsData.chats, forumTopicsData.users, forumTopicsData.pts) let orderByDate = (flags & (1 << 0)) != 0 self.init(items: topics.map(Item.forum), totalCount: Int(count), orderByDate: orderByDate, pts: pts, messages: messages, users: users, chats: chats) } @@ -2025,9 +2126,11 @@ final class FetchedForumThreads { convenience init(savedDialogs: Api.messages.SavedDialogs) { switch savedDialogs { - case let .savedDialogs(dialogs, messages, chats, users): + case let .savedDialogs(savedDialogsData): + let (dialogs, messages, chats, users) = (savedDialogsData.dialogs, savedDialogsData.messages, savedDialogsData.chats, savedDialogsData.users) self.init(items: dialogs.map(Item.savedDialog), totalCount: Int(dialogs.count), orderByDate: false, pts: nil, messages: messages, users: users, chats: chats) - case let .savedDialogsSlice(count, dialogs, messages, chats, users): + case let .savedDialogsSlice(savedDialogsSliceData): + let (count, dialogs, messages, chats, users) = (savedDialogsSliceData.count, savedDialogsSliceData.dialogs, savedDialogsSliceData.messages, savedDialogsSliceData.chats, savedDialogsSliceData.users) self.init(items: dialogs.map(Item.savedDialog), totalCount: Int(count), orderByDate: false, pts: nil, messages: messages, users: users, chats: chats) case .savedDialogsNotModified: self.init(items: [], totalCount: 0, orderByDate: false, pts: 0, messages: [], users: [], chats: []) @@ -2134,10 +2237,11 @@ func resolveForumThreads(accountPeerId: PeerId, postbox: Postbox, source: FetchM switch topic { case let .forum(topic): switch topic { - case let .forumTopic(flags, id, date, peer, title, iconColor, iconEmojiId, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, fromId, notifySettings, draft): + case let .forumTopic(forumTopicData): + let (flags, id, date, peer, title, iconColor, iconEmojiId, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, fromId, notifySettings, draft) = (forumTopicData.flags, forumTopicData.id, forumTopicData.date, forumTopicData.peer, forumTopicData.title, forumTopicData.iconColor, forumTopicData.iconEmojiId, forumTopicData.topMessage, forumTopicData.readInboxMaxId, forumTopicData.readOutboxMaxId, forumTopicData.unreadCount, forumTopicData.unreadMentionsCount, forumTopicData.unreadReactionsCount, forumTopicData.fromId, forumTopicData.notifySettings, forumTopicData.draft) let _ = peer let _ = draft - + state.operations.append(.ResetForumTopic( topicId: PeerAndBoundThreadId(peerId: peerId, threadId: Int64(id)), data: StoreMessageHistoryThreadData( @@ -2171,7 +2275,8 @@ func resolveForumThreads(accountPeerId: PeerId, postbox: Postbox, source: FetchM } case let .savedDialog(savedDialog): switch savedDialog { - case let .monoForumDialog(flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadReactionsCount, _): + case let .monoForumDialog(monoForumDialogData): + let (flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadReactionsCount, _) = (monoForumDialogData.flags, monoForumDialogData.peer, monoForumDialogData.topMessage, monoForumDialogData.readInboxMaxId, monoForumDialogData.readOutboxMaxId, monoForumDialogData.unreadCount, monoForumDialogData.unreadReactionsCount, monoForumDialogData.draft) state.operations.append(.ResetForumTopic( topicId: PeerAndBoundThreadId(peerId: peerId, threadId: peer.peerId.toInt64()), data: StoreMessageHistoryThreadData( @@ -2299,10 +2404,11 @@ func resolveForumThreads(accountPeerId: PeerId, postbox: Postbox, source: FetchM switch item { case let .forum(topic): switch topic { - case let .forumTopic(flags, id, date, peer, title, iconColor, iconEmojiId, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, fromId, notifySettings, draft): + case let .forumTopic(forumTopicData): + let (flags, id, date, peer, title, iconColor, iconEmojiId, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, fromId, notifySettings, draft) = (forumTopicData.flags, forumTopicData.id, forumTopicData.date, forumTopicData.peer, forumTopicData.title, forumTopicData.iconColor, forumTopicData.iconEmojiId, forumTopicData.topMessage, forumTopicData.readInboxMaxId, forumTopicData.readOutboxMaxId, forumTopicData.unreadCount, forumTopicData.unreadMentionsCount, forumTopicData.unreadReactionsCount, forumTopicData.fromId, forumTopicData.notifySettings, forumTopicData.draft) let _ = peer let _ = draft - + let data = MessageHistoryThreadData( creationDate: date, isOwnedByMe: (flags & (1 << 1)) != 0, @@ -2333,7 +2439,8 @@ func resolveForumThreads(accountPeerId: PeerId, postbox: Postbox, source: FetchM } case let .savedDialog(savedDialog): switch savedDialog { - case let .monoForumDialog(flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadReactionsCount, _): + case let .monoForumDialog(monoForumDialogData): + let (flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadReactionsCount, _) = (monoForumDialogData.flags, monoForumDialogData.peer, monoForumDialogData.topMessage, monoForumDialogData.readInboxMaxId, monoForumDialogData.readOutboxMaxId, monoForumDialogData.unreadCount, monoForumDialogData.unreadReactionsCount, monoForumDialogData.draft) let data = MessageHistoryThreadData( creationDate: 0, isOwnedByMe: true, @@ -2466,10 +2573,11 @@ func resolveForumThreads(accountPeerId: PeerId, postbox: Postbox, source: FetchM switch item { case let .forum(topic): switch topic { - case let .forumTopic(flags, id, date, peer, title, iconColor, iconEmojiId, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, fromId, notifySettings, draft): + case let .forumTopic(forumTopicData): + let (flags, id, date, peer, title, iconColor, iconEmojiId, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, fromId, notifySettings, draft) = (forumTopicData.flags, forumTopicData.id, forumTopicData.date, forumTopicData.peer, forumTopicData.title, forumTopicData.iconColor, forumTopicData.iconEmojiId, forumTopicData.topMessage, forumTopicData.readInboxMaxId, forumTopicData.readOutboxMaxId, forumTopicData.unreadCount, forumTopicData.unreadMentionsCount, forumTopicData.unreadReactionsCount, forumTopicData.fromId, forumTopicData.notifySettings, forumTopicData.draft) let _ = peer let _ = draft - + fetchedChatList.threadInfos[PeerAndBoundThreadId(peerId: peerId, threadId: Int64(id))] = StoreMessageHistoryThreadData( data: MessageHistoryThreadData( creationDate: date, @@ -2499,8 +2607,9 @@ func resolveForumThreads(accountPeerId: PeerId, postbox: Postbox, source: FetchM } case let .savedDialog(savedDialog): switch savedDialog { - case let .monoForumDialog(flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadReactionsCount, _): - + case let .monoForumDialog(monoForumDialogData): + let (flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadReactionsCount, _) = (monoForumDialogData.flags, monoForumDialogData.peer, monoForumDialogData.topMessage, monoForumDialogData.readInboxMaxId, monoForumDialogData.readOutboxMaxId, monoForumDialogData.unreadCount, monoForumDialogData.unreadReactionsCount, monoForumDialogData.draft) + fetchedChatList.threadInfos[PeerAndBoundThreadId(peerId: peerId, threadId: peer.peerId.toInt64())] = StoreMessageHistoryThreadData( data: MessageHistoryThreadData( creationDate: 0, @@ -2716,22 +2825,25 @@ private func resolveAssociatedMessages(accountPeerId: PeerId, postbox: Postbox, if let peer = state.peers[peerId] { var signal: Signal? if peerId.namespace == Namespaces.Peer.CloudUser || peerId.namespace == Namespaces.Peer.CloudGroup { - signal = network.request(Api.functions.messages.getMessages(id: messageIds.targetIdsBySourceId.values.map({ Api.InputMessage.inputMessageReplyTo(id: $0.id) }))) + signal = network.request(Api.functions.messages.getMessages(id: messageIds.targetIdsBySourceId.values.map({ Api.InputMessage.inputMessageReplyTo(.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.targetIdsBySourceId.values.map({ Api.InputMessage.inputMessageReplyTo(id: $0.id) }))) + signal = network.request(Api.functions.channels.getMessages(channel: inputChannel, id: messageIds.targetIdsBySourceId.values.map({ Api.InputMessage.inputMessageReplyTo(.init(id: $0.id)) }))) } } if let signal = signal { signals.append(signal |> map { result in switch result { - case let .messages(messages, apiTopics, chats, users): + case let .messages(messagesData): + let (messages, apiTopics, chats, users) = (messagesData.messages, messagesData.topics, messagesData.chats, messagesData.users) let _ = apiTopics return (messages, chats, users) - case let .messagesSlice(_, _, _, _, _, messages, apiTopics, chats, users): + case let .messagesSlice(messagesSliceData): + let (messages, apiTopics, chats, users) = (messagesSliceData.messages, messagesSliceData.topics, messagesSliceData.chats, messagesSliceData.users) let _ = apiTopics return (messages, chats, users) - case let .channelMessages(_, _, _, _, messages, apiTopics, chats, users): + case let .channelMessages(channelMessagesData): + let (messages, apiTopics, chats, users) = (channelMessagesData.messages, channelMessagesData.topics, channelMessagesData.chats, channelMessagesData.users) let _ = apiTopics return (messages, chats, users) case .messagesNotModified: @@ -2749,20 +2861,23 @@ private func resolveAssociatedMessages(accountPeerId: PeerId, postbox: Postbox, if let peer = state.peers[peerId] { var signal: Signal? 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.chats, messagesData.users) return (messages, chats, users) - case let .messagesSlice(_, _, _, _, _, messages, _, chats, users): + case let .messagesSlice(messagesSliceData): + let (messages, chats, users) = (messagesSliceData.messages, messagesSliceData.chats, messagesSliceData.users) return (messages, chats, users) - case let .channelMessages(_, _, _, _, messages, apiTopics, chats, users): + case let .channelMessages(channelMessagesData): + let (messages, apiTopics, chats, users) = (channelMessagesData.messages, channelMessagesData.topics, channelMessagesData.chats, channelMessagesData.users) let _ = apiTopics return (messages, chats, users) case .messagesNotModified: @@ -2834,7 +2949,7 @@ private func resolveMissingPeerChatInfos(accountPeerId: PeerId, network: Network return .single((state, hadError)) } else { Logger.shared.log("State", "will fetch chat info for \(missingPeers.count) peers") - let signal = network.request(Api.functions.messages.getPeerDialogs(peers: missingPeers.values.map(Api.InputDialogPeer.inputDialogPeer(peer:)))) + let signal = network.request(Api.functions.messages.getPeerDialogs(peers: missingPeers.values.map { .inputDialogPeer(.init(peer: $0)) })) |> map(Optional.init) return signal @@ -2850,7 +2965,8 @@ private func resolveMissingPeerChatInfos(accountPeerId: PeerId, network: Network var updatedState = state 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) updatedState.mergeChats(chats) updatedState.mergeUsers(users) @@ -2858,7 +2974,8 @@ private func resolveMissingPeerChatInfos(accountPeerId: PeerId, network: Network 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 updatedState.setNeedsHoleFromPreviousState(peerId: peerId, namespace: Namespaces.Message.Cloud, validateChannelPts: pts) @@ -3065,7 +3182,7 @@ func resetChannels(accountPeerId: PeerId, postbox: Postbox, network: Network, pe var inputPeers: [Api.InputDialogPeer] = [] for peer in peers { if let inputPeer = apiInputPeer(peer) { - inputPeers.append(.inputDialogPeer(peer: inputPeer)) + inputPeers.append(.inputDialogPeer(.init(peer: inputPeer))) } } return network.request(Api.functions.messages.getPeerDialogs(peers: inputPeers)) @@ -3095,7 +3212,8 @@ func resetChannels(accountPeerId: PeerId, postbox: Postbox, network: Network, pe if let result = result { 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) dialogsChats.append(contentsOf: chats) dialogsUsers.append(contentsOf: users) @@ -3113,7 +3231,8 @@ func resetChannels(accountPeerId: PeerId, postbox: Postbox, network: Network, pe let groupId: PeerGroupId let apiTtlPeriod: Int32? switch dialog { - case let .dialog(flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, peerNotificationSettings, pts, _, folderId, ttlPeriod): + case let .dialog(dialogData): + let (flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, peerNotificationSettings, pts, folderId, ttlPeriod) = (dialogData.flags, dialogData.peer, dialogData.topMessage, dialogData.readInboxMaxId, dialogData.readOutboxMaxId, dialogData.unreadCount, dialogData.unreadMentionsCount, dialogData.unreadReactionsCount, dialogData.notifySettings, dialogData.pts, dialogData.folderId, dialogData.ttlPeriod) apiPeer = peer apiTopMessage = topMessage apiReadInboxMaxId = readInboxMaxId @@ -3287,7 +3406,8 @@ private func pollChannel(accountPeerId: PeerId, postbox: Postbox, network: Netwo } switch difference { - case let .channelDifference(_, pts, timeout, newMessages, otherUpdates, chats, users): + case let .channelDifference(channelDifferenceData): + let (_, pts, timeout, newMessages, otherUpdates, chats, users) = (channelDifferenceData.flags, channelDifferenceData.pts, channelDifferenceData.timeout, channelDifferenceData.newMessages, channelDifferenceData.otherUpdates, channelDifferenceData.chats, channelDifferenceData.users) var updatedState = state var apiTimeout: Int32? @@ -3342,10 +3462,11 @@ private func pollChannel(accountPeerId: PeerId, postbox: Postbox, network: Netwo for update in otherUpdates { switch update { - case let .updateDeleteChannelMessages(_, messages, _, _): + case let .updateDeleteChannelMessages(updateDeleteChannelMessagesData): let peerId = peer.id - updatedState.deleteMessages(messages.map({ MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: $0) })) - case let .updateEditChannelMessage(apiMessage, _, _): + updatedState.deleteMessages(updateDeleteChannelMessagesData.messages.map({ MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: $0) })) + case let .updateEditChannelMessage(updateEditChannelMessageData): + let apiMessage = updateEditChannelMessageData.message var peerIsForum = peer.isForum if let peerId = apiMessage.peerId, updatedState.isPeerForum(peerId: peerId) { peerIsForum = true @@ -3375,12 +3496,14 @@ private func pollChannel(accountPeerId: PeerId, postbox: Postbox, network: Netwo } else { Logger.shared.log("State", "Invalid updateEditChannelMessage") } - case let .updatePinnedChannelMessages(flags, channelId, messages, _, _): + case let .updatePinnedChannelMessages(updatePinnedChannelMessagesData): + let (flags, channelId, messages) = (updatePinnedChannelMessagesData.flags, updatePinnedChannelMessagesData.channelId, updatePinnedChannelMessagesData.messages) let channelPeerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) updatedState.updateMessagesPinned(ids: messages.map { id in MessageId(peerId: channelPeerId, namespace: Namespaces.Message.Cloud, id: id) }, pinned: (flags & (1 << 0)) != 0) - case let .updateChannelReadMessagesContents(_, _, topMsgId, savedPeerId, messages): + case let .updateChannelReadMessagesContents(updateChannelReadMessagesContentsData): + let (topMsgId, savedPeerId, messages) = (updateChannelReadMessagesContentsData.topMsgId, updateChannelReadMessagesContentsData.savedPeerId, updateChannelReadMessagesContentsData.messages) var threadId: Int64? if let savedPeerId { threadId = savedPeerId.peerId.toInt64() @@ -3388,11 +3511,13 @@ private func pollChannel(accountPeerId: PeerId, postbox: Postbox, network: Netwo threadId = Int64(topMsgId) } updatedState.addReadMessagesContents((peer.id, threadId, messages), date: nil) - case let .updateChannelMessageViews(_, id, views): - updatedState.addUpdateMessageImpressionCount(id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: id), count: views) - case let .updateChannelWebPage(_, apiWebpage, _, _): + case let .updateChannelMessageViews(updateChannelMessageViewsData): + updatedState.addUpdateMessageImpressionCount(id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: updateChannelMessageViewsData.id), count: updateChannelMessageViewsData.views) + case let .updateChannelWebPage(updateChannelWebPageData): + let apiWebpage = updateChannelWebPageData.webpage switch apiWebpage { - case let .webPageEmpty(flags, id, url): + case let .webPageEmpty(webPageEmptyData): + let (flags, id, url) = (webPageEmptyData.flags, webPageEmptyData.id, webPageEmptyData.url) let _ = flags let _ = url updatedState.updateMedia(MediaId(namespace: Namespaces.Media.CloudWebpage, id: id), media: nil) @@ -3401,7 +3526,8 @@ private func pollChannel(accountPeerId: PeerId, postbox: Postbox, network: Netwo updatedState.updateMedia(webpage.webpageId, media: webpage) } } - case let .updateChannelAvailableMessages(_, minId): + case let .updateChannelAvailableMessages(updateChannelAvailableMessagesData): + let minId = updateChannelAvailableMessagesData.availableMinId let messageId = MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: minId) updatedState.updateMinAvailableMessage(messageId) updatedState.updateCachedPeerData(peer.id, { current in @@ -3425,12 +3551,13 @@ private func pollChannel(accountPeerId: PeerId, postbox: Postbox, network: Netwo return (updatedState, true, apiTimeout) } } - case let .channelDifferenceEmpty(_, pts, timeout): + case let .channelDifferenceEmpty(channelDifferenceEmptyData): + let (_, pts, timeout) = (channelDifferenceEmptyData.flags, channelDifferenceEmptyData.pts, channelDifferenceEmptyData.timeout) var updatedState = state var apiTimeout: Int32? - + apiTimeout = timeout - + let channelPts: Int32 if let _ = updatedState.channelStates[peer.id] { channelPts = pts @@ -3438,9 +3565,10 @@ private func pollChannel(accountPeerId: PeerId, postbox: Postbox, network: Netwo channelPts = pts } updatedState.updateChannelState(peer.id, pts: channelPts) - + return .single((updatedState, true, apiTimeout)) - case let .channelDifferenceTooLong(_, timeout, dialog, messages, chats, users): + case let .channelDifferenceTooLong(channelDifferenceTooLongData): + let (_, timeout, dialog, messages, chats, users) = (channelDifferenceTooLongData.flags, channelDifferenceTooLongData.timeout, channelDifferenceTooLongData.dialog, channelDifferenceTooLongData.messages, channelDifferenceTooLongData.chats, channelDifferenceTooLongData.users) var updatedState = state var apiTimeout: Int32? @@ -3449,7 +3577,8 @@ private func pollChannel(accountPeerId: PeerId, postbox: Postbox, network: Netwo var parameters: (peer: Api.Peer, pts: Int32, topMessage: Int32, readInboxMaxId: Int32, readOutboxMaxId: Int32, unreadCount: Int32, unreadMentionsCount: Int32, unreadReactionsCount: Int32, ttlPeriod: Int32?)? switch dialog { - case let .dialog(_, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, _, pts, _, _, ttlPeriod): + case let .dialog(dialogData): + let (peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, pts, ttlPeriod) = (dialogData.peer, dialogData.topMessage, dialogData.readInboxMaxId, dialogData.readOutboxMaxId, dialogData.unreadCount, dialogData.unreadMentionsCount, dialogData.unreadReactionsCount, dialogData.pts, dialogData.ttlPeriod) if let pts = pts { parameters = (peer, pts, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, ttlPeriod) } @@ -4229,46 +4358,43 @@ func replayFinalState( } } case let .DeleteMessagesWithGlobalIds(ids): - // ANTI-DELETE: Archive messages with full content before deletion if AntiDeleteManager.shared.isEnabled { let messageIds = transaction.messageIdsForGlobalIds(ids) for (index, messageId) in messageIds.enumerated() { - // Skip scheduled/local/quick-reply messages — they get deleted when sent, not by the remote peer - guard messageId.namespace == Namespaces.Message.Cloud else { continue } + guard messageId.namespace == Namespaces.Message.Cloud else { + continue + } if let message = transaction.getMessage(messageId) { let globalId = index < ids.count ? ids[index] : 0 - - // Extract text content let textContent = message.text - // Extract media description - var mediaDesc: String? = nil + var mediaDesc: String? for media in message.media { switch media { case let image as TelegramMediaImage: - mediaDesc = "📷 Photo" + mediaDesc = "Photo" if let largest = image.representations.last { - mediaDesc = "📷 Photo \(largest.dimensions.width)x\(largest.dimensions.height)" + mediaDesc = "Photo \(largest.dimensions.width)x\(largest.dimensions.height)" } case let file as TelegramMediaFile: if file.isVideo { - mediaDesc = "🎬 Video" + mediaDesc = "Video" } else if file.isVoice { - mediaDesc = "🎤 Voice Message" + mediaDesc = "Voice" } else if file.isInstantVideo { - mediaDesc = "📹 Video Message" + mediaDesc = "Video Message" } else if file.isSticker { - mediaDesc = "🎭 Sticker" + mediaDesc = "Sticker" } else { - mediaDesc = "📎 \(file.fileName ?? "File")" + mediaDesc = file.fileName ?? "File" } case is TelegramMediaContact: - mediaDesc = "👤 Contact" + mediaDesc = "Contact" case is TelegramMediaMap: - mediaDesc = "📍 Location" + mediaDesc = "Location" case let poll as TelegramMediaPoll: - mediaDesc = "📊 Poll: \(poll.text)" + mediaDesc = "Poll: \(poll.text)" default: break } @@ -4286,26 +4412,20 @@ func replayFinalState( ) } } - } - - // ANTI-DELETE: Mark messages as deleted instead of removing them - if AntiDeleteManager.shared.isEnabled { - let messageIds = transaction.messageIdsForGlobalIds(ids) + for messageId in messageIds { - // Skip scheduled/local/quick-reply messages — they get deleted when sent, not by the remote peer - guard messageId.namespace == Namespaces.Message.Cloud else { continue } + guard messageId.namespace == Namespaces.Message.Cloud else { + continue + } - // Mark as deleted for icon display AntiDeleteManager.shared.markAsDeleted(peerId: messageId.peerId.toInt64(), messageId: messageId.id) transaction.updateMessage(messageId, update: { currentMessage in var attributes = currentMessage.attributes - // Don't add duplicate DeletedMessageAttribute if !attributes.contains(where: { $0 is DeletedMessageAttribute }) { attributes.append(DeletedMessageAttribute(deletedAt: Int32(Date().timeIntervalSince1970))) } let storeForwardInfo = currentMessage.forwardInfo.flatMap(StoreMessageForwardInfo.init) - // Keep original text, no prefix needed - icon will show deleted status 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)) }) } @@ -4320,50 +4440,48 @@ func replayFinalState( } deletedMessageIds.append(contentsOf: ids.map { .global($0) }) case let .DeleteMessages(ids): - // ANTI-DELETE: Archive channel messages with full content before deletion if AntiDeleteManager.shared.isEnabled { for messageId in ids { - // Skip scheduled/local/quick-reply messages — they get deleted when sent, not by the remote peer - guard messageId.namespace == Namespaces.Message.Cloud else { continue } + guard messageId.namespace == Namespaces.Message.Cloud else { + continue + } if let message = transaction.getMessage(messageId) { - // Extract text content let textContent = message.text - // Extract media description - var mediaDesc: String? = nil + var mediaDesc: String? for media in message.media { switch media { case let image as TelegramMediaImage: - mediaDesc = "📷 Photo" + mediaDesc = "Photo" if let largest = image.representations.last { - mediaDesc = "📷 Photo \(largest.dimensions.width)x\(largest.dimensions.height)" + mediaDesc = "Photo \(largest.dimensions.width)x\(largest.dimensions.height)" } case let file as TelegramMediaFile: if file.isVideo { - mediaDesc = "🎬 Video" + mediaDesc = "Video" } else if file.isVoice { - mediaDesc = "🎤 Voice Message" + mediaDesc = "Voice" } else if file.isInstantVideo { - mediaDesc = "📹 Video Message" + mediaDesc = "Video Message" } else if file.isSticker { - mediaDesc = "🎭 Sticker" + mediaDesc = "Sticker" } else { - mediaDesc = "📎 \(file.fileName ?? "File")" + mediaDesc = file.fileName ?? "File" } case is TelegramMediaContact: - mediaDesc = "👤 Contact" + mediaDesc = "Contact" case is TelegramMediaMap: - mediaDesc = "📍 Location" + mediaDesc = "Location" case let poll as TelegramMediaPoll: - mediaDesc = "📊 Poll: \(poll.text)" + mediaDesc = "Poll: \(poll.text)" default: break } } AntiDeleteManager.shared.archiveMessage( - globalId: messageId.id, // Use message id as globalId for channel messages + globalId: messageId.id, peerId: messageId.peerId.toInt64(), messageId: messageId.id, timestamp: message.timestamp, @@ -4374,39 +4492,26 @@ func replayFinalState( ) } } - } - - // ANTI-DELETE: Mark messages as deleted instead of removing them - if AntiDeleteManager.shared.isEnabled { - // GHOSTGRAM: Collect non-Cloud IDs (scheduled/local) that must be - // physically removed even when AntiDelete is on. Without this, sent - // scheduled messages stay stuck in the scheduled list forever because - // the `continue` guard skips them but nothing else removes them. - var nonCloudIdsToDelete: [MessageId] = [] + var nonCloudIdsToDelete: [MessageId] = [] for messageId in ids { - // Skip scheduled/local/quick-reply messages — they get deleted when sent, not by the remote peer guard messageId.namespace == Namespaces.Message.Cloud else { nonCloudIdsToDelete.append(messageId) continue } - // Mark as deleted for icon display AntiDeleteManager.shared.markAsDeleted(peerId: messageId.peerId.toInt64(), messageId: messageId.id) transaction.updateMessage(messageId, update: { currentMessage in var attributes = currentMessage.attributes - // Don't add duplicate DeletedMessageAttribute if !attributes.contains(where: { $0 is DeletedMessageAttribute }) { attributes.append(DeletedMessageAttribute(deletedAt: Int32(Date().timeIntervalSince1970))) } let storeForwardInfo = currentMessage.forwardInfo.flatMap(StoreMessageForwardInfo.init) - // Keep original text, no prefix needed - icon will show deleted status 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)) }) } - // Physically remove scheduled/local messages that were skipped above if !nonCloudIdsToDelete.isEmpty { _internal_deleteMessages(transaction: transaction, mediaBox: mediaBox, ids: nonCloudIdsToDelete, manualAddMessageThreadStatsDifference: { id, add, remove in addMessageThreadStatsDifference(threadKey: id, remove: remove, addedMessagePeer: nil, addedMessageId: nil, isOutgoing: false) @@ -4476,7 +4581,6 @@ func replayFinalState( } } } else { - // GHOSTGRAM: Save original text before edit EditHistoryManager.shared.saveOriginalText( peerId: id.peerId.toInt64(), messageId: id.id, @@ -4511,12 +4615,14 @@ func replayFinalState( var updatedPoll = poll let resultsMin: Bool switch results { - case let .pollResults(flags, _, _, _, _, _): + case let .pollResults(pollResultsData): + let flags = pollResultsData.flags resultsMin = (flags & (1 << 0)) != 0 } if let apiPoll = apiPoll { switch apiPoll { - case let .poll(id, flags, question, answers, closePeriod, _): + case let .poll(pollData): + let (id, flags, question, answers, closePeriod) = (pollData.id, pollData.flags, pollData.question, pollData.answers, pollData.closePeriod) let publicity: TelegramMediaPollPublicity if (flags & (1 << 1)) != 0 { publicity = .public @@ -4533,7 +4639,8 @@ func replayFinalState( 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) } @@ -4887,9 +4994,11 @@ func replayFinalState( if peerId == accountPeerId { if explicit { switch status { - case let .userStatusOnline(timestamp): + case let .userStatusOnline(userStatusOnlineData): + let timestamp = userStatusOnlineData.expires delayNotificatonsUntil = timestamp + 30 - case let .userStatusOffline(timestamp): + case let .userStatusOffline(userStatusOfflineData): + let timestamp = userStatusOfflineData.wasOnline delayNotificatonsUntil = timestamp default: break @@ -5086,7 +5195,8 @@ func replayFinalState( )) case let .UpdateGroupCallMessage(callId, authorId, isFromAdmin, messageId, text, date, paidMessageStars): switch text { - case let .textWithEntities(text, entities): + case let .textWithEntities(textWithEntitiesData): + let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities) groupCallMessageUpdates.append(GroupCallMessageUpdate(callId: callId, update: .newPlaintextMessage(authorId: authorId, isFromAdmin: isFromAdmin, messageId: messageId, text: text, entities: messageTextEntitiesFromApiEntities(entities), timestamp: date, paidMessageStars: paidMessageStars))) } case let .UpdateGroupCallOpaqueMessage(callId, authorId, data): @@ -5108,7 +5218,8 @@ func replayFinalState( } switch call { - case let .groupCall(flags, _, _, participantsCount, title, _, recordStartDate, scheduleDate, _, _, _, _, sendPaidMessagesStars, _): + case let .groupCall(groupCallData): + let (flags, participantsCount, title, recordStartDate, scheduleDate, sendPaidMessagesStars) = (groupCallData.flags, groupCallData.participantsCount, groupCallData.title, groupCallData.recordStartDate, groupCallData.scheduleDate, groupCallData.sendPaidMessagesStars) let isMin = (flags & (1 << 19)) != 0 let isMuted = (flags & (1 << 1)) != 0 let canChange = (flags & (1 << 2)) != 0 @@ -5125,7 +5236,8 @@ func replayFinalState( break } } - case let .groupCallDiscarded(callId, _, _): + case let .groupCallDiscarded(groupCallDiscardedData): + let callId = groupCallDiscardedData.id updatedGroupCallParticipants.append(( callId, .call(isTerminated: true, defaultParticipantsAreMuted: GroupCallParticipantsContext.State.DefaultParticipantsAreMuted(isMuted: false, canChange: false), messagesAreEnabled: GroupCallParticipantsContext.State.MessagesAreEnabled(isEnabled: false, canChange: false, sendPaidMessagesStars: nil), title: nil, recordingStartTimestamp: nil, scheduleTimestamp: nil, isVideoEnabled: false, participantCount: nil, isMin: false) @@ -5374,8 +5486,8 @@ func replayFinalState( } } } else { - if case let .storyItemDeleted(id) = story { - if let index = updatedPeerEntries.firstIndex(where: { $0.id == id }) { + if case let .storyItemDeleted(storyItemDeletedData) = story { + if let index = updatedPeerEntries.firstIndex(where: { $0.id == storyItemDeletedData.id }) { updatedPeerEntries.remove(at: index) } } @@ -5635,11 +5747,13 @@ func replayFinalState( let namespace: ItemCollectionId.Namespace var items: [ItemCollectionItem] = [] let info: StickerPackCollectionInfo - if case let .stickerSet(set, packs, keywords, documents) = apiSet { + if case let .stickerSet(stickerSetData) = apiSet { + let (set, packs, keywords, documents) = (stickerSetData.set, stickerSetData.packs, stickerSetData.keywords, stickerSetData.documents) var indexKeysByFile: [MediaId: [MemoryBuffer]] = [:] for pack in packs { switch pack { - case let .stickerPack(text, fileIds): + case let .stickerPack(stickerPackData): + let (text, fileIds) = (stickerPackData.emoticon, stickerPackData.documents) let key = ValueBoxKey(text).toMemoryBuffer() for fileId in fileIds { let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: fileId) @@ -5654,7 +5768,8 @@ func replayFinalState( } for keyword in keywords { switch keyword { - case let .stickerKeyword(documentId, texts): + case let .stickerKeyword(stickerKeywordData): + let (documentId, texts) = (stickerKeywordData.documentId, stickerKeywordData.keyword) for text in texts { let key = ValueBoxKey(text).toMemoryBuffer() let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: documentId) @@ -5679,7 +5794,8 @@ func replayFinalState( } } switch set { - 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 { @@ -5918,12 +6034,14 @@ func replayFinalState( let sortedLangPackDifference = langPackDifference.sorted(by: { lhs, rhs in let lhsVersion: Int32 switch lhs { - case let .langPackDifference(_, fromVersion, _, _): + case let .langPackDifference(langPackDifferenceData): + let (fromVersion) = (langPackDifferenceData.fromVersion) lhsVersion = fromVersion } let rhsVersion: Int32 switch rhs { - case let .langPackDifference(_, fromVersion, _, _): + case let .langPackDifference(langPackDifferenceData): + let (fromVersion) = (langPackDifferenceData.fromVersion) rhsVersion = fromVersion } return lhsVersion < rhsVersion diff --git a/submodules/TelegramCore/Sources/State/AccountStateManager.swift b/submodules/TelegramCore/Sources/State/AccountStateManager.swift index 75c8b017..eea995bc 100644 --- a/submodules/TelegramCore/Sources/State/AccountStateManager.swift +++ b/submodules/TelegramCore/Sources/State/AccountStateManager.swift @@ -925,7 +925,8 @@ public final class AccountStateManager { return postbox.transaction { transaction -> (difference: Api.updates.Difference?, finalStatte: AccountReplayedFinalState?, skipBecauseOfError: Bool, resetState: Bool) in if let currentState = transaction.getState() as? AuthorizedAccountState { switch state { - case let .state(pts, qts, date, seq, _): + case let .state(stateData): + let (pts, qts, date, seq) = (stateData.pts, stateData.qts, stateData.date, stateData.seq) transaction.setState(currentState.changedState(AuthorizedAccountState.State(pts: pts, qts: qts, date: date, seq: seq))) } } @@ -1883,10 +1884,12 @@ public final class AccountStateManager { if let updates = Api.parse(Buffer(data: rawData)) as? Api.Updates { switch updates { - case let .updates(updates, _, _, _, _): + case let .updates(updatesData): + let updates = updatesData.updates for update in updates { switch update { - case let .updatePhoneCall(phoneCall): + case let .updatePhoneCall(updatePhoneCallData): + let phoneCall = updatePhoneCallData.phoneCall if let callSessionManager = self.callSessionManager { callSessionManager.updateSession(phoneCall, completion: { result in completion(result) @@ -2297,17 +2300,20 @@ public final class AccountStateManager { return nil } switch updates { - case let .updates(updates, users, _, _, _): + case let .updates(updatesData): + let (updates, users) = (updatesData.updates, updatesData.users) var peers: [Peer] = [] for user in users { peers.append(TelegramUser(user: user)) } - + for update in updates { switch update { - case let .updatePhoneCall(phoneCall): + case let .updatePhoneCall(updatePhoneCallData): + let phoneCall = updatePhoneCallData.phoneCall switch phoneCall { - case let .phoneCallRequested(flags, id, accessHash, date, adminId, _, _, _): + case let .phoneCallRequested(phoneCallRequestedData): + let (flags, id, accessHash, date, adminId) = (phoneCallRequestedData.flags, phoneCallRequestedData.id, phoneCallRequestedData.accessHash, phoneCallRequestedData.date, phoneCallRequestedData.adminId) guard let peer = peers.first(where: { $0.id == PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(adminId)) }) else { return nil } diff --git a/submodules/TelegramCore/Sources/State/AccountViewTracker.swift b/submodules/TelegramCore/Sources/State/AccountViewTracker.swift index ae88fa3c..9772f2bc 100644 --- a/submodules/TelegramCore/Sources/State/AccountViewTracker.swift +++ b/submodules/TelegramCore/Sources/State/AccountViewTracker.swift @@ -87,10 +87,11 @@ private func fetchWebpage(account: Account, messageId: MessageId, threadId: Int6 } } else { switch inputPeer { - case let .inputPeerChannel(channelId, accessHash): - messages = account.network.request(Api.functions.channels.getMessages(channel: Api.InputChannel.inputChannel(channelId: channelId, accessHash: accessHash), id: [Api.InputMessage.inputMessageID(id: messageId.id)])) + case let .inputPeerChannel(inputPeerChannelData): + let (channelId, accessHash) = (inputPeerChannelData.channelId, inputPeerChannelData.accessHash) + messages = account.network.request(Api.functions.channels.getMessages(channel: Api.InputChannel.inputChannel(.init(channelId: channelId, accessHash: accessHash)), id: [Api.InputMessage.inputMessageID(.init(id: messageId.id))])) default: - messages = account.network.request(Api.functions.messages.getMessages(id: [Api.InputMessage.inputMessageID(id: messageId.id)])) + messages = account.network.request(Api.functions.messages.getMessages(id: [Api.InputMessage.inputMessageID(.init(id: messageId.id))])) } } return messages @@ -100,17 +101,20 @@ private func fetchWebpage(account: Account, messageId: MessageId, threadId: Int6 let chats: [Api.Chat] let users: [Api.User] switch result { - case let .messages(messages: apiMessages, topics: apiTopics, chats: apiChats, users: apiUsers): + case let .messages(messagesData): + let (apiMessages, apiTopics, apiChats, apiUsers) = (messagesData.messages, messagesData.topics, messagesData.chats, messagesData.users) let _ = apiTopics messages = apiMessages chats = apiChats users = apiUsers - case let .messagesSlice(_, _, _, _, _, messages: apiMessages, topics: apiTopics, chats: apiChats, users: apiUsers): + case let .messagesSlice(messagesSliceData): + let (apiMessages, apiTopics, apiChats, apiUsers) = (messagesSliceData.messages, messagesSliceData.topics, messagesSliceData.chats, messagesSliceData.users) let _ = apiTopics messages = apiMessages chats = apiChats users = apiUsers - case let .channelMessages(_, _, _, _, apiMessages, apiTopics, apiChats, apiUsers): + case let .channelMessages(channelMessagesData): + let (apiMessages, apiTopics, apiChats, apiUsers) = (channelMessagesData.messages, channelMessagesData.topics, channelMessagesData.chats, channelMessagesData.users) messages = apiMessages let _ = apiTopics chats = apiChats @@ -719,10 +723,11 @@ public final class AccountViewTracker { return .single(nil) } |> mapToSignal { result -> Signal<[MessageId: ViewCountContextState], NoError> in - guard case let .messageViews(viewCounts, chats, users)? = result else { + guard case let .messageViews(messageViewsData)? = result else { return .complete() } - + let (viewCounts, chats, users) = (messageViewsData.views, messageViewsData.chats, messageViewsData.users) + return account.postbox.transaction { transaction -> [MessageId: ViewCountContextState] in var resultStates: [MessageId: ViewCountContextState] = [:] @@ -732,7 +737,8 @@ public final class AccountViewTracker { for i in 0 ..< messageIds.count { if i < viewCounts.count { - if case let .messageViews(_, views, forwards, replies) = viewCounts[i] { + if case let .messageViews(messageViewsData) = viewCounts[i] { + let (views, forwards, replies) = (messageViewsData.views, messageViewsData.forwards, messageViewsData.replies) transaction.updateMessage(messageIds[i], update: { currentMessage in let storeForwardInfo = currentMessage.forwardInfo.flatMap(StoreMessageForwardInfo.init) var attributes = currentMessage.attributes @@ -744,7 +750,8 @@ public final class AccountViewTracker { var repliesReadMaxId: Int32? if let replies = replies { switch replies { - case let .messageReplies(_, repliesCountValue, _, recentRepliers, channelId, maxId, readMaxId): + case let .messageReplies(messageRepliesData): + let (repliesCountValue, recentRepliers, channelId, maxId, readMaxId) = (messageRepliesData.replies, messageRepliesData.recentRepliers, messageRepliesData.channelId, messageRepliesData.maxId, messageRepliesData.readMaxId) if let channelId = channelId { commentsChannelId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) } @@ -861,18 +868,22 @@ public final class AccountViewTracker { return account.postbox.transaction { transaction -> Void in let updateList: [Api.Update] switch updates { - case let .updates(updates, _, _, _, _): + case let .updates(updatesData): + let updates = updatesData.updates updateList = updates - case let .updatesCombined(updates, _, _, _, _, _): + case let .updatesCombined(updatesCombinedData): + let updates = updatesCombinedData.updates updateList = updates - case let .updateShort(update, _): + case let .updateShort(updateShortData): + let update = updateShortData.update updateList = [update] default: updateList = [] } for update in updateList { switch update { - case let .updateMessageReactions(_, peer, msgId, _, _, reactions): + case let .updateMessageReactions(updateMessageReactionsData): + let (peer, msgId, reactions) = (updateMessageReactionsData.peer, updateMessageReactionsData.msgId, updateMessageReactionsData.reactions) transaction.updateMessage(MessageId(peerId: peer.peerId, namespace: Namespaces.Message.Cloud, id: msgId), update: { currentMessage in var updatedReactions = ReactionsMessageAttribute(apiReactions: reactions) @@ -949,8 +960,9 @@ public final class AccountViewTracker { case .inputPeerChat, .inputPeerSelf, .inputPeerUser: request = account.network.request(Api.functions.messages.readMessageContents(id: messageIds.map { $0.id })) |> map { _ in true } - case let .inputPeerChannel(channelId, accessHash): - request = account.network.request(Api.functions.channels.readMessageContents(channel: .inputChannel(channelId: channelId, accessHash: accessHash), id: messageIds.map { $0.id })) + case let .inputPeerChannel(inputPeerChannelData): + let (channelId, accessHash) = (inputPeerChannelData.channelId, inputPeerChannelData.accessHash) + request = account.network.request(Api.functions.channels.readMessageContents(channel: .inputChannel(.init(channelId: channelId, accessHash: accessHash)), id: messageIds.map { $0.id })) |> map { _ in true } default: return .complete() @@ -1074,10 +1086,10 @@ public final class AccountViewTracker { fetchSignal = .never() } } else if peerIdAndThreadId.peerId.namespace == Namespaces.Peer.CloudUser || peerIdAndThreadId.peerId.namespace == Namespaces.Peer.CloudGroup { - fetchSignal = account.network.request(Api.functions.messages.getMessages(id: messageIds.map { Api.InputMessage.inputMessageID(id: $0.id) })) + fetchSignal = account.network.request(Api.functions.messages.getMessages(id: messageIds.map { Api.InputMessage.inputMessageID(.init(id: $0.id)) })) } else if peerIdAndThreadId.peerId.namespace == Namespaces.Peer.CloudChannel { if let inputChannel = apiInputChannel(peer) { - fetchSignal = account.network.request(Api.functions.channels.getMessages(channel: inputChannel, id: messageIds.map { Api.InputMessage.inputMessageID(id: $0.id) })) + fetchSignal = account.network.request(Api.functions.channels.getMessages(channel: inputChannel, id: messageIds.map { Api.InputMessage.inputMessageID(.init(id: $0.id)) })) } } guard let signal = fetchSignal else { @@ -1087,11 +1099,14 @@ public final class AccountViewTracker { return signal |> map { result -> (Peer, [Api.Message], [Api.Chat], [Api.User]) in switch result { - case let .messages(messages, _, chats, users): + case let .messages(messagesData): + let (messages, chats, users) = (messagesData.messages, messagesData.chats, messagesData.users) return (peer, messages, chats, users) - case let .messagesSlice(_, _, _, _, _, messages, _, chats, users): + case let .messagesSlice(messagesSliceData): + let (messages, chats, users) = (messagesSliceData.messages, messagesSliceData.chats, messagesSliceData.users) return (peer, messages, chats, users) - case let .channelMessages(_, _, _, _, messages, _, chats, users): + case let .channelMessages(channelMessagesData): + let (messages, chats, users) = (channelMessagesData.messages, channelMessagesData.chats, channelMessagesData.users) return (peer, messages, chats, users) case .messagesNotModified: return (peer, [], [], []) @@ -1180,7 +1195,7 @@ public final class AccountViewTracker { var requests: [Signal] = [] for reference in stickerPacks { if case let .id(id, accessHash) = reference { - requests.append(account.network.request(Api.functions.messages.getStickerSet(stickerset: .inputStickerSetID(id: id, accessHash: accessHash), hash: 0)) + requests.append(account.network.request(Api.functions.messages.getStickerSet(stickerset: .inputStickerSetID(.init(id: id, accessHash: accessHash)), hash: 0)) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -1196,7 +1211,8 @@ public final class AccountViewTracker { return account.postbox.transaction { transaction -> Void in for result in results { switch result { - case let .stickerSet(_, _, _, documents)?: + case let .stickerSet(stickerSetData)?: + let documents = stickerSetData.documents for document in documents { if let file = telegramMediaFileFromApiDocument(document, altDocuments: []) { if transaction.getMedia(file.fileId) != nil { @@ -1440,7 +1456,8 @@ public final class AccountViewTracker { if i < slice.count { let value = result[i] switch value { - case let .recentStory(flags, maxId): + case let .recentStory(recentStoryData): + let (flags, maxId) = (recentStoryData.flags, recentStoryData.maxId) if let maxId { transaction.setStoryItemsInexactMaxId(peerId: slice[i].0, id: maxId, hasLiveItems: (flags & (1 << 0)) != 0) } else { @@ -1552,7 +1569,8 @@ public final class AccountViewTracker { case .requirementToContactPremium: flags.insert(.premiumRequired) sendPaidMessageStars = nil - case let .requirementToContactPaidMessages(starsAmount): + case let .requirementToContactPaidMessages(requirementToContactPaidMessagesData): + let starsAmount = requirementToContactPaidMessagesData.starsAmount flags.remove(.premiumRequired) sendPaidMessageStars = StarsAmount(value: starsAmount, nanos: 0) } diff --git a/submodules/TelegramCore/Sources/State/AppConfiguration.swift b/submodules/TelegramCore/Sources/State/AppConfiguration.swift index 7b081fb9..4e36d2cf 100644 --- a/submodules/TelegramCore/Sources/State/AppConfiguration.swift +++ b/submodules/TelegramCore/Sources/State/AppConfiguration.swift @@ -8,7 +8,7 @@ public func currentAppConfiguration(transaction: Transaction) -> AppConfiguratio } } -func updateAppConfiguration(transaction: Transaction, _ f: (AppConfiguration) -> AppConfiguration) { +public func updateAppConfiguration(transaction: Transaction, _ f: (AppConfiguration) -> AppConfiguration) { let current = currentAppConfiguration(transaction: transaction) let updated = f(current) if updated != current { diff --git a/submodules/TelegramCore/Sources/State/AppUpdate.swift b/submodules/TelegramCore/Sources/State/AppUpdate.swift index 753bad03..04c16418 100644 --- a/submodules/TelegramCore/Sources/State/AppUpdate.swift +++ b/submodules/TelegramCore/Sources/State/AppUpdate.swift @@ -22,7 +22,8 @@ public struct AppUpdateInfo: Equatable { extension AppUpdateInfo { init?(apiAppUpdate: Api.help.AppUpdate) { switch apiAppUpdate { - case let .appUpdate(flags, _, version, text, entities, _, _, _): + case let .appUpdate(appUpdateData): + let (flags, version, text, entities) = (appUpdateData.flags, appUpdateData.version, appUpdateData.text, appUpdateData.entities) self.blocking = (flags & (1 << 0)) != 0 self.version = version self.text = text diff --git a/submodules/TelegramCore/Sources/State/ApplyUpdateMessage.swift b/submodules/TelegramCore/Sources/State/ApplyUpdateMessage.swift index 56c75694..a5249dc8 100644 --- a/submodules/TelegramCore/Sources/State/ApplyUpdateMessage.swift +++ b/submodules/TelegramCore/Sources/State/ApplyUpdateMessage.swift @@ -67,7 +67,8 @@ func applyUpdateMessage(postbox: Postbox, stateManager: AccountStateManager, mes for update in result.allUpdates { switch update { - case let .updateMessageID(id, randomId): + case let .updateMessageID(updateMessageIDData): + let (id, randomId) = (updateMessageIDData.id, updateMessageIDData.randomId) for attribute in message.attributes { if let attribute = attribute as? OutgoingMessageInfoAttribute { if attribute.uniqueId == randomId { @@ -104,16 +105,19 @@ func applyUpdateMessage(postbox: Postbox, stateManager: AccountStateManager, mes var updatedTimestamp: Int32? if let apiMessage = apiMessage { switch apiMessage { - case let .message(_, _, _, _, _, _, _, _, _, _, _, date, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + case let .message(messageData): + let date = messageData.date updatedTimestamp = date case .messageEmpty: break - case let .messageService(_, _, _, _, _, _, date, _, _, _): + case let .messageService(messageServiceData): + let date = messageServiceData.date updatedTimestamp = date } } else { switch result { - case let .updateShortSentMessage(_, _, _, _, date, _, _, _): + case let .updateShortSentMessage(updateShortSentMessageData): + let (_, _, _, _, date, _, _, _) = (updateShortSentMessageData.flags, updateShortSentMessageData.id, updateShortSentMessageData.pts, updateShortSentMessageData.ptsCount, updateShortSentMessageData.date, updateShortSentMessageData.media, updateShortSentMessageData.entities, updateShortSentMessageData.ttlPeriod) updatedTimestamp = date default: break @@ -151,7 +155,8 @@ func applyUpdateMessage(postbox: Postbox, stateManager: AccountStateManager, mes text = updatedMessage.text forwardInfo = updatedMessage.forwardInfo threadId = updatedMessage.threadId - } else if case let .updateShortSentMessage(_, _, _, _, _, apiMedia, entities, ttlPeriod) = result { + } else if case let .updateShortSentMessage(updateShortSentMessageData) = result { + let (_, _, _, _, _, apiMedia, entities, ttlPeriod) = (updateShortSentMessageData.flags, updateShortSentMessageData.id, updateShortSentMessageData.pts, updateShortSentMessageData.ptsCount, updateShortSentMessageData.date, updateShortSentMessageData.media, updateShortSentMessageData.entities, updateShortSentMessageData.ttlPeriod) let (mediaValue, _, nonPremium, hasSpoiler, _, _) = textMediaAndExpirationTimerFromApiMedia(apiMedia, currentMessage.id.peerId) if let mediaValue = mediaValue { media = [mediaValue] @@ -400,7 +405,7 @@ func applyUpdateGroupMessages(postbox: Postbox, stateManager: AccountStateManage } else if let message = messages.first, let apiMessage = result.messages.first { if message.scheduleTime != nil && message.scheduleTime == apiMessage.timestamp { namespace = Namespaces.Message.ScheduledCloud - } else if let apiMessage = result.messages.first, case let .message(_, flags2, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _) = apiMessage, (flags2 & (1 << 4)) != 0 { + } else if let apiMessage = result.messages.first, case let .message(messageData) = apiMessage, (messageData.flags2 & (1 << 4)) != 0 { namespace = Namespaces.Message.ScheduledCloud } } diff --git a/submodules/TelegramCore/Sources/State/AvailableMessageEffects.swift b/submodules/TelegramCore/Sources/State/AvailableMessageEffects.swift index f5bf7e5b..e699d92b 100644 --- a/submodules/TelegramCore/Sources/State/AvailableMessageEffects.swift +++ b/submodules/TelegramCore/Sources/State/AvailableMessageEffects.swift @@ -173,7 +173,8 @@ public final class AvailableMessageEffects: Equatable, Codable { private extension AvailableMessageEffects.MessageEffect { convenience init?(apiMessageEffect: Api.AvailableEffect, files: [Int64: TelegramMediaFile]) { switch apiMessageEffect { - case let .availableEffect(flags, id, emoticon, staticIconId, effectStickerId, effectAnimationId): + case let .availableEffect(availableEffectData): + let (flags, id, emoticon, staticIconId, effectStickerId, effectAnimationId) = (availableEffectData.flags, availableEffectData.id, availableEffectData.emoticon, availableEffectData.staticIconId, availableEffectData.effectStickerId, availableEffectData.effectAnimationId) guard let effectSticker = files[effectStickerId] else { return nil } @@ -239,7 +240,8 @@ func managedSynchronizeAvailableMessageEffects(postbox: Postbox, network: Networ return .complete() } switch result { - case let .availableEffects(hash, effects, documents): + case let .availableEffects(availableEffectsData): + let (hash, effects, documents) = (availableEffectsData.hash, availableEffectsData.effects, availableEffectsData.documents) var files: [Int64: TelegramMediaFile] = [:] for document in documents { if let file = telegramMediaFileFromApiDocument(document, altDocuments: []) { diff --git a/submodules/TelegramCore/Sources/State/AvailableReactions.swift b/submodules/TelegramCore/Sources/State/AvailableReactions.swift index c9b304da..c6689042 100644 --- a/submodules/TelegramCore/Sources/State/AvailableReactions.swift +++ b/submodules/TelegramCore/Sources/State/AvailableReactions.swift @@ -314,7 +314,8 @@ public final class AvailableReactions: Equatable, Codable { private extension AvailableReactions.Reaction { convenience init?(apiReaction: Api.AvailableReaction) { switch apiReaction { - case let .availableReaction(flags, reaction, title, staticIcon, appearAnimation, selectAnimation, activateAnimation, effectAnimation, aroundAnimation, centerIcon): + case let .availableReaction(availableReactionData): + let (flags, reaction, title, staticIcon, appearAnimation, selectAnimation, activateAnimation, effectAnimation, aroundAnimation, centerIcon) = (availableReactionData.flags, availableReactionData.reaction, availableReactionData.title, availableReactionData.staticIcon, availableReactionData.appearAnimation, availableReactionData.selectAnimation, availableReactionData.activateAnimation, availableReactionData.effectAnimation, availableReactionData.aroundAnimation, availableReactionData.centerIcon) guard let staticIconFile = telegramMediaFileFromApiDocument(staticIcon, altDocuments: []) else { return nil } @@ -419,7 +420,8 @@ func managedSynchronizeAvailableReactions(postbox: Postbox, network: Network) -> } switch result { - case let .availableReactions(hash, reactions): + case let .availableReactions(availableReactionsData): + let (hash, reactions) = (availableReactionsData.hash, availableReactionsData.reactions) let availableReactions = AvailableReactions( hash: hash, reactions: reactions.compactMap(AvailableReactions.Reaction.init(apiReaction:)) diff --git a/submodules/TelegramCore/Sources/State/CallSessionManager.swift b/submodules/TelegramCore/Sources/State/CallSessionManager.swift index f49db116..f5eb58ef 100644 --- a/submodules/TelegramCore/Sources/State/CallSessionManager.swift +++ b/submodules/TelegramCore/Sources/State/CallSessionManager.swift @@ -66,7 +66,8 @@ public struct GroupCallReference: Codable, Equatable { extension GroupCallReference { init?(_ apiGroupCall: Api.InputGroupCall) { switch apiGroupCall { - case let .inputGroupCall(id, accessHash): + case let .inputGroupCall(inputGroupCallData): + let (id, accessHash) = (inputGroupCallData.id, inputGroupCallData.accessHash) self.init(id: id, accessHash: accessHash) case .inputGroupCallSlug, .inputGroupCallInviteMessage: return nil @@ -74,7 +75,7 @@ extension GroupCallReference { } var apiInputGroupCall: Api.InputGroupCall { - return .inputGroupCall(id: self.id, accessHash: self.accessHash) + return .inputGroupCall(.init(id: self.id, accessHash: self.accessHash)) } } @@ -329,10 +330,12 @@ public enum CallSessionConnection: Equatable { private func parseConnection(_ apiConnection: Api.PhoneConnection) -> CallSessionConnection { switch apiConnection { - case let .phoneConnection(flags, id, ip, ipv6, port, peerTag): + case let .phoneConnection(phoneConnectionData): + let (flags, id, ip, ipv6, port, peerTag) = (phoneConnectionData.flags, phoneConnectionData.id, phoneConnectionData.ip, phoneConnectionData.ipv6, phoneConnectionData.port, phoneConnectionData.peerTag) let isTcp = (flags & (1 << 0)) != 0 return .reflector(CallSessionConnection.Reflector(id: id, ip: ip, ipv6: ipv6, isTcp: isTcp, port: port, peerTag: peerTag.makeData())) - case let .phoneConnectionWebrtc(flags, id, ip, ipv6, port, username, password): + case let .phoneConnectionWebrtc(phoneConnectionWebrtcData): + let (flags, id, ip, ipv6, port, username, password) = (phoneConnectionWebrtcData.flags, phoneConnectionWebrtcData.id, phoneConnectionWebrtcData.ip, phoneConnectionWebrtcData.ipv6, phoneConnectionWebrtcData.port, phoneConnectionWebrtcData.username, phoneConnectionWebrtcData.password) return .webRtcReflector(CallSessionConnection.WebRtcReflector( id: id, hasStun: (flags & (1 << 1)) != 0, @@ -751,7 +754,7 @@ private final class CallSessionManagerContext { self.contexts[internalId] = context let queue = self.queue - let requestSignal: Signal = self.network.request(Api.functions.phone.receivedCall(peer: .inputPhoneCall(id: stableId, accessHash: accessHash))) + let requestSignal: Signal = self.network.request(Api.functions.phone.receivedCall(peer: .inputPhoneCall(.init(id: stableId, accessHash: accessHash)))) context.acknowledgeIncomingCallDisposable.set(requestSignal.start(error: { [weak self] _ in queue.async { @@ -1018,7 +1021,7 @@ private final class CallSessionManagerContext { if let context = self.contexts[internalId] { switch context.state { case let .active(id, accessHash, _, _, _, _, _, _, _, _, _, _): - context.signalingDisposables.add(self.network.request(Api.functions.phone.sendSignalingData(peer: .inputPhoneCall(id: id, accessHash: accessHash), data: Buffer(data: data))).start()) + context.signalingDisposables.add(self.network.request(Api.functions.phone.sendSignalingData(peer: .inputPhoneCall(.init(id: id, accessHash: accessHash)), data: Buffer(data: data))).start()) default: break } @@ -1073,10 +1076,12 @@ private final class CallSessionManagerContext { switch call { case .phoneCallEmpty: break - case let .phoneCallAccepted(_, id, _, _, _, _, gB, remoteProtocol): + case let .phoneCallAccepted(phoneCallAcceptedData): + let (id, gB, remoteProtocol) = (phoneCallAcceptedData.id, phoneCallAcceptedData.gB, phoneCallAcceptedData.protocol) let remoteVersions: [String] switch remoteProtocol { - case let .phoneCallProtocol(_, _, _, versions): + case let .phoneCallProtocol(phoneCallProtocolData): + let versions = phoneCallProtocolData.libraryVersions remoteVersions = versions } if let internalId = self.contextIdByStableId[id] { @@ -1129,7 +1134,8 @@ private final class CallSessionManagerContext { assertionFailure() } } - case let .phoneCallDiscarded(flags, id, reason, _): + case let .phoneCallDiscarded(phoneCallDiscardedData): + let (flags, id, reason) = (phoneCallDiscardedData.flags, phoneCallDiscardedData.id, phoneCallDiscardedData.reason) let reportRating = (flags & (1 << 2)) != 0 let sendDebugLogs = (flags & (1 << 3)) != 0 if let internalId = self.contextIdByStableId[id] { @@ -1145,7 +1151,8 @@ private final class CallSessionManagerContext { parsedReason = .ended(.hungUp) case .phoneCallDiscardReasonMissed: parsedReason = .ended(.missed) - case let .phoneCallDiscardReasonMigrateConferenceCall(slug): + case let .phoneCallDiscardReasonMigrateConferenceCall(phoneCallDiscardReasonMigrateConferenceCallData): + let slug = phoneCallDiscardReasonMigrateConferenceCallData.slug parsedReason = .ended(.switchedToConference(slug: slug)) } } else { @@ -1185,7 +1192,8 @@ private final class CallSessionManagerContext { //assertionFailure() } } - case let .phoneCall(flags, id, _, _, _, _, gAOrB, keyFingerprint, callProtocol, connections, startDate, customParameters): + case let .phoneCall(phoneCallData): + let (flags, id, gAOrB, keyFingerprint, callProtocol, connections, startDate, customParameters) = (phoneCallData.flags, phoneCallData.id, phoneCallData.gAOrB, phoneCallData.keyFingerprint, phoneCallData.protocol, phoneCallData.connections, phoneCallData.startDate, phoneCallData.customParameters) let allowsP2P = (flags & (1 << 5)) != 0 let supportsConferenceCalls = (flags & (1 << 8)) != 0 if let internalId = self.contextIdByStableId[id] { @@ -1200,19 +1208,21 @@ private final class CallSessionManagerContext { if let (key, calculatedKeyId, keyVisualHash) = self.makeSessionEncryptionKey(config: config, gAHash: gAHash, b: b, gA: gAOrB.makeData()) { if keyFingerprint == calculatedKeyId { switch callProtocol { - case let .phoneCallProtocol(_, _, maxLayer, versions): + case let .phoneCallProtocol(phoneCallProtocolData): + let (maxLayer, versions) = (phoneCallProtocolData.maxLayer, phoneCallProtocolData.libraryVersions) if !versions.isEmpty { var customParametersValue: String? switch customParameters { case .none: break - case let .dataJSON(data): + case let .dataJSON(dataJSONData): + let data = dataJSONData.data customParametersValue = data } - + let isVideoPossible = self.videoVersions().contains(where: { versions.contains($0) }) context.isVideoPossible = isVideoPossible - + context.state = .active(id: id, accessHash: accessHash, beginTimestamp: startDate, key: key, keyId: calculatedKeyId, keyVisualHash: keyVisualHash, connections: parseConnectionSet(primary: connections.first!, alternative: Array(connections[1...])), maxLayer: maxLayer, version: versions[0], customParameters: customParametersValue, allowsP2P: allowsP2P, supportsConferenceCalls: supportsConferenceCalls) self.contextUpdated(internalId: internalId) } else { @@ -1227,19 +1237,21 @@ private final class CallSessionManagerContext { } case let .confirming(id, accessHash, key, keyId, keyVisualHash, _): switch callProtocol { - case let .phoneCallProtocol(_, _, maxLayer, versions): + case let .phoneCallProtocol(phoneCallProtocolData): + let (maxLayer, versions) = (phoneCallProtocolData.maxLayer, phoneCallProtocolData.libraryVersions) if !versions.isEmpty { var customParametersValue: String? switch customParameters { case .none: break - case let .dataJSON(data): + case let .dataJSON(dataJSONData): + let data = dataJSONData.data customParametersValue = data } - + let isVideoPossible = self.videoVersions().contains(where: { versions.contains($0) }) context.isVideoPossible = isVideoPossible - + context.state = .active(id: id, accessHash: accessHash, beginTimestamp: startDate, key: key, keyId: keyId, keyVisualHash: keyVisualHash, connections: parseConnectionSet(primary: connections.first!, alternative: Array(connections[1...])), maxLayer: maxLayer, version: versions[0], customParameters: customParametersValue, allowsP2P: allowsP2P, supportsConferenceCalls: supportsConferenceCalls) self.contextUpdated(internalId: internalId) } else { @@ -1251,11 +1263,13 @@ private final class CallSessionManagerContext { assertionFailure() } } - case let .phoneCallRequested(flags, id, accessHash, date, adminId, _, gAHash, requestedProtocol): + case let .phoneCallRequested(phoneCallRequestedData): + let (flags, id, accessHash, date, adminId, gAHash, requestedProtocol) = (phoneCallRequestedData.flags, phoneCallRequestedData.id, phoneCallRequestedData.accessHash, phoneCallRequestedData.date, phoneCallRequestedData.adminId, phoneCallRequestedData.gAHash, phoneCallRequestedData.protocol) let isVideo = (flags & (1 << 6)) != 0 let versions: [String] switch requestedProtocol { - case let .phoneCallProtocol(_, _, _, libraryVersions): + case let .phoneCallProtocol(phoneCallProtocolData): + let libraryVersions = phoneCallProtocolData.libraryVersions versions = libraryVersions } if self.contextIdByStableId[id] == nil { @@ -1276,7 +1290,8 @@ private final class CallSessionManagerContext { } } } - case let .phoneCallWaiting(_, id, _, _, _, _, _, receiveDate): + case let .phoneCallWaiting(phoneCallWaitingData): + let (id, receiveDate) = (phoneCallWaitingData.id, phoneCallWaitingData.receiveDate) if let internalId = self.contextIdByStableId[id] { if let context = self.contexts[internalId] { switch context.state { @@ -1598,7 +1613,7 @@ private func acceptCallSession(accountPeerId: PeerId, postbox: Postbox, network: return .single(.failed) } - return network.request(Api.functions.phone.acceptCall(peer: .inputPhoneCall(id: stableId, accessHash: accessHash), gB: Buffer(data: gb), protocol: .phoneCallProtocol(flags: (1 << 0) | (1 << 1), minLayer: minLayer, maxLayer: maxLayer, libraryVersions: versions))) + return network.request(Api.functions.phone.acceptCall(peer: .inputPhoneCall(.init(id: stableId, accessHash: accessHash)), gB: Buffer(data: gb), protocol: .phoneCallProtocol(.init(flags: (1 << 0) | (1 << 1), minLayer: minLayer, maxLayer: maxLayer, libraryVersions: versions)))) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -1607,7 +1622,8 @@ private func acceptCallSession(accountPeerId: PeerId, postbox: Postbox, network: if let call = call { return postbox.transaction { transaction -> AcceptCallResult in switch call { - case let .phoneCall(phoneCall, users): + case let .phoneCall(phoneCallData): + let (phoneCall, users) = (phoneCallData.phoneCall, phoneCallData.users) updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(users: users)) switch phoneCall { @@ -1615,19 +1631,22 @@ private func acceptCallSession(accountPeerId: PeerId, postbox: Postbox, network: return .failed case .phoneCallWaiting: return .success(.waiting(config: config)) - case let .phoneCall(flags, id, _, _, _, _, gAOrB, _, callProtocol, connections, startDate, customParameters): + case let .phoneCall(phoneCallData): + let (flags, id, gAOrB, callProtocol, connections, startDate, customParameters) = (phoneCallData.flags, phoneCallData.id, phoneCallData.gAOrB, phoneCallData.protocol, phoneCallData.connections, phoneCallData.startDate, phoneCallData.customParameters) if id == stableId { switch callProtocol{ - case let .phoneCallProtocol(_, _, maxLayer, versions): + case let .phoneCallProtocol(phoneCallProtocolData): + let (maxLayer, versions) = (phoneCallProtocolData.maxLayer, phoneCallProtocolData.libraryVersions) if !versions.isEmpty { var customParametersValue: String? switch customParameters { case .none: break - case let .dataJSON(data): + case let .dataJSON(dataJSONData): + let data = dataJSONData.data customParametersValue = data } - + return .success(.call(config: config, gA: gAOrB.makeData(), timestamp: startDate, connections: parseConnectionSet(primary: connections.first!, alternative: Array(connections[1...])), maxLayer: maxLayer, version: versions[0], customParameters: customParametersValue, allowsP2P: (flags & (1 << 5)) != 0, supportsConferenceCalls: (flags & (1 << 8)) != 0)) } else { return .failed @@ -1672,14 +1691,17 @@ private func requestCallSession(postbox: Postbox, network: Network, peerId: Peer callFlags |= 1 << 0 } - return network.request(Api.functions.phone.requestCall(flags: callFlags, userId: inputUser, randomId: Int32(bitPattern: arc4random()), gAHash: Buffer(data: gAHash), protocol: .phoneCallProtocol(flags: (1 << 0) | (1 << 1), minLayer: minLayer, maxLayer: maxLayer, libraryVersions: versions))) + return network.request(Api.functions.phone.requestCall(flags: callFlags, userId: inputUser, randomId: Int32(bitPattern: arc4random()), gAHash: Buffer(data: gAHash), protocol: .phoneCallProtocol(.init(flags: (1 << 0) | (1 << 1), minLayer: minLayer, maxLayer: maxLayer, libraryVersions: versions)))) |> map { result -> RequestCallSessionResult in switch result { - case let .phoneCall(phoneCall, _): + case let .phoneCall(phoneCallData): + let (phoneCall, _) = (phoneCallData.phoneCall, phoneCallData.users) switch phoneCall { - case let .phoneCallRequested(_, id, accessHash, _, _, _, _, _): + case let .phoneCallRequested(phoneCallRequestedData): + let (id, accessHash) = (phoneCallRequestedData.id, phoneCallRequestedData.accessHash) return .success(id: id, accessHash: accessHash, config: config, gA: ga, remoteConfirmationTimestamp: nil) - case let .phoneCallWaiting(_, id, accessHash, _, _, _, _, receiveDate): + case let .phoneCallWaiting(phoneCallWaitingData): + let (id, accessHash, receiveDate) = (phoneCallWaitingData.id, phoneCallWaitingData.accessHash, phoneCallWaitingData.receiveDate) return .success(id: id, accessHash: accessHash, config: config, gA: ga, remoteConfirmationTimestamp: receiveDate) default: return .failed(.generic) @@ -1709,7 +1731,7 @@ private func requestCallSession(postbox: Postbox, network: Network, peerId: Peer } private func confirmCallSession(network: Network, stableId: CallSessionStableId, accessHash: Int64, gA: Data, keyFingerprint: Int64, maxLayer: Int32, versions: [String]) -> Signal { - return network.request(Api.functions.phone.confirmCall(peer: Api.InputPhoneCall.inputPhoneCall(id: stableId, accessHash: accessHash), gA: Buffer(data: gA), keyFingerprint: keyFingerprint, protocol: .phoneCallProtocol(flags: (1 << 0) | (1 << 1), minLayer: minLayer, maxLayer: maxLayer, libraryVersions: versions))) + return network.request(Api.functions.phone.confirmCall(peer: Api.InputPhoneCall.inputPhoneCall(.init(id: stableId, accessHash: accessHash)), gA: Buffer(data: gA), keyFingerprint: keyFingerprint, protocol: .phoneCallProtocol(.init(flags: (1 << 0) | (1 << 1), minLayer: minLayer, maxLayer: maxLayer, libraryVersions: versions)))) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -1717,7 +1739,8 @@ private func confirmCallSession(network: Network, stableId: CallSessionStableId, |> map { result -> Api.PhoneCall? in if let result = result { switch result { - case let .phoneCall(phoneCall, _): + case let .phoneCall(phoneCallData): + let (phoneCall, _) = (phoneCallData.phoneCall, phoneCallData.users) return phoneCall } } else { @@ -1751,7 +1774,7 @@ private func dropCallSession(network: Network, addUpdates: @escaping (Api.Update case .missed: mappedReason = .phoneCallDiscardReasonMissed case let .switchToConference(slug): - mappedReason = .phoneCallDiscardReasonMigrateConferenceCall(slug: slug) + mappedReason = .phoneCallDiscardReasonMigrateConferenceCall(.init(slug: slug)) } var callFlags: Int32 = 0 @@ -1759,7 +1782,7 @@ private func dropCallSession(network: Network, addUpdates: @escaping (Api.Update callFlags |= 1 << 0 } - return network.request(Api.functions.phone.discardCall(flags: callFlags, peer: Api.InputPhoneCall.inputPhoneCall(id: stableId, accessHash: accessHash), duration: duration, reason: mappedReason, connectionId: 0)) + return network.request(Api.functions.phone.discardCall(flags: callFlags, peer: Api.InputPhoneCall.inputPhoneCall(.init(id: stableId, accessHash: accessHash)), duration: duration, reason: mappedReason, connectionId: 0)) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -1769,12 +1792,15 @@ private func dropCallSession(network: Network, addUpdates: @escaping (Api.Update var sendDebugLogs: Bool = false if let updates = updates { switch updates { - case .updates(let updates, _, _, _, _): + case let .updates(updatesData): + let updates = updatesData.updates for update in updates { switch update { - case .updatePhoneCall(let phoneCall): + case let .updatePhoneCall(updatePhoneCallData): + let phoneCall = updatePhoneCallData.phoneCall switch phoneCall { - case let .phoneCallDiscarded(flags, _, _, _): + case let .phoneCallDiscarded(phoneCallDiscardedData): + let flags = phoneCallDiscardedData.flags reportRating = (flags & (1 << 2)) != 0 sendDebugLogs = (flags & (1 << 3)) != 0 default: diff --git a/submodules/TelegramCore/Sources/State/ChannelBoost.swift b/submodules/TelegramCore/Sources/State/ChannelBoost.swift index 62847354..d9f7df24 100644 --- a/submodules/TelegramCore/Sources/State/ChannelBoost.swift +++ b/submodules/TelegramCore/Sources/State/ChannelBoost.swift @@ -100,7 +100,8 @@ func _internal_getChannelBoostStatus(account: Account, peerId: PeerId) -> Signal return nil } switch result { - case let .boostsStatus(flags, level, currentLevelBoosts, boosts, giftBoosts, nextLevelBoosts, premiumAudience, boostUrl, prepaidGiveaways, myBoostSlots): + case let .boostsStatus(boostsStatusData): + let (flags, level, currentLevelBoosts, boosts, giftBoosts, nextLevelBoosts, premiumAudience, boostUrl, prepaidGiveaways, myBoostSlots) = (boostsStatusData.flags, boostsStatusData.level, boostsStatusData.currentLevelBoosts, boostsStatusData.boosts, boostsStatusData.giftBoosts, boostsStatusData.nextLevelBoosts, boostsStatusData.premiumAudience, boostsStatusData.boostUrl, boostsStatusData.prepaidGiveaways, boostsStatusData.myBoostSlots) let _ = myBoostSlots return ChannelBoostStatus(level: Int(level), boosts: Int(boosts), giftBoosts: giftBoosts.flatMap(Int.init), currentLevelBoosts: Int(currentLevelBoosts), nextLevelBoosts: nextLevelBoosts.flatMap(Int.init), premiumAudience: premiumAudience.flatMap({ StatsPercentValue(apiPercentValue: $0) }), url: boostUrl, prepaidGiveaways: prepaidGiveaways?.map({ PrepaidGiveaway(apiPrepaidGiveaway: $0) }) ?? [], boostedByMe: (flags & (1 << 2)) != 0) } @@ -274,12 +275,14 @@ private final class ChannelBoostersContextImpl { return ([], 0, nil) } switch result { - case let .boostsList(_, count, boosts, nextOffset, users): + case let .boostsList(boostsListData): + let (_, count, boosts, nextOffset, users) = (boostsListData.flags, boostsListData.count, boostsListData.boosts, boostsListData.nextOffset, boostsListData.users) updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(users: users)) var resultBoosts: [ChannelBoostersContext.State.Boost] = [] for boost in boosts { switch boost { - case let .boost(flags, id, userId, giveawayMessageId, date, expires, usedGiftSlug, multiplier, stars): + case let .boost(boostData): + let (flags, id, userId, giveawayMessageId, date, expires, usedGiftSlug, multiplier, stars) = (boostData.flags, boostData.id, boostData.userId, boostData.giveawayMsgId, boostData.date, boostData.expires, boostData.usedGiftSlug, boostData.multiplier, boostData.stars) var boostFlags: ChannelBoostersContext.State.Boost.Flags = [] var boostPeer: EnginePeer? if let userId = userId { @@ -546,12 +549,14 @@ extension MyBoostStatus { init(apiMyBoostStatus: Api.premium.MyBoosts, accountPeerId: PeerId, transaction: Transaction) { var boostsResult: [MyBoostStatus.Boost] = [] switch apiMyBoostStatus { - case let .myBoosts(myBoosts, chats, users): + case let .myBoosts(myBoostsData): + let (myBoosts, chats, users) = (myBoostsData.myBoosts, myBoostsData.chats, myBoostsData.users) let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users) updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers) for boost in myBoosts { switch boost { - case let .myBoost(_, slot, peer, date, expires, cooldownUntilDate): + case let .myBoost(myBoostData): + let (slot, peer, date, expires, cooldownUntilDate) = (myBoostData.slot, myBoostData.peer, myBoostData.date, myBoostData.expires, myBoostData.cooldownUntilDate) var boostPeer: EnginePeer? if let peerId = peer?.peerId, let peer = transaction.getPeer(peerId) { boostPeer = EnginePeer(peer) diff --git a/submodules/TelegramCore/Sources/State/ChannelState.swift b/submodules/TelegramCore/Sources/State/ChannelState.swift index 41cf6ec4..9c21a162 100644 --- a/submodules/TelegramCore/Sources/State/ChannelState.swift +++ b/submodules/TelegramCore/Sources/State/ChannelState.swift @@ -14,13 +14,17 @@ func channelUpdatesByPeerId(updates: [ChannelUpdate]) -> [PeerId: [ChannelUpdate for update in updates { var peerId: PeerId? switch update.update { - case let .updateNewChannelMessage(message, _, _): + case let .updateNewChannelMessage(updateNewChannelMessageData): + let (message, _, _) = (updateNewChannelMessageData.message, updateNewChannelMessageData.pts, updateNewChannelMessageData.ptsCount) peerId = apiMessagePeerId(message) - case let .updateDeleteChannelMessages(channelId, _, _, _): + case let .updateDeleteChannelMessages(updateDeleteChannelMessagesData): + let (channelId, _, _, _) = (updateDeleteChannelMessagesData.channelId, updateDeleteChannelMessagesData.messages, updateDeleteChannelMessagesData.pts, updateDeleteChannelMessagesData.ptsCount) peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) - case let .updateEditChannelMessage(message, _, _): + case let .updateEditChannelMessage(updateEditChannelMessageData): + let (message, _, _) = (updateEditChannelMessageData.message, updateEditChannelMessageData.pts, updateEditChannelMessageData.ptsCount) peerId = apiMessagePeerId(message) - case let .updateChannelWebPage(channelId, _, _, _): + case let .updateChannelWebPage(updateChannelWebPageData): + let (channelId, _, _, _) = (updateChannelWebPageData.channelId, updateChannelWebPageData.webpage, updateChannelWebPageData.pts, updateChannelWebPageData.ptsCount) peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) default: break diff --git a/submodules/TelegramCore/Sources/State/ContactSyncManager.swift b/submodules/TelegramCore/Sources/State/ContactSyncManager.swift index 567aecf4..76c26603 100644 --- a/submodules/TelegramCore/Sources/State/ContactSyncManager.swift +++ b/submodules/TelegramCore/Sources/State/ContactSyncManager.swift @@ -326,7 +326,7 @@ private func pushDeviceContactData(accountPeerId: PeerId, postbox: Postbox, netw batches = batches |> mapToSignal { intermediateResult -> Signal in return network.request(Api.functions.contacts.importContacts(contacts: zip(0 ..< batch.count, batch).map { index, item -> Api.InputContact in - return .inputPhoneContact(flags: 0, clientId: Int64(index), phone: item.0.rawValue, firstName: item.1.firstName, lastName: item.1.lastName, note: nil) + return .inputPhoneContact(.init(flags: 0, clientId: Int64(index), phone: item.0.rawValue, firstName: item.1.firstName, lastName: item.1.lastName, note: nil)) })) |> map(Optional.init) |> `catch` { _ -> Signal in @@ -341,12 +341,14 @@ private func pushDeviceContactData(accountPeerId: PeerId, postbox: Postbox, netw var importedCounts: [Int: Int32] = [:] var peerIdByClientId: [Int64: PeerId] = [:] switch result { - case let .importedContacts(imported, popularInvites, retryContacts, users): - updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(users: users)) + case let .importedContacts(importedContactsData): + let (imported, popularInvites, retryContacts, users) = (importedContactsData.imported, importedContactsData.popularInvites, importedContactsData.retryContacts, importedContactsData.users) + updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(users: users)) for item in imported { switch item { - case let .importedContact(userId, clientId): + case let .importedContact(importedContactData): + let (userId, clientId) = (importedContactData.userId, importedContactData.clientId) let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)) addedContactPeerIds.insert(peerId) peerIdByClientId[clientId] = peerId @@ -357,7 +359,8 @@ private func pushDeviceContactData(accountPeerId: PeerId, postbox: Postbox, netw } for item in popularInvites { switch item { - case let .popularContact(clientId, importers): + case let .popularContact(popularContactData): + let (clientId, importers) = (popularContactData.clientId, popularContactData.importers) importedCounts[Int(clientId)] = importers } } @@ -405,7 +408,8 @@ private func updateContactPresences(postbox: Postbox, network: Network, accountP var peerPresences: [PeerId: PeerPresence] = [:] for status in statuses { switch status { - case let .contactStatus(userId, status): + case let .contactStatus(contactStatusData): + let (userId, status) = (contactStatusData.userId, contactStatusData.status) peerPresences[PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))] = TelegramUserPresence(apiStatus: status) } } diff --git a/submodules/TelegramCore/Sources/State/EmojiSearchCategories.swift b/submodules/TelegramCore/Sources/State/EmojiSearchCategories.swift index c0af005c..19ef1773 100644 --- a/submodules/TelegramCore/Sources/State/EmojiSearchCategories.swift +++ b/submodules/TelegramCore/Sources/State/EmojiSearchCategories.swift @@ -159,26 +159,30 @@ func managedSynchronizeEmojiSearchCategories(postbox: Postbox, network: Network, |> mapToSignal { result -> Signal in return postbox.transaction { transaction -> Signal in switch result { - case let .emojiGroups(hash, groups): + case let .emojiGroups(emojiGroupsData): + let (hash, groups) = (emojiGroupsData.hash, emojiGroupsData.groups) let categories = EmojiSearchCategories( hash: hash, groups: groups.compactMap { item -> EmojiSearchCategories.Group? in switch item { - case let .emojiGroup(title, iconEmojiId, emoticons): + case let .emojiGroup(emojiGroupData): + let (title, iconEmojiId, emoticons) = (emojiGroupData.title, emojiGroupData.iconEmojiId, emojiGroupData.emoticons) return EmojiSearchCategories.Group( id: iconEmojiId, title: title, identifiers: emoticons, kind: .generic ) - case let .emojiGroupGreeting(title, iconEmojiId, emoticons): + case let .emojiGroupGreeting(emojiGroupGreetingData): + let (title, iconEmojiId, emoticons) = (emojiGroupGreetingData.title, emojiGroupGreetingData.iconEmojiId, emojiGroupGreetingData.emoticons) return EmojiSearchCategories.Group( id: iconEmojiId, title: title, identifiers: emoticons, kind: .greeting ) - case let .emojiGroupPremium(title, iconEmojiId): + case let .emojiGroupPremium(emojiGroupPremiumData): + let (title, iconEmojiId) = (emojiGroupPremiumData.title, emojiGroupPremiumData.iconEmojiId) return EmojiSearchCategories.Group( id: iconEmojiId, title: title, diff --git a/submodules/TelegramCore/Sources/State/FetchChatList.swift b/submodules/TelegramCore/Sources/State/FetchChatList.swift index 222719bf..829272a5 100644 --- a/submodules/TelegramCore/Sources/State/FetchChatList.swift +++ b/submodules/TelegramCore/Sources/State/FetchChatList.swift @@ -30,9 +30,11 @@ struct ParsedDialogs { private func extractDialogsData(dialogs: Api.messages.Dialogs) -> (apiDialogs: [Api.Dialog], apiMessages: [Api.Message], apiChats: [Api.Chat], apiUsers: [Api.User], apiIsAtLowestBoundary: Bool) { switch dialogs { - case let .dialogs(dialogs, messages, chats, users): + case let .dialogs(dialogsData): + let (dialogs, messages, chats, users) = (dialogsData.dialogs, dialogsData.messages, dialogsData.chats, dialogsData.users) return (dialogs, messages, chats, users, true) - case let .dialogsSlice(_, dialogs, messages, chats, users): + case let .dialogsSlice(dialogsSliceData): + let (_, dialogs, messages, chats, users) = (dialogsSliceData.count, dialogsSliceData.dialogs, dialogsSliceData.messages, dialogsSliceData.chats, dialogsSliceData.users) return (dialogs, messages, chats, users, false) case .dialogsNotModified: assertionFailure() @@ -42,7 +44,8 @@ private func extractDialogsData(dialogs: Api.messages.Dialogs) -> (apiDialogs: [ private func extractDialogsData(peerDialogs: Api.messages.PeerDialogs) -> (apiDialogs: [Api.Dialog], apiMessages: [Api.Message], apiChats: [Api.Chat], apiUsers: [Api.User], apiIsAtLowestBoundary: Bool) { switch peerDialogs { - case let .peerDialogs(dialogs, messages, chats, users, _): + case let .peerDialogs(peerDialogsData): + let (dialogs, messages, chats, users) = (peerDialogsData.dialogs, peerDialogsData.messages, peerDialogsData.chats, peerDialogsData.users) return (dialogs, messages, chats, users, false) } } @@ -77,7 +80,8 @@ private func parseDialogs(accountPeerId: PeerId, apiDialogs: [Api.Dialog], apiMe var apiChannelPts: Int32? let apiNotificationSettings: Api.PeerNotifySettings switch dialog { - case let .dialog(flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, peerNotificationSettings, pts, _, _, ttlPeriod): + case let .dialog(dialogData): + let (flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, peerNotificationSettings, pts, ttlPeriod) = (dialogData.flags, dialogData.peer, dialogData.topMessage, dialogData.readInboxMaxId, dialogData.readOutboxMaxId, dialogData.unreadCount, dialogData.unreadMentionsCount, dialogData.unreadReactionsCount, dialogData.notifySettings, dialogData.pts, dialogData.ttlPeriod) if let peer = peers.get(peer.peerId) { var isExluded = false if let group = peer as? TelegramGroup { @@ -109,11 +113,14 @@ private func parseDialogs(accountPeerId: PeerId, apiDialogs: [Api.Dialog], apiMe } let peerId: PeerId switch apiPeer { - 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)) } @@ -133,9 +140,11 @@ private func parseDialogs(accountPeerId: PeerId, apiDialogs: [Api.Dialog], apiMe } notificationSettings[peerId] = TelegramPeerNotificationSettings(apiSettings: apiNotificationSettings) - case let .dialogFolder(_, folder, _, _, unreadMutedPeersCount, _, unreadMutedMessagesCount, _): + case let .dialogFolder(dialogFolderData): + let (folder, unreadMutedPeersCount, unreadMutedMessagesCount) = (dialogFolderData.folder, dialogFolderData.unreadMutedPeersCount, dialogFolderData.unreadMutedMessagesCount) switch folder { - case let .folder(_, id, _, _): + case let .folder(folderData): + let id = folderData.id referencedFolders[PeerGroupId(rawValue: id)] = PeerGroupUnreadCountersSummary(all: PeerGroupUnreadCounters(messageCount: unreadMutedMessagesCount, chatCount: unreadMutedPeersCount)) } } diff --git a/submodules/TelegramCore/Sources/State/HistoryViewStateValidation.swift b/submodules/TelegramCore/Sources/State/HistoryViewStateValidation.swift index 038f5650..8b1c5459 100644 --- a/submodules/TelegramCore/Sources/State/HistoryViewStateValidation.swift +++ b/submodules/TelegramCore/Sources/State/HistoryViewStateValidation.swift @@ -558,17 +558,20 @@ private func validateChannelMessagesBatch(postbox: Postbox, network: Network, ac var channelPts: Int32? switch result { - case let .messages(messages: apiMessages, topics: apiTopics, chats: apiChats, users: apiUsers): + case let .messages(messagesData): + let (apiMessages, apiTopics, apiChats, apiUsers) = (messagesData.messages, messagesData.topics, messagesData.chats, messagesData.users) let _ = apiTopics messages = apiMessages chats = apiChats users = apiUsers - case let .messagesSlice(_, _, _, _, _, messages: apiMessages, topics: apiTopics, chats: apiChats, users: apiUsers): + case let .messagesSlice(messagesSliceData): + let (apiMessages, apiTopics, apiChats, apiUsers) = (messagesSliceData.messages, messagesSliceData.topics, messagesSliceData.chats, messagesSliceData.users) let _ = apiTopics messages = apiMessages chats = apiChats users = apiUsers - case let .channelMessages(_, pts, _, _, apiMessages, apiTopics, apiChats, apiUsers): + case let .channelMessages(channelMessagesData): + let (pts, apiMessages, apiTopics, apiChats, apiUsers) = (channelMessagesData.pts, channelMessagesData.messages, channelMessagesData.topics, channelMessagesData.chats, channelMessagesData.users) messages = apiMessages let _ = apiTopics chats = apiChats @@ -629,17 +632,20 @@ private func validateReplyThreadMessagesBatch(postbox: Postbox, network: Network var channelPts: Int32? switch result { - case let .messages(messages: apiMessages, topics: apiTopics, chats: apiChats, users: apiUsers): + case let .messages(messagesData): + let (apiMessages, apiTopics, apiChats, apiUsers) = (messagesData.messages, messagesData.topics, messagesData.chats, messagesData.users) let _ = apiTopics messages = apiMessages chats = apiChats users = apiUsers - case let .messagesSlice(_, _, _, _, _, messages: apiMessages, topics: apiTopics, chats: apiChats, users: apiUsers): + case let .messagesSlice(messagesSliceData): + let (apiMessages, apiTopics, apiChats, apiUsers) = (messagesSliceData.messages, messagesSliceData.topics, messagesSliceData.chats, messagesSliceData.users) let _ = apiTopics messages = apiMessages chats = apiChats users = apiUsers - case let .channelMessages(_, pts, _, _, apiMessages, apiTopics, apiChats, apiUsers): + case let .channelMessages(channelMessagesData): + let (pts, apiMessages, apiTopics, apiChats, apiUsers) = (channelMessagesData.pts, channelMessagesData.messages, channelMessagesData.topics, channelMessagesData.chats, channelMessagesData.users) messages = apiMessages let _ = apiTopics chats = apiChats @@ -653,7 +659,7 @@ private func validateReplyThreadMessagesBatch(postbox: Postbox, network: Network } else { return .complete() } - + return validateReplyThreadBatch(postbox: postbox, network: network, transaction: transaction, accountPeerId: accountPeerId, peerId: peerId, threadId: Int64(threadMessageId), signal: signal, previous: previous, messageNamespace: Namespaces.Message.Cloud) } |> switchToLatest @@ -673,17 +679,20 @@ private func validateScheduledMessagesBatch(postbox: Postbox, network: Network, let users: [Api.User] switch result { - case let .messages(messages: apiMessages, topics: apiTopics, chats: apiChats, users: apiUsers): + case let .messages(messagesData): + let (apiMessages, apiTopics, apiChats, apiUsers) = (messagesData.messages, messagesData.topics, messagesData.chats, messagesData.users) let _ = apiTopics messages = apiMessages chats = apiChats users = apiUsers - case let .messagesSlice(_, _, _, _, _, messages: apiMessages, topics: apiTopics, chats: apiChats, users: apiUsers): + case let .messagesSlice(messagesSliceData): + let (apiMessages, apiTopics, apiChats, apiUsers) = (messagesSliceData.messages, messagesSliceData.topics, messagesSliceData.chats, messagesSliceData.users) let _ = apiTopics messages = apiMessages chats = apiChats users = apiUsers - case let .channelMessages(_, _, _, _, apiMessages, apiTopics, apiChats, apiUsers): + case let .channelMessages(channelMessagesData): + let (apiMessages, apiTopics, apiChats, apiUsers) = (channelMessagesData.messages, channelMessagesData.topics, channelMessagesData.chats, channelMessagesData.users) messages = apiMessages let _ = apiTopics chats = apiChats @@ -721,17 +730,20 @@ private func validateQuickReplyMessagesBatch(postbox: Postbox, network: Network, let users: [Api.User] switch result { - case let .messages(messages: apiMessages, topics: apiTopics, chats: apiChats, users: apiUsers): + case let .messages(messagesData): + let (apiMessages, apiTopics, apiChats, apiUsers) = (messagesData.messages, messagesData.topics, messagesData.chats, messagesData.users) let _ = apiTopics messages = apiMessages chats = apiChats users = apiUsers - case let .messagesSlice(_, _, _, _, _, messages: apiMessages, topics: apiTopics, chats: apiChats, users: apiUsers): + case let .messagesSlice(messagesSliceData): + let (apiMessages, apiTopics, apiChats, apiUsers) = (messagesSliceData.messages, messagesSliceData.topics, messagesSliceData.chats, messagesSliceData.users) let _ = apiTopics messages = apiMessages chats = apiChats users = apiUsers - case let .channelMessages(_, _, _, _, apiMessages, apiTopics, apiChats, apiUsers): + case let .channelMessages(channelMessagesData): + let (apiMessages, apiTopics, apiChats, apiUsers) = (channelMessagesData.messages, channelMessagesData.topics, channelMessagesData.chats, channelMessagesData.users) messages = apiMessages let _ = apiTopics chats = apiChats @@ -802,16 +814,19 @@ private func validateBatch(postbox: Postbox, network: Network, transaction: Tran case let .channel(peerId, _): actuallyRemovedMessagesSignal = postbox.transaction { transaction -> Signal, NoError> in if let inputChannel = transaction.getPeer(peerId).flatMap(apiInputChannel) { - return network.request(Api.functions.channels.getMessages(channel: inputChannel, id: maybeRemovedMessageIds.map({ Api.InputMessage.inputMessageID(id: $0.id) }))) + return network.request(Api.functions.channels.getMessages(channel: inputChannel, id: maybeRemovedMessageIds.map({ Api.InputMessage.inputMessageID(.init(id: $0.id)) }))) |> map { result -> Set in let apiMessages: [Api.Message] switch result { - case let .channelMessages(_, _, _, _, messages, apiTopics, _, _): + case let .channelMessages(channelMessagesData): + let (messages, apiTopics) = (channelMessagesData.messages, channelMessagesData.topics) apiMessages = messages let _ = apiTopics - case let .messages(messages, _, _, _): + case let .messages(messagesData): + let messages = messagesData.messages apiMessages = messages - case let .messagesSlice(_, _, _, _, _, messages, _, _, _): + case let .messagesSlice(messagesSliceData): + let messages = messagesSliceData.messages apiMessages = messages case .messagesNotModified: return Set() @@ -1051,16 +1066,19 @@ private func validateReplyThreadBatch(postbox: Postbox, network: Network, transa } else { actuallyRemovedMessagesSignal = postbox.transaction { transaction -> Signal, NoError> in if let inputChannel = transaction.getPeer(peerId).flatMap(apiInputChannel) { - return network.request(Api.functions.channels.getMessages(channel: inputChannel, id: maybeRemovedMessageIds.map({ Api.InputMessage.inputMessageID(id: $0.id) }))) + return network.request(Api.functions.channels.getMessages(channel: inputChannel, id: maybeRemovedMessageIds.map({ Api.InputMessage.inputMessageID(.init(id: $0.id)) }))) |> map { result -> Set in let apiMessages: [Api.Message] switch result { - case let .channelMessages(_, _, _, _, messages, apiTopics, _, _): + case let .channelMessages(channelMessagesData): + let (messages, apiTopics) = (channelMessagesData.messages, channelMessagesData.topics) apiMessages = messages let _ = apiTopics - case let .messages(messages, _, _, _): + case let .messages(messagesData): + let messages = messagesData.messages apiMessages = messages - case let .messagesSlice(_, _, _, _, _, messages, _, _, _): + case let .messagesSlice(messagesSliceData): + let messages = messagesSliceData.messages apiMessages = messages case .messagesNotModified: return Set() diff --git a/submodules/TelegramCore/Sources/State/Holes.swift b/submodules/TelegramCore/Sources/State/Holes.swift index 974ea0d5..356bb3c3 100644 --- a/submodules/TelegramCore/Sources/State/Holes.swift +++ b/submodules/TelegramCore/Sources/State/Holes.swift @@ -244,21 +244,24 @@ func withResolvedAssociatedMessages(postbox: Postbox, source: FetchMessageHis if let peer = transaction.getPeer(peerId) ?? parsedPeers.get(peerId) { var signal: Signal? if peerId.namespace == Namespaces.Peer.CloudUser || peerId.namespace == Namespaces.Peer.CloudGroup { - signal = source.request(Api.functions.messages.getMessages(id: messageIds.targetIdsBySourceId.values.map({ Api.InputMessage.inputMessageReplyTo(id: $0.id) }))) + signal = source.request(Api.functions.messages.getMessages(id: messageIds.targetIdsBySourceId.values.map({ Api.InputMessage.inputMessageReplyTo(.init(id: $0.id)) }))) } else if peerId.namespace == Namespaces.Peer.CloudChannel { if let inputChannel = apiInputChannel(peer) { - signal = source.request(Api.functions.channels.getMessages(channel: inputChannel, id: messageIds.targetIdsBySourceId.values.map({ Api.InputMessage.inputMessageReplyTo(id: $0.id) }))) + signal = source.request(Api.functions.channels.getMessages(channel: inputChannel, id: messageIds.targetIdsBySourceId.values.map({ Api.InputMessage.inputMessageReplyTo(.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.messages, 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.messages, channelMessagesData.topics, channelMessagesData.chats, channelMessagesData.users) let _ = apiTopics return (peer, messages, chats, users) case .messagesNotModified: @@ -275,21 +278,24 @@ func withResolvedAssociatedMessages(postbox: Postbox, source: FetchMessageHis if let peer = transaction.getPeer(peerId) ?? parsedPeers.get(peerId) { var signal: Signal? if peerId.namespace == Namespaces.Peer.CloudUser || peerId.namespace == Namespaces.Peer.CloudGroup { - signal = source.request(Api.functions.messages.getMessages(id: messageIds.map({ Api.InputMessage.inputMessageID(id: $0.id) }))) + signal = source.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 = source.request(Api.functions.channels.getMessages(channel: inputChannel, id: messageIds.map({ Api.InputMessage.inputMessageID(id: $0.id) }))) + signal = source.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.messages, 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.messages, channelMessagesData.topics, channelMessagesData.chats, channelMessagesData.users) let _ = apiTopics return (peer, messages, chats, users) case .messagesNotModified: @@ -919,15 +925,18 @@ func fetchMessageHistoryHole(accountPeerId: PeerId, source: FetchMessageHistoryH let users: [Api.User] var channelPts: Int32? switch result { - case let .messages(messages: apiMessages, _, chats: apiChats, users: 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(_, _, _, _, _, messages: apiMessages, _, chats: apiChats, users: apiUsers): + case let .messagesSlice(messagesSliceData): + let (apiMessages, apiChats, apiUsers) = (messagesSliceData.messages, messagesSliceData.chats, messagesSliceData.users) messages = apiMessages chats = apiChats users = apiUsers - case let .channelMessages(_, pts, _, _, apiMessages, apiTopics, apiChats, apiUsers): + case let .channelMessages(channelMessagesData): + let (pts, apiMessages, apiTopics, apiChats, apiUsers) = (channelMessagesData.pts, channelMessagesData.messages, channelMessagesData.topics, channelMessagesData.chats, channelMessagesData.users) messages = apiMessages let _ = apiTopics chats = apiChats @@ -1089,13 +1098,13 @@ func fetchMessageHistoryHole(accountPeerId: PeerId, source: FetchMessageHistoryH func groupBoundaryPeer(_ peerId: PeerId, accountPeerId: PeerId) -> Api.Peer { switch peerId.namespace { case Namespaces.Peer.CloudUser: - return Api.Peer.peerUser(userId: peerId.id._internalGetInt64Value()) + return Api.Peer.peerUser(.init(userId: peerId.id._internalGetInt64Value())) case Namespaces.Peer.CloudGroup: - return Api.Peer.peerChat(chatId: peerId.id._internalGetInt64Value()) + return Api.Peer.peerChat(.init(chatId: peerId.id._internalGetInt64Value())) case Namespaces.Peer.CloudChannel: - return Api.Peer.peerChannel(channelId: peerId.id._internalGetInt64Value()) + return Api.Peer.peerChannel(.init(channelId: peerId.id._internalGetInt64Value())) default: - return Api.Peer.peerUser(userId: accountPeerId.id._internalGetInt64Value()) + return Api.Peer.peerUser(.init(userId: accountPeerId.id._internalGetInt64Value())) } } @@ -1210,22 +1219,25 @@ func fetchCallListHole(network: Network, postbox: Postbox, accountPeerId: PeerId offset = single((holeIndex.timestamp, min(holeIndex.id.id, Int32.max - 1) + 1, Api.InputPeer.inputPeerEmpty), NoError.self) return offset |> mapToSignal { (timestamp, id, peer) -> Signal in - let searchResult = network.request(Api.functions.messages.search(flags: 0, peer: .inputPeerEmpty, q: "", fromId: nil, savedPeerId: nil, savedReaction: nil, topMsgId: nil, filter: .inputMessagesFilterPhoneCalls(flags: 0), minDate: 0, maxDate: holeIndex.timestamp, offsetId: 0, addOffset: 0, limit: limit, maxId: holeIndex.id.id, minId: 0, hash: 0)) + let searchResult = network.request(Api.functions.messages.search(flags: 0, peer: .inputPeerEmpty, q: "", fromId: nil, savedPeerId: nil, savedReaction: nil, topMsgId: nil, filter: .inputMessagesFilterPhoneCalls(.init(flags: 0)), minDate: 0, maxDate: holeIndex.timestamp, offsetId: 0, addOffset: 0, limit: limit, maxId: holeIndex.id.id, minId: 0, hash: 0)) |> retryRequest |> mapToSignal { result -> Signal in let messages: [Api.Message] let chats: [Api.Chat] let users: [Api.User] switch result { - case let .messages(messages: apiMessages, _, chats: apiChats, users: 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(_, _, _, _, _, messages: apiMessages, _, chats: apiChats, users: apiUsers): + case let .messagesSlice(messagesSliceData): + let (apiMessages, apiChats, apiUsers) = (messagesSliceData.messages, messagesSliceData.chats, messagesSliceData.users) messages = apiMessages chats = apiChats users = apiUsers - case let .channelMessages(_, _, _, _, apiMessages, apiTopics, apiChats, apiUsers): + case let .channelMessages(channelMessagesData): + let (apiMessages, apiTopics, apiChats, apiUsers) = (channelMessagesData.messages, channelMessagesData.topics, channelMessagesData.chats, channelMessagesData.users) messages = apiMessages let _ = apiTopics chats = apiChats diff --git a/submodules/TelegramCore/Sources/State/ManagedAppConfigurationUpdates.swift b/submodules/TelegramCore/Sources/State/ManagedAppConfigurationUpdates.swift index e62bc842..7f7134a3 100644 --- a/submodules/TelegramCore/Sources/State/ManagedAppConfigurationUpdates.swift +++ b/submodules/TelegramCore/Sources/State/ManagedAppConfigurationUpdates.swift @@ -12,7 +12,8 @@ func updateAppConfigurationOnce(postbox: Postbox, network: Network) -> Signal map { result -> (data: Api.JSONValue, hash: Int32)? in switch result { - case let .appConfig(updatedHash, config): + case let .appConfig(appConfigData): + let (updatedHash, config) = (appConfigData.hash, appConfigData.config) return (config, updatedHash) case .appConfigNotModified: return nil diff --git a/submodules/TelegramCore/Sources/State/ManagedCloudChatRemoveMessagesOperations.swift b/submodules/TelegramCore/Sources/State/ManagedCloudChatRemoveMessagesOperations.swift index ddca0d3f..f13434cd 100644 --- a/submodules/TelegramCore/Sources/State/ManagedCloudChatRemoveMessagesOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedCloudChatRemoveMessagesOperations.swift @@ -205,7 +205,8 @@ private func removeMessages(postbox: Postbox, network: Network, stateManager: Ac |> mapToSignal { result -> Signal 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([.updateChannelPts(channelId: peer.id.id._internalGetInt64Value(), pts: pts, ptsCount: ptsCount)]) } } @@ -240,13 +241,14 @@ private func removeMessages(postbox: Postbox, network: Network, stateManager: Ac |> mapToSignal { result -> Signal 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)]) } } return .complete() } - + signal = signal |> then(partSignal) } @@ -396,7 +398,8 @@ private func requestClearHistory(postbox: Postbox, network: Network, stateManage |> mapToSignal { result -> Signal 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) stateManager.addUpdateGroups([.updatePts(pts: pts, ptsCount: ptsCount)]) if offset == 0 { return .fail(true) @@ -463,7 +466,8 @@ private func _internal_clearHistory(transaction: Transaction, postbox: Postbox, |> mapToSignal { result -> Signal 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) stateManager.addUpdateGroups([.updatePts(pts: pts, ptsCount: ptsCount)]) if offset == 0 { return .fail(true) @@ -491,7 +495,8 @@ private func _internal_clearHistory(transaction: Transaction, postbox: Postbox, |> mapToSignal { result -> Signal in if let result = result { switch result { - case let .affectedHistory(pts, ptsCount, _): + case let .affectedHistory(affectedHistoryData): + let (pts, ptsCount) = (affectedHistoryData.pts, affectedHistoryData.ptsCount) stateManager.addUpdateGroups([.updatePts(pts: pts, ptsCount: ptsCount)]) return .complete() } @@ -539,7 +544,8 @@ private func _internal_clearHistory(transaction: Transaction, postbox: Postbox, |> mapToSignal { result -> Signal 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) stateManager.addUpdateGroups([.updatePts(pts: pts, ptsCount: ptsCount)]) if offset == 0 { return .fail(true) diff --git a/submodules/TelegramCore/Sources/State/ManagedConfigurationUpdates.swift b/submodules/TelegramCore/Sources/State/ManagedConfigurationUpdates.swift index 1c1de778..e50f3a2a 100644 --- a/submodules/TelegramCore/Sources/State/ManagedConfigurationUpdates.swift +++ b/submodules/TelegramCore/Sources/State/ManagedConfigurationUpdates.swift @@ -14,11 +14,13 @@ func managedConfigurationUpdates(accountManager: AccountManager mapToSignal { result, defaultHistoryTtl -> Signal in return postbox.transaction { transaction -> Signal in switch result { - case let .config(flags, _, _, _, _, dcOptions, _, chatSizeMax, megagroupSizeMax, forwardedCountMax, _, _, _, _, _, _, _, _, editTimeLimit, revokeTimeLimit, revokePmTimeLimit, _, stickersRecentLimit, _, _, _, _, _, _, _, autoupdateUrlPrefix, gifSearchUsername, venueSearchUsername, imgSearchUsername, _, _, _, webfileDcId, suggestedLangCode, langPackVersion, baseLangPackVersion, reactionsDefault, autologinToken): + case let .config(configData): + let (flags, dcOptions, chatSizeMax, megagroupSizeMax, forwardedCountMax, editTimeLimit, revokeTimeLimit, revokePmTimeLimit, stickersRecentLimit, autoupdateUrlPrefix, gifSearchUsername, venueSearchUsername, imgSearchUsername, webfileDcId, suggestedLangCode, langPackVersion, baseLangPackVersion, reactionsDefault, autologinToken) = (configData.flags, configData.dcOptions, configData.chatSizeMax, configData.megagroupSizeMax, configData.forwardedCountMax, configData.editTimeLimit, configData.revokeTimeLimit, configData.revokePmTimeLimit, configData.stickersRecentLimit, configData.autoupdateUrlPrefix, configData.gifSearchUsername, configData.venueSearchUsername, configData.imgSearchUsername, configData.webfileDcId, configData.suggestedLangCode, configData.langPackVersion, configData.baseLangPackVersion, configData.reactionsDefault, configData.autologinToken) var addressList: [Int: [MTDatacenterAddress]] = [:] for option in dcOptions { switch option { - case let .dcOption(flags, id, ipAddress, port, secret): + case let .dcOption(dcOptionData): + let (flags, id, ipAddress, port, secret) = (dcOptionData.flags, dcOptionData.id, dcOptionData.ipAddress, dcOptionData.port, dcOptionData.secret) let preferForMedia = (flags & (1 << 1)) != 0 if addressList[Int(id)] == nil { addressList[Int(id)] = [] @@ -77,7 +79,8 @@ func managedConfigurationUpdates(accountManager: AccountManager mapToSignal { result -> Signal 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)]) } } @@ -324,7 +325,8 @@ private func synchronizeReadMessageReactions(transaction: Transaction, postbox: |> mapToSignal { result -> Signal 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)]) } } @@ -386,7 +388,7 @@ private func synchronizeReadMessageReactions(transaction: Transaction, postbox: private func synchronizeUnseenPersonalMentionsTag(postbox: Postbox, network: Network, entry: InvalidatedMessageHistoryTagsSummaryEntry) -> Signal { return postbox.transaction { transaction -> Signal in if let peer = transaction.getPeer(entry.key.peerId), let inputPeer = apiInputPeer(peer) { - return network.request(Api.functions.messages.getPeerDialogs(peers: [.inputDialogPeer(peer: inputPeer)])) + return network.request(Api.functions.messages.getPeerDialogs(peers: [.inputDialogPeer(.init(peer: inputPeer))])) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -394,20 +396,22 @@ private func synchronizeUnseenPersonalMentionsTag(postbox: Postbox, network: Net |> mapToSignal { result -> Signal in if let result = result { switch result { - case let .peerDialogs(dialogs, _, _, _, _): + case let .peerDialogs(peerDialogsData): + let dialogs = peerDialogsData.dialogs if let dialog = dialogs.filter({ $0.peerId == entry.key.peerId }).first { let apiTopMessage: Int32 let apiUnreadMentionsCount: Int32 switch dialog { - case let .dialog(_, _, topMessage, _, _, _, unreadMentionsCount, _, _, _, _, _, _): + case let .dialog(dialogData): + let (topMessage, unreadMentionsCount) = (dialogData.topMessage, dialogData.unreadMentionsCount) apiTopMessage = topMessage apiUnreadMentionsCount = unreadMentionsCount - + case .dialogFolder: assertionFailure() return .complete() } - + return postbox.transaction { transaction -> Void in transaction.replaceMessageTagSummary(peerId: entry.key.peerId, threadId: nil, tagMask: entry.key.tagMask, namespace: entry.key.namespace, customTag: nil, count: apiUnreadMentionsCount, maxId: apiTopMessage) } @@ -428,7 +432,7 @@ private func synchronizeUnseenPersonalMentionsTag(postbox: Postbox, network: Net private func synchronizeUnseenReactionsTag(postbox: Postbox, network: Network, entry: InvalidatedMessageHistoryTagsSummaryEntry) -> Signal { return postbox.transaction { transaction -> Signal in if let peer = transaction.getPeer(entry.key.peerId), let inputPeer = apiInputPeer(peer) { - return network.request(Api.functions.messages.getPeerDialogs(peers: [.inputDialogPeer(peer: inputPeer)])) + return network.request(Api.functions.messages.getPeerDialogs(peers: [.inputDialogPeer(.init(peer: inputPeer))])) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -436,20 +440,22 @@ private func synchronizeUnseenReactionsTag(postbox: Postbox, network: Network, e |> mapToSignal { result -> Signal in if let result = result { switch result { - case let .peerDialogs(dialogs, _, _, _, _): + case let .peerDialogs(peerDialogsData): + let dialogs = peerDialogsData.dialogs if let dialog = dialogs.filter({ $0.peerId == entry.key.peerId }).first { let apiTopMessage: Int32 let apiUnreadReactionsCount: Int32 switch dialog { - case let .dialog(_, _, topMessage, _, _, _, _, unreadReactionsCount, _, _, _, _, _): + case let .dialog(dialogData): + let (topMessage, unreadReactionsCount) = (dialogData.topMessage, dialogData.unreadReactionsCount) apiTopMessage = topMessage apiUnreadReactionsCount = unreadReactionsCount - + case .dialogFolder: assertionFailure() return .complete() } - + return postbox.transaction { transaction -> Void in transaction.replaceMessageTagSummary(peerId: entry.key.peerId, threadId: nil, tagMask: entry.key.tagMask, namespace: entry.key.namespace, customTag: nil, count: apiUnreadReactionsCount, maxId: apiTopMessage) } @@ -546,7 +552,8 @@ private func synchronizeMessageHistoryTagSummary(accountPeerId: PeerId, postbox: } return postbox.transaction { transaction -> Void in switch result { - case let .channelMessages(_, _, count, _, messages, _, _, _): + case let .channelMessages(channelMessagesData): + let (count, messages) = (channelMessagesData.count, channelMessagesData.messages) let topId: Int32 = messages.first?.id(namespace: Namespaces.Message.Cloud)?.id ?? 1 transaction.replaceMessageTagSummary(peerId: entry.key.peerId, threadId: threadId, tagMask: entry.key.tagMask, namespace: entry.key.namespace, customTag: nil, count: count, maxId: topId) default: @@ -574,16 +581,20 @@ private func synchronizeMessageHistoryTagSummary(accountPeerId: PeerId, postbox: let apiMessages: [Api.Message] let apiCount: Int32 switch result { - case let .channelMessages(_, _, count, _, messages, _, _, _): + case let .channelMessages(channelMessagesData): + let (count, messages) = (channelMessagesData.count, channelMessagesData.messages) apiMessages = messages apiCount = count - case let .messages(messages, _, _, _): + case let .messages(messagesData): + let messages = messagesData.messages apiMessages = messages apiCount = Int32(messages.count) - case let .messagesNotModified(count): + case let .messagesNotModified(messagesNotModifiedData): + let count = messagesNotModifiedData.count apiMessages = [] apiCount = count - case let .messagesSlice(_, count, _, _, _, messages, _, _, _): + case let .messagesSlice(messagesSliceData): + let (count, messages) = (messagesSliceData.count, messagesSliceData.messages) apiMessages = messages apiCount = count } @@ -731,12 +742,14 @@ func synchronizeSavedMessageTags(postbox: Postbox, network: Network, peerId: Pee transaction.setPreferencesEntry(key: PreferencesKeys.didCacheSavedMessageTags(threadId: threadId), value: PreferencesEntry(data: Data())) } |> ignoreValues - case let .savedReactionTags(tags, _): + case let .savedReactionTags(savedReactionTagsData): + let tags = savedReactionTagsData.tags var customFileIds: [Int64] = [] var parsedTags: [SavedMessageTags.Tag] = [] for tag in tags { switch tag { - case let .savedReactionTag(_, reaction, title, count): + case let .savedReactionTag(savedReactionTagData): + let (reaction, title, count) = (savedReactionTagData.reaction, savedReactionTagData.title, savedReactionTagData.count) guard let reaction = MessageReaction.Reaction(apiReaction: reaction) else { continue } diff --git a/submodules/TelegramCore/Sources/State/ManagedEmojiGameUpdates.swift b/submodules/TelegramCore/Sources/State/ManagedEmojiGameUpdates.swift index 710f7890..489ec76c 100644 --- a/submodules/TelegramCore/Sources/State/ManagedEmojiGameUpdates.swift +++ b/submodules/TelegramCore/Sources/State/ManagedEmojiGameUpdates.swift @@ -50,7 +50,8 @@ public enum EmojiGameInfo: Codable, Equatable { extension EmojiGameInfo { init(apiEmojiGameInfo: Api.messages.EmojiGameInfo) { switch apiEmojiGameInfo { - case let .emojiGameDiceInfo(_, gameHash, prevStake, currentStreak, params, playsLeft): + case let .emojiGameDiceInfo(emojiGameDiceInfoData): + let (gameHash, prevStake, currentStreak, params, playsLeft) = (emojiGameDiceInfoData.gameHash, emojiGameDiceInfoData.prevStake, emojiGameDiceInfoData.currentStreak, emojiGameDiceInfoData.params, emojiGameDiceInfoData.playsLeft) self = .available(Info(gameHash: gameHash, previousStake: prevStake, currentStreak: currentStreak, parameters: params, playsLeft: playsLeft)) case .emojiGameUnavailable: self = .unavailable diff --git a/submodules/TelegramCore/Sources/State/ManagedGlobalNotificationSettings.swift b/submodules/TelegramCore/Sources/State/ManagedGlobalNotificationSettings.swift index f76b368b..0e401533 100644 --- a/submodules/TelegramCore/Sources/State/ManagedGlobalNotificationSettings.swift +++ b/submodules/TelegramCore/Sources/State/ManagedGlobalNotificationSettings.swift @@ -120,7 +120,8 @@ private func fetchedNotificationSettings(network: Network) -> Signal Signal Signal Signal Signal Signal Signal Signal Signal Signal Signal { @@ -413,13 +417,13 @@ private func pushedNotificationSettings(network: Network, settings: GlobalNotifi reactionFlags |= 1 << 1 } - let inputReactionSettings: Api.ReactionsNotifySettings = .reactionsNotifySettings( + let inputReactionSettings: Api.ReactionsNotifySettings = .reactionsNotifySettings(.init( flags: reactionFlags, messagesNotifyFrom: reactionsMessages, storiesNotifyFrom: reactionsStories, sound: settings.reactionSettings.sound.apiSound, showPreviews: settings.reactionSettings.hideSender == .hide ? .boolFalse : .boolTrue - ) + )) let pushedReactions = network.request(Api.functions.account.setReactionsNotifySettings(settings: inputReactionSettings)) |> map(Optional.init) |> `catch` { _ -> Signal in diff --git a/submodules/TelegramCore/Sources/State/ManagedLocalInputActivities.swift b/submodules/TelegramCore/Sources/State/ManagedLocalInputActivities.swift index 099d3c85..5d26aacc 100644 --- a/submodules/TelegramCore/Sources/State/ManagedLocalInputActivities.swift +++ b/submodules/TelegramCore/Sources/State/ManagedLocalInputActivities.swift @@ -118,23 +118,23 @@ private func actionFromActivity(_ activity: PeerInputActivity?) -> Api.SendMessa case .playingGame: return .sendMessageGamePlayAction case let .uploadingFile(progress): - return .sendMessageUploadDocumentAction(progress: progress) + return .sendMessageUploadDocumentAction(.init(progress: progress)) case let .uploadingPhoto(progress): - return .sendMessageUploadPhotoAction(progress: progress) + return .sendMessageUploadPhotoAction(.init(progress: progress)) case let .uploadingVideo(progress): - return .sendMessageUploadVideoAction(progress: progress) + return .sendMessageUploadVideoAction(.init(progress: progress)) case .recordingInstantVideo: return .sendMessageRecordRoundAction case let .uploadingInstantVideo(progress): - return .sendMessageUploadRoundAction(progress: progress) + return .sendMessageUploadRoundAction(.init(progress: progress)) case .speakingInGroupCall: return .speakingInGroupCallAction case .choosingSticker: return .sendMessageChooseStickerAction case let .interactingWithEmoji(emoticon, messageId, interaction): - return .sendMessageEmojiInteraction(emoticon: emoticon, msgId: messageId.id, interaction: interaction?.apiDataJson ?? .dataJSON(data: "")) + return .sendMessageEmojiInteraction(.init(emoticon: emoticon, msgId: messageId.id, interaction: interaction?.apiDataJson ?? .dataJSON(.init(data: "")))) case let .seeingEmojiInteraction(emoticon): - return .sendMessageEmojiInteractionSeen(emoticon: emoticon) + return .sendMessageEmojiInteractionSeen(.init(emoticon: emoticon)) } } else { return .sendMessageCancelAction @@ -142,7 +142,7 @@ private func actionFromActivity(_ activity: PeerInputActivity?) -> Api.SendMessa } private func requestActivity(postbox: Postbox, network: Network, accountPeerId: PeerId, peerId: PeerId, threadId: Int64?, activity: PeerInputActivity?) -> Signal { - // GHOST MODE: Block typing indicator + // GHOST MODE: Block typing indicator updates. if GhostModeManager.shared.shouldHideTypingIndicator { return .complete() } @@ -195,7 +195,7 @@ private func requestActivity(postbox: Postbox, network: Network, accountPeerId: } } else if let peer = peer as? TelegramSecretChat, activity == .typingText { let _ = PeerId(peer.id.toInt64()) - return network.request(Api.functions.messages.setEncryptedTyping(peer: .inputEncryptedChat(chatId: Int32(peer.id.id._internalGetInt64Value()), accessHash: peer.accessHash), typing: .boolTrue)) + return network.request(Api.functions.messages.setEncryptedTyping(peer: .inputEncryptedChat(.init(chatId: Int32(peer.id.id._internalGetInt64Value()), accessHash: peer.accessHash)), typing: .boolTrue)) |> `catch` { _ -> Signal in return .single(.boolFalse) } diff --git a/submodules/TelegramCore/Sources/State/ManagedLocalizationUpdatesOperations.swift b/submodules/TelegramCore/Sources/State/ManagedLocalizationUpdatesOperations.swift index 99977c2d..a0e92c4a 100644 --- a/submodules/TelegramCore/Sources/State/ManagedLocalizationUpdatesOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedLocalizationUpdatesOperations.swift @@ -132,15 +132,19 @@ func getLocalization(_ transaction: AccountManagerModifier (code: String, fromVersion: Int32, version: Int32, entries: [LocalizationEntry]) { switch difference { - case let .langPackDifference(code, fromVersion, version, strings): + case let .langPackDifference(langPackDifferenceData): + let (code, fromVersion, version, strings) = (langPackDifferenceData.langCode, langPackDifferenceData.fromVersion, langPackDifferenceData.version, langPackDifferenceData.strings) 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: "")) } } @@ -242,7 +246,8 @@ private func synchronizeLocalizationUpdates(accountManager: AccountManager, langCode: String, difference: Api.LangPackDifference) -> Bool { let (primary, secondary) = getLocalization(transaction) switch difference { - case let .langPackDifference(updatedCode, fromVersion, updatedVersion, strings): + case let .langPackDifference(langPackDifferenceData): + let (updatedCode, fromVersion, updatedVersion, strings) = (langPackDifferenceData.langCode, langPackDifferenceData.fromVersion, langPackDifferenceData.version, langPackDifferenceData.strings) var current: (isPrimary: Bool, version: Int32, entries: [LocalizationEntry])? if updatedCode == primary.code { current = (true, primary.version, primary.entries) @@ -259,11 +264,14 @@ func tryApplyingLanguageDifference(transaction: AccountManagerModifier Void in let value = EngineAvailableColorOptions(hash: hash, apiColors: colors) _internal_setCachedAvailableColorOptions(transaction: transaction, scope: scope, value: value) diff --git a/submodules/TelegramCore/Sources/State/ManagedPendingPeerNotificationSettings.swift b/submodules/TelegramCore/Sources/State/ManagedPendingPeerNotificationSettings.swift index 8d251c64..3c469253 100644 --- a/submodules/TelegramCore/Sources/State/ManagedPendingPeerNotificationSettings.swift +++ b/submodules/TelegramCore/Sources/State/ManagedPendingPeerNotificationSettings.swift @@ -162,8 +162,8 @@ func pushPeerNotificationSettings(postbox: Postbox, network: Network, peerId: Pe flags |= (1 << 8) } - let inputSettings = Api.InputPeerNotifySettings.inputPeerNotifySettings(flags: flags, showPreviews: showPreviews, silent: nil, muteUntil: muteUntil, sound: sound, storiesMuted: storiesMuted, storiesHideSender: storiesHideSender, storiesSound: storiesSound) - return network.request(Api.functions.account.updateNotifySettings(peer: .inputNotifyForumTopic(peer: inputPeer, topMsgId: Int32(clamping: threadId)), settings: inputSettings)) + let inputSettings = Api.InputPeerNotifySettings.inputPeerNotifySettings(.init(flags: flags, showPreviews: showPreviews, silent: nil, muteUntil: muteUntil, sound: sound, storiesMuted: storiesMuted, storiesHideSender: storiesHideSender, storiesSound: storiesSound)) + return network.request(Api.functions.account.updateNotifySettings(peer: .inputNotifyForumTopic(.init(peer: inputPeer, topMsgId: Int32(clamping: threadId))), settings: inputSettings)) |> `catch` { _ -> Signal in return .single(.boolFalse) } @@ -237,8 +237,8 @@ func pushPeerNotificationSettings(postbox: Postbox, network: Network, peerId: Pe flags |= (1 << 8) } - let inputSettings = Api.InputPeerNotifySettings.inputPeerNotifySettings(flags: flags, showPreviews: showPreviews, silent: nil, muteUntil: muteUntil, sound: sound, storiesMuted: storiesMuted, storiesHideSender: storiesHideSender, storiesSound: storiesSound) - return network.request(Api.functions.account.updateNotifySettings(peer: .inputNotifyPeer(peer: inputPeer), settings: inputSettings)) + let inputSettings = Api.InputPeerNotifySettings.inputPeerNotifySettings(.init(flags: flags, showPreviews: showPreviews, silent: nil, muteUntil: muteUntil, sound: sound, storiesMuted: storiesMuted, storiesHideSender: storiesHideSender, storiesSound: storiesSound)) + return network.request(Api.functions.account.updateNotifySettings(peer: .inputNotifyPeer(.init(peer: inputPeer)), settings: inputSettings)) |> `catch` { _ -> Signal in return .single(.boolFalse) } diff --git a/submodules/TelegramCore/Sources/State/ManagedPremiumPromoConfigurationUpdates.swift b/submodules/TelegramCore/Sources/State/ManagedPremiumPromoConfigurationUpdates.swift index 9f1018be..a63606ab 100644 --- a/submodules/TelegramCore/Sources/State/ManagedPremiumPromoConfigurationUpdates.swift +++ b/submodules/TelegramCore/Sources/State/ManagedPremiumPromoConfigurationUpdates.swift @@ -19,7 +19,8 @@ func updatePremiumPromoConfigurationOnce(accountPeerId: PeerId, postbox: Postbox return .complete() } return postbox.transaction { transaction -> Void in - if case let .premiumPromo(_, _, _, _, _, apiUsers) = result { + if case let .premiumPromo(premiumPromoData) = result { + let apiUsers = premiumPromoData.users let parsedPeers = AccumulatedPeers(transaction: transaction, chats: [], users: apiUsers) updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers) } @@ -59,7 +60,8 @@ private func updatePremiumPromoConfiguration(transaction: Transaction, _ f: (Pre private extension PremiumPromoConfiguration { init(apiPremiumPromo: Api.help.PremiumPromo) { switch apiPremiumPromo { - case let .premiumPromo(statusText, statusEntities, videoSections, videoFiles, options, _): + case let .premiumPromo(premiumPromoData): + let (statusText, statusEntities, videoSections, videoFiles, options) = (premiumPromoData.statusText, premiumPromoData.statusEntities, premiumPromoData.videoSections, premiumPromoData.videos, premiumPromoData.periodOptions) self.status = statusText self.statusEntities = messageTextEntitiesFromApiEntities(statusEntities) @@ -73,7 +75,8 @@ private extension PremiumPromoConfiguration { var productOptions: [PremiumProductOption] = [] for option in options { - if case let .premiumSubscriptionOption(flags, transaction, months, currency, amount, botUrl, storeProduct) = option { + if case let .premiumSubscriptionOption(premiumSubscriptionOptionData) = option { + let (flags, transaction, months, currency, amount, botUrl, storeProduct) = (premiumSubscriptionOptionData.flags, premiumSubscriptionOptionData.transaction, premiumSubscriptionOptionData.months, premiumSubscriptionOptionData.currency, premiumSubscriptionOptionData.amount, premiumSubscriptionOptionData.botUrl, premiumSubscriptionOptionData.storeProduct) productOptions.append(PremiumProductOption(isCurrent: (flags & (1 << 1)) != 0, months: months, currency: currency, amount: amount, botUrl: botUrl, transactionId: transaction, availableForUpgrade: (flags & (1 << 2)) != 0, storeProductId: storeProduct)) } } diff --git a/submodules/TelegramCore/Sources/State/ManagedProxyInfoUpdates.swift b/submodules/TelegramCore/Sources/State/ManagedProxyInfoUpdates.swift index 088ee5d0..87796714 100644 --- a/submodules/TelegramCore/Sources/State/ManagedProxyInfoUpdates.swift +++ b/submodules/TelegramCore/Sources/State/ManagedProxyInfoUpdates.swift @@ -166,7 +166,8 @@ public final class ServerSuggestionInfo: Codable, Equatable { extension ServerSuggestionInfo.Item.Text { convenience init(_ apiText: Api.TextWithEntities) { switch apiText { - case let .textWithEntities(text, entities): + case let .textWithEntities(textWithEntitiesData): + let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities) self.init(string: text, entities: messageTextEntitiesFromApiEntities(entities)) } } @@ -175,7 +176,8 @@ extension ServerSuggestionInfo.Item.Text { extension ServerSuggestionInfo.Item { convenience init(_ apiItem: Api.PendingSuggestion) { switch apiItem { - case let .pendingSuggestion(suggestion, title, description, url): + case let .pendingSuggestion(pendingSuggestionData): + let (suggestion, title, description, url) = (pendingSuggestionData.suggestion, pendingSuggestionData.title, pendingSuggestionData.description, pendingSuggestionData.url) self.init( id: suggestion, title: ServerSuggestionInfo.Item.Text(title), @@ -189,12 +191,12 @@ extension ServerSuggestionInfo.Item { func _internal_fetchPromoInfo(accountPeerId: EnginePeer.Id, postbox: Postbox, network: Network) -> Signal { return network.request(Api.functions.help.getPromoData()) |> `catch` { _ -> Signal in - return .single(.promoDataEmpty(expires: 10 * 60)) + return .single(.promoDataEmpty(.init(expires: 10 * 60))) } |> mapToSignal { data -> Signal in return postbox.transaction { transaction -> Void in switch data { - case .promoDataEmpty: + case .promoDataEmpty(_): transaction.replaceAdditionalChatListItems([]) let suggestionInfo = ServerSuggestionInfo( @@ -206,7 +208,8 @@ func _internal_fetchPromoInfo(accountPeerId: EnginePeer.Id, postbox: Postbox, ne transaction.updatePreferencesEntry(key: PreferencesKeys.serverSuggestionInfo(), { _ in return PreferencesEntry(suggestionInfo) }) - case let .promoData(flags, expires, peer, psaType, psaMessage, pendingSuggestions, dismissedSuggestions, customPendingSuggestion, chats, users): + case let .promoData(promoDataData): + let (flags, expires, peer, psaType, psaMessage, pendingSuggestions, dismissedSuggestions, customPendingSuggestion, chats, users) = (promoDataData.flags, promoDataData.expires, promoDataData.peer, promoDataData.psaType, promoDataData.psaMessage, promoDataData.pendingSuggestions, promoDataData.dismissedSuggestions, promoDataData.customPendingSuggestion, promoDataData.chats, promoDataData.users) let _ = expires let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users) diff --git a/submodules/TelegramCore/Sources/State/ManagedRecentStickers.swift b/submodules/TelegramCore/Sources/State/ManagedRecentStickers.swift index 4a954b1c..8b0b65bf 100644 --- a/submodules/TelegramCore/Sources/State/ManagedRecentStickers.swift +++ b/submodules/TelegramCore/Sources/State/ManagedRecentStickers.swift @@ -53,7 +53,8 @@ func managedRecentStickers(postbox: Postbox, network: Network, forceFetch: Bool switch result { case .recentStickersNotModified: return .single(nil) - case let .recentStickers(_, _, stickers, _): + case let .recentStickers(recentStickersData): + let stickers = recentStickersData.stickers var items: [OrderedItemListEntry] = [] for sticker in stickers { if let file = telegramMediaFileFromApiDocument(sticker, altDocuments: []), let id = file.id { @@ -79,7 +80,8 @@ func managedRecentGifs(postbox: Postbox, network: Network, forceFetch: Bool = fa switch result { case .savedGifsNotModified: return .single(nil) - case let .savedGifs(_, gifs): + case let .savedGifs(savedGifsData): + let gifs = savedGifsData.gifs var items: [OrderedItemListEntry] = [] for gif in gifs { if let file = telegramMediaFileFromApiDocument(gif, altDocuments: []), let id = file.id { @@ -105,11 +107,13 @@ func managedSavedStickers(postbox: Postbox, network: Network, forceFetch: Bool = switch result { case .favedStickersNotModified: return .single(nil) - case let .favedStickers(_, packs, stickers): + case let .favedStickers(favedStickersData): + let (packs, stickers) = (favedStickersData.packs, favedStickersData.stickers) var fileStringRepresentations: [MediaId: [String]] = [:] for pack in packs { switch pack { - case let .stickerPack(text, fileIds): + case let .stickerPack(stickerPackData): + let (text, fileIds) = (stickerPackData.emoticon, stickerPackData.documents) for fileId in fileIds { let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: fileId) if fileStringRepresentations[mediaId] == nil { @@ -150,7 +154,8 @@ func managedGreetingStickers(postbox: Postbox, network: Network) -> Signal Signal Signal Signal map { files -> [OrderedItemListEntry] in var items: [OrderedItemListEntry] = [] @@ -264,9 +272,10 @@ func managedFeaturedStatusEmoji(postbox: Postbox, network: Network) -> Signal map { files -> [OrderedItemListEntry] in var items: [OrderedItemListEntry] = [] @@ -297,9 +306,10 @@ func managedFeaturedChannelStatusEmoji(postbox: Postbox, network: Network) -> Si switch result { case .emojiStatusesNotModified: return .single(nil) - case let .emojiStatuses(_, statuses): + case let .emojiStatuses(emojiStatusesData): + let statuses = emojiStatusesData.statuses let parsedStatuses = statuses.compactMap(PeerEmojiStatus.init(apiStatus:)) - + return _internal_resolveInlineStickers(postbox: postbox, network: network, fileIds: parsedStatuses.compactMap(\.emojiFileId)) |> map { files -> [OrderedItemListEntry] in var items: [OrderedItemListEntry] = [] @@ -330,9 +340,10 @@ func managedUniqueStarGifts(accountPeerId: PeerId, postbox: Postbox, network: Ne switch result { case .emojiStatusesNotModified: return .single(nil) - case let .emojiStatuses(_, statuses): + case let .emojiStatuses(emojiStatusesData): + let statuses = emojiStatusesData.statuses let parsedStatuses = statuses.compactMap(PeerEmojiStatus.init(apiStatus:)) - + return _internal_resolveInlineStickers(postbox: postbox, network: network, fileIds: parsedStatuses.flatMap(\.associatedFileIds)) |> map { files -> [OrderedItemListEntry] in var items: [OrderedItemListEntry] = [] @@ -349,9 +360,9 @@ func managedUniqueStarGifts(accountPeerId: PeerId, postbox: Postbox, network: Ne slug: slug, owner: .peerId(accountPeerId), attributes: [ - .model(name: "", file: file, rarity: 0), - .pattern(name: "", file: patternFile, rarity: 0), - .backdrop(name: "", id: 0, innerColor: innerColor, outerColor: outerColor, patternColor: patternColor, textColor: textColor, rarity: 0) + .model(name: "", file: file, rarity: .rare, crafted: true), + .pattern(name: "", file: patternFile, rarity: .rare), + .backdrop(name: "", id: 0, innerColor: innerColor, outerColor: outerColor, patternColor: patternColor, textColor: textColor, rarity: .rare) ], availability: StarGift.UniqueGift.Availability(issued: 0, total: 0), giftAddress: nil, @@ -365,7 +376,8 @@ func managedUniqueStarGifts(accountPeerId: PeerId, postbox: Postbox, network: Ne themePeerId: nil, peerColor: nil, hostPeerId: nil, - minOfferStars: nil + minOfferStars: nil, + craftChancePermille: nil ) if let entry = CodableEntry(RecentStarGiftItem(gift)) { items.append(OrderedItemListEntry(id: RecentStarGiftItemId(id).rawValue, contents: entry)) @@ -395,7 +407,8 @@ func managedProfilePhotoEmoji(postbox: Postbox, network: Network) -> Signal map { files -> [OrderedItemListEntry] in var items: [OrderedItemListEntry] = [] @@ -426,7 +439,8 @@ func managedGroupPhotoEmoji(postbox: Postbox, network: Network) -> Signal map { files -> [OrderedItemListEntry] in var items: [OrderedItemListEntry] = [] @@ -457,7 +471,8 @@ func managedBackgroundIconEmoji(postbox: Postbox, network: Network) -> Signal map { files -> [OrderedItemListEntry] in var items: [OrderedItemListEntry] = [] @@ -488,7 +503,8 @@ func managedDisabledChannelStatusIconEmoji(postbox: Postbox, network: Network) - switch result { case .emojiListNotModified: return .single(nil) - case let .emojiList(_, documentIds): + case let .emojiList(emojiListData): + let documentIds = emojiListData.documentId return _internal_resolveInlineStickers(postbox: postbox, network: network, fileIds: documentIds) |> map { files -> [OrderedItemListEntry] in var items: [OrderedItemListEntry] = [] @@ -528,9 +544,10 @@ func managedRecentReactions(postbox: Postbox, network: Network) -> Signal Int64? in switch reaction { case .builtin: @@ -588,9 +605,10 @@ func managedTopReactions(postbox: Postbox, network: Network) -> Signal Int64? in switch reaction { case .builtin: @@ -648,9 +666,10 @@ func managedDefaultTagReactions(postbox: Postbox, network: Network) -> Signal Int64? in switch reaction { case .builtin: diff --git a/submodules/TelegramCore/Sources/State/ManagedSecretChatOutgoingOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSecretChatOutgoingOperations.swift index 45d409b3..51c9526e 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSecretChatOutgoingOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSecretChatOutgoingOperations.swift @@ -246,7 +246,7 @@ private func initialHandshakeAccept(postbox: Postbox, network: Network, peerId: memcpy(&keyFingerprint, bytes.advanced(by: keyHash.count - 8), 8) } - let result = network.request(Api.functions.messages.acceptEncryption(peer: .inputEncryptedChat(chatId: Int32(peerId.id._internalGetInt64Value()), accessHash: accessHash), gB: Buffer(data: gb), keyFingerprint: keyFingerprint)) + let result = network.request(Api.functions.messages.acceptEncryption(peer: .inputEncryptedChat(.init(chatId: Int32(peerId.id._internalGetInt64Value()), accessHash: accessHash)), gB: Buffer(data: gb), keyFingerprint: keyFingerprint)) let response = result |> map { result -> Api.EncryptedChat? in @@ -1783,9 +1783,11 @@ private func sendMessage(auxiliaryMethods: AccountAuxiliaryMethods, postbox: Pos var encryptedFile: SecretChatFileReference? if case let .message(result) = result { switch result { - case let .sentEncryptedMessage(date): + case let .sentEncryptedMessage(sentEncryptedMessageData): + let date = sentEncryptedMessageData.date timestamp = date - case let .sentEncryptedFile(date, file): + case let .sentEncryptedFile(sentEncryptedFileData): + let (date, file) = (sentEncryptedFileData.date, sentEncryptedFileData.file) timestamp = date encryptedFile = SecretChatFileReference(file) } @@ -1928,9 +1930,11 @@ private func sendStandaloneMessage(auxiliaryMethods: AccountAuxiliaryMethods, po var encryptedFile: SecretChatFileReference? if case let .message(result) = result { switch result { - case let .sentEncryptedMessage(date): + case let .sentEncryptedMessage(sentEncryptedMessageData): + let date = sentEncryptedMessageData.date timestamp = date - case let .sentEncryptedFile(date, file): + case let .sentEncryptedFile(sentEncryptedFileData): + let (date, file) = (sentEncryptedFileData.date, sentEncryptedFileData.file) timestamp = date encryptedFile = SecretChatFileReference(file) } @@ -2048,9 +2052,11 @@ private func sendServiceActionMessage(postbox: Postbox, network: Network, peerId var timestamp = currentMessage.timestamp if case let .message(result) = result { switch result { - case let .sentEncryptedMessage(date): + case let .sentEncryptedMessage(sentEncryptedMessageData): + let date = sentEncryptedMessageData.date timestamp = date - case let .sentEncryptedFile(date, _): + case let .sentEncryptedFile(sentEncryptedFileData): + let date = sentEncryptedFileData.date timestamp = date } flags.remove(.Unsent) @@ -2132,7 +2138,7 @@ private func sendBoxedDecryptedMessage(postbox: Postbox, network: Network, peer: decryptedMessage.serialize(payload, role: state.role, sequenceInfo: sequenceInfo) let encryptedPayload = encryptedMessageContents(parameters: parameters, data: MemoryBuffer(payload)) let sendMessage: Signal - let inputPeer = Api.InputEncryptedChat.inputEncryptedChat(chatId: Int32(peer.id.id._internalGetInt64Value()), accessHash: peer.accessHash) + let inputPeer = Api.InputEncryptedChat.inputEncryptedChat(.init(chatId: Int32(peer.id.id._internalGetInt64Value()), accessHash: peer.accessHash)) var flags: Int32 = 0 if silent { @@ -2188,7 +2194,7 @@ private func requestTerminateSecretChat(postbox: Postbox, network: Network, peer } |> mapToSignal { peer -> Signal in if let peer = peer { - return network.request(Api.functions.messages.reportEncryptedSpam(peer: Api.InputEncryptedChat.inputEncryptedChat(chatId: Int32(peer.id.id._internalGetInt64Value()), accessHash: peer.accessHash))) + return 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 in return .single(nil) diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizeAppLogEventsOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizeAppLogEventsOperations.swift index e9c912e3..21aa5595 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizeAppLogEventsOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizeAppLogEventsOperations.swift @@ -117,7 +117,7 @@ private func synchronizeAppLogEvents(transaction: Transaction, postbox: Postbox, switch operation.content { case let .add(time, type, peerId, data): if let data = apiJson(data) { - events.append(.inputAppEvent(time: time, type: type, peer: peerId?.toInt64() ?? 0, data: data)) + events.append(.inputAppEvent(.init(time: time, type: type, peer: peerId?.toInt64() ?? 0, data: data))) } default: break diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizeChatInputStateOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizeChatInputStateOperations.swift index 46ea7677..1ea84481 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizeChatInputStateOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizeChatInputStateOperations.swift @@ -215,17 +215,17 @@ private func synchronizeChatInputState(transaction: Transaction, postbox: Postbo innerFlags |= 1 << 6 } if !discard { - replyTo = .inputReplyToMessage(flags: innerFlags, replyToMsgId: replySubject.messageId.id, topMsgId: topMsgId, replyToPeerId: replyToPeer, quoteText: quoteText, quoteEntities: quoteEntities, quoteOffset: quoteOffset, monoforumPeerId: monoforumPeerId, todoItemId: replyTodoItemId) + replyTo = .inputReplyToMessage(.init(flags: innerFlags, replyToMsgId: replySubject.messageId.id, topMsgId: topMsgId, replyToPeerId: replyToPeer, quoteText: quoteText, quoteEntities: quoteEntities, quoteOffset: quoteOffset, monoforumPeerId: monoforumPeerId, todoItemId: replyTodoItemId)) } } else if let topMsgId { flags |= 1 << 0 var innerFlags: Int32 = 0 innerFlags |= 1 << 0 - replyTo = .inputReplyToMessage(flags: innerFlags, replyToMsgId: topMsgId, topMsgId: topMsgId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil) + replyTo = .inputReplyToMessage(.init(flags: innerFlags, replyToMsgId: topMsgId, 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)) } let suggestedPost = inputState?.suggestedPost.flatMap { suggestedPost -> Api.SuggestedPost in @@ -233,7 +233,7 @@ private func synchronizeChatInputState(transaction: Transaction, postbox: Postbo if suggestedPost.timestamp != nil { flags |= 1 << 0 } - return .suggestedPost(flags: flags, price: suggestedPost.price?.apiAmount ?? .starsAmount(amount: 0, nanos: 0), scheduleDate: suggestedPost.timestamp) + return .suggestedPost(.init(flags: flags, price: suggestedPost.price?.apiAmount ?? .starsAmount(.init(amount: 0, nanos: 0)), scheduleDate: suggestedPost.timestamp)) } if suggestedPost != nil { flags |= 1 << 8 diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizeConsumeMessageContentsOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizeConsumeMessageContentsOperations.swift index 5274d71a..f6df475f 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizeConsumeMessageContentsOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizeConsumeMessageContentsOperations.swift @@ -119,7 +119,8 @@ private func synchronizeConsumeMessageContents(transaction: Transaction, network |> mapToSignal { result -> Signal 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)]) } } diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizeEmojiKeywordsOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizeEmojiKeywordsOperations.swift index 49cb80cd..930ebc12 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizeEmojiKeywordsOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizeEmojiKeywordsOperations.swift @@ -123,18 +123,21 @@ private func synchronizeEmojiKeywords(postbox: Postbox, transaction: Transaction |> retryRequest |> mapToSignal { result -> Signal in switch result { - case let .emojiKeywordsDifference(langCode, _, version, keywords): + case let .emojiKeywordsDifference(emojiKeywordsDifferenceData): + let (langCode, version, keywords) = (emojiKeywordsDifferenceData.langCode, emojiKeywordsDifferenceData.version, emojiKeywordsDifferenceData.keywords) if langCode == languageCode { var itemsToAppend: [String: EmojiKeywordItem] = [:] var itemsToSubtract: [String: EmojiKeywordItem] = [:] for apiEmojiKeyword in keywords { switch apiEmojiKeyword { - case let .emojiKeyword(keyword, emoticons): - let keyword = keyword.replacingOccurrences(of: " ", with: "") + case let .emojiKeyword(emojiKeywordData): + let (rawKeyword, emoticons) = (emojiKeywordData.keyword, emojiKeywordData.emoticons) + let keyword = rawKeyword.replacingOccurrences(of: " ", with: "") let indexKeys = stringIndexTokens(keyword, transliteration: .none).map { $0.toMemoryBuffer() } let item = EmojiKeywordItem(index: ItemCollectionItemIndex(index: 0, id: 0), collectionId: collectionId.id, keyword: keyword, emoticons: emoticons, indexKeys: indexKeys) itemsToAppend[keyword] = item - case let .emojiKeywordDeleted(keyword, emoticons): + case let .emojiKeywordDeleted(emojiKeywordDeletedData): + let (keyword, emoticons) = (emojiKeywordDeletedData.keyword, emojiKeywordDeletedData.emoticons) let item = EmojiKeywordItem(index: ItemCollectionItemIndex(index: 0, id: 0), collectionId: collectionId.id, keyword: keyword, emoticons: emoticons, indexKeys: []) itemsToSubtract[keyword] = item } @@ -195,11 +198,13 @@ private func synchronizeEmojiKeywords(postbox: Postbox, transaction: Transaction |> retryRequest |> mapToSignal { result -> Signal in switch result { - case let .emojiKeywordsDifference(langCode, _, version, keywords): + case let .emojiKeywordsDifference(emojiKeywordsDifferenceData): + let (langCode, version, keywords) = (emojiKeywordsDifferenceData.langCode, emojiKeywordsDifferenceData.version, emojiKeywordsDifferenceData.keywords) var items: [EmojiKeywordItem] = [] var index: Int32 = 0 for apiEmojiKeyword in keywords { - if case let .emojiKeyword(fullKeyword, emoticons) = apiEmojiKeyword, !emoticons.isEmpty { + if case let .emojiKeyword(emojiKeywordData) = apiEmojiKeyword, !emojiKeywordData.emoticons.isEmpty { + let (fullKeyword, emoticons) = (emojiKeywordData.keyword, emojiKeywordData.emoticons) let keyword = fullKeyword let indexKeys = stringIndexTokens(keyword, transliteration: .none).map { $0.toMemoryBuffer() } let item = EmojiKeywordItem(index: ItemCollectionItemIndex(index: index, id: keywordCollectionItemId(keyword, inputLanguageCode: operation.inputLanguageCode)), collectionId: collectionId.id, keyword: keyword, emoticons: emoticons, indexKeys: indexKeys) diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizeGroupMessageStats.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizeGroupMessageStats.swift index 92842729..d6b8bf22 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizeGroupMessageStats.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizeGroupMessageStats.swift @@ -79,7 +79,7 @@ private func synchronizeGroupMessageStats(postbox: Postbox, network: Network, gr return .complete() } - return network.request(Api.functions.messages.getPeerDialogs(peers: [.inputDialogPeerFolder(folderId: groupId.rawValue)])) + return network.request(Api.functions.messages.getPeerDialogs(peers: [.inputDialogPeerFolder(.init(folderId: groupId.rawValue))])) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -88,10 +88,12 @@ private func synchronizeGroupMessageStats(postbox: Postbox, network: Network, gr return postbox.transaction { transaction in if let result = result { switch result { - case let .peerDialogs(dialogs, _, _, _, _): + case let .peerDialogs(peerDialogsData): + let dialogs = peerDialogsData.dialogs for dialog in dialogs { switch dialog { - case let .dialogFolder(_, _, _, _, unreadMutedPeersCount, _, unreadMutedMessagesCount, _): + case let .dialogFolder(dialogFolderData): + let (unreadMutedPeersCount, unreadMutedMessagesCount) = (dialogFolderData.unreadMutedPeersCount, dialogFolderData.unreadMutedMessagesCount) transaction.resetPeerGroupSummary(groupId: groupId, namespace: namespace, summary: PeerGroupUnreadCountersSummary(all: PeerGroupUnreadCounters(messageCount: unreadMutedMessagesCount, chatCount: unreadMutedPeersCount))) case .dialog: assertionFailure() diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizeGroupedPeersOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizeGroupedPeersOperations.swift index 55f3de99..48da58b8 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizeGroupedPeersOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizeGroupedPeersOperations.swift @@ -134,7 +134,7 @@ private func synchronizeGroupedPeers(transaction: Transaction, postbox: Postbox, var folderPeers: [Api.InputFolderPeer] = [] for operation in operations { if let inputPeer = transaction.getPeer(operation.peerId).flatMap(apiInputPeer) { - folderPeers.append(.inputFolderPeer(peer: inputPeer, folderId: operation.groupId.rawValue)) + folderPeers.append(.inputFolderPeer(.init(peer: inputPeer, folderId: operation.groupId.rawValue))) } } if folderPeers.isEmpty { diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizeInstalledStickerPacksOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizeInstalledStickerPacksOperations.swift index d45af15a..d7e1728e 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizeInstalledStickerPacksOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizeInstalledStickerPacksOperations.swift @@ -143,19 +143,21 @@ private enum SynchronizeInstalledStickerPacksError { } private func fetchStickerPack(network: Network, info: StickerPackCollectionInfo) -> Signal<(StickerPackCollectionInfo, [ItemCollectionItem]), NoError> { - return network.request(Api.functions.messages.getStickerSet(stickerset: .inputStickerSetID(id: info.id.id, accessHash: info.accessHash), hash: 0)) + return network.request(Api.functions.messages.getStickerSet(stickerset: .inputStickerSetID(.init(id: info.id.id, accessHash: info.accessHash)), hash: 0)) |> map { result -> (StickerPackCollectionInfo, [ItemCollectionItem]) in var items: [ItemCollectionItem] = [] var updatedInfo = info switch result { case .stickerSetNotModified: break - case let .stickerSet(stickerSet, packs, keywords, documents): + case let .stickerSet(stickerSetData): + let (stickerSet, packs, keywords, documents) = (stickerSetData.set, stickerSetData.packs, stickerSetData.keywords, stickerSetData.documents) updatedInfo = StickerPackCollectionInfo(apiSet: stickerSet, namespace: info.id.namespace) var indexKeysByFile: [MediaId: [MemoryBuffer]] = [:] for pack in packs { switch pack { - case let .stickerPack(text, fileIds): + case let .stickerPack(stickerPackData): + let (text, fileIds) = (stickerPackData.emoticon, stickerPackData.documents) let key = ValueBoxKey(text).toMemoryBuffer() for fileId in fileIds { let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: fileId) @@ -170,7 +172,8 @@ private func fetchStickerPack(network: Network, info: StickerPackCollectionInfo) } for keyword in keywords { switch keyword { - case let .stickerKeyword(documentId, texts): + case let .stickerKeyword(stickerKeywordData): + let (documentId, texts) = (stickerKeywordData.documentId, stickerKeywordData.keyword) for text in texts { let key = ValueBoxKey(text).toMemoryBuffer() let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: documentId) @@ -228,22 +231,27 @@ private func resolveStickerPacks(network: Network, remoteInfos: [ItemCollectionI private func installRemoteStickerPacks(network: Network, infos: [StickerPackCollectionInfo]) -> Signal, NoError> { var signals: [Signal, NoError>] = [] for info in infos { - let install = network.request(Api.functions.messages.installStickerSet(stickerset: .inputStickerSetID(id: info.id.id, accessHash: info.accessHash), archived: .boolFalse)) + let install = network.request(Api.functions.messages.installStickerSet(stickerset: .inputStickerSetID(.init(id: info.id.id, accessHash: info.accessHash)), archived: .boolFalse)) |> map { result -> Set in switch result { case .stickerSetInstallResultSuccess: return Set() - case let .stickerSetInstallResultArchive(archivedSets): + case let .stickerSetInstallResultArchive(stickerSetInstallResultArchiveData): + let archivedSets = stickerSetInstallResultArchiveData.sets var archivedIds = Set() for archivedSet in archivedSets { switch archivedSet { - case let .stickerSetCovered(set, _): + case let .stickerSetCovered(stickerSetCoveredData): + let set = stickerSetCoveredData.set archivedIds.insert(StickerPackCollectionInfo(apiSet: set, namespace: info.id.namespace).id) - case let .stickerSetMultiCovered(set, _): + case let .stickerSetMultiCovered(stickerSetMultiCoveredData): + let set = stickerSetMultiCoveredData.set archivedIds.insert(StickerPackCollectionInfo(apiSet: set, namespace: info.id.namespace).id) - case let .stickerSetFullCovered(set, _, _, _): + case let .stickerSetFullCovered(stickerSetFullCoveredData): + let set = stickerSetFullCoveredData.set archivedIds.insert(StickerPackCollectionInfo(apiSet: set, namespace: info.id.namespace).id) - case let .stickerSetNoCovered(set): + case let .stickerSetNoCovered(stickerSetNoCoveredData): + let set = stickerSetNoCoveredData.set archivedIds.insert(StickerPackCollectionInfo(apiSet: set, namespace: info.id.namespace).id) } } @@ -268,7 +276,7 @@ private func installRemoteStickerPacks(network: Network, infos: [StickerPackColl private func removeRemoteStickerPacks(network: Network, infos: [StickerPackCollectionInfo]) -> Signal { if infos.count > 0 { if infos.count > 1 { - return network.request(Api.functions.messages.toggleStickerSets(flags: 1 << 0, stickersets: infos.map { .inputStickerSetID(id: $0.id.id, accessHash: $0.accessHash) })) + return network.request(Api.functions.messages.toggleStickerSets(flags: 1 << 0, stickersets: infos.map { .inputStickerSetID(.init(id: $0.id.id, accessHash: $0.accessHash)) })) |> mapToSignal { _ -> Signal in return .single(Void()) } @@ -276,7 +284,7 @@ private func removeRemoteStickerPacks(network: Network, infos: [StickerPackColle return .single(Void()) } } else if let info = infos.first { - return network.request(Api.functions.messages.uninstallStickerSet(stickerset: .inputStickerSetID(id: info.id.id, accessHash: info.accessHash))) + return network.request(Api.functions.messages.uninstallStickerSet(stickerset: .inputStickerSetID(.init(id: info.id.id, accessHash: info.accessHash)))) |> mapToSignal { _ -> Signal in return .single(Void()) } @@ -291,7 +299,7 @@ private func removeRemoteStickerPacks(network: Network, infos: [StickerPackColle private func archiveRemoteStickerPacks(network: Network, infos: [StickerPackCollectionInfo]) -> Signal { if infos.count > 0 { if infos.count > 1 { - return network.request(Api.functions.messages.toggleStickerSets(flags: 1 << 1, stickersets: infos.map { .inputStickerSetID(id: $0.id.id, accessHash: $0.accessHash) })) + return network.request(Api.functions.messages.toggleStickerSets(flags: 1 << 1, stickersets: infos.map { .inputStickerSetID(.init(id: $0.id.id, accessHash: $0.accessHash)) })) |> mapToSignal { _ -> Signal in return .single(Void()) } @@ -299,7 +307,7 @@ private func archiveRemoteStickerPacks(network: Network, infos: [StickerPackColl return .single(Void()) } } else if let info = infos.first { - return network.request(Api.functions.messages.installStickerSet(stickerset: .inputStickerSetID(id: info.id.id, accessHash: info.accessHash), archived: .boolTrue)) + return network.request(Api.functions.messages.installStickerSet(stickerset: .inputStickerSetID(.init(id: info.id.id, accessHash: info.accessHash)), archived: .boolTrue)) |> mapToSignal { _ -> Signal in return .single(Void()) } @@ -501,7 +509,8 @@ private func continueSynchronizeInstalledStickerPacks(transaction: Transaction, var remoteCollectionInfos: [StickerPackCollectionInfo] = [] switch result { - case let .allStickers(_, sets): + case let .allStickers(allStickersData): + let sets = allStickersData.sets for apiSet in sets { let info = StickerPackCollectionInfo(apiSet: apiSet, namespace: collectionNamespace) remoteCollectionInfos.append(info) diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizeMarkAllUnseenPersonalMessagesOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizeMarkAllUnseenPersonalMessagesOperations.swift index 79bef55e..754e7732 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizeMarkAllUnseenPersonalMessagesOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizeMarkAllUnseenPersonalMessagesOperations.swift @@ -126,13 +126,16 @@ private func synchronizeMarkAllUnseen(transaction: Transaction, postbox: Postbox return network.request(Api.functions.messages.getUnreadMentions(flags: 0, peer: inputPeer, topMsgId: nil, offsetId: maxId, addOffset: maxId == 0 ? 0 : -1, limit: limit, maxId: maxId == 0 ? 0 : (maxId + 1), minId: 1)) |> mapToSignal { result -> Signal<[MessageId], MTRpcError> in switch result { - case let .messages(messages, _, _, _): + case let .messages(messagesData): + let messages = messagesData.messages return .single(messages.compactMap({ $0.id() })) - case let .channelMessages(_, _, _, _, messages, _, _, _): + case let .channelMessages(channelMessagesData): + let messages = channelMessagesData.messages return .single(messages.compactMap({ $0.id() })) case .messagesNotModified: return .single([]) - case let .messagesSlice(_, _, _, _, _, messages, _, _, _): + case let .messagesSlice(messagesSliceData): + let messages = messagesSliceData.messages return .single(messages.compactMap({ $0.id() })) } } @@ -157,7 +160,8 @@ private func synchronizeMarkAllUnseen(transaction: Transaction, postbox: Postbox return network.request(Api.functions.messages.readMessageContents(id: filteredIds.map { $0.id })) |> map { result -> Int32? in 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)]) } if ids.count < limit { @@ -310,7 +314,8 @@ private func synchronizeMarkAllUnseenReactions(transaction: Transaction, postbox |> mapToSignal { result -> Signal 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) stateManager.addUpdateGroups([.updatePts(pts: pts, ptsCount: ptsCount)]) if offset == 0 { return .fail(true) diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizePinnedChatsOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizePinnedChatsOperations.swift index f0dd1edf..75a15557 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizePinnedChatsOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizePinnedChatsOperations.swift @@ -146,7 +146,8 @@ private func synchronizePinnedChats(transaction: Transaction, postbox: Postbox, let parsedPeers: AccumulatedPeers switch dialogs { - case let .peerDialogs(dialogs, messages, chats, users, _): + case let .peerDialogs(peerDialogsData): + let (dialogs, messages, chats, users) = (peerDialogsData.dialogs, peerDialogsData.messages, peerDialogsData.chats, peerDialogsData.users) parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users) loop: for dialog in dialogs { @@ -160,7 +161,8 @@ private func synchronizePinnedChats(transaction: Transaction, postbox: Postbox, let apiTtlPeriod: Int32? let apiNotificationSettings: Api.PeerNotifySettings switch dialog { - case let .dialog(flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, _, _, peerNotificationSettings, pts, _, _, ttlPeriod): + case let .dialog(dialogData): + let (flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, peerNotificationSettings, pts, ttlPeriod) = (dialogData.flags, dialogData.peer, dialogData.topMessage, dialogData.readInboxMaxId, dialogData.readOutboxMaxId, dialogData.unreadCount, dialogData.notifySettings, dialogData.pts, dialogData.ttlPeriod) apiPeer = peer apiTopMessage = topMessage apiReadInboxMaxId = readInboxMaxId @@ -265,7 +267,7 @@ private func synchronizePinnedChats(transaction: Transaction, postbox: Postbox, switch itemId { case let .peer(peerId): if let peer = transaction.getPeer(peerId), let inputPeer = apiInputPeer(peer) { - inputDialogPeers.append(Api.InputDialogPeer.inputDialogPeer(peer: inputPeer)) + inputDialogPeers.append(Api.InputDialogPeer.inputDialogPeer(.init(peer: inputPeer))) } } } @@ -311,7 +313,8 @@ private func synchronizePinnedSavedChats(transaction: Transaction, postbox: Post loop: for dialog in dialogs { switch dialog { - case let .savedDialog(_, peer, _): + case let .savedDialog(savedDialogData): + let peer = savedDialogData.peer remoteItemIds.append(peer.peerId) } } diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizeRecentlyUsedMediaOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizeRecentlyUsedMediaOperations.swift index d5949cfe..6a545803 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizeRecentlyUsedMediaOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizeRecentlyUsedMediaOperations.swift @@ -128,7 +128,7 @@ private func synchronizeRecentlyUsedMedia(transaction: Transaction, accountPeerI } let addSticker: (Data) -> Signal = { fileReference in - return network.request(Api.functions.messages.saveRecentSticker(flags: 0, id: .inputDocument(id: id, accessHash: accessHash, fileReference: Buffer(data: fileReference)), unsave: .boolFalse)) + return network.request(Api.functions.messages.saveRecentSticker(flags: 0, id: .inputDocument(.init(id: id, accessHash: accessHash, fileReference: Buffer(data: fileReference))), unsave: .boolFalse)) |> mapError { error -> SaveRecentlyUsedMediaError in if error.errorDescription.hasPrefix("FILEREF_INVALID") || error.errorDescription.hasPrefix("FILE_REFERENCE_") { return .invalidReference @@ -170,7 +170,7 @@ private func synchronizeRecentlyUsedMedia(transaction: Transaction, accountPeerI return .complete() } case let .remove(id, accessHash): - return network.request(Api.functions.messages.saveRecentSticker(flags: 0, id: .inputDocument(id: id, accessHash: accessHash, fileReference: Buffer()), unsave: .boolTrue)) + return network.request(Api.functions.messages.saveRecentSticker(flags: 0, id: .inputDocument(.init(id: id, accessHash: accessHash, fileReference: Buffer())), unsave: .boolTrue)) |> `catch` { _ -> Signal in return .single(.boolFalse) } diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizeSavedGifsOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizeSavedGifsOperations.swift index 88e02c3f..f6ebf0dd 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizeSavedGifsOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizeSavedGifsOperations.swift @@ -124,7 +124,7 @@ private func synchronizeSavedGifs(transaction: Transaction, accountPeerId: PeerI } let saveGif: (Data) -> Signal = { fileReference in - return network.request(Api.functions.messages.saveGif(id: .inputDocument(id: id, accessHash: accessHash, fileReference: Buffer(data: fileReference)), unsave: .boolFalse)) + return network.request(Api.functions.messages.saveGif(id: .inputDocument(.init(id: id, accessHash: accessHash, fileReference: Buffer(data: fileReference))), unsave: .boolFalse)) |> mapError { error -> SaveGifError in if error.errorDescription.hasPrefix("FILEREF_INVALID") || error.errorDescription.hasPrefix("FILE_REFERENCE_") { return .invalidReference @@ -166,7 +166,7 @@ private func synchronizeSavedGifs(transaction: Transaction, accountPeerId: PeerI return .complete() } case let .remove(id, accessHash): - return network.request(Api.functions.messages.saveGif(id: .inputDocument(id: id, accessHash: accessHash, fileReference: Buffer()), unsave: .boolTrue)) + return network.request(Api.functions.messages.saveGif(id: .inputDocument(.init(id: id, accessHash: accessHash, fileReference: Buffer())), unsave: .boolTrue)) |> `catch` { _ -> Signal in return .single(.boolFalse) } diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizeSavedStickersOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizeSavedStickersOperations.swift index 369acdbc..e4f91f67 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizeSavedStickersOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizeSavedStickersOperations.swift @@ -124,7 +124,7 @@ private func synchronizeSavedStickers(transaction: Transaction, accountPeerId: P } let saveSticker: (Data) -> Signal = { fileReference in - return network.request(Api.functions.messages.faveSticker(id: .inputDocument(id: id, accessHash: accessHash, fileReference: Buffer(data: fileReference)), unfave: .boolFalse)) + return network.request(Api.functions.messages.faveSticker(id: .inputDocument(.init(id: id, accessHash: accessHash, fileReference: Buffer(data: fileReference))), unfave: .boolFalse)) |> mapError { error -> SaveStickerError in if error.errorDescription.hasPrefix("FILEREF_INVALID") || error.errorDescription.hasPrefix("FILE_REFERENCE_") { return .invalidReference @@ -166,7 +166,7 @@ private func synchronizeSavedStickers(transaction: Transaction, accountPeerId: P return .complete() } case let .remove(id, accessHash): - return network.request(Api.functions.messages.faveSticker(id: .inputDocument(id: id, accessHash: accessHash, fileReference: Buffer()), unfave: .boolTrue)) + return network.request(Api.functions.messages.faveSticker(id: .inputDocument(.init(id: id, accessHash: accessHash, fileReference: Buffer())), unfave: .boolTrue)) |> `catch` { _ -> Signal in return .single(.boolFalse) } diff --git a/submodules/TelegramCore/Sources/State/ManagedVoipConfigurationUpdates.swift b/submodules/TelegramCore/Sources/State/ManagedVoipConfigurationUpdates.swift index 2465ca6d..a7161650 100644 --- a/submodules/TelegramCore/Sources/State/ManagedVoipConfigurationUpdates.swift +++ b/submodules/TelegramCore/Sources/State/ManagedVoipConfigurationUpdates.swift @@ -11,7 +11,8 @@ func managedVoipConfigurationUpdates(postbox: Postbox, network: Network) -> Sign |> mapToSignal { result -> Signal in return postbox.transaction { transaction -> Void in switch result { - case let .dataJSON(data): + case let .dataJSON(dataJSONData): + let data = dataJSONData.data updateVoipConfiguration(transaction: transaction, { configuration in var configuration = configuration configuration.serializedData = data diff --git a/submodules/TelegramCore/Sources/State/MessageReactions.swift b/submodules/TelegramCore/Sources/State/MessageReactions.swift index aee70179..5f0a641f 100644 --- a/submodules/TelegramCore/Sources/State/MessageReactions.swift +++ b/submodules/TelegramCore/Sources/State/MessageReactions.swift @@ -309,7 +309,7 @@ func _internal_updateStarsReactionPrivacy(account: Account, messageId: MessageId guard let inputPrivacyPeer else { return .complete() } - mappedPrivacy = .paidReactionPrivacyPeer(peer: inputPrivacyPeer) + mappedPrivacy = .paidReactionPrivacyPeer(.init(peer: inputPrivacyPeer)) } return account.network.request(Api.functions.messages.togglePaidReactionPrivacy(peer: inputPeer, msgId: messageId.id, private: mappedPrivacy)) @@ -431,7 +431,7 @@ private func requestSendStarsReaction(postbox: Postbox, network: Network, stateM guard let inputPrivacyPeer = transaction.getPeer(peerId).flatMap(apiInputPeer) else { return nil } - mappedPrivacy = .paidReactionPrivacyPeer(peer: inputPrivacyPeer) + mappedPrivacy = .paidReactionPrivacyPeer(.init(peer: inputPrivacyPeer)) } privacy = mappedPrivacy break @@ -907,7 +907,8 @@ public final class EngineMessageReactionListContext { |> mapToSignal { result -> Signal in return account.postbox.transaction { transaction -> InternalState in switch result { - case let .messageReactionsList(_, count, reactions, chats, users, nextOffset): + case let .messageReactionsList(messageReactionsListData): + let (count, reactions, chats, users, nextOffset) = (messageReactionsListData.count, messageReactionsListData.reactions, messageReactionsListData.chats, messageReactionsListData.users, messageReactionsListData.nextOffset) let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users) updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers) @@ -915,7 +916,8 @@ public final class EngineMessageReactionListContext { var items: [EngineMessageReactionListContext.Item] = [] for reaction in reactions { switch reaction { - case let .messagePeerReaction(_, peer, date, reaction): + case let .messagePeerReaction(messagePeerReactionData): + let (peer, date, reaction) = (messagePeerReactionData.peerId, messagePeerReactionData.date, messagePeerReactionData.reaction) if let peer = transaction.getPeer(peer.peerId), let reaction = MessageReaction.Reaction(apiReaction: reaction) { items.append(EngineMessageReactionListContext.Item(peer: EnginePeer(peer), reaction: reaction, timestamp: date, timestampIsReaction: true)) } @@ -1022,9 +1024,9 @@ func _internal_updatePeerReactionSettings(account: Account, peerId: PeerId, reac let mappedReactions: Api.ChatReactions switch reactionSettings.allowedReactions { case .all: - mappedReactions = .chatReactionsAll(flags: 0) + mappedReactions = .chatReactionsAll(.init(flags: 0)) case let .limited(array): - mappedReactions = .chatReactionsSome(reactions: array.map(\.apiReaction)) + mappedReactions = .chatReactionsSome(.init(reactions: array.map(\.apiReaction))) case .empty: mappedReactions = .chatReactionsNone } diff --git a/submodules/TelegramCore/Sources/State/PaidMessages.swift b/submodules/TelegramCore/Sources/State/PaidMessages.swift index 035dcf36..fc412518 100644 --- a/submodules/TelegramCore/Sources/State/PaidMessages.swift +++ b/submodules/TelegramCore/Sources/State/PaidMessages.swift @@ -32,7 +32,8 @@ func _internal_getPaidMessagesRevenue(account: Account, scopePeerId: PeerId, pee return nil } switch result { - case let .paidMessagesRevenue(amount): + case let .paidMessagesRevenue(paidMessagesRevenueData): + let amount = paidMessagesRevenueData.starsAmount return StarsAmount(value: amount, nanos: 0) } } diff --git a/submodules/TelegramCore/Sources/State/PeerInputActivity.swift b/submodules/TelegramCore/Sources/State/PeerInputActivity.swift index 3d8dc5fe..587b8e8f 100644 --- a/submodules/TelegramCore/Sources/State/PeerInputActivity.swift +++ b/submodules/TelegramCore/Sources/State/PeerInputActivity.swift @@ -20,28 +20,33 @@ public struct EmojiInteraction: Equatable { } public init?(apiDataJson: Api.DataJSON) { - if case let .dataJSON(string) = apiDataJson, let data = string.data(using: .utf8) { - do { - let decodedData = try JSONSerialization.jsonObject(with: data, options: []) - guard let item = decodedData as? [String: Any] else { - return nil - } - guard let version = item["v"] as? Int, version == 1 else { - return nil - } - guard let animationsArray = item["a"] as? [Any] else { - return nil - } - var animations: [EmojiInteraction.Animation] = [] - for animationDict in animationsArray { - if let animationDict = animationDict as? [String: Any] { - if let index = animationDict["i"] as? Int, let timeOffset = animationDict["t"] as? Double { - animations.append(EmojiInteraction.Animation(index: index, timeOffset: Float(timeOffset))) + if case let .dataJSON(dataJSONData) = apiDataJson { + let string = dataJSONData.data + if let data = string.data(using: .utf8) { + do { + let decodedData = try JSONSerialization.jsonObject(with: data, options: []) + guard let item = decodedData as? [String: Any] else { + return nil + } + guard let version = item["v"] as? Int, version == 1 else { + return nil + } + guard let animationsArray = item["a"] as? [Any] else { + return nil + } + var animations: [EmojiInteraction.Animation] = [] + for animationDict in animationsArray { + if let animationDict = animationDict as? [String: Any] { + if let index = animationDict["i"] as? Int, let timeOffset = animationDict["t"] as? Double { + animations.append(EmojiInteraction.Animation(index: index, timeOffset: Float(timeOffset))) + } } } + self.animations = animations + } catch { + return nil } - self.animations = animations - } catch { + } else { return nil } } else { @@ -54,9 +59,9 @@ public struct EmojiInteraction: Equatable { public var apiDataJson: Api.DataJSON { let dict = ["v": 1, "a": self.animations.map({ ["i": $0.index, "t": NSDecimalNumber(value: $0.timeOffset).rounding(accordingToBehavior: roundingBehavior)] as [String : Any] })] as [String : Any] if let data = try? JSONSerialization.data(withJSONObject: dict, options: []), let dataString = String(data: data, encoding: .utf8) { - return .dataJSON(data: dataString) + return .dataJSON(.init(data: dataString)) } else { - return .dataJSON(data: "") + return .dataJSON(.init(data: "")) } } } @@ -120,15 +125,19 @@ extension PeerInputActivity { self = .recordingVoice case .sendMessageTypingAction: self = .typingText - case let .sendMessageUploadDocumentAction(progress): + case let .sendMessageUploadDocumentAction(sendMessageUploadDocumentActionData): + let progress = sendMessageUploadDocumentActionData.progress self = .uploadingFile(progress: progress) - case let .sendMessageUploadPhotoAction(progress): + case let .sendMessageUploadPhotoAction(sendMessageUploadPhotoActionData): + let progress = sendMessageUploadPhotoActionData.progress self = .uploadingPhoto(progress: progress) - case let .sendMessageUploadVideoAction(progress): + case let .sendMessageUploadVideoAction(sendMessageUploadVideoActionData): + let progress = sendMessageUploadVideoActionData.progress self = .uploadingVideo(progress: progress) case .sendMessageRecordRoundAction: self = .recordingInstantVideo - case let .sendMessageUploadRoundAction(progress): + case let .sendMessageUploadRoundAction(sendMessageUploadRoundActionData): + let progress = sendMessageUploadRoundActionData.progress self = .uploadingInstantVideo(progress: progress) case .speakingInGroupCallAction: self = .speakingInGroupCall(timestamp: timestamp) @@ -136,13 +145,15 @@ extension PeerInputActivity { self = .choosingSticker case .sendMessageHistoryImportAction: return nil - case let .sendMessageEmojiInteraction(emoticon, messageId, interaction): + case let .sendMessageEmojiInteraction(sendMessageEmojiInteractionData): + let (emoticon, messageId, interaction) = (sendMessageEmojiInteractionData.emoticon, sendMessageEmojiInteractionData.msgId, sendMessageEmojiInteractionData.interaction) if let peerId = peerId { self = .interactingWithEmoji(emoticon: emoticon, messageId: MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: messageId), interaction: EmojiInteraction(apiDataJson: interaction)) } else { return nil } - case let .sendMessageEmojiInteractionSeen(emoticon): + case let .sendMessageEmojiInteractionSeen(sendMessageEmojiInteractionSeenData): + let emoticon = sendMessageEmojiInteractionSeenData.emoticon self = .seeingEmojiInteraction(emoticon: emoticon) case .sendMessageTextDraftAction: return nil diff --git a/submodules/TelegramCore/Sources/State/PendingMessageManager.swift b/submodules/TelegramCore/Sources/State/PendingMessageManager.swift index 869b2f9d..ff485b31 100644 --- a/submodules/TelegramCore/Sources/State/PendingMessageManager.swift +++ b/submodules/TelegramCore/Sources/State/PendingMessageManager.swift @@ -1105,9 +1105,9 @@ public final class PendingMessageManager { var quickReplyShortcut: Api.InputQuickReplyShortcut? if let quickReply { if let threadId = messages[0].0.threadId { - quickReplyShortcut = .inputQuickReplyShortcutId(shortcutId: Int32(clamping: threadId)) + quickReplyShortcut = .inputQuickReplyShortcutId(.init(shortcutId: Int32(clamping: threadId))) } else { - quickReplyShortcut = .inputQuickReplyShortcut(shortcut: quickReply.shortcut) + quickReplyShortcut = .inputQuickReplyShortcut(.init(shortcut: quickReply.shortcut)) } flags |= 1 << 17 } @@ -1118,7 +1118,7 @@ public final class PendingMessageManager { var replyTo: Api.InputReplyTo? if let monoforumPeerId { - replyTo = .inputReplyToMonoForum(monoforumPeerId: monoforumPeerId) + replyTo = .inputReplyToMonoForum(.init(monoforumPeerId: monoforumPeerId)) flags |= 1 << 22 } @@ -1176,7 +1176,7 @@ public final class PendingMessageManager { singleFlags |= 1 << 0 } - singleMedias.append(.inputSingleMedia(flags: singleFlags, media: inputMedia, randomId: uniqueId, message: text, entities: messageEntities)) + singleMedias.append(.inputSingleMedia(.init(flags: singleFlags, media: inputMedia, randomId: uniqueId, message: text, entities: messageEntities))) default: return failMessages(postbox: postbox, ids: group.map { $0.0 }) } @@ -1253,23 +1253,23 @@ public final class PendingMessageManager { replyFlags |= 1 << 6 } - replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: topMsgId, replyToPeerId: replyToPeerId, quoteText: quoteText, quoteEntities: quoteEntities, quoteOffset: quoteOffset, monoforumPeerId: monoforumPeerId, todoItemId: replyTodoItemId) + replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: topMsgId, replyToPeerId: replyToPeerId, quoteText: quoteText, quoteEntities: quoteEntities, quoteOffset: quoteOffset, monoforumPeerId: monoforumPeerId, todoItemId: replyTodoItemId)) } else if let replyToStoryId { if let inputPeer = transaction.getPeer(replyToStoryId.peerId).flatMap(apiInputPeer) { flags |= 1 << 0 - replyTo = .inputReplyToStory(peer: inputPeer, storyId: replyToStoryId.id) + replyTo = .inputReplyToStory(.init(peer: inputPeer, storyId: replyToStoryId.id)) } } else if let monoforumPeerId { flags |= 1 << 0 - replyTo = .inputReplyToMonoForum(monoforumPeerId: monoforumPeerId) + replyTo = .inputReplyToMonoForum(.init(monoforumPeerId: monoforumPeerId)) } var quickReplyShortcut: Api.InputQuickReplyShortcut? if let quickReply { if let threadId = messages[0].0.threadId { - quickReplyShortcut = .inputQuickReplyShortcutId(shortcutId: Int32(clamping: threadId)) + quickReplyShortcut = .inputQuickReplyShortcutId(.init(shortcutId: Int32(clamping: threadId))) } else { - quickReplyShortcut = .inputQuickReplyShortcut(shortcut: quickReply.shortcut) + quickReplyShortcut = .inputQuickReplyShortcut(.init(shortcut: quickReply.shortcut)) } flags |= 1 << 17 } @@ -1645,15 +1645,15 @@ public final class PendingMessageManager { if let _ = replyTodoItemId { replyFlags |= 1 << 6 } - replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: topMsgId, replyToPeerId: replyToPeerId, quoteText: quoteText, quoteEntities: quoteEntities, quoteOffset: quoteOffset, monoforumPeerId: monoforumPeerId, todoItemId: replyTodoItemId) + replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: topMsgId, replyToPeerId: replyToPeerId, quoteText: quoteText, quoteEntities: quoteEntities, quoteOffset: quoteOffset, monoforumPeerId: monoforumPeerId, todoItemId: replyTodoItemId)) } else if let replyToStoryId = replyToStoryId { if let inputPeer = transaction.getPeer(replyToStoryId.peerId).flatMap(apiInputPeer) { flags |= 1 << 0 - replyTo = .inputReplyToStory(peer: inputPeer, storyId: replyToStoryId.id) + replyTo = .inputReplyToStory(.init(peer: inputPeer, storyId: replyToStoryId.id)) } } else if let monoforumPeerId { flags |= 1 << 0 - replyTo = .inputReplyToMonoForum(monoforumPeerId: monoforumPeerId) + replyTo = .inputReplyToMonoForum(.init(monoforumPeerId: monoforumPeerId)) } if let attribute = message.webpagePreviewAttribute { if attribute.leadingPreview { @@ -1667,9 +1667,9 @@ public final class PendingMessageManager { var quickReplyShortcut: Api.InputQuickReplyShortcut? if let quickReply { if let threadId = message.threadId { - quickReplyShortcut = .inputQuickReplyShortcutId(shortcutId: Int32(clamping: threadId)) + quickReplyShortcut = .inputQuickReplyShortcutId(.init(shortcutId: Int32(clamping: threadId))) } else { - quickReplyShortcut = .inputQuickReplyShortcut(shortcut: quickReply.shortcut) + quickReplyShortcut = .inputQuickReplyShortcut(.init(shortcut: quickReply.shortcut)) } flags |= 1 << 17 } @@ -1743,17 +1743,17 @@ public final class PendingMessageManager { if let _ = replyTodoItemId { replyFlags |= 1 << 6 } - replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: topMsgId, replyToPeerId: replyToPeerId, quoteText: quoteText, quoteEntities: quoteEntities, quoteOffset: quoteOffset, monoforumPeerId: monoforumPeerId, todoItemId: replyTodoItemId) + replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: topMsgId, replyToPeerId: replyToPeerId, quoteText: quoteText, quoteEntities: quoteEntities, quoteOffset: quoteOffset, monoforumPeerId: monoforumPeerId, todoItemId: replyTodoItemId)) } else if let replyToStoryId = replyToStoryId { if let inputPeer = transaction.getPeer(replyToStoryId.peerId).flatMap(apiInputPeer) { flags |= 1 << 0 - replyTo = .inputReplyToStory(peer: inputPeer, storyId: replyToStoryId.id) + replyTo = .inputReplyToStory(.init(peer: inputPeer, storyId: replyToStoryId.id)) } } else if let monoforumPeerId { flags |= 1 << 0 - replyTo = .inputReplyToMonoForum(monoforumPeerId: monoforumPeerId) + replyTo = .inputReplyToMonoForum(.init(monoforumPeerId: monoforumPeerId)) } - + if let attribute = message.webpagePreviewAttribute { if attribute.leadingPreview { flags |= 1 << 16 @@ -1766,9 +1766,9 @@ public final class PendingMessageManager { var quickReplyShortcut: Api.InputQuickReplyShortcut? if let quickReply { if let threadId = message.threadId { - quickReplyShortcut = .inputQuickReplyShortcutId(shortcutId: Int32(clamping: threadId)) + quickReplyShortcut = .inputQuickReplyShortcutId(.init(shortcutId: Int32(clamping: threadId))) } else { - quickReplyShortcut = .inputQuickReplyShortcut(shortcut: quickReply.shortcut) + quickReplyShortcut = .inputQuickReplyShortcut(.init(shortcut: quickReply.shortcut)) } flags |= 1 << 17 } @@ -1805,9 +1805,9 @@ public final class PendingMessageManager { var quickReplyShortcut: Api.InputQuickReplyShortcut? if let quickReply { if let threadId = message.threadId { - quickReplyShortcut = .inputQuickReplyShortcutId(shortcutId: Int32(clamping: threadId)) + quickReplyShortcut = .inputQuickReplyShortcutId(.init(shortcutId: Int32(clamping: threadId))) } else { - quickReplyShortcut = .inputQuickReplyShortcut(shortcut: quickReply.shortcut) + quickReplyShortcut = .inputQuickReplyShortcut(.init(shortcut: quickReply.shortcut)) } flags |= 1 << 17 } @@ -1822,7 +1822,7 @@ public final class PendingMessageManager { var replyTo: Api.InputReplyTo? if let monoforumPeerId { - replyTo = .inputReplyToMonoForum(monoforumPeerId: monoforumPeerId) + replyTo = .inputReplyToMonoForum(.init(monoforumPeerId: monoforumPeerId)) flags |= 1 << 22 } @@ -1891,23 +1891,23 @@ public final class PendingMessageManager { if let _ = replyTodoItemId { replyFlags |= 1 << 6 } - replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: message.threadId.flatMap(Int32.init(clamping:)), replyToPeerId: replyToPeerId, quoteText: quoteText, quoteEntities: quoteEntities, quoteOffset: quoteOffset, monoforumPeerId: monoforumPeerId, todoItemId: replyTodoItemId) + replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: message.threadId.flatMap(Int32.init(clamping:)), replyToPeerId: replyToPeerId, quoteText: quoteText, quoteEntities: quoteEntities, quoteOffset: quoteOffset, monoforumPeerId: monoforumPeerId, todoItemId: replyTodoItemId)) } else if let replyToStoryId = replyToStoryId { if let inputPeer = transaction.getPeer(replyToStoryId.peerId).flatMap(apiInputPeer) { flags |= 1 << 0 - replyTo = .inputReplyToStory(peer: inputPeer, storyId: replyToStoryId.id) + replyTo = .inputReplyToStory(.init(peer: inputPeer, storyId: replyToStoryId.id)) } } else if let monoforumPeerId { flags |= 1 << 0 - replyTo = .inputReplyToMonoForum(monoforumPeerId: monoforumPeerId) + replyTo = .inputReplyToMonoForum(.init(monoforumPeerId: monoforumPeerId)) } var quickReplyShortcut: Api.InputQuickReplyShortcut? if let quickReply { if let threadId = message.threadId { - quickReplyShortcut = .inputQuickReplyShortcutId(shortcutId: Int32(clamping: threadId)) + quickReplyShortcut = .inputQuickReplyShortcutId(.init(shortcutId: Int32(clamping: threadId))) } else { - quickReplyShortcut = .inputQuickReplyShortcut(shortcut: quickReply.shortcut) + quickReplyShortcut = .inputQuickReplyShortcut(.init(shortcut: quickReply.shortcut)) } flags |= 1 << 17 } @@ -1923,18 +1923,18 @@ public final class PendingMessageManager { if let replyMessageId = replyMessageId { let replyFlags: Int32 = 0 - replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil) + replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: replyMessageId, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil)) } else if let replyToStoryId = replyToStoryId { if let inputPeer = transaction.getPeer(replyToStoryId.peerId).flatMap(apiInputPeer) { flags |= 1 << 0 - replyTo = .inputReplyToStory(peer: inputPeer, storyId: replyToStoryId.id) + replyTo = .inputReplyToStory(.init(peer: inputPeer, storyId: replyToStoryId.id)) } else { let replyFlags: Int32 = 0 - replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: 0, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: monoforumPeerId, todoItemId: nil) + replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: 0, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: monoforumPeerId, todoItemId: nil)) } } else { let replyFlags: Int32 = 0 - replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: 0, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: monoforumPeerId, todoItemId: nil) + replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: 0, topMsgId: nil, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: monoforumPeerId, todoItemId: nil)) } sendMessageRequest = network.request(Api.functions.messages.sendScreenshotNotification(peer: inputPeer, replyTo: replyTo, randomId: uniqueId)) @@ -2042,7 +2042,7 @@ public final class PendingMessageManager { } private func applySentMessage(postbox: Postbox, stateManager: AccountStateManager, message: Message, content: PendingMessageUploadedContentAndReuploadInfo, result: Api.Updates) -> Signal { - if let channel = message.peers[message.id.peerId] as? TelegramChannel, channel.isMonoForum { + if let _ = message.peers[message.id.peerId] as? TelegramChannel { for attribute in message.attributes { if let attribute = attribute as? PaidStarsMessageAttribute { stateManager.starsContext?.add(balance: StarsAmount(value: -attribute.stars.value, nanos: (attribute.stars.value == 0 && attribute.stars.nanos != 0 ? -1 : 1) * attribute.stars.nanos)) @@ -2076,7 +2076,8 @@ public final class PendingMessageManager { if message.scheduleTime != nil && message.scheduleTime == apiMessage.timestamp { isScheduled = true } - if case let .message(_, flags2, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _) = apiMessage { + if case let .message(messageData) = apiMessage { + let flags2 = messageData.flags2 if (flags2 & (1 << 4)) != 0 { isScheduled = true } @@ -2120,7 +2121,7 @@ public final class PendingMessageManager { namespace = Namespaces.Message.QuickReplyCloud } else if let apiMessage = result.messages.first, message.scheduleTime != nil && message.scheduleTime == apiMessage.timestamp { namespace = Namespaces.Message.ScheduledCloud - } else if let apiMessage = result.messages.first, case let .message(_, flags2, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _) = apiMessage, (flags2 & (1 << 4)) != 0 { + } else if let apiMessage = result.messages.first, case let .message(messageData) = apiMessage, (messageData.flags2 & (1 << 4)) != 0 { namespace = Namespaces.Message.ScheduledCloud } } diff --git a/submodules/TelegramCore/Sources/State/PremiumRequiredToContact.swift b/submodules/TelegramCore/Sources/State/PremiumRequiredToContact.swift index f6810684..d90c362c 100644 --- a/submodules/TelegramCore/Sources/State/PremiumRequiredToContact.swift +++ b/submodules/TelegramCore/Sources/State/PremiumRequiredToContact.swift @@ -51,7 +51,8 @@ internal func _internal_updateIsPremiumRequiredToContact(account: Account, peerI flags.insert(.premiumRequired) sendPaidMessageStars = nil requirements[peerId] = .premium - case let .requirementToContactPaidMessages(starsAmount): + case let .requirementToContactPaidMessages(requirementToContactPaidMessagesData): + let starsAmount = requirementToContactPaidMessagesData.starsAmount flags.remove(.premiumRequired) sendPaidMessageStars = StarsAmount(value: starsAmount, nanos: 0) requirements[peerId] = .stars(StarsAmount(value: starsAmount, nanos: 0)) diff --git a/submodules/TelegramCore/Sources/State/ResetState.swift b/submodules/TelegramCore/Sources/State/ResetState.swift index c46e2b9f..58176e95 100644 --- a/submodules/TelegramCore/Sources/State/ResetState.swift +++ b/submodules/TelegramCore/Sources/State/ResetState.swift @@ -147,7 +147,8 @@ func _internal_resetAccountState(postbox: Postbox, network: Network, accountPeer if let currentState = transaction.getState() as? AuthorizedAccountState { switch state { - case let .state(pts, qts, date, seq, _): + case let .state(stateData): + let (pts, qts, date, seq) = (stateData.pts, stateData.qts, stateData.date, stateData.seq) transaction.setState(currentState.changedState(AuthorizedAccountState.State(pts: pts, qts: qts, date: date, seq: seq))) } } diff --git a/submodules/TelegramCore/Sources/State/SavedMessageTags.swift b/submodules/TelegramCore/Sources/State/SavedMessageTags.swift index 3d0cb4e8..e228edf2 100644 --- a/submodules/TelegramCore/Sources/State/SavedMessageTags.swift +++ b/submodules/TelegramCore/Sources/State/SavedMessageTags.swift @@ -168,13 +168,15 @@ func managedSynchronizeSavedMessageTags(postbox: Postbox, network: Network, acco switch result { case .savedReactionTagsNotModified: return .complete() - case let .savedReactionTags(tags, hash): + case let .savedReactionTags(savedReactionTagsData): + let (tags, hash) = (savedReactionTagsData.tags, savedReactionTagsData.hash) var customFileIds: [Int64] = [] var parsedTags: [SavedMessageTags.Tag] = [] for tag in tags { switch tag { - case let .savedReactionTag(_, reaction, title, count): + case let .savedReactionTag(savedReactionTagData): + let (_, reaction, title, count) = (savedReactionTagData.flags, savedReactionTagData.reaction, savedReactionTagData.title, savedReactionTagData.count) guard let reaction = MessageReaction.Reaction(apiReaction: reaction) else { continue } diff --git a/submodules/TelegramCore/Sources/State/Serialization.swift b/submodules/TelegramCore/Sources/State/Serialization.swift index 72cea0ce..e1003fb6 100644 --- a/submodules/TelegramCore/Sources/State/Serialization.swift +++ b/submodules/TelegramCore/Sources/State/Serialization.swift @@ -210,7 +210,7 @@ public class BoxedMessage: NSObject { public class Serialization: NSObject, MTSerialization { public func currentLayer() -> UInt { - return 221 + return 222 } public func parseMessage(_ data: Data!) -> Any! { @@ -227,7 +227,8 @@ public class Serialization: NSObject, MTSerialization { return { data -> MTExportedAuthorizationData? in if let exported = functionContext.2.parse(Buffer(data: data)) { switch exported { - case let .exportedAuthorization(id, bytes): + case let .exportedAuthorization(exportedAuthorizationData): + let (id, bytes) = (exportedAuthorizationData.id, exportedAuthorizationData.bytes) return MTExportedAuthorizationData(authorizationBytes: bytes.makeData(), authorizationId: id) } } else { @@ -246,11 +247,13 @@ public class Serialization: NSObject, MTSerialization { return { response -> MTDatacenterAddressListData? in if let config = parser.parse(Buffer(data: response)) { switch config { - case let .config(_, _, _, _, _, dcOptions, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + case let .config(configData): + let dcOptions = configData.dcOptions var addressDict: [NSNumber: [Any]] = [:] for option in dcOptions { switch option { - case let .dcOption(flags, id, ipAddress, port, secret): + case let .dcOption(dcOptionData): + let (flags, id, ipAddress, port, secret) = (dcOptionData.flags, dcOptionData.id, dcOptionData.ipAddress, dcOptionData.port, dcOptionData.secret) if addressDict[id as NSNumber] == nil { addressDict[id as NSNumber] = [] } diff --git a/submodules/TelegramCore/Sources/State/StickerManagement.swift b/submodules/TelegramCore/Sources/State/StickerManagement.swift index e1590223..9b060fc5 100644 --- a/submodules/TelegramCore/Sources/State/StickerManagement.swift +++ b/submodules/TelegramCore/Sources/State/StickerManagement.swift @@ -65,14 +65,16 @@ func resolveMissingStickerSets(network: Network, postbox: Postbox, stickerSets: var missingSignals: [Signal<(Int, Api.StickerSetCovered)?, NoError>] = [] for i in 0 ..< stickerSets.count { switch stickerSets[i] { - case let .stickerSetNoCovered(value), let .stickerSetCovered(value, _): + case let .stickerSetNoCovered(stickerSetNoCoveredData): + let value = stickerSetNoCoveredData.set switch value { - case let .stickerSet(_, _, id, accessHash, _, _, _, _, _, _, _, hash): + case let .stickerSet(stickerSetData): + let (id, accessHash, hash) = (stickerSetData.id, stickerSetData.accessHash, stickerSetData.hash) if ignorePacksWithHashes[id] == hash { continue } - - missingSignals.append(network.request(Api.functions.messages.getStickerSet(stickerset: .inputStickerSetID(id: id, accessHash: accessHash), hash: 0)) + + missingSignals.append(network.request(Api.functions.messages.getStickerSet(stickerset: .inputStickerSetID(.init(id: id, accessHash: accessHash)), hash: 0)) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -80,8 +82,37 @@ func resolveMissingStickerSets(network: Network, postbox: Postbox, stickerSets: |> map { result -> (Int, Api.StickerSetCovered)? in if let result = result { switch result { - case let .stickerSet(set, packs, keywords, documents): - return (i, Api.StickerSetCovered.stickerSetFullCovered(set: set, packs: packs, keywords: keywords, documents: documents)) + case let .stickerSet(stickerSetData): + let (set, packs, keywords, documents) = (stickerSetData.set, stickerSetData.packs, stickerSetData.keywords, stickerSetData.documents) + return (i, Api.StickerSetCovered.stickerSetFullCovered(.init(set: set, packs: packs, keywords: keywords, documents: documents))) + case .stickerSetNotModified: + return nil + } + } else { + return nil + } + }) + } + case let .stickerSetCovered(stickerSetCoveredData): + let value = stickerSetCoveredData.set + switch value { + case let .stickerSet(stickerSetData): + let (id, accessHash, hash) = (stickerSetData.id, stickerSetData.accessHash, stickerSetData.hash) + if ignorePacksWithHashes[id] == hash { + continue + } + + missingSignals.append(network.request(Api.functions.messages.getStickerSet(stickerset: .inputStickerSetID(.init(id: id, accessHash: accessHash)), hash: 0)) + |> map(Optional.init) + |> `catch` { _ -> Signal in + return .single(nil) + } + |> map { result -> (Int, Api.StickerSetCovered)? in + if let result = result { + switch result { + case let .stickerSet(stickerSetData): + let (set, packs, keywords, documents) = (stickerSetData.set, stickerSetData.packs, stickerSetData.keywords, stickerSetData.documents) + return (i, Api.StickerSetCovered.stickerSetFullCovered(.init(set: set, packs: packs, keywords: keywords, documents: documents))) case .stickerSetNotModified: return nil } @@ -142,7 +173,8 @@ func updatedFeaturedStickerPacks(network: Network, postbox: Postbox, category: F switch result { case .featuredStickersNotModified: return .single(.notModified) - case let .featuredStickers(flags, _, _, sets, unread): + case let .featuredStickers(featuredStickersData): + let (flags, sets, unread) = (featuredStickersData.flags, featuredStickersData.sets, featuredStickersData.unread) return resolveMissingStickerSets(network: network, postbox: postbox, stickerSets: sets, ignorePacksWithHashes: initialPackMap.filter { $0.value.topItems.count > 1 }.mapValues({ item in item.info.hash })) @@ -179,7 +211,8 @@ func updatedFeaturedStickerPacks(network: Network, postbox: Postbox, category: F switch result { case .featuredStickersNotModified: return .single(.notModified) - case let .featuredStickers(flags, _, _, sets, unread): + case let .featuredStickers(featuredStickersData): + let (flags, sets, unread) = (featuredStickersData.flags, featuredStickersData.sets, featuredStickersData.unread) return resolveMissingStickerSets(network: network, postbox: postbox, stickerSets: sets, ignorePacksWithHashes: initialPackMap.mapValues({ item in item.info.hash })) @@ -242,7 +275,8 @@ public func requestOldFeaturedStickerPacks(network: Network, postbox: Postbox, o switch result { case .featuredStickersNotModified: return [] - case let .featuredStickers(_, _, _, sets, unread): + case let .featuredStickers(featuredStickersData): + let (sets, unread) = (featuredStickersData.sets, featuredStickersData.unread) let unreadIds = Set(unread) var updatedPacks: [FeaturedStickerPackItem] = [] for set in sets { @@ -288,14 +322,16 @@ public func preloadedFeaturedStickerSet(network: Network, postbox: Postbox, id: func parsePreviewStickerSet(_ set: Api.StickerSetCovered, namespace: ItemCollectionId.Namespace) -> (StickerPackCollectionInfo, [StickerPackItem]) { switch set { - case let .stickerSetCovered(set, cover): + case let .stickerSetCovered(stickerSetCoveredData): + let (set, cover) = (stickerSetCoveredData.set, stickerSetCoveredData.cover) let info = StickerPackCollectionInfo(apiSet: set, namespace: namespace) var items: [StickerPackItem] = [] if let file = telegramMediaFileFromApiDocument(cover, altDocuments: []), let id = file.id { items.append(StickerPackItem(index: ItemCollectionItemIndex(index: 0, id: id.id), file: file, indexKeys: [])) } return (info, items) - case let .stickerSetMultiCovered(set, covers): + case let .stickerSetMultiCovered(stickerSetMultiCoveredData): + let (set, covers) = (stickerSetMultiCoveredData.set, stickerSetMultiCoveredData.covers) let info = StickerPackCollectionInfo(apiSet: set, namespace: namespace) var items: [StickerPackItem] = [] for cover in covers { @@ -304,11 +340,13 @@ func parsePreviewStickerSet(_ set: Api.StickerSetCovered, namespace: ItemCollect } } return (info, items) - case let .stickerSetFullCovered(set, packs, keywords, documents): + case let .stickerSetFullCovered(stickerSetFullCoveredData): + let (set, packs, keywords, documents) = (stickerSetFullCoveredData.set, stickerSetFullCoveredData.packs, stickerSetFullCoveredData.keywords, stickerSetFullCoveredData.documents) var indexKeysByFile: [MediaId: [MemoryBuffer]] = [:] for pack in packs { switch pack { - case let .stickerPack(text, fileIds): + case let .stickerPack(stickerPackData): + let (text, fileIds) = (stickerPackData.emoticon, stickerPackData.documents) let key = ValueBoxKey(text).toMemoryBuffer() for fileId in fileIds { let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: fileId) @@ -323,7 +361,8 @@ func parsePreviewStickerSet(_ set: Api.StickerSetCovered, namespace: ItemCollect } for keyword in keywords { switch keyword { - case let .stickerKeyword(documentId, texts): + case let .stickerKeyword(stickerKeywordData): + let (documentId, texts) = (stickerKeywordData.documentId, stickerKeywordData.keyword) for text in texts { let key = ValueBoxKey(text).toMemoryBuffer() let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: documentId) @@ -350,7 +389,8 @@ func parsePreviewStickerSet(_ set: Api.StickerSetCovered, namespace: ItemCollect } } return (info, items) - case let .stickerSetNoCovered(set): + case let .stickerSetNoCovered(stickerSetNoCoveredData): + let set = stickerSetNoCoveredData.set let info = StickerPackCollectionInfo(apiSet: set, namespace: namespace) let items: [StickerPackItem] = [] return (info, items) diff --git a/submodules/TelegramCore/Sources/State/SynchronizePeerReadState.swift b/submodules/TelegramCore/Sources/State/SynchronizePeerReadState.swift index 4e169d54..f54264f0 100644 --- a/submodules/TelegramCore/Sources/State/SynchronizePeerReadState.swift +++ b/submodules/TelegramCore/Sources/State/SynchronizePeerReadState.swift @@ -47,11 +47,14 @@ private func dialogTopMessage(network: Network, postbox: Postbox, peerId: PeerId } let apiMessages: [Api.Message] switch result { - case let .channelMessages(_, _, _, _, messages, _, _, _): + case let .channelMessages(channelMessagesData): + let messages = channelMessagesData.messages apiMessages = messages - case let .messages(messages, _, _, _): + case let .messages(messagesData): + let messages = messagesData.messages apiMessages = messages - case let .messagesSlice(_, _, _, _, _, messages, _, _, _): + case let .messagesSlice(messagesSliceData): + let messages = messagesSliceData.messages apiMessages = messages case .messagesNotModified: apiMessages = [] @@ -74,11 +77,12 @@ private func dialogReadState(network: Network, postbox: Postbox, peerId: PeerId) return inputPeer(postbox: postbox, peerId: peerId) |> mapToSignal { inputPeer -> Signal<(PeerReadState, PeerReadStateMarker)?, PeerReadStateValidationError> in - return network.request(Api.functions.messages.getPeerDialogs(peers: [.inputDialogPeer(peer: inputPeer)])) + return network.request(Api.functions.messages.getPeerDialogs(peers: [.inputDialogPeer(.init(peer: inputPeer))])) |> retryRequest |> mapToSignalPromotingError { result -> Signal<(PeerReadState, PeerReadStateMarker)?, PeerReadStateValidationError> in switch result { - case let .peerDialogs(dialogs, _, _, _, state): + case let .peerDialogs(peerDialogsData): + let (dialogs, state) = (peerDialogsData.dialogs, peerDialogsData.state) if let dialog = dialogs.filter({ $0.peerId == peerId }).first { let apiTopMessage: Int32 let apiReadInboxMaxId: Int32 @@ -87,7 +91,8 @@ private func dialogReadState(network: Network, postbox: Postbox, peerId: PeerId) let apiMarkedUnread: Bool var apiChannelPts: Int32 = 0 switch dialog { - case let .dialog(flags, _, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, _, _, _, pts, _, _, _): + case let .dialog(dialogData): + let (flags, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, pts) = (dialogData.flags, dialogData.topMessage, dialogData.readInboxMaxId, dialogData.readOutboxMaxId, dialogData.unreadCount, dialogData.pts) apiTopMessage = topMessage apiReadInboxMaxId = readInboxMaxId apiReadOutboxMaxId = readOutboxMaxId @@ -107,7 +112,8 @@ private func dialogReadState(network: Network, postbox: Postbox, peerId: PeerId) } else { let pts: Int32 switch state { - case let .state(statePts, _, _, _, _): + case let .state(stateData): + let (statePts) = (stateData.pts) pts = statePts } @@ -219,7 +225,7 @@ private func validatePeerReadState(network: Network, postbox: Postbox, stateMana } private func pushPeerReadState(network: Network, postbox: Postbox, stateManager: AccountStateManager, peerId: PeerId, readState: PeerReadState) -> Signal { - // GHOST MODE: Block read receipts (blue checkmarks) for non-secret chats + // GHOST MODE: Keep local read state but skip server read receipts. if peerId.namespace != Namespaces.Peer.SecretChat && GhostModeManager.shared.shouldHideReadReceipts { return .single(readState) } @@ -244,10 +250,11 @@ private func pushPeerReadState(network: Network, postbox: Postbox, stateManager: return inputPeer(postbox: postbox, peerId: peerId) |> mapToSignal { inputPeer -> Signal in switch inputPeer { - case let .inputPeerChannel(channelId, accessHash): + case let .inputPeerChannel(inputPeerChannelData): + let (channelId, accessHash) = (inputPeerChannelData.channelId, inputPeerChannelData.accessHash) switch readState { case let .idBased(maxIncomingReadId, _, _, _, markedUnread): - var pushSignal: Signal = network.request(Api.functions.channels.readHistory(channel: Api.InputChannel.inputChannel(channelId: channelId, accessHash: accessHash), maxId: maxIncomingReadId)) + var pushSignal: Signal = network.request(Api.functions.channels.readHistory(channel: Api.InputChannel.inputChannel(.init(channelId: channelId, accessHash: accessHash)), maxId: maxIncomingReadId)) |> `catch` { _ -> Signal in return .complete() } @@ -256,7 +263,7 @@ private func pushPeerReadState(network: Network, postbox: Postbox, stateManager: } if markedUnread { pushSignal = pushSignal - |> then(network.request(Api.functions.messages.markDialogUnread(flags: 1 << 0, parentPeer: nil, peer: .inputDialogPeer(peer: inputPeer))) + |> then(network.request(Api.functions.messages.markDialogUnread(flags: 1 << 0, parentPeer: nil, peer: .inputDialogPeer(.init(peer: inputPeer)))) |> `catch` { _ -> Signal in return .complete() } @@ -285,16 +292,17 @@ private func pushPeerReadState(network: Network, postbox: Postbox, stateManager: |> mapToSignal { result -> Signal 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)]) } } return .complete() } - + if markedUnread { pushSignal = pushSignal - |> then(network.request(Api.functions.messages.markDialogUnread(flags: 1 << 0, parentPeer: nil, peer: .inputDialogPeer(peer: inputPeer))) + |> then(network.request(Api.functions.messages.markDialogUnread(flags: 1 << 0, parentPeer: nil, peer: .inputDialogPeer(.init(peer: inputPeer)))) |> `catch` { _ -> Signal in return .complete() } diff --git a/submodules/TelegramCore/Sources/State/SynchronizeSavedStickersOperation.swift b/submodules/TelegramCore/Sources/State/SynchronizeSavedStickersOperation.swift index 0cb157c0..6d9ee488 100644 --- a/submodules/TelegramCore/Sources/State/SynchronizeSavedStickersOperation.swift +++ b/submodules/TelegramCore/Sources/State/SynchronizeSavedStickersOperation.swift @@ -75,11 +75,13 @@ public func addSavedSticker(postbox: Postbox, network: Network, file: TelegramMe switch result { case .stickerSetNotModified: break - case let .stickerSet(_, packs, _, _): + case let .stickerSet(stickerSetData): + let packs = stickerSetData.packs var stringRepresentationsByFile: [MediaId: [String]] = [:] for pack in packs { switch pack { - case let .stickerPack(text, fileIds): + case let .stickerPack(stickerPackData): + let (text, fileIds) = (stickerPackData.emoticon, stickerPackData.documents) for fileId in fileIds { let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: fileId) if stringRepresentationsByFile[mediaId] == nil { diff --git a/submodules/TelegramCore/Sources/State/UnauthorizedAccountStateManager.swift b/submodules/TelegramCore/Sources/State/UnauthorizedAccountStateManager.swift index 9a12e560..cbdd638e 100644 --- a/submodules/TelegramCore/Sources/State/UnauthorizedAccountStateManager.swift +++ b/submodules/TelegramCore/Sources/State/UnauthorizedAccountStateManager.swift @@ -34,11 +34,14 @@ private final class UnauthorizedUpdateMessageService: NSObject, MTMessageService func addUpdates(_ updates: Api.Updates) { switch updates { - case let .updates(updates, _, _, _, _): + case let .updates(updatesData): + let updates = updatesData.updates self.putNext(updates) - case let .updatesCombined(updates, _, _, _, _, _): + case let .updatesCombined(updatesCombinedData): + let updates = updatesCombinedData.updates self.putNext(updates) - case let .updateShort(update, _): + case let .updateShort(updateShortData): + let update = updateShortData.update self.putNext([update]) case .updateShortChatMessage, .updateShortMessage, .updatesTooLong, .updateShortSentMessage: break @@ -90,12 +93,14 @@ final class UnauthorizedAccountStateManager { switch update { case .updateLoginToken: updateLoginToken() - case let .updateServiceNotification(flags, _, _, message, _, _): + case let .updateServiceNotification(updateServiceNotificationData): + let (flags, message) = (updateServiceNotificationData.flags, updateServiceNotificationData.message) let popup = (flags & (1 << 0)) != 0 if popup { displayServiceNotification(message) } - case let .updateSentPhoneCode(sentCode): + case let .updateSentPhoneCode(updateSentPhoneCodeData): + let sentCode = updateSentPhoneCodeData.sentCode updateSentCode(sentCode) default: break diff --git a/submodules/TelegramCore/Sources/State/UpdateGroup.swift b/submodules/TelegramCore/Sources/State/UpdateGroup.swift index 6efb50e3..0b04536e 100644 --- a/submodules/TelegramCore/Sources/State/UpdateGroup.swift +++ b/submodules/TelegramCore/Sources/State/UpdateGroup.swift @@ -60,27 +60,36 @@ enum UpdateGroup { func apiUpdatePtsRange(_ update: Api.Update) -> (Int32, Int32)? { switch update { - case let .updateDeleteMessages(_, pts, ptsCount): + case let .updateDeleteMessages(updateDeleteMessagesData): + let (pts, ptsCount) = (updateDeleteMessagesData.pts, updateDeleteMessagesData.ptsCount) return (pts, ptsCount) - case let .updateNewMessage(_, pts, ptsCount): + case let .updateNewMessage(updateNewMessageData): + let (pts, ptsCount) = (updateNewMessageData.pts, updateNewMessageData.ptsCount) return (pts, ptsCount) - case let .updateReadHistoryInbox(_, _, _, _, _, _, pts, ptsCount): + case let .updateReadHistoryInbox(updateReadHistoryInboxData): + let (pts, ptsCount) = (updateReadHistoryInboxData.pts, updateReadHistoryInboxData.ptsCount) return (pts, ptsCount) - case let .updateReadHistoryOutbox(_, _, pts, ptsCount): + case let .updateReadHistoryOutbox(updateReadHistoryOutboxData): + let (pts, ptsCount) = (updateReadHistoryOutboxData.pts, updateReadHistoryOutboxData.ptsCount) return (pts, ptsCount) - case let .updateEditMessage(_, pts, ptsCount): + case let .updateEditMessage(updateEditMessageData): + let (pts, ptsCount) = (updateEditMessageData.pts, updateEditMessageData.ptsCount) return (pts, ptsCount) - case let .updateReadMessagesContents(_, _, pts, ptsCount, _): + case let .updateReadMessagesContents(updateReadMessagesContentsData): + let (pts, ptsCount) = (updateReadMessagesContentsData.pts, updateReadMessagesContentsData.ptsCount) return (pts, ptsCount) - case let .updateWebPage(_, pts, ptsCount): + case let .updateWebPage(updateWebPageData): + let (pts, ptsCount) = (updateWebPageData.pts, updateWebPageData.ptsCount) return (pts, ptsCount) - case let .updateFolderPeers(_, pts, ptsCount): + case let .updateFolderPeers(updateFolderPeersData): + let (pts, ptsCount) = (updateFolderPeersData.pts, updateFolderPeersData.ptsCount) if ptsCount != 0 { return (pts, ptsCount) } else { return nil } - case let .updatePinnedMessages(_, _, _, pts, ptsCount): + case let .updatePinnedMessages(updatePinnedMessagesData): + let (pts, ptsCount) = (updatePinnedMessagesData.pts, updatePinnedMessagesData.ptsCount) return (pts, ptsCount) default: return nil @@ -89,7 +98,8 @@ func apiUpdatePtsRange(_ update: Api.Update) -> (Int32, Int32)? { func apiUpdateQtsRange(_ update: Api.Update) -> (Int32, Int32)? { switch update { - case let .updateNewEncryptedMessage(_, qts): + case let .updateNewEncryptedMessage(updateNewEncryptedMessageData): + let qts = updateNewEncryptedMessageData.qts return (qts, 1) case _: return nil diff --git a/submodules/TelegramCore/Sources/State/UpdateMessageService.swift b/submodules/TelegramCore/Sources/State/UpdateMessageService.swift index 655b2380..afa23310 100644 --- a/submodules/TelegramCore/Sources/State/UpdateMessageService.swift +++ b/submodules/TelegramCore/Sources/State/UpdateMessageService.swift @@ -42,47 +42,53 @@ class UpdateMessageService: NSObject, MTMessageService { func addUpdates(_ updates: Api.Updates) { switch updates { - case let .updates(updates, users, chats, date, seq): + case let .updates(updatesData): + let (updates, users, chats, date, seq) = (updatesData.updates, updatesData.users, updatesData.chats, updatesData.date, updatesData.seq) let groups = groupUpdates(updates, users: users, chats: chats, date: date, seqRange: seq == 0 ? nil : (seq, 1)) if groups.count != 0 { self.putNext(groups) } - case let .updatesCombined(updates, users, chats, date, seqStart, seq): + case let .updatesCombined(updatesCombinedData): + let (updates, users, chats, date, seqStart, seq) = (updatesCombinedData.updates, updatesCombinedData.users, updatesCombinedData.chats, updatesCombinedData.date, updatesCombinedData.seqStart, updatesCombinedData.seq) let groups = groupUpdates(updates, users: users, chats: chats, date: date, seqRange: seq == 0 ? nil : (seq, seq - seqStart)) if groups.count != 0 { self.putNext(groups) } - case let .updateShort(update, date): + case let .updateShort(updateShortData): + let (update, date) = (updateShortData.update, updateShortData.date) let groups = groupUpdates([update], users: [], chats: [], date: date, seqRange: nil) if groups.count != 0 { self.putNext(groups) } - case let .updateShortChatMessage(flags, id, fromId, chatId, message, pts, ptsCount, date, fwdFrom, viaBotId, replyHeader, entities, ttlPeriod): - let generatedMessage = Api.Message.message(flags: flags, flags2: 0, id: id, fromId: .peerUser(userId: fromId), fromBoostsApplied: nil, peerId: Api.Peer.peerChat(chatId: chatId), savedPeerId: nil, fwdFrom: fwdFrom, viaBotId: viaBotId, viaBusinessBotId: nil, replyTo: replyHeader, date: date, message: message, media: Api.MessageMedia.messageMediaEmpty, replyMarkup: nil, entities: entities, views: nil, forwards: nil, replies: nil, editDate: nil, postAuthor: nil, groupedId: nil, reactions: nil, restrictionReason: nil, ttlPeriod: ttlPeriod, quickReplyShortcutId: nil, effect: nil, factcheck: nil, reportDeliveryUntilDate: nil, paidMessageStars: nil, suggestedPost: nil, scheduleRepeatPeriod: nil, summaryFromLanguage: nil) - let update = Api.Update.updateNewMessage(message: generatedMessage, pts: pts, ptsCount: ptsCount) + case let .updateShortChatMessage(updateShortChatMessageData): + let (flags, id, fromId, chatId, message, pts, ptsCount, date, fwdFrom, viaBotId, replyHeader, entities, ttlPeriod) = (updateShortChatMessageData.flags, updateShortChatMessageData.id, updateShortChatMessageData.fromId, updateShortChatMessageData.chatId, updateShortChatMessageData.message, updateShortChatMessageData.pts, updateShortChatMessageData.ptsCount, updateShortChatMessageData.date, updateShortChatMessageData.fwdFrom, updateShortChatMessageData.viaBotId, updateShortChatMessageData.replyTo, updateShortChatMessageData.entities, updateShortChatMessageData.ttlPeriod) + let generatedMessage = Api.Message.message(.init(flags: flags, flags2: 0, id: id, fromId: .peerUser(.init(userId: fromId)), fromBoostsApplied: nil, peerId: Api.Peer.peerChat(.init(chatId: chatId)), savedPeerId: nil, fwdFrom: fwdFrom, viaBotId: viaBotId, viaBusinessBotId: nil, replyTo: replyHeader, date: date, message: message, media: Api.MessageMedia.messageMediaEmpty, replyMarkup: nil, entities: entities, views: nil, forwards: nil, replies: nil, editDate: nil, postAuthor: nil, groupedId: nil, reactions: nil, restrictionReason: nil, ttlPeriod: ttlPeriod, quickReplyShortcutId: nil, effect: nil, factcheck: nil, reportDeliveryUntilDate: nil, paidMessageStars: nil, suggestedPost: nil, scheduleRepeatPeriod: nil, summaryFromLanguage: nil)) + let update = Api.Update.updateNewMessage(.init(message: generatedMessage, pts: pts, ptsCount: ptsCount)) let groups = groupUpdates([update], users: [], chats: [], date: date, seqRange: nil) if groups.count != 0 { self.putNext(groups) } - case let .updateShortMessage(flags, id, userId, message, pts, ptsCount, date, fwdFrom, viaBotId, replyHeader, entities, ttlPeriod): + case let .updateShortMessage(updateShortMessageData): + let (flags, id, userId, message, pts, ptsCount, date, fwdFrom, viaBotId, replyHeader, entities, ttlPeriod) = (updateShortMessageData.flags, updateShortMessageData.id, updateShortMessageData.userId, updateShortMessageData.message, updateShortMessageData.pts, updateShortMessageData.ptsCount, updateShortMessageData.date, updateShortMessageData.fwdFrom, updateShortMessageData.viaBotId, updateShortMessageData.replyTo, updateShortMessageData.entities, updateShortMessageData.ttlPeriod) let generatedFromId: Api.Peer if (Int(flags) & 1 << 1) != 0 { - generatedFromId = Api.Peer.peerUser(userId: self.peerId.id._internalGetInt64Value()) + generatedFromId = Api.Peer.peerUser(.init(userId: self.peerId.id._internalGetInt64Value())) } else { - generatedFromId = Api.Peer.peerUser(userId: userId) + generatedFromId = Api.Peer.peerUser(.init(userId: userId)) } - - let generatedPeerId = Api.Peer.peerUser(userId: userId) - - let generatedMessage = Api.Message.message(flags: flags, flags2: 0, id: id, fromId: generatedFromId, fromBoostsApplied: nil, peerId: generatedPeerId, savedPeerId: nil, fwdFrom: fwdFrom, viaBotId: viaBotId, viaBusinessBotId: nil, replyTo: replyHeader, date: date, message: message, media: Api.MessageMedia.messageMediaEmpty, replyMarkup: nil, entities: entities, views: nil, forwards: nil, replies: nil, editDate: nil, postAuthor: nil, groupedId: nil, reactions: nil, restrictionReason: nil, ttlPeriod: ttlPeriod, quickReplyShortcutId: nil, effect: nil, factcheck: nil, reportDeliveryUntilDate: nil, paidMessageStars: nil, suggestedPost: nil, scheduleRepeatPeriod: nil, summaryFromLanguage: nil) - let update = Api.Update.updateNewMessage(message: generatedMessage, pts: pts, ptsCount: ptsCount) + + let generatedPeerId = Api.Peer.peerUser(.init(userId: userId)) + + let generatedMessage = Api.Message.message(.init(flags: flags, flags2: 0, id: id, fromId: generatedFromId, fromBoostsApplied: nil, peerId: generatedPeerId, savedPeerId: nil, fwdFrom: fwdFrom, viaBotId: viaBotId, viaBusinessBotId: nil, replyTo: replyHeader, date: date, message: message, media: Api.MessageMedia.messageMediaEmpty, replyMarkup: nil, entities: entities, views: nil, forwards: nil, replies: nil, editDate: nil, postAuthor: nil, groupedId: nil, reactions: nil, restrictionReason: nil, ttlPeriod: ttlPeriod, quickReplyShortcutId: nil, effect: nil, factcheck: nil, reportDeliveryUntilDate: nil, paidMessageStars: nil, suggestedPost: nil, scheduleRepeatPeriod: nil, summaryFromLanguage: nil)) + let update = Api.Update.updateNewMessage(.init(message: generatedMessage, pts: pts, ptsCount: ptsCount)) let groups = groupUpdates([update], users: [], chats: [], date: date, seqRange: nil) if groups.count != 0 { self.putNext(groups) } case .updatesTooLong: self.pipe.putNext([.reset]) - case let .updateShortSentMessage(_, _, pts, ptsCount, _, _, _, _): + case let .updateShortSentMessage(updateShortSentMessageData): + let (pts, ptsCount) = (updateShortSentMessageData.pts, updateShortSentMessageData.ptsCount) self.pipe.putNext([.updatePts(pts: pts, ptsCount: ptsCount)]) } } diff --git a/submodules/TelegramCore/Sources/State/UpdatesApiUtils.swift b/submodules/TelegramCore/Sources/State/UpdatesApiUtils.swift index 77f07157..555931a7 100644 --- a/submodules/TelegramCore/Sources/State/UpdatesApiUtils.swift +++ b/submodules/TelegramCore/Sources/State/UpdatesApiUtils.swift @@ -5,10 +5,12 @@ import TelegramApi private func collectPreCachedResources(for photo: Api.Photo) -> [(MediaResource, Data)]? { switch photo { - case let .photo(_, id, accessHash, fileReference, _, sizes, _, dcId): + case let .photo(photoData): + let (id, accessHash, fileReference, sizes, dcId) = (photoData.id, photoData.accessHash, photoData.fileReference, photoData.sizes, photoData.dcId) for size in sizes { switch size { - case let .photoCachedSize(type, _, _, bytes): + case let .photoCachedSize(photoCachedSizeData): + let (type, bytes) = (photoCachedSizeData.type, photoCachedSizeData.bytes) let resource = CloudPhotoSizeMediaResource(datacenterId: dcId, photoId: id, accessHash: accessHash, sizeSpec: type, size: nil, fileReference: fileReference.makeData()) let data = bytes.makeData() return [(resource, data)] @@ -24,11 +26,13 @@ private func collectPreCachedResources(for photo: Api.Photo) -> [(MediaResource, private func collectPreCachedResources(for document: Api.Document) -> [(MediaResource, Data)]? { switch document { - case let .document(_, id, accessHash, fileReference, _, _, _, thumbs, _, dcId, _): + case let .document(documentData): + let (id, accessHash, fileReference, thumbs, dcId) = (documentData.id, documentData.accessHash, documentData.fileReference, documentData.thumbs, documentData.dcId) if let thumbs = thumbs { for thumb in thumbs { switch thumb { - case let .photoCachedSize(type, _, _, bytes): + case let .photoCachedSize(photoCachedSizeData): + let (type, bytes) = (photoCachedSizeData.type, photoCachedSizeData.bytes) let resource = CloudDocumentSizeMediaResource(datacenterId: dcId, documentId: id, accessHash: accessHash, sizeSpec: type, fileReference: fileReference.makeData()) let data = bytes.makeData() return [(resource, data)] @@ -46,22 +50,25 @@ private func collectPreCachedResources(for document: Api.Document) -> [(MediaRes extension Api.MessageMedia { var preCachedResources: [(MediaResource, Data)]? { switch self { - case let .messageMediaPhoto(_, photo, _): + case let .messageMediaPhoto(messageMediaPhotoData): + let photo = messageMediaPhotoData.photo if let photo = photo { return collectPreCachedResources(for: photo) } else { return nil } - case let .messageMediaDocument(_, document, _, _, _, _): + case let .messageMediaDocument(messageMediaDocumentData): + let document = messageMediaDocumentData.document if let document = document { return collectPreCachedResources(for: document) } return nil - case let .messageMediaWebPage(flags, webPage): - let _ = flags + case let .messageMediaWebPage(messageMediaWebPageData): + let webpage = messageMediaWebPageData.webpage var result: [(MediaResource, Data)]? - switch webPage { - case let .webPage(_, _, _, _, _, _, _, _, _, photo, _, _, _, _, _, _, document, _, _): + switch webpage { + case let .webPage(webPageData): + let (photo, document) = (webPageData.photo, webPageData.document) if let photo = photo { if let photoResult = collectPreCachedResources(for: photo) { if result == nil { @@ -89,9 +96,10 @@ extension Api.MessageMedia { var preCachedStories: [StoryId: Api.StoryItem]? { switch self { - case let .messageMediaStory(_, peerId, id, story): + case let .messageMediaStory(messageMediaStoryData): + let (peer, id, story) = (messageMediaStoryData.peer, messageMediaStoryData.id, messageMediaStoryData.story) if let story = story { - return [StoryId(peerId: peerId.peerId, id: id): story] + return [StoryId(peerId: peer.peerId, id: id): story] } else { return nil } @@ -104,31 +112,37 @@ extension Api.MessageMedia { extension Api.Message { var rawId: Int32 { switch self { - case let .message(_, _, id, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + case let .message(messageData): + let id = messageData.id return id - case let .messageEmpty(_, id, _): + case let .messageEmpty(messageEmptyData): + let id = messageEmptyData.id return id - case let .messageService(_, id, _, _, _, _, _, _, _, _): + case let .messageService(messageServiceData): + let id = messageServiceData.id return id } } func id(namespace: MessageId.Namespace = Namespaces.Message.Cloud) -> MessageId? { switch self { - case let .message(_, flags2, id, _, _, messagePeerId, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + case let .message(messageData): + let (flags2, id, messagePeerId) = (messageData.flags2, messageData.id, messageData.peerId) var namespace = namespace if (flags2 & (1 << 4)) != 0 { namespace = Namespaces.Message.ScheduledCloud } let peerId: PeerId = messagePeerId.peerId return MessageId(peerId: peerId, namespace: namespace, id: id) - case let .messageEmpty(_, id, peerId): + case let .messageEmpty(messageEmptyData): + let (id, peerId) = (messageEmptyData.id, messageEmptyData.peerId) if let peerId = peerId { return MessageId(peerId: peerId.peerId, namespace: Namespaces.Message.Cloud, id: id) } else { return nil } - case let .messageService(_, id, _, chatPeerId, _, _, _, _, _, _): + case let .messageService(messageServiceData): + let (id, chatPeerId) = (messageServiceData.id, messageServiceData.peerId) let peerId: PeerId = chatPeerId.peerId return MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: id) } @@ -136,12 +150,15 @@ extension Api.Message { var peerId: PeerId? { switch self { - case let .message(_, _, _, _, _, messagePeerId, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + case let .message(messageData): + let messagePeerId = messageData.peerId let peerId: PeerId = messagePeerId.peerId return peerId - case let .messageEmpty(_, _, peerId): + case let .messageEmpty(messageEmptyData): + let peerId = messageEmptyData.peerId return peerId?.peerId - case let .messageService(_, _, _, chatPeerId, _, _, _, _, _, _): + case let .messageService(messageServiceData): + let chatPeerId = messageServiceData.peerId let peerId: PeerId = chatPeerId.peerId return peerId } @@ -149,9 +166,11 @@ extension Api.Message { var timestamp: Int32? { switch self { - case let .message(_, _, _, _, _, _, _, _, _, _, _, date, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + case let .message(messageData): + let date = messageData.date return date - case let .messageService(_, _, _, _, _, _, date, _, _, _): + case let .messageService(messageServiceData): + let date = messageServiceData.date return date case .messageEmpty: return nil @@ -160,16 +179,18 @@ extension Api.Message { var preCachedResources: [(MediaResource, Data)]? { switch self { - case let .message(_, _, _, _, _, _, _, _, _, _, _, _, _, media, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + case let .message(messageData): + let media = messageData.media return media?.preCachedResources default: return nil } } - + var preCachedStories: [StoryId: Api.StoryItem]? { switch self { - case let .message(_, _, _, _, _, _, _, _, _, _, _, _, _, media, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + case let .message(messageData): + let media = messageData.media return media?.preCachedStories default: return nil @@ -180,15 +201,20 @@ extension Api.Message { extension Api.Chat { var peerId: PeerId { switch self { - case let .chat(_, id, _, _, _, _, _, _, _, _): + case let .chat(chatData): + let id = chatData.id return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(id)) - case let .chatEmpty(id): + case let .chatEmpty(chatEmptyData): + let id = chatEmptyData.id return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(id)) - case let .chatForbidden(id, _): + case let .chatForbidden(chatForbiddenData): + let id = chatForbiddenData.id return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(id)) - case let .channel(_, _, id, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + case let .channel(channelData): + let id = channelData.id return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(id)) - case let .channelForbidden(_, id, _, _, _): + case let .channelForbidden(channelForbiddenData): + let id = channelForbiddenData.id return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(id)) } } @@ -197,9 +223,11 @@ extension Api.Chat { extension Api.User { var peerId: PeerId { switch self { - case let .user(_, _, id, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + case let .user(userData): + let id = userData.id return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(id)) - case let .userEmpty(id): + case let .userEmpty(userEmptyData): + let id = userEmptyData.id return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(id)) } } @@ -208,11 +236,14 @@ extension Api.User { extension Api.Peer { var peerId: PeerId { switch self { - case let .peerChannel(channelId): + case let .peerChannel(peerChannelData): + let channelId = peerChannelData.channelId return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId)) - case let .peerChat(chatId): + case let .peerChat(peerChatData): + let chatId = peerChatData.chatId return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId)) - case let .peerUser(userId): + case let .peerUser(peerUserData): + let userId = peerUserData.userId return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)) } } @@ -221,8 +252,8 @@ extension Api.Peer { extension Api.Dialog { var peerId: PeerId? { switch self { - case let .dialog(_, peer, _, _, _, _, _, _, _, _, _, _, _): - return peer.peerId + case let .dialog(dialogData): + return dialogData.peer.peerId case .dialogFolder: return nil } @@ -232,11 +263,14 @@ extension Api.Dialog { extension Api.Update { var rawMessageId: Int32? { switch self { - case let .updateMessageID(id, _): + case let .updateMessageID(updateMessageIDData): + let id = updateMessageIDData.id return id - case let .updateNewMessage(message, _, _): + case let .updateNewMessage(updateNewMessageData): + let message = updateNewMessageData.message return message.rawId - case let .updateNewChannelMessage(message, _, _): + case let .updateNewChannelMessage(updateNewChannelMessageData): + let message = updateNewChannelMessageData.message return message.rawId default: return nil @@ -245,7 +279,8 @@ extension Api.Update { var updatedRawMessageId: (Int64, Int32)? { switch self { - case let .updateMessageID(id, randomId): + case let .updateMessageID(updateMessageIDData): + let (id, randomId) = (updateMessageIDData.id, updateMessageIDData.randomId) return (randomId, id) default: return nil @@ -254,9 +289,11 @@ extension Api.Update { var messageId: MessageId? { switch self { - case let .updateNewMessage(message, _, _): + case let .updateNewMessage(updateNewMessageData): + let message = updateNewMessageData.message return message.id() - case let .updateNewChannelMessage(message, _, _): + case let .updateNewChannelMessage(updateNewChannelMessageData): + let message = updateNewChannelMessageData.message return message.id() default: return nil @@ -265,17 +302,23 @@ extension Api.Update { var message: Api.Message? { switch self { - case let .updateNewMessage(message, _, _): + case let .updateNewMessage(updateNewMessageData): + let message = updateNewMessageData.message return message - case let .updateNewChannelMessage(message, _, _): + case let .updateNewChannelMessage(updateNewChannelMessageData): + let message = updateNewChannelMessageData.message return message - case let .updateEditMessage(message, _, _): + case let .updateEditMessage(updateEditMessageData): + let message = updateEditMessageData.message return message - case let .updateEditChannelMessage(message, _, _): + case let .updateEditChannelMessage(updateEditChannelMessageData): + let message = updateEditChannelMessageData.message return message - case let .updateNewScheduledMessage(message): + case let .updateNewScheduledMessage(updateNewScheduledMessageData): + let message = updateNewScheduledMessageData.message return message - case let .updateQuickReplyMessage(message): + case let .updateQuickReplyMessage(updateQuickReplyMessageData): + let message = updateQuickReplyMessageData.message return message default: return nil @@ -284,63 +327,88 @@ extension Api.Update { var peerIds: [PeerId] { switch self { - case let .updateChannel(channelId): + case let .updateChannel(updateChannelData): + let channelId = updateChannelData.channelId return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))] - case let .updateChat(chatId): + case let .updateChat(updateChatData): + let chatId = updateChatData.chatId return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId))] - case let .updateChannelTooLong(_, channelId, _): + case let .updateChannelTooLong(updateChannelTooLongData): + let channelId = updateChannelTooLongData.channelId return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))] - case let .updateChatParticipantAdd(chatId, userId, inviterId, _, _): + case let .updateChatParticipantAdd(updateChatParticipantAddData): + let (chatId, userId, inviterId) = (updateChatParticipantAddData.chatId, updateChatParticipantAddData.userId, updateChatParticipantAddData.inviterId) return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId)), PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(inviterId))] - case let .updateChatParticipantAdmin(chatId, userId, _, _): + case let .updateChatParticipantAdmin(updateChatParticipantAdminData): + let (chatId, userId) = (updateChatParticipantAdminData.chatId, updateChatParticipantAdminData.userId) return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId)), PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))] - case let .updateChatParticipantDelete(chatId, userId, _): + case let .updateChatParticipantDelete(updateChatParticipantDeleteData): + let (chatId, userId) = (updateChatParticipantDeleteData.chatId, updateChatParticipantDeleteData.userId) return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId)), PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))] - case let .updateChatParticipants(participants): + case let .updateChatParticipants(updateChatParticipantsData): + let participants = updateChatParticipantsData.participants switch participants { - case let .chatParticipants(chatId, _, _): + case let .chatParticipants(chatParticipantsData): + let chatId = chatParticipantsData.chatId return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId))] - case let .chatParticipantsForbidden(_, chatId, _): + case let .chatParticipantsForbidden(chatParticipantsForbiddenData): + let chatId = chatParticipantsForbiddenData.chatId return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId))] } - case let .updateDeleteChannelMessages(channelId, _, _, _): + case let .updateDeleteChannelMessages(updateDeleteChannelMessagesData): + let channelId = updateDeleteChannelMessagesData.channelId return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))] - case let .updatePinnedChannelMessages(_, channelId, _, _, _): + case let .updatePinnedChannelMessages(updatePinnedChannelMessagesData): + let channelId = updatePinnedChannelMessagesData.channelId return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))] - case let .updateNewChannelMessage(message, _, _): + case let .updateNewChannelMessage(updateNewChannelMessageData): + let message = updateNewChannelMessageData.message return apiMessagePeerIds(message) - case let .updateEditChannelMessage(message, _, _): + case let .updateEditChannelMessage(updateEditChannelMessageData): + let message = updateEditChannelMessageData.message return apiMessagePeerIds(message) - case let .updateChannelWebPage(channelId, _, _, _): + case let .updateChannelWebPage(updateChannelWebPageData): + let channelId = updateChannelWebPageData.channelId return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))] - case let .updateNewMessage(message, _, _): + case let .updateNewMessage(updateNewMessageData): + let message = updateNewMessageData.message return apiMessagePeerIds(message) - case let .updateEditMessage(message, _, _): + case let .updateEditMessage(updateEditMessageData): + let message = updateEditMessageData.message return apiMessagePeerIds(message) - case let .updateReadChannelInbox(_, _, channelId, _, _, _): + case let .updateReadChannelInbox(updateReadChannelInboxData): + let channelId = updateReadChannelInboxData.channelId return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))] - case let .updateNotifySettings(peer, _): + case let .updateNotifySettings(updateNotifySettingsData): + let peer = updateNotifySettingsData.peer switch peer { - case let .notifyPeer(peer): + case let .notifyPeer(notifyPeerData): + let peer = notifyPeerData.peer return [peer.peerId] default: return [] } - case let .updateUserName(userId, _, _, _): + case let .updateUserName(updateUserNameData): + let userId = updateUserNameData.userId return [PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))] - case let .updateUserPhone(userId, _): + case let .updateUserPhone(updateUserPhoneData): + let userId = updateUserPhoneData.userId return [PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))] - case let .updateServiceNotification(_, inboxDate, _, _, _, _): + case let .updateServiceNotification(updateServiceNotificationData): + let inboxDate = updateServiceNotificationData.inboxDate if let _ = inboxDate { return [PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(777000))] } else { return [] } - case let .updateDraftMessage(_, peer, _, _, _): + case let .updateDraftMessage(updateDraftMessageData): + let peer = updateDraftMessageData.peer return [peer.peerId] - case let .updateNewScheduledMessage(message): + case let .updateNewScheduledMessage(updateNewScheduledMessageData): + let message = updateNewScheduledMessageData.message return apiMessagePeerIds(message) - case let .updateQuickReplyMessage(message): + case let .updateQuickReplyMessage(updateQuickReplyMessageData): + let message = updateQuickReplyMessageData.message return apiMessagePeerIds(message) default: return [] @@ -349,15 +417,20 @@ extension Api.Update { var associatedMessageIds: (replyIds: ReferencedReplyMessageIds, generalIds: [MessageId])? { switch self { - case let .updateNewMessage(message, _, _): + case let .updateNewMessage(updateNewMessageData): + let message = updateNewMessageData.message return apiMessageAssociatedMessageIds(message) - case let .updateNewChannelMessage(message, _, _): + case let .updateNewChannelMessage(updateNewChannelMessageData): + let message = updateNewChannelMessageData.message return apiMessageAssociatedMessageIds(message) - case let .updateEditChannelMessage(message, _, _): + case let .updateEditChannelMessage(updateEditChannelMessageData): + let message = updateEditChannelMessageData.message return apiMessageAssociatedMessageIds(message) - case let .updateNewScheduledMessage(message): + case let .updateNewScheduledMessage(updateNewScheduledMessageData): + let message = updateNewScheduledMessageData.message return apiMessageAssociatedMessageIds(message) - case let .updateQuickReplyMessage(message): + case let .updateQuickReplyMessage(updateQuickReplyMessageData): + let message = updateQuickReplyMessageData.message return apiMessageAssociatedMessageIds(message) default: break @@ -367,9 +440,11 @@ extension Api.Update { var channelPts: Int32? { switch self { - case let .updateNewChannelMessage(_, pts, _): + case let .updateNewChannelMessage(updateNewChannelMessageData): + let pts = updateNewChannelMessageData.pts return pts - case let .updateEditChannelMessage(_, pts, _): + case let .updateEditChannelMessage(updateEditChannelMessageData): + let pts = updateEditChannelMessageData.pts return pts default: return nil @@ -380,11 +455,14 @@ extension Api.Update { extension Api.Updates { var allUpdates: [Api.Update] { switch self { - case let .updates(updates, _, _, _, _): + case let .updates(updatesData): + let updates = updatesData.updates return updates - case let .updatesCombined(updates, _, _, _, _, _): + case let .updatesCombined(updatesCombinedData): + let updates = updatesCombinedData.updates return updates - case let .updateShort(update, _): + case let .updateShort(updateShortData): + let update = updateShortData.update return [update] default: return [] @@ -395,7 +473,8 @@ extension Api.Updates { extension Api.Updates { var rawMessageIds: [Int32] { switch self { - case let .updates(updates, _, _, _, _): + case let .updates(updatesData): + let updates = updatesData.updates var result: [Int32] = [] for update in updates { if let id = update.rawMessageId { @@ -403,7 +482,8 @@ extension Api.Updates { } } return result - case let .updatesCombined(updates, _, _, _, _, _): + case let .updatesCombined(updatesCombinedData): + let updates = updatesCombinedData.updates var result: [Int32] = [] for update in updates { if let id = update.rawMessageId { @@ -411,26 +491,31 @@ extension Api.Updates { } } return result - case let .updateShort(update, _): + case let .updateShort(updateShortData): + let update = updateShortData.update if let id = update.rawMessageId { return [id] } else { return [] } - case let .updateShortSentMessage(_, id, _, _, _, _, _, _): + case let .updateShortSentMessage(updateShortSentMessageData): + let id = updateShortSentMessageData.id return [id] case .updatesTooLong: return [] - case let .updateShortMessage(_, id, _, _, _, _, _, _, _, _, _, _): + case let .updateShortMessage(updateShortMessageData): + let id = updateShortMessageData.id return [id] - case let .updateShortChatMessage(_, id, _, _, _, _, _, _, _, _, _, _, _): + case let .updateShortChatMessage(updateShortChatMessageData): + let id = updateShortChatMessageData.id return [id] } } var messageIds: [MessageId] { switch self { - case let .updates(updates, _, _, _, _): + case let .updates(updatesData): + let updates = updatesData.updates var result: [MessageId] = [] for update in updates { if let id = update.messageId { @@ -438,7 +523,8 @@ extension Api.Updates { } } return result - case let .updatesCombined(updates, _, _, _, _, _): + case let .updatesCombined(updatesCombinedData): + let updates = updatesCombinedData.updates var result: [MessageId] = [] for update in updates { if let id = update.messageId { @@ -446,7 +532,8 @@ extension Api.Updates { } } return result - case let .updateShort(update, _): + case let .updateShort(updateShortData): + let update = updateShortData.update if let id = update.messageId { return [id] } else { @@ -456,16 +543,19 @@ extension Api.Updates { return [] case .updatesTooLong: return [] - case let .updateShortMessage(_, id, userId, _, _, _, _, _, _, _, _, _): + case let .updateShortMessage(updateShortMessageData): + let (id, userId) = (updateShortMessageData.id, updateShortMessageData.userId) return [MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), namespace: Namespaces.Message.Cloud, id: id)] - case let .updateShortChatMessage(_, id, _, chatId, _, _, _, _, _, _, _, _, _): + case let .updateShortChatMessage(updateShortChatMessageData): + let (id, chatId) = (updateShortChatMessageData.id, updateShortChatMessageData.chatId) return [MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId)), namespace: Namespaces.Message.Cloud, id: id)] } } var updatedRawMessageIds: [Int64: Int32] { switch self { - case let .updates(updates, _, _, _, _): + case let .updates(updatesData): + let updates = updatesData.updates var result: [Int64: Int32] = [:] for update in updates { if let (randomId, id) = update.updatedRawMessageId { @@ -473,7 +563,8 @@ extension Api.Updates { } } return result - case let .updatesCombined(updates, _, _, _, _, _): + case let .updatesCombined(updatesCombinedData): + let updates = updatesCombinedData.updates var result: [Int64: Int32] = [:] for update in updates { if let (randomId, id) = update.updatedRawMessageId { @@ -481,7 +572,8 @@ extension Api.Updates { } } return result - case let .updateShort(update, _): + case let .updateShort(updateShortData): + let update = updateShortData.update if let (randomId, id) = update.updatedRawMessageId { return [randomId: id] } else { @@ -502,18 +594,21 @@ extension Api.Updates { extension Api.Updates { var users: [Api.User] { switch self { - case let .updates(_, users, _, _, _): + case let .updates(updatesData): + let users = updatesData.users return users - case let .updatesCombined(_, users, _, _, _, _): + case let .updatesCombined(updatesCombinedData): + let users = updatesCombinedData.users return users default: return [] } } - + var messages: [Api.Message] { switch self { - case let .updates(updates, _, _, _, _): + case let .updates(updatesData): + let updates = updatesData.updates var result: [Api.Message] = [] for update in updates { if let message = update.message { @@ -521,7 +616,8 @@ extension Api.Updates { } } return result - case let .updatesCombined(updates, _, _, _, _, _): + case let .updatesCombined(updatesCombinedData): + let updates = updatesCombinedData.updates var result: [Api.Message] = [] for update in updates { if let message = update.message { @@ -529,7 +625,8 @@ extension Api.Updates { } } return result - case let .updateShort(update, _): + case let .updateShort(updateShortData): + let update = updateShortData.update if let message = update.message { return [message] } else { @@ -539,10 +636,11 @@ extension Api.Updates { return [] } } - + var channelPts: Int32? { switch self { - case let .updates(updates, _, _, _, _): + case let .updates(updatesData): + let updates = updatesData.updates var result: Int32? for update in updates { if let channelPts = update.channelPts { @@ -552,7 +650,8 @@ extension Api.Updates { } } return result - case let .updatesCombined(updates, _, _, _, _, _): + case let .updatesCombined(updatesCombinedData): + let updates = updatesCombinedData.updates var result: Int32? for update in updates { if let channelPts = update.channelPts { @@ -562,7 +661,8 @@ extension Api.Updates { } } return result - case let .updateShort(update, _): + case let .updateShort(updateShortData): + let update = updateShortData.update if let channelPts = update.channelPts { return channelPts } else { @@ -577,13 +677,15 @@ extension Api.Updates { extension Api.Updates { var chats: [Api.Chat] { switch self { - case let .updates(_, _, chats, _, _): + case let .updates(updatesData): + let chats = updatesData.chats var result: [Api.Chat] = [] for chat in chats { result.append(chat) } return result - case let .updatesCombined(_, _, chats, _, _, _): + case let .updatesCombined(updatesCombinedData): + let chats = updatesCombinedData.chats var result: [Api.Chat] = [] for chat in chats { result.append(chat) @@ -598,15 +700,20 @@ extension Api.Updates { extension Api.EncryptedChat { var peerId: PeerId { switch self { - case let .encryptedChat(id, _, _, _, _, _, _): + case let .encryptedChat(encryptedChatData): + let id = encryptedChatData.id return PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt64Value(Int64(id))) - case let .encryptedChatDiscarded(_, id): + case let .encryptedChatDiscarded(encryptedChatDiscardedData): + let id = encryptedChatDiscardedData.id return PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt64Value(Int64(id))) - case let .encryptedChatEmpty(id): + case let .encryptedChatEmpty(encryptedChatEmptyData): + let id = encryptedChatEmptyData.id return PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt64Value(Int64(id))) - case let .encryptedChatRequested(_, _, id, _, _, _, _, _): + case let .encryptedChatRequested(encryptedChatRequestedData): + let id = encryptedChatRequestedData.id return PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt64Value(Int64(id))) - case let .encryptedChatWaiting(id, _, _, _, _): + case let .encryptedChatWaiting(encryptedChatWaitingData): + let id = encryptedChatWaitingData.id return PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt64Value(Int64(id))) } } @@ -615,9 +722,11 @@ extension Api.EncryptedChat { extension Api.EncryptedMessage { var peerId: PeerId { switch self { - case let .encryptedMessage(_, chatId, _, _, _): + case let .encryptedMessage(encryptedMessageData): + let chatId = encryptedMessageData.chatId return PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt64Value(Int64(chatId))) - case let .encryptedMessageService(_, chatId, _, _): + case let .encryptedMessageService(encryptedMessageServiceData): + let chatId = encryptedMessageServiceData.chatId return PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt64Value(Int64(chatId))) } } @@ -626,20 +735,22 @@ extension Api.EncryptedMessage { extension Api.InputMedia { func withUpdatedStickers(_ stickers: [Api.InputDocument]?) -> Api.InputMedia { switch self { - case let .inputMediaUploadedDocument(flags, file, thumb, mimeType, attributes, _, videoCover, videoTimestamp, ttlSeconds): - var flags = flags - var attributes = attributes + case let .inputMediaUploadedDocument(inputMediaUploadedDocumentData): + let (apiFlags, file, thumb, mimeType, apiAttributes, videoCover, videoTimestamp, ttlSeconds) = (inputMediaUploadedDocumentData.flags, inputMediaUploadedDocumentData.file, inputMediaUploadedDocumentData.thumb, inputMediaUploadedDocumentData.mimeType, inputMediaUploadedDocumentData.attributes, inputMediaUploadedDocumentData.videoCover, inputMediaUploadedDocumentData.videoTimestamp, inputMediaUploadedDocumentData.ttlSeconds) + var flags = apiFlags + var attributes = apiAttributes if let _ = stickers { flags |= (1 << 0) attributes.append(.documentAttributeHasStickers) } - return .inputMediaUploadedDocument(flags: flags, file: file, thumb: thumb, mimeType: mimeType, attributes: attributes, stickers: stickers, videoCover: videoCover, videoTimestamp: videoTimestamp, ttlSeconds: ttlSeconds) - case let .inputMediaUploadedPhoto(flags, file, _, ttlSeconds): - var flags = flags + return .inputMediaUploadedDocument(.init(flags: flags, file: file, thumb: thumb, mimeType: mimeType, attributes: attributes, stickers: stickers, videoCover: videoCover, videoTimestamp: videoTimestamp, ttlSeconds: ttlSeconds)) + case let .inputMediaUploadedPhoto(inputMediaUploadedPhotoData): + let (apiFlags, file, ttlSeconds) = (inputMediaUploadedPhotoData.flags, inputMediaUploadedPhotoData.file, inputMediaUploadedPhotoData.ttlSeconds) + var flags = apiFlags if let _ = stickers { flags |= (1 << 0) } - return .inputMediaUploadedPhoto(flags: flags, file: file, stickers: stickers, ttlSeconds: ttlSeconds) + return .inputMediaUploadedPhoto(.init(flags: flags, file: file, stickers: stickers, ttlSeconds: ttlSeconds)) default: return self } diff --git a/submodules/TelegramCore/Sources/State/UserLimitsConfiguration.swift b/submodules/TelegramCore/Sources/State/UserLimitsConfiguration.swift index 29255b7e..7c1fc585 100644 --- a/submodules/TelegramCore/Sources/State/UserLimitsConfiguration.swift +++ b/submodules/TelegramCore/Sources/State/UserLimitsConfiguration.swift @@ -32,10 +32,9 @@ public struct UserLimitsConfiguration: Equatable { public static var defaultValue: UserLimitsConfiguration { return UserLimitsConfiguration( - // GHOSTGRAM: Unlimited pinned chats bypass - maxPinnedChatCount: 99, - maxPinnedSavedChatCount: 99, - maxArchivedPinnedChatCount: 99, + maxPinnedChatCount: 5, + maxPinnedSavedChatCount: 5, + maxArchivedPinnedChatCount: 100, maxChannelsCount: 500, maxPublicLinksCount: 10, maxSavedGifCount: 200, @@ -146,10 +145,9 @@ extension UserLimitsConfiguration { } } - // GHOSTGRAM: Force unlimited pinned chats (ignore server limits) - self.maxPinnedChatCount = 99 - self.maxPinnedSavedChatCount = 99 - self.maxArchivedPinnedChatCount = 99 + self.maxPinnedChatCount = getValue("dialogs_pinned_limit", orElse: defaultValue.maxPinnedChatCount) + self.maxPinnedSavedChatCount = getValue("saved_dialogs_pinned_limit", orElse: defaultValue.maxPinnedSavedChatCount) + self.maxArchivedPinnedChatCount = getValue("dialogs_folder_pinned_limit", orElse: defaultValue.maxArchivedPinnedChatCount) self.maxChannelsCount = getValue("channels_limit", orElse: defaultValue.maxChannelsCount) self.maxPublicLinksCount = getValue("channels_public_limit", orElse: defaultValue.maxPublicLinksCount) self.maxSavedGifCount = getValue("saved_gifs_limit", orElse: defaultValue.maxSavedGifCount) diff --git a/submodules/TelegramCore/Sources/Statistics/MessageStatistics.swift b/submodules/TelegramCore/Sources/Statistics/MessageStatistics.swift index 81e0e51d..8b490736 100644 --- a/submodules/TelegramCore/Sources/Statistics/MessageStatistics.swift +++ b/submodules/TelegramCore/Sources/Statistics/MessageStatistics.swift @@ -98,7 +98,8 @@ private func requestMessageStats(postbox: Postbox, network: Network, messageId: return signal |> mapToSignal { result -> Signal in - if case let .messageStats(apiInteractionsGraph, apiReactionsGraph) = result { + if case let .messageStats(messageStatsData) = result { + let (apiInteractionsGraph, apiReactionsGraph) = (messageStatsData.viewsGraph, messageStatsData.reactionsByEmotionGraph) let interactionsGraph = StatsGraph(apiStatsGraph: apiInteractionsGraph) var interactionsGraphDelta: Int64 = 86400 if case let .Loaded(_, data) = interactionsGraph { diff --git a/submodules/TelegramCore/Sources/Statistics/PeerStatistics.swift b/submodules/TelegramCore/Sources/Statistics/PeerStatistics.swift index f61b9792..00fb5a03 100644 --- a/submodules/TelegramCore/Sources/Statistics/PeerStatistics.swift +++ b/submodules/TelegramCore/Sources/Statistics/PeerStatistics.swift @@ -836,7 +836,8 @@ private func requestGroupStats(accountPeerId: PeerId, postbox: Postbox, network: return signal |> mapToSignal { result -> Signal in return postbox.transaction { transaction -> GroupStats? in - if case let .megagroupStats(_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, users) = result { + if case let .megagroupStats(megagroupStatsData) = result { + let users = megagroupStatsData.users updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(users: users)) } return GroupStats(apiMegagroupStats: result) @@ -1114,32 +1115,40 @@ public final class GroupStatsContext { extension StatsGraph { init(apiStatsGraph: Api.StatsGraph) { switch apiStatsGraph { - case let .statsGraph(_, json, zoomToken): - if case let .dataJSON(string) = json, let data = string.data(using: .utf8) { - do { - let decodedData = try JSONSerialization.jsonObject(with: data, options: []) - guard let item = decodedData as? [String: Any] else { - self = .Failed(error: "") - return - } - if let columns = item["columns"] as? [[Any]] { - if columns.isEmpty { - self = .Empty - } else { - self = .Loaded(token: zoomToken, data: string) + case let .statsGraph(statsGraphData): + let (_, json, zoomToken) = (statsGraphData.flags, statsGraphData.json, statsGraphData.zoomToken) + if case let .dataJSON(dataJSONData) = json { + let string = dataJSONData.data + if let data = string.data(using: .utf8) { + do { + let decodedData = try JSONSerialization.jsonObject(with: data, options: []) + guard let item = decodedData as? [String: Any] else { + self = .Failed(error: "") + return } - } else { - self = .Empty + if let columns = item["columns"] as? [[Any]] { + if columns.isEmpty { + self = .Empty + } else { + self = .Loaded(token: zoomToken, data: string) + } + } else { + self = .Empty + } + } catch { + self = .Failed(error: "") } - } catch { + } else { self = .Failed(error: "") } } else { self = .Failed(error: "") } - case let .statsGraphError(error): + case let .statsGraphError(statsGraphErrorData): + let error = statsGraphErrorData.error self = .Failed(error: error) - case let .statsGraphAsync(token): + case let .statsGraphAsync(statsGraphAsyncData): + let token = statsGraphAsyncData.token if !token.isEmpty { self = .OnDemand(token: token) } else { @@ -1152,7 +1161,8 @@ extension StatsGraph { extension StatsDateRange { init(apiStatsDateRangeDays: Api.StatsDateRangeDays) { switch apiStatsDateRangeDays { - case let .statsDateRangeDays(minDate, maxDate): + case let .statsDateRangeDays(statsDateRangeDaysData): + let (minDate, maxDate) = (statsDateRangeDaysData.minDate, statsDateRangeDaysData.maxDate) self = StatsDateRange(minDate: minDate, maxDate: maxDate) } } @@ -1161,7 +1171,8 @@ extension StatsDateRange { extension StatsValue { init(apiStatsAbsValueAndPrev: Api.StatsAbsValueAndPrev) { switch apiStatsAbsValueAndPrev { - case let .statsAbsValueAndPrev(current, previous): + case let .statsAbsValueAndPrev(statsAbsValueAndPrevData): + let (current, previous) = (statsAbsValueAndPrevData.current, statsAbsValueAndPrevData.previous) self = StatsValue(current: current, previous: previous) } } @@ -1170,7 +1181,8 @@ extension StatsValue { extension StatsPercentValue { init(apiPercentValue: Api.StatsPercentValue) { switch apiPercentValue { - case let .statsPercentValue(part, total): + case let .statsPercentValue(statsPercentValueData): + let (part, total) = (statsPercentValueData.part, statsPercentValueData.total) self = StatsPercentValue(value: part, total: total) } } @@ -1179,9 +1191,11 @@ extension StatsPercentValue { extension ChannelStatsPostInteractions { init(apiPostInteractionCounters: Api.PostInteractionCounters, peerId: PeerId) { switch apiPostInteractionCounters { - case let .postInteractionCountersMessage(msgId, views, forwards, reactions): + case let .postInteractionCountersMessage(postInteractionCountersMessageData): + let (msgId, views, forwards, reactions) = (postInteractionCountersMessageData.msgId, postInteractionCountersMessageData.views, postInteractionCountersMessageData.forwards, postInteractionCountersMessageData.reactions) self = ChannelStatsPostInteractions(postId: .message(id: EngineMessage.Id(peerId: peerId, namespace: Namespaces.Message.Cloud, id: msgId)), views: views, forwards: forwards, reactions: reactions) - case let .postInteractionCountersStory(storyId, views, forwards, reactions): + case let .postInteractionCountersStory(postInteractionCountersStoryData): + let (storyId, views, forwards, reactions) = (postInteractionCountersStoryData.storyId, postInteractionCountersStoryData.views, postInteractionCountersStoryData.forwards, postInteractionCountersStoryData.reactions) self = ChannelStatsPostInteractions(postId: .story(peerId: peerId, id: storyId), views: views, forwards: forwards, reactions: reactions) } } @@ -1190,7 +1204,8 @@ extension ChannelStatsPostInteractions { extension ChannelStats { init(apiBroadcastStats: Api.stats.BroadcastStats, peerId: PeerId) { switch apiBroadcastStats { - case let .broadcastStats(period, followers, viewsPerPost, sharesPerPost, reactionsPerPost, viewsPerStory, sharesPerStory, reactionsPerStory, enabledNotifications, apiGrowthGraph, apiFollowersGraph, apiMuteGraph, apiTopHoursGraph, apiInteractionsGraph, apiInstantViewInteractionsGraph, apiViewsBySourceGraph, apiNewFollowersBySourceGraph, apiLanguagesGraph, apiReactionsByEmotionGraph, apiStoryInteractionsGraph, apiStoryReactionsByEmotionGraph, recentPostInteractions): + case let .broadcastStats(broadcastStatsData): + let (period, followers, viewsPerPost, sharesPerPost, reactionsPerPost, viewsPerStory, sharesPerStory, reactionsPerStory, enabledNotifications, apiGrowthGraph, apiFollowersGraph, apiMuteGraph, apiTopHoursGraph, apiInteractionsGraph, apiInstantViewInteractionsGraph, apiViewsBySourceGraph, apiNewFollowersBySourceGraph, apiLanguagesGraph, apiReactionsByEmotionGraph, apiStoryInteractionsGraph, apiStoryReactionsByEmotionGraph, recentPostInteractions) = (broadcastStatsData.period, broadcastStatsData.followers, broadcastStatsData.viewsPerPost, broadcastStatsData.sharesPerPost, broadcastStatsData.reactionsPerPost, broadcastStatsData.viewsPerStory, broadcastStatsData.sharesPerStory, broadcastStatsData.reactionsPerStory, broadcastStatsData.enabledNotifications, broadcastStatsData.growthGraph, broadcastStatsData.followersGraph, broadcastStatsData.muteGraph, broadcastStatsData.topHoursGraph, broadcastStatsData.interactionsGraph, broadcastStatsData.ivInteractionsGraph, broadcastStatsData.viewsBySourceGraph, broadcastStatsData.newFollowersBySourceGraph, broadcastStatsData.languagesGraph, broadcastStatsData.reactionsByEmotionGraph, broadcastStatsData.storyInteractionsGraph, broadcastStatsData.storyReactionsByEmotionGraph, broadcastStatsData.recentPostsInteractions) let growthGraph = StatsGraph(apiStatsGraph: apiGrowthGraph) let isEmpty = growthGraph.isEmpty @@ -1224,7 +1239,8 @@ extension ChannelStats { extension GroupStatsTopPoster { init(apiStatsGroupTopPoster: Api.StatsGroupTopPoster) { switch apiStatsGroupTopPoster { - case let .statsGroupTopPoster(userId, messages, avgChars): + case let .statsGroupTopPoster(statsGroupTopPosterData): + let (userId, messages, avgChars) = (statsGroupTopPosterData.userId, statsGroupTopPosterData.messages, statsGroupTopPosterData.avgChars) self = GroupStatsTopPoster(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), messageCount: messages, averageChars: avgChars) } } @@ -1233,7 +1249,8 @@ extension GroupStatsTopPoster { extension GroupStatsTopAdmin { init(apiStatsGroupTopAdmin: Api.StatsGroupTopAdmin) { switch apiStatsGroupTopAdmin { - case let .statsGroupTopAdmin(userId, deleted, kicked, banned): + case let .statsGroupTopAdmin(statsGroupTopAdminData): + let (userId, deleted, kicked, banned) = (statsGroupTopAdminData.userId, statsGroupTopAdminData.deleted, statsGroupTopAdminData.kicked, statsGroupTopAdminData.banned) self = GroupStatsTopAdmin(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), deletedCount: deleted, kickedCount: kicked, bannedCount: banned) } } @@ -1242,7 +1259,8 @@ extension GroupStatsTopAdmin { extension GroupStatsTopInviter { init(apiStatsGroupTopInviter: Api.StatsGroupTopInviter) { switch apiStatsGroupTopInviter { - case let .statsGroupTopInviter(userId, invitations): + case let .statsGroupTopInviter(statsGroupTopInviterData): + let (userId, invitations) = (statsGroupTopInviterData.userId, statsGroupTopInviterData.invitations) self = GroupStatsTopInviter(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), inviteCount: invitations) } } @@ -1251,9 +1269,10 @@ extension GroupStatsTopInviter { extension GroupStats { init(apiMegagroupStats: Api.stats.MegagroupStats) { switch apiMegagroupStats { - case let .megagroupStats(period, members, messages, viewers, posters, apiGrowthGraph, apiMembersGraph, apiNewMembersBySourceGraph, apiLanguagesGraph, apiMessagesGraph, apiActionsGraph, apiTopHoursGraph, apiTopWeekdaysGraph, topPosters, topAdmins, topInviters, _): + case let .megagroupStats(megagroupStatsData): + let (period, members, messages, viewers, posters, apiGrowthGraph, apiMembersGraph, apiNewMembersBySourceGraph, apiLanguagesGraph, apiMessagesGraph, apiActionsGraph, apiTopHoursGraph, apiTopWeekdaysGraph, topPosters, topAdmins, topInviters) = (megagroupStatsData.period, megagroupStatsData.members, megagroupStatsData.messages, megagroupStatsData.viewers, megagroupStatsData.posters, megagroupStatsData.growthGraph, megagroupStatsData.membersGraph, megagroupStatsData.newMembersBySourceGraph, megagroupStatsData.languagesGraph, megagroupStatsData.messagesGraph, megagroupStatsData.actionsGraph, megagroupStatsData.topHoursGraph, megagroupStatsData.weekdaysGraph, megagroupStatsData.topPosters, megagroupStatsData.topAdmins, megagroupStatsData.topInviters) let growthGraph = StatsGraph(apiStatsGraph: apiGrowthGraph) - + self.init(period: StatsDateRange(apiStatsDateRangeDays: period), members: StatsValue(apiStatsAbsValueAndPrev: members), messages: StatsValue(apiStatsAbsValueAndPrev: messages), viewers: StatsValue(apiStatsAbsValueAndPrev: viewers), posters: StatsValue(apiStatsAbsValueAndPrev: posters), growthGraph: growthGraph, membersGraph: StatsGraph(apiStatsGraph: apiMembersGraph), newMembersBySourceGraph: StatsGraph(apiStatsGraph: apiNewMembersBySourceGraph), languagesGraph: StatsGraph(apiStatsGraph: apiLanguagesGraph), messagesGraph: StatsGraph(apiStatsGraph: apiMessagesGraph), actionsGraph: StatsGraph(apiStatsGraph: apiActionsGraph), topHoursGraph: StatsGraph(apiStatsGraph: apiTopHoursGraph), topWeekdaysGraph: StatsGraph(apiStatsGraph: apiTopWeekdaysGraph), topPosters: topPosters.map { GroupStatsTopPoster(apiStatsGroupTopPoster: $0) }, topAdmins: topAdmins.map { GroupStatsTopAdmin(apiStatsGroupTopAdmin: $0) }, topInviters: topInviters.map { GroupStatsTopInviter(apiStatsGroupTopInviter: $0) }) } } diff --git a/submodules/TelegramCore/Sources/Statistics/StarsRevenueStatistics.swift b/submodules/TelegramCore/Sources/Statistics/StarsRevenueStatistics.swift index 2ffecfba..c1d5e7b7 100644 --- a/submodules/TelegramCore/Sources/Statistics/StarsRevenueStatistics.swift +++ b/submodules/TelegramCore/Sources/Statistics/StarsRevenueStatistics.swift @@ -146,7 +146,8 @@ public extension StarsRevenueStats { extension StarsRevenueStats { init(apiStarsRevenueStats: Api.payments.StarsRevenueStats, peerId: PeerId) { switch apiStarsRevenueStats { - case let .starsRevenueStats(_, topHoursGraph, revenueGraph, balances, usdRate): + case let .starsRevenueStats(starsRevenueStatsData): + let (topHoursGraph, revenueGraph, balances, usdRate) = (starsRevenueStatsData.topHoursGraph, starsRevenueStatsData.revenueGraph, starsRevenueStatsData.status, starsRevenueStatsData.usdRate) self.init(topHoursGraph: topHoursGraph.flatMap { StatsGraph(apiStatsGraph: $0) }, revenueGraph: StatsGraph(apiStatsGraph: revenueGraph), balances: StarsRevenueStats.Balances(apiStarsRevenueStatus: balances), usdRate: usdRate) } } @@ -155,7 +156,12 @@ extension StarsRevenueStats { extension StarsRevenueStats.Balances { init(apiStarsRevenueStatus: Api.StarsRevenueStatus) { switch apiStarsRevenueStatus { - case let .starsRevenueStatus(flags, currentBalance, availableBalance, overallRevenue, nextWithdrawalAt): + case let .starsRevenueStatus(starsRevenueStatusData): + let flags = starsRevenueStatusData.flags + let currentBalance = starsRevenueStatusData.currentBalance + let availableBalance = starsRevenueStatusData.availableBalance + let overallRevenue = starsRevenueStatusData.overallRevenue + let nextWithdrawalAt = starsRevenueStatusData.nextWithdrawalAt self.init(currentBalance: CurrencyAmount(apiAmount: currentBalance), availableBalance: CurrencyAmount(apiAmount: availableBalance), overallRevenue: CurrencyAmount(apiAmount: overallRevenue), withdrawEnabled: ((flags & (1 << 0)) != 0), nextWithdrawalTimestamp: nextWithdrawalAt) } } @@ -408,7 +414,7 @@ func _internal_requestStarsRevenueWithdrawalUrl(account: Account, ton: Bool, pee 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) } @@ -447,7 +453,8 @@ func _internal_requestStarsRevenueWithdrawalUrl(account: Account, ton: Bool, pee } |> map { result -> String in switch result { - case let .starsRevenueWithdrawalUrl(url): + case let .starsRevenueWithdrawalUrl(starsRevenueWithdrawalUrlData): + let url = starsRevenueWithdrawalUrlData.url return url } } @@ -472,7 +479,8 @@ func _internal_requestStarsRevenueAdsAccountlUrl(account: Account, peerId: Engin return nil } switch result { - case let .starsRevenueAdsAccountUrl(url): + case let .starsRevenueAdsAccountUrl(starsRevenueAdsAccountUrlData): + let url = starsRevenueAdsAccountUrlData.url return url } } diff --git a/submodules/TelegramCore/Sources/Statistics/StoryStatistics.swift b/submodules/TelegramCore/Sources/Statistics/StoryStatistics.swift index e7f3b86f..d4610f4f 100644 --- a/submodules/TelegramCore/Sources/Statistics/StoryStatistics.swift +++ b/submodules/TelegramCore/Sources/Statistics/StoryStatistics.swift @@ -68,7 +68,8 @@ private func requestStoryStats(accountPeerId: PeerId, postbox: Postbox, network: return signal |> mapToSignal { result -> Signal in - if case let .storyStats(apiInteractionsGraph, apiReactionsGraph) = result { + if case let .storyStats(storyStatsData) = result { + let (apiInteractionsGraph, apiReactionsGraph) = (storyStatsData.viewsGraph, storyStatsData.reactionsByEmotionGraph) let interactionsGraph = StatsGraph(apiStatsGraph: apiInteractionsGraph) var interactionsGraphDelta: Int64 = 86400 if case let .Loaded(_, data) = interactionsGraph { @@ -294,7 +295,8 @@ private final class StoryStatsPublicForwardsContextImpl { return ([], 0, nil) } switch result { - case let .publicForwards(_, count, forwards, nextOffset, chats, users): + case let .publicForwards(publicForwardsData): + let (count, forwards, nextOffset, chats, users) = (publicForwardsData.count, publicForwardsData.forwards, publicForwardsData.nextOffset, publicForwardsData.chats, publicForwardsData.users) var peers: [PeerId: Peer] = [:] for user in users { if let user = TelegramUser.merge(transaction.getPeer(user.peerId) as? TelegramUser, rhs: user) { @@ -310,11 +312,13 @@ private final class StoryStatsPublicForwardsContextImpl { var resultForwards: [StoryStatsPublicForwardsContext.State.Forward] = [] for forward in forwards { switch forward { - case let .publicForwardMessage(apiMessage): + case let .publicForwardMessage(publicForwardMessageData): + let apiMessage = publicForwardMessageData.message if let message = StoreMessage(apiMessage: apiMessage, accountPeerId: accountPeerId, peerIsForum: false), let renderedMessage = locallyRenderedMessage(message: message, peers: peers) { resultForwards.append(.message(EngineMessage(renderedMessage))) } - case let .publicForwardStory(apiPeer, apiStory): + case let .publicForwardStory(publicForwardStoryData): + let (apiPeer, apiStory) = (publicForwardStoryData.peer, publicForwardStoryData.story) if let storedItem = Stories.StoredItem(apiStoryItem: apiStory, peerId: apiPeer.peerId, transaction: transaction), case let .item(item) = storedItem, let media = item.media, let peer = peers[apiPeer.peerId] { let mappedItem = EngineStoryItem( id: item.id, diff --git a/submodules/TelegramCore/Sources/Suggestions.swift b/submodules/TelegramCore/Sources/Suggestions.swift index d6b47a9a..2d0de0bb 100644 --- a/submodules/TelegramCore/Sources/Suggestions.swift +++ b/submodules/TelegramCore/Sources/Suggestions.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import Postbox import SwiftSignalKit @@ -225,3 +226,63 @@ func _internal_dismissPeerSpecificServerProvidedSuggestion(account: Account, pee } } } + + +// MARK: Swiftgram +private var dismissedSGSuggestionsPromise = ValuePromise>(Set()) +private var dismissedSGSuggestions: Set = Set() { + didSet { + dismissedSGSuggestionsPromise.set(dismissedSGSuggestions) + } +} + + +public func dismissSGProvidedSuggestion(suggestionId: String) { + dismissedSGSuggestions.insert(suggestionId) + SGSimpleSettings.shared.dismissedSGSuggestions.append(suggestionId) +} + +public func getSGProvidedSuggestions(account: Account) -> Signal { + let key: PostboxViewKey = .preferences(keys: Set([PreferencesKeys.appConfiguration])) + + return combineLatest(account.postbox.combinedView(keys: [key]), dismissedSGSuggestionsPromise.get()) + |> map { views, dismissedSuggestionsValue -> Data? in + guard let view = views.views[key] as? PreferencesView, + let appConfiguration = view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) else { + return nil + } + + func parseAnnouncements(from string: String?) -> [[String: Any]] { + guard let string = string, + let data = string.data(using: .utf8), + let json = try? JSONSerialization.jsonObject(with: data, options: []), + let array = json as? [[String: Any]] else { + return [] + } + return array + } + + let ghSuggestions = parseAnnouncements(from: appConfiguration.sgGHSettings.announcementsData) + let webSuggestions = parseAnnouncements(from: appConfiguration.sgWebSettings.global.announcementsData) + + let combinedSuggestions = ghSuggestions + webSuggestions + + let filteredSuggestions = combinedSuggestions.filter { suggestion in + guard let id = suggestion["id"] as? String else { + return true + } + return !dismissedSuggestionsValue.contains(id) && + !SGSimpleSettings.shared.dismissedSGSuggestions.contains(id) + } + + guard let modifiedData = try? JSONSerialization.data(withJSONObject: filteredSuggestions, options: []) else { + return nil + } + + return modifiedData + } + |> distinctUntilChanged +} + + + diff --git a/submodules/TelegramCore/Sources/SyncCore/SuggestedPostMessageAttribute.swift b/submodules/TelegramCore/Sources/SyncCore/SuggestedPostMessageAttribute.swift index 4602bd7c..1c1d881c 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SuggestedPostMessageAttribute.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SuggestedPostMessageAttribute.swift @@ -59,7 +59,8 @@ public final class SuggestedPostMessageAttribute: Equatable, MessageAttribute { extension SuggestedPostMessageAttribute { convenience init(apiSuggestedPost: Api.SuggestedPost) { switch apiSuggestedPost { - case let .suggestedPost(flags, starsAmount, scheduleDate): + case let .suggestedPost(suggestedPostData): + let (flags, starsAmount, scheduleDate) = (suggestedPostData.flags, suggestedPostData.price, suggestedPostData.scheduleDate) var state: State? if (flags & (1 << 1)) != 0 { state = .accepted @@ -95,7 +96,7 @@ extension SuggestedPostMessageAttribute { flags |= 1 << 3 price = amount.apiAmount } - return .suggestedPost(flags: flags, price: price, scheduleDate: timestamp) + return .suggestedPost(.init(flags: flags, price: price, scheduleDate: timestamp)) } } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_AppConfiguration.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_AppConfiguration.swift index fa04d5db..126d1c18 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_AppConfiguration.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_AppConfiguration.swift @@ -1,29 +1,42 @@ import Foundation import Postbox +import SGWebSettingsScheme +import SGGHSettingsScheme public struct AppConfiguration: Codable, Equatable { + // MARK: Swiftgram + public var sgWebSettings: SGWebSettings + public var sgGHSettings: SGGHSettings + public var data: JSON? public var hash: Int32 public static var defaultValue: AppConfiguration { - return AppConfiguration(data: nil, hash: 0) + return AppConfiguration(sgWebSettings: SGWebSettings.defaultValue, sgGHSettings: SGGHSettings.defaultValue, data: nil, hash: 0) } - init(data: JSON?, hash: Int32) { + init(sgWebSettings: SGWebSettings, sgGHSettings: SGGHSettings, data: JSON?, hash: Int32) { + self.sgWebSettings = sgWebSettings + self.sgGHSettings = sgGHSettings self.data = data self.hash = hash } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) - + + self.sgWebSettings = (try container.decodeIfPresent(SGWebSettings.self, forKey: "sg")) ?? SGWebSettings.defaultValue + self.sgGHSettings = (try container.decodeIfPresent(SGGHSettings.self, forKey: "sggh")) ?? SGGHSettings.defaultValue self.data = try container.decodeIfPresent(JSON.self, forKey: "data") self.hash = (try container.decodeIfPresent(Int32.self, forKey: "storedHash")) ?? 0 } + public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) - + + try container.encode(self.sgWebSettings, forKey: "sg") + try container.encode(self.sgGHSettings, forKey: "sggh") try container.encodeIfPresent(self.data, forKey: "data") try container.encode(self.hash, forKey: "storedHash") } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedGroupData.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedGroupData.swift index 1ee1f64b..a2dfa1b1 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedGroupData.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedGroupData.swift @@ -89,7 +89,8 @@ extension PeerAllowedReactions { switch apiReactions { case .chatReactionsAll: self = .all - case let .chatReactionsSome(reactions): + case let .chatReactionsSome(chatReactionsSomeData): + let reactions = chatReactionsSomeData.reactions self = .limited(reactions.compactMap(MessageReaction.Reaction.init(apiReaction:))) case .chatReactionsNone: self = .empty diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedUserData.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedUserData.swift index 2eba659b..726bd572 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedUserData.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedUserData.swift @@ -559,9 +559,11 @@ public struct PeerEmojiStatus: Equatable, Codable { extension PeerEmojiStatus { init?(apiStatus: Api.EmojiStatus) { switch apiStatus { - case let .emojiStatus(_, documentId, until): + case let .emojiStatus(emojiStatusData): + let (documentId, until) = (emojiStatusData.documentId, emojiStatusData.until) self.init(content: .emoji(fileId: documentId), expirationDate: until) - case let .emojiStatusCollectible(_, collectibleId, documentId, title, slug, patternDocumentId, centerColor, edgeColor, patternColor, textColor, until): + case let .emojiStatusCollectible(emojiStatusCollectibleData): + let (collectibleId, documentId, title, slug, patternDocumentId, centerColor, edgeColor, patternColor, textColor, until) = (emojiStatusCollectibleData.collectibleId, emojiStatusCollectibleData.documentId, emojiStatusCollectibleData.title, emojiStatusCollectibleData.slug, emojiStatusCollectibleData.patternDocumentId, emojiStatusCollectibleData.centerColor, emojiStatusCollectibleData.edgeColor, emojiStatusCollectibleData.patternColor, emojiStatusCollectibleData.textColor, emojiStatusCollectibleData.until) self.init(content: .starGift(id: collectibleId, fileId: documentId, title: title, slug: slug, patternFileId: patternDocumentId, innerColor: centerColor, outerColor: edgeColor, patternColor: patternColor, textColor: textColor), expirationDate: until) case .emojiStatusEmpty, .inputEmojiStatusCollectible: return nil @@ -826,33 +828,36 @@ public final class TelegramBusinessLocation: Equatable, Codable { extension TelegramBusinessHours.WorkingTimeInterval { init(apiInterval: Api.BusinessWeeklyOpen) { switch apiInterval { - case let .businessWeeklyOpen(startMinute, endMinute): + case let .businessWeeklyOpen(businessWeeklyOpenData): + let (startMinute, endMinute) = (businessWeeklyOpenData.startMinute, businessWeeklyOpenData.endMinute) self.init(startMinute: Int(startMinute), endMinute: Int(endMinute)) } } var apiInterval: Api.BusinessWeeklyOpen { - return .businessWeeklyOpen(startMinute: Int32(clamping: self.startMinute), endMinute: Int32(clamping: self.endMinute)) + return .businessWeeklyOpen(Api.BusinessWeeklyOpen.Cons_businessWeeklyOpen(startMinute: Int32(clamping: self.startMinute), endMinute: Int32(clamping: self.endMinute))) } } extension TelegramBusinessHours { convenience init(apiWorkingHours: Api.BusinessWorkHours) { switch apiWorkingHours { - case let .businessWorkHours(_, timezoneId, weeklyOpen): + case let .businessWorkHours(businessWorkHoursData): + let (_, timezoneId, weeklyOpen) = (businessWorkHoursData.flags, businessWorkHoursData.timezoneId, businessWorkHoursData.weeklyOpen) self.init(timezoneId: timezoneId, weeklyTimeIntervals: weeklyOpen.map(TelegramBusinessHours.WorkingTimeInterval.init(apiInterval:))) } } var apiBusinessHours: Api.BusinessWorkHours { - return .businessWorkHours(flags: 0, timezoneId: self.timezoneId, weeklyOpen: self.weeklyTimeIntervals.map(\.apiInterval)) + return .businessWorkHours(Api.BusinessWorkHours.Cons_businessWorkHours(flags: 0, timezoneId: self.timezoneId, weeklyOpen: self.weeklyTimeIntervals.map(\.apiInterval))) } } extension TelegramBusinessLocation.Coordinates { init?(apiGeoPoint: Api.GeoPoint) { switch apiGeoPoint { - case let .geoPoint(_, long, lat, _, _): + case let .geoPoint(geoPointData): + let (_, long, lat, _, _) = (geoPointData.flags, geoPointData.long, geoPointData.lat, geoPointData.accessHash, geoPointData.accuracyRadius) self.init(latitude: lat, longitude: long) case .geoPointEmpty: return nil @@ -860,14 +865,15 @@ extension TelegramBusinessLocation.Coordinates { } var apiInputGeoPoint: Api.InputGeoPoint { - return .inputGeoPoint(flags: 0, lat: self.latitude, long: self.longitude, accuracyRadius: nil) + return .inputGeoPoint(.init(flags: 0, lat: self.latitude, long: self.longitude, accuracyRadius: nil)) } } extension TelegramBusinessLocation { convenience init(apiLocation: Api.BusinessLocation) { switch apiLocation { - case let .businessLocation(_, geoPoint, address): + case let .businessLocation(businessLocationData): + let (_, geoPoint, address) = (businessLocationData.flags, businessLocationData.geoPoint, businessLocationData.address) self.init(address: address, coordinates: geoPoint.flatMap { Coordinates(apiGeoPoint: $0) }) } } @@ -932,7 +938,8 @@ public final class TelegramBusinessChatLinks: Codable, Equatable { extension TelegramBusinessChatLinks.Link { convenience init(apiLink: Api.BusinessChatLink) { switch apiLink { - case let .businessChatLink(_, link, message, entities, title, views): + case let .businessChatLink(businessChatLinkData): + let (_, link, message, entities, title, views) = (businessChatLinkData.flags, businessChatLinkData.link, businessChatLinkData.message, businessChatLinkData.entities, businessChatLinkData.title, businessChatLinkData.views) self.init(url: link, message: message, entities: messageTextEntitiesFromApiEntities(entities ?? []), title: title, viewCount: views) } } @@ -941,7 +948,8 @@ extension TelegramBusinessChatLinks.Link { extension TelegramBusinessChatLinks { static func fromApiLinks(apiLinks: Api.account.BusinessChatLinks) -> (result: TelegramBusinessChatLinks, users: [Api.User], chats: [Api.Chat]) { switch apiLinks { - case let .businessChatLinks(links, chats, users): + case let .businessChatLinks(businessChatLinksData): + let (links, chats, users) = (businessChatLinksData.links, businessChatLinksData.chats, businessChatLinksData.users) return ( TelegramBusinessChatLinks(links: links.map(Link.init(apiLink:))), users, @@ -989,7 +997,8 @@ public final class TelegramStarRefProgram: Codable, Equatable { extension TelegramStarRefProgram { convenience init(apiStarRefProgram: Api.StarRefProgram) { switch apiStarRefProgram { - case let .starRefProgram(_, botId, commissionPermille, durationMonths, endDate, dailyRevenuePerUser): + case let .starRefProgram(starRefProgramData): + let (botId, commissionPermille, durationMonths, endDate, dailyRevenuePerUser) = (starRefProgramData.botId, starRefProgramData.commissionPermille, starRefProgramData.durationMonths, starRefProgramData.endDate, starRefProgramData.dailyRevenuePerUser) self.init(botId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(botId)), commissionPermille: commissionPermille, durationMonths: durationMonths, endDate: endDate, dailyRevenuePerUser: dailyRevenuePerUser.flatMap(StarsAmount.init(apiAmount:))) } } @@ -1103,7 +1112,8 @@ extension TelegramProfileTab { extension TelegramStarRating { convenience init(apiRating: Api.StarsRating) { switch apiRating { - case let .starsRating(_, level, currentLevelStars, stars, nextLevelStars): + case let .starsRating(starsRatingData): + let (level, currentLevelStars, stars, nextLevelStars) = (starsRatingData.level, starsRatingData.currentLevelStars, starsRatingData.stars, starsRatingData.nextLevelStars) self.init( level: level, currentLevelStars: currentLevelStars, @@ -1922,7 +1932,7 @@ func _internal_createBusinessChatLink(account: Account, message: String, entitie flags |= 1 << 1 } - return account.network.request(Api.functions.account.createBusinessChatLink(link: .inputBusinessChatLink(flags: flags, message: message, entities: apiEntities, title: title))) + return account.network.request(Api.functions.account.createBusinessChatLink(link: .inputBusinessChatLink(.init(flags: flags, message: message, entities: apiEntities, title: title)))) |> mapError { error -> AddBusinessChatLinkError in if error.errorDescription == "CHATLINKS_TOO_MUCH" { return .tooManyLinks @@ -1962,7 +1972,7 @@ func _internal_editBusinessChatLink(account: Account, url: String, message: Stri flags |= 1 << 1 } - return account.network.request(Api.functions.account.editBusinessChatLink(slug: url, link: .inputBusinessChatLink(flags: flags, message: message, entities: apiEntities, title: title))) + return account.network.request(Api.functions.account.editBusinessChatLink(slug: url, link: .inputBusinessChatLink(.init(flags: flags, message: message, entities: apiEntities, title: title)))) |> mapError { _ -> AddBusinessChatLinkError in return .generic } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CloudFileMediaResource.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CloudFileMediaResource.swift index b3568d69..f0b84c42 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CloudFileMediaResource.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CloudFileMediaResource.swift @@ -714,7 +714,7 @@ public final class WebFileReferenceMediaResource: TelegramMediaResource, MediaRe } var apiInputLocation: Api.InputWebFileLocation { - return .inputWebFileLocation(url: self.url, accessHash: self.accessHash) + return .inputWebFileLocation(.init(url: self.url, accessHash: self.accessHash)) } } @@ -762,7 +762,7 @@ final class AlbumCoverResource: TelegramMediaResource, MediaResourceWithWebFileR var flags: Int32 = 0 var document: Api.InputDocument? if let file = self.file, let resource = file.media.resource as? CloudDocumentMediaResource { - document = .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data())) + document = .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data()))) flags |= 1 << 0 } var requestTitle: String? @@ -775,12 +775,12 @@ final class AlbumCoverResource: TelegramMediaResource, MediaResourceWithWebFileR if self.isThumbnail { flags |= 1 << 2 } - return .inputWebFileAudioAlbumThumbLocation( + return .inputWebFileAudioAlbumThumbLocation(.init( flags: flags, document: document, title: requestTitle, performer: requestPerformer - ) + )) } } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_ReactionsMessageAttribute.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_ReactionsMessageAttribute.swift index db40bcab..6b2c4b85 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_ReactionsMessageAttribute.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_ReactionsMessageAttribute.swift @@ -183,9 +183,11 @@ extension MessageReaction.Reaction { switch apiReaction { case .reactionEmpty: return nil - case let .reactionEmoji(emoticon): + case let .reactionEmoji(reactionEmojiData): + let emoticon = reactionEmojiData.emoticon self = .builtin(emoticon) - case let .reactionCustomEmoji(documentId): + case let .reactionCustomEmoji(reactionCustomEmojiData): + let documentId = reactionCustomEmojiData.documentId self = .custom(documentId) case .reactionPaid: self = .stars @@ -195,9 +197,9 @@ extension MessageReaction.Reaction { var apiReaction: Api.Reaction { switch self { case let .builtin(value): - return .reactionEmoji(emoticon: value) + return .reactionEmoji(.init(emoticon: value)) case let .custom(fileId): - return .reactionCustomEmoji(documentId: fileId) + return .reactionCustomEmoji(.init(documentId: fileId)) case .stars: return .reactionPaid } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_ReplyMarkupMessageAttribute.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_ReplyMarkupMessageAttribute.swift index 5b7a5302..22596fe4 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_ReplyMarkupMessageAttribute.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_ReplyMarkupMessageAttribute.swift @@ -1,4 +1,5 @@ import Postbox +import TelegramApi public enum ReplyMarkupButtonRequestPeerType: Codable, Equatable { enum CodingKeys: String, CodingKey { @@ -323,21 +324,79 @@ public enum ReplyMarkupButtonAction: PostboxCoding, Equatable { } } +extension ReplyMarkupButton.Style { + init(apiStyle: Api.KeyboardButtonStyle) { + switch apiStyle { + case let .keyboardButtonStyle(keyboardButtonStyle): + var color: Color? + + if keyboardButtonStyle.flags & (1 << 0) != 0 { + color = .primary + } else if keyboardButtonStyle.flags & (1 << 1) != 0 { + color = .danger + } else if keyboardButtonStyle.flags & (1 << 2) != 0 { + color = .success + } + + self.init(color: color, iconFileId: keyboardButtonStyle.icon) + } + } +} + public struct ReplyMarkupButton: PostboxCoding, Equatable { + public struct Style: PostboxCoding, Equatable { + public enum Color: Int32 { + case primary = 0 + case danger = 1 + case success = 2 + } + + public let color: Color? + public let iconFileId: Int64? + + public init(color: Color?, iconFileId: Int64?) { + self.color = color + self.iconFileId = iconFileId + } + + public init(decoder: PostboxDecoder) { + let rawColor = decoder.decodeInt32ForKey("c", orElse: -1) + if rawColor != -1 { + self.color = Color(rawValue: rawColor) + } else { + self.color = nil + } + + self.iconFileId = decoder.decodeOptionalInt64ForKey("i") + } + + public func encode(_ encoder: PostboxEncoder) { + encoder.encodeInt32(self.color?.rawValue ?? -1, forKey: "c") + if let iconFileId = self.iconFileId { + encoder.encodeInt64(iconFileId, forKey: "i") + } else { + encoder.encodeNil(forKey: "i") + } + } + } + public let title: String public let titleWhenForwarded: String? public let action: ReplyMarkupButtonAction + public let style: Style? - public init(title: String, titleWhenForwarded: String?, action: ReplyMarkupButtonAction) { + public init(title: String, titleWhenForwarded: String?, action: ReplyMarkupButtonAction, style: Style?) { self.title = title self.titleWhenForwarded = titleWhenForwarded self.action = action + self.style = style } public init(decoder: PostboxDecoder) { self.title = decoder.decodeStringForKey(".t", orElse: "") self.titleWhenForwarded = decoder.decodeOptionalStringForKey(".tf") self.action = ReplyMarkupButtonAction(decoder: decoder) + self.style = (decoder.decodeObjectForKey(".stl", decoder: { Style(decoder: $0) }) as? Style) } public func encode(_ encoder: PostboxEncoder) { @@ -348,10 +407,15 @@ public struct ReplyMarkupButton: PostboxCoding, Equatable { encoder.encodeNil(forKey: ".tf") } self.action.encode(encoder) + if let style = self.style { + encoder.encodeObject(style, forKey: ".stl") + } else { + encoder.encodeNil(forKey: ".stl") + } } public static func ==(lhs: ReplyMarkupButton, rhs: ReplyMarkupButton) -> Bool { - return lhs.title == rhs.title && lhs.action == rhs.action + return lhs.title == rhs.title && lhs.action == rhs.action && lhs.style == rhs.style } } @@ -399,6 +463,21 @@ public class ReplyMarkupMessageAttribute: MessageAttribute, Equatable { public let flags: ReplyMarkupMessageFlags public let placeholder: String? + public var associatedMediaIds: [MediaId] { + var result: [MediaId] = [] + for row in rows { + for button in row.buttons { + if let iconFileId = button.style?.iconFileId { + let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: iconFileId) + if !result.contains(mediaId) { + result.append(mediaId) + } + } + } + } + return result + } + public init(rows: [ReplyMarkupRow], flags: ReplyMarkupMessageFlags, placeholder: String?) { self.rows = rows self.flags = flags diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_ReplyMessageAttribute.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_ReplyMessageAttribute.swift index 296320e9..d7e57a32 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_ReplyMessageAttribute.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_ReplyMessageAttribute.swift @@ -117,7 +117,8 @@ public class QuotedReplyMessageAttribute: MessageAttribute { extension QuotedReplyMessageAttribute { convenience init(apiHeader: Api.MessageFwdHeader, quote: EngineMessageReplyQuote?, isQuote: Bool) { switch apiHeader { - case let .messageFwdHeader(_, fromId, fromName, _, _, _, _, _, _, _, _, _): + case let .messageFwdHeader(messageFwdHeaderData): + let (_, fromId, fromName, _, _, _, _, _, _, _, _, _) = (messageFwdHeaderData.flags, messageFwdHeaderData.fromId, messageFwdHeaderData.fromName, messageFwdHeaderData.date, messageFwdHeaderData.channelPost, messageFwdHeaderData.postAuthor, messageFwdHeaderData.savedFromPeer, messageFwdHeaderData.savedFromMsgId, messageFwdHeaderData.savedFromId, messageFwdHeaderData.savedFromName, messageFwdHeaderData.savedDate, messageFwdHeaderData.psaType) self.init(peerId: fromId?.peerId, authorName: fromName, quote: quote, isQuote: isQuote) } } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramMediaAction.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramMediaAction.swift index f65aaede..5aaadd46 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramMediaAction.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramMediaAction.swift @@ -211,6 +211,38 @@ public enum TelegramMediaActionType: PostboxCoding, Equatable { public static let isFinal = StarGiftAuctionBidFlags(rawValue: 1 << 3) } + public struct GroupCreatorChange: Codable, Equatable { + private enum CodingKeys: String, CodingKey { + case kind = "k" + case targetPeerId = "t" + } + + public enum Kind: Int32 { + case pending = 0 + case applied = 1 + } + + public let kind: Kind + public let targetPeerId: PeerId + + public init(kind: Kind, targetPeerId: PeerId) { + self.kind = kind + self.targetPeerId = targetPeerId + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.kind = Kind(rawValue: try container.decode(Int32.self, forKey: .kind)) ?? .pending + self.targetPeerId = PeerId(try container.decode(Int64.self, forKey: .targetPeerId)) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.kind.rawValue, forKey: .kind) + try container.encode(self.targetPeerId.toInt64(), forKey: .targetPeerId) + } + } + case unknown case groupCreated(title: String) case addedMembers(peerIds: [PeerId]) @@ -256,7 +288,7 @@ public enum TelegramMediaActionType: PostboxCoding, Equatable { case giftStars(currency: String, amount: Int64, count: Int64, cryptoCurrency: String?, cryptoAmount: Int64?, transactionId: String?) case prizeStars(amount: Int64, isUnclaimed: Bool, boostPeerId: PeerId?, transactionId: String?, giveawayMessageId: MessageId?) case starGift(gift: StarGift, convertStars: Int64?, text: String?, entities: [MessageTextEntity]?, nameHidden: Bool, savedToProfile: Bool, converted: Bool, upgraded: Bool, canUpgrade: Bool, upgradeStars: Int64?, isRefunded: Bool, isPrepaidUpgrade: Bool, upgradeMessageId: Int32?, peerId: EnginePeer.Id?, senderId: EnginePeer.Id?, savedId: Int64?, prepaidUpgradeHash: String?, giftMessageId: Int32?, upgradeSeparate: Bool, isAuctionAcquired: Bool, toPeerId: EnginePeer.Id?, number: Int32?) - case starGiftUnique(gift: StarGift, isUpgrade: Bool, isTransferred: Bool, savedToProfile: Bool, canExportDate: Int32?, transferStars: Int64?, isRefunded: Bool, isPrepaidUpgrade: Bool, peerId: EnginePeer.Id?, senderId: EnginePeer.Id?, savedId: Int64?, resaleAmount: CurrencyAmount?, canTransferDate: Int32?, canResaleDate: Int32?, dropOriginalDetailsStars: Int64?, assigned: Bool, fromOffer: Bool) + case starGiftUnique(gift: StarGift, isUpgrade: Bool, isTransferred: Bool, savedToProfile: Bool, canExportDate: Int32?, transferStars: Int64?, isRefunded: Bool, isPrepaidUpgrade: Bool, peerId: EnginePeer.Id?, senderId: EnginePeer.Id?, savedId: Int64?, resaleAmount: CurrencyAmount?, canTransferDate: Int32?, canResaleDate: Int32?, dropOriginalDetailsStars: Int64?, assigned: Bool, fromOffer: Bool, canCraftAt: Int32?, isCrafted: Bool) case paidMessagesRefunded(count: Int32, stars: Int64) case paidMessagesPriceEdited(stars: Int64, broadcastMessagesAllowed: Bool) case conferenceCall(ConferenceCall) @@ -269,6 +301,7 @@ public enum TelegramMediaActionType: PostboxCoding, Equatable { case suggestedBirthday(TelegramBirthday) case starGiftPurchaseOffer(gift: StarGift, amount: CurrencyAmount, expireDate: Int32, isAccepted: Bool, isDeclined: Bool) case starGiftPurchaseOfferDeclined(gift: StarGift, amount: CurrencyAmount, hasExpired: Bool) + case groupCreatorChange(GroupCreatorChange) public init(decoder: PostboxDecoder) { let rawValue: Int32 = decoder.decodeInt32ForKey("_rawValue", orElse: 0) @@ -404,7 +437,7 @@ public enum TelegramMediaActionType: PostboxCoding, Equatable { } else if let stars = decoder.decodeOptionalInt64ForKey("resaleStars") { resaleAmount = CurrencyAmount(amount: StarsAmount(value: stars, nanos: 0), currency: .stars) } - self = .starGiftUnique(gift: decoder.decodeObjectForKey("gift", decoder: { StarGift(decoder: $0) }) as! StarGift, isUpgrade: decoder.decodeBoolForKey("isUpgrade", orElse: false), isTransferred: decoder.decodeBoolForKey("isTransferred", orElse: false), savedToProfile: decoder.decodeBoolForKey("savedToProfile", orElse: false), canExportDate: decoder.decodeOptionalInt32ForKey("canExportDate"), transferStars: decoder.decodeOptionalInt64ForKey("transferStars"), isRefunded: decoder.decodeBoolForKey("isRefunded", orElse: false), isPrepaidUpgrade: decoder.decodeBoolForKey("isPrepaidUpgrade", orElse: false), peerId: decoder.decodeOptionalInt64ForKey("peerId").flatMap { EnginePeer.Id($0) }, senderId: decoder.decodeOptionalInt64ForKey("senderId").flatMap { EnginePeer.Id($0) }, savedId: decoder.decodeOptionalInt64ForKey("savedId"), resaleAmount: resaleAmount, canTransferDate: decoder.decodeOptionalInt32ForKey("canTransferDate"), canResaleDate: decoder.decodeOptionalInt32ForKey("canResaleDate"), dropOriginalDetailsStars: decoder.decodeOptionalInt64ForKey("dropOriginalDetailsStars"), assigned: decoder.decodeBoolForKey("assigned", orElse: false), fromOffer: decoder.decodeBoolForKey("fromOffer", orElse: false)) + self = .starGiftUnique(gift: decoder.decodeObjectForKey("gift", decoder: { StarGift(decoder: $0) }) as! StarGift, isUpgrade: decoder.decodeBoolForKey("isUpgrade", orElse: false), isTransferred: decoder.decodeBoolForKey("isTransferred", orElse: false), savedToProfile: decoder.decodeBoolForKey("savedToProfile", orElse: false), canExportDate: decoder.decodeOptionalInt32ForKey("canExportDate"), transferStars: decoder.decodeOptionalInt64ForKey("transferStars"), isRefunded: decoder.decodeBoolForKey("isRefunded", orElse: false), isPrepaidUpgrade: decoder.decodeBoolForKey("isPrepaidUpgrade", orElse: false), peerId: decoder.decodeOptionalInt64ForKey("peerId").flatMap { EnginePeer.Id($0) }, senderId: decoder.decodeOptionalInt64ForKey("senderId").flatMap { EnginePeer.Id($0) }, savedId: decoder.decodeOptionalInt64ForKey("savedId"), resaleAmount: resaleAmount, canTransferDate: decoder.decodeOptionalInt32ForKey("canTransferDate"), canResaleDate: decoder.decodeOptionalInt32ForKey("canResaleDate"), dropOriginalDetailsStars: decoder.decodeOptionalInt64ForKey("dropOriginalDetailsStars"), assigned: decoder.decodeBoolForKey("assigned", orElse: false), fromOffer: decoder.decodeBoolForKey("fromOffer", orElse: false), canCraftAt: decoder.decodeOptionalInt32ForKey("canCraftAt"), isCrafted: decoder.decodeBoolForKey("isCrafted", orElse: false)) case 46: self = .paidMessagesRefunded(count: decoder.decodeInt32ForKey("count", orElse: 0), stars: decoder.decodeInt64ForKey("stars", orElse: 0)) case 47: @@ -437,9 +470,11 @@ public enum TelegramMediaActionType: PostboxCoding, Equatable { case 55: self = .suggestedBirthday(decoder.decodeCodable(TelegramBirthday.self, forKey: "birthday") ?? TelegramBirthday(day: 1, month: 1, year: nil)) case 56: - self = .starGiftPurchaseOffer(gift: decoder.decodeObjectForKey("gift", decoder: { StarGift(decoder: $0) }) as! StarGift, amount: decoder.decodeCodable(CurrencyAmount.self, forKey: "amount")!, expireDate: decoder.decodeInt32ForKey("expireDate", orElse: 0), isAccepted: decoder.decodeBoolForKey("isAccepted", orElse: false), isDeclined: decoder.decodeBoolForKey("isDeclined", orElse: false)) + self = .starGiftPurchaseOffer(gift: decoder.decodeObjectForKey("gift", decoder: { StarGift(decoder: $0) }) as! StarGift, amount: decoder.decodeCodable(CurrencyAmount.self, forKey: "amount") ?? CurrencyAmount(amount: .zero, currency: .stars), expireDate: decoder.decodeInt32ForKey("expireDate", orElse: 0), isAccepted: decoder.decodeBoolForKey("isAccepted", orElse: false), isDeclined: decoder.decodeBoolForKey("isDeclined", orElse: false)) case 57: self = .starGiftPurchaseOfferDeclined(gift: decoder.decodeObjectForKey("gift", decoder: { StarGift(decoder: $0) }) as! StarGift, amount: decoder.decodeCodable(CurrencyAmount.self, forKey: "amount")!, hasExpired: decoder.decodeBoolForKey("hasExpired", orElse: false)) + case 59: + self = .groupCreatorChange(decoder.decodeCodable(GroupCreatorChange.self, forKey: "d") ?? GroupCreatorChange(kind: .pending, targetPeerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(0)))) default: self = .unknown } @@ -803,7 +838,7 @@ public enum TelegramMediaActionType: PostboxCoding, Equatable { } else { encoder.encodeNil(forKey: "number") } - case let .starGiftUnique(gift, isUpgrade, isTransferred, savedToProfile, canExportDate, transferStars, isRefunded, isPrepaidUpgrade, peerId, senderId, savedId, resaleAmount, canTransferDate, canResaleDate, dropOriginalDetailsStars, assigned, fromOffer): + case let .starGiftUnique(gift, isUpgrade, isTransferred, savedToProfile, canExportDate, transferStars, isRefunded, isPrepaidUpgrade, peerId, senderId, savedId, resaleAmount, canTransferDate, canResaleDate, dropOriginalDetailsStars, assigned, fromOffer, canCraftAt, isCrafted): encoder.encodeInt32(45, forKey: "_rawValue") encoder.encodeObject(gift, forKey: "gift") encoder.encodeBool(isUpgrade, forKey: "isUpgrade") @@ -858,6 +893,14 @@ public enum TelegramMediaActionType: PostboxCoding, Equatable { } encoder.encodeBool(assigned, forKey: "assigned") encoder.encodeBool(fromOffer, forKey: "fromOffer") + + if let canCraftAt { + encoder.encodeInt32(canCraftAt, forKey: "canCraftAt") + } else { + encoder.encodeNil(forKey: "canCraftAt") + } + + encoder.encodeBool(isCrafted, forKey: "isCrafted") case let .paidMessagesRefunded(count, stars): encoder.encodeInt32(46, forKey: "_rawValue") encoder.encodeInt32(count, forKey: "count") @@ -923,6 +966,9 @@ public enum TelegramMediaActionType: PostboxCoding, Equatable { encoder.encodeObject(gift, forKey: "gift") encoder.encodeCodable(amount, forKey: "amount") encoder.encodeBool(hasExpired, forKey: "hasExpired") + case let .groupCreatorChange(groupCreatorChange): + encoder.encodeInt32(59, forKey: "_rawValue") + encoder.encodeCodable(groupCreatorChange, forKey: "d") } } @@ -965,7 +1011,7 @@ public enum TelegramMediaActionType: PostboxCoding, Equatable { peerIds.append(toPeerId) } return peerIds - case let .starGiftUnique(gift, _, _, _, _, _, _, _, peerId, senderId, _, _, _, _, _, _, _): + case let .starGiftUnique(gift, _, _, _, _, _, _, _, peerId, senderId, _, _, _, _, _, _, _, _, _): var peerIds: [PeerId] = [] if let peerId { peerIds.append(peerId) @@ -979,6 +1025,8 @@ public enum TelegramMediaActionType: PostboxCoding, Equatable { return peerIds case let .conferenceCall(conferenceCall): return conferenceCall.otherParticipants + case let .groupCreatorChange(groupCreatorChange): + return [groupCreatorChange.targetPeerId] default: return [] } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramUser.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramUser.swift index 1006e61b..be2637e7 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramUser.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramUser.swift @@ -43,6 +43,7 @@ public struct BotUserInfoFlags: OptionSet { public static let isBusiness = BotUserInfoFlags(rawValue: (1 << 6)) public static let hasWebApp = BotUserInfoFlags(rawValue: (1 << 7)) public static let hasForum = BotUserInfoFlags(rawValue: (1 << 8)) + public static let forumManagedByUser = BotUserInfoFlags(rawValue: (1 << 9)) } public struct BotUserInfo: PostboxCoding, Equatable { diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_TranslationMessageAttribute.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_TranslationMessageAttribute.swift index 37333a5d..8deaebbf 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_TranslationMessageAttribute.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_TranslationMessageAttribute.swift @@ -86,3 +86,47 @@ public class TranslationMessageAttribute: MessageAttribute, Equatable { return true } } + + + + + + + +// MARK: Swiftgram +public class QuickTranslationMessageAttribute: MessageAttribute, Equatable { + public let originalText: String + public let originalEntities: [MessageTextEntity] + + public var associatedPeerIds: [PeerId] { + return [] + } + + public init( + text: String, + entities: [MessageTextEntity] + ) { + self.originalText = text + self.originalEntities = entities + } + + required public init(decoder: PostboxDecoder) { + self.originalText = decoder.decodeStringForKey("originalText", orElse: "") + self.originalEntities = decoder.decodeObjectArrayWithDecoderForKey("originalEntities") + } + + public func encode(_ encoder: PostboxEncoder) { + encoder.encodeString(self.originalText, forKey: "originalText") + encoder.encodeObjectArray(self.originalEntities, forKey: "originalEntities") + } + + public static func ==(lhs: QuickTranslationMessageAttribute, rhs: QuickTranslationMessageAttribute) -> Bool { + if lhs.originalText != rhs.originalText { + return false + } + if lhs.originalEntities != rhs.originalEntities { + return false + } + return true + } +} diff --git a/submodules/TelegramCore/Sources/TelegramEngine/AccountData/ChangeAccountPhoneNumber.swift b/submodules/TelegramCore/Sources/TelegramEngine/AccountData/ChangeAccountPhoneNumber.swift index 537d05ee..cf2d9622 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/AccountData/ChangeAccountPhoneNumber.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/AccountData/ChangeAccountPhoneNumber.swift @@ -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 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 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 { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/AccountData/TelegramEngineAccountData.swift b/submodules/TelegramCore/Sources/TelegramEngine/AccountData/TelegramEngineAccountData.swift index c71b6cdb..d2b33e64 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/AccountData/TelegramEngineAccountData.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/AccountData/TelegramEngineAccountData.swift @@ -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 in return .single(.boolFalse) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/AccountData/TermsOfService.swift b/submodules/TelegramCore/Sources/TelegramEngine/AccountData/TermsOfService.swift index 77c05cc9..a7e98cf7 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/AccountData/TermsOfService.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/AccountData/TermsOfService.swift @@ -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 { - 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 in return .complete() } @@ -50,7 +52,8 @@ func managedTermsOfServiceUpdates(postbox: Postbox, network: Network, stateManag |> mapToSignal { [weak stateManager] result -> Signal 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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/AccountData/UpdateAccountPeerName.swift b/submodules/TelegramCore/Sources/TelegramEngine/AccountData/UpdateAccountPeerName.swift index 6a953e46..63e1c856 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/AccountData/UpdateAccountPeerName.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/AccountData/UpdateAccountPeerName.swift @@ -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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Auth/AuthTransfer.swift b/submodules/TelegramCore/Sources/TelegramEngine/Auth/AuthTransfer.swift index e37ce0cb..21f14a3c 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Auth/AuthTransfer.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Auth/AuthTransfer.swift @@ -35,7 +35,8 @@ func _internal_exportAuthTransferToken(accountManager: AccountManager mapToSignal { result -> Signal 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 castError(ExportAuthTransferTokenError.self) @@ -73,7 +76,8 @@ func _internal_exportAuthTransferToken(accountManager: AccountManager mapToSignal { result -> Signal 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 Signal 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 Signal 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) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Auth/CancelAccountReset.swift b/submodules/TelegramCore/Sources/TelegramEngine/Auth/CancelAccountReset.swift index b1dc5b97..b4fbc329 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Auth/CancelAccountReset.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Auth/CancelAccountReset.swift @@ -18,7 +18,7 @@ public enum RequestCancelAccountResetDataError { } func _internal_requestCancelAccountResetData(network: Network, hash: String) -> Signal { - 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 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 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) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Auth/TelegramEngineAuth.swift b/submodules/TelegramCore/Sources/TelegramEngine/Auth/TelegramEngineAuth.swift index b35faece..6fbca607 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Auth/TelegramEngineAuth.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Auth/TelegramEngineAuth.swift @@ -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) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Auth/TwoStepVerification.swift b/submodules/TelegramCore/Sources/TelegramEngine/Auth/TwoStepVerification.swift index f0750daa..d0e005a8 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Auth/TwoStepVerification.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Auth/TwoStepVerification.swift @@ -15,7 +15,8 @@ func _internal_twoStepVerificationConfiguration(account: Account) -> Signal 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 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 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) } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Calls/GroupCalls.swift b/submodules/TelegramCore/Sources/TelegramEngine/Calls/GroupCalls.swift index 90d13ee1..005f450a 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Calls/GroupCalls.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Calls/GroupCalls.swift @@ -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 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 { - 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 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 { - 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 { - 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 { - 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 { - 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 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 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 { - 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 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 { - 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 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 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 = network.request(Api.functions.phone.exportGroupCallInvite(flags: 1 << 0, call: .inputGroupCall(id: info.id, accessHash: info.accessHash))) + let speakerInvite: Signal = network.request(Api.functions.phone.exportGroupCallInvite(flags: 1 << 0, call: .inputGroupCall(.init(id: info.id, accessHash: info.accessHash)))) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) } |> castError(CreateConferenceCallError.self) |> mapToSignal { result -> Signal 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 { - 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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Calls/RateCall.swift b/submodules/TelegramCore/Sources/TelegramEngine/Calls/RateCall.swift index 297aef9f..f98c5111 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Calls/RateCall.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Calls/RateCall.swift @@ -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 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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Calls/TelegramEngineCalls.swift b/submodules/TelegramCore/Sources/TelegramEngine/Calls/TelegramEngineCalls.swift index 883ba976..15ff6759 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Calls/TelegramEngineCalls.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Calls/TelegramEngineCalls.swift @@ -158,13 +158,15 @@ public extension TelegramEngine { } public func requestStreamState(dataSource: AudioBroadcastDataSource, callId: Int64, accessHash: Int64) -> Signal { - 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 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) } }) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Contacts/ContactManagement.swift b/submodules/TelegramCore/Sources/TelegramEngine/Contacts/ContactManagement.swift index 6e4bae85..1b282061 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Contacts/ContactManagement.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Contacts/ContactManagement.swift @@ -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) } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Contacts/ImportContact.swift b/submodules/TelegramCore/Sources/TelegramEngine/Contacts/ImportContact.swift index d6aa2696..cbce3c84 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Contacts/ImportContact.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Contacts/ImportContact.swift @@ -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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Contacts/UpdateContactName.swift b/submodules/TelegramCore/Sources/TelegramEngine/Contacts/UpdateContactName.swift index 55625b1c..936f71bd 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Contacts/UpdateContactName.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Contacts/UpdateContactName.swift @@ -35,7 +35,7 @@ public enum UpdateContactNoteError { func _internal_updateContactNote(account: Account, peerId: PeerId, text: String, entities: [MessageTextEntity]) -> Signal { return account.postbox.transaction { transaction -> Signal 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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/HistoryImport/TelegramEngineHistoryImport.swift b/submodules/TelegramCore/Sources/TelegramEngine/HistoryImport/TelegramEngineHistoryImport.swift index 46f9494b..ef440334 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/HistoryImport/TelegramEngineHistoryImport.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/HistoryImport/TelegramEngineHistoryImport.swift @@ -45,7 +45,8 @@ public extension TelegramEngine { } |> mapToSignal { result -> Signal 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 { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Localization/Countries.swift b/submodules/TelegramCore/Sources/TelegramEngine/Localization/Countries.swift index 037bfaba..2867f43e 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Localization/Countries.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Localization/Countries.swift @@ -106,7 +106,8 @@ func _internal_getCountriesList(accountManager: AccountManager 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 retryRequest |> mapToSignal { result -> Signal 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: "")) } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/AdMessages.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/AdMessages.swift index 69d51898..8c48207f 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/AdMessages.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/AdMessages.swift @@ -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( diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ApplyMaxReadIndexInteractively.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ApplyMaxReadIndexInteractively.swift index 1ade75ef..ea85eed5 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ApplyMaxReadIndexInteractively.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ApplyMaxReadIndexInteractively.swift @@ -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 { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/AttachMenuBots.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/AttachMenuBots.swift index d353439b..45520a01 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/AttachMenuBots.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/AttachMenuBots.swift @@ -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 in return postbox.transaction { transaction -> Signal 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 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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/BotWebView.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/BotWebView.swift index b9dd8263..8b37f8e9 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/BotWebView.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/BotWebView.swift @@ -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 { 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 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 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 { 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 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 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 = 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 { 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 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 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 { 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 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 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 { - let params = Api.DataJSON.dataJSON(data: params) + let params = Api.DataJSON.dataJSON(.init(data: params)) return postbox.transaction { transaction -> Signal 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 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 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)) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ClearCloudDrafts.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ClearCloudDrafts.swift index 739d78da..e65f75d7 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ClearCloudDrafts.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ClearCloudDrafts.swift @@ -15,12 +15,14 @@ func _internal_clearCloudDraftsInteractively(postbox: Postbox, network: Network, } var keys = Set() 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 in diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/DeleteMessages.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/DeleteMessages.swift index fd85bd5d..001fcc12 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/DeleteMessages.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/DeleteMessages.swift @@ -129,7 +129,8 @@ func _internal_clearCallHistory(account: Account, forEveryone: Bool) -> Signal mapToSignal { result -> Signal 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) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/DeleteMessagesInteractively.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/DeleteMessagesInteractively.swift index c9f3d5ec..8c8fa7fa 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/DeleteMessagesInteractively.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/DeleteMessagesInteractively.swift @@ -219,7 +219,8 @@ func _internal_clearAuthorHistory(account: Account, peerId: PeerId, memberId: Pe |> mapToSignal { result -> Signal 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) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/EngineStoryViewListContext.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/EngineStoryViewListContext.swift index 8fa6c1e7..b54e699f 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/EngineStoryViewListContext.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/EngineStoryViewListContext.swift @@ -465,17 +465,19 @@ public final class EngineStoryViewListContext { |> mapToSignal { result -> Signal 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 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( diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ExportMessageLink.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ExportMessageLink.swift index 1d64aec7..f42d9a17 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ExportMessageLink.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ExportMessageLink.swift @@ -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 in diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/FactCheck.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/FactCheck.swift index bd4f8918..2092c402 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/FactCheck.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/FactCheck.swift @@ -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 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 { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/LoadMessagesIfNecessary.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/LoadMessagesIfNecessary.swift index 279d59e0..3f484371 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/LoadMessagesIfNecessary.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/LoadMessagesIfNecessary.swift @@ -61,20 +61,23 @@ func _internal_getMessagesLoadIfNecessary(_ messageIds: [MessageId], postbox: Po if let peer = supportPeers[peerId] { var signal: Signal? 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: diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/MarkAllChatsAsRead.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/MarkAllChatsAsRead.swift index 6749f90f..873db589 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/MarkAllChatsAsRead.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/MarkAllChatsAsRead.swift @@ -20,7 +20,8 @@ func _internal_markAllChatsAsRead(postbox: Postbox, network: Network, stateManag var signals: [Signal] = [] 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 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)]) } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/MessageReadStats.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/MessageReadStats.swift index 8011bd6f..d2046331 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/MessageReadStats.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/MessageReadStats.swift @@ -37,7 +37,8 @@ func _internal_messageReadStats(account: Account, id: MessageId) -> Signal Signal Signal = 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) } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/Polls.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/Polls.swift index 519eac42..e51b3831 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/Polls.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/Polls.swift @@ -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 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) { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/PreparedInlineMessages.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/PreparedInlineMessages.swift index b28358fc..7f374d84 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/PreparedInlineMessages.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/PreparedInlineMessages.swift @@ -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( diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/QuickReplyMessages.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/QuickReplyMessages.swift index f65987fe..aaf771f1 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/QuickReplyMessages.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/QuickReplyMessages.swift @@ -152,7 +152,8 @@ func _internal_keepShortcutMessagesUpdated(account: Account) -> Signal Signal 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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ReplyThreadHistory.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ReplyThreadHistory.swift index 1d561110..40469326 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ReplyThreadHistory.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ReplyThreadHistory.swift @@ -156,7 +156,8 @@ private class ReplyThreadHistoryContextImpl { |> mapToSignal { discussionMessage -> Signal in return account.postbox.transaction { transaction -> Signal 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) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ReportAds.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ReportAds.swift index 83e40887..2bfc2459 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ReportAds.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ReportAds.swift @@ -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()) } }) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ReportContent.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ReportContent.swift index 6d857d05..4334c6ac 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ReportContent.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ReportContent.swift @@ -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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestChatContextResults.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestChatContextResults.swift index 05dc2ec2..deae6012 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestChatContextResults.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestChatContextResults.swift @@ -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 { +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 { 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 = 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 { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestMessageActionCallback.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestMessageActionCallback.swift index 560a108e..2d35a587 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestMessageActionCallback.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestMessageActionCallback.swift @@ -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 { +func _internal_acceptMessageActionUrlAuth(account: Account, subject: MessageActionUrlSubject, allowWriteAccess: Bool, sharePhoneNumber: Bool) -> Signal { var flags: Int32 = 0 if allowWriteAccess { flags |= Int32(1 << 0) } + if sharePhoneNumber { + flags |= Int32(1 << 3) + } let request: Signal switch subject { @@ -250,16 +297,14 @@ func _internal_acceptMessageActionUrlAuth(account: Account, subject: MessageActi return request - |> `catch` { _ -> Signal 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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/SearchMessages.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/SearchMessages.swift index 8d1bccd1..b0ce19e6 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/SearchMessages.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/SearchMessages.swift @@ -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 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 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 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 [SendAsPeer] in var subscribers: [PeerId: Int32] = [:] let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: []) - + var premiumRequiredPeerIds = Set() 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() 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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/SparseMessageList.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/SparseMessageList.swift index 4efa8be0..b6c5942e 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/SparseMessageList.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/SparseMessageList.swift @@ -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() - 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)) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/Stories.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/Stories.swift index 4b2c2a2d..158a8a12 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/Stories.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/Stories.swift @@ -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 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 reactions_count:flags.4?int recent_viewers:flags.0?Vector = 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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/StoryListContext.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/StoryListContext.swift index e629c4bc..b8ad57ef 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/StoryListContext.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/StoryListContext.swift @@ -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))) } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/Summarize.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/Summarize.swift index ab55533e..e4d3641c 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/Summarize.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/Summarize.swift @@ -45,7 +45,8 @@ func _internal_summarizeMessage(account: Account, messageId: EngineMessage.Id, t |> mapToSignal { result -> Signal 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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/TelegramEngineMessages.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/TelegramEngineMessages.swift index 143106a1..9dc8e012 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/TelegramEngineMessages.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/TelegramEngineMessages.swift @@ -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 { - _internal_requestMessageActionUrlAuth(account: self.account, subject: subject) + return _internal_requestMessageActionUrlAuth(account: self.account, subject: subject) } - public func acceptMessageActionUrlAuth(subject: MessageActionUrlSubject, allowWriteAccess: Bool) -> Signal { - return _internal_acceptMessageActionUrlAuth(account: self.account, subject: subject, allowWriteAccess: allowWriteAccess) + public func acceptMessageActionUrlAuth(subject: MessageActionUrlSubject, allowWriteAccess: Bool, sharePhoneNumber: Bool) -> Signal { + 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 { @@ -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 { - 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 { + 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 { @@ -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 { + 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 { @@ -1471,6 +1487,10 @@ public extension TelegramEngine { } public func markStoryAsSeen(peerId: EnginePeer.Id, id: Int32, asPinned: Bool) -> Signal { + // 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) + } +} diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/TimeZones.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/TimeZones.swift index 5f231500..1d43d082 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/TimeZones.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/TimeZones.swift @@ -85,11 +85,13 @@ func _internal_keepCachedTimeZoneListUpdated(account: Account) -> Signal 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 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 { + var listOfSignals: [Signal] = [] + for (messageId, text) in messagesDict { + listOfSignals.append( + // _internal_translate(network: account.network, text: text, toLang: toLang) + // |> mapToSignal { result -> Signal in + // guard let translatedText = result else { + // return .complete() + // } + gtranslate(text, toLang) + |> mapError { _ -> TranslationError in + return .generic + } + |> mapToSignal { translatedText -> Signal 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 { 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: "
") + + 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: "
", with: "\n").replacingOccurrences(of: "< br>", with: "\n").replacingOccurrences(of: "
", 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 { + return Signal { subscriber in + let completed = Atomic(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 { + // 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] = 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 { + 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.. String { + return components(separatedBy: characterSet).joined(separator: replacementString) + } +} diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/UpdatePinnedMessage.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/UpdatePinnedMessage.swift index 69277048..c74d15b9 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/UpdatePinnedMessage.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/UpdatePinnedMessage.swift @@ -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 in switch result { - case let .affectedHistory(_, _, count): + case let .affectedHistory(affectedHistoryData): + let count = affectedHistoryData.offset if count != 0 { return .fail(.restart) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Payments/AppStore.swift b/submodules/TelegramCore/Sources/TelegramEngine/Payments/AppStore.swift index 92767962..56455cee 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Payments/AppStore.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Payments/AppStore.swift @@ -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 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 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 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))) } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Payments/BankCards.swift b/submodules/TelegramCore/Sources/TelegramEngine/Payments/BankCards.swift index 7490c0b2..af2dd268 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Payments/BankCards.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Payments/BankCards.swift @@ -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) } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Payments/BotPaymentForm.swift b/submodules/TelegramCore/Sources/TelegramEngine/Payments/BotPaymentForm.swift index 6de13f78..13c24812 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Payments/BotPaymentForm.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Payments/BotPaymentForm.swift @@ -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 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 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 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) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Payments/GiftCodes.swift b/submodules/TelegramCore/Sources/TelegramEngine/Payments/GiftCodes.swift index d5a9b8e4..2b2fd4dd 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Payments/GiftCodes.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Payments/GiftCodes.swift @@ -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 mapToSignal { result -> Signal 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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Payments/StarGifts.swift b/submodules/TelegramCore/Sources/TelegramEngine/Payments/StarGifts.swift index 95e29856..fd74f41c 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Payments/StarGifts.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Payments/StarGifts.swift @@ -415,6 +415,7 @@ public enum StarGift: Equatable, Codable, PostboxCoding { case peerColor case hostPeerId case minOfferStars + case craftChancePermille } public struct Flags: OptionSet { @@ -425,6 +426,7 @@ public enum StarGift: Equatable, Codable, PostboxCoding { } public static let isThemeAvailable = Flags(rawValue: 1 << 0) + public static let isBurned = Flags(rawValue: 1 << 1) } public enum Attribute: Equatable, Codable, PostboxCoding { @@ -443,18 +445,67 @@ public enum StarGift: Equatable, Codable, PostboxCoding { case text case entities case rarity + case rarityType + case crafted } - + public enum AttributeType { case model case pattern case backdrop case originalInfo } - - case model(name: String, file: TelegramMediaFile, rarity: Int32) - case pattern(name: String, file: TelegramMediaFile, rarity: Int32) - case backdrop(name: String, id: Int32, innerColor: Int32, outerColor: Int32, patternColor: Int32, textColor: Int32, rarity: Int32) + + public enum Rarity: Equatable, Codable { + case permille(Int32) + case rare + case epic + case legendary + case uncommon + + public var permilleValue: Int32 { + switch self { + case let .permille(value): + return value + case .rare, .epic, .legendary, .uncommon: + return 0 + } + } + + public var isPermille: Bool { + if case .permille = self { + return true + } + return false + } + + public var badgeText: String { + switch self { + case let .permille(value): + if value == 0 { + return "<0.1%" + } + let percent = Double(value) / 10.0 + if percent.truncatingRemainder(dividingBy: 1) == 0 { + return "\(Int(percent))%" + } else { + return String(format: "%.1f%%", percent) + } + case .rare: + return "rare" + case .epic: + return "epic" + case .legendary: + return "legendary" + case .uncommon: + return "uncommon" + } + } + } + + case model(name: String, file: TelegramMediaFile, rarity: Rarity, crafted: Bool) + case pattern(name: String, file: TelegramMediaFile, rarity: Rarity) + case backdrop(name: String, id: Int32, innerColor: Int32, outerColor: Int32, patternColor: Int32, textColor: Int32, rarity: Rarity) case originalInfo(senderPeerId: EnginePeer.Id?, recipientPeerId: EnginePeer.Id, date: Int32, text: String?, entities: [MessageTextEntity]?) public var attributeType: AttributeType { @@ -472,20 +523,38 @@ public enum StarGift: Equatable, Codable, PostboxCoding { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - + + func decodeRarity() throws -> Rarity { + let rarityType = try container.decodeIfPresent(Int32.self, forKey: .rarityType) ?? 0 + switch rarityType { + case 1: + return .rare + case 2: + return .epic + case 3: + return .legendary + case 4: + return .uncommon + default: + let permille = try container.decodeIfPresent(Int32.self, forKey: .rarity) ?? 0 + return .permille(permille) + } + } + let type = try container.decode(Int32.self, forKey: .type) switch type { case 0: self = .model( name: try container.decode(String.self, forKey: .name), file: try container.decode(TelegramMediaFile.self, forKey: .file), - rarity: try container.decode(Int32.self, forKey: .rarity) + rarity: try decodeRarity(), + crafted: try container.decodeIfPresent(Bool.self, forKey: .crafted) ?? false ) case 1: self = .pattern( name: try container.decode(String.self, forKey: .name), file: try container.decode(TelegramMediaFile.self, forKey: .file), - rarity: try container.decode(Int32.self, forKey: .rarity) + rarity: try decodeRarity() ) case 2: self = .backdrop( @@ -495,7 +564,7 @@ public enum StarGift: Equatable, Codable, PostboxCoding { outerColor: try container.decode(Int32.self, forKey: .outerColor), patternColor: try container.decode(Int32.self, forKey: .patternColor), textColor: try container.decode(Int32.self, forKey: .textColor), - rarity: try container.decode(Int32.self, forKey: .rarity) + rarity: try decodeRarity() ) case 3: self = .originalInfo( @@ -511,20 +580,38 @@ public enum StarGift: Equatable, Codable, PostboxCoding { } public init(decoder: PostboxDecoder) { + func decodeRarity() -> Rarity { + let rarityType = decoder.decodeInt32ForKey(CodingKeys.rarityType.rawValue, orElse: 0) + switch rarityType { + case 1: + return .rare + case 2: + return .epic + case 3: + return .legendary + case 4: + return .uncommon + default: + let permille = decoder.decodeInt32ForKey(CodingKeys.rarity.rawValue, orElse: 0) + return .permille(permille) + } + } + let type = decoder.decodeInt32ForKey(CodingKeys.type.rawValue, orElse: 0) - + switch type { case 0: self = .model( name: decoder.decodeStringForKey(CodingKeys.name.rawValue, orElse: ""), file: decoder.decodeObjectForKey(CodingKeys.file.rawValue) as! TelegramMediaFile, - rarity: decoder.decodeInt32ForKey(CodingKeys.rarity.rawValue, orElse: 0) + rarity: decodeRarity(), + crafted: decoder.decodeBoolForKey(CodingKeys.crafted.rawValue, orElse: false) ) case 1: self = .pattern( name: decoder.decodeStringForKey(CodingKeys.name.rawValue, orElse: ""), file: decoder.decodeObjectForKey(CodingKeys.file.rawValue) as! TelegramMediaFile, - rarity: decoder.decodeInt32ForKey(CodingKeys.rarity.rawValue, orElse: 0) + rarity: decodeRarity() ) case 2: self = .backdrop( @@ -534,7 +621,7 @@ public enum StarGift: Equatable, Codable, PostboxCoding { outerColor: decoder.decodeInt32ForKey(CodingKeys.outerColor.rawValue, orElse: 0), patternColor: decoder.decodeInt32ForKey(CodingKeys.patternColor.rawValue, orElse: 0), textColor: decoder.decodeInt32ForKey(CodingKeys.textColor.rawValue, orElse: 0), - rarity: decoder.decodeInt32ForKey(CodingKeys.rarity.rawValue, orElse: 0) + rarity: decodeRarity() ) case 3: self = .originalInfo( @@ -551,18 +638,35 @@ public enum StarGift: Equatable, Codable, PostboxCoding { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - + + func encodeRarity(_ rarity: Rarity) throws { + switch rarity { + case let .permille(value): + try container.encode(Int32(0), forKey: .rarityType) + try container.encode(value, forKey: .rarity) + case .rare: + try container.encode(Int32(1), forKey: .rarityType) + case .epic: + try container.encode(Int32(2), forKey: .rarityType) + case .legendary: + try container.encode(Int32(3), forKey: .rarityType) + case .uncommon: + try container.encode(Int32(4), forKey: .rarityType) + } + } + switch self { - case let .model(name, file, rarity): + case let .model(name, file, rarity, crafted): try container.encode(Int32(0), forKey: .type) try container.encode(name, forKey: .name) try container.encode(file, forKey: .file) - try container.encode(rarity, forKey: .rarity) + try encodeRarity(rarity) + try container.encode(crafted, forKey: .crafted) case let .pattern(name, file, rarity): try container.encode(Int32(1), forKey: .type) try container.encode(name, forKey: .name) try container.encode(file, forKey: .file) - try container.encode(rarity, forKey: .rarity) + try encodeRarity(rarity) case let .backdrop(name, id, innerColor, outerColor, patternColor, textColor, rarity): try container.encode(Int32(2), forKey: .type) try container.encode(name, forKey: .name) @@ -571,7 +675,7 @@ public enum StarGift: Equatable, Codable, PostboxCoding { try container.encode(outerColor, forKey: .outerColor) try container.encode(patternColor, forKey: .patternColor) try container.encode(textColor, forKey: .textColor) - try container.encode(rarity, forKey: .rarity) + try encodeRarity(rarity) case let .originalInfo(senderPeerId, recipientPeerId, date, text, entities): try container.encode(Int32(3), forKey: .type) try container.encodeIfPresent(senderPeerId?.toInt64(), forKey: .sendPeerId) @@ -583,17 +687,34 @@ public enum StarGift: Equatable, Codable, PostboxCoding { } public func encode(_ encoder: PostboxEncoder) { + func encodeRarity(_ rarity: Rarity) { + switch rarity { + case let .permille(value): + encoder.encodeInt32(0, forKey: CodingKeys.rarityType.rawValue) + encoder.encodeInt32(value, forKey: CodingKeys.rarity.rawValue) + case .rare: + encoder.encodeInt32(1, forKey: CodingKeys.rarityType.rawValue) + case .epic: + encoder.encodeInt32(2, forKey: CodingKeys.rarityType.rawValue) + case .legendary: + encoder.encodeInt32(3, forKey: CodingKeys.rarityType.rawValue) + case .uncommon: + encoder.encodeInt32(4, forKey: CodingKeys.rarityType.rawValue) + } + } + switch self { - case let .model(name, file, rarity): + case let .model(name, file, rarity, crafted): encoder.encodeInt32(0, forKey: CodingKeys.type.rawValue) encoder.encodeString(name, forKey: CodingKeys.name.rawValue) encoder.encodeObject(file, forKey: CodingKeys.file.rawValue) - encoder.encodeInt32(rarity, forKey: CodingKeys.rarity.rawValue) + encodeRarity(rarity) + encoder.encodeBool(crafted, forKey: CodingKeys.crafted.rawValue) case let .pattern(name, file, rarity): encoder.encodeInt32(1, forKey: CodingKeys.type.rawValue) encoder.encodeString(name, forKey: CodingKeys.name.rawValue) encoder.encodeObject(file, forKey: CodingKeys.file.rawValue) - encoder.encodeInt32(rarity, forKey: CodingKeys.rarity.rawValue) + encodeRarity(rarity) case let .backdrop(name, id, innerColor, outerColor, patternColor, textColor, rarity): encoder.encodeInt32(2, forKey: CodingKeys.type.rawValue) encoder.encodeString(name, forKey: CodingKeys.name.rawValue) @@ -602,7 +723,7 @@ public enum StarGift: Equatable, Codable, PostboxCoding { encoder.encodeInt32(outerColor, forKey: CodingKeys.outerColor.rawValue) encoder.encodeInt32(patternColor, forKey: CodingKeys.patternColor.rawValue) encoder.encodeInt32(textColor, forKey: CodingKeys.textColor.rawValue) - encoder.encodeInt32(rarity, forKey: CodingKeys.rarity.rawValue) + encodeRarity(rarity) case let .originalInfo(senderPeerId, recipientPeerId, date, text, entities): encoder.encodeInt32(3, forKey: CodingKeys.type.rawValue) if let senderPeerId { @@ -691,7 +812,7 @@ public enum StarGift: Equatable, Codable, PostboxCoding { public let title: String public let number: Int32 public let slug: String - public let owner: Owner + public let owner: Owner? public let attributes: [Attribute] public let availability: Availability public let giftAddress: String? @@ -706,8 +827,9 @@ public enum StarGift: Equatable, Codable, PostboxCoding { public let peerColor: PeerCollectibleColor? public let hostPeerId: EnginePeer.Id? public let minOfferStars: Int64? + public let craftChancePermille: Int32? - public init(id: Int64, giftId: Int64, title: String, number: Int32, slug: String, owner: Owner, attributes: [Attribute], availability: Availability, giftAddress: String?, resellAmounts: [CurrencyAmount]?, resellForTonOnly: Bool, releasedBy: EnginePeer.Id?, valueAmount: Int64?, valueCurrency: String?, valueUsdAmount: Int64?, flags: Flags, themePeerId: EnginePeer.Id?, peerColor: PeerCollectibleColor?, hostPeerId: EnginePeer.Id?, minOfferStars: Int64?) { + public init(id: Int64, giftId: Int64, title: String, number: Int32, slug: String, owner: Owner?, attributes: [Attribute], availability: Availability, giftAddress: String?, resellAmounts: [CurrencyAmount]?, resellForTonOnly: Bool, releasedBy: EnginePeer.Id?, valueAmount: Int64?, valueCurrency: String?, valueUsdAmount: Int64?, flags: Flags, themePeerId: EnginePeer.Id?, peerColor: PeerCollectibleColor?, hostPeerId: EnginePeer.Id?, minOfferStars: Int64?, craftChancePermille: Int32?) { self.id = id self.giftId = giftId self.title = title @@ -728,6 +850,7 @@ public enum StarGift: Equatable, Codable, PostboxCoding { self.peerColor = peerColor self.hostPeerId = hostPeerId self.minOfferStars = minOfferStars + self.craftChancePermille = craftChancePermille } public init(from decoder: Decoder) throws { @@ -744,7 +867,7 @@ public enum StarGift: Equatable, Codable, PostboxCoding { } else if let ownerName = try container.decodeIfPresent(String.self, forKey: .ownerName) { self.owner = .name(ownerName) } else { - self.owner = .name("Unknown") + self.owner = nil } self.attributes = try container.decode([UniqueGift.Attribute].self, forKey: .attributes) self.availability = try container.decode(UniqueGift.Availability.self, forKey: .availability) @@ -766,6 +889,7 @@ public enum StarGift: Equatable, Codable, PostboxCoding { self.peerColor = try container.decodeIfPresent(PeerCollectibleColor.self, forKey: .peerColor) self.hostPeerId = try container.decodeIfPresent(Int64.self, forKey: .hostPeerId).flatMap { EnginePeer.Id($0) } self.minOfferStars = try container.decodeIfPresent(Int64.self, forKey: .minOfferStars) + self.craftChancePermille = try container.decodeIfPresent(Int32.self, forKey: .craftChancePermille) } public init(decoder: PostboxDecoder) { @@ -781,7 +905,7 @@ public enum StarGift: Equatable, Codable, PostboxCoding { } else if let ownerName = decoder.decodeOptionalStringForKey(CodingKeys.ownerName.rawValue) { self.owner = .name(ownerName) } else { - self.owner = .name("Unknown") + self.owner = nil } self.attributes = (try? decoder.decodeObjectArrayWithCustomDecoderForKey(CodingKeys.attributes.rawValue, decoder: { UniqueGift.Attribute(decoder: $0) })) ?? [] self.availability = decoder.decodeObjectForKey(CodingKeys.availability.rawValue, decoder: { UniqueGift.Availability(decoder: $0) }) as! UniqueGift.Availability @@ -803,6 +927,7 @@ public enum StarGift: Equatable, Codable, PostboxCoding { self.peerColor = decoder.decodeCodable(PeerCollectibleColor.self, forKey: CodingKeys.peerColor.rawValue) self.hostPeerId = decoder.decodeOptionalInt64ForKey(CodingKeys.hostPeerId.rawValue).flatMap { EnginePeer.Id($0) } self.minOfferStars = decoder.decodeOptionalInt64ForKey(CodingKeys.minOfferStars.rawValue) + self.craftChancePermille = decoder.decodeOptionalInt32ForKey(CodingKeys.craftChancePermille.rawValue) } public func encode(to encoder: Encoder) throws { @@ -819,6 +944,8 @@ public enum StarGift: Equatable, Codable, PostboxCoding { try container.encode(name, forKey: .ownerName) case let .address(address): try container.encode(address, forKey: .ownerAddress) + default: + break } try container.encode(self.attributes, forKey: .attributes) try container.encode(self.availability, forKey: .availability) @@ -834,6 +961,7 @@ public enum StarGift: Equatable, Codable, PostboxCoding { try container.encodeIfPresent(self.peerColor, forKey: .peerColor) try container.encodeIfPresent(self.hostPeerId?.toInt64(), forKey: .hostPeerId) try container.encodeIfPresent(self.minOfferStars, forKey: .minOfferStars) + try container.encodeIfPresent(self.craftChancePermille, forKey: .craftChancePermille) } public func encode(_ encoder: PostboxEncoder) { @@ -849,6 +977,8 @@ public enum StarGift: Equatable, Codable, PostboxCoding { encoder.encodeString(name, forKey: CodingKeys.ownerName.rawValue) case let .address(address): encoder.encodeString(address, forKey: CodingKeys.ownerAddress.rawValue) + default: + break } encoder.encodeObjectArray(self.attributes, forKey: CodingKeys.attributes.rawValue) encoder.encodeObject(self.availability, forKey: CodingKeys.availability.rawValue) @@ -901,6 +1031,11 @@ public enum StarGift: Equatable, Codable, PostboxCoding { } else { encoder.encodeNil(forKey: CodingKeys.minOfferStars.rawValue) } + if let craftChancePermille = self.craftChancePermille { + encoder.encodeInt32(craftChancePermille, forKey: CodingKeys.craftChancePermille.rawValue) + } else { + encoder.encodeNil(forKey: CodingKeys.craftChancePermille.rawValue) + } } public func withResellAmounts(_ resellAmounts: [CurrencyAmount]?) -> UniqueGift { @@ -924,7 +1059,8 @@ public enum StarGift: Equatable, Codable, PostboxCoding { themePeerId: self.themePeerId, peerColor: self.peerColor, hostPeerId: self.hostPeerId, - minOfferStars: self.minOfferStars + minOfferStars: self.minOfferStars, + craftChancePermille: self.craftChancePermille ) } @@ -949,7 +1085,8 @@ public enum StarGift: Equatable, Codable, PostboxCoding { themePeerId: self.themePeerId, peerColor: self.peerColor, hostPeerId: self.hostPeerId, - minOfferStars: self.minOfferStars + minOfferStars: self.minOfferStars, + craftChancePermille: self.craftChancePermille ) } @@ -974,7 +1111,8 @@ public enum StarGift: Equatable, Codable, PostboxCoding { themePeerId: themePeerId, peerColor: self.peerColor, hostPeerId: self.hostPeerId, - minOfferStars: self.minOfferStars + minOfferStars: self.minOfferStars, + craftChancePermille: self.craftChancePermille ) } @@ -999,7 +1137,8 @@ public enum StarGift: Equatable, Codable, PostboxCoding { themePeerId: self.themePeerId, peerColor: self.peerColor, hostPeerId: self.hostPeerId, - minOfferStars: self.minOfferStars + minOfferStars: self.minOfferStars, + craftChancePermille: self.craftChancePermille ) } } @@ -1097,7 +1236,8 @@ public extension StarGift { extension StarGift { init?(apiStarGift: Api.StarGift) { switch apiStarGift { - case let .starGift(apiFlags, id, sticker, stars, availabilityRemains, availabilityTotal, availabilityResale, convertStars, firstSale, lastSale, upgradeStars, minResaleStars, title, releasedBy, perUserTotal, perUserRemains, lockedUntilDate, auctionSlug, giftsPerRound, auctionStartDate, upgradeVariantsCount, apiBackground): + case let .starGift(starGiftData): + let (apiFlags, id, sticker, stars, availabilityRemains, availabilityTotal, availabilityResale, convertStars, firstSale, lastSale, upgradeStars, minResaleStars, title, releasedBy, perUserTotal, perUserRemains, lockedUntilDate, auctionSlug, giftsPerRound, auctionStartDate, upgradeVariantsCount, apiBackground) = (starGiftData.flags, starGiftData.id, starGiftData.sticker, starGiftData.stars, starGiftData.availabilityRemains, starGiftData.availabilityTotal, starGiftData.availabilityResale, starGiftData.convertStars, starGiftData.firstSaleDate, starGiftData.lastSaleDate, starGiftData.upgradeStars, starGiftData.resellMinStars, starGiftData.title, starGiftData.releasedBy, starGiftData.perUserTotal, starGiftData.perUserRemains, starGiftData.lockedUntilDate, starGiftData.auctionSlug, starGiftData.giftsPerRound, starGiftData.auctionStartDate, starGiftData.upgradeVariants, starGiftData.background) var flags = StarGift.Gift.Flags() if (apiFlags & (1 << 2)) != 0 { flags.insert(.isBirthdayGift) @@ -1131,7 +1271,8 @@ extension StarGift { } var background: StarGift.Gift.Background? switch apiBackground { - case let .starGiftBackground(centerColor, edgeColor, textColor): + case let .starGiftBackground(starGiftBackgroundData): + let (centerColor, edgeColor, textColor) = (starGiftBackgroundData.centerColor, starGiftBackgroundData.edgeColor, starGiftBackgroundData.textColor) background = StarGift.Gift.Background(centerColor: centerColor, edgeColor: edgeColor, textColor: textColor) default: break @@ -1158,8 +1299,9 @@ extension StarGift { upgradeVariantsCount: upgradeVariantsCount, background: background )) - case let .starGiftUnique(apiFlags, id, giftId, title, slug, num, ownerPeerId, ownerName, ownerAddress, attributes, availabilityIssued, availabilityTotal, giftAddress, resellAmounts, releasedBy, valueAmount, valueCurrency, valueUsdAmount, themePeer, peerColor, hostPeerId, minOfferStars): - let owner: StarGift.UniqueGift.Owner + case let .starGiftUnique(starGiftUniqueData): + let (apiFlags, id, giftId, title, slug, num, ownerPeerId, ownerName, ownerAddress, attributes, availabilityIssued, availabilityTotal, giftAddress, apiResellAmount, releasedBy, valueAmount, valueCurrency, valueUsdAmount, themePeer, peerColor, hostPeerId, minOfferStars, craftChancePermille) = (starGiftUniqueData.flags, starGiftUniqueData.id, starGiftUniqueData.giftId, starGiftUniqueData.title, starGiftUniqueData.slug, starGiftUniqueData.num, starGiftUniqueData.ownerId, starGiftUniqueData.ownerName, starGiftUniqueData.ownerAddress, starGiftUniqueData.attributes, starGiftUniqueData.availabilityIssued, starGiftUniqueData.availabilityTotal, starGiftUniqueData.giftAddress, starGiftUniqueData.resellAmount, starGiftUniqueData.releasedBy, starGiftUniqueData.valueAmount, starGiftUniqueData.valueCurrency, starGiftUniqueData.valueUsdAmount, starGiftUniqueData.themePeer, starGiftUniqueData.peerColor, starGiftUniqueData.hostId, starGiftUniqueData.offerMinStars, starGiftUniqueData.craftChancePermille) + let owner: StarGift.UniqueGift.Owner? if let ownerAddress { owner = .address(ownerAddress) } else if let ownerId = ownerPeerId?.peerId { @@ -1167,16 +1309,20 @@ extension StarGift { } else if let ownerName { owner = .name(ownerName) } else { - return nil + owner = .none } - let resellAmounts = resellAmounts?.compactMap { CurrencyAmount(apiAmount: $0) } + let resellAmounts = apiResellAmount?.compactMap { CurrencyAmount(apiAmount: $0) } var flags = StarGift.UniqueGift.Flags() if (apiFlags & (1 << 9)) != 0 { flags.insert(.isThemeAvailable) } + if (apiFlags & (1 << 14)) != 0 { + flags.insert(.isBurned) + } var peerCollectibleColor: PeerCollectibleColor? switch peerColor { - case let .peerColorCollectible(_, collectibleId, giftEmojiId, backgroundEmojiId, accentColor, colors, darkAccentColor, darkColors): + case let .peerColorCollectible(peerColorCollectibleData): + let (collectibleId, giftEmojiId, backgroundEmojiId, accentColor, colors, darkAccentColor, darkColors) = (peerColorCollectibleData.collectibleId, peerColorCollectibleData.giftEmojiId, peerColorCollectibleData.backgroundEmojiId, peerColorCollectibleData.accentColor, peerColorCollectibleData.colors, peerColorCollectibleData.darkAccentColor, peerColorCollectibleData.darkColors) peerCollectibleColor = PeerCollectibleColor( collectibleId: collectibleId, giftEmojiFileId: giftEmojiId, @@ -1197,8 +1343,7 @@ extension StarGift { number: num, slug: slug, owner: owner, - attributes: attributes.compactMap { UniqueGift.Attribute(apiAttribute: $0) - }, + attributes: attributes.compactMap { UniqueGift.Attribute(apiAttribute: $0) }, availability: UniqueGift.Availability(issued: availabilityIssued, total: availabilityTotal), giftAddress: giftAddress, resellAmounts: resellAmounts, @@ -1211,8 +1356,9 @@ extension StarGift { themePeerId: themePeer?.peerId, peerColor: peerCollectibleColor, hostPeerId: hostPeerId?.peerId, - minOfferStars: minOfferStars.flatMap { Int64($0) } - )) + minOfferStars: minOfferStars.flatMap { Int64($0) }, + craftChancePermille: craftChancePermille + )) } } } @@ -1247,10 +1393,11 @@ func _internal_keepCachedStarGiftsUpdated(postbox: Postbox, network: Network, ac return postbox.transaction { transaction in switch result { - case let .starGifts(hash, gifts, chats, users): + case let .starGifts(starGiftsData): + let (hash, gifts, chats, users) = (starGiftsData.hash, starGiftsData.gifts, starGiftsData.chats, starGiftsData.users) let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users) updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers) - + let starGiftsLists = StarGiftsList(items: gifts.compactMap { StarGift(apiStarGift: $0) }, hashValue: hash) transaction.setPreferencesEntry(key: PreferencesKeys.starGifts(), value: PreferencesEntry(starGiftsLists)) case .starGiftsNotModified: @@ -1423,7 +1570,7 @@ func _internal_dropStarGiftOriginalDetails(account: Account, reference: StarGift storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author?.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature, psaType: forwardInfo.psaType, flags: forwardInfo.flags) } var media = currentMessage.media - if let action = media.first(where: { $0 is TelegramMediaAction }) as? TelegramMediaAction, case let .starGiftUnique(gift, isUpgrade, isTransferred, savedToProfile, canExportDate, transferStars, isRefunded, isPrepaidUpgrade, peerId, senderId, savedId, resaleAmount, canTransferDate, canResaleDate, _, assigned, fromOffer) = action.action, case let .unique(uniqueGift) = gift { + if let action = media.first(where: { $0 is TelegramMediaAction }) as? TelegramMediaAction, case let .starGiftUnique(gift, isUpgrade, isTransferred, savedToProfile, canExportDate, transferStars, isRefunded, isPrepaidUpgrade, peerId, senderId, savedId, resaleAmount, canTransferDate, canResaleDate, _, assigned, fromOffer, canCraftAt, isCrafted) = action.action, case let .unique(uniqueGift) = gift { let updatedAttributes = uniqueGift.attributes.filter { $0.attributeType != .originalInfo } media = [ TelegramMediaAction( @@ -1444,7 +1591,9 @@ func _internal_dropStarGiftOriginalDetails(account: Account, reference: StarGift canResaleDate: canResaleDate, dropOriginalDetailsStars: nil, assigned: assigned, - fromOffer: fromOffer + fromOffer: fromOffer, + canCraftAt: canCraftAt, + isCrafted: isCrafted ) ) ] @@ -1547,10 +1696,11 @@ func _internal_upgradeStarGift(account: Account, formId: Int64?, reference: Star account.stateManager.addUpdates(updates) for update in updates.allUpdates { switch update { - case let .updateNewMessage(message, _, _): + case let .updateNewMessage(updateNewMessageData): + let message = updateNewMessageData.message if let message = StoreMessage(apiMessage: message, accountPeerId: account.peerId, peerIsForum: false) { for media in message.media { - if let action = media as? TelegramMediaAction, case let .starGiftUnique(gift, _, _, savedToProfile, canExportDate, transferStars, _, _, peerId, _, savedId, _, canTransferDate, canResaleDate, dropOriginalDetailsStars, _, _) = action.action, case let .Id(messageId) = message.id { + if let action = media as? TelegramMediaAction, case let .starGiftUnique(gift, _, _, savedToProfile, canExportDate, transferStars, _, _, 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) @@ -1579,7 +1729,8 @@ func _internal_upgradeStarGift(account: Account, formId: Int64?, reference: Star upgradeSeparate: false, dropOriginalDetailsStars: dropOriginalDetailsStars, number: nil, - isRefunded: false + isRefunded: false, + canCraftAt: canCraftAt )) } } @@ -1625,19 +1776,22 @@ func _internal_starGiftUpgradePreview(account: Account, giftId: Int64) -> Signal return nil } switch result { - case let .starGiftUpgradePreview(apiSampleAttributes, apiPrices, apiNextPrices): + case let .starGiftUpgradePreview(starGiftUpgradePreviewData): + let (apiSampleAttributes, apiPrices, apiNextPrices) = (starGiftUpgradePreviewData.sampleAttributes, starGiftUpgradePreviewData.prices, starGiftUpgradePreviewData.nextPrices) let attributes = apiSampleAttributes.compactMap { StarGift.UniqueGift.Attribute(apiAttribute: $0) } var prices: [StarGiftUpgradePreview.Price] = [] var nextPrices: [StarGiftUpgradePreview.Price] = [] for price in apiPrices { switch price { - case let .starGiftUpgradePrice(date, upgradeStars): + case let .starGiftUpgradePrice(starGiftUpgradePriceData): + let (date, upgradeStars) = (starGiftUpgradePriceData.date, starGiftUpgradePriceData.upgradeStars) prices.append(StarGiftUpgradePreview.Price(stars: upgradeStars, date: date)) } } for price in apiNextPrices { switch price { - case let .starGiftUpgradePrice(date, upgradeStars): + case let .starGiftUpgradePrice(starGiftUpgradePriceData): + let (date, upgradeStars) = (starGiftUpgradePriceData.date, starGiftUpgradePriceData.upgradeStars) nextPrices.append(StarGiftUpgradePreview.Price(stars: upgradeStars, date: date)) } } @@ -1665,9 +1819,11 @@ func _internal_checkCanSendStarGift(account: Account, giftId: Int64) -> Signal ([ProfileGiftsContext.State.StarGift], Int32, String?, Bool?) in switch result { - case let .savedStarGifts(_, count, apiNotificationsEnabled, apiGifts, nextOffset, chats, users): + case let .savedStarGifts(savedStarGiftsData): + let (_, count, apiNotificationsEnabled, apiGifts, nextOffset, chats, users) = (savedStarGiftsData.flags, savedStarGiftsData.count, savedStarGiftsData.chatNotificationsEnabled, savedStarGiftsData.gifts, savedStarGiftsData.nextOffset, savedStarGiftsData.chats, savedStarGiftsData.users) let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users) updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers) @@ -2260,12 +2417,16 @@ private final class ProfileGiftsContextImpl { } func removeStarGifts(references: [StarGiftReference]) { - self.gifts.removeAll(where: { - if let reference = $0.reference { - return references.contains(reference) - } else { - return false + self.gifts.removeAll(where: { gift in + if let reference = gift.reference, references.contains(reference) { + return true } + for reference in references { + if case let .slug(slug) = reference, case let .unique(uniqueGift) = gift.gift, uniqueGift.slug == slug { + return true + } + } + return false }) self.pushState() @@ -2280,13 +2441,17 @@ private final class ProfileGiftsContextImpl { } else { updatedGifts = [] } - updatedGifts = updatedGifts.filter { gift in - if let reference = gift.reference { - return !references.contains(reference) - } else { + updatedGifts.removeAll(where: { gift in + if let reference = gift.reference, references.contains(reference) { return true } - } + for reference in references { + if case let .slug(slug) = reference, case let .unique(uniqueGift) = gift.gift, uniqueGift.slug == slug { + return true + } + } + return false + }) updatedCount -= Int32(references.count) if let entry = CodableEntry(CachedProfileGifts(gifts: updatedGifts, count: updatedCount, notificationsEnabled: nil)) { transaction.putItemCacheEntry(id: giftsEntryId(peerId: peerId, collectionId: collectionId), entry: entry) @@ -2535,6 +2700,7 @@ public final class ProfileGiftsContext { case dropOriginalDetailsStars case number case isRefunded + case canCraftAt } public let gift: TelegramCore.StarGift @@ -2559,6 +2725,7 @@ public final class ProfileGiftsContext { public let dropOriginalDetailsStars: Int64? public let number: Int32? public let isRefunded: Bool + public let canCraftAt: Int32? fileprivate let _fromPeerId: EnginePeer.Id? @@ -2588,7 +2755,8 @@ public final class ProfileGiftsContext { upgradeSeparate: Bool, dropOriginalDetailsStars: Int64?, number: Int32?, - isRefunded: Bool + isRefunded: Bool, + canCraftAt: Int32? ) { self.gift = gift self.reference = reference @@ -2613,6 +2781,7 @@ public final class ProfileGiftsContext { self.dropOriginalDetailsStars = dropOriginalDetailsStars self.number = number self.isRefunded = isRefunded + self.canCraftAt = canCraftAt } public init(from decoder: Decoder) throws { @@ -2647,6 +2816,7 @@ public final class ProfileGiftsContext { self.dropOriginalDetailsStars = try container.decodeIfPresent(Int64.self, forKey: .dropOriginalDetailsStars) self.number = try container.decodeIfPresent(Int32.self, forKey: .number) self.isRefunded = try container.decodeIfPresent(Bool.self, forKey: .isRefunded) ?? false + self.canCraftAt = try container.decodeIfPresent(Int32.self, forKey: .canCraftAt) } public func encode(to encoder: Encoder) throws { @@ -2674,7 +2844,7 @@ public final class ProfileGiftsContext { try container.encodeIfPresent(self.dropOriginalDetailsStars, forKey: .dropOriginalDetailsStars) try container.encodeIfPresent(self.number, forKey: .number) try container.encode(self.isRefunded, forKey: .isRefunded) - + try container.encodeIfPresent(self.canCraftAt, forKey: .canCraftAt) } public func withGift(_ gift: TelegramCore.StarGift) -> StarGift { @@ -2700,7 +2870,8 @@ public final class ProfileGiftsContext { upgradeSeparate: self.upgradeSeparate, dropOriginalDetailsStars: self.dropOriginalDetailsStars, number: self.number, - isRefunded: self.isRefunded + isRefunded: self.isRefunded, + canCraftAt: self.canCraftAt ) } @@ -2727,7 +2898,8 @@ public final class ProfileGiftsContext { upgradeSeparate: self.upgradeSeparate, dropOriginalDetailsStars: self.dropOriginalDetailsStars, number: self.number, - isRefunded: self.isRefunded + isRefunded: self.isRefunded, + canCraftAt: self.canCraftAt ) } @@ -2754,7 +2926,8 @@ public final class ProfileGiftsContext { upgradeSeparate: self.upgradeSeparate, dropOriginalDetailsStars: self.dropOriginalDetailsStars, number: self.number, - isRefunded: self.isRefunded + isRefunded: self.isRefunded, + canCraftAt: self.canCraftAt ) } fileprivate func withFromPeer(_ fromPeer: EnginePeer?) -> StarGift { @@ -2780,7 +2953,8 @@ public final class ProfileGiftsContext { upgradeSeparate: self.upgradeSeparate, dropOriginalDetailsStars: self.dropOriginalDetailsStars, number: self.number, - isRefunded: self.isRefunded + isRefunded: self.isRefunded, + canCraftAt: self.canCraftAt ) } @@ -2807,7 +2981,8 @@ public final class ProfileGiftsContext { upgradeSeparate: self.upgradeSeparate, dropOriginalDetailsStars: self.dropOriginalDetailsStars, number: self.number, - isRefunded: self.isRefunded + isRefunded: self.isRefunded, + canCraftAt: self.canCraftAt ) } } @@ -3022,10 +3197,299 @@ public final class ProfileGiftsContext { } } +// MARK: - CraftGiftsContext + +private final class CraftGiftsContextImpl { + private let queue: Queue + private let account: Account + private let giftId: Int64 + + private let disposable = MetaDisposable() + private let craftDisposable = MetaDisposable() + private var limit: Int32 + + private var gifts: [ProfileGiftsContext.State.StarGift] = [] + private var count: Int32 = 0 + private var dataState: ProfileGiftsContext.State.DataState = .ready(canLoadMore: true, nextOffset: nil) + + var _state: CraftGiftsContext.State? + private let stateValue = Promise() + var state: Signal { + return self.stateValue.get() + } + + init( + queue: Queue, + account: Account, + giftId: Int64, + limit: Int32 + ) { + self.queue = queue + self.account = account + self.giftId = giftId + self.limit = limit + + self.loadMore() + } + + deinit { + self.disposable.dispose() + self.craftDisposable.dispose() + } + + func craft(references: [StarGiftReference]) -> Signal { + return _internal_craftStarGift(account: self.account, references: references) + } + + func removeGifts(references: [StarGiftReference]) { + let referencesSet = Set(references) + self.gifts.removeAll { gift in + guard let ref = gift.reference else { return false } + return referencesSet.contains(ref) + } + self.count = max(0, self.count - Int32(references.count)) + self.pushState() + } + + func reload() { + self.gifts = [] + self.dataState = .ready(canLoadMore: true, nextOffset: nil) + self.loadMore() + } + + func loadMore() { + let giftId = self.giftId + let accountPeerId = self.account.peerId + let network = self.account.network + let postbox = self.account.postbox + let limit = self.limit + + guard case let .ready(true, initialNextOffset) = self.dataState else { + return + } + + self.dataState = .loading + self.pushState() + + let signal: Signal<([ProfileGiftsContext.State.StarGift], Int32, String?), NoError> = network.request(Api.functions.payments.getCraftStarGifts(giftId: giftId, offset: initialNextOffset ?? "", limit: limit)) + |> map(Optional.init) + |> `catch` { _ -> Signal in + return .single(nil) + } + |> mapToSignal { result -> Signal<([ProfileGiftsContext.State.StarGift], Int32, String?), NoError> in + guard let result else { + return .single(([], 0, nil)) + } + return postbox.transaction { transaction -> ([ProfileGiftsContext.State.StarGift], Int32, String?) in + switch result { + case let .savedStarGifts(savedStarGiftsData): + let (_, count, _, apiGifts, nextOffset, chats, users) = (savedStarGiftsData.flags, savedStarGiftsData.count, savedStarGiftsData.chatNotificationsEnabled, savedStarGiftsData.gifts, savedStarGiftsData.nextOffset, savedStarGiftsData.chats, savedStarGiftsData.users) + let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users) + updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers) + + let gifts = apiGifts.compactMap { ProfileGiftsContext.State.StarGift(apiSavedStarGift: $0, peerId: accountPeerId, transaction: transaction) } + return (gifts, count, nextOffset) + } + } + } + + self.disposable.set((signal + |> deliverOn(self.queue)).start(next: { [weak self] (gifts, count, nextOffset) in + guard let self else { + return + } + if initialNextOffset == nil { + self.gifts = gifts + } else { + self.gifts.append(contentsOf: gifts) + } + + let updatedCount = max(Int32(self.gifts.count), count) + self.count = updatedCount + self.dataState = .ready(canLoadMore: count != 0 && updatedCount > self.gifts.count && nextOffset != nil, nextOffset: nextOffset) + + self.pushState() + })) + } + + private func pushState() { + let state = CraftGiftsContext.State( + gifts: self.gifts, + count: self.count, + dataState: self.dataState + ) + self._state = state + self.stateValue.set(.single(state)) + } +} + +public final class CraftGiftsContext { + public struct State: Equatable { + public var gifts: [ProfileGiftsContext.State.StarGift] + public var count: Int32 + public var dataState: ProfileGiftsContext.State.DataState + } + + private let queue: Queue = .mainQueue() + private let impl: QueueLocalObject + + public var state: Signal { + return Signal { subscriber in + let disposable = MetaDisposable() + + self.impl.with { impl in + disposable.set(impl.state.start(next: { value in + subscriber.putNext(value) + })) + } + + return disposable + } + } + + public let giftId: Int64 + + public init( + account: Account, + giftId: Int64, + limit: Int32 = 36 + ) { + self.giftId = giftId + + let queue = self.queue + self.impl = QueueLocalObject(queue: queue, generate: { + return CraftGiftsContextImpl(queue: queue, account: account, giftId: giftId, limit: limit) + }) + } + + public func loadMore() { + self.impl.with { impl in + impl.loadMore() + } + } + + public func reload() { + self.impl.with { impl in + impl.reload() + } + } + + public func removeGifts(references: [StarGiftReference]) { + self.impl.with { impl in + impl.removeGifts(references: references) + } + } + + public func craft(references: [StarGiftReference]) -> Signal { + return Signal { subscriber in + let disposable = MetaDisposable() + self.impl.with { impl in + disposable.set(impl.craft(references: references).start(next: { value in + subscriber.putNext(value) + }, error: { error in + subscriber.putError(error) + }, completed: { + subscriber.putCompletion() + })) + } + return disposable + } + } + + public var currentState: CraftGiftsContext.State? { + var state: CraftGiftsContext.State? + self.impl.syncWith { impl in + state = impl._state + } + return state + } +} + +public enum CraftStarGiftError { + case generic + case tooEarly(Int32) + case craftFailed + case unavailable +} + +func _internal_craftStarGift(account: Account, references: [StarGiftReference]) -> Signal { + return account.postbox.transaction { transaction -> [Api.InputSavedStarGift] in + return references.compactMap { $0.apiStarGiftReference(transaction: transaction) } + } + |> castError(CraftStarGiftError.self) + |> mapToSignal { starGifts -> Signal in + guard !starGifts.isEmpty else { + return .fail(.generic) + } + return account.network.request(Api.functions.payments.craftStarGift(stargift: starGifts)) + |> mapError { error -> CraftStarGiftError in + if error.errorDescription.hasPrefix("STARGIFT_CRAFT_TOO_EARLY_") { + let timeout = String(error.errorDescription[error.errorDescription.index(error.errorDescription.startIndex, offsetBy: "STARGIFT_CRAFT_TOO_EARLY_".count)...]) + if let value = Int32(timeout) { + return .tooEarly(value) + } + } else if error.errorDescription == "STARGIFT_CRAFT_UNAVAILABLE" { + return .unavailable + } + return .generic + } + |> mapToSignal { updates -> Signal in + account.stateManager.addUpdates(updates) + for update in updates.allUpdates { + switch update { + case let .updateNewMessage(updateNewMessageData): + let message = updateNewMessageData.message + if let message = StoreMessage(apiMessage: message, accountPeerId: account.peerId, peerIsForum: false) { + for media in message.media { + if let action = media as? TelegramMediaAction, case let .starGiftUnique(gift, _, _, savedToProfile, canExportDate, transferStars, _, _, 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) + } else { + reference = .message(messageId: messageId) + } + return .single(ProfileGiftsContext.State.StarGift( + gift: gift, + reference: reference, + fromPeer: nil, + date: message.timestamp, + text: nil, + entities: nil, + nameHidden: false, + savedToProfile: savedToProfile, + pinnedToTop: false, + convertStars: nil, + canUpgrade: false, + canExportDate: canExportDate, + upgradeStars: nil, + transferStars: transferStars, + canTransferDate: canTransferDate, + canResaleDate: canResaleDate, + collectionIds: nil, + prepaidUpgradeHash: nil, + upgradeSeparate: false, + dropOriginalDetailsStars: dropOriginalDetailsStars, + number: nil, + isRefunded: false, + canCraftAt: canCraftAt + )) + } + } + } + default: + break + } + } + return .fail(.craftFailed) + } + } +} + extension ProfileGiftsContext.State.StarGift { init?(apiSavedStarGift: Api.SavedStarGift, peerId: EnginePeer.Id, transaction: Transaction) { switch apiSavedStarGift { - case let .savedStarGift(flags, fromId, date, apiGift, message, msgId, savedId, convertStars, upgradeStars, canExportDate, transferStars, canTransferAt, canResaleAt, collectionIds, prepaidUpgradeHash, dropOriginalDetailsStars, number): + case let .savedStarGift(savedStarGiftData): + let (flags, fromId, date, apiGift, message, msgId, savedId, convertStars, upgradeStars, canExportDate, transferStars, canTransferAt, canResaleAt, collectionIds, prepaidUpgradeHash, dropOriginalDetailsStars, number, canCraftAt) = (savedStarGiftData.flags, savedStarGiftData.fromId, savedStarGiftData.date, savedStarGiftData.gift, savedStarGiftData.message, savedStarGiftData.msgId, savedStarGiftData.savedId, savedStarGiftData.convertStars, savedStarGiftData.upgradeStars, savedStarGiftData.canExportAt, savedStarGiftData.transferStars, savedStarGiftData.canTransferAt, savedStarGiftData.canResellAt, savedStarGiftData.collectionId, savedStarGiftData.prepaidUpgradeHash, savedStarGiftData.dropOriginalDetailsStars, savedStarGiftData.giftNum, savedStarGiftData.canCraftAt) guard let gift = StarGift(apiStarGift: apiGift) else { return nil } @@ -3040,7 +3504,8 @@ extension ProfileGiftsContext.State.StarGift { if let message { switch message { - case let .textWithEntities(text, entities): + case let .textWithEntities(textWithEntitiesData): + let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities) self.text = text self.entities = messageTextEntitiesFromApiEntities(entities) } @@ -3077,59 +3542,89 @@ extension ProfileGiftsContext.State.StarGift { self.dropOriginalDetailsStars = dropOriginalDetailsStars self.number = number self.isRefunded = (flags & (1 << 9)) != 0 + self.canCraftAt = canCraftAt } } } extension StarGift.UniqueGift.Attribute { init?(apiAttribute: Api.StarGiftAttribute) { + func parseRarity(_ apiRarity: Api.StarGiftAttributeRarity) -> Rarity { + switch apiRarity { + case let .starGiftAttributeRarity(starGiftAttributeRarityData): + let permille = starGiftAttributeRarityData.permille + return .permille(permille) + case .starGiftAttributeRarityRare: + return .rare + case .starGiftAttributeRarityEpic: + return .epic + case .starGiftAttributeRarityLegendary: + return .legendary + case .starGiftAttributeRarityUncommon: + return .uncommon + } + } + switch apiAttribute { - case let .starGiftAttributeModel(name, document, rarityPermille): + case let .starGiftAttributeModel(starGiftAttributeModelData): + let (flags, name, document, rarity) = (starGiftAttributeModelData.flags, starGiftAttributeModelData.name, starGiftAttributeModelData.document, starGiftAttributeModelData.rarity) guard let file = telegramMediaFileFromApiDocument(document, altDocuments: nil) else { return nil } - self = .model(name: name, file: file, rarity: rarityPermille) - case let .starGiftAttributePattern(name, document, rarityPermille): + let crafted = (flags & (1 << 0)) != 0 + self = .model(name: name, file: file, rarity: parseRarity(rarity), crafted: crafted) + case let .starGiftAttributePattern(starGiftAttributePatternData): + let (name, document, rarity) = (starGiftAttributePatternData.name, starGiftAttributePatternData.document, starGiftAttributePatternData.rarity) guard let file = telegramMediaFileFromApiDocument(document, altDocuments: nil) else { return nil } - self = .pattern(name: name, file: file, rarity: rarityPermille) - case let .starGiftAttributeBackdrop(name, id, centerColor, edgeColor, patternColor, textColor, rarityPermille): - self = .backdrop(name: name, id: id, innerColor: centerColor, outerColor: edgeColor, patternColor: patternColor, textColor: textColor, rarity: rarityPermille) - case let .starGiftAttributeOriginalDetails(_, sender, recipient, date, message): + self = .pattern(name: name, file: file, rarity: parseRarity(rarity)) + case let .starGiftAttributeBackdrop(starGiftAttributeBackdropData): + let (name, id, centerColor, edgeColor, patternColor, textColor, rarity) = (starGiftAttributeBackdropData.name, starGiftAttributeBackdropData.backdropId, starGiftAttributeBackdropData.centerColor, starGiftAttributeBackdropData.edgeColor, starGiftAttributeBackdropData.patternColor, starGiftAttributeBackdropData.textColor, starGiftAttributeBackdropData.rarity) + self = .backdrop(name: name, id: id, innerColor: centerColor, outerColor: edgeColor, patternColor: patternColor, textColor: textColor, rarity: parseRarity(rarity)) + case let .starGiftAttributeOriginalDetails(starGiftAttributeOriginalDetailsData): + let (_, sender, recipient, date, message) = (starGiftAttributeOriginalDetailsData.flags, starGiftAttributeOriginalDetailsData.senderId, starGiftAttributeOriginalDetailsData.recipientId, starGiftAttributeOriginalDetailsData.date, starGiftAttributeOriginalDetailsData.message) var text: String? var entities: [MessageTextEntity]? - if case let .textWithEntities(textValue, entitiesValue) = message { - text = textValue - entities = messageTextEntitiesFromApiEntities(entitiesValue) + if case let .textWithEntities(textWithEntitiesData) = message { + text = textWithEntitiesData.text + entities = messageTextEntitiesFromApiEntities(textWithEntitiesData.entities) } self = .originalInfo(senderPeerId: sender?.peerId, recipientPeerId: recipient.peerId, date: date, text: text, entities: entities) } } } +public enum GetUniqueStarGiftError { + case generic + case invalidSlug + case alreadyBurned +} -func _internal_getUniqueStarGift(account: Account, slug: String) -> Signal { +func _internal_getUniqueStarGift(account: Account, slug: String) -> Signal { return account.network.request(Api.functions.payments.getUniqueStarGift(slug: slug)) - |> map(Optional.init) - |> `catch` { _ -> Signal in - return .single(nil) + |> mapError { error -> GetUniqueStarGiftError in + if error.errorDescription == "STARGIFT_ALREADY_BURNED" { + return .alreadyBurned + } else if error.errorDescription == "STARGIFT_SLUG_INVALID" { + return .invalidSlug + } + return .generic } - |> mapToSignal { result -> Signal in - if let result = result { - switch result { - case let .uniqueStarGift(gift, chats, users): - return account.postbox.transaction { transaction in - let parsedPeers = AccumulatedPeers(chats: chats, users: users) - updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: parsedPeers) - guard case let .unique(uniqueGift) = StarGift(apiStarGift: gift) else { - return nil - } - return uniqueGift + |> mapToSignal { result -> Signal in + switch result { + case let .uniqueStarGift(uniqueStarGiftData): + let (gift, chats, users) = (uniqueStarGiftData.gift, uniqueStarGiftData.chats, uniqueStarGiftData.users) + return account.postbox.transaction { transaction -> Signal in + let parsedPeers = AccumulatedPeers(chats: chats, users: users) + updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: parsedPeers) + guard case let .unique(uniqueGift) = StarGift(apiStarGift: gift) else { + return .fail(.invalidSlug) } + return .single(uniqueGift) } - } else { - return .single(nil) + |> castError(GetUniqueStarGiftError.self) + |> switchToLatest } } } @@ -3143,7 +3638,8 @@ func _internal_getUniqueStarGiftValueInfo(account: Account, slug: String) -> Sig |> map { result -> StarGift.UniqueGift.ValueInfo? in if let result { switch result { - case let .uniqueStarGiftValueInfo(flags, currency, value, initialSaleDate, initialSaleStars, initialSalePrice, lastSaleDate, lastSalePrice, floorPrice, averagePrice, listedCount, fragmentListedCount, fragmentListedUrl): + case let .uniqueStarGiftValueInfo(uniqueStarGiftValueInfoData): + let (flags, currency, value, initialSaleDate, initialSaleStars, initialSalePrice, lastSaleDate, lastSalePrice, floorPrice, averagePrice, listedCount, fragmentListedCount, fragmentListedUrl) = (uniqueStarGiftValueInfoData.flags, uniqueStarGiftValueInfoData.currency, uniqueStarGiftValueInfoData.value, uniqueStarGiftValueInfoData.initialSaleDate, uniqueStarGiftValueInfoData.initialSaleStars, uniqueStarGiftValueInfoData.initialSalePrice, uniqueStarGiftValueInfoData.lastSaleDate, uniqueStarGiftValueInfoData.lastSalePrice, uniqueStarGiftValueInfoData.floorPrice, uniqueStarGiftValueInfoData.averagePrice, uniqueStarGiftValueInfoData.listedCount, uniqueStarGiftValueInfoData.fragmentListedCount, uniqueStarGiftValueInfoData.fragmentListedUrl) return StarGift.UniqueGift.ValueInfo( isLastSaleOnFragment: flags & (1 << 1) != 0, valueIsAverage: flags & (1 << 6) != 0, @@ -3222,14 +3718,14 @@ extension StarGiftReference { func apiStarGiftReference(transaction: Transaction) -> Api.InputSavedStarGift? { switch self { case let .message(messageId): - return .inputSavedStarGiftUser(msgId: messageId.id) + return .inputSavedStarGiftUser(.init(msgId: messageId.id)) case let .peer(peerId, id): guard let inputPeer = transaction.getPeer(peerId).flatMap({ apiInputPeer($0) }) else { return nil } - return .inputSavedStarGiftChat(peer: inputPeer, savedId: id) + return .inputSavedStarGiftChat(.init(peer: inputPeer, savedId: id)) case let .slug(slug): - return .inputSavedStarGiftSlug(slug: slug) + return .inputSavedStarGiftSlug(.init(slug: slug)) } } } @@ -3301,7 +3797,7 @@ func _internal_requestStarGiftWithdrawalUrl(account: Account, reference: StarGif 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) } @@ -3334,7 +3830,8 @@ func _internal_requestStarGiftWithdrawalUrl(account: Account, reference: StarGif } |> map { result -> String in switch result { - case let .starGiftWithdrawalUrl(url): + case let .starGiftWithdrawalUrl(starGiftWithdrawalUrlData): + let url = starGiftWithdrawalUrlData.url return url } } @@ -3396,7 +3893,7 @@ func _internal_updateStarGiftResalePrice(account: Account, reference: StarGiftRe public extension StarGift.UniqueGift { var itemFile: TelegramMediaFile? { for attribute in self.attributes { - if case let .model(_, file, _) = attribute { + if case let .model(_, file, _, _) = attribute { return file } } @@ -3408,6 +3905,7 @@ private final class ResaleGiftsContextImpl { private let queue: Queue private let account: Account private let giftId: Int64 + private let forCrafting: Bool private let disposable = MetaDisposable() @@ -3431,11 +3929,13 @@ private final class ResaleGiftsContextImpl { init( queue: Queue, account: Account, - giftId: Int64 + giftId: Int64, + forCrafting: Bool ) { self.queue = queue self.account = account self.giftId = giftId + self.forCrafting = forCrafting self.loadMore() } @@ -3468,6 +3968,10 @@ private final class ResaleGiftsContextImpl { } var flags: Int32 = 0 + if self.forCrafting { + flags |= (1 << 4) + } + switch sorting { case .date: break @@ -3483,11 +3987,11 @@ private final class ResaleGiftsContextImpl { apiAttributes = filterAttributes.map { switch $0 { case let .model(id): - return .starGiftAttributeIdModel(documentId: id) + return .starGiftAttributeIdModel(.init(documentId: id)) case let .pattern(id): - return .starGiftAttributeIdPattern(documentId: id) + return .starGiftAttributeIdPattern(.init(documentId: id)) case let .backdrop(id): - return .starGiftAttributeIdBackdrop(backdropId: id) + return .starGiftAttributeIdBackdrop(.init(backdropId: id)) } } } @@ -3506,7 +4010,8 @@ private final class ResaleGiftsContextImpl { } return postbox.transaction { transaction -> ([StarGift], [StarGift.UniqueGift.Attribute]?, [ResaleGiftsContext.Attribute: Int32]?, Int64?, Int32, String?) in switch result { - case let .resaleStarGifts(_, count, gifts, nextOffset, attributes, attributesHash, chats, counters, users): + case let .resaleStarGifts(resaleStarGiftsData): + let (_, count, gifts, nextOffset, attributes, attributesHash, chats, counters, users) = (resaleStarGiftsData.flags, resaleStarGiftsData.count, resaleStarGiftsData.gifts, resaleStarGiftsData.nextOffset, resaleStarGiftsData.attributes, resaleStarGiftsData.attributesHash, resaleStarGiftsData.chats, resaleStarGiftsData.counters, resaleStarGiftsData.users) let _ = attributesHash var resultAttributes: [StarGift.UniqueGift.Attribute]? @@ -3519,13 +4024,17 @@ private final class ResaleGiftsContextImpl { var attributeCountValue: [ResaleGiftsContext.Attribute: Int32] = [:] for counter in counters { switch counter { - case let .starGiftAttributeCounter(attribute, count): + case let .starGiftAttributeCounter(starGiftAttributeCounterData): + let (attribute, count) = (starGiftAttributeCounterData.attribute, starGiftAttributeCounterData.count) switch attribute { - case let .starGiftAttributeIdModel(documentId): + case let .starGiftAttributeIdModel(starGiftAttributeIdModelData): + let documentId = starGiftAttributeIdModelData.documentId attributeCountValue[.model(documentId)] = count - case let .starGiftAttributeIdPattern(documentId): + case let .starGiftAttributeIdPattern(starGiftAttributeIdPatternData): + let documentId = starGiftAttributeIdPatternData.documentId attributeCountValue[.pattern(documentId)] = count - case let .starGiftAttributeIdBackdrop(backdropId): + case let .starGiftAttributeIdBackdrop(starGiftAttributeIdBackdropData): + let backdropId = starGiftAttributeIdBackdropData.backdropId attributeCountValue[.backdrop(backdropId)] = count } } @@ -3732,13 +4241,18 @@ public final class ResaleGiftsContext { } } + public let forCrafting: Bool + public init( account: Account, - giftId: Int64 + giftId: Int64, + forCrafting: Bool ) { + self.forCrafting = forCrafting + let queue = self.queue self.impl = QueueLocalObject(queue: queue, generate: { - return ResaleGiftsContextImpl(queue: queue, account: account, giftId: giftId) + return ResaleGiftsContextImpl(queue: queue, account: account, giftId: giftId, forCrafting: forCrafting) }) } @@ -3846,7 +4360,8 @@ func _internal_getStarGiftUpgradeAttributes(account: Account, giftId: Int64) -> return .single(nil) } switch result { - case let .starGiftUpgradeAttributes(apiAttributes): + case let .starGiftUpgradeAttributes(starGiftUpgradeAttributesData): + let apiAttributes = starGiftUpgradeAttributesData.attributes let attributes = apiAttributes.compactMap { StarGift.UniqueGift.Attribute(apiAttribute: $0) } return account.postbox.transaction { transaction in if !attributes.isEmpty { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Payments/StarGiftsAuctions.swift b/submodules/TelegramCore/Sources/TelegramEngine/Payments/StarGiftsAuctions.swift index a3652a45..de7b020b 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Payments/StarGiftsAuctions.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Payments/StarGiftsAuctions.swift @@ -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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Payments/StarGiftsCollections.swift b/submodules/TelegramCore/Sources/TelegramEngine/Payments/StarGiftsCollections.swift index 7adb42b0..dc858255 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Payments/StarGiftsCollections.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Payments/StarGiftsCollections.swift @@ -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 ?? [] diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Payments/Stars.swift b/submodules/TelegramCore/Sources/TelegramEngine/Payments/Stars.swift index b51aebda..fa6c51a4 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Payments/Stars.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Payments/Stars.swift @@ -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 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 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)) } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Payments/TelegramEnginePayments.swift b/submodules/TelegramCore/Sources/TelegramEngine/Payments/TelegramEnginePayments.swift index ec9b54d7..6d27aa60 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Payments/TelegramEnginePayments.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Payments/TelegramEnginePayments.swift @@ -149,7 +149,7 @@ public extension TelegramEngine { return _internal_checkCanSendStarGift(account: self.account, giftId: giftId) } - public func getUniqueStarGift(slug: String) -> Signal { + public func getUniqueStarGift(slug: String) -> Signal { return _internal_getUniqueStarGift(account: self.account, slug: slug) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/AdPeers.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/AdPeers.swift index d9b889c6..62f16197 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/AdPeers.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/AdPeers.swift @@ -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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/AddPeerMember.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/AddPeerMember.swift index d303743a..ae5c44b6 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/AddPeerMember.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/AddPeerMember.swift @@ -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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/AddressNames.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/AddressNames.swift index bd80fb9e..231f1206 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/AddressNames.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/AddressNames.swift @@ -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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/Birthdays.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/Birthdays.swift index 31253d0e..aa100b2f 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/Birthdays.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/Birthdays.swift @@ -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 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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/BotRecomendation.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/BotRecomendation.swift index 2f7d3681..000e81af 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/BotRecomendation.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/BotRecomendation.swift @@ -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) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelAdminEventLogs.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelAdminEventLogs.swift index 2fd1488d..60f0512b 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelAdminEventLogs.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelAdminEventLogs.swift @@ -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)) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelBlacklist.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelBlacklist.swift index 516d812d..0630e1db 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelBlacklist.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelBlacklist.swift @@ -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)) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelCreation.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelCreation.swift index 10c5a4a2..16562551 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelCreation.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelCreation.swift @@ -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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelMembers.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelMembers.swift index a1d943cf..c90272d4 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelMembers.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelMembers.swift @@ -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] = [:] diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift index 2394f8f5..ec6676b3 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift @@ -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) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelRecommendation.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelRecommendation.swift index 0a4b1afe..0ea563f1 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelRecommendation.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelRecommendation.swift @@ -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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChatListFiltering.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChatListFiltering.swift index 2282e190..1d744505 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChatListFiltering.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChatListFiltering.swift @@ -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 { - 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() 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 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: ) } } -} +} \ No newline at end of file diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChatOnlineMembers.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChatOnlineMembers.swift index aeb9e859..12eecda1 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChatOnlineMembers.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChatOnlineMembers.swift @@ -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 } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/Communities.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/Communities.swift index 73b408d7..457b2a55 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/Communities.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/Communities.swift @@ -72,7 +72,7 @@ func _internal_exportChatFolder(account: Account, filterId: Int32, title: String } |> castError(ExportChatFolderError.self) |> mapToSignal { inputPeers -> Signal 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 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 in return account.postbox.transaction { transaction -> Signal 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 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 { - 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 mapToSignal { result -> Signal 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() for peer in peers { @@ -306,26 +313,29 @@ func _internal_checkChatFolderLink(account: Account, slug: String) -> Signal 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 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 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 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 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 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 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 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) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ContactToken.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ContactToken.swift index 8a891019..dab523ba 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ContactToken.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ContactToken.swift @@ -26,7 +26,8 @@ func _internal_exportContactToken(account: Account) -> Signal 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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/CreateGroup.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/CreateGroup.swift index 44a28f39..85d9fb79 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/CreateGroup.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/CreateGroup.swift @@ -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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/FindChannelById.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/FindChannelById.swift index adac9d6d..a81731b5 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/FindChannelById.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/FindChannelById.swift @@ -4,7 +4,7 @@ import Postbox import TelegramApi func _internal_findChannelById(accountPeerId: PeerId, postbox: Postbox, network: Network, channelId: Int64) -> Signal { - 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 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 { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/GroupsInCommon.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/GroupsInCommon.swift index c0455444..2cf4cbdd 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/GroupsInCommon.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/GroupsInCommon.swift @@ -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) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/InactiveChannels.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/InactiveChannels.swift index 71cffeee..dceedea3 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/InactiveChannels.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/InactiveChannels.swift @@ -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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/InvitationLinks.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/InvitationLinks.swift index 5f4e7797..c2717753 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/InvitationLinks.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/InvitationLinks.swift @@ -147,7 +147,8 @@ func _internal_editPeerExportedInvitation(account: Account, peerId: PeerId, link |> mapError { _ in return EditPeerExportedInvitationError.generic } |> mapToSignal { result -> Signal 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 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 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)) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinChannel.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinChannel.swift index 94dacbdc..5bf4891b 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinChannel.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinChannel.swift @@ -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 { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinLink.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinLink.swift index ea763de6..e54c3489 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinLink.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinLink.swift @@ -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 mapToSignal { result -> Signal 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 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: []) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ManageChannelDiscussionGroup.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ManageChannelDiscussionGroup.swift index c55c9393..31d5cbb9 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ManageChannelDiscussionGroup.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ManageChannelDiscussionGroup.swift @@ -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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/NotificationExceptionsList.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/NotificationExceptionsList.swift index 7119da46..022d4a04 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/NotificationExceptionsList.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/NotificationExceptionsList.swift @@ -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) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/NotificationSoundList.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/NotificationSoundList.swift index 2ea20ee4..1dd9c607 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/NotificationSoundList.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/NotificationSoundList.swift @@ -180,7 +180,8 @@ func requestNotificationSoundList(network: Network, hash: Int64) -> Signal 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 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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerAdmins.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerAdmins.swift index 2a3dca75..1adef9f7 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerAdmins.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerAdmins.swift @@ -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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerPhotoUpdater.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerPhotoUpdater.swift index e38ab757..d83df9c8 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerPhotoUpdater.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerPhotoUpdater.swift @@ -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 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 { 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 in return .complete() } |> mapToSignal { photo -> Signal 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([]) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/RecentPeers.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/RecentPeers.swift index aed28a84..c4de6ebe 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/RecentPeers.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/RecentPeers.swift @@ -68,7 +68,8 @@ public func _internal_managedUpdatedRecentPeers(accountPeerId: PeerId, postbox: |> mapToSignal { result -> Signal 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 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) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/RemovePeerChat.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/RemovePeerChat.swift index 9c6d805d..1489e30d 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/RemovePeerChat.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/RemovePeerChat.swift @@ -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 { 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 { + 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) + } + } +} diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ReportPeer.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ReportPeer.swift index 5d84874f..54ede971 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ReportPeer.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ReportPeer.swift @@ -9,7 +9,7 @@ func _internal_reportPeer(account: Account, peerId: PeerId) -> Signal Signal 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 in return .single(nil) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/RequestUserPhotos.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/RequestUserPhotos.swift index 1c8f4b2b..f2236faf 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/RequestUserPhotos.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/RequestUserPhotos.swift @@ -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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ResolvePeerByName.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ResolvePeerByName.swift index 26a20c0e..2e290468 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ResolvePeerByName.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ResolvePeerByName.swift @@ -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) { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/SavedMusic.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/SavedMusic.swift index 62dc50b2..c1d6b785 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/SavedMusic.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/SavedMusic.swift @@ -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 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 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) } } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/SearchPeers.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/SearchPeers.swift index 1e924f8f..fbbb62a2 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/SearchPeers.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/SearchPeers.swift @@ -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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/SupportPeerId.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/SupportPeerId.swift index d234bd6a..6de473b7 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/SupportPeerId.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/SupportPeerId.swift @@ -15,7 +15,8 @@ func _internal_supportPeerId(account: Account) -> Signal { |> mapToSignal { support -> Signal 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) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/TelegramEnginePeers.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/TelegramEnginePeers.swift index 2c246af2..e1ec601d 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/TelegramEnginePeers.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/TelegramEnginePeers.swift @@ -612,6 +612,10 @@ public extension TelegramEngine { } |> ignoreValues } + + public func getFutureCreatorAfterLeave(peerId: EnginePeer.Id) -> Signal { + return _internal_getFutureCreatorAfterLeave(account: self.account, peerId: peerId) + } public func terminateSecretChat(peerId: PeerId, requestRemoteHistoryRemoval: Bool) -> Signal { return self.account.postbox.transaction { transaction -> Void in @@ -1648,7 +1652,7 @@ public extension TelegramEngine { } public func getCollectibleUsernameInfo(username: String) -> Signal { - 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 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 { - 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 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 { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdateCachedPeerData.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdateCachedPeerData.swift index 7786b7ae..7e9292da 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdateCachedPeerData.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdateCachedPeerData.swift @@ -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 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 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) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdateGroupSpecificStickerset.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdateGroupSpecificStickerset.swift index 047910c5..42cd78ee 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdateGroupSpecificStickerset.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdateGroupSpecificStickerset.swift @@ -14,7 +14,7 @@ func _internal_updateGroupSpecificStickerset(postbox: Postbox, network: Network, |> mapToSignal { peer -> Signal 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 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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdatePeerInfo.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdatePeerInfo.swift index 2d01695c..e2525e7b 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdatePeerInfo.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdatePeerInfo.swift @@ -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 diff --git a/submodules/TelegramCore/Sources/TelegramEngine/PeersNearby/PeersNearby.swift b/submodules/TelegramCore/Sources/TelegramEngine/PeersNearby/PeersNearby.swift index ac04a7b4..39b45bcc 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/PeersNearby/PeersNearby.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/PeersNearby/PeersNearby.swift @@ -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 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 } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Privacy/BlockedPeersContext.swift b/submodules/TelegramCore/Sources/TelegramEngine/Privacy/BlockedPeersContext.swift index dbfba915..93e40132 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Privacy/BlockedPeersContext.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Privacy/BlockedPeersContext.swift @@ -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)) } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Privacy/RecentAccountSession.swift b/submodules/TelegramCore/Sources/TelegramEngine/Privacy/RecentAccountSession.swift index ecc0e9c3..8b0570c6 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Privacy/RecentAccountSession.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Privacy/RecentAccountSession.swift @@ -104,7 +104,8 @@ public struct RecentAccountSession: Equatable { extension RecentAccountSession { init(apiAuthorization: Api.Authorization) { switch apiAuthorization { - case let .authorization(flags, hash, deviceModel, platform, systemVersion, apiId, appName, appVersion, dateCreated, dateActive, ip, country, region): + case let .authorization(authorizationData): + let (flags, hash, deviceModel, platform, systemVersion, apiId, appName, appVersion, dateCreated, dateActive, ip, country, region) = (authorizationData.flags, authorizationData.hash, authorizationData.deviceModel, authorizationData.platform, authorizationData.systemVersion, authorizationData.apiId, authorizationData.appName, authorizationData.appVersion, authorizationData.dateCreated, authorizationData.dateActive, authorizationData.ip, authorizationData.country, authorizationData.region) var accountSessionFlags: AccountSessionFlags = [] if (flags & (1 << 1)) != 0 { accountSessionFlags.insert(.isOfficial) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Privacy/RecentAccountSessions.swift b/submodules/TelegramCore/Sources/TelegramEngine/Privacy/RecentAccountSessions.swift index ed6e50d6..a221c3a1 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Privacy/RecentAccountSessions.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Privacy/RecentAccountSessions.swift @@ -13,7 +13,8 @@ func requestRecentAccountSessions(account: Account) -> Signal<([RecentAccountSes var sessions: [RecentAccountSession] = [] var ttlDays: Int32 = 1 switch result { - case let .authorizations(authorizationTtlDays, authorizations): + case let .authorizations(authorizationsData): + let (authorizationTtlDays, authorizations) = (authorizationsData.authorizationTtlDays, authorizationsData.authorizations) for authorization in authorizations { sessions.append(RecentAccountSession(apiAuthorization: authorization)) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Privacy/RecentWebSessions.swift b/submodules/TelegramCore/Sources/TelegramEngine/Privacy/RecentWebSessions.swift index 7e97b2f9..e0910f05 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Privacy/RecentWebSessions.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Privacy/RecentWebSessions.swift @@ -30,12 +30,14 @@ func webSessions(network: Network) -> Signal<([WebAuthorization], [PeerId: Peer] var sessions: [WebAuthorization] = [] var peers:[PeerId : Peer] = [:] switch result { - case let .webAuthorizations(authorizations, users): + case let .webAuthorizations(webAuthorizationsData): + let (authorizations, users) = (webAuthorizationsData.authorizations, webAuthorizationsData.users) for authorization in authorizations { switch authorization { - case let .webAuthorization(hash, botId, domain, browser, platform, dateCreated, dateActive, ip, region): + case let .webAuthorization(webAuthorizationData): + let (hash, botId, domain, browser, platform, dateCreated, dateActive, ip, region) = (webAuthorizationData.hash, webAuthorizationData.botId, webAuthorizationData.domain, webAuthorizationData.browser, webAuthorizationData.platform, webAuthorizationData.dateCreated, webAuthorizationData.dateActive, webAuthorizationData.ip, webAuthorizationData.region) sessions.append(WebAuthorization(hash: hash, botId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(botId)), domain: domain, browser: browser, platform: platform, dateCreated: dateCreated, dateActive: dateActive, ip: ip, region: region)) - + } } for user in users { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Privacy/UpdatedAccountPrivacySettings.swift b/submodules/TelegramCore/Sources/TelegramEngine/Privacy/UpdatedAccountPrivacySettings.swift index 95f208d4..abf8a381 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Privacy/UpdatedAccountPrivacySettings.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Privacy/UpdatedAccountPrivacySettings.swift @@ -16,7 +16,8 @@ func _internal_updateGlobalPrivacySettings(account: Account) -> Signal Signal mapToSignal { lastSeenPrivacy, groupPrivacy, voiceCallPrivacy, voiceCallP2P, profilePhotoPrivacy, forwardPrivacy, phoneNumberPrivacy, phoneDiscoveryPrivacy, voiceMessagesPrivacy, bioPrivacy, birthdayPrivacy, giftsAutoSavePrivacy, noPaidMessagesPrivacy, savedMusicPrivacy, autoremoveTimeout, globalPrivacySettings, messageAutoremoveTimeout -> Signal in let accountTimeoutSeconds: Int32 switch autoremoveTimeout { - case let .accountDaysTTL(days): - accountTimeoutSeconds = days * 24 * 60 * 60 + case let .accountDaysTTL(accountDaysTTL): + accountTimeoutSeconds = accountDaysTTL.days * 24 * 60 * 60 } let messageAutoremoveSeconds: Int32? switch messageAutoremoveTimeout { - case let .defaultHistoryTTL(period): + case let .defaultHistoryTTL(defaultHistoryTTLData): + let period = defaultHistoryTTLData.period if period != 0 { messageAutoremoveSeconds = period } else { @@ -111,49 +113,56 @@ func _internal_requestAccountPrivacySettings(account: Account) -> Signal Signal Signal Signal Signal retryRequest |> ignoreValues } func _internal_updateAccountRemovalTimeout(account: Account, timeout: Int32) -> Signal { - return account.network.request(Api.functions.account.setAccountTTL(ttl: .accountDaysTTL(days: timeout / (24 * 60 * 60)))) + return account.network.request(Api.functions.account.setAccountTTL(ttl: .accountDaysTTL(Api.AccountDaysTTL.Cons_accountDaysTTL(days: timeout / (24 * 60 * 60))))) |> retryRequest |> mapToSignal { _ -> Signal in return .complete() @@ -529,10 +547,10 @@ func _internal_updateSelectiveAccountPrivacySettings(account: Account, type: Upd let enablePeers = apiUserAndGroupIds(peerIds: enableFor) if !enablePeers.users.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowUsers(users: apiInputUsers(transaction: transaction, peerIds: enablePeers.users))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowUsers(.init(users: apiInputUsers(transaction: transaction, peerIds: enablePeers.users)))) } if !enablePeers.groups.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowChatParticipants(chats: enablePeers.groups.map({ $0.id._internalGetInt64Value() }))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowChatParticipants(.init(chats: enablePeers.groups.map({ $0.id._internalGetInt64Value() })))) } rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowAll) @@ -550,17 +568,17 @@ func _internal_updateSelectiveAccountPrivacySettings(account: Account, type: Upd let disablePeers = apiUserAndGroupIds(peerIds: disableFor) if !enablePeers.users.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowUsers(users: apiInputUsers(transaction: transaction, peerIds: enablePeers.users))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowUsers(.init(users: apiInputUsers(transaction: transaction, peerIds: enablePeers.users)))) } if !enablePeers.groups.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowChatParticipants(chats: enablePeers.groups.map({ $0.id._internalGetInt64Value() }))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowChatParticipants(.init(chats: enablePeers.groups.map({ $0.id._internalGetInt64Value() })))) } if !disablePeers.users.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowUsers(users: apiInputUsers(transaction: transaction, peerIds: disablePeers.users))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowUsers(.init(users: apiInputUsers(transaction: transaction, peerIds: disablePeers.users)))) } if !disablePeers.groups.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowChatParticipants(chats: disablePeers.groups.map({ $0.id._internalGetInt64Value() }))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowChatParticipants(.init(chats: disablePeers.groups.map({ $0.id._internalGetInt64Value() })))) } rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowContacts) @@ -574,10 +592,10 @@ func _internal_updateSelectiveAccountPrivacySettings(account: Account, type: Upd let disablePeers = apiUserAndGroupIds(peerIds: disableFor) if !disablePeers.users.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowUsers(users: apiInputUsers(transaction: transaction, peerIds: disablePeers.users))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowUsers(.init(users: apiInputUsers(transaction: transaction, peerIds: disablePeers.users)))) } if !disablePeers.groups.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowChatParticipants(chats: disablePeers.groups.map({ $0.id._internalGetInt64Value() }))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowChatParticipants(.init(chats: disablePeers.groups.map({ $0.id._internalGetInt64Value() })))) } rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowAll) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Resolve/DeepLinkInfo.swift b/submodules/TelegramCore/Sources/TelegramEngine/Resolve/DeepLinkInfo.swift index 6d0f3788..3ac9f099 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Resolve/DeepLinkInfo.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Resolve/DeepLinkInfo.swift @@ -15,7 +15,8 @@ func _internal_getDeepLinkInfo(network: Network, path: String) -> Signal mapError { error -> GrantSecureIdAccessError in return .generic } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/RequestSecureIdForm.swift b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/RequestSecureIdForm.swift index 5d091941..292bfd21 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/RequestSecureIdForm.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/RequestSecureIdForm.swift @@ -44,7 +44,8 @@ private func parseSecureValueType(_ type: Api.SecureValueType, selfie: Bool, tra private func parseSecureData(_ value: Api.SecureData) -> (data: Data, hash: Data, secret: Data) { switch value { - case let .secureData(data, dataHash, secret): + case let .secureData(secureDataData): + let (data, dataHash, secret) = (secureDataData.data, secureDataData.dataHash, secureDataData.secret) return (data.makeData(), dataHash.makeData(), secret.makeData()) } } @@ -55,7 +56,8 @@ struct ParsedSecureValue { func parseSecureValue(context: SecureIdAccessContext, value: Api.SecureValue, errors: [Api.SecureValueError]) -> ParsedSecureValue? { switch value { - case let .secureValue(_, type, data, frontSide, reverseSide, selfie, translation, files, plainData, hash): + case let .secureValue(secureValueData): + let (_, type, data, frontSide, reverseSide, selfie, translation, files, plainData, hash) = (secureValueData.flags, secureValueData.type, secureValueData.data, secureValueData.frontSide, secureValueData.reverseSide, secureValueData.selfie, secureValueData.translation, secureValueData.files, secureValueData.plainData, secureValueData.hash) let parsedFileReferences = files.flatMap { $0.compactMap(SecureIdFileReference.init) } ?? [] let parsedFiles = parsedFileReferences.map(SecureIdVerificationDocumentReference.remote) let parsedTranslationReferences = translation.flatMap { $0.compactMap(SecureIdFileReference.init) } ?? [] @@ -204,7 +206,8 @@ func parseSecureValue(context: SecureIdAccessContext, value: Api.SecureValue, er return nil } switch publicData { - case let .securePlainPhone(phone): + case let .securePlainPhone(securePlainPhoneData): + let (phone) = (securePlainPhoneData.phone) value = .phone(SecureIdPhoneValue(phone: phone)) default: return nil @@ -214,7 +217,8 @@ func parseSecureValue(context: SecureIdAccessContext, value: Api.SecureValue, er return nil } switch publicData { - case let .securePlainEmail(email): + case let .securePlainEmail(securePlainEmailData): + let (email) = (securePlainEmailData.email) value = .email(SecureIdEmailValue(email: email)) default: return nil @@ -262,17 +266,21 @@ public func requestSecureIdForm(accountPeerId: PeerId, postbox: Postbox, network |> mapToSignal { result -> Signal in return postbox.transaction { transaction -> EncryptedSecureIdForm in switch result { - case let .authorizationForm(_, requiredTypes, values, errors, users, termsUrl): + case let .authorizationForm(authorizationFormData): + let (_, requiredTypes, values, errors, users, termsUrl) = (authorizationFormData.flags, authorizationFormData.requiredTypes, authorizationFormData.values, authorizationFormData.errors, authorizationFormData.users, authorizationFormData.privacyPolicyUrl) updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(users: users)) return EncryptedSecureIdForm(peerId: peerId, requestedFields: requiredTypes.map { requiredType in switch requiredType { - case let .secureRequiredType(flags, type): + case let .secureRequiredType(secureRequiredTypeData): + let (flags, type) = (secureRequiredTypeData.flags, secureRequiredTypeData.type) return .just(parseSecureValueType(type, selfie: (flags & 1 << 1) != 0, translation: (flags & 1 << 2) != 0, nativeNames: (flags & 1 << 0) != 0)) - case let .secureRequiredTypeOneOf(types): + case let .secureRequiredTypeOneOf(secureRequiredTypeOneOfData): + let (types) = (secureRequiredTypeOneOfData.types) let parsedInnerTypes = types.compactMap { innerType -> SecureIdRequestedFormFieldValue? in switch innerType { - case let .secureRequiredType(flags, type): + case let .secureRequiredType(secureRequiredTypeData): + let (flags, type) = (secureRequiredTypeData.flags, secureRequiredTypeData.type) return parseSecureValueType(type, selfie: (flags & 1 << 1) != 0, translation: (flags & 1 << 2) != 0, nativeNames: (flags & 1 << 0) != 0) case .secureRequiredTypeOneOf: return nil diff --git a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SaveSecureIdValue.swift b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SaveSecureIdValue.swift index dc8d6bcb..818d662b 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SaveSecureIdValue.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SaveSecureIdValue.swift @@ -89,9 +89,9 @@ func decryptedSecureValueData(context: SecureIdValueAccessContext, encryptedData private func apiInputSecretFile(_ file: SecureIdVerificationDocumentReference) -> Api.InputSecureFile { switch file { case let .remote(file): - return Api.InputSecureFile.inputSecureFile(id: file.id, accessHash: file.accessHash) + return Api.InputSecureFile.inputSecureFile(.init(id: file.id, accessHash: file.accessHash)) case let .uploaded(file): - return Api.InputSecureFile.inputSecureFileUploaded(id: file.id, parts: file.parts, md5Checksum: file.md5Checksum, fileHash: Buffer(data: file.fileHash), secret: Buffer(data: file.encryptedSecret)) + return Api.InputSecureFile.inputSecureFileUploaded(.init(id: file.id, parts: file.parts, md5Checksum: file.md5Checksum, fileHash: Buffer(data: file.fileHash), secret: Buffer(data: file.encryptedSecret))) } } @@ -142,9 +142,9 @@ private func inputSecureIdValueData(value: SecureIdValue) -> InputSecureIdValueD let (dict, fileReferences, translations) = rentalAgreement.serialize() return InputSecureIdValueData(type: .secureValueTypeRentalAgreement, dict: dict, fileReferences: fileReferences, translationReferences: translations, frontSideReference: nil, backSideReference: nil, selfieReference: nil, publicData: nil) case let .phone(phone): - return InputSecureIdValueData(type: .secureValueTypePhone, dict: nil, fileReferences: [], translationReferences: [], frontSideReference: nil, backSideReference: nil, selfieReference: nil, publicData: .securePlainPhone(phone: phone.phone)) + return InputSecureIdValueData(type: .secureValueTypePhone, dict: nil, fileReferences: [], translationReferences: [], frontSideReference: nil, backSideReference: nil, selfieReference: nil, publicData: .securePlainPhone(.init(phone: phone.phone))) case let .email(email): - return InputSecureIdValueData(type: .secureValueTypeEmail, dict: nil, fileReferences: [], translationReferences: [], frontSideReference: nil, backSideReference: nil, selfieReference: nil, publicData: .securePlainEmail(email: email.email)) + return InputSecureIdValueData(type: .secureValueTypeEmail, dict: nil, fileReferences: [], translationReferences: [], frontSideReference: nil, backSideReference: nil, selfieReference: nil, publicData: .securePlainEmail(.init(email: email.email))) } } @@ -175,7 +175,7 @@ private func makeInputSecureValue(context: SecureIdAccessContext, value: SecureI } else { return nil } - secureData = .secureData(data: Buffer(data: encryptedData.data), dataHash: Buffer(data: encryptedData.dataHash), secret: Buffer(data: encryptedData.encryptedSecret)) + secureData = .secureData(.init(data: Buffer(data: encryptedData.data), dataHash: Buffer(data: encryptedData.dataHash), secret: Buffer(data: encryptedData.encryptedSecret))) } var flags: Int32 = 0 @@ -205,7 +205,7 @@ private func makeInputSecureValue(context: SecureIdAccessContext, value: SecureI flags |= 1 << 5 } - return Api.InputSecureValue.inputSecureValue(flags: flags, type: inputData.type, data: secureData, frontSide: inputData.frontSideReference.flatMap(apiInputSecretFile), reverseSide: inputData.backSideReference.flatMap(apiInputSecretFile), selfie: inputData.selfieReference.flatMap(apiInputSecretFile), translation: translations, files: files, plainData: inputData.publicData) + return Api.InputSecureValue.inputSecureValue(.init(flags: flags, type: inputData.type, data: secureData, frontSide: inputData.frontSideReference.flatMap(apiInputSecretFile), reverseSide: inputData.backSideReference.flatMap(apiInputSecretFile), selfie: inputData.selfieReference.flatMap(apiInputSecretFile), translation: translations, files: files, plainData: inputData.publicData)) } public func saveSecureIdValue(postbox: Postbox, network: Network, context: SecureIdAccessContext, value: SecureIdValue, uploadedFiles: [Data: Data]) -> Signal { @@ -286,7 +286,7 @@ public func dropSecureId(network: Network, currentPassword: String) -> Signal Signal map { _ in } |> mapError { _ in return AuthorizationPasswordVerificationError.generic diff --git a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureFileMediaResource.swift b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureFileMediaResource.swift index c5640b33..40fa0d25 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureFileMediaResource.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureFileMediaResource.swift @@ -5,7 +5,7 @@ import TelegramApi extension SecureFileMediaResource: TelegramCloudMediaResource, TelegramMultipartFetchableResource, EncryptedMediaResource { func apiInputLocation(fileReference: Data?) -> Api.InputFileLocation? { - return Api.InputFileLocation.inputSecureFileLocation(id: self.file.id, accessHash: self.file.accessHash) + return Api.InputFileLocation.inputSecureFileLocation(.init(id: self.file.id, accessHash: self.file.accessHash)) } public func decrypt(data: Data, params: Any) -> Data? { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdConfiguration.swift b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdConfiguration.swift index d0ef354b..ece6a191 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdConfiguration.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdConfiguration.swift @@ -27,9 +27,11 @@ public func secureIdConfiguration(postbox: Postbox, network: Network) -> Signal< assertionFailure() return .complete() } - case let .passportConfig(hash, countriesLangs): + case let .passportConfig(passportConfigData): + let (hash, countriesLangs) = (passportConfigData.hash, passportConfigData.countriesLangs) switch countriesLangs { - case let .dataJSON(data): + case let .dataJSON(dataJSONData): + let data = dataJSONData.data let value = SecureIdConfiguration(jsonString: data) parsed = CachedSecureIdConfiguration(value: value, hash: hash) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdDataTypes.swift b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdDataTypes.swift index 9f165c72..b6394794 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdDataTypes.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdDataTypes.swift @@ -38,7 +38,8 @@ public enum SecureIdGender { extension SecureIdFileReference { init?(apiFile: Api.SecureFile) { switch apiFile { - case let .secureFile(id, accessHash, size, dcId, date, fileHash, secret): + case let .secureFile(secureFileData): + let (id, accessHash, size, dcId, date, fileHash, secret) = (secureFileData.id, secureFileData.accessHash, secureFileData.size, secureFileData.dcId, secureFileData.date, secureFileData.fileHash, secureFileData.secret) self.init(id: id, accessHash: accessHash, size: size, datacenterId: dcId, timestamp: date, fileHash: fileHash.makeData(), encryptedSecret: secret.makeData()) case .secureFileEmpty: return nil diff --git a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdValueContentError.swift b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdValueContentError.swift index 01b395bf..56e76f3d 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdValueContentError.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdValueContentError.swift @@ -71,9 +71,11 @@ func parseSecureIdValueContentErrors(dataHash: Data?, fileHashes: Set, sel var result: [SecureIdValueContentErrorKey: SecureIdValueContentError] = [:] for error in errors { switch error { - case let .secureValueError(type, _, text): + case let .secureValueError(secureValueErrorData): + let (type, _, text) = (secureValueErrorData.type, secureValueErrorData.hash, secureValueErrorData.text) result[.value(SecureIdValueKey(apiType: type))] = text - case let .secureValueErrorData(type, errorDataHash, field, text): + case let .secureValueErrorData(secureValueErrorDataData): + let (type, errorDataHash, field, text) = (secureValueErrorDataData.type, secureValueErrorDataData.dataHash, secureValueErrorDataData.field, secureValueErrorDataData.text) if errorDataHash.makeData() == dataHash { switch type { case .secureValueTypePersonalDetails: @@ -104,11 +106,13 @@ func parseSecureIdValueContentErrors(dataHash: Data?, fileHashes: Set, sel break } } - case let .secureValueErrorFile(_, fileHash, text): + case let .secureValueErrorFile(secureValueErrorFileData): + let (_, fileHash, text) = (secureValueErrorFileData.type, secureValueErrorFileData.fileHash, secureValueErrorFileData.text) if fileHashes.contains(fileHash.makeData()) { result[.file(hash: fileHash.makeData())] = text } - case let .secureValueErrorFiles(_, fileHash, text): + case let .secureValueErrorFiles(secureValueErrorFilesData): + let (_, fileHash, text) = (secureValueErrorFilesData.type, secureValueErrorFilesData.fileHash, secureValueErrorFilesData.text) var containsAll = true loop: for hash in fileHash { if !fileHashes.contains(hash.makeData()) { @@ -119,11 +123,13 @@ func parseSecureIdValueContentErrors(dataHash: Data?, fileHashes: Set, sel if containsAll { result[.files(hashes: Set(fileHash.map { $0.makeData() }))] = text } - case let .secureValueErrorTranslationFile(_, fileHash, text): + case let .secureValueErrorTranslationFile(secureValueErrorTranslationFileData): + let (_, fileHash, text) = (secureValueErrorTranslationFileData.type, secureValueErrorTranslationFileData.fileHash, secureValueErrorTranslationFileData.text) if fileHashes.contains(fileHash.makeData()) { result[.translationFile(hash: fileHash.makeData())] = text } - case let .secureValueErrorTranslationFiles(_, fileHash, text): + case let .secureValueErrorTranslationFiles(secureValueErrorTranslationFilesData): + let (_, fileHash, text) = (secureValueErrorTranslationFilesData.type, secureValueErrorTranslationFilesData.fileHash, secureValueErrorTranslationFilesData.text) var containsAll = true loop: for hash in fileHash { if !fileHashes.contains(hash.makeData()) { @@ -134,15 +140,18 @@ func parseSecureIdValueContentErrors(dataHash: Data?, fileHashes: Set, sel if containsAll { result[.translationFiles(hashes: Set(fileHash.map { $0.makeData() }))] = text } - case let .secureValueErrorSelfie(_, fileHash, text): + case let .secureValueErrorSelfie(secureValueErrorSelfieData): + let (_, fileHash, text) = (secureValueErrorSelfieData.type, secureValueErrorSelfieData.fileHash, secureValueErrorSelfieData.text) if selfieHash == fileHash.makeData() { result[.selfie(hash: fileHash.makeData())] = text } - case let .secureValueErrorFrontSide(_, fileHash, text): + case let .secureValueErrorFrontSide(secureValueErrorFrontSideData): + let (_, fileHash, text) = (secureValueErrorFrontSideData.type, secureValueErrorFrontSideData.fileHash, secureValueErrorFrontSideData.text) if frontSideHash == fileHash.makeData() { result[.frontSide(hash: fileHash.makeData())] = text } - case let .secureValueErrorReverseSide(_, fileHash, text): + case let .secureValueErrorReverseSide(secureValueErrorReverseSideData): + let (_, fileHash, text) = (secureValueErrorReverseSideData.type, secureValueErrorReverseSideData.fileHash, secureValueErrorReverseSideData.text) if backSideHash == fileHash.makeData() { result[.backSide(hash: fileHash.makeData())] = text } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/UploadSecureIdFile.swift b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/UploadSecureIdFile.swift index c8f7c312..fbc091f8 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/UploadSecureIdFile.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/UploadSecureIdFile.swift @@ -112,12 +112,8 @@ public func uploadSecureIdFile(context: SecureIdAccessContext, postbox: Postbox, switch result { case let .progress(value): return .single(.progress(value)) - case let .inputFile(file): - if case let .inputFile(id, parts, _, md5Checksum) = file { - return .single(.result(UploadedSecureIdFile(id: id, parts: parts, md5Checksum: md5Checksum, fileHash: encryptedData.hash, encryptedSecret: encryptedData.encryptedSecret), encryptedData.data)) - } else { - return .fail(.generic) - } + case let .inputFile(.inputFile(fileData)): + return .single(.result(UploadedSecureIdFile(id: fileData.id, parts: fileData.parts, md5Checksum: fileData.md5Checksum, fileHash: encryptedData.hash, encryptedSecret: encryptedData.encryptedSecret), encryptedData.data)) default: return .fail(.generic) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/VerifySecureIdValue.swift b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/VerifySecureIdValue.swift index 400feb52..75a8d7c6 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/VerifySecureIdValue.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/VerifySecureIdValue.swift @@ -19,7 +19,7 @@ public struct SecureIdPreparePhoneVerificationPayload { } public func secureIdPreparePhoneVerification(network: Network, value: SecureIdPhoneValue) -> Signal { - return network.request(Api.functions.account.sendVerifyPhoneCode(phoneNumber: value.phone, settings: .codeSettings(flags: 0, logoutTokens: nil, token: nil, appSandbox: nil)), automaticFloodWait: false) + return network.request(Api.functions.account.sendVerifyPhoneCode(phoneNumber: value.phone, settings: .codeSettings(.init(flags: 0, logoutTokens: nil, token: nil, appSandbox: nil))), automaticFloodWait: false) |> mapError { error -> SecureIdPreparePhoneVerificationError in if error.errorDescription.hasPrefix("FLOOD_WAIT") { return .flood @@ -28,7 +28,8 @@ public func secureIdPreparePhoneVerification(network: Network, value: SecureIdPh } |> mapToSignal { sentCode -> Signal 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) return .single(SecureIdPreparePhoneVerificationPayload(type: SentAuthorizationCodeType(apiType: type), nextType: nextType.flatMap(AuthorizationCodeNextType.init), timeout: timeout, phone: value.phone, phoneCodeHash: phoneCodeHash)) case .sentCodeSuccess, .sentCodePaymentRequired: return .never() @@ -84,7 +85,8 @@ public func secureIdPrepareEmailVerification(network: Network, value: SecureIdEm } |> map { sentCode -> SecureIdPrepareEmailVerificationPayload in switch sentCode { - case .sentEmailCode(_, let length): + case let .sentEmailCode(sentEmailCodeData): + let length = sentEmailCodeData.length return SecureIdPrepareEmailVerificationPayload(email: value.email, length: length) } } @@ -97,7 +99,7 @@ public enum SecureIdCommitEmailVerificationError { } public func secureIdCommitEmailVerification(postbox: Postbox, network: Network, context: SecureIdAccessContext, payload: SecureIdPrepareEmailVerificationPayload, code: String) -> Signal { - return network.request(Api.functions.account.verifyEmail(purpose: .emailVerifyPurposePassport, verification: .emailVerificationCode(code: code)), automaticFloodWait: false) + return network.request(Api.functions.account.verifyEmail(purpose: .emailVerifyPurposePassport, verification: .emailVerificationCode(.init(code: code))), automaticFloodWait: false) |> mapError { error -> SecureIdCommitEmailVerificationError in if error.errorDescription.hasPrefix("FLOOD_WAIT") { return .flood diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/ArchivedStickerPacks.swift b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/ArchivedStickerPacks.swift index e9743b26..9684abdb 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/ArchivedStickerPacks.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/ArchivedStickerPacks.swift @@ -42,7 +42,8 @@ func _internal_archivedStickerPacks(account: Account, namespace: ArchivedSticker |> map { result -> [ArchivedStickerPackItem] in var archivedItems: [ArchivedStickerPackItem] = [] switch result { - case let .archivedStickers(_, sets): + case let .archivedStickers(archivedStickersData): + let sets = archivedStickersData.sets for set in sets { let (info, items) = parsePreviewStickerSet(set, namespace: namespace.itemCollectionNamespace) archivedItems.append(ArchivedStickerPackItem(info: info, topItems: items)) @@ -55,7 +56,7 @@ func _internal_archivedStickerPacks(account: Account, namespace: ArchivedSticker } func _internal_removeArchivedStickerPack(account: Account, info: StickerPackCollectionInfo) -> Signal { - return account.network.request(Api.functions.messages.uninstallStickerSet(stickerset: Api.InputStickerSet.inputStickerSetID(id: info.id.id, accessHash: info.accessHash))) + return account.network.request(Api.functions.messages.uninstallStickerSet(stickerset: Api.InputStickerSet.inputStickerSetID(.init(id: info.id.id, accessHash: info.accessHash)))) |> `catch` { _ -> Signal in return .single(.boolFalse) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/ImportStickers.swift b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/ImportStickers.swift index 484b8bf4..ca0da2cf 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/ImportStickers.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/ImportStickers.swift @@ -78,16 +78,17 @@ func _internal_uploadSticker(account: Account, peer: Peer, resource: MediaResour flags |= (1 << 2) } var attributes: [Api.DocumentAttribute] = [] - attributes.append(.documentAttributeSticker(flags: 0, alt: alt, stickerset: .inputStickerSetEmpty, maskCoords: nil)) + attributes.append(.documentAttributeSticker(.init(flags: 0, alt: alt, stickerset: .inputStickerSetEmpty, maskCoords: nil))) if let duration { - attributes.append(.documentAttributeVideo(flags: 0, duration: duration, w: dimensions.width, h: dimensions.height, preloadPrefixSize: nil, videoStartTs: nil, videoCodec: nil)) + attributes.append(.documentAttributeVideo(.init(flags: 0, duration: duration, w: dimensions.width, h: dimensions.height, preloadPrefixSize: nil, videoStartTs: nil, videoCodec: nil))) } - attributes.append(.documentAttributeImageSize(w: dimensions.width, h: dimensions.height)) - return account.network.request(Api.functions.messages.uploadMedia(flags: 0, businessConnectionId: nil, peer: inputPeer, media: Api.InputMedia.inputMediaUploadedDocument(flags: flags, file: file, thumb: thumbnailFile, mimeType: mimeType, attributes: attributes, stickers: nil, videoCover: nil, videoTimestamp: nil, ttlSeconds: nil))) + attributes.append(.documentAttributeImageSize(.init(w: dimensions.width, h: dimensions.height))) + return account.network.request(Api.functions.messages.uploadMedia(flags: 0, businessConnectionId: nil, peer: inputPeer, media: Api.InputMedia.inputMediaUploadedDocument(.init(flags: flags, file: file, thumb: thumbnailFile, mimeType: mimeType, attributes: attributes, stickers: nil, videoCover: nil, videoTimestamp: nil, ttlSeconds: nil)))) |> mapError { _ -> UploadStickerError in return .generic } |> mapToSignal { media -> Signal in switch media { - case let .messageMediaDocument(_, document, altDocuments, _, _, _): + case let .messageMediaDocument(messageMediaDocumentData): + let (document, altDocuments) = (messageMediaDocumentData.document, messageMediaDocumentData.altDocuments) if let document = document, let file = telegramMediaFileFromApiDocument(document, altDocuments: altDocuments), let uploadedResource = file.resource as? CloudDocumentMediaResource { account.postbox.mediaBox.copyResourceData(from: resource.id, to: uploadedResource.id, synchronous: true) if let thumbnail, let previewRepresentation = file.previewRepresentations.first(where: { $0.dimensions == PixelDimensions(width: 320, height: 320) }) { @@ -243,12 +244,12 @@ func _internal_createStickerSet(account: Account, title: String, shortName: Stri flags |= (1 << 1) } - inputStickers.append(.inputStickerSetItem(flags: flags, document: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data())), emoji: sticker.emojis.joined(), maskCoords: nil, keywords: sticker.keywords)) + inputStickers.append(.inputStickerSetItem(.init(flags: flags, document: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data()))), emoji: sticker.emojis.joined(), maskCoords: nil, keywords: sticker.keywords))) } var thumbnailDocument: Api.InputDocument? if thumbnail != nil, let resource = resources.last { flags |= (1 << 2) - thumbnailDocument = .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data())) + thumbnailDocument = .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data()))) } if let software = software, !software.isEmpty { flags |= (1 << 3) @@ -388,7 +389,7 @@ func _internal_addStickerToStickerSet(account: Account, packReference: StickerPa if sticker.keywords.count > 0 { flags |= (1 << 1) } - let inputSticker: Api.InputStickerSetItem = .inputStickerSetItem(flags: flags, document: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data())), emoji: sticker.emojis.joined(), maskCoords: nil, keywords: sticker.keywords) + let inputSticker: Api.InputStickerSetItem = .inputStickerSetItem(.init(flags: flags, document: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data()))), emoji: sticker.emojis.joined(), maskCoords: nil, keywords: sticker.keywords)) return account.network.request(Api.functions.stickers.addStickerToSet(stickerset: packReference.apiInputStickerSet, sticker: inputSticker)) |> `catch` { error -> Signal in if error.errorDescription == "FILE_REFERENCE_EXPIRED" { @@ -400,8 +401,8 @@ func _internal_addStickerToStickerSet(account: Account, packReference: StickerPa guard let resource = result.updatedResource as? CloudDocumentMediaResource else { return .fail(MTRpcError(errorCode: 500, errorDescription: "Internal")) } - - let inputSticker: Api.InputStickerSetItem = .inputStickerSetItem(flags: flags, document: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)), emoji: sticker.emojis.joined(), maskCoords: nil, keywords: sticker.keywords) + + let inputSticker: Api.InputStickerSetItem = .inputStickerSetItem(.init(flags: flags, document: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))), emoji: sticker.emojis.joined(), maskCoords: nil, keywords: sticker.keywords)) return account.network.request(Api.functions.stickers.addStickerToSet(stickerset: packReference.apiInputStickerSet, sticker: inputSticker)) } @@ -434,7 +435,7 @@ public enum ReorderStickerError { func _internal_reorderSticker(account: Account, sticker: FileMediaReference, position: Int) -> Signal { return revalidatedSticker(account: account, sticker: sticker, signal: { resource in - return account.network.request(Api.functions.stickers.changeStickerPosition(sticker: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)), position: Int32(position))) + return account.network.request(Api.functions.stickers.changeStickerPosition(sticker: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))), position: Int32(position))) }) |> mapError { error -> ReorderStickerError in return .generic @@ -461,7 +462,7 @@ public enum DeleteStickerError { func _internal_deleteStickerFromStickerSet(account: Account, sticker: FileMediaReference) -> Signal { return revalidatedSticker(account: account, sticker: sticker, signal: { resource in - return account.network.request(Api.functions.stickers.removeStickerFromSet(sticker: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)))) + return account.network.request(Api.functions.stickers.removeStickerFromSet(sticker: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))))) }) |> mapError { error -> DeleteStickerError in return .generic @@ -508,9 +509,9 @@ func _internal_replaceSticker(account: Account, previousSticker: FileMediaRefere if sticker.keywords.count > 0 { flags |= (1 << 1) } - let inputSticker: Api.InputStickerSetItem = .inputStickerSetItem(flags: flags, document: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data())), emoji: sticker.emojis.joined(), maskCoords: nil, keywords: sticker.keywords) + let inputSticker: Api.InputStickerSetItem = .inputStickerSetItem(.init(flags: flags, document: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data()))), emoji: sticker.emojis.joined(), maskCoords: nil, keywords: sticker.keywords)) return revalidatedSticker(account: account, sticker: previousSticker, signal: { previousResource in - return account.network.request(Api.functions.stickers.replaceSticker(sticker: .inputDocument(id: previousResource.fileId, accessHash: previousResource.accessHash, fileReference: Buffer(data: previousResource.fileReference)), newSticker: inputSticker)) + return account.network.request(Api.functions.stickers.replaceSticker(sticker: .inputDocument(.init(id: previousResource.fileId, accessHash: previousResource.accessHash, fileReference: Buffer(data: previousResource.fileReference))), newSticker: inputSticker)) }) |> mapError { error -> ReplaceStickerError in return .generic @@ -543,13 +544,16 @@ func _internal_getMyStickerSets(account: Account) -> Signal<[(StickerPackCollect } var infos: [(StickerPackCollectionInfo, StickerPackItem?)] = [] switch result { - case let .myStickers(_, sets): + case let .myStickers(myStickersData): + let sets = myStickersData.sets for set in sets { switch set { - case let .stickerSetCovered(set, cover): + case let .stickerSetCovered(stickerSetCoveredData): + let (set, cover) = (stickerSetCoveredData.set, stickerSetCoveredData.cover) let namespace: ItemCollectionId.Namespace switch set { - 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 { @@ -564,10 +568,12 @@ func _internal_getMyStickerSets(account: Account) -> Signal<[(StickerPackCollect firstItem = StickerPackItem(index: ItemCollectionItemIndex(index: 0, id: id.id), file: file, indexKeys: []) } infos.append((info, firstItem)) - case let .stickerSetFullCovered(set, _, _, documents): + case let .stickerSetFullCovered(stickerSetFullCoveredData): + let (set, documents) = (stickerSetFullCoveredData.set, stickerSetFullCoveredData.documents) let namespace: ItemCollectionId.Namespace switch set { - 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 { @@ -597,10 +603,12 @@ private func parseStickerSetInfoAndItems(apiStickerSet: Api.messages.StickerSet) switch apiStickerSet { case .stickerSetNotModified: return nil - case let .stickerSet(set, packs, keywords, documents): + case let .stickerSet(stickerSetData): + let (set, packs, keywords, documents) = (stickerSetData.set, stickerSetData.packs, stickerSetData.keywords, stickerSetData.documents) let namespace: ItemCollectionId.Namespace switch set { - 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 { @@ -613,7 +621,8 @@ private func parseStickerSetInfoAndItems(apiStickerSet: Api.messages.StickerSet) var indexKeysByFile: [MediaId: [MemoryBuffer]] = [:] for pack in packs { switch pack { - case let .stickerPack(text, fileIds): + case let .stickerPack(stickerPackData): + let (text, fileIds) = (stickerPackData.emoticon, stickerPackData.documents) let key = ValueBoxKey(text).toMemoryBuffer() for fileId in fileIds { let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: fileId) @@ -627,7 +636,8 @@ private func parseStickerSetInfoAndItems(apiStickerSet: Api.messages.StickerSet) } for keyword in keywords { switch keyword { - case let .stickerKeyword(documentId, texts): + case let .stickerKeyword(stickerKeywordData): + let (documentId, texts) = (stickerKeywordData.documentId, stickerKeywordData.keyword) for text in texts { let key = ValueBoxKey(text).toMemoryBuffer() let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: documentId) @@ -667,8 +677,8 @@ func _internal_getStickerSetShortNameSuggestion(account: Account, title: String) return nil } switch result { - case let .suggestedShortName(shortName): - return shortName + case let .suggestedShortName(suggestedShortNameData): + return suggestedShortNameData.shortName } } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/LoadedStickerPack.swift b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/LoadedStickerPack.swift index b4be25de..03167f9b 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/LoadedStickerPack.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/LoadedStickerPack.swift @@ -11,13 +11,13 @@ extension StickerPackReference { var apiInputStickerSet: Api.InputStickerSet { switch self { case let .id(id, accessHash): - return .inputStickerSetID(id: id, accessHash: accessHash) + return .inputStickerSetID(.init(id: id, accessHash: accessHash)) case let .name(name): - return .inputStickerSetShortName(shortName: name) + return .inputStickerSetShortName(.init(shortName: name)) case .animatedEmoji: return .inputStickerSetAnimatedEmoji case let .dice(emoji): - return .inputStickerSetDice(emoticon: emoji) + return .inputStickerSetDice(.init(emoticon: emoji)) case .animatedEmojiAnimations: return .inputStickerSetAnimatedEmojiAnimations case .premiumGifts: @@ -58,10 +58,12 @@ func updatedRemoteStickerPack(postbox: Postbox, network: Network, reference: Sti switch result { case .stickerSetNotModified: return .complete() - case let .stickerSet(set, packs, keywords, documents): + case let .stickerSet(stickerSetData): + let (set, packs, keywords, documents) = (stickerSetData.set, stickerSetData.packs, stickerSetData.keywords, stickerSetData.documents) let namespace: ItemCollectionId.Namespace switch set { - 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 { @@ -74,7 +76,8 @@ func updatedRemoteStickerPack(postbox: Postbox, network: Network, reference: Sti var indexKeysByFile: [MediaId: [MemoryBuffer]] = [:] for pack in packs { switch pack { - case let .stickerPack(text, fileIds): + case let .stickerPack(stickerPackData): + let (text, fileIds) = (stickerPackData.emoticon, stickerPackData.documents) let key = ValueBoxKey(text).toMemoryBuffer() for fileId in fileIds { let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: fileId) @@ -88,7 +91,8 @@ func updatedRemoteStickerPack(postbox: Postbox, network: Network, reference: Sti } for keyword in keywords { switch keyword { - case let .stickerKeyword(documentId, texts): + case let .stickerKeyword(stickerKeywordData): + let (documentId, texts) = (stickerKeywordData.documentId, stickerKeywordData.keyword) for text in texts { let key = ValueBoxKey(text).toMemoryBuffer() let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: documentId) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/SearchStickers.swift b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/SearchStickers.swift index 450fcc44..a4bb8525 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/SearchStickers.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/SearchStickers.swift @@ -300,18 +300,19 @@ func _internal_searchStickers(account: Account, query: String?, emoticon: [Strin let flags: Int32 = 0 remote = account.network.request(Api.functions.messages.searchStickers(flags: flags, q: query, emoticon: emoticon.joined(separator: ""), langCode: [inputLanguageCode], offset: 0, limit: 128, hash: cached?.hash ?? 0)) |> `catch` { _ -> Signal in - return .single(.foundStickersNotModified(flags: 0, nextOffset: nil)) + return .single(.foundStickersNotModified(.init(flags: 0, nextOffset: nil))) } |> mapToSignal { result -> Signal<(items: [FoundStickerItem], isFinalResult: Bool), NoError> in return account.postbox.transaction { transaction -> (items: [FoundStickerItem], isFinalResult: Bool) in switch result { - case let .foundStickers(_, _, hash, stickers): + case let .foundStickers(foundStickersData): + let (_, _, hash, stickers) = (foundStickersData.flags, foundStickersData.nextOffset, foundStickersData.hash, foundStickersData.stickers) var result: [FoundStickerItem] = [] let currentItemIds = Set(localItems.map { $0.file.fileId }) - + var premiumItems: [FoundStickerItem] = [] var otherItems: [FoundStickerItem] = [] - + for item in localItems { if item.file.isPremiumSticker { premiumItems.append(item) @@ -319,11 +320,11 @@ func _internal_searchStickers(account: Account, query: String?, emoticon: [Strin otherItems.append(item) } } - + var foundItems: [FoundStickerItem] = [] var foundAnimatedItems: [FoundStickerItem] = [] var foundPremiumItems: [FoundStickerItem] = [] - + var files: [TelegramMediaFile] = [] for sticker in stickers { if let file = telegramMediaFileFromApiDocument(sticker, altDocuments: []), let id = file.id { @@ -339,10 +340,10 @@ func _internal_searchStickers(account: Account, query: String?, emoticon: [Strin } } } - + let allPremiumItems = premiumItems + foundPremiumItems let allOtherItems = otherItems + foundAnimatedItems + foundItems - + if isPremium { let batchCount = Int(searchStickersConfiguration.normalStickersPerPremiumCount) if batchCount == 0 { @@ -373,12 +374,12 @@ func _internal_searchStickers(account: Account, query: String?, emoticon: [Strin result.append(contentsOf: allOtherItems) result.append(contentsOf: allPremiumItems.prefix(max(0, Int(searchStickersConfiguration.premiumStickersCount)))) } - + let currentTime = Int32(CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970) if hash != 0, let entry = CodableEntry(CachedStickerQueryResult(items: files, hash: hash, timestamp: currentTime)) { transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerQueryResults, key: CachedStickerQueryResult.cacheKey(cacheKey)), entry: entry) } - + return (result, true) case .foundStickersNotModified: break @@ -394,7 +395,8 @@ func _internal_searchStickers(account: Account, query: String?, emoticon: [Strin |> mapToSignal { result -> Signal<(items: [FoundStickerItem], isFinalResult: Bool), NoError> in return account.postbox.transaction { transaction -> (items: [FoundStickerItem], isFinalResult: Bool) in switch result { - case let .stickers(hash, stickers): + case let .stickers(stickersData): + let (hash, stickers) = (stickersData.hash, stickersData.stickers) var result: [FoundStickerItem] = [] let currentItemIds = Set(localItems.map { $0.file.fileId }) @@ -784,13 +786,14 @@ func _internal_searchStickers(account: Account, category: EmojiSearchCategories. |> mapToSignal { result -> Signal<(items: [FoundStickerItem], isFinalResult: Bool), NoError> in return account.postbox.transaction { transaction -> (items: [FoundStickerItem], isFinalResult: Bool) in switch result { - case let .stickers(hash, stickers): + case let .stickers(stickersData): + let (hash, stickers) = (stickersData.hash, stickersData.stickers) var result: [FoundStickerItem] = [] let currentItemIds = Set(localItems.map { $0.file.fileId }) - + var premiumItems: [FoundStickerItem] = [] var otherItems: [FoundStickerItem] = [] - + for item in localItems { if item.file.isPremiumSticker { premiumItems.append(item) @@ -798,11 +801,11 @@ func _internal_searchStickers(account: Account, category: EmojiSearchCategories. otherItems.append(item) } } - + var foundItems: [FoundStickerItem] = [] var foundAnimatedItems: [FoundStickerItem] = [] var foundPremiumItems: [FoundStickerItem] = [] - + var files: [TelegramMediaFile] = [] for sticker in stickers { if let file = telegramMediaFileFromApiDocument(sticker, altDocuments: []), let id = file.id { @@ -818,10 +821,10 @@ func _internal_searchStickers(account: Account, category: EmojiSearchCategories. } } } - + let allPremiumItems = premiumItems + foundPremiumItems let allOtherItems = otherItems + foundAnimatedItems + foundItems - + if isPremium { let batchCount = Int(searchStickersConfiguration.normalStickersPerPremiumCount) if batchCount == 0 { @@ -852,12 +855,12 @@ func _internal_searchStickers(account: Account, category: EmojiSearchCategories. result.append(contentsOf: allOtherItems) result.append(contentsOf: allPremiumItems.prefix(max(0, Int(searchStickersConfiguration.premiumStickersCount)))) } - + let currentTime = Int32(CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970) if let entry = CodableEntry(CachedStickerQueryResult(items: files, hash: hash, timestamp: currentTime)) { transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerQueryResults, key: CachedStickerQueryResult.cacheKey(query.joined(separator: ""))), entry: entry) } - + return (result, true) case .stickersNotModified: break @@ -953,12 +956,13 @@ func _internal_searchEmoji(account: Account, query: String?, emoticon: [String], let flags: Int32 = 1 << 0 remote = account.network.request(Api.functions.messages.searchStickers(flags: flags, q: query, emoticon: emoticon.joined(separator: ""), langCode: [inputLanguageCode], offset: 0, limit: 128, hash: cached?.hash ?? 0)) |> `catch` { _ -> Signal in - return .single(.foundStickersNotModified(flags: 0, nextOffset: nil)) + return .single(.foundStickersNotModified(.init(flags: 0, nextOffset: nil))) } |> mapToSignal { result -> Signal<(items: [FoundStickerItem], isFinalResult: Bool), NoError> in return account.postbox.transaction { transaction -> (items: [FoundStickerItem], isFinalResult: Bool) in switch result { - case let .foundStickers(_, _, hash, stickers): + case let .foundStickers(foundStickersData): + let (_, _, hash, stickers) = (foundStickersData.flags, foundStickersData.nextOffset, foundStickersData.hash, foundStickersData.stickers) var result: [FoundStickerItem] = localItems var currentItemIds = Set(localItems.map { $0.file.fileId }) @@ -973,12 +977,12 @@ func _internal_searchEmoji(account: Account, query: String?, emoticon: [String], result.append(FoundStickerItem(file: file, stringRepresentations: [])) } } - + let currentTime = Int32(CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970) if let entry = CodableEntry(CachedStickerQueryResult(items: files, hash: hash, timestamp: currentTime)) { transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedEmojiQueryResults, key: CachedStickerQueryResult.cacheKey(cacheKey)), entry: entry) } - + return (result, true) case .foundStickersNotModified: break @@ -995,7 +999,8 @@ func _internal_searchEmoji(account: Account, query: String?, emoticon: [String], switch result { case .emojiListNotModified: return .single(nil) - case let .emojiList(hash, documentIds): + case let .emojiList(emojiListData): + let (hash, documentIds) = (emojiListData.hash, emojiListData.documentId) return TelegramEngine(account: account).stickers.resolveInlineStickers(fileIds: documentIds) |> map { fileMap -> (files: [TelegramMediaFile], hash: Int64)? in var files: [TelegramMediaFile] = [] @@ -1068,7 +1073,8 @@ func _internal_searchStickerSetsRemotely(network: Network, query: String) -> Sig |> mapToSignal { value in var index: Int32 = 1000 switch value { - case let .foundStickerSets(_, sets: sets): + case let .foundStickerSets(foundStickerSetsData): + let (_, sets) = (foundStickerSetsData.hash, foundStickerSetsData.sets) var result = FoundStickerSets() for set in sets { let parsed = parsePreviewStickerSet(set, namespace: Namespaces.ItemCollection.CloudStickerPacks) @@ -1080,7 +1086,7 @@ func _internal_searchStickerSetsRemotely(network: Network, query: String) -> Sig default: break } - + return .complete() } |> `catch` { _ -> Signal in @@ -1094,7 +1100,8 @@ func _internal_searchEmojiSetsRemotely(postbox: Postbox, network: Network, query |> mapToSignal { value in var index: Int32 = 1000 switch value { - case let .foundStickerSets(_, sets: sets): + case let .foundStickerSets(foundStickerSetsData): + let (_, sets) = (foundStickerSetsData.hash, foundStickerSetsData.sets) var result = FoundStickerSets() for set in sets { let parsed = parsePreviewStickerSet(set, namespace: Namespaces.ItemCollection.CloudEmojiPacks) @@ -1106,7 +1113,7 @@ func _internal_searchEmojiSetsRemotely(postbox: Postbox, network: Network, query default: break } - + return .complete() } |> `catch` { _ -> Signal in diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/StickerPack.swift b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/StickerPack.swift index bce87751..06592131 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/StickerPack.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/StickerPack.swift @@ -21,16 +21,20 @@ func telegramStickerPackThumbnailRepresentationFromApiSizes(datacenterId: Int32, var representations: [TelegramMediaImageRepresentation] = [] for size in sizes { switch size { - case let .photoCachedSize(type, w, h, _): + case let .photoCachedSize(photoCachedSizeData): + let (type, w, h) = (photoCachedSizeData.type, photoCachedSizeData.w, photoCachedSizeData.h) let resource = CloudStickerPackThumbnailMediaResource(datacenterId: datacenterId, thumbVersion: thumbVersion, volumeId: nil, localId: nil) representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: resource, progressiveSizes: [], immediateThumbnailData: nil, typeHint: stickerTypeHint(for: type))) - case let .photoSize(type, w, h, _): + case let .photoSize(photoSizeData): + let (type, w, h) = (photoSizeData.type, photoSizeData.w, photoSizeData.h) let resource = CloudStickerPackThumbnailMediaResource(datacenterId: datacenterId, thumbVersion: thumbVersion, volumeId: nil, localId: nil) representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: resource, progressiveSizes: [], immediateThumbnailData: nil, typeHint: stickerTypeHint(for: type))) - case let .photoSizeProgressive(type, w, h, sizes): + case let .photoSizeProgressive(photoSizeProgressiveData): + let (type, w, h, sizes) = (photoSizeProgressiveData.type, photoSizeProgressiveData.w, photoSizeProgressiveData.h, photoSizeProgressiveData.sizes) let resource = CloudStickerPackThumbnailMediaResource(datacenterId: datacenterId, thumbVersion: thumbVersion, volumeId: nil, localId: nil) representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: resource, progressiveSizes: sizes, immediateThumbnailData: nil, typeHint: stickerTypeHint(for: type))) - case let .photoPathSize(_, data): + case let .photoPathSize(photoPathSizeData): + let data = photoPathSizeData.bytes immediateThumbnailData = data.makeData() case .photoStrippedSize: break @@ -44,7 +48,8 @@ func telegramStickerPackThumbnailRepresentationFromApiSizes(datacenterId: Int32, extension StickerPackCollectionInfo { convenience init(apiSet: Api.StickerSet, namespace: ItemCollectionId.Namespace) { switch apiSet { - case let .stickerSet(flags, _, id, accessHash, title, shortName, thumbs, thumbDcId, thumbVersion, thumbDocumentId, count, nHash): + case let .stickerSet(stickerSetData): + let (flags, _, id, accessHash, title, shortName, thumbs, thumbDcId, thumbVersion, thumbDocumentId, count, nHash) = (stickerSetData.flags, stickerSetData.installedDate, stickerSetData.id, stickerSetData.accessHash, stickerSetData.title, stickerSetData.shortName, stickerSetData.thumbs, stickerSetData.thumbDcId, stickerSetData.thumbVersion, stickerSetData.thumbDocumentId, stickerSetData.count, stickerSetData.hash) var setFlags: StickerPackCollectionInfoFlags = StickerPackCollectionInfoFlags() if (flags & (1 << 2)) != 0 { setFlags.insert(.isOfficial) @@ -82,10 +87,10 @@ func _internal_stickerPacksAttachedToMedia(account: Account, media: AnyMediaRefe let inputMedia: Api.InputStickeredMedia let resourceReference: MediaResourceReference if let imageReference = media.concrete(TelegramMediaImage.self), let reference = imageReference.media.reference, case let .cloud(imageId, accessHash, fileReference) = reference, let representation = largestImageRepresentation(imageReference.media.representations) { - inputMedia = .inputStickeredMediaPhoto(id: Api.InputPhoto.inputPhoto(id: imageId, accessHash: accessHash, fileReference: Buffer(data: fileReference ?? Data()))) + inputMedia = .inputStickeredMediaPhoto(.init(id: Api.InputPhoto.inputPhoto(.init(id: imageId, accessHash: accessHash, fileReference: Buffer(data: fileReference ?? Data()))))) resourceReference = imageReference.resourceReference(representation.resource) } else if let fileReference = media.concrete(TelegramMediaFile.self), let resource = fileReference.media.resource as? CloudDocumentMediaResource { - inputMedia = .inputStickeredMediaDocument(id: Api.InputDocument.inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data()))) + inputMedia = .inputStickeredMediaDocument(.init(id: Api.InputDocument.inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data()))))) resourceReference = fileReference.resourceReference(fileReference.media.resource) } else { return .single([]) @@ -101,9 +106,9 @@ func _internal_stickerPacksAttachedToMedia(account: Account, media: AnyMediaRefe let inputMedia: Api.InputStickeredMedia if let resource = reference.updatedResource as? TelegramCloudMediaResourceWithFileReference, let updatedReference = resource.fileReference { if let imageReference = media.concrete(TelegramMediaImage.self), let reference = imageReference.media.reference, case let .cloud(imageId, accessHash, _) = reference, let _ = largestImageRepresentation(imageReference.media.representations) { - inputMedia = .inputStickeredMediaPhoto(id: Api.InputPhoto.inputPhoto(id: imageId, accessHash: accessHash, fileReference: Buffer(data: updatedReference))) + inputMedia = .inputStickeredMediaPhoto(.init(id: Api.InputPhoto.inputPhoto(.init(id: imageId, accessHash: accessHash, fileReference: Buffer(data: updatedReference))))) } else if let fileReference = media.concrete(TelegramMediaFile.self), let resource = fileReference.media.resource as? CloudDocumentMediaResource { - inputMedia = .inputStickeredMediaDocument(id: Api.InputDocument.inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: updatedReference))) + inputMedia = .inputStickeredMediaDocument(.init(id: Api.InputDocument.inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: updatedReference))))) } else { return .single([]) } @@ -118,11 +123,19 @@ func _internal_stickerPacksAttachedToMedia(account: Account, media: AnyMediaRefe } |> map { result -> [StickerPackReference] in return result.map { pack in + let set: Api.StickerSet switch pack { - case let .stickerSetCovered(set, _), let .stickerSetMultiCovered(set, _), let .stickerSetFullCovered(set, _, _, _), let .stickerSetNoCovered(set): - let info = StickerPackCollectionInfo(apiSet: set, namespace: Namespaces.ItemCollection.CloudStickerPacks) - return .id(id: info.id.id, accessHash: info.accessHash) + case let .stickerSetCovered(stickerSetCoveredData): + set = stickerSetCoveredData.set + case let .stickerSetMultiCovered(stickerSetMultiCoveredData): + set = stickerSetMultiCoveredData.set + case let .stickerSetFullCovered(stickerSetFullCoveredData): + set = stickerSetFullCoveredData.set + case let .stickerSetNoCovered(stickerSetNoCoveredData): + set = stickerSetNoCoveredData.set } + let info = StickerPackCollectionInfo(apiSet: set, namespace: Namespaces.ItemCollection.CloudStickerPacks) + return .id(id: info.id.id, accessHash: info.accessHash) } } |> `catch` { _ -> Signal<[StickerPackReference], NoError> in diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/StickerSetInstallation.swift b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/StickerSetInstallation.swift index a806edfb..7c431888 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/StickerSetInstallation.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/StickerSetInstallation.swift @@ -30,16 +30,16 @@ func _internal_requestStickerSet(postbox: Postbox, network: Network, reference: switch reference { case let .name(name): collectionId = nil - input = .inputStickerSetShortName(shortName: name) + input = .inputStickerSetShortName(.init(shortName: name)) case let .id(id, accessHash): collectionId = ItemCollectionId(namespace: Namespaces.ItemCollection.CloudStickerPacks, id: id) - input = .inputStickerSetID(id: id, accessHash: accessHash) + input = .inputStickerSetID(.init(id: id, accessHash: accessHash)) case .animatedEmoji: collectionId = nil input = .inputStickerSetAnimatedEmoji case let .dice(emoji): collectionId = nil - input = .inputStickerSetDice(emoticon: emoji) + input = .inputStickerSetDice(.init(emoticon: emoji)) case .animatedEmojiAnimations: collectionId = nil input = .inputStickerSetAnimatedEmojiAnimations @@ -80,18 +80,21 @@ func _internal_requestStickerSet(postbox: Postbox, network: Network, reference: switch result { case .stickerSetNotModified: return .complete() - case let .stickerSet(set, packs, keywords, documents): + case let .stickerSet(stickerSetData): + let (set, packs, keywords, documents) = (stickerSetData.set, stickerSetData.packs, stickerSetData.keywords, stickerSetData.documents) info = StickerPackCollectionInfo(apiSet: set, namespace: Namespaces.ItemCollection.CloudStickerPacks) switch set { - case let .stickerSet(flags, _, _, _, _, _, _, _, _, _, _, _): + case let .stickerSet(stickerSetData): + let flags = stickerSetData.flags installed = (flags & (1 << 0) != 0) } var indexKeysByFile: [MediaId: [MemoryBuffer]] = [:] for pack in packs { switch pack { - case let .stickerPack(text, fileIds): + case let .stickerPack(stickerPackData): + let (text, fileIds) = (stickerPackData.emoticon, stickerPackData.documents) let key = ValueBoxKey(text).toMemoryBuffer() for fileId in fileIds { let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: fileId) @@ -106,7 +109,8 @@ func _internal_requestStickerSet(postbox: Postbox, network: Network, reference: } for keyword in keywords { switch keyword { - case let .stickerKeyword(documentId, texts): + case let .stickerKeyword(stickerKeywordData): + let (documentId, texts) = (stickerKeywordData.documentId, stickerKeywordData.keyword) for text in texts { let key = ValueBoxKey(text).toMemoryBuffer() let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: documentId) @@ -170,7 +174,7 @@ public final class CoveredStickerSet : Equatable { } func _internal_installStickerSetInteractively(account: Account, info: StickerPackCollectionInfo, items: [ItemCollectionItem]) -> Signal { - return account.network.request(Api.functions.messages.installStickerSet(stickerset: .inputStickerSetID(id: info.id.id, accessHash: info.accessHash), archived: .boolFalse)) |> mapError { _ -> InstallStickerSetError in + return account.network.request(Api.functions.messages.installStickerSet(stickerset: .inputStickerSetID(.init(id: info.id.id, accessHash: info.accessHash)), archived: .boolFalse)) |> mapError { _ -> InstallStickerSetError in return .generic } |> mapToSignal { result -> Signal in @@ -178,22 +182,27 @@ func _internal_installStickerSetInteractively(account: Account, info: StickerPac switch result { case .stickerSetInstallResultSuccess: addResult = .successful - case let .stickerSetInstallResultArchive(sets: archived): + case let .stickerSetInstallResultArchive(stickerSetInstallResultArchiveData): + let archived = stickerSetInstallResultArchiveData.sets var coveredSets: [CoveredStickerSet] = [] for archived in archived { let apiDocuments:[Api.Document] let apiSet:Api.StickerSet switch archived { - case let .stickerSetCovered(set: set, cover: cover): + case let .stickerSetCovered(stickerSetCoveredData): + let (set, cover) = (stickerSetCoveredData.set, stickerSetCoveredData.cover) apiSet = set apiDocuments = [cover] - case let .stickerSetMultiCovered(set: set, covers: covers): + case let .stickerSetMultiCovered(stickerSetMultiCoveredData): + let (set, covers) = (stickerSetMultiCoveredData.set, stickerSetMultiCoveredData.covers) apiSet = set apiDocuments = covers - case let .stickerSetFullCovered(set, _, _, documents): + case let .stickerSetFullCovered(stickerSetFullCoveredData): + let (set, documents) = (stickerSetFullCoveredData.set, stickerSetFullCoveredData.documents) apiSet = set apiDocuments = documents - case let .stickerSetNoCovered(set): + case let .stickerSetNoCovered(stickerSetNoCoveredData): + let set = stickerSetNoCoveredData.set apiSet = set apiDocuments = [] } @@ -243,7 +252,7 @@ func _internal_installStickerSetInteractively(account: Account, info: StickerPac func _internal_uninstallStickerSetInteractively(account: Account, info: StickerPackCollectionInfo) -> Signal { - return account.network.request(Api.functions.messages.uninstallStickerSet(stickerset: .inputStickerSetID(id: info.id.id, accessHash: info.accessHash))) + return account.network.request(Api.functions.messages.uninstallStickerSet(stickerset: .inputStickerSetID(.init(id: info.id.id, accessHash: info.accessHash)))) |> `catch` { _ -> Signal in return .single(.boolFalse) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Themes/ChatThemes.swift b/submodules/TelegramCore/Sources/TelegramEngine/Themes/ChatThemes.swift index cd920db4..8f5a8057 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Themes/ChatThemes.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Themes/ChatThemes.swift @@ -167,9 +167,11 @@ public enum ChatTheme: PostboxCoding, Codable, Equatable { extension ChatTheme { init?(apiChatTheme: Api.ChatTheme) { switch apiChatTheme { - case let .chatTheme(emoticon): + case let .chatTheme(chatThemeData): + let emoticon = chatThemeData.emoticon self = .emoticon(emoticon) - case let .chatThemeUniqueGift(gift, themeSettings): + case let .chatThemeUniqueGift(chatThemeUniqueGiftData): + let (gift, themeSettings) = (chatThemeUniqueGiftData.gift, chatThemeUniqueGiftData.themeSettings) guard let gift = StarGift(apiStarGift: gift) else { return nil } @@ -180,11 +182,11 @@ extension ChatTheme { var apiChatTheme: Api.InputChatTheme { switch self { case let .emoticon(emoticon): - return .inputChatTheme(emoticon: emoticon) + return .inputChatTheme(.init(emoticon: emoticon)) case let .gift(gift, _): switch gift { case let .unique(uniqueGift): - return .inputChatThemeUniqueGift(slug: uniqueGift.slug) + return .inputChatThemeUniqueGift(.init(slug: uniqueGift.slug)) default: fatalError() } @@ -201,7 +203,8 @@ func _internal_getChatThemes(accountManager: AccountManager ([ChatTheme], String?) in switch result { - case let .chatThemes(_, _, themes, chats, users, nextOffset): + case let .chatThemes(chatThemesData): + let (themes, chats, users, nextOffset) = (chatThemesData.themes, chatThemesData.chats, chatThemesData.users, chatThemesData.nextOffset) let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users) updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers) return (themes.compactMap { ChatTheme(apiChatTheme: $0) }, nextOffset) diff --git a/submodules/TelegramCore/Sources/Themes.swift b/submodules/TelegramCore/Sources/Themes.swift index 9bb600e8..4d8b2d41 100644 --- a/submodules/TelegramCore/Sources/Themes.swift +++ b/submodules/TelegramCore/Sources/Themes.swift @@ -17,7 +17,8 @@ public func telegramThemes(postbox: Postbox, network: Network, accountManager: A |> retryRequest |> mapToSignal { result -> Signal<([TelegramTheme], Int64), NoError> in switch result { - case let .themes(hash, themes): + case let .themes(themesData): + let (hash, themes) = (themesData.hash, themesData.themes) let result = themes.compactMap { TelegramTheme(apiTheme: $0) } if result == current { return .complete() @@ -93,7 +94,7 @@ public enum GetThemeError { } public func getTheme(account: Account, slug: String) -> Signal { - return account.network.request(Api.functions.account.getTheme(format: telegramThemeFormat, theme: .inputThemeSlug(slug: slug))) + return account.network.request(Api.functions.account.getTheme(format: telegramThemeFormat, theme: .inputThemeSlug(.init(slug: slug)))) |> mapError { error -> GetThemeError in if error.errorDescription == "THEME_FORMAT_INVALID" { return .unsupported @@ -114,7 +115,7 @@ public enum ThemeUpdatedResult { } private func checkThemeUpdated(network: Network, theme: TelegramTheme) -> Signal { - return network.request(Api.functions.account.getTheme(format: telegramThemeFormat, theme: .inputTheme(id: theme.id, accessHash: theme.accessHash))) + return network.request(Api.functions.account.getTheme(format: telegramThemeFormat, theme: .inputTheme(.init(id: theme.id, accessHash: theme.accessHash)))) |> mapError { _ -> GetThemeError in return .generic } |> map { theme -> ThemeUpdatedResult in return .updated(TelegramTheme(apiTheme: theme)) @@ -139,7 +140,7 @@ private func saveUnsaveTheme(account: Account, accountManager: AccountManager `catch` { _ -> Signal in return .complete() } @@ -161,7 +162,7 @@ private func installTheme(account: Account, theme: TelegramTheme?, baseTheme: Te let inputTheme: Api.InputTheme? if let theme = theme { - inputTheme = .inputTheme(id: theme.id, accessHash: theme.accessHash) + inputTheme = .inputTheme(.init(id: theme.id, accessHash: theme.accessHash)) flags |= 1 << 1 } else { inputTheme = nil @@ -251,8 +252,8 @@ private func uploadTheme(account: Account, resource: MediaResource, thumbnailDat case let .inputFile(file): var flags: Int32 = 0 var thumbnailFile: Api.InputFile? - if let thumbnailResult = thumbnailResult?.content, case let .result(result) = thumbnailResult, case let .inputFile(file) = result { - thumbnailFile = file + if let thumbnailResult = thumbnailResult?.content, case let .result(result) = thumbnailResult, case let .inputFile(thumbFile) = result { + thumbnailFile = thumbFile flags |= 1 << 0 } return account.network.request(Api.functions.account.uploadTheme(flags: flags, file: file, thumb: thumbnailFile, fileName: fileName, mimeType: mimeType)) @@ -302,7 +303,7 @@ public func createTheme(account: Account, title: String, resource: MediaResource switch result { case let .complete(file): if let resource = file.resource as? CloudDocumentMediaResource { - return account.network.request(Api.functions.account.createTheme(flags: flags, slug: "", title: title, document: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)), settings: inputSettings)) + return account.network.request(Api.functions.account.createTheme(flags: flags, slug: "", title: title, document: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))), settings: inputSettings)) |> mapError { error in if error.errorDescription == "THEME_SLUG_INVALID" { return .slugInvalid @@ -408,7 +409,7 @@ public func updateTheme(account: Account, accountManager: AccountManager mapError { error in if error.errorDescription == "THEME_SLUG_INVALID" { return .slugInvalid diff --git a/submodules/TelegramCore/Sources/UpdatePeers.swift b/submodules/TelegramCore/Sources/UpdatePeers.swift index 2fd502f1..53db73d1 100644 --- a/submodules/TelegramCore/Sources/UpdatePeers.swift +++ b/submodules/TelegramCore/Sources/UpdatePeers.swift @@ -51,13 +51,15 @@ func updatePeers(transaction: Transaction, accountPeerId: PeerId, peers: Accumul if let telegramUser = TelegramUser.merge(transaction.getPeer(user.peerId) as? TelegramUser, rhs: user) { parsedPeers.append(telegramUser) switch user { - case let .user(flags, flags2, _, _, _, _, _, _, _, _, _, _, _, _, _, _, storiesMaxId, _, _, _, _, _): + case let .user(userData): + let (flags, flags2, storiesMaxId) = (userData.flags, userData.flags2, userData.storiesMaxId) let isMin = (flags & (1 << 20)) != 0 let storiesUnavailable = (flags2 & (1 << 4)) != 0 if let storiesMaxId { switch storiesMaxId { - case let .recentStory(flags, maxId): + case let .recentStory(recentStoryData): + let (flags, maxId) = (recentStoryData.flags, recentStoryData.maxId) if let maxId { transaction.setStoryItemsInexactMaxId(peerId: user.peerId, id: maxId, hasLiveItems: (flags & (1 << 0)) != 0) } else { @@ -81,13 +83,15 @@ func updatePeers(transaction: Transaction, accountPeerId: PeerId, peers: Accumul } for (_, chat) in peers.chats { switch chat { - case let .channel(flags, flags2, _, _, _, _, _, _, _, _, _, _, _, _, storiesMaxId, _, _, _, _, _, _, _, _): + case let .channel(channelData): + let (flags, flags2, storiesMaxId) = (channelData.flags, channelData.flags2, channelData.storiesMaxId) let isMin = (flags & (1 << 12)) != 0 let storiesUnavailable = (flags2 & (1 << 3)) != 0 if let storiesMaxId { switch storiesMaxId { - case let .recentStory(flags, maxId): + case let .recentStory(recentStoryData): + let (flags, maxId) = (recentStoryData.flags, recentStoryData.maxId) if let maxId { transaction.setStoryItemsInexactMaxId(peerId: chat.peerId, id: maxId, hasLiveItems: (flags & (1 << 0)) != 0) } else { @@ -333,7 +337,8 @@ func updatePeerPresences(transaction: Transaction, accountPeerId: PeerId, peerPr parsedPresences[peerId] = presence default: switch user { - case let .user(flags, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + case let .user(userData): + let flags = userData.flags let isMin = (flags & (1 << 20)) != 0 if isMin, let _ = transaction.getPeerPresence(peerId: peerId) { } else { @@ -401,7 +406,8 @@ func updateContacts(transaction: Transaction, apiUsers: [Api.User]) { for user in apiUsers { var isContact: Bool? switch user { - case let .user(flags, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + case let .user(userData): + let flags = userData.flags if (flags & (1 << 20)) == 0 { isContact = (flags & (1 << 11)) != 0 } diff --git a/submodules/TelegramCore/Sources/Utils/JSON.swift b/submodules/TelegramCore/Sources/Utils/JSON.swift index 3251cd22..4a183b7d 100644 --- a/submodules/TelegramCore/Sources/Utils/JSON.swift +++ b/submodules/TelegramCore/Sources/Utils/JSON.swift @@ -345,19 +345,25 @@ public extension JSON { switch (apiJson, root) { case (.jsonNull, false): self = .null - case let (.jsonNumber(value), false): + case let (.jsonNumber(jsonNumberData), false): + let value = jsonNumberData.value self = .number(value) - case let (.jsonString(value), false): + case let (.jsonString(jsonStringData), false): + let value = jsonStringData.value self = .string(value) - case let (.jsonBool(value), false): + case let (.jsonBool(jsonBoolData), false): + let value = jsonBoolData.value self = .bool(Bool(apiBool: value)) - case let (.jsonArray(value), _): + case let (.jsonArray(jsonArrayData), _): + let value = jsonArrayData.value self = .array(value.compactMap { JSON(apiJson: $0, root: false) }) - case let (.jsonObject(value), _): + case let (.jsonObject(jsonObjectData), _): + let value = jsonObjectData.value self = .dictionary(value.reduce([String: JSON]()) { dictionary, value in var dictionary = dictionary switch value { - case let .jsonObjectValue(key, value): + case let .jsonObjectValue(jsonObjectValueData): + let (key, value) = (jsonObjectValueData.key, jsonObjectValueData.value) if let value = JSON(apiJson: value, root: false) { dictionary[key] = value } @@ -379,21 +385,21 @@ private func apiJson(_ json: JSON, root: Bool) -> Api.JSONValue? { case (.null, false): return .jsonNull case let (.number(value), false): - return .jsonNumber(value: value) + return .jsonNumber(.init(value: value)) case let (.string(value), false): - return .jsonString(value: value) + return .jsonString(.init(value: value)) case let (.bool(value), false): - return .jsonBool(value: value.apiBool) + return .jsonBool(.init(value: value.apiBool)) case let (.array(value), _): - return .jsonArray(value: value.compactMap { apiJson($0, root: false) }) + return .jsonArray(.init(value: value.compactMap { apiJson($0, root: false) })) case let (.dictionary(value), _): - return .jsonObject(value: value.reduce([Api.JSONObjectValue]()) { objectValues, keyAndValue in + return .jsonObject(.init(value: value.reduce([Api.JSONObjectValue]()) { objectValues, keyAndValue in var objectValues = objectValues if let value = apiJson(keyAndValue.value, root: false) { - objectValues.append(.jsonObjectValue(key: keyAndValue.key, value: value)) + objectValues.append(.jsonObjectValue(.init(key: keyAndValue.key, value: value))) } return objectValues - }) + })) default: return nil } diff --git a/submodules/TelegramCore/Sources/Utils/MessageUtils.swift b/submodules/TelegramCore/Sources/Utils/MessageUtils.swift index 8254b733..9e12a847 100644 --- a/submodules/TelegramCore/Sources/Utils/MessageUtils.swift +++ b/submodules/TelegramCore/Sources/Utils/MessageUtils.swift @@ -385,6 +385,10 @@ public extension Message { return false } + return self.isCopyProtectedIgnoringBypass() + } + + func isCopyProtectedIgnoringBypass() -> Bool { if self.flags.contains(.CopyProtected) { return true } else if let group = self.peers[self.id.peerId] as? TelegramGroup, group.flags.contains(.copyProtectionEnabled) { diff --git a/submodules/TelegramCore/Sources/Utils/PeerUtils.swift b/submodules/TelegramCore/Sources/Utils/PeerUtils.swift index 49eb1535..3875fc48 100644 --- a/submodules/TelegramCore/Sources/Utils/PeerUtils.swift +++ b/submodules/TelegramCore/Sources/Utils/PeerUtils.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import SGSimpleSettings public let anonymousSavedMessagesId: Int64 = 2666000 @@ -28,6 +29,13 @@ public extension Peer { break } + // MARK: Swiftgram + let chatId = self.id.id._internalGetInt64Value() + if contentSettings.appConfiguration.sgWebSettings.global.forceReasons.contains(chatId) { + return "Unavailable in Swiftgram due to App Store Guidelines" + } else if contentSettings.appConfiguration.sgWebSettings.global.unforceReasons.contains(chatId) { + return nil + } if let restrictionInfo = restrictionInfo { for rule in restrictionInfo.rules { if rule.reason == "sensitive" { @@ -35,7 +43,7 @@ public extension Peer { } if rule.platform == "all" || rule.platform == platform || contentSettings.addContentRestrictionReasons.contains(rule.platform) { if !contentSettings.ignoreContentRestrictionReasons.contains(rule.reason) { - return rule.text + return rule.text + "\n" + "\(rule.reason)-\(rule.platform)" } } } @@ -302,6 +310,9 @@ public extension Peer { } var nameColor: PeerColor? { + if SGSimpleSettings.shared.accountColorsSaturation == 0 { // MARK: Swiftgram + return nil + } switch self { case let user as TelegramUser: if let nameColor = user.nameColor { diff --git a/submodules/TelegramCore/Sources/Wallpapers.swift b/submodules/TelegramCore/Sources/Wallpapers.swift index 9d998570..84985dc5 100644 --- a/submodules/TelegramCore/Sources/Wallpapers.swift +++ b/submodules/TelegramCore/Sources/Wallpapers.swift @@ -13,7 +13,8 @@ public func telegramWallpapers(postbox: Postbox, network: Network, forceUpdate: return .single(([], -1)) } switch result { - case let .wallPapers(hash, wallpapers): + case let .wallPapers(wallPapersData): + let (hash, wallpapers) = (wallPapersData.hash, wallPapersData.wallpapers) var items: [TelegramWallpaper] = [] var addedBuiltin = false for apiWallpaper in wallpapers { @@ -161,7 +162,7 @@ public enum GetWallpaperError { } public func getWallpaper(network: Network, slug: String) -> Signal { - return network.request(Api.functions.account.getWallPaper(wallpaper: .inputWallPaperSlug(slug: slug))) + return network.request(Api.functions.account.getWallPaper(wallpaper: .inputWallPaperSlug(.init(slug: slug)))) |> mapError { _ -> GetWallpaperError in return .generic } |> map { wallpaper -> TelegramWallpaper in return TelegramWallpaper(apiWallpaper: wallpaper) @@ -180,7 +181,7 @@ private func saveUnsaveWallpaper(account: Account, wallpaper: TelegramWallpaper, guard case let .file(file) = wallpaper else { return .complete() } - return account.network.request(Api.functions.account.saveWallPaper(wallpaper: Api.InputWallPaper.inputWallPaperSlug(slug: file.slug), unsave: unsave ? Api.Bool.boolTrue : Api.Bool.boolFalse, settings: apiWallpaperSettings(file.settings))) + return account.network.request(Api.functions.account.saveWallPaper(wallpaper: Api.InputWallPaper.inputWallPaperSlug(.init(slug: file.slug)), unsave: unsave ? Api.Bool.boolTrue : Api.Bool.boolFalse, settings: apiWallpaperSettings(file.settings))) |> `catch` { _ -> Signal in return .complete() } @@ -195,9 +196,9 @@ public func installWallpaper(account: Account, wallpaper: TelegramWallpaper) -> } let inputWallpaper: Api.InputWallPaper if file.id != 0 && file.accessHash != 0 { - inputWallpaper = .inputWallPaper(id: file.id, accessHash: file.accessHash) + inputWallpaper = .inputWallPaper(.init(id: file.id, accessHash: file.accessHash)) } else { - inputWallpaper = .inputWallPaperSlug(slug: file.slug) + inputWallpaper = .inputWallPaperSlug(.init(slug: file.slug)) } return account.network.request(Api.functions.account.installWallPaper(wallpaper: inputWallpaper, settings: apiWallpaperSettings(file.settings))) |> `catch` { _ -> Signal in diff --git a/submodules/TelegramCore/Sources/WebpagePreview.swift b/submodules/TelegramCore/Sources/WebpagePreview.swift index dbc84408..db5fc220 100644 --- a/submodules/TelegramCore/Sources/WebpagePreview.swift +++ b/submodules/TelegramCore/Sources/WebpagePreview.swift @@ -131,7 +131,7 @@ public func webpagePreviewWithProgress(account: Account, urls: [String], webpage } if let imageProvider = metadata.imageProvider { - imageProvider.loadFileRepresentation(forTypeIdentifier: kUTTypeImage as String, completionHandler: { imageUrl, _ in + imageProvider.loadFileRepresentation(forTypeIdentifier: "public.image", completionHandler: { imageUrl, _ in guard let imageUrl, let imageData = try? Data(contentsOf: imageUrl) else { completeWithImage(nil) return @@ -157,7 +157,7 @@ public func webpagePreviewWithProgress(account: Account, urls: [String], webpage return account.network.requestWithAdditionalInfo(Api.functions.messages.getWebPagePreview(flags: 0, message: urls.joined(separator: " "), entities: nil), info: .progress) |> `catch` { _ -> Signal, NoError> in - return .single(.result(.webPagePreview(media: .messageMediaEmpty, chats: [], users: []))) + return .single(.result(.webPagePreview(.init(media: .messageMediaEmpty, chats: [], users: [])))) } |> mapToSignal { result -> Signal in switch result { @@ -170,15 +170,17 @@ public func webpagePreviewWithProgress(account: Account, urls: [String], webpage return .complete() } case let .result(result): - if case let .webPagePreview(result, _, _) = result, let preCachedResources = result.preCachedResources { + if case let .webPagePreview(webPagePreviewData) = result, let preCachedResources = webPagePreviewData.media.preCachedResources { for (resource, data) in preCachedResources { account.postbox.mediaBox.storeResourceData(resource.id, data: data) } } switch result { - case let .webPagePreview(media, chats, users): + case let .webPagePreview(webPagePreviewData): + let (media, chats, users) = (webPagePreviewData.media, webPagePreviewData.chats, webPagePreviewData.users) switch media { - case let .messageMediaWebPage(_, webpage): + case let .messageMediaWebPage(messageMediaWebPageData): + let webpage = messageMediaWebPageData.webpage return account.postbox.transaction { transaction -> Signal in let peers = AccumulatedPeers(chats: chats, users: users) updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: peers) @@ -227,13 +229,14 @@ public func actualizedWebpage(account: Account, webpage: TelegramMediaWebpage) - if let result = result { return account.postbox.transaction { transaction -> Signal in switch result { - case let .webPage(apiWebpage, chats, users): + case let .webPage(webPageData): + let (apiWebpage, chats, users) = (webPageData.webpage, webPageData.chats, webPageData.users) let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users) updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: parsedPeers) if let updatedWebpage = telegramMediaWebpageFromApiWebpage(apiWebpage), case .Loaded = updatedWebpage.content, updatedWebpage.webpageId == webpage.webpageId { return .single(updatedWebpage) - } else if case let .webPageNotModified(_, viewsValue) = apiWebpage, let views = viewsValue, case let .Loaded(content) = webpage.content { + } else if case let .webPageNotModified(webPageNotModifiedData) = apiWebpage, let views = webPageNotModifiedData.cachedPageViews, case let .Loaded(content) = webpage.content { let updatedContent: TelegramMediaWebpageContent = .Loaded(TelegramMediaWebpageLoadedContent( url: content.url, displayUrl: content.displayUrl, @@ -280,7 +283,8 @@ public func updatedRemoteWebpage(postbox: Postbox, network: Network, accountPeer return .single(nil) } |> mapToSignal { result -> Signal in - if let result = result, case let .webPage(webpage, chats, users) = result, let updatedWebpage = telegramMediaWebpageFromApiWebpage(webpage), case .Loaded = updatedWebpage.content { + if let result = result, case let .webPage(webPageData) = result, let updatedWebpage = telegramMediaWebpageFromApiWebpage(webPageData.webpage), case .Loaded = updatedWebpage.content { + let (chats, users) = (webPageData.chats, webPageData.users) if updatedWebpage.webpageId.id == id { return postbox.transaction { transaction -> TelegramMediaWebpage? in let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users) diff --git a/submodules/TelegramPresentationData/Sources/PresentationData.swift b/submodules/TelegramPresentationData/Sources/PresentationData.swift index 17dc241a..9cf142a1 100644 --- a/submodules/TelegramPresentationData/Sources/PresentationData.swift +++ b/submodules/TelegramPresentationData/Sources/PresentationData.swift @@ -45,12 +45,14 @@ public struct PresentationAppIcon: Equatable { public let imageName: String public let isDefault: Bool public let isPremium: Bool + public let isSGPro: Bool - public init(name: String, imageName: String, isDefault: Bool = false, isPremium: Bool = false) { + public init(name: String, imageName: String, isDefault: Bool = false, isPremium: Bool = false, isSGPro: Bool = false) { self.name = name self.imageName = imageName self.isDefault = isDefault self.isPremium = isPremium + self.isSGPro = isSGPro } } diff --git a/submodules/TelegramPresentationData/Sources/PresentationTheme.swift b/submodules/TelegramPresentationData/Sources/PresentationTheme.swift index 56384410..66271776 100644 --- a/submodules/TelegramPresentationData/Sources/PresentationTheme.swift +++ b/submodules/TelegramPresentationData/Sources/PresentationTheme.swift @@ -456,6 +456,9 @@ public final class PresentationThemeList { public let itemBlocksBackgroundColor: UIColor public let itemModalBlocksBackgroundColor: UIColor public let itemHighlightedBackgroundColor: UIColor + public var itemSearchHighlightColor: UIColor { + return self.itemHighlightedBackgroundColor + } public let itemBlocksSeparatorColor: UIColor public let itemPlainSeparatorColor: UIColor public let disclosureArrowColor: UIColor diff --git a/submodules/TelegramPresentationData/Sources/Resources/PresentationResourcesSettings.swift b/submodules/TelegramPresentationData/Sources/Resources/PresentationResourcesSettings.swift index 785aa906..67438af7 100644 --- a/submodules/TelegramPresentationData/Sources/Resources/PresentationResourcesSettings.swift +++ b/submodules/TelegramPresentationData/Sources/Resources/PresentationResourcesSettings.swift @@ -31,6 +31,16 @@ private func renderIcon(name: String, scaleFactor: CGFloat = 1.0, backgroundColo let bounds = CGRect(origin: CGPoint(), size: size) context.clear(bounds) + func drawImage(_ image: UIImage, in rect: CGRect) { + context.saveGState() + context.translateBy(x: 0, y: size.height) + context.scaleBy(x: 1.0, y: -1.0) + UIGraphicsPushContext(context) + image.draw(in: rect) + UIGraphicsPopContext() + context.restoreGState() + } + if let backgroundColors { addRoundedRectPath(context: context, rect: CGRect(origin: CGPoint(), size: size), radius: 7.0) context.clip() @@ -44,25 +54,27 @@ private func renderIcon(name: String, scaleFactor: CGFloat = 1.0, backgroundColo context.drawLinearGradient(gradient, start: CGPoint(x: size.width, y: size.height), end: CGPoint(x: 0.0, y: 0.0), options: CGGradientDrawingOptions()) context.resetClip() - if let image = generateTintedImage(image: UIImage(bundleImageName: name), color: .white), let cgImage = image.cgImage { + if let image = generateTintedImage(image: UIImage(bundleImageName: name), color: .white) { let imageSize = CGSize(width: image.size.width * scaleFactor, height: image.size.height * scaleFactor) - context.draw(cgImage, in: CGRect(origin: CGPoint(x: (bounds.width - imageSize.width) * 0.5, y: (bounds.height - imageSize.height) * 0.5), size: imageSize)) + drawImage(image, in: CGRect(origin: CGPoint(x: (bounds.width - imageSize.width) * 0.5, y: (bounds.height - imageSize.height) * 0.5), size: imageSize)) } } else { - if let image = UIImage(bundleImageName: name), let cgImage = image.cgImage { + if let image = UIImage(bundleImageName: name) { let imageSize: CGSize if scaleFactor == 1.0 { imageSize = size } else { imageSize = CGSize(width: image.size.width * scaleFactor, height: image.size.height * scaleFactor) } - context.draw(cgImage, in: CGRect(origin: CGPoint(x: (bounds.width - imageSize.width) * 0.5, y: (bounds.height - imageSize.height) * 0.5), size: imageSize)) + drawImage(image, in: CGRect(origin: CGPoint(x: (bounds.width - imageSize.width) * 0.5, y: (bounds.height - imageSize.height) * 0.5), size: imageSize)) } } }) } public struct PresentationResourcesSettings { + public static let swiftgram = renderIcon(name: "SwiftgramSettings") + public static let swiftgramPro = renderIcon(name: "SwiftgramPro") public static let editProfile = renderIcon(name: "Settings/Menu/EditProfile") public static let proxy = renderIcon(name: "Settings/Menu/Proxy") public static let savedMessages = renderIcon(name: "Settings/Menu/SavedMessages") @@ -81,6 +93,7 @@ public struct PresentationResourcesSettings { public static let premiumGift = renderIcon(name: "Settings/Menu/Gift") public static let business = renderIcon(name: "Settings/Menu/Business", backgroundColors: [UIColor(rgb: 0xA95CE3), UIColor(rgb: 0xF16B80)]) public static let myProfile = renderIcon(name: "Settings/Menu/Profile") + public static let ghostgram = renderIcon(name: "Settings/Menu/GhostgramSettings") public static let reactions = renderIcon(name: "Settings/Menu/Reactions") public static let balance = renderIcon(name: "Settings/Menu/Balance", scaleFactor: 0.97, backgroundColors: [UIColor(rgb: 0x34c759)]) public static let affiliateProgram = renderIcon(name: "Settings/Menu/AffiliateProgram") diff --git a/submodules/TelegramStringFormatting/BUILD b/submodules/TelegramStringFormatting/BUILD index 932916cf..2180b8a0 100644 --- a/submodules/TelegramStringFormatting/BUILD +++ b/submodules/TelegramStringFormatting/BUILD @@ -1,5 +1,7 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = ["//Swiftgram/SGSimpleSettings:SGSimpleSettings"] + swift_library( name = "TelegramStringFormatting", module_name = "TelegramStringFormatting", @@ -9,7 +11,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/TelegramCore:TelegramCore", "//submodules/Display:Display", "//submodules/PlatformRestrictionMatching:PlatformRestrictionMatching", diff --git a/submodules/TelegramStringFormatting/Sources/DateFormat.swift b/submodules/TelegramStringFormatting/Sources/DateFormat.swift index 430fde43..a2d537a0 100644 --- a/submodules/TelegramStringFormatting/Sources/DateFormat.swift +++ b/submodules/TelegramStringFormatting/Sources/DateFormat.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import TelegramPresentationData import TelegramUIPreferences @@ -46,8 +47,11 @@ public func stringForMessageTimestamp(timestamp: Int32, dateTimeFormat: Presenta } else { gmtime_r(&t, &timeinfo) } - - return stringForShortTimestamp(hours: timeinfo.tm_hour, minutes: timeinfo.tm_min, dateTimeFormat: dateTimeFormat) + if SGSimpleSettings.shared.secondsInMessages { + return stringForShortTimestampWithSeconds(hours: timeinfo.tm_hour, minutes: timeinfo.tm_min, seconds: timeinfo.tm_sec, dateTimeFormat: dateTimeFormat) + } else { + return stringForShortTimestamp(hours: timeinfo.tm_hour, minutes: timeinfo.tm_min, dateTimeFormat: dateTimeFormat) + } } public func getDateTimeComponents(timestamp: Int32) -> (day: Int32, month: Int32, year: Int32, hour: Int32, minutes: Int32) { @@ -193,3 +197,69 @@ public func roundDateToDays(_ timestamp: Int32) -> Int32 { } return Int32(date.timeIntervalSince1970) } + + + + + + + + + + +// MARK: Swiftgram +public func stringForDateWithoutDay(date: Date, timeZone: TimeZone? = TimeZone(secondsFromGMT: 0), strings: PresentationStrings) -> String { + let formatter = DateFormatter() + formatter.timeStyle = .none + formatter.timeZone = timeZone + formatter.locale = localeWithStrings(strings) + formatter.setLocalizedDateFormatFromTemplate("MMMMyyyy") + return formatter.string(from: date) +} + + +public func stringForDateWithoutDayAndMonth(date: Date, timeZone: TimeZone? = TimeZone(secondsFromGMT: 0), strings: PresentationStrings) -> String { + let formatter = DateFormatter() + formatter.timeStyle = .none + formatter.timeZone = timeZone + formatter.locale = localeWithStrings(strings) + formatter.setLocalizedDateFormatFromTemplate("yyyy") + return formatter.string(from: date) +} + +// MARK: Swiftgram +public func stringForShortTimestampWithSeconds(hours: Int32, minutes: Int32, seconds: Int32, dateTimeFormat: PresentationDateTimeFormat) -> String { + switch dateTimeFormat.timeFormat { + case .regular: + let hourString: String + if hours == 0 { + hourString = "12" + } else if hours > 12 { + hourString = "\(hours - 12)" + } else { + hourString = "\(hours)" + } + + let periodString: String + if hours >= 12 { + periodString = "PM" + } else { + periodString = "AM" + } + + let minuteString: String + if minutes >= 10 { + minuteString = "\(minutes)" + } else { + minuteString = "0\(minutes)" + } + if seconds >= 10 { + return "\(hourString):\(minuteString):\(seconds)\u{00a0}\(periodString)" + } else { + return "\(hourString):\(minuteString):0\(seconds)\u{00a0}\(periodString)" + } + case .military: + return String(format: "%02d:%02d:%02d", arguments: [Int(hours), Int(minutes), Int(seconds)]) + } +} +// diff --git a/submodules/TelegramStringFormatting/Sources/ServiceMessageStrings.swift b/submodules/TelegramStringFormatting/Sources/ServiceMessageStrings.swift index f6d67402..5902a8d7 100644 --- a/submodules/TelegramStringFormatting/Sources/ServiceMessageStrings.swift +++ b/submodules/TelegramStringFormatting/Sources/ServiceMessageStrings.swift @@ -148,6 +148,8 @@ public func universalServiceMessageString(presentationData: (PresentationTheme, attributedString = addAttributesToStringWithRanges(strings.Notification_CreatedChatWithTitle(authorName, title)._tuple, body: bodyAttributes, argumentAttributes: peerMentionsAttributes(primaryTextColor: primaryTextColor, peerIds: [(0, message.author?.id)])) } } + case .groupCreatorChange: + attributedString = NSAttributedString(string: message.text, font: titleFont, textColor: primaryTextColor) case let .addedMembers(peerIds): if let peerId = peerIds.first, peerId == message.author?.id { if let peer = message.peers[message.id.peerId] as? TelegramChannel, case .broadcast = peer.info { @@ -791,7 +793,7 @@ public func universalServiceMessageString(presentationData: (PresentationTheme, if case let .unique(uniqueGift) = starGift { giftTitle = "\(uniqueGift.title) #\(formatCollectibleNumber(uniqueGift.number, dateTimeFormat: dateTimeFormat))" for attribute in uniqueGift.attributes { - if case let .model(_, fileValue, _) = attribute { + if case let .model(_, fileValue, _, _) = attribute { file = fileValue break } @@ -1262,7 +1264,7 @@ public func universalServiceMessageString(presentationData: (PresentationTheme, attributedString = addAttributesToStringWithRanges(strings.Notification_StarsGift_Sent(authorName, starsPrice)._tuple, body: bodyAttributes, argumentAttributes: attributes) } } - case let .starGiftUnique(gift, isUpgrade, _, _, _, _, _, isPrepaidUpgrade, peerId, senderId, _, resaleStars, _, _, _, assigned, fromOffer): + case let .starGiftUnique(gift, isUpgrade, _, _, _, _, _, isPrepaidUpgrade, peerId, senderId, _, resaleStars, _, _, _, assigned, fromOffer, _, _): if case let .unique(gift) = gift { if !forAdditionalServiceMessage && !"".isEmpty { attributedString = NSAttributedString(string: "\(gift.title) #\(presentationStringsFormattedNumber(gift.number, dateTimeFormat.groupingSeparator))", font: titleFont, textColor: primaryTextColor) diff --git a/submodules/TelegramUI/BUILD b/submodules/TelegramUI/BUILD index 8d05f333..4b1052ce 100644 --- a/submodules/TelegramUI/BUILD +++ b/submodules/TelegramUI/BUILD @@ -5,6 +5,36 @@ load( "telegram_bundle_id", ) +sgdeps = [ + "//Swiftgram/SGSettingsUI:SGSettingsUI", + "//Swiftgram/SGConfig:SGConfig", + "//Swiftgram/SGAPIWebSettings:SGAPIWebSettings", + "//Swiftgram/SGAppGroupIdentifier:SGAppGroupIdentifier", + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//Swiftgram/SFSafariViewControllerPlus:SFSafariViewControllerPlus", + "//Swiftgram/SGLogging:SGLogging", + "//Swiftgram/SGStrings:SGStrings", + "//Swiftgram/SGActionRequestHandlerSanitizer:SGActionRequestHandlerSanitizer", + "//Swiftgram/Wrap:Wrap", + "//Swiftgram/SGDeviceToken:SGDeviceToken", + "//Swiftgram/SGDebugUI:SGDebugUI", + "//Swiftgram/SGInputToolbar:SGInputToolbar", + "//Swiftgram/SGIAP:SGIAP", + "//Swiftgram/SGPayWall:SGPayWall", + "//Swiftgram/SGStatus:SGStatus", + "//Swiftgram/SGSwiftSignalKit:SGSwiftSignalKit", + "//Swiftgram/SGProUI:SGProUI", + "//Swiftgram/SGKeychainBackupManager:SGKeychainBackupManager", + "//Swiftgram/SGGHSettings:SGGHSettings", + # "//Swiftgram/SGContentAnalysis:SGContentAnalysis" +] + +sgsrcs = [ + "//Swiftgram/SGDBReset:SGDBReset", + "//Swiftgram/SGShowMessageJson:SGShowMessageJson", + "//Swiftgram/ChatControllerImplExtension:ChatControllerImplExtension", + "//Swiftgram/SGSharedAccountContextMigration:SGSharedAccountContextMigration" +] filegroup( name = "TelegramUIResources", @@ -44,12 +74,12 @@ swift_library( module_name = "TelegramUI", srcs = glob([ "Sources/**/*.swift", - ]), + ]) + sgsrcs, copts = [ "-warnings-as-errors", ], - deps = [ - "//third-party/recaptcha:RecaptchaEnterpriseSDK", + deps = sgdeps + [ + "//third-party/recaptcha:RecaptchaEnterprise", "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", "//submodules/SSignalKit/SSignalKit:SSignalKit", "//submodules/AsyncDisplayKit:AsyncDisplayKit", @@ -71,6 +101,7 @@ swift_library( "//submodules/TelegramVoip:TelegramVoip", "//submodules/DeviceAccess:DeviceAccess", "//submodules/Utils/DeviceModel", + "//submodules/WatchCommon/Host:WatchCommon", "//submodules/BuildConfig:BuildConfig", "//submodules/BuildConfigExtra:BuildConfigExtra", "//submodules/rlottie:RLottieBinding", @@ -191,6 +222,8 @@ swift_library( "//submodules/RaiseToListen:RaiseToListen", "//submodules/OpusBinding:OpusBinding", "//third-party/opus:opus", + "//submodules/WatchBridgeAudio:WatchBridgeAudio", + "//submodules/WatchBridge:WatchBridge", "//submodules/ShareItems:ShareItems", "//submodules/ShareItems/Impl:ShareItemsImpl", "//submodules/SettingsUI:SettingsUI", @@ -465,6 +498,7 @@ swift_library( "//submodules/TelegramUI/Components/Gifts/GiftOptionsScreen", "//submodules/TelegramUI/Components/Gifts/GiftStoreScreen", "//submodules/TelegramUI/Components/Gifts/GiftSetupScreen", + "//submodules/TelegramUI/Components/Gifts/GiftCraftScreen", "//submodules/TelegramUI/Components/ContentReportScreen", "//submodules/TelegramUI/Components/PeerInfo/AffiliateProgramSetupScreen", "//submodules/TelegramUI/Components/Stars/StarsBalanceOverlayComponent", @@ -513,10 +547,12 @@ swift_library( "//submodules/TelegramUI/Components/AlertComponent", "//submodules/TelegramUI/Components/Chat/ChatAgeRestrictionAlertController", "//submodules/TelegramUI/Components/CocoonInfoScreen", + "//submodules/TelegramUI/Components/ProxyServerPreviewScreen", + "//submodules/TelegramUI/Components/ContextControllerImpl", + "//submodules/TelegramUI/Components/AuthConfirmationScreen", ] + select({ "@build_bazel_rules_apple//apple:ios_arm64": appcenter_targets, "//build-system:ios_sim_arm64": [], - "//conditions:default": [], }), visibility = [ "//visibility:public", diff --git a/submodules/TelegramUI/Components/AuthConfirmationScreen/BUILD b/submodules/TelegramUI/Components/AuthConfirmationScreen/BUILD new file mode 100644 index 00000000..c03b30d9 --- /dev/null +++ b/submodules/TelegramUI/Components/AuthConfirmationScreen/BUILD @@ -0,0 +1,41 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "AuthConfirmationScreen", + module_name = "AuthConfirmationScreen", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/AsyncDisplayKit", + "//submodules/Display", + "//submodules/Postbox", + "//submodules/TelegramCore", + "//submodules/SSignalKit/SwiftSignalKit", + "//submodules/ComponentFlow", + "//submodules/Components/ViewControllerComponent", + "//submodules/Components/ComponentDisplayAdapters", + "//submodules/Components/MultilineTextComponent", + "//submodules/TelegramPresentationData", + "//submodules/AccountContext", + "//submodules/TelegramUI/Components/ButtonComponent", + "//submodules/TelegramUI/Components/GlassBarButtonComponent", + "//submodules/Components/SheetComponent", + "//submodules/PresentationDataUtils", + "//submodules/Components/BundleIconComponent", + "//submodules/TelegramUI/Components/ListSectionComponent", + "//submodules/TelegramUI/Components/ListActionItemComponent", + "//submodules/TelegramUI/Components/AvatarComponent", + "//submodules/Markdown", + "//submodules/PhoneNumberFormat", + "//submodules/ContextUI", + "//submodules/AccountUtils", + "//submodules/TelegramUI/Components/PeerInfo/AccountPeerContextItem", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/submodules/TelegramUI/Components/AuthConfirmationScreen/Sources/AccountSwitchComponent.swift b/submodules/TelegramUI/Components/AuthConfirmationScreen/Sources/AccountSwitchComponent.swift new file mode 100644 index 00000000..ef8d2c5e --- /dev/null +++ b/submodules/TelegramUI/Components/AuthConfirmationScreen/Sources/AccountSwitchComponent.swift @@ -0,0 +1,134 @@ +import Foundation +import UIKit +import AsyncDisplayKit +import Display +import ComponentFlow +import TelegramCore +import TelegramPresentationData +import GlassBackgroundComponent +import AvatarComponent +import BundleIconComponent +import AccountContext + +final class AccountSwitchComponent: Component { + let context: AccountContext + let theme: PresentationTheme + let peer: EnginePeer + let canSwitch: Bool + let action: () -> Void + + init( + context: AccountContext, + theme: PresentationTheme, + peer: EnginePeer, + canSwitch: Bool, + action: @escaping () -> Void + ) { + self.context = context + self.theme = theme + self.peer = peer + self.canSwitch = canSwitch + self.action = action + } + + static func ==(lhs: AccountSwitchComponent, rhs: AccountSwitchComponent) -> Bool { + if lhs.context !== rhs.context { + return false + } + if lhs.theme !== rhs.theme { + return false + } + if lhs.peer != rhs.peer { + return false + } + if lhs.canSwitch != rhs.canSwitch { + return false + } + return true + } + + final class View: UIView { + private let backgroundView = GlassBackgroundView() + private let avatar = ComponentView() + private let arrow = ComponentView() + private let button = HighlightTrackingButton() + + private var component: AccountSwitchComponent? + + override init(frame: CGRect) { + super.init(frame: frame) + + self.addSubview(self.backgroundView) + + self.button.addTarget(self, action: #selector(self.buttonPressed), for: .touchUpInside) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + @objc private func buttonPressed() { + if let component = self.component { + component.action() + } + } + + func update(component: AccountSwitchComponent, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + self.component = component + + let size = CGSize(width: component.canSwitch ? 76.0 : 44.0, height: 44.0) + + let avatarSize = self.avatar.update( + transition: .immediate, + component: AnyComponent( + AvatarComponent( + context: component.context, + theme: component.theme, + peer: component.peer, + ) + ), + environment: {}, + containerSize: CGSize(width: 36.0, height: 36.0) + ) + if let avatarView = self.avatar.view { + if avatarView.superview == nil { + avatarView.isUserInteractionEnabled = false + self.backgroundView.contentView.addSubview(avatarView) + } + avatarView.frame = CGRect(origin: CGPoint(x: 4.0, y: 4.0), size: avatarSize) + } + + let arrowSize = self.arrow.update( + transition: .immediate, + component: AnyComponent( + BundleIconComponent(name: "Navigation/Disclosure", tintColor: component.theme.rootController.navigationBar.secondaryTextColor) + ), + environment: {}, + containerSize: availableSize + ) + if let arrowView = self.arrow.view { + if arrowView.superview == nil { + arrowView.isUserInteractionEnabled = false + self.backgroundView.contentView.addSubview(arrowView) + self.backgroundView.contentView.addSubview(self.button) + } + arrowView.frame = CGRect(origin: CGPoint(x: size.width - arrowSize.width - 8.0, y: floorToScreenPixels((size.height - arrowSize.height) / 2.0)), size: arrowSize) + transition.setAlpha(view: arrowView, alpha: component.canSwitch ? 1.0 : 0.0) + } + + self.backgroundView.update(size: size, cornerRadius: size.height * 0.5, isDark: component.theme.overallDarkAppearance, tintColor: .init(kind: .panel), isInteractive: component.canSwitch, transition: transition) + transition.setFrame(view: self.backgroundView, frame: CGRect(origin: .zero, size: size)) + transition.setFrame(view: self.button, frame: CGRect(origin: .zero, size: size)) + + return size + } + } + + func makeView() -> View { + return View(frame: CGRect()) + } + + func update(view: View, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + return view.update(component: self, availableSize: availableSize, state: state, environment: environment, transition: transition) + } +} diff --git a/submodules/TelegramUI/Components/AuthConfirmationScreen/Sources/AuthConfirmationScreen.swift b/submodules/TelegramUI/Components/AuthConfirmationScreen/Sources/AuthConfirmationScreen.swift new file mode 100644 index 00000000..0b5a10ac --- /dev/null +++ b/submodules/TelegramUI/Components/AuthConfirmationScreen/Sources/AuthConfirmationScreen.swift @@ -0,0 +1,648 @@ +import Foundation +import UIKit +import Display +import AsyncDisplayKit +import TelegramCore +import SwiftSignalKit +import AccountContext +import TelegramPresentationData +import ComponentFlow +import ViewControllerComponent +import SheetComponent +import MultilineTextComponent +import GlassBarButtonComponent +import ButtonComponent +import PresentationDataUtils +import BundleIconComponent +import ListSectionComponent +import ListActionItemComponent +import AvatarComponent +import Markdown +import PhoneNumberFormat +import ContextUI +import AccountUtils +import GlassBackgroundComponent +import AccountPeerContextItem + +private final class AuthConfirmationSheetContent: CombinedComponent { + typealias EnvironmentType = ViewControllerComponentContainer.Environment + + let context: AccountContext + let subject: MessageActionUrlAuthResult + let completion: (AccountContext, EnginePeer, Bool, Bool) -> Void + let cancel: (Bool) -> Void + + init( + context: AccountContext, + subject: MessageActionUrlAuthResult, + completion: @escaping (AccountContext, EnginePeer, Bool, Bool) -> Void, + cancel: @escaping (Bool) -> Void + ) { + self.context = context + self.subject = subject + self.completion = completion + self.cancel = cancel + } + + static func ==(lhs: AuthConfirmationSheetContent, rhs: AuthConfirmationSheetContent) -> Bool { + if lhs.context !== rhs.context { + return false + } + return true + } + + final class State: ComponentState { + private let context: AccountContext + private let subject: MessageActionUrlAuthResult + + var peer: EnginePeer? + var forcedAccount: (AccountContext, EnginePeer)? + + fileprivate var inProgress = false + var allowWrite = true + weak var controller: ViewController? + + init(context: AccountContext, subject: MessageActionUrlAuthResult) { + self.context = context + self.subject = subject + + super.init() + + let _ = (context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: context.account.peerId)) + |> deliverOnMainQueue).start(next: { [weak self] peer in + guard let self, let peer else { + return + } + self.peer = peer + self.updated() + }) + } + + func displayPhoneNumberConfirmation(commit: @escaping (Bool) -> Void) { + guard case let .request(domain, _, _, _) = self.subject else { + return + } + let presentationData = self.context.sharedContext.currentPresentationData.with { $0 } + + let _ = (self.context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: self.context.account.peerId)) + |> deliverOnMainQueue).start(next: { [weak self] peer in + guard let self, case let .user(user) = peer, let phone = user.phone else { + return + } + let phoneNumber = formatPhoneNumber(context: self.context, number: phone).replacingOccurrences(of: " ", with: "\u{00A0}") + + let alertController = textAlertController( + context: self.context, + title: nil, + text: "\(domain)\n\(phoneNumber)", + actions: [ + TextAlertAction(type: .genericAction, title: presentationData.strings.Common_Cancel, action: { + commit(false) + }), + TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: { + commit(true) + }) + ] + ) + self.controller?.present(alertController, in: .window(.root)) + }) + } + + func presentAccountSwitchMenu() { + // Account switch menu is disabled in this compatibility build. + } + } + + func makeState() -> State { + return State(context: self.context, subject: self.subject) + } + + static var body: Body { + let closeButton = Child(GlassBarButtonComponent.self) + let accountButton = Child(AccountSwitchComponent.self) + let avatar = Child(AvatarComponent.self) + let title = Child(MultilineTextComponent.self) + let description = Child(MultilineTextComponent.self) + let clientSection = Child(ListSectionComponent.self) + let optionsSection = Child(ListSectionComponent.self) + let cancelButton = Child(ButtonComponent.self) + let doneButton = Child(ButtonComponent.self) + + return { context in + let environment = context.environment[ViewControllerComponentContainer.Environment.self].value + let component = context.component + let theme = environment.theme + let strings = environment.strings + let state = context.state + if state.controller == nil { + state.controller = environment.controller() + } + + let presentationData = context.component.context.sharedContext.currentPresentationData.with { $0 } + let _ = strings + + guard case let .request(domain, bot, clientData, flags) = component.subject else { + fatalError() + } + + let sideInset: CGFloat = 16.0 + environment.safeInsets.left + + let closeButton = closeButton.update( + component: GlassBarButtonComponent( + size: CGSize(width: 44.0, height: 44.0), + backgroundColor: nil, + isDark: theme.overallDarkAppearance, + state: .glass, + component: AnyComponentWithIdentity(id: "close", component: AnyComponent( + BundleIconComponent( + name: "Navigation/Close", + tintColor: theme.chat.inputPanel.panelControlColor + ) + )), + action: { _ in + component.cancel(true) + } + ), + availableSize: CGSize(width: 44.0, height: 44.0), + transition: .immediate + ) + context.add(closeButton + .position(CGPoint(x: 16.0 + closeButton.size.width / 2.0, y: 16.0 + closeButton.size.height / 2.0)) + ) + + if let peer = state.peer { + let accountButton = accountButton.update( + component: AccountSwitchComponent( + context: state.forcedAccount?.0 ?? component.context, + theme: environment.theme, + peer: state.forcedAccount?.1 ?? peer, + canSwitch: false, + action: { [weak state] in + state?.presentAccountSwitchMenu() + } + ), + availableSize: context.availableSize, + transition: .immediate + ) + context.add(accountButton + .position(CGPoint(x: context.availableSize.width - 16.0 - accountButton.size.width / 2.0, y: 16.0 + accountButton.size.height / 2.0)) + ) + } + + var contentHeight: CGFloat = 32.0 + let avatar = avatar.update( + component: AvatarComponent( + context: component.context, + theme: environment.theme, + peer: EnginePeer(bot) + ), + availableSize: CGSize(width: 92.0, height: 92.0), + transition: .immediate + ) + context.add(avatar + .position(CGPoint(x: context.availableSize.width / 2.0, y: contentHeight + avatar.size.height / 2.0)) + ) + contentHeight += avatar.size.height + contentHeight += 18.0 + + let titleFont = Font.bold(24.0) + let titleText = "Sign in to **\(domain)**" + let title = title.update( + component: MultilineTextComponent( + text: .markdown(text: titleText, attributes: MarkdownAttributes(body: MarkdownAttributeSet(font: titleFont, textColor: theme.actionSheet.primaryTextColor), bold: MarkdownAttributeSet(font: titleFont, textColor: theme.actionSheet.controlAccentColor), link: MarkdownAttributeSet(font: titleFont, textColor: theme.actionSheet.primaryTextColor), linkAttribute: { _ in return nil })), + horizontalAlignment: .center, + maximumNumberOfLines: 2 + ), + availableSize: CGSize(width: context.availableSize.width - sideInset * 2.0 - 60.0, height: CGFloat.greatestFiniteMagnitude), + transition: .immediate + ) + context.add(title + .position(CGPoint(x: context.availableSize.width / 2.0, y: contentHeight + title.size.height / 2.0)) + ) + contentHeight += title.size.height + contentHeight += 16.0 + + let textFont = Font.regular(15.0) + let boldTextFont = Font.semibold(15.0) + let descriptionText = "Review requested permissions and tap **Continue** to proceed." + let description = description.update( + component: MultilineTextComponent( + text: .markdown(text: descriptionText, attributes: MarkdownAttributes(body: MarkdownAttributeSet(font: textFont, textColor: theme.actionSheet.primaryTextColor), bold: MarkdownAttributeSet(font: boldTextFont, textColor: theme.actionSheet.primaryTextColor), link: MarkdownAttributeSet(font: textFont, textColor: theme.actionSheet.primaryTextColor), linkAttribute: { _ in return nil })), + horizontalAlignment: .center, + maximumNumberOfLines: 3, + lineSpacing: 0.2 + ), + availableSize: CGSize(width: context.availableSize.width - sideInset * 2.0 - 60.0, height: CGFloat.greatestFiniteMagnitude), + transition: .immediate + ) + context.add(description + .position(CGPoint(x: context.availableSize.width / 2.0, y: contentHeight + description.size.height / 2.0)) + ) + contentHeight += description.size.height + contentHeight += 16.0 + + var clientSectionItems: [AnyComponentWithIdentity] = [] + clientSectionItems.append( + AnyComponentWithIdentity(id: "device", component: AnyComponent( + ListActionItemComponent( + theme: theme, + style: .glass, + title: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: "Device", + font: Font.regular(17.0), + textColor: theme.list.itemPrimaryTextColor + )), + maximumNumberOfLines: 1 + )), + contentInsets: UIEdgeInsets(top: 19.0, left: 0.0, bottom: 19.0, right: 0.0), + accessory: .custom(ListActionItemComponent.CustomAccessory( + component: AnyComponentWithIdentity( + id: "info", + component: AnyComponent( + VStack([ + AnyComponentWithIdentity(id: AnyHashable(0), component: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: clientData?.platform ?? "", + font: Font.regular(presentationData.listsFontSize.itemListBaseFontSize), + textColor: theme.list.itemPrimaryTextColor + )), + maximumNumberOfLines: 1 + ))), + AnyComponentWithIdentity(id: AnyHashable(1), component: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: clientData?.browser ?? "", + font: Font.regular(presentationData.listsFontSize.itemListBaseFontSize / 17.0 * 15.0), + textColor: theme.list.itemSecondaryTextColor + )), + horizontalAlignment: .left, + truncationType: .middle, + maximumNumberOfLines: 1 + ))) + ], alignment: .right, spacing: 3.0) + ) + ), + insets: UIEdgeInsets(top: 0.0, left: 8.0, bottom: 0.0, right: 14.0), + isInteractive: true + )), + action: nil + ) + )) + ) + + clientSectionItems.append( + AnyComponentWithIdentity(id: "region", component: AnyComponent( + ListActionItemComponent( + theme: theme, + style: .glass, + title: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: "IP Address", + font: Font.regular(17.0), + textColor: theme.list.itemPrimaryTextColor + )), + maximumNumberOfLines: 1 + )), + contentInsets: UIEdgeInsets(top: 19.0, left: 0.0, bottom: 19.0, right: 0.0), + accessory: .custom(ListActionItemComponent.CustomAccessory( + component: AnyComponentWithIdentity( + id: "info", + component: AnyComponent( + VStack([ + AnyComponentWithIdentity(id: AnyHashable(0), component: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: clientData?.ip ?? "", + font: Font.regular(presentationData.listsFontSize.itemListBaseFontSize), + textColor: theme.list.itemPrimaryTextColor + )), + maximumNumberOfLines: 1 + ))), + AnyComponentWithIdentity(id: AnyHashable(1), component: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: clientData?.region ?? "", + font: Font.regular(presentationData.listsFontSize.itemListBaseFontSize / 17.0 * 15.0), + textColor: theme.list.itemSecondaryTextColor + )), + horizontalAlignment: .left, + truncationType: .middle, + maximumNumberOfLines: 1 + ))) + ], alignment: .right, spacing: 3.0) + ) + ), + insets: UIEdgeInsets(top: 0.0, left: 8.0, bottom: 0.0, right: 14.0), + isInteractive: true + )), + action: nil + ) + )) + ) + + let clientSection = clientSection.update( + component: ListSectionComponent( + theme: theme, + style: .glass, + header: nil, + footer: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: "Session details are shown for security verification.", + font: Font.regular(presentationData.listsFontSize.itemListBaseHeaderFontSize), + textColor: environment.theme.list.freeTextColor + )), + maximumNumberOfLines: 0 + )), + items: clientSectionItems + ), + availableSize: CGSize(width: context.availableSize.width - sideInset * 2.0, height: context.availableSize.height), + transition: context.transition + ) + context.add(clientSection + .position(CGPoint(x: context.availableSize.width / 2.0, y: contentHeight + clientSection.size.height / 2.0)) + ) + contentHeight += clientSection.size.height + + if flags.contains(.requestWriteAccess) { + contentHeight += 38.0 + + var optionsSectionItems: [AnyComponentWithIdentity] = [] + optionsSectionItems.append(AnyComponentWithIdentity(id: "allowWrite", component: AnyComponent(ListActionItemComponent( + theme: theme, + style: .glass, + title: AnyComponent(VStack([ + AnyComponentWithIdentity(id: AnyHashable(0), component: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: "Allow Messages", + font: Font.regular(presentationData.listsFontSize.itemListBaseFontSize), + textColor: theme.list.itemPrimaryTextColor + )), + maximumNumberOfLines: 1 + ))), + ], alignment: .left, spacing: 2.0)), + accessory: .toggle(ListActionItemComponent.Toggle(style: .regular, isOn: state.allowWrite, action: { [weak state] _ in + guard let state else { + return + } + state.allowWrite = !state.allowWrite + state.updated() + })), + action: nil + )))) + let optionsSection = optionsSection.update( + component: ListSectionComponent( + theme: theme, + style: .glass, + header: nil, + footer: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString( + string: "Allow \(EnginePeer(bot).compactDisplayTitle) to send you messages.", + font: Font.regular(presentationData.listsFontSize.itemListBaseHeaderFontSize), + textColor: environment.theme.list.freeTextColor + )), + maximumNumberOfLines: 0 + )), + items: optionsSectionItems + ), + availableSize: CGSize(width: context.availableSize.width - sideInset * 2.0, height: context.availableSize.height), + transition: context.transition + ) + context.add(optionsSection + .position(CGPoint(x: context.availableSize.width / 2.0, y: contentHeight + optionsSection.size.height / 2.0)) + ) + contentHeight += optionsSection.size.height + } + contentHeight += 32.0 + + let buttonSpacing: CGFloat = 10.0 + let buttonInsets = ContainerViewLayout.concentricInsets(bottomInset: environment.safeInsets.bottom, innerDiameter: 52.0, sideInset: 30.0) + let buttonWidth = (context.availableSize.width - buttonInsets.left - buttonInsets.right - buttonSpacing) / 2.0 + + let cancelButton = cancelButton.update( + component: ButtonComponent( + background: ButtonComponent.Background( + style: .glass, + color: theme.list.itemPrimaryTextColor.withMultipliedAlpha(0.1), + foreground: theme.list.itemPrimaryTextColor, + pressedColor: theme.list.itemCheckColors.fillColor.withMultipliedAlpha(0.9) + ), + content: AnyComponentWithIdentity( + id: AnyHashable(0), + component: AnyComponent(MultilineTextComponent(text: .plain(NSMutableAttributedString(string: strings.Common_Cancel, font: Font.semibold(17.0), textColor: theme.list.itemPrimaryTextColor, paragraphAlignment: .center)))) + ), + action: { + component.cancel(true) + } + ), + availableSize: CGSize(width: buttonWidth, height: 52.0), + transition: .immediate + ) + context.add(cancelButton + .position(CGPoint(x: context.availableSize.width / 2.0 - buttonSpacing / 2.0 - cancelButton.size.width / 2.0, y: contentHeight + cancelButton.size.height / 2.0)) + ) + + let doneButton = doneButton.update( + component: ButtonComponent( + background: ButtonComponent.Background( + style: .glass, + color: theme.list.itemCheckColors.fillColor, + foreground: theme.list.itemCheckColors.foregroundColor, + pressedColor: theme.list.itemCheckColors.fillColor.withMultipliedAlpha(0.9), + cornerRadius: 10.0, + ), + content: AnyComponentWithIdentity( + id: AnyHashable(0), + component: AnyComponent(MultilineTextComponent(text: .plain(NSMutableAttributedString(string: "Continue", font: Font.semibold(17.0), textColor: theme.list.itemCheckColors.foregroundColor, paragraphAlignment: .center)))) + ), + displaysProgress: state.inProgress, + action: { [weak state] in + guard let state else { + return + } + var allowWrite = false + if flags.contains(.requestWriteAccess) && state.allowWrite { + allowWrite = true + } + + let accountContext = state.forcedAccount?.0 ?? component.context + guard let accountPeer = state.forcedAccount?.1 ?? state.peer else { + return + } + + if flags.contains(.requestPhoneNumber) { + state.displayPhoneNumberConfirmation(commit: { sharePhoneNumber in + component.completion(accountContext, accountPeer, allowWrite, sharePhoneNumber) + state.inProgress = true + state.updated() + }) + } else { + component.completion(accountContext, accountPeer, allowWrite, false) + state.inProgress = true + state.updated() + } + } + ), + availableSize: CGSize(width: buttonWidth, height: 52.0), + transition: .immediate + ) + context.add(doneButton + .position(CGPoint(x: context.availableSize.width / 2.0 + buttonSpacing / 2.0 + doneButton.size.width / 2.0, y: contentHeight + doneButton.size.height / 2.0)) + ) + contentHeight += doneButton.size.height + contentHeight += buttonInsets.bottom + + return CGSize(width: context.availableSize.width, height: contentHeight) + } + } +} + +private final class AuthConfirmationSheetComponent: CombinedComponent { + typealias EnvironmentType = ViewControllerComponentContainer.Environment + + let context: AccountContext + let subject: MessageActionUrlAuthResult + let completion: (AccountContext, EnginePeer, Bool, Bool) -> Void + + init( + context: AccountContext, + subject: MessageActionUrlAuthResult, + completion: @escaping (AccountContext, EnginePeer, Bool, Bool) -> Void + ) { + self.context = context + self.subject = subject + self.completion = completion + } + + static func ==(lhs: AuthConfirmationSheetComponent, rhs: AuthConfirmationSheetComponent) -> Bool { + if lhs.context !== rhs.context { + return false + } + return true + } + + static var body: Body { + let sheet = Child(SheetComponent.self) + let animateOut = StoredActionSlot(Action.self) + + return { context in + let environment = context.environment[EnvironmentType.self] + let controller = environment.controller + + let sheet = sheet.update( + component: SheetComponent( + content: AnyComponent(AuthConfirmationSheetContent( + context: context.component.context, + subject: context.component.subject, + completion: context.component.completion, + cancel: { animate in + if animate { + animateOut.invoke(Action { _ in + if let controller = controller() { + controller.dismiss(completion: nil) + } + }) + } else if let controller = controller() { + controller.dismiss(animated: false, completion: nil) + } + } + )), + style: .glass, + backgroundColor: .color(environment.theme.list.modalBlocksBackgroundColor), + followContentSizeChanges: true, + clipsContent: true, + animateOut: animateOut + ), + environment: { + environment + SheetComponentEnvironment( + isDisplaying: environment.value.isVisible, + isCentered: environment.metrics.widthClass == .regular, + hasInputHeight: !environment.inputHeight.isZero, + regularMetricsSize: CGSize(width: 430.0, height: 900.0), + dismiss: { animated in + if animated { + animateOut.invoke(Action { _ in + if let controller = controller() { + controller.dismiss(completion: nil) + } + }) + } else { + if let controller = controller() { + controller.dismiss(completion: nil) + } + } + } + ) + }, + availableSize: context.availableSize, + transition: context.transition + ) + + context.add(sheet + .position(CGPoint(x: context.availableSize.width / 2.0, y: context.availableSize.height / 2.0)) + ) + + return context.availableSize + } + } +} + +public class AuthConfirmationScreen: ViewControllerComponentContainer { + private let context: AccountContext + private let subject: MessageActionUrlAuthResult + fileprivate let completion: (AccountContext, EnginePeer, Bool, Bool) -> Void + + public init( + context: AccountContext, + subject: MessageActionUrlAuthResult, + completion: @escaping (AccountContext, EnginePeer, Bool, Bool) -> Void + ) { + self.context = context + self.subject = subject + self.completion = completion + + super.init( + context: context, + component: AuthConfirmationSheetComponent( + context: context, + subject: subject, + completion: completion + ), + navigationBarAppearance: .none, + statusBarStyle: .ignore, + theme: .default + ) + + self.navigationPresentation = .flatModal + } + + required public init(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + public override func viewDidLoad() { + super.viewDidLoad() + + self.view.disablesInteractiveModalDismiss = true + } + + public func dismissAnimated() { + if let view = self.node.hostView.findTaggedView(tag: SheetComponent.View.Tag()) as? SheetComponent.View { + view.dismissAnimated() + } + } +} + +private final class AuthConfirmationReferenceContentSource: ContextReferenceContentSource { + private let controller: ViewController + private let sourceView: UIView + + let forceDisplayBelowKeyboard = true + + init(controller: ViewController, sourceView: UIView) { + self.controller = controller + self.sourceView = sourceView + } + + func transitionInfo() -> ContextControllerReferenceViewInfo? { + return ContextControllerReferenceViewInfo(referenceView: self.sourceView, contentAreaInScreenSpace: UIScreen.main.bounds) + } +} diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageAnimatedStickerItemNode/Sources/ChatMessageAnimatedStickerItemNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageAnimatedStickerItemNode/Sources/ChatMessageAnimatedStickerItemNode.swift index 9a835b50..9df443be 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageAnimatedStickerItemNode/Sources/ChatMessageAnimatedStickerItemNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageAnimatedStickerItemNode/Sources/ChatMessageAnimatedStickerItemNode.swift @@ -83,6 +83,7 @@ public class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { public let contextSourceNode: ContextExtractedContentContainingNode private let containerNode: ContextControllerSourceNode public let imageNode: TransformImageNode + public var sizeCoefficient: Float = 1.0 private var enableSynchronousImageApply: Bool = false private var backgroundNode: WallpaperBubbleBackgroundNode? public private(set) var placeholderNode: StickerShimmerEffectNode @@ -117,7 +118,7 @@ public class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { private let disposables = DisposableSet() private var viaBotNode: TextNode? - private let dateAndStatusNode: ChatMessageDateAndStatusNode + public let dateAndStatusNode: ChatMessageDateAndStatusNode private var threadInfoNode: ChatMessageThreadInfoNode? private var replyInfoNode: ChatMessageReplyInfoNode? private var replyBackgroundContent: WallpaperBubbleBackgroundNode? @@ -1165,6 +1166,7 @@ public class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { context: item.context, presentationData: item.presentationData, edited: edited, + isDeleted: item.message.ghostgramIsDeleted, impressionCount: viewCount, dateText: dateText, type: statusType, @@ -1410,11 +1412,11 @@ public class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { ReplyMarkupMessageAttribute( rows: [ ReplyMarkupRow(buttons: [ - ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionReject, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonDecline)), - ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionApprove, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonApprove)) + ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionReject, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonDecline), style: nil), + ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionApprove, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonApprove), style: nil) ]), ReplyMarkupRow(buttons: [ - ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionSuggestChanges, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonSuggestChanges)) + ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionSuggestChanges, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonSuggestChanges), style: nil) ]) ], flags: [], diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageAttachedContentNode/Sources/ChatMessageAttachedContentNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageAttachedContentNode/Sources/ChatMessageAttachedContentNode.swift index 45ef4deb..c34d83e3 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageAttachedContentNode/Sources/ChatMessageAttachedContentNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageAttachedContentNode/Sources/ChatMessageAttachedContentNode.swift @@ -749,6 +749,7 @@ public final class ChatMessageAttachedContentNode: ASDisplayNode { context: context, presentationData: presentationData, edited: edited && !isPreview, + isDeleted: message.ghostgramIsDeleted, impressionCount: !isPreview ? viewCount : nil, dateText: dateText, type: statusType, diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageBubbleItemNode/BUILD b/submodules/TelegramUI/Components/Chat/ChatMessageBubbleItemNode/BUILD index d764dbd7..fc043190 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageBubbleItemNode/BUILD +++ b/submodules/TelegramUI/Components/Chat/ChatMessageBubbleItemNode/BUILD @@ -1,15 +1,25 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGStrings:SGStrings", + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//submodules/TranslateUI:TranslateUI" +] + +sgsrc = [ + "//Swiftgram/SGDoubleTapMessageAction:SGDoubleTapMessageAction" +] + swift_library( name = "ChatMessageBubbleItemNode", module_name = "ChatMessageBubbleItemNode", - srcs = glob([ + srcs = sgsrc + glob([ "Sources/**/*.swift", ]), copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/AsyncDisplayKit", "//submodules/Display", "//submodules/SSignalKit/SwiftSignalKit", diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageBubbleItemNode/Sources/ChatMessageBubbleItemNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageBubbleItemNode/Sources/ChatMessageBubbleItemNode.swift index 2fa5cd2f..97d7463f 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageBubbleItemNode/Sources/ChatMessageBubbleItemNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageBubbleItemNode/Sources/ChatMessageBubbleItemNode.swift @@ -1,3 +1,6 @@ +import SGStrings +import SGSimpleSettings +import TranslateUI import Foundation import UIKit import AsyncDisplayKit @@ -132,7 +135,7 @@ private func contentNodeMessagesAndClassesForItem(_ item: ChatMessageItem) -> ([ outer: for (message, itemAttributes) in item.content { for attribute in message.attributes { - if let attribute = attribute as? RestrictedContentMessageAttribute, attribute.platformText(platform: "ios", contentSettings: item.context.currentContentSettings.with { $0 }) != nil { + if let attribute = attribute as? RestrictedContentMessageAttribute, attribute.platformText(platform: "ios", contentSettings: item.context.currentContentSettings.with { $0 }, chatId: message.author?.id.id._internalGetInt64Value()) != nil { result.append((message, ChatMessageRestrictedBubbleContentNode.self, itemAttributes, BubbleItemAttributes(isAttachment: false, neighborType: .text, neighborSpacing: .default))) needReactions = false break outer @@ -316,6 +319,35 @@ private func contentNodeMessagesAndClassesForItem(_ item: ChatMessageItem) -> ([ isMediaInverted = true } + + // MARK: Swiftgram + var message = message + if message.canRevealContent(contentSettings: item.context.currentContentSettings.with { $0 }) { + let originalTextLength = message.text.count + let noticeString = i18n("Message.HoldToShowOrReport", item.presentationData.strings.baseLanguageCode) + + message = message.withUpdatedText(message.text + "\n" + noticeString) + let noticeStringLength = noticeString.count + let startIndex = originalTextLength + 1 // +1 for the newline character + // Calculate the end index, which is the start index plus the length of noticeString + let endIndex = startIndex + noticeStringLength + + var newAttributes = message.attributes + newAttributes.append( + TextEntitiesMessageAttribute( + entities: [ + MessageTextEntity( + range: startIndex.. Bool { - return AntiDeleteManager.shared.isMessageDeleted(peerId: message.id.peerId.toInt64(), messageId: message.id.id) || AntiDeleteManager.shared.isMessageDeleted(text: message.text) + return message.ghostgramIsDeleted } public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewItemNode { @@ -1235,7 +1267,6 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI if let shareButtonNode = strongSelf.shareButtonNode, shareButtonNode.frame.contains(point) { return .fail } - if let actionButtonsNode = strongSelf.actionButtonsNode { if let _ = actionButtonsNode.hitTest(strongSelf.view.convert(point, to: actionButtonsNode.view), with: nil) { return .fail @@ -1734,6 +1765,7 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI let isFailed = item.content.firstMessage.effectivelyFailed(timestamp: item.context.account.network.getApproximateRemoteTimestamp()) var needsShareButton = false + var mayHaveSeparateCommentsButton = false // MARK: Swiftgram var needsSummarizeButton = false if incoming, case let .customChatContents(contents) = item.associatedData.subject, case .hashTagSearch = contents.kind { @@ -1789,7 +1821,7 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI needsShareButton = true } } - var mayHaveSeparateCommentsButton = false + // var mayHaveSeparateCommentsButton = false // MARK: Swiftgram if !needsShareButton { loop: for media in item.message.media { if media is TelegramMediaGame || media is TelegramMediaInvoice { @@ -1831,7 +1863,7 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI needsShareButton = true } for attribute in item.content.firstMessage.attributes { - if let attribute = attribute as? RestrictedContentMessageAttribute, attribute.platformText(platform: "ios", contentSettings: item.context.currentContentSettings.with { $0 }) != nil { + if let attribute = attribute as? RestrictedContentMessageAttribute, attribute.platformText(platform: "ios", contentSettings: item.context.currentContentSettings.with { $0 }, chatId: item.content.firstMessage.author?.id.id._internalGetInt64Value()) != nil { needsShareButton = false needsSummarizeButton = false } @@ -1862,11 +1894,21 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI } tmpWidth -= deliveryFailedInset + // MARK: Swifgram + let renderWideChannelPosts: Bool + if let channel = item.message.peers[item.message.id.peerId] as? TelegramChannel, case .broadcast = channel.info, SGSimpleSettings.shared.wideChannelPosts, !(mayHaveSeparateCommentsButton && hasCommentButton(item: item)) { + renderWideChannelPosts = true + + tmpWidth = baseWidth + needsShareButton = false + } else { + renderWideChannelPosts = false + } let (contentNodeMessagesAndClasses, needSeparateContainers, needReactions) = contentNodeMessagesAndClassesForItem(item) var maximumContentWidth = floor(tmpWidth - layoutConstants.bubble.edgeInset * 3.0 - layoutConstants.bubble.contentInsets.left - layoutConstants.bubble.contentInsets.right - avatarInset) - if (needsShareButton && !isSidePanelOpen) { + if needsShareButton && !isSidePanelOpen { maximumContentWidth -= 10.0 } @@ -2386,13 +2428,29 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI var mosaicStatusSizeAndApply: (CGSize, (ListViewItemUpdateAnimation) -> ChatMessageDateAndStatusNode)? if let mosaicRange = mosaicRange { - let maxSize = layoutConstants.image.maxDimensions.fittedToWidthOrSmaller(maximumContentWidth - layoutConstants.image.bubbleInsets.left - layoutConstants.image.bubbleInsets.right) - let (innerFramesAndPositions, innerSize) = chatMessageBubbleMosaicLayout(maxSize: maxSize, itemSizes: contentPropertiesAndLayouts[mosaicRange].map { item in + // MARK: Swiftgram + var maxDimensions = layoutConstants.image.maxDimensions + if renderWideChannelPosts { + maxDimensions.width = maximumContentWidth + } + var maxSize = maxDimensions.fittedToWidthOrSmaller(maximumContentWidth - layoutConstants.image.bubbleInsets.left - layoutConstants.image.bubbleInsets.right) + var (innerFramesAndPositions, innerSize) = chatMessageBubbleMosaicLayout(maxSize: maxSize, itemSizes: contentPropertiesAndLayouts[mosaicRange].map { item in guard let size = item.0, size.width > 0.0, size.height > 0 else { return CGSize(width: 256.0, height: 256.0) } return size - }) + }/*, TODO(swiftgram): fillWidth: SGSimpleSettings.shared.wideChannelPosts */) + // MARK: Swiftgram + if innerSize.height > maxSize.height, maxDimensions.width != layoutConstants.image.maxDimensions.width { + maxDimensions.width = max(round(maxDimensions.width * maxSize.height / innerSize.height), layoutConstants.image.maxDimensions.width) + maxSize = maxDimensions.fittedToWidthOrSmaller(maximumContentWidth - layoutConstants.image.bubbleInsets.left - layoutConstants.image.bubbleInsets.right) + (innerFramesAndPositions, innerSize) = chatMessageBubbleMosaicLayout(maxSize: maxSize, itemSizes: contentPropertiesAndLayouts[mosaicRange].map { item in + guard let size = item.0, size.width > 0.0, size.height > 0 else { + return CGSize(width: 256.0, height: 256.0) + } + return size + }/*, TODO(swiftgram): fillWidth: SGSimpleSettings.shared.wideChannelPosts */) + } let framesAndPositions = innerFramesAndPositions.map { ($0.0.offsetBy(dx: layoutConstants.image.bubbleInsets.left, dy: layoutConstants.image.bubbleInsets.top), $0.1) } @@ -2474,6 +2532,7 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI context: item.context, presentationData: item.presentationData, edited: edited && !item.presentationData.isPreview, + isDeleted: message.ghostgramIsDeleted, impressionCount: !item.presentationData.isPreview ? viewCount : nil, dateText: dateText, type: statusType, @@ -2852,7 +2911,7 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI ReplyMarkupMessageAttribute( rows: [ ReplyMarkupRow( - buttons: [ReplyMarkupButton(title: item.presentationData.strings.Channel_AdminLog_ShowMoreMessages(Int32(messages.count - 1)), titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: MemoryBuffer(data: Data())))] + buttons: [ReplyMarkupButton(title: item.presentationData.strings.Channel_AdminLog_ShowMoreMessages(Int32(messages.count - 1)), titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: MemoryBuffer(data: Data())), style: nil)] ) ], flags: [], @@ -2891,8 +2950,8 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI ReplyMarkupMessageAttribute( rows: [ ReplyMarkupRow(buttons: [ - ReplyMarkupButton(title: item.presentationData.strings.Chat_GiftPurchaseOffer_Reject, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonDecline)), - ReplyMarkupButton(title: item.presentationData.strings.Chat_GiftPurchaseOffer_Accept, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonApprove)) + ReplyMarkupButton(title: item.presentationData.strings.Chat_GiftPurchaseOffer_Reject, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonDecline), style: nil), + ReplyMarkupButton(title: item.presentationData.strings.Chat_GiftPurchaseOffer_Accept, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonApprove), style: nil) ]) ], flags: [], @@ -2940,11 +2999,11 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI ReplyMarkupMessageAttribute( rows: [ ReplyMarkupRow(buttons: [ - ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionReject, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonDecline)), - ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionApprove, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonApprove)) + ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionReject, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonDecline), style: nil), + ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionApprove, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonApprove), style: nil) ]), ReplyMarkupRow(buttons: [ - ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionSuggestChanges, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonSuggestChanges)) + ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionSuggestChanges, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonSuggestChanges), style: nil) ]) ], flags: [], @@ -2978,7 +3037,7 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI ReplyMarkupMessageAttribute( rows: [ ReplyMarkupRow(buttons: [ - ReplyMarkupButton(title: item.presentationData.strings.Chat_MessageContinueLastThread, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: button)) + ReplyMarkupButton(title: item.presentationData.strings.Chat_MessageContinueLastThread, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: button), style: nil) ]) ], flags: [], @@ -4371,7 +4430,7 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI strongSelf.replyInfoNode = nil } } - + let deletedMessageAlpha = CGFloat(AntiDeleteManager.shared.deletedMessageDisplayAlpha) var deletedMessageStableIds = Set() for (message, _) in item.content { @@ -4524,7 +4583,7 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI } contentContainer?.update(size: relativeFrame.size, contentOrigin: contentOrigin, selectionInsets: selectionInsets, index: index, presentationData: item.presentationData, graphics: graphics, backgroundType: backgroundType, presentationContext: item.controllerInteraction.presentationContext, mediaBox: item.context.account.postbox.mediaBox, messageSelection: itemSelection) - + if let contentContainer = contentContainer { let containerAlpha: CGFloat = deletedMessageStableIds.contains(stableId) ? deletedMessageAlpha : 1.0 if case .System = animation { @@ -4536,7 +4595,7 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI index += 1 } - + let mainContainerAlpha: CGFloat if contentContainerNodeFrames.isEmpty, !deletedMessageStableIds.isEmpty { mainContainerAlpha = deletedMessageAlpha @@ -5153,7 +5212,7 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI animation.animator.updateAlpha(layer: shareButtonNode.layer, alpha: (isCurrentlyPlayingMedia || isSidePanelOpen) ? 0.0 : 1.0, completion: nil) animation.animator.updateScale(layer: shareButtonNode.layer, scale: (isCurrentlyPlayingMedia || isSidePanelOpen) ? 0.001 : 1.0, completion: nil) } - + if case .System = animation, strongSelf.mainContextSourceNode.isExtractedToContextPreview { legacyTransition.updateFrame(node: strongSelf.backgroundNode, frame: backgroundFrame) if let backgroundHighlightNode = strongSelf.backgroundHighlightNode { @@ -5291,18 +5350,32 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI case let .optionalAction(f): f() case let .openContextMenu(openContextMenu): + switch (sgDoubleTapMessageAction(incoming: openContextMenu.tapMessage.effectivelyIncoming(item.context.account.peerId), message: openContextMenu.tapMessage)) { + case SGSimpleSettings.MessageDoubleTapAction.none.rawValue: + break + case SGSimpleSettings.MessageDoubleTapAction.edit.rawValue: + item.controllerInteraction.sgStartMessageEdit(openContextMenu.tapMessage) + default: if canAddMessageReactions(message: openContextMenu.tapMessage) { item.controllerInteraction.updateMessageReaction(openContextMenu.tapMessage, .default, false, nil) } else { item.controllerInteraction.openMessageContextMenu(openContextMenu.tapMessage, openContextMenu.selectAll, self, openContextMenu.subFrame, nil, nil) } + } } } else if case .tap = gesture { item.controllerInteraction.clickThroughMessage(self.view, location) } else if case .doubleTap = gesture { + switch (sgDoubleTapMessageAction(incoming: item.message.effectivelyIncoming(item.context.account.peerId), message: item.message)) { + case SGSimpleSettings.MessageDoubleTapAction.none.rawValue: + break + case SGSimpleSettings.MessageDoubleTapAction.edit.rawValue: + item.controllerInteraction.sgStartMessageEdit(item.message) + default: if canAddMessageReactions(message: item.message) { item.controllerInteraction.updateMessageReaction(item.message, .default, false, nil) } + } } } default: @@ -5971,7 +6044,6 @@ public class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewI if let shareButtonNode = self.shareButtonNode, shareButtonNode.frame.contains(point) { return shareButtonNode.view.hitTest(self.view.convert(point, to: shareButtonNode.view), with: event) } - if let selectionNode = self.selectionNode { if let result = self.traceSelectionNodes(parent: self, point: point.offsetBy(dx: -42.0, dy: 0.0)) { return result.view diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageContactBubbleContentNode/Sources/ChatMessageContactBubbleContentNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageContactBubbleContentNode/Sources/ChatMessageContactBubbleContentNode.swift index b668005c..66a50e4f 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageContactBubbleContentNode/Sources/ChatMessageContactBubbleContentNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageContactBubbleContentNode/Sources/ChatMessageContactBubbleContentNode.swift @@ -298,6 +298,7 @@ public class ChatMessageContactBubbleContentNode: ChatMessageBubbleContentNode { context: item.context, presentationData: item.presentationData, edited: edited, + isDeleted: item.topMessage.ghostgramIsDeleted, impressionCount: viewCount, dateText: dateText, type: statusType, diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageDateAndStatusNode/BUILD b/submodules/TelegramUI/Components/Chat/ChatMessageDateAndStatusNode/BUILD index 87db0a75..2eb7c11a 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageDateAndStatusNode/BUILD +++ b/submodules/TelegramUI/Components/Chat/ChatMessageDateAndStatusNode/BUILD @@ -1,5 +1,9 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + swift_library( name = "ChatMessageDateAndStatusNode", module_name = "ChatMessageDateAndStatusNode", @@ -9,7 +13,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/AsyncDisplayKit", "//submodules/Postbox", "//submodules/TelegramCore", diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageDateAndStatusNode/Sources/ChatMessageDateAndStatusNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageDateAndStatusNode/Sources/ChatMessageDateAndStatusNode.swift index eb78bd5a..d46054a7 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageDateAndStatusNode/Sources/ChatMessageDateAndStatusNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageDateAndStatusNode/Sources/ChatMessageDateAndStatusNode.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import AsyncDisplayKit @@ -30,6 +31,10 @@ private func maybeAddRotationAnimation(_ layer: CALayer, duration: Double) { layer.add(basicAnimation, forKey: "clockFrameAnimation") } +private func generateDeletedStatusIcon(color: UIColor) -> UIImage? { + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Delete"), color: color)?.precomposed() +} + public enum ChatMessageDateAndStatusOutgoingType: Equatable { case Sent(read: Bool) case Sending @@ -183,6 +188,7 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { var context: AccountContext var presentationData: ChatPresentationData var edited: Bool + var isDeleted: Bool var impressionCount: Int? var dateText: String var type: ChatMessageDateAndStatusType @@ -201,7 +207,6 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { var tonAmount: Int64? var isPinned: Bool var hasAutoremove: Bool - var isDeleted: Bool var canViewReactionList: Bool var animationCache: AnimationCache var animationRenderer: MultiAnimationRenderer @@ -210,6 +215,7 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { context: AccountContext, presentationData: ChatPresentationData, edited: Bool, + isDeleted: Bool, impressionCount: Int?, dateText: String, type: ChatMessageDateAndStatusType, @@ -228,7 +234,6 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { tonAmount: Int64? = nil, isPinned: Bool, hasAutoremove: Bool, - isDeleted: Bool = false, canViewReactionList: Bool, animationCache: AnimationCache, animationRenderer: MultiAnimationRenderer @@ -236,6 +241,7 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { self.context = context self.presentationData = presentationData self.edited = edited + self.isDeleted = isDeleted self.impressionCount = impressionCount == 0 ? nil : impressionCount self.dateText = dateText self.type = type @@ -254,7 +260,6 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { self.tonAmount = tonAmount self.isPinned = isPinned self.hasAutoremove = hasAutoremove - self.isDeleted = isDeleted self.canViewReactionList = canViewReactionList self.animationCache = animationCache self.animationRenderer = animationRenderer @@ -268,6 +273,7 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { private var clockFrameNode: ASImageNode? private var clockMinNode: ASImageNode? private let dateNode: TextNode + private var deletedIcon: ASImageNode? private var impressionIcon: ASImageNode? private var reactionNodes: [MessageReaction.Reaction: StatusReactionNode] = [:] private let reactionButtonsContainer = ReactionButtonsAsyncLayoutContainer() @@ -277,7 +283,6 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { private var replyCountNode: TextNode? private var starsIcon: ASImageNode? private var starsCountNode: TextNode? - private var deletedIcon: ASImageNode? private var type: ChatMessageDateAndStatusType? private var theme: ChatPresentationThemeData? @@ -330,6 +335,7 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { var clockMinNode = self.clockMinNode var currentBackgroundNode = self.backgroundNode + var currentDeletedIcon = self.deletedIcon var currentImpressionIcon = self.impressionIcon var currentRepliesIcon = self.repliesIcon var currentStarsIcon = self.starsIcon @@ -353,6 +359,7 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { let loadedCheckPartialImage: UIImage? let clockFrameImage: UIImage? let clockMinImage: UIImage? + let deletedImage: UIImage? var impressionImage: UIImage? var repliesImage: UIImage? var starsImage: UIImage? @@ -541,6 +548,8 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { starsImage = graphics.freeTonIcon } } + + deletedImage = arguments.isDeleted ? generateDeletedStatusIcon(color: dateColor) : nil var updatedDateText = arguments.dateText if arguments.edited { @@ -561,6 +570,23 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { var checkReadFrame: CGRect? var clockPosition = CGPoint() + + var deletedSize = CGSize() + var deletedWidth: CGFloat = 0.0 + if deletedImage != nil { + if currentDeletedIcon == nil { + let iconNode = ASImageNode() + iconNode.isLayerBacked = true + iconNode.displayWithoutProcessing = true + iconNode.displaysAsynchronously = false + iconNode.contentMode = .scaleAspectFit + currentDeletedIcon = iconNode + } + deletedSize = CGSize(width: 11.0, height: 11.0) + deletedWidth = deletedSize.width + 4.0 + } else { + currentDeletedIcon = nil + } var impressionSize = CGSize() var impressionWidth: CGFloat = 0.0 @@ -606,36 +632,6 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { currentStarsIcon = nil } - // ANTIDELETE: Deleted message icon - var currentDeletedIcon = self?.deletedIcon - var deletedIconSize = CGSize() - if arguments.isDeleted { - if currentDeletedIcon == nil { - let iconNode = ASImageNode() - iconNode.isLayerBacked = true - iconNode.displayWithoutProcessing = true - iconNode.displaysAsynchronously = false - currentDeletedIcon = iconNode - } - // Use trash icon from bundle or create simple one - let deletedImage = UIImage(bundleImageName: "Chat/Message/DeletedIcon") ?? generateTintedImage(image: UIImage(systemName: "trash"), color: dateColor) - deletedIconSize = deletedImage?.size ?? CGSize(width: 10, height: 10) - // Scale down the image - if let img = deletedImage { - let scaledSize = CGSize(width: 10, height: 10) - UIGraphicsBeginImageContextWithOptions(scaledSize, false, 0.0) - img.draw(in: CGRect(origin: .zero, size: scaledSize)) - let scaledImage = UIGraphicsGetImageFromCurrentImageContext() - UIGraphicsEndImageContext() - currentDeletedIcon?.image = scaledImage - deletedIconSize = scaledSize - } else { - currentDeletedIcon?.image = deletedImage - } - } else { - currentDeletedIcon = nil - } - if let outgoingStatus = outgoingStatus { switch outgoingStatus { case .Sending: @@ -670,7 +666,7 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { clockMinNode?.displayWithoutProcessing = true clockMinNode?.frame = CGRect(origin: CGPoint(), size: clockMinImage?.size ?? CGSize()) } - clockPosition = CGPoint(x: leftInset + date.size.width + 8.5, y: 7.5 + offset) + clockPosition = CGPoint(x: leftInset + deletedWidth + impressionWidth + date.size.width + 8.5, y: 7.5 + offset) case let .Sent(read): let hideStatus: Bool switch arguments.type { @@ -710,9 +706,9 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { let checkSize = loadedCheckFullImage!.size if read { - checkReadFrame = CGRect(origin: CGPoint(x: leftInset + impressionWidth + date.size.width + 5.0 + statusWidth - checkSize.width, y: 3.0 + offset), size: checkSize) + checkReadFrame = CGRect(origin: CGPoint(x: leftInset + deletedWidth + impressionWidth + date.size.width + 5.0 + statusWidth - checkSize.width, y: 3.0 + offset), size: checkSize) } - checkSentFrame = CGRect(origin: CGPoint(x: leftInset + impressionWidth + date.size.width + 5.0 + statusWidth - checkSize.width - checkOffset, y: 3.0 + offset), size: checkSize) + checkSentFrame = CGRect(origin: CGPoint(x: leftInset + deletedWidth + impressionWidth + date.size.width + 5.0 + statusWidth - checkSize.width - checkOffset, y: 3.0 + offset), size: checkSize) } case .Failed: statusWidth = 0.0 @@ -799,15 +795,9 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { reactionInset += 13.0 } - // ANTIDELETE: Add deleted icon space - var deletedIconWidth: CGFloat = 0.0 - if arguments.isDeleted { - deletedIconWidth = deletedIconSize.width + 3.0 - } - leftInset += reactionInset - let layoutSize = CGSize(width: leftInset + deletedIconWidth + impressionWidth + date.size.width + statusWidth + backgroundInsets.left + backgroundInsets.right, height: date.size.height + backgroundInsets.top + backgroundInsets.bottom) + let layoutSize = CGSize(width: leftInset + deletedWidth + impressionWidth + date.size.width + statusWidth + backgroundInsets.left + backgroundInsets.right, height: date.size.height + backgroundInsets.top + backgroundInsets.bottom) let verticalReactionsInset: CGFloat let verticalInset: CGFloat @@ -1132,8 +1122,26 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { let _ = dateApply() + if let currentDeletedIcon = currentDeletedIcon { + let deletedIconFrame = CGRect(origin: CGPoint(x: leftOffset + leftInset + backgroundInsets.left, y: backgroundInsets.top + 1.0 + offset + verticalInset + floor((date.size.height - deletedSize.height) / 2.0)), size: deletedSize) + currentDeletedIcon.displaysAsynchronously = false + if currentDeletedIcon.image !== deletedImage { + currentDeletedIcon.image = deletedImage + } + if currentDeletedIcon.supernode == nil { + strongSelf.deletedIcon = currentDeletedIcon + strongSelf.addSubnode(currentDeletedIcon) + currentDeletedIcon.frame = deletedIconFrame + } else { + animation.animator.updateFrame(layer: currentDeletedIcon.layer, frame: deletedIconFrame, completion: nil) + } + } else if let deletedIcon = strongSelf.deletedIcon { + deletedIcon.removeFromSupernode() + strongSelf.deletedIcon = nil + } + if let currentImpressionIcon = currentImpressionIcon { - let impressionIconFrame = CGRect(origin: CGPoint(x: leftOffset + leftInset + backgroundInsets.left, y: backgroundInsets.top + 1.0 + offset + verticalInset + floor((date.size.height - impressionSize.height) / 2.0)), size: impressionSize) + let impressionIconFrame = CGRect(origin: CGPoint(x: leftOffset + leftInset + backgroundInsets.left + deletedWidth, y: backgroundInsets.top + 1.0 + offset + verticalInset + floor((date.size.height - impressionSize.height) / 2.0)), size: impressionSize) currentImpressionIcon.displaysAsynchronously = false if currentImpressionIcon.image !== impressionImage { currentImpressionIcon.image = impressionImage @@ -1150,22 +1158,7 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { strongSelf.impressionIcon = nil } - // ANTIDELETE: Position deleted icon - if let currentDeletedIcon = currentDeletedIcon { - let deletedIconFrame = CGRect(origin: CGPoint(x: leftOffset + leftInset + backgroundInsets.left + impressionWidth, y: backgroundInsets.top + 1.0 + offset + verticalInset + floor((date.size.height - deletedIconSize.height) / 2.0)), size: deletedIconSize) - if currentDeletedIcon.supernode == nil { - strongSelf.deletedIcon = currentDeletedIcon - strongSelf.addSubnode(currentDeletedIcon) - currentDeletedIcon.frame = deletedIconFrame - } else { - animation.animator.updateFrame(layer: currentDeletedIcon.layer, frame: deletedIconFrame, completion: nil) - } - } else if let deletedIcon = strongSelf.deletedIcon { - deletedIcon.removeFromSupernode() - strongSelf.deletedIcon = nil - } - - animation.animator.updateFrame(layer: strongSelf.dateNode.layer, frame: CGRect(origin: CGPoint(x: leftOffset + leftInset + backgroundInsets.left + impressionWidth + deletedIconWidth, y: backgroundInsets.top + 1.0 + offset + verticalInset), size: date.size), completion: nil) + animation.animator.updateFrame(layer: strongSelf.dateNode.layer, frame: CGRect(origin: CGPoint(x: leftOffset + leftInset + backgroundInsets.left + deletedWidth + impressionWidth, y: backgroundInsets.top + 1.0 + offset + verticalInset), size: date.size), completion: nil) if let clockFrameNode = clockFrameNode { let clockPosition = CGPoint(x: leftOffset + backgroundInsets.left + clockPosition.x + reactionInset, y: backgroundInsets.top + clockPosition.y + verticalInset) @@ -1527,5 +1520,7 @@ public class ChatMessageDateAndStatusNode: ASDisplayNode { } public func shouldDisplayInlineDateReactions(message: Message, isPremium: Bool, forceInline: Bool) -> Bool { - return false + // MARK: Swiftgram + // With 10.13 it now hides reactions in favor of message effect badge + return SGSimpleSettings.shared.hideReactions } diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageFactCheckBubbleContentNode/Sources/ChatMessageFactCheckBubbleContentNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageFactCheckBubbleContentNode/Sources/ChatMessageFactCheckBubbleContentNode.swift index 6102bf22..fd4ed9c9 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageFactCheckBubbleContentNode/Sources/ChatMessageFactCheckBubbleContentNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageFactCheckBubbleContentNode/Sources/ChatMessageFactCheckBubbleContentNode.swift @@ -437,6 +437,7 @@ public class ChatMessageFactCheckBubbleContentNode: ChatMessageBubbleContentNode context: item.context, presentationData: item.presentationData, edited: edited && !item.presentationData.isPreview, + isDeleted: message.ghostgramIsDeleted, impressionCount: !item.presentationData.isPreview ? viewCount : nil, dateText: dateText, type: statusType, diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageGiftBubbleContentNode/Sources/ChatMessageGiftBubbleContentNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageGiftBubbleContentNode/Sources/ChatMessageGiftBubbleContentNode.swift index b19d721b..ae54a37a 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageGiftBubbleContentNode/Sources/ChatMessageGiftBubbleContentNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageGiftBubbleContentNode/Sources/ChatMessageGiftBubbleContentNode.swift @@ -282,7 +282,7 @@ public class ChatMessageGiftBubbleContentNode: ChatMessageBubbleContentNode { switch action.action { case let .starGift(gift, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): releasedBy = gift.releasedBy - case let .starGiftUnique(gift, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + case let .starGiftUnique(gift, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): releasedBy = gift.releasedBy default: break @@ -378,6 +378,17 @@ public class ChatMessageGiftBubbleContentNode: ChatMessageBubbleContentNode { } override public func asyncLayoutContent() -> (_ item: ChatMessageBubbleContentItem, _ layoutConstants: ChatMessageItemLayoutConstants, _ preparePosition: ChatMessageBubblePreparePosition, _ messageSelection: Bool?, _ constrainedSize: CGSize, _ avatarInset: CGFloat) -> (ChatMessageBubbleContentProperties, unboundSize: CGSize?, maxWidth: CGFloat, layout: (CGSize, ChatMessageBubbleContentPosition) -> (CGFloat, (CGFloat) -> (CGSize, (ListViewItemUpdateAnimation, Bool, ListViewItemApply?) -> Void))) { + return { item, _, _, _, _, _ in + let contentProperties = ChatMessageBubbleContentProperties(hidesSimpleAuthorHeader: true, headerSpacing: 0.0, hidesBackground: .always, forceFullCorners: false, forceAlignment: .center) + return (contentProperties, nil, 220.0, { _, _ in + return (220.0, { _ in + return (CGSize(width: 220.0, height: 120.0), { [weak self] _, _, _ in + self?.item = item + }) + }) + }) + } +#if false let makeLabelLayout = TextNode.asyncLayout(self.labelNode) let makeTitleLayout = TextNode.asyncLayout(self.titleNode) let makeSubtitleLayout = TextNodeWithEntities.asyncLayout(self.subtitleNode) @@ -402,10 +413,10 @@ public class ChatMessageGiftBubbleContentNode: ChatMessageBubbleContentNode { let cachedTonImage = self.cachedTonImage - return { item, layoutConstants, _, _, _, _ in + let asyncLayout: (ChatMessageBubbleContentItem, ChatMessageItemLayoutConstants, ChatMessageBubblePreparePosition, Bool?, CGSize, CGFloat) -> (ChatMessageBubbleContentProperties, CGSize?, CGFloat, (CGSize, ChatMessageBubbleContentPosition) -> (CGFloat, (CGFloat) -> (CGSize, (ListViewItemUpdateAnimation, Bool, ListViewItemApply?) -> Void))) = { (item: ChatMessageBubbleContentItem, layoutConstants: ChatMessageItemLayoutConstants, preparePosition: ChatMessageBubblePreparePosition, messageSelection: Bool?, constrainedSize: CGSize, avatarInset: CGFloat) in let contentProperties = ChatMessageBubbleContentProperties(hidesSimpleAuthorHeader: true, headerSpacing: 0.0, hidesBackground: .always, forceFullCorners: false, forceAlignment: .center) - return (contentProperties, nil, CGFloat.greatestFiniteMagnitude, { constrainedSize, position in + return (contentProperties, nil, CGFloat.greatestFiniteMagnitude, { (constrainedSize: CGSize, position: ChatMessageBubbleContentPosition) -> (CGFloat, (CGFloat) -> (CGSize, (ListViewItemUpdateAnimation, Bool, ListViewItemApply?) -> Void)) in var giftSize = CGSize(width: 220.0, height: 240.0) let incoming: Bool @@ -1471,6 +1482,8 @@ public class ChatMessageGiftBubbleContentNode: ChatMessageBubbleContentNode { }) }) } + return asyncLayout +#endif } override public func updateAbsoluteRect(_ rect: CGRect, within containerSize: CGSize) { diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageGiveawayBubbleContentNode/Sources/ChatMessageGiveawayBubbleContentNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageGiveawayBubbleContentNode/Sources/ChatMessageGiveawayBubbleContentNode.swift index fbb56f38..c30b7b7f 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageGiveawayBubbleContentNode/Sources/ChatMessageGiveawayBubbleContentNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageGiveawayBubbleContentNode/Sources/ChatMessageGiveawayBubbleContentNode.swift @@ -565,6 +565,7 @@ public class ChatMessageGiveawayBubbleContentNode: ChatMessageBubbleContentNode, context: item.context, presentationData: item.presentationData, edited: edited, + isDeleted: item.topMessage.ghostgramIsDeleted, impressionCount: !item.presentationData.isPreview ? viewCount : nil, dateText: dateText, type: statusType, diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveFileNode/BUILD b/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveFileNode/BUILD index 555ad4a0..31df24c0 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveFileNode/BUILD +++ b/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveFileNode/BUILD @@ -1,5 +1,10 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + + swift_library( name = "ChatMessageInteractiveFileNode", module_name = "ChatMessageInteractiveFileNode", @@ -9,7 +14,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/AsyncDisplayKit", "//submodules/Postbox", "//submodules/SSignalKit/SwiftSignalKit", diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveFileNode/Sources/ChatMessageInteractiveFileNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveFileNode/Sources/ChatMessageInteractiveFileNode.swift index 7e79f7dc..90db9284 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveFileNode/Sources/ChatMessageInteractiveFileNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveFileNode/Sources/ChatMessageInteractiveFileNode.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import AsyncDisplayKit @@ -349,16 +350,53 @@ public final class ChatMessageInteractiveFileNode: ASDisplayNode { } private func transcribe() { - guard let _ = self.arguments, let context = self.context, let message = self.message else { + guard let arguments = self.arguments, let context = self.context, let message = self.message else { return } - if !context.isPremium, case .inProgress = self.audioTranscriptionState { + if /*!context.isPremium,*/ case .inProgress = self.audioTranscriptionState { return } let presentationData = context.sharedContext.currentPresentationData.with { $0 } - // GHOSTGRAM: Premium check removed - local transcription is free! + let premiumConfiguration = PremiumConfiguration.with(appConfiguration: arguments.context.currentAppConfiguration.with { $0 }) + + let transcriptionText = self.forcedAudioTranscriptionText ?? transcribedText(message: message) + // MARK: Swiftgram + if transcriptionText == nil && false { + if premiumConfiguration.audioTransciptionTrialCount > 0 { + if !arguments.associatedData.isPremium { + if self.presentAudioTranscriptionTooltip(finished: false) { + return + } + } + } else { + guard arguments.associatedData.isPremium else { + if self.hapticFeedback == nil { + self.hapticFeedback = HapticFeedback() + } + self.hapticFeedback?.impact(.medium) + + let tipController = UndoOverlayController(presentationData: presentationData, content: .universal(animation: "anim_voiceToText", scale: 0.065, colors: [:], title: nil, text: presentationData.strings.Message_AudioTranscription_SubscribeToPremium, customUndoText: presentationData.strings.Message_AudioTranscription_SubscribeToPremiumAction, timeout: nil), elevatedLayout: false, position: .top, animateInAsReplacement: false, action: { action in + if case .undo = action { + var replaceImpl: ((ViewController) -> Void)? + let controller = context.sharedContext.makePremiumDemoController(context: context, subject: .voiceToText, forceDark: false, action: { + let controller = context.sharedContext.makePremiumIntroController(context: context, source: .settings, forceDark: false, dismissed: nil) + replaceImpl?(controller) + }, dismissed: nil) + replaceImpl = { [weak controller] c in + controller?.replace(with: c) + } + arguments.controllerInteraction.navigationController()?.pushViewController(controller, animated: true) + + let _ = ApplicationSpecificNotice.incrementAudioTranscriptionSuggestion(accountManager: context.sharedContext.accountManager).startStandalone() + } + return false }) + arguments.controllerInteraction.presentControllerInCurrent(tipController, nil) + return + } + } + } var shouldBeginTranscription = false var shouldExpandNow = false @@ -384,8 +422,7 @@ public final class ChatMessageInteractiveFileNode: ASDisplayNode { self.audioTranscriptionState = .inProgress self.requestUpdateLayout(true) - // GHOSTGRAM: Always use local transcription (free, private, on-device!) - if true { + if context.sharedContext.immediateExperimentalUISettings.localTranscription || !arguments.associatedData.isPremium || SGSimpleSettings.shared.transcriptionBackend == SGSimpleSettings.TranscriptionBackend.apple.rawValue { let appLocale = presentationData.strings.baseLanguageCode let signal: Signal = context.engine.data.get(TelegramEngine.EngineData.Item.Messages.Message(id: message.id)) @@ -417,7 +454,8 @@ public final class ChatMessageInteractiveFileNode: ASDisplayNode { guard let result = result else { return .single(nil) } - return transcribeAudio(path: result, appLocale: appLocale) + + return transcribeAudio(path: result, appLocale: arguments.controllerInteraction.sgGetChatPredictedLang() ?? appLocale) } self.transcribeDisposable = (signal @@ -605,6 +643,8 @@ public final class ChatMessageInteractiveFileNode: ASDisplayNode { var audioWaveform: AudioWaveform? var isVoice = false var audioDuration: Int32 = 0 + var isConsumed: Bool? + var consumableContentIcon: UIImage? for attribute in arguments.message.attributes { if let attribute = attribute as? ConsumableContentMessageAttribute { @@ -615,6 +655,7 @@ public final class ChatMessageInteractiveFileNode: ASDisplayNode { consumableContentIcon = PresentationResourcesChat.chatBubbleConsumableContentOutgoingIcon(arguments.presentationData.theme.theme) } } + isConsumed = attribute.consumed break } } @@ -733,8 +774,25 @@ public final class ChatMessageInteractiveFileNode: ASDisplayNode { if Namespaces.Message.allNonRegular.contains(arguments.message.id.namespace) { displayTranscribe = false } else if arguments.message.id.peerId.namespace != Namespaces.Peer.SecretChat && !isViewOnceMessage && !arguments.presentationData.isPreview { - // GHOSTGRAM: Always show transcribe button for voice messages - displayTranscribe = true + let premiumConfiguration = PremiumConfiguration.with(appConfiguration: arguments.context.currentAppConfiguration.with { $0 }) + // MARK: Swiftgram + if arguments.associatedData.isPremium || true { + displayTranscribe = true + } else if premiumConfiguration.audioTransciptionTrialCount > 0 { + if arguments.incoming { + if audioDuration < premiumConfiguration.audioTransciptionTrialMaxDuration { + displayTranscribe = true + } + } + } else if arguments.associatedData.alwaysDisplayTranscribeButton.canBeDisplayed { + if audioDuration >= 60 { + displayTranscribe = true + } else if arguments.incoming && isConsumed == false && arguments.associatedData.alwaysDisplayTranscribeButton.displayForNotConsumed { + displayTranscribe = true + } + } else if arguments.associatedData.alwaysDisplayTranscribeButton.providedByGroupBoost { + displayTranscribe = true + } } let transcribedText = forcedAudioTranscriptionText ?? transcribedText(message: arguments.message) @@ -749,7 +807,7 @@ public final class ChatMessageInteractiveFileNode: ASDisplayNode { } let currentTime = Int32(Date().timeIntervalSince1970) - if transcribedText == nil, let cooldownUntilTime = arguments.associatedData.audioTranscriptionTrial.cooldownUntilTime, cooldownUntilTime > currentTime { + if transcribedText == nil, let cooldownUntilTime = arguments.associatedData.audioTranscriptionTrial.cooldownUntilTime, cooldownUntilTime > currentTime, { return false }() /* MARK: Swiftgram */ { updatedAudioTranscriptionState = .locked } @@ -899,6 +957,7 @@ public final class ChatMessageInteractiveFileNode: ASDisplayNode { context: arguments.context, presentationData: arguments.presentationData, edited: edited && !arguments.presentationData.isPreview, + isDeleted: arguments.topMessage.ghostgramIsDeleted, impressionCount: !arguments.presentationData.isPreview ? viewCount : nil, dateText: dateText, type: statusType, @@ -2173,4 +2232,3 @@ public final class FileMessageSelectionNode: ASDisplayNode { self.checkNode.frame = CGRect(origin: checkOrigin, size: checkSize) } } - diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveInstantVideoNode/Sources/ChatMessageInteractiveInstantVideoNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveInstantVideoNode/Sources/ChatMessageInteractiveInstantVideoNode.swift index b13d2699..f5e9ff76 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveInstantVideoNode/Sources/ChatMessageInteractiveInstantVideoNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveInstantVideoNode/Sources/ChatMessageInteractiveInstantVideoNode.swift @@ -577,6 +577,7 @@ public class ChatMessageInteractiveInstantVideoNode: ASDisplayNode { context: item.context, presentationData: item.presentationData, edited: edited && !sentViaBot && !item.presentationData.isPreview, + isDeleted: item.topMessage.ghostgramIsDeleted, impressionCount: !item.presentationData.isPreview ? viewCount : nil, dateText: dateText, type: statusType, diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/BUILD b/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/BUILD index 85b0e373..318a138d 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/BUILD +++ b/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/BUILD @@ -1,5 +1,9 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + swift_library( name = "ChatMessageInteractiveMediaNode", module_name = "ChatMessageInteractiveMediaNode", @@ -9,7 +13,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/AsyncDisplayKit", "//submodules/Postbox", "//submodules/SSignalKit/SwiftSignalKit", diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/Sources/ChatMessageInteractiveMediaNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/Sources/ChatMessageInteractiveMediaNode.swift index 730327cf..d27f728f 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/Sources/ChatMessageInteractiveMediaNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/Sources/ChatMessageInteractiveMediaNode.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import AsyncDisplayKit @@ -947,6 +948,8 @@ public final class ChatMessageInteractiveMediaNode: ASDisplayNode, GalleryItemTr var isSticker = false var maxDimensions = layoutConstants.image.maxDimensions var maxHeight = layoutConstants.image.maxDimensions.height + // MARK: Swiftgram + var imageOriginalMaxDimensions: CGSize? var isStory = false var isGift = false @@ -969,6 +972,19 @@ public final class ChatMessageInteractiveMediaNode: ASDisplayNode, GalleryItemTr } } else if let image = media as? TelegramMediaImage, let dimensions = largestImageRepresentation(image.representations)?.dimensions { unboundSize = CGSize(width: max(10.0, floor(dimensions.cgSize.width * 0.5)), height: max(10.0, floor(dimensions.cgSize.height * 0.5))) + // MARK: Swiftgram + if let channel = message.peers[message.id.peerId] as? TelegramChannel, case .broadcast = channel.info, SGSimpleSettings.shared.wideChannelPosts { + imageOriginalMaxDimensions = maxDimensions + switch sizeCalculation { + case let .constrained(constrainedSize): + maxDimensions.width = constrainedSize.width + case .unconstrained: + maxDimensions.width = unboundSize.width + } + if message.text.isEmpty { + maxDimensions.width = max(layoutConstants.image.maxDimensions.width, unboundSize.aspectFitted(CGSize(width: maxDimensions.width, height: layoutConstants.image.minDimensions.height)).width) + } + } } else if let file = media as? TelegramMediaFile, var dimensions = file.dimensions { if let thumbnail = file.previewRepresentations.first { let dimensionsVertical = dimensions.width < dimensions.height @@ -1112,6 +1128,7 @@ public final class ChatMessageInteractiveMediaNode: ASDisplayNode, GalleryItemTr context: context, presentationData: presentationData, edited: dateAndStatus.edited && !presentationData.isPreview, + isDeleted: message.ghostgramIsDeleted, impressionCount: !presentationData.isPreview ? dateAndStatus.viewCount : nil, dateText: dateAndStatus.dateText, type: dateAndStatus.type, @@ -1196,6 +1213,9 @@ public final class ChatMessageInteractiveMediaNode: ASDisplayNode, GalleryItemTr } boundingSize = CGSize(width: boundingWidth, height: filledSize.height).cropped(CGSize(width: CGFloat.greatestFiniteMagnitude, height: maxHeight)) + if let imageOriginalMaxDimensions = imageOriginalMaxDimensions { + boundingSize.height = min(boundingSize.height, nativeSize.aspectFitted(imageOriginalMaxDimensions).height) + } boundingSize.height = max(boundingSize.height, layoutConstants.image.minDimensions.height) boundingSize.width = max(boundingSize.width, layoutConstants.image.minDimensions.width) switch contentMode { @@ -2992,6 +3012,7 @@ public final class ChatMessageInteractiveMediaNode: ASDisplayNode, GalleryItemTr icon = .eye } } + if displaySpoiler, let context = self.context { let extendedMediaOverlayNode: ExtendedMediaOverlayNode @@ -3272,6 +3293,10 @@ public final class ChatMessageInteractiveMediaNode: ASDisplayNode, GalleryItemTr } public func scrubberTransition() -> GalleryItemScrubberTransition? { + if "".isEmpty { + return nil + } + final class TimestampContainerTransitionView: UIView { let containerView: UIView let containerMaskView: UIImageView diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageItemImpl/BUILD b/submodules/TelegramUI/Components/Chat/ChatMessageItemImpl/BUILD index a5e2f3cd..bcc91cb5 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageItemImpl/BUILD +++ b/submodules/TelegramUI/Components/Chat/ChatMessageItemImpl/BUILD @@ -1,5 +1,10 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//submodules/TranslateUI:TranslateUI" +] + swift_library( name = "ChatMessageItemImpl", module_name = "ChatMessageItemImpl", @@ -9,7 +14,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/Postbox", "//submodules/AsyncDisplayKit", "//submodules/Display", diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageItemImpl/Sources/ChatMessageItemImpl.swift b/submodules/TelegramUI/Components/Chat/ChatMessageItemImpl/Sources/ChatMessageItemImpl.swift index 63ccc3c4..26c1ad58 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageItemImpl/Sources/ChatMessageItemImpl.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageItemImpl/Sources/ChatMessageItemImpl.swift @@ -1,3 +1,5 @@ +import SGSimpleSettings +import TranslateUI import Foundation import UIKit import Postbox @@ -327,14 +329,14 @@ public final class ChatMessageItemImpl: ChatMessageItem, CustomStringConvertible } displayAuthorInfo = incoming && peerId.isGroupOrChannel && effectiveAuthor != nil - if let channel = content.firstMessage.peers[content.firstMessage.id.peerId] as? TelegramChannel, channel.isForumOrMonoForum { + if let chatPeer = content.firstMessage.peers[content.firstMessage.id.peerId], chatPeer.isForumOrMonoForum { if case .replyThread = chatLocation { - if channel.isMonoForum && chatLocation.threadId != context.account.peerId.toInt64() { + if chatPeer.isMonoForum && chatLocation.threadId != context.account.peerId.toInt64() { displayAuthorInfo = false } } else { - if channel.isMonoForum { - if let linkedMonoforumId = channel.linkedMonoforumId, let mainChannel = content.firstMessage.peers[linkedMonoforumId] as? TelegramChannel, mainChannel.hasPermission(.manageDirect) { + if chatPeer.isMonoForum { + if let chatPeer = chatPeer as? TelegramChannel, let linkedMonoforumId = chatPeer.linkedMonoforumId, let mainChannel = content.firstMessage.peers[linkedMonoforumId] as? TelegramChannel, mainChannel.hasPermission(.manageDirect) { headerSeparableThreadId = content.firstMessage.threadId if let threadId = content.firstMessage.threadId, let peer = content.firstMessage.peers[EnginePeer.Id(threadId)] { @@ -533,6 +535,17 @@ public final class ChatMessageItemImpl: ChatMessageItem, CustomStringConvertible let configure = { let node = (viewClassName as! ChatMessageItemView.Type).init(rotated: self.controllerInteraction.chatIsRotated) + if let node = node as? ChatMessageStickerItemNode { + node.sizeCoefficient = Float(SGSimpleSettings.shared.stickerSize) / 100.0 + if !SGSimpleSettings.shared.stickerTimestamp { + node.dateAndStatusNode.isHidden = true + } + } else if let node = node as? ChatMessageAnimatedStickerItemNode { + node.sizeCoefficient = Float(SGSimpleSettings.shared.stickerSize) / 100.0 + if !SGSimpleSettings.shared.stickerTimestamp { + node.dateAndStatusNode.isHidden = true + } + } node.setupItem(self, synchronousLoad: synchronousLoads) let nodeLayout = node.asyncLayout() diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageItemView/Sources/ChatMessageItemView.swift b/submodules/TelegramUI/Components/Chat/ChatMessageItemView/Sources/ChatMessageItemView.swift index 7d0d161a..6fe9cdba 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageItemView/Sources/ChatMessageItemView.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageItemView/Sources/ChatMessageItemView.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import AsyncDisplayKit @@ -663,6 +664,9 @@ open class ChatMessageItemView: ListViewItemNode, ChatMessageItemNodeProtocol { public var playedEffectAnimation: Bool = false public var effectAnimationNodes: [ChatMessageTransitionNode.DecorationItemNode] = [] + private var wasFilteredKeywordTested: Bool = false + private var matchedFilterKeyword: String? = nil + public required init(rotated: Bool) { super.init(layerBacked: false, rotated: rotated) if rotated { @@ -683,10 +687,23 @@ open class ChatMessageItemView: ListViewItemNode, ChatMessageItemNodeProtocol { self.item = nil self.frame = CGRect() + self.wasFilteredKeywordTested = false + self.matchedFilterKeyword = nil } open func setupItem(_ item: ChatMessageItem, synchronousLoad: Bool) { self.item = item + + if !self.wasFilteredKeywordTested && !SGSimpleSettings.shared.messageFilterKeywords.isEmpty && SGSimpleSettings.shared.ephemeralStatus > 1 { + let incomingMessage = item.message.effectivelyIncoming(item.context.account.peerId) + if incomingMessage { + if let matchedKeyword = SGSimpleSettings.shared.messageFilterKeywords.first(where: { item.message.text.contains($0) }) { + self.matchedFilterKeyword = matchedKeyword + self.alpha = item.presentationData.theme.theme.overallDarkAppearance ? 0.2 : 0.3 + } + } + } + self.wasFilteredKeywordTested = true } open func updateAccessibilityData(_ accessibilityData: ChatMessageAccessibilityData) { diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageMapBubbleContentNode/Sources/ChatMessageMapBubbleContentNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageMapBubbleContentNode/Sources/ChatMessageMapBubbleContentNode.swift index ad82af9b..140e3a28 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageMapBubbleContentNode/Sources/ChatMessageMapBubbleContentNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageMapBubbleContentNode/Sources/ChatMessageMapBubbleContentNode.swift @@ -274,6 +274,7 @@ public class ChatMessageMapBubbleContentNode: ChatMessageBubbleContentNode { context: item.context, presentationData: item.presentationData, edited: edited, + isDeleted: item.topMessage.ghostgramIsDeleted, impressionCount: !item.presentationData.isPreview ? viewCount : nil, dateText: dateText, type: statusType, diff --git a/submodules/TelegramUI/Components/Chat/ChatMessagePollBubbleContentNode/Sources/ChatMessagePollBubbleContentNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessagePollBubbleContentNode/Sources/ChatMessagePollBubbleContentNode.swift index 11ea5ed6..cccc7d80 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessagePollBubbleContentNode/Sources/ChatMessagePollBubbleContentNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessagePollBubbleContentNode/Sources/ChatMessagePollBubbleContentNode.swift @@ -1117,6 +1117,7 @@ public class ChatMessagePollBubbleContentNode: ChatMessageBubbleContentNode { context: item.context, presentationData: item.presentationData, edited: edited, + isDeleted: item.topMessage.ghostgramIsDeleted, impressionCount: viewCount, dateText: dateText, type: statusType, diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageRestrictedBubbleContentNode/Sources/ChatMessageRestrictedBubbleContentNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageRestrictedBubbleContentNode/Sources/ChatMessageRestrictedBubbleContentNode.swift index 5203e555..cc8a6819 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageRestrictedBubbleContentNode/Sources/ChatMessageRestrictedBubbleContentNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageRestrictedBubbleContentNode/Sources/ChatMessageRestrictedBubbleContentNode.swift @@ -130,6 +130,7 @@ public class ChatMessageRestrictedBubbleContentNode: ChatMessageBubbleContentNod context: item.context, presentationData: item.presentationData, edited: edited, + isDeleted: message.ghostgramIsDeleted, impressionCount: viewCount, dateText: dateText, type: statusType, diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageSelectionInputPanelNode/Sources/ChatMessageSelectionInputPanelNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageSelectionInputPanelNode/Sources/ChatMessageSelectionInputPanelNode.swift index bf7b210c..18b70645 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageSelectionInputPanelNode/Sources/ChatMessageSelectionInputPanelNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageSelectionInputPanelNode/Sources/ChatMessageSelectionInputPanelNode.swift @@ -321,7 +321,7 @@ public final class ChatMessageSelectionInputPanelNode: ChatInputPanelNode { if let actions = self.actions, actions.isCopyProtected { self.interfaceInteraction?.displayCopyProtectionTip(self.forwardButton, false) } else if !self.forwardButton.isImplicitlyDisabled { - self.interfaceInteraction?.forwardSelectedMessages() + self.interfaceInteraction?.forwardSelectedMessages(nil) } } diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageStickerItemNode/Sources/ChatMessageStickerItemNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageStickerItemNode/Sources/ChatMessageStickerItemNode.swift index 5e3a781e..dbdec849 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageStickerItemNode/Sources/ChatMessageStickerItemNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageStickerItemNode/Sources/ChatMessageStickerItemNode.swift @@ -38,6 +38,7 @@ public class ChatMessageStickerItemNode: ChatMessageItemView { public let contextSourceNode: ContextExtractedContentContainingNode private let containerNode: ContextControllerSourceNode public let imageNode: TransformImageNode + public var sizeCoefficient: Float = 1.0 private var backgroundNode: WallpaperBubbleBackgroundNode? private var placeholderNode: StickerShimmerEffectNode public var textNode: TextNode? @@ -55,7 +56,7 @@ public class ChatMessageStickerItemNode: ChatMessageItemView { private var suggestedPostInfoNode: ChatMessageSuggestedPostInfoNode? private var viaBotNode: TextNode? - private let dateAndStatusNode: ChatMessageDateAndStatusNode + public let dateAndStatusNode: ChatMessageDateAndStatusNode private var threadInfoNode: ChatMessageThreadInfoNode? private var replyInfoNode: ChatMessageReplyInfoNode? private var replyBackgroundContent: WallpaperBubbleBackgroundNode? @@ -654,6 +655,7 @@ public class ChatMessageStickerItemNode: ChatMessageItemView { context: item.context, presentationData: item.presentationData, edited: edited, + isDeleted: item.message.ghostgramIsDeleted, impressionCount: viewCount, dateText: dateText, type: statusType, @@ -897,11 +899,11 @@ public class ChatMessageStickerItemNode: ChatMessageItemView { ReplyMarkupMessageAttribute( rows: [ ReplyMarkupRow(buttons: [ - ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionReject, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonDecline)), - ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionApprove, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonApprove)) + ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionReject, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonDecline), style: nil), + ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionApprove, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonApprove), style: nil) ]), ReplyMarkupRow(buttons: [ - ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionSuggestChanges, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonSuggestChanges)) + ReplyMarkupButton(title: item.presentationData.strings.Chat_PostApproval_Message_ActionSuggestChanges, titleWhenForwarded: nil, action: .callback(requiresPassword: false, data: buttonSuggestChanges), style: nil) ]) ], flags: [], diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageTextBubbleContentNode/Sources/ChatMessageTextBubbleContentNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageTextBubbleContentNode/Sources/ChatMessageTextBubbleContentNode.swift index ce3349ac..82b57c41 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageTextBubbleContentNode/Sources/ChatMessageTextBubbleContentNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageTextBubbleContentNode/Sources/ChatMessageTextBubbleContentNode.swift @@ -725,6 +725,7 @@ public class ChatMessageTextBubbleContentNode: ChatMessageBubbleContentNode { context: item.context, presentationData: item.presentationData, edited: edited && !item.presentationData.isPreview, + isDeleted: item.topMessage.ghostgramIsDeleted, impressionCount: !item.presentationData.isPreview ? viewCount : nil, dateText: dateText, type: statusType, @@ -742,7 +743,6 @@ public class ChatMessageTextBubbleContentNode: ChatMessageBubbleContentNode { starsCount: starsCount, isPinned: item.message.tags.contains(.pinned) && (!item.associatedData.isInPinnedListMode || isReplyThread), hasAutoremove: item.message.isSelfExpiring, - isDeleted: AntiDeleteManager.shared.isMessageDeleted(peerId: item.message.id.peerId.toInt64(), messageId: item.message.id.id) || AntiDeleteManager.shared.isMessageDeleted(text: item.message.text), canViewReactionList: canViewMessageReactionList(message: item.topMessage), animationCache: item.controllerInteraction.presentationContext.animationCache, animationRenderer: item.controllerInteraction.presentationContext.animationRenderer @@ -1256,7 +1256,7 @@ public class ChatMessageTextBubbleContentNode: ChatMessageBubbleContentNode { return super.hitTest(point, with: event) } - private func updateIsTranslating(_ isTranslating: Bool) { + public func updateIsTranslating(_ isTranslating: Bool) { guard let item = self.item else { return } diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageTodoBubbleContentNode/Sources/ChatMessageTodoBubbleContentNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageTodoBubbleContentNode/Sources/ChatMessageTodoBubbleContentNode.swift index bb614b86..1fbe50e3 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageTodoBubbleContentNode/Sources/ChatMessageTodoBubbleContentNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageTodoBubbleContentNode/Sources/ChatMessageTodoBubbleContentNode.swift @@ -1173,6 +1173,7 @@ public class ChatMessageTodoBubbleContentNode: ChatMessageBubbleContentNode { context: item.context, presentationData: item.presentationData, edited: edited, + isDeleted: item.topMessage.ghostgramIsDeleted, impressionCount: viewCount, dateText: dateText, type: statusType, diff --git a/submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsController.swift b/submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsController.swift index 6c94d414..134677f1 100644 --- a/submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsController.swift +++ b/submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsController.swift @@ -65,9 +65,9 @@ public final class ChatRecentActionsController: TelegramBaseController { }, blockMessageAuthor: { _, _ in }, deleteMessages: { _, _, f in f(.default) - }, forwardSelectedMessages: { + }, forwardSelectedMessages: { _ in }, forwardCurrentForwardMessages: { - }, forwardMessages: { _ in + }, forwardMessages: { _, _ in }, updateForwardOptionsState: { _ in }, presentForwardOptions: { _ in }, presentReplyOptions: { _ in diff --git a/submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsControllerNode.swift b/submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsControllerNode.swift index 3a659778..54a07f67 100644 --- a/submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsControllerNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsControllerNode.swift @@ -1465,6 +1465,18 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { break case .sendGift: break + case .unknownDeepLink: + break + case .oauth: + break + case .chats: + break + case .compose: + break + case .postStory: + break + case .contacts: + break } } })) diff --git a/submodules/TelegramUI/Components/Chat/ChatTextInputActionButtonsNode/Sources/ChatTextInputActionButtonsNode.swift b/submodules/TelegramUI/Components/Chat/ChatTextInputActionButtonsNode/Sources/ChatTextInputActionButtonsNode.swift index b758e33d..efc5b590 100644 --- a/submodules/TelegramUI/Components/Chat/ChatTextInputActionButtonsNode/Sources/ChatTextInputActionButtonsNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatTextInputActionButtonsNode/Sources/ChatTextInputActionButtonsNode.swift @@ -19,6 +19,14 @@ import GlassBackgroundComponent import ComponentDisplayAdapters import StarsParticleEffect +private func neutralActionButtonGlassTint(theme: PresentationTheme) -> GlassBackgroundView.TintColor { + if theme.overallDarkAppearance { + return .init(kind: .custom, color: UIColor(white: 0.0, alpha: 0.38)) + } else { + return .init(kind: .custom, color: UIColor(white: 1.0, alpha: 0.68)) + } +} + private final class EffectBadgeView: UIView { private let context: AccountContext private var currentEffectId: Int64? @@ -345,7 +353,7 @@ public final class ChatTextInputActionButtonsNode: ASDisplayNode, ChatSendMessag } transition.updateFrame(view: self.micButtonBackgroundView, frame: CGRect(origin: CGPoint(), size: size)) - self.micButtonBackgroundView.update(size: size, cornerRadius: size.height * 0.5, isDark: interfaceState.theme.overallDarkAppearance, tintColor: .init(kind: .panel, color: interfaceState.theme.chat.inputPanel.inputBackgroundColor.withMultipliedAlpha(0.7)), isInteractive: true, transition: ComponentTransition(transition)) + self.micButtonBackgroundView.update(size: size, cornerRadius: size.height * 0.5, isDark: interfaceState.theme.overallDarkAppearance, tintColor: neutralActionButtonGlassTint(theme: interfaceState.theme), isInteractive: true, transition: ComponentTransition(transition)) transition.updateFrame(layer: self.micButton.layer, frame: CGRect(origin: CGPoint(), size: size)) self.micButton.layoutItems() @@ -401,7 +409,7 @@ public final class ChatTextInputActionButtonsNode: ASDisplayNode, ChatSendMessag transition.updateFrame(view: self.expandMediaInputButton, frame: CGRect(origin: CGPoint(), size: size)) transition.updateFrame(view: self.expandMediaInputButtonBackgroundView, frame: CGRect(origin: CGPoint(), size: size)) - self.expandMediaInputButtonBackgroundView.update(size: size, cornerRadius: size.height * 0.5, isDark: interfaceState.theme.overallDarkAppearance, tintColor: .init(kind: .panel, color: interfaceState.theme.chat.inputPanel.inputBackgroundColor.withMultipliedAlpha(0.7)), isInteractive: true, transition: ComponentTransition(transition)) + self.expandMediaInputButtonBackgroundView.update(size: size, cornerRadius: size.height * 0.5, isDark: interfaceState.theme.overallDarkAppearance, tintColor: neutralActionButtonGlassTint(theme: interfaceState.theme), isInteractive: true, transition: ComponentTransition(transition)) if let image = self.expandMediaInputButtonIcon.image { let expandIconFrame = CGRect(origin: CGPoint(x: floor((size.width - image.size.width) * 0.5), y: floor((size.height - image.size.height) * 0.5)), size: image.size) self.expandMediaInputButtonIcon.center = expandIconFrame.center diff --git a/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelComponent.swift b/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelComponent.swift index 1a0b15a8..b4038e03 100644 --- a/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelComponent.swift +++ b/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelComponent.swift @@ -418,11 +418,11 @@ public final class ChatTextInputPanelComponent: Component { deleteMessages: { _, _, f in f(.default) }, - forwardSelectedMessages: { + forwardSelectedMessages: { _ in }, forwardCurrentForwardMessages: { }, - forwardMessages: { _ in + forwardMessages: { _, _ in }, updateForwardOptionsState: { _ in }, @@ -472,6 +472,7 @@ public final class ChatTextInputPanelComponent: Component { var presentationInterfaceState = ChatPresentationInterfaceState( chatWallpaper: .color(0), theme: component.theme, + preferredGlassType: .default, strings: component.strings, dateTimeFormat: PresentationDateTimeFormat(), nameDisplayOrder: .firstLast, @@ -773,6 +774,7 @@ public final class ChatTextInputPanelComponent: Component { var presentationInterfaceState = ChatPresentationInterfaceState( chatWallpaper: .color(0), theme: component.theme, + preferredGlassType: .default, strings: component.strings, dateTimeFormat: PresentationDateTimeFormat(), nameDisplayOrder: .firstLast, diff --git a/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelNode.swift b/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelNode.swift index 1f78c9fd..21072d8e 100644 --- a/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelNode.swift @@ -1,3 +1,9 @@ +// MARK: Swiftgram +import TelegramUIPreferences +import SGSimpleSettings +import SwiftUI +import SGInputToolbar + import Foundation import UniformTypeIdentifiers import UIKit @@ -65,6 +71,14 @@ public let chatTextInputMinFontSize: CGFloat = 5.0 private let minInputFontSize = chatTextInputMinFontSize +private func neutralChatInputGlassTint(theme: PresentationTheme, innerColor: UIColor? = nil) -> GlassBackgroundView.TintColor { + if theme.overallDarkAppearance { + return .init(kind: .custom, color: UIColor(white: 0.0, alpha: 0.38), innerColor: innerColor) + } else { + return .init(kind: .custom, color: UIColor(white: 1.0, alpha: 0.68), innerColor: innerColor) + } +} + private func calclulateTextFieldMinHeight(_ presentationInterfaceState: ChatPresentationInterfaceState, metrics: LayoutMetrics) -> CGFloat { var baseFontSize = max(minInputFontSize, presentationInterfaceState.fontSize.baseDisplaySize) if "".isEmpty { @@ -333,6 +347,12 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg private let hapticFeedback = HapticFeedback() + // MARK: Swiftgram + private var sendWithReturnKey: Bool + private var sendWithReturnKeyDisposable: Disposable? +// private var toolbarHostingController: UIViewController? //Any? // UIHostingController? + private var toolbarNode: ASDisplayNode? + public var inputTextState: ChatTextInputState { if let textInputNode = self.textInputNode { let selectionRange: Range = textInputNode.selectedRange.location ..< (textInputNode.selectedRange.location + textInputNode.selectedRange.length) @@ -619,6 +639,11 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg self.textInputViewInternalInsets = UIEdgeInsets(top: 5.0, left: 12.0, bottom: 4.0, right: 11.0) + + // MARK: Swiftgram + self.sendWithReturnKey = SGSimpleSettings.shared.sendWithReturnKey // MARK: Swiftgram + // + var hasSpoilers = true var hasQuotes = true if presentationInterfaceState.chatLocation.peerId?.namespace == Namespaces.Peer.SecretChat { @@ -755,7 +780,11 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg if let data = context.currentAppConfiguration.with({ $0 }).data, data["ios_killswitch_input_bounce"] != nil { self.enableBounceAnimations = false }*/ - + + // MARK: Swiftgram + self.initToolbarIfNeeded(context: context) + // + self.sendAsAvatarContainerNode.activated = { [weak self] gesture, _ in guard let strongSelf = self else { return @@ -818,6 +847,10 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg } } self.attachmentButtonDisabledNode.addTarget(self, action: #selector(self.attachmentButtonPressed), forControlEvents: .touchUpInside) + // MARK: Swiftgram + let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.attachmentButtonLongPressed(_:))) + longPressGesture.minimumPressDuration = 1.0 + self.attachmentButton.addGestureRecognizer(longPressGesture) self.sendActionButtons.sendButtonLongPressed = { [weak self] node, gesture in self?.interfaceInteraction?.displaySendMessageOptions(node, gesture) @@ -1013,6 +1046,7 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg deinit { self.statusDisposable.dispose() + self.sendWithReturnKeyDisposable?.dispose() self.tooltipController?.dismiss() self.currentEmojiSuggestion?.disposable.dispose() } @@ -1060,6 +1094,7 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg self.textInputNodeClippingContainer.addSubnode(textInputNode) textInputNode.view.disablesInteractiveTransitionGestureRecognizer = true textInputNode.isUserInteractionEnabled = !self.sendingTextDisabled + textInputNode.textView.returnKeyType = self.sendWithReturnKey ? .send : .default self.textInputNode = textInputNode if let textInputBackgroundTapRecognizer = self.textInputBackgroundTapRecognizer { @@ -1421,6 +1456,16 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg let previousAdditionalSideInsets = self.validLayout?.4 self.validLayout = (width, leftInset, rightInset, bottomInset, additionalSideInsets, maxHeight, maxOverlayHeight, metrics, isSecondary, isMediaInputExpanded) + let defaultGlassTintColor: GlassBackgroundView.TintColor + let defaultGlassTintWithInnerColor: GlassBackgroundView.TintColor + if case .clear = interfaceState.preferredGlassType { + defaultGlassTintColor = .init(kind: .custom, color: UIColor.clear) + defaultGlassTintWithInnerColor = .init(kind: .custom, color: UIColor.clear, innerColor: interfaceState.theme.list.itemCheckColors.fillColor) + } else { + defaultGlassTintColor = neutralChatInputGlassTint(theme: interfaceState.theme) + defaultGlassTintWithInnerColor = neutralChatInputGlassTint(theme: interfaceState.theme, innerColor: interfaceState.theme.list.itemCheckColors.fillColor) + } + var leftInset = leftInset var rightInset = rightInset @@ -2205,6 +2250,9 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg if buttonTitleUpdated && !transition.isAnimated { transition = .animated(duration: 0.3, curve: .easeInOut) } + // MARK: Swiftgram + let originalLeftInset = leftInset + // let textInputBackgroundWidthOffset: CGFloat = 0.0 var attachmentButtonX: CGFloat = hideOffset.x + leftInset + leftMenuInset + 8.0 @@ -2365,7 +2413,7 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg let menuButtonFrame = CGRect(x: leftInset + 8.0, y: menuButtonOriginY, width: menuButtonExpanded ? menuButtonWidth : menuCollapsedButtonWidth, height: menuButtonHeight) transition.updateFrameAsPositionAndBounds(node: self.menuButton, frame: menuButtonFrame) transition.updateFrame(view: self.menuButtonBackgroundView, frame: CGRect(origin: CGPoint(), size: menuButtonFrame.size)) - self.menuButtonBackgroundView.update(size: menuButtonFrame.size, cornerRadius: menuButtonFrame.height * 0.5, isDark: interfaceState.theme.overallDarkAppearance, tintColor: .init(kind: .panel, color: interfaceState.theme.chat.inputPanel.inputBackgroundColor.withMultipliedAlpha(0.7), innerColor: interfaceState.theme.chat.inputPanel.actionControlFillColor), transition: ComponentTransition(transition)) + self.menuButtonBackgroundView.update(size: menuButtonFrame.size, cornerRadius: menuButtonFrame.height * 0.5, isDark: interfaceState.theme.overallDarkAppearance, tintColor: defaultGlassTintWithInnerColor, transition: ComponentTransition(transition)) transition.updateFrame(node: self.menuButtonClippingNode, frame: CGRect(origin: CGPoint(x: 19.0, y: 0.0), size: CGSize(width: menuButtonWidth - 19.0, height: menuButtonFrame.height))) var menuButtonTitleTransition = transition if buttonTitleUpdated { @@ -2385,7 +2433,7 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg if additionalSideInsets.right > 0.0 { textFieldInsets.right += additionalSideInsets.right / 3.0 } - if inputHasText || self.extendedSearchLayout || hasMediaDraft || hasForward { + if SGSimpleSettings.shared.hideRecordingButton || inputHasText || self.extendedSearchLayout || hasMediaDraft || hasForward { } else { if let customRightAction = self.customRightAction, case .empty = customRightAction { textFieldInsets.right = 8.0 @@ -2513,7 +2561,9 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg case let .audio(recorder, isLocked): let hadAudioRecorder = self.mediaActionButtons.micButton.audioRecorder != nil if !hadAudioRecorder, isLocked { - self.mediaActionButtons.micButton.lock() + DispatchQueue.main.async { [weak self] in + self?.mediaActionButtons.micButton.lock() + } } self.mediaActionButtons.micButton.audioRecorder = recorder audioRecordingTimeNode.audioRecorder = recorder @@ -2887,7 +2937,7 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg self.updateCounterTextNode(backgroundSize: textInputContainerBackgroundFrame.size, transition: transition) let textInputContainerBackgroundTransition = ComponentTransition(transition) - self.textInputContainerBackgroundView.update(size: textInputContainerBackgroundFrame.size, cornerRadius: floor(minimalInputHeight * 0.5), isDark: interfaceState.theme.overallDarkAppearance, tintColor: .init(kind: .panel, color: interfaceState.theme.chat.inputPanel.inputBackgroundColor.withMultipliedAlpha(0.7)), isInteractive: true, transition: textInputContainerBackgroundTransition) + self.textInputContainerBackgroundView.update(size: textInputContainerBackgroundFrame.size, cornerRadius: floor(minimalInputHeight * 0.5), isDark: interfaceState.theme.overallDarkAppearance, tintColor: defaultGlassTintColor, isInteractive: true, transition: textInputContainerBackgroundTransition) transition.updateFrame(layer: self.textInputBackgroundNode.layer, frame: textInputContainerBackgroundFrame) transition.updateAlpha(node: self.textInputBackgroundNode, alpha: audioRecordingItemsAlpha) @@ -3277,7 +3327,7 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg let attachmentButtonFrame = CGRect(origin: CGPoint(x: attachmentButtonX, y: textInputFrame.maxY - 40.0), size: CGSize(width: 40.0, height: 40.0)) attachmentButtonX += 40.0 + 6.0 - self.attachmentButtonBackground.update(size: attachmentButtonFrame.size, cornerRadius: attachmentButtonFrame.height * 0.5, isDark: interfaceState.theme.overallDarkAppearance, tintColor: .init(kind: .panel, color: interfaceState.theme.chat.inputPanel.inputBackgroundColor.withMultipliedAlpha(0.7)), isInteractive: true, transition: ComponentTransition(transition)) + self.attachmentButtonBackground.update(size: attachmentButtonFrame.size, cornerRadius: attachmentButtonFrame.height * 0.5, isDark: interfaceState.theme.overallDarkAppearance, tintColor: defaultGlassTintColor, isInteractive: true, transition: ComponentTransition(transition)) transition.updateFrame(layer: self.attachmentButtonBackground.layer, frame: attachmentButtonFrame) transition.updateFrame(layer: self.attachmentButton.layer, frame: CGRect(origin: CGPoint(), size: attachmentButtonFrame.size)) @@ -3505,7 +3555,11 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg transition.updateFrame(view: self.glassBackgroundContainer, frame: containerFrame) self.glassBackgroundContainer.update(size: containerFrame.size, isDark: interfaceState.theme.overallDarkAppearance, transition: ComponentTransition(transition)) - return contentHeight + // MARK: Swiftgram + var toolbarOffset: CGFloat = 0.0 + toolbarOffset = layoutToolbar(transition: transition, panelHeight: contentHeight, width: width, leftInset: originalLeftInset, rightInset: rightInset, displayBotStartButton: displayBotStartButton) + + return contentHeight + toolbarOffset } @objc private func slowModeButtonPressed() { @@ -4046,7 +4100,7 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg } let presentationData = context.sharedContext.currentPresentationData.with { $0 } - let controller = PeekController(presentationData: presentationData, content: content, sourceView: { + let controller = makePeekController(presentationData: presentationData, content: content, sourceView: { return (sourceView, sourceRect) }) //strongSelf.peekController = controller @@ -4318,8 +4372,8 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg let blurTransitionOut: ComponentTransition = transition.isAnimated ? .easeInOut(duration: 0.18) : .immediate let sendButtonBlurOut: CGFloat = 4.0 - var hideMicButton = false - var hideMicButtonBackground = false + var hideMicButton = SGSimpleSettings.shared.hideRecordingButton + var hideMicButtonBackground = SGSimpleSettings.shared.hideRecordingButton if self.customRightAction != nil { self.mediaActionButtons.isHidden = true @@ -4397,7 +4451,7 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg } } - if (hasText || keepSendButtonEnabled && !mediaInputIsActive && !hasSlowModeButton) { + if (SGSimpleSettings.shared.hideRecordingButton || hasText || keepSendButtonEnabled && !mediaInputIsActive && !hasSlowModeButton) { if self.sendActionButtons.sendContainerNode.alpha.isZero && self.rightSlowModeInset.isZero { alphaTransition.updateAlpha(node: self.sendActionButtons.sendContainerNode, alpha: 1.0) blurTransitionIn.animateBlur(layer: self.sendActionButtons.sendContainerNode.layer, fromRadius: sendButtonBlurOut, toRadius: 0.0) @@ -4522,14 +4576,32 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg } public func chatInputTextNodeShouldReturn() -> Bool { + return self.chatInputTextNodeShouldReturn(modifierFlags: []) + } + + public func chatInputTextNodeShouldReturn(modifierFlags: UIKeyModifierFlags) -> Bool { + var shouldSendMessage = false if self.sendActionButtons.sendButton.supernode != nil && !self.sendActionButtons.sendButton.isHidden && !self.sendActionButtons.sendContainerNode.alpha.isZero { - self.sendButtonPressed() + if let context = self.context, context.sharedContext.currentChatSettings.with({ $0 }).sendWithCmdEnter { + if modifierFlags.contains(.command) { + shouldSendMessage = true + } + } else { + if modifierFlags.isEmpty { + shouldSendMessage = true + } + } } - return false + if shouldSendMessage { + self.sendButtonPressed() + return false + } + + return true } @objc public func editableTextNodeShouldReturn(_ editableTextNode: ASEditableTextNode) -> Bool { - return self.chatInputTextNodeShouldReturn() + return self.chatInputTextNodeShouldReturn(modifierFlags: []) } private func applyUpdateSendButtonIcon() { @@ -4943,6 +5015,13 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg } self.updateActivity() + + // MARK: Swiftgram + if self.sendWithReturnKey && text == "\n" { + self.sendButtonPressed() + return false + } + var cleanText = text let removeSequences: [String] = ["\u{202d}", "\u{202c}"] for sequence in removeSequences { @@ -5169,6 +5248,11 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg } } + // MARK: Swiftgram + @objc func attachmentButtonLongPressed(_ gesture: UILongPressGestureRecognizer) { + guard gesture.state == .began else { return } + } + @objc func searchLayoutClearButtonPressed() { if let interfaceInteraction = self.interfaceInteraction { interfaceInteraction.updateTextInputStateAndMode { textInputState, inputMode in @@ -5477,3 +5561,114 @@ public class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDeleg return AttachmentInputPanelTransition(inputNode: self, accessoryPanelNode: accessoryPanelNode, menuButtonNode: self.menuButton, menuButtonBackgroundView: self.menuButtonBackgroundView, menuIconNode: self.menuButtonIconNode, menuTextNode: self.menuButtonTextNode, prepareForDismiss: { self.menuButtonIconNode.enqueueState(.app, animated: false) }) } } + + +// MARK: Swiftgram +extension ChatTextInputPanelNode { + + func initToolbarIfNeeded(context: AccountContext) { + guard #available(iOS 13.0, *) else { return } + guard SGSimpleSettings.shared.inputToolbar else { return } + guard context.sharedContext.immediateSGStatus.status > 1 else { return } + guard self.toolbarNode == nil else { return } + let toolbarView = ChatToolbarView( + onQuote: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesQuote(strongSelf) + }, + onSpoiler: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesSpoiler(strongSelf) + }, + onBold: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesBold(strongSelf) + }, + onItalic: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesItalic(strongSelf) + }, + onMonospace: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesMonospace(strongSelf) + }, + onLink: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesLink(strongSelf) + }, + onStrikethrough: { [weak self] + in guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesStrikethrough(strongSelf) + }, + onUnderline: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesUnderline(strongSelf) + }, + onCode: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSelectLastWordIfIdle() + strongSelf.formatAttributesCodeBlock(strongSelf) + }, + onNewLine: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.sgSetNewLine() + }, + // TODO(swiftgram): Binding + showNewLine: .constant(true), //.constant(self.sendWithReturnKey) + onClearFormatting: { [weak self] in + guard let strongSelf = self else { return } + strongSelf.interfaceInteraction?.updateTextInputStateAndMode { current, inputMode in + return (chatTextInputClearFormattingAttributes(current), inputMode) + } + } + ) + let toolbarHostingController = UIHostingController(rootView: toolbarView) + toolbarHostingController.view.backgroundColor = UIColor.clear + let toolbarNode = ASDisplayNode { toolbarHostingController.view } + self.toolbarNode = toolbarNode + // assigning toolbarHostingController bugs responsivness and overrides layout + // self.toolbarHostingController = toolbarHostingController + + // Disable "Swipe to go back" gesture when touching scrollview + self.view.interactiveTransitionGestureRecognizerTest = { [weak self] point in + if let self, let _ = self.toolbarNode?.view.hitTest(point, with: nil) { + return false + } + return true + } + self.addSubnode(toolbarNode) + } + + func layoutToolbar(transition: ContainedViewLayoutTransition, panelHeight: CGFloat, width: CGFloat, leftInset: CGFloat, rightInset: CGFloat, displayBotStartButton: Bool) -> CGFloat { + var toolbarHeight: CGFloat = 0.0 + var toolbarSpacing: CGFloat = 0.0 + if let toolbarNode = self.toolbarNode { + if displayBotStartButton { + toolbarNode.view.alpha = 0.0 +// transition.updateAlpha(node: toolbarNode, alpha: 0.0) + /*} else if !self.isFocused { + transition.updateAlpha(node: toolbarNode, alpha: 0.0, completion: { _ in + toolbarNode.isHidden = true + })*/ + } else { + if !self.isFocused { + transition.updateAlpha(node: toolbarNode, alpha: 0.0) + } else { + toolbarHeight = 44.0 + toolbarSpacing = 6.0 + transition.updateFrame(node: toolbarNode, frame: CGRect(origin: CGPoint(x: leftInset, y: panelHeight + toolbarSpacing), size: CGSize(width: width - rightInset - leftInset, height: toolbarHeight))) + transition.updateAlpha(node: toolbarNode, alpha: 1.0) + } + } + } + return toolbarHeight + toolbarSpacing + } +} diff --git a/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/InputIconButtonComponent.swift b/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/InputIconButtonComponent.swift index ca342c12..05659006 100644 --- a/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/InputIconButtonComponent.swift +++ b/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/InputIconButtonComponent.swift @@ -6,6 +6,14 @@ import ComponentFlow import GlassBackgroundComponent import AppBundle +private func neutralInputButtonGlassTint(theme: PresentationTheme) -> GlassBackgroundView.TintColor { + if theme.overallDarkAppearance { + return .init(kind: .custom, color: UIColor(white: 0.0, alpha: 0.38)) + } else { + return .init(kind: .custom, color: UIColor(white: 1.0, alpha: 0.68)) + } +} + final class InputIconButtonComponent: Component { let theme: PresentationTheme let name: String @@ -87,7 +95,7 @@ final class InputIconButtonComponent: Component { } transition.setFrame(view: self.backgroundView, frame: CGRect(origin: CGPoint(), size: size)) - self.backgroundView.update(size: size, cornerRadius: size.height * 0.5, isDark: component.theme.overallDarkAppearance, tintColor: .init(kind: .panel, color: component.theme.chat.inputPanel.inputBackgroundColor.withMultipliedAlpha(0.7)), isInteractive: true, transition: transition) + self.backgroundView.update(size: size, cornerRadius: size.height * 0.5, isDark: component.theme.overallDarkAppearance, tintColor: neutralInputButtonGlassTint(theme: component.theme), isInteractive: true, transition: transition) self.button.frame = CGRect(origin: CGPoint(), size: size) diff --git a/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/StarReactionButtonComponent.swift b/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/StarReactionButtonComponent.swift index c4f34a96..8b64dde6 100644 --- a/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/StarReactionButtonComponent.swift +++ b/submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/StarReactionButtonComponent.swift @@ -7,6 +7,14 @@ import GlassBackgroundComponent import AnimatedTextComponent import StarsParticleEffect +private func neutralStarReactionGlassTint(theme: PresentationTheme) -> GlassBackgroundView.TintColor { + if theme.overallDarkAppearance { + return .init(kind: .custom, color: UIColor(white: 0.0, alpha: 0.38)) + } else { + return .init(kind: .custom, color: UIColor(white: 1.0, alpha: 0.68)) + } +} + final class StarReactionButtonBadgeComponent: Component { let theme: PresentationTheme let count: Int @@ -80,7 +88,7 @@ final class StarReactionButtonBadgeComponent: Component { if component.isFilled { backgroundTintColor = .init(kind: .custom, color: UIColor(rgb: 0xFFB10D)) } else { - backgroundTintColor = .init(kind: .panel, color: component.theme.chat.inputPanel.inputBackgroundColor.withMultipliedAlpha(0.7)) + backgroundTintColor = neutralStarReactionGlassTint(theme: component.theme) } self.backgroundView.update(size: backgroundFrame.size, cornerRadius: backgroundFrame.height * 0.5, isDark: component.theme.overallDarkAppearance, tintColor: backgroundTintColor, isInteractive: true, transition: transition) @@ -338,7 +346,7 @@ final class StarReactionButtonComponent: Component { if component.isFilled { backgroundTintColor = .init(kind: .custom, color: UIColor(rgb: 0xFFB10D)) } else { - backgroundTintColor = .init(kind: .panel, color: component.theme.chat.inputPanel.inputBackgroundColor.withMultipliedAlpha(0.7)) + backgroundTintColor = neutralStarReactionGlassTint(theme: component.theme) } self.backgroundView.update(size: backgroundFrame.size, cornerRadius: backgroundFrame.height * 0.5, isDark: component.theme.overallDarkAppearance, tintColor: backgroundTintColor, isInteractive: false, transition: transition) diff --git a/submodules/TelegramUI/Components/ChatControllerInteraction/Sources/ChatControllerInteraction.swift b/submodules/TelegramUI/Components/ChatControllerInteraction/Sources/ChatControllerInteraction.swift index 894a9d0f..e8b430e8 100644 --- a/submodules/TelegramUI/Components/ChatControllerInteraction/Sources/ChatControllerInteraction.swift +++ b/submodules/TelegramUI/Components/ChatControllerInteraction/Sources/ChatControllerInteraction.swift @@ -174,6 +174,9 @@ public final class ChatControllerInteraction: ChatControllerInteractionProtocol } public let openMessage: (Message, OpenMessageParams) -> Bool + // MARK: Swiftgram + public let sgStartMessageEdit: (Message) -> Void + public let sgGetChatPredictedLang: () -> String? public let openPeer: (EnginePeer, ChatControllerInteractionNavigateToPeer, MessageReference?, OpenPeerSource) -> Void public let openPeerMention: (String, Promise?) -> Void public let openMessageContextMenu: (Message, Bool, ASDisplayNode, CGRect, UIGestureRecognizer?, CGPoint?) -> Void @@ -343,6 +346,8 @@ public final class ChatControllerInteraction: ChatControllerInteractionProtocol public init( openMessage: @escaping (Message, OpenMessageParams) -> Bool, + sgGetChatPredictedLang: @escaping () -> String? = { return nil }, + sgStartMessageEdit: @escaping (Message) -> Void = { _ in }, openPeer: @escaping (EnginePeer, ChatControllerInteractionNavigateToPeer, MessageReference?, OpenPeerSource) -> Void, openPeerMention: @escaping (String, Promise?) -> Void, openMessageContextMenu: @escaping (Message, Bool, ASDisplayNode, CGRect, UIGestureRecognizer?, CGPoint?) -> Void, @@ -465,6 +470,8 @@ public final class ChatControllerInteraction: ChatControllerInteractionProtocol presentationContext: ChatPresentationContext ) { self.openMessage = openMessage + self.sgGetChatPredictedLang = sgGetChatPredictedLang + self.sgStartMessageEdit = sgStartMessageEdit self.openPeer = openPeer self.openPeerMention = openPeerMention self.openMessageContextMenu = openMessageContextMenu diff --git a/submodules/TelegramUI/Components/ChatEntityKeyboardInputNode/Sources/ChatEntityKeyboardInputNode.swift b/submodules/TelegramUI/Components/ChatEntityKeyboardInputNode/Sources/ChatEntityKeyboardInputNode.swift index efac3288..d89743a4 100644 --- a/submodules/TelegramUI/Components/ChatEntityKeyboardInputNode/Sources/ChatEntityKeyboardInputNode.swift +++ b/submodules/TelegramUI/Components/ChatEntityKeyboardInputNode/Sources/ChatEntityKeyboardInputNode.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import Display @@ -483,7 +484,7 @@ public final class ChatEntityKeyboardInputNode: ChatInputNode { public init(context: AccountContext, currentInputData: InputData, updatedInputData: Signal, defaultToEmojiTab: Bool, opaqueTopPanelBackground: Bool = false, useOpaqueTheme: Bool = false, interaction: ChatEntityKeyboardInputNode.Interaction?, chatPeerId: PeerId?, stateContext: StateContext?, forceHasPremium: Bool = false) { self.context = context self.currentInputData = currentInputData - self.defaultToEmojiTab = defaultToEmojiTab + self.defaultToEmojiTab = SGSimpleSettings.shared.forceEmojiTab ? true : defaultToEmojiTab self.opaqueTopPanelBackground = opaqueTopPanelBackground self.useOpaqueTheme = useOpaqueTheme self.stateContext = stateContext @@ -2653,6 +2654,7 @@ public final class EntityInputView: UIInputView, AttachmentTextInputPanelInputVi let presentationInterfaceState = ChatPresentationInterfaceState( chatWallpaper: .builtin(WallpaperSettings()), theme: self.presentationData.theme, + preferredGlassType: .default, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, diff --git a/submodules/TelegramUI/Components/ChatList/ChatListFilterTabContainerNode/Sources/ChatListFilterTabContainerNode.swift b/submodules/TelegramUI/Components/ChatList/ChatListFilterTabContainerNode/Sources/ChatListFilterTabContainerNode.swift index b393b8da..7f674884 100644 --- a/submodules/TelegramUI/Components/ChatList/ChatListFilterTabContainerNode/Sources/ChatListFilterTabContainerNode.swift +++ b/submodules/TelegramUI/Components/ChatList/ChatListFilterTabContainerNode/Sources/ChatListFilterTabContainerNode.swift @@ -1,4 +1,5 @@ import Foundation +import SGSimpleSettings import UIKit import AsyncDisplayKit import Display @@ -334,6 +335,11 @@ private final class ItemNode: ASDisplayNode { } func updateLayout(height: CGFloat, transition: ContainedViewLayoutTransition) -> (width: CGFloat, shortWidth: CGFloat) { + // MARK: Swiftgram + var height = height + if SGSimpleSettings.shared.hideTabBar { + height = 46.0 + } let titleSize = self.titleNode.updateLayout(CGSize(width: 160.0, height: .greatestFiniteMagnitude)) let _ = self.titleActiveNode.updateLayout(CGSize(width: 160.0, height: .greatestFiniteMagnitude)) let titleFrame = CGRect(origin: CGPoint(x: -self.titleNode.insets.left, y: floor((height - titleSize.height) / 2.0)), size: titleSize) @@ -380,6 +386,11 @@ private final class ItemNode: ASDisplayNode { } func updateArea(size: CGSize, sideInset: CGFloat, useShortTitle: Bool, transition: ContainedViewLayoutTransition) { + // MARK: Swiftgram + var size = size + if SGSimpleSettings.shared.hideTabBar { + size.height = 46.0 + } transition.updateAlpha(node: self.titleContainer, alpha: useShortTitle ? 0.0 : 1.0) transition.updateAlpha(node: self.shortTitleContainer, alpha: useShortTitle ? 1.0 : 0.0) @@ -534,7 +545,11 @@ public final class ChatListFilterTabContainerNode: ASDisplayNode { } } - public init(context: AccountContext) { + // MARK: Swiftgram + public let inline: Bool + private var backgroundNode: NavigationBackgroundNode? = nil + + public init(inline: Bool = false, context: AccountContext) { self.context = context self.backgroundContainerView = GlassBackgroundContainerView() @@ -547,6 +562,13 @@ public final class ChatListFilterTabContainerNode: ASDisplayNode { self.selectedBackgroundNode.displaysAsynchronously = false self.selectedBackgroundNode.displayWithoutProcessing = true + // MARK: Swiftgram + self.inline = inline + if self.inline { + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + self.backgroundNode = NavigationBackgroundNode(color: presentationData.theme.rootController.navigationBar.blurredBackgroundColor) + } + super.init() self.view.addSubview(self.backgroundContainerView) @@ -703,7 +725,7 @@ public final class ChatListFilterTabContainerNode: ASDisplayNode { self.backgroundContainerView.update(size: backgroundSize, isDark: presentationData.theme.overallDarkAppearance, transition: ComponentTransition(transition)) transition.updateFrame(view: self.backgroundView, frame: CGRect(origin: CGPoint(), size: backgroundSize)) - self.backgroundView.update(size: backgroundSize, cornerRadius: backgroundSize.height * 0.5, isDark: presentationData.theme.overallDarkAppearance, tintColor: .init(kind: .panel, color: UIColor(white: presentationData.theme.overallDarkAppearance ? 0.0 : 1.0, alpha: 0.6)), isInteractive: true, transition: ComponentTransition(transition)) + self.backgroundView.update(size: backgroundSize, cornerRadius: backgroundSize.height * 0.5, isDark: presentationData.theme.overallDarkAppearance, tintColor: .init(kind: .panel), isInteractive: true, transition: ComponentTransition(transition)) var isEditing = isEditing if isReordering { @@ -828,7 +850,7 @@ public final class ChatListFilterTabContainerNode: ASDisplayNode { selectionFraction = 0.0 } - itemNode.updateText(strings: presentationData.strings, title: filter.title(strings: presentationData.strings), shortTitle: i == 0 ? filter.shortTitle(strings: presentationData.strings) : filter.title(strings: presentationData.strings), unreadCount: unreadCount, unreadHasUnmuted: unreadHasUnmuted, isNoFilter: isNoFilter, selectionFraction: selectionFraction, isEditing: isEditing, isReordering: isReordering, canReorderAllChats: canReorderAllChats, isDisabled: isDisabled, presentationData: presentationData, transition: itemNodeTransition) + itemNode.updateText(strings: presentationData.strings, title: filter.title(strings: presentationData.strings), shortTitle: filter.shortTitle(strings: presentationData.strings), unreadCount: unreadCount, unreadHasUnmuted: unreadHasUnmuted, isNoFilter: isNoFilter, selectionFraction: selectionFraction, isEditing: isEditing, isReordering: isReordering, canReorderAllChats: canReorderAllChats, isDisabled: isDisabled, presentationData: presentationData, transition: itemNodeTransition) } var removeKeys: [ChatListFilterTabEntryId] = [] for (id, _) in self.itemNodes { @@ -875,7 +897,7 @@ public final class ChatListFilterTabContainerNode: ASDisplayNode { } } - let minSpacing: CGFloat = 26.0 + let minSpacing: CGFloat = 26.0 / (SGSimpleSettings.shared.compactFolderNames ? 2.5 : 1.0) let resolvedSideInset: CGFloat = 14.0 var leftOffset: CGFloat = resolvedSideInset @@ -898,7 +920,7 @@ public final class ChatListFilterTabContainerNode: ASDisplayNode { itemNodeTransition = .immediate } - let useShortTitle = itemId == .all && useShortTitles + let useShortTitle = itemId == .all && sgUseShortAllChatsTitle(useShortTitles) let paneNodeSize = useShortTitle ? paneNodeShortSize : paneNodeLongSize let paneFrame = CGRect(origin: CGPoint(x: leftOffset, y: floor((backgroundSize.height - paneNodeSize.height) / 2.0)), size: paneNodeSize) diff --git a/submodules/TelegramUI/Components/ChatList/ChatListHeaderNoticeComponent/Sources/ChatListNoticeItem.swift b/submodules/TelegramUI/Components/ChatList/ChatListHeaderNoticeComponent/Sources/ChatListNoticeItem.swift index 7c7cb283..cff71569 100644 --- a/submodules/TelegramUI/Components/ChatList/ChatListHeaderNoticeComponent/Sources/ChatListNoticeItem.swift +++ b/submodules/TelegramUI/Components/ChatList/ChatListHeaderNoticeComponent/Sources/ChatListNoticeItem.swift @@ -186,6 +186,12 @@ final class ChatListNoticeItemNode: ItemListRevealOptionsItemNode { var alignment: NSTextAlignment = .left switch item.notice { + // MARK: Swiftgram + case let .sgUrl(_, title, text, _, _, _): + let titleStringValue = NSMutableAttributedString(attributedString: NSAttributedString(string: title, font: titleFont, textColor: item.theme.rootController.navigationBar.primaryTextColor)) + titleString = titleStringValue + + textString = NSAttributedString(string: text ?? "", font: textFont, textColor: item.theme.rootController.navigationBar.secondaryTextColor) case let .clearStorage(sizeFraction): let sizeString = dataSizeString(Int64(sizeFraction), formatting: DataSizeStringFormatting(strings: item.strings, decimalSeparator: ".")) let rawTitleString = item.strings.ChatList_StorageHintTitle(sizeString) diff --git a/submodules/TelegramUI/Components/ChatThemeScreen/Sources/ChatThemeScreen.swift b/submodules/TelegramUI/Components/ChatThemeScreen/Sources/ChatThemeScreen.swift index abcfe86f..28f829c0 100644 --- a/submodules/TelegramUI/Components/ChatThemeScreen/Sources/ChatThemeScreen.swift +++ b/submodules/TelegramUI/Components/ChatThemeScreen/Sources/ChatThemeScreen.swift @@ -976,35 +976,40 @@ private class ChatThemeScreenNode: ViewControllerTracingNode, ASScrollViewDelega } self.otherButton.addTarget(self, action: #selector(self.otherButtonPressed), forControlEvents: .touchUpInside) - self.disposable.set(combineLatest( - queue: Queue.mainQueue(), - self.context.engine.themes.getChatThemes(accountManager: self.context.sharedContext.accountManager), - self.uniqueGiftChatThemesContext.state - |> mapToSignal { state -> Signal<(UniqueGiftChatThemesContext.State, [EnginePeer.Id: EnginePeer]), NoError> in - var peerIds: [EnginePeer.Id] = [] - for theme in state.themes { - if case let .gift(gift, _) = theme, case let .unique(uniqueGift) = gift, let themePeerId = uniqueGift.themePeerId { - peerIds.append(themePeerId) - } + let chatThemesSignal: Signal<[TelegramTheme], NoError> = self.context.engine.themes.getChatThemes(accountManager: self.context.sharedContext.accountManager) + let uniqueGiftThemesSignal: Signal<(UniqueGiftChatThemesContext.State, [EnginePeer.Id: EnginePeer]), NoError> = self.uniqueGiftChatThemesContext.state + |> mapToSignal { [context] state -> Signal<(UniqueGiftChatThemesContext.State, [EnginePeer.Id: EnginePeer]), NoError> in + var peerIds: [EnginePeer.Id] = [] + for theme in state.themes { + if case let .gift(gift, _) = theme, case let .unique(uniqueGift) = gift, let themePeerId = uniqueGift.themePeerId { + peerIds.append(themePeerId) } - return combineLatest( - .single(state), - context.engine.data.get( - EngineDataMap(peerIds.map(TelegramEngine.EngineData.Item.Peer.Peer.init)) - ) |> map { peers in - var result: [EnginePeer.Id: EnginePeer] = [:] - for peerId in peerIds { - if let maybePeer = peers[peerId], let peer = maybePeer { - result[peerId] = peer - } + } + return combineLatest( + .single(state), + context.engine.data.get( + EngineDataMap(peerIds.map(TelegramEngine.EngineData.Item.Peer.Peer.init)) + ) |> map { peers in + var result: [EnginePeer.Id: EnginePeer] = [:] + for peerId in peerIds { + if let maybePeer = peers[peerId], let peer = maybePeer { + result[peerId] = peer } - return result } - ) - }, + return result + } + ) + } + + let combinedSignal: Signal<([TelegramTheme], (UniqueGiftChatThemesContext.State, [EnginePeer.Id: EnginePeer]), ChatTheme?, Bool), NoError> = combineLatest( + chatThemesSignal, + uniqueGiftThemesSignal, self.selectedThemePromise.get(), self.isDarkAppearancePromise.get() - ).startStrict(next: { [weak self] themes, uniqueGiftChatThemesStateAndPeers, selectedTheme, isDarkAppearance in + ) + |> deliverOnMainQueue + + let combinedDisposable = combinedSignal.startStrict(next: { [weak self] themes, uniqueGiftChatThemesStateAndPeers, selectedTheme, isDarkAppearance in guard let strongSelf = self else { return } @@ -1045,7 +1050,7 @@ private class ChatThemeScreenNode: ViewControllerTracingNode, ASScrollViewDelega var peer: EnginePeer? if case let .unique(uniqueGift) = gift { for attribute in uniqueGift.attributes { - if case let .model(_, file, _) = attribute { + if case let .model(_, file, _, _) = attribute { emojiFile = file } } @@ -1139,7 +1144,8 @@ private class ChatThemeScreenNode: ViewControllerTracingNode, ASScrollViewDelega } } } - })) + }) + self.disposable.set(combinedDisposable) self.switchThemeButton.highligthedChanged = { [weak self] highlighted in if let strongSelf = self { diff --git a/submodules/TelegramUI/Components/ComposeTodoScreen/Sources/ComposeTodoScreen.swift b/submodules/TelegramUI/Components/ComposeTodoScreen/Sources/ComposeTodoScreen.swift index 0f9c4740..a2290011 100644 --- a/submodules/TelegramUI/Components/ComposeTodoScreen/Sources/ComposeTodoScreen.swift +++ b/submodules/TelegramUI/Components/ComposeTodoScreen/Sources/ComposeTodoScreen.swift @@ -450,6 +450,7 @@ final class ComposeTodoScreenComponent: Component { let presentationInterfaceState = ChatPresentationInterfaceState( chatWallpaper: .builtin(WallpaperSettings()), theme: presentationData.theme, + preferredGlassType: .default, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameDisplayOrder: presentationData.nameDisplayOrder, diff --git a/submodules/TelegramUI/Components/ContextControllerImpl/BUILD b/submodules/TelegramUI/Components/ContextControllerImpl/BUILD new file mode 100644 index 00000000..1d483ab2 --- /dev/null +++ b/submodules/TelegramUI/Components/ContextControllerImpl/BUILD @@ -0,0 +1,18 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "ContextControllerImpl", + module_name = "ContextControllerImpl", + srcs = [ + "Sources/ContextControllerCompatibility.swift", + ], + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/ContextUI", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextActionNode.swift b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextActionNode.swift new file mode 100644 index 00000000..c086d6d1 --- /dev/null +++ b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextActionNode.swift @@ -0,0 +1,445 @@ +import Foundation +import UIKit +import AsyncDisplayKit +import Display +import TelegramPresentationData +import SwiftSignalKit +import Markdown +import ContextUI + +public final class ContextActionNode: ASDisplayNode, ContextActionNodeProtocol { + private var presentationData: PresentationData + private(set) var action: ContextMenuActionItem + private let getController: () -> ContextControllerProtocol? + private let actionSelected: (ContextMenuActionResult) -> Void + private let requestLayout: () -> Void + private let requestUpdateAction: (AnyHashable, ContextMenuActionItem) -> Void + + private let backgroundNode: ASDisplayNode + private let highlightedBackgroundNode: ASDisplayNode + private let textNode: ImmediateTextNode + private let statusNode: ImmediateTextNode? + private let iconNode: ASImageNode + private let titleIconNode: ASImageNode + private let badgeBackgroundNode: ASImageNode + private let badgeTextNode: ImmediateTextNode + private let buttonNode: HighlightTrackingButtonNode + + private var iconDisposable: Disposable? + + private var pointerInteraction: PointerInteraction? + + public var isActionEnabled: Bool { + return true + } + + public init(presentationData: PresentationData, action: ContextMenuActionItem, getController: @escaping () -> ContextControllerProtocol?, actionSelected: @escaping (ContextMenuActionResult) -> Void, requestLayout: @escaping () -> Void, requestUpdateAction: @escaping (AnyHashable, ContextMenuActionItem) -> Void) { + self.presentationData = presentationData + self.action = action + self.getController = getController + self.actionSelected = actionSelected + self.requestLayout = requestLayout + self.requestUpdateAction = requestUpdateAction + + let textFont = Font.regular(presentationData.listsFontSize.baseDisplaySize) + let smallTextFont = Font.regular(floor(presentationData.listsFontSize.baseDisplaySize * 14.0 / 17.0)) + + let boldTextFont = Font.semibold(presentationData.listsFontSize.baseDisplaySize) + let smallBoldTextFont = Font.semibold(floor(presentationData.listsFontSize.baseDisplaySize * 14.0 / 17.0)) + + self.backgroundNode = ASDisplayNode() + self.backgroundNode.isAccessibilityElement = false + self.backgroundNode.backgroundColor = presentationData.theme.contextMenu.itemBackgroundColor + self.highlightedBackgroundNode = ASDisplayNode() + self.highlightedBackgroundNode.isAccessibilityElement = false + self.highlightedBackgroundNode.backgroundColor = presentationData.theme.contextMenu.itemHighlightedBackgroundColor + self.highlightedBackgroundNode.alpha = 0.0 + + self.textNode = ImmediateTextNode() + self.textNode.isAccessibilityElement = false + self.textNode.isUserInteractionEnabled = false + self.textNode.displaysAsynchronously = false + let textColor: UIColor + switch action.textColor { + case .primary: + textColor = presentationData.theme.contextMenu.primaryColor + case .destructive: + textColor = presentationData.theme.contextMenu.destructiveColor + case .disabled: + textColor = presentationData.theme.contextMenu.primaryColor.withMultipliedAlpha(0.4) + } + + let titleFont: UIFont + let titleBoldFont: UIFont + switch action.textFont { + case .regular: + titleFont = textFont + titleBoldFont = boldTextFont + case .small: + titleFont = smallTextFont + titleBoldFont = smallBoldTextFont + case let .custom(customFont, _, _): + titleFont = customFont + titleBoldFont = customFont + } + + let subtitleFont = Font.regular(presentationData.listsFontSize.baseDisplaySize * 14.0 / 17.0) + + if action.parseMarkdown { + let attributedText = parseMarkdownIntoAttributedString(action.text, attributes: MarkdownAttributes(body: MarkdownAttributeSet(font: titleFont, textColor: textColor), bold: MarkdownAttributeSet(font: titleBoldFont, textColor: textColor), link: MarkdownAttributeSet(font: titleFont, textColor: textColor), linkAttribute: { _ in + return nil + })) + self.textNode.attributedText = attributedText + } else { + self.textNode.attributedText = NSAttributedString(string: action.text, font: titleFont, textColor: textColor) + } + + switch action.textLayout { + case .singleLine: + self.textNode.maximumNumberOfLines = 1 + self.statusNode = nil + case .twoLinesMax: + self.textNode.maximumNumberOfLines = 2 + self.statusNode = nil + case let .secondLineWithValue(value): + self.textNode.maximumNumberOfLines = 1 + let statusNode = ImmediateTextNode() + statusNode.isAccessibilityElement = false + statusNode.isUserInteractionEnabled = false + statusNode.displaysAsynchronously = false + statusNode.attributedText = NSAttributedString(string: value, font: subtitleFont, textColor: presentationData.theme.contextMenu.secondaryColor) + statusNode.maximumNumberOfLines = 1 + self.statusNode = statusNode + case let .secondLineWithAttributedValue(value): + self.textNode.maximumNumberOfLines = 1 + let statusNode = ImmediateTextNode() + statusNode.isAccessibilityElement = false + statusNode.isUserInteractionEnabled = false + statusNode.displaysAsynchronously = false + + let mutableString = value.mutableCopy() as! NSMutableAttributedString + mutableString.addAttribute(.foregroundColor, value: presentationData.theme.contextMenu.secondaryColor, range: NSRange(location: 0, length: mutableString.length)) + mutableString.addAttribute(.font, value: subtitleFont, range: NSRange(location: 0, length: mutableString.length)) + statusNode.attributedText = mutableString + statusNode.maximumNumberOfLines = 1 + self.statusNode = statusNode + case .multiline: + self.textNode.maximumNumberOfLines = 0 + self.statusNode = nil + } + + self.iconNode = ASImageNode() + self.iconNode.isAccessibilityElement = false + self.iconNode.displaysAsynchronously = false + self.iconNode.displayWithoutProcessing = true + self.iconNode.isUserInteractionEnabled = false + if let iconSource = action.iconSource { + self.iconNode.clipsToBounds = true + self.iconNode.contentMode = iconSource.contentMode + self.iconNode.cornerRadius = iconSource.cornerRadius + } else { + self.iconNode.image = action.icon(presentationData.theme) + } + + self.titleIconNode = ASImageNode() + self.titleIconNode.isAccessibilityElement = false + self.titleIconNode.displaysAsynchronously = false + self.titleIconNode.displayWithoutProcessing = true + self.titleIconNode.isUserInteractionEnabled = false + self.titleIconNode.image = action.textIcon(presentationData.theme) + + self.badgeBackgroundNode = ASImageNode() + self.badgeBackgroundNode.isAccessibilityElement = false + self.badgeBackgroundNode.displaysAsynchronously = false + self.badgeBackgroundNode.displayWithoutProcessing = true + self.badgeBackgroundNode.isUserInteractionEnabled = false + + self.badgeTextNode = ImmediateTextNode() + if let badge = action.badge { + let badgeFillColor: UIColor + let badgeForegroundColor: UIColor + switch badge.color { + case .accent: + badgeForegroundColor = presentationData.theme.contextMenu.badgeForegroundColor + badgeFillColor = presentationData.theme.contextMenu.badgeFillColor + case .inactive: + badgeForegroundColor = presentationData.theme.contextMenu.badgeInactiveForegroundColor + badgeFillColor = presentationData.theme.contextMenu.badgeInactiveFillColor + } + self.badgeBackgroundNode.image = generateStretchableFilledCircleImage(diameter: 18.0, color: badgeFillColor) + self.badgeTextNode.attributedText = NSAttributedString(string: badge.value, font: Font.regular(14.0), textColor: badgeForegroundColor) + } + self.badgeTextNode.isAccessibilityElement = false + self.badgeTextNode.isUserInteractionEnabled = false + self.badgeTextNode.displaysAsynchronously = false + + self.buttonNode = HighlightTrackingButtonNode() + self.buttonNode.isAccessibilityElement = true + self.buttonNode.accessibilityLabel = action.text + + super.init() + + self.addSubnode(self.backgroundNode) + self.addSubnode(self.highlightedBackgroundNode) + self.addSubnode(self.textNode) + self.statusNode.flatMap(self.addSubnode) + self.addSubnode(self.iconNode) + self.addSubnode(self.badgeBackgroundNode) + self.addSubnode(self.badgeTextNode) + self.addSubnode(self.buttonNode) + if let _ = self.titleIconNode.image { + self.addSubnode(self.titleIconNode) + } + + self.buttonNode.highligthedChanged = { [weak self] highligted in + guard let strongSelf = self else { + return + } + if highligted { + strongSelf.highlightedBackgroundNode.alpha = 1.0 + } else { + strongSelf.highlightedBackgroundNode.alpha = 0.0 + strongSelf.highlightedBackgroundNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.3) + } + } + self.buttonNode.addTarget(self, action: #selector(self.buttonPressed), forControlEvents: .touchUpInside) + self.buttonNode.isUserInteractionEnabled = self.action.action != nil + + if let iconSource = action.iconSource { + self.iconDisposable = (iconSource.signal + |> deliverOnMainQueue).start(next: { [weak self] image in + guard let strongSelf = self else { + return + } + strongSelf.iconNode.image = image + }).strict() + } + } + + deinit { + self.iconDisposable?.dispose() + } + + public override func didLoad() { + super.didLoad() + + self.pointerInteraction = PointerInteraction(node: self.buttonNode, style: .hover, willEnter: { [weak self] in + if let strongSelf = self { + strongSelf.highlightedBackgroundNode.alpha = 0.75 + } + }, willExit: { [weak self] in + if let strongSelf = self { + strongSelf.highlightedBackgroundNode.alpha = 0.0 + } + }) + } + + public func updateLayout(constrainedWidth: CGFloat, previous: ContextActionSibling, next: ContextActionSibling) -> (CGSize, (CGSize, ContainedViewLayoutTransition) -> Void) { + let sideInset: CGFloat = 16.0 + let iconSideInset: CGFloat = 12.0 + let verticalInset: CGFloat = 12.0 + + let iconSize: CGSize + if let iconSource = self.action.iconSource { + iconSize = iconSource.size + } else { + iconSize = self.iconNode.image.flatMap({ $0.size }) ?? CGSize() + } + + let standardIconWidth: CGFloat = 32.0 + var rightTextInset: CGFloat = sideInset + if !iconSize.width.isZero { + rightTextInset = max(iconSize.width, standardIconWidth) + iconSideInset + sideInset + } + if let iconSize = self.titleIconNode.image?.size { + rightTextInset += iconSize.width + 10.0 + } + + let badgeTextSize = self.badgeTextNode.updateLayout(CGSize(width: constrainedWidth, height: .greatestFiniteMagnitude)) + let badgeInset: CGFloat = 4.0 + + let badgeSize: CGSize + let badgeWidthSpace: CGFloat + let badgeSpacing: CGFloat = 10.0 + if badgeTextSize.width.isZero { + badgeSize = CGSize() + badgeWidthSpace = 0.0 + } else { + badgeSize = CGSize(width: max(18.0, badgeTextSize.width + badgeInset * 2.0), height: 18.0) + badgeWidthSpace = badgeSize.width + badgeSpacing + } + + let textSize = self.textNode.updateLayout(CGSize(width: constrainedWidth - sideInset - rightTextInset - badgeWidthSpace, height: .greatestFiniteMagnitude)) + let statusSize = self.statusNode?.updateLayout(CGSize(width: constrainedWidth - sideInset - rightTextInset - badgeWidthSpace, height: .greatestFiniteMagnitude)) ?? CGSize() + + if !statusSize.width.isZero, let statusNode = self.statusNode { + let verticalSpacing: CGFloat = 2.0 + let combinedTextHeight = textSize.height + verticalSpacing + statusSize.height + return (CGSize(width: max(textSize.width, statusSize.width) + sideInset + rightTextInset + badgeWidthSpace, height: verticalInset * 2.0 + combinedTextHeight), { size, transition in + let verticalOrigin = floor((size.height - combinedTextHeight) / 2.0) + let textFrame = CGRect(origin: CGPoint(x: sideInset, y: verticalOrigin), size: textSize) + transition.updateFrameAdditive(node: self.textNode, frame: textFrame) + transition.updateFrameAdditive(node: statusNode, frame: CGRect(origin: CGPoint(x: sideInset, y: verticalOrigin + verticalSpacing + textSize.height), size: statusSize)) + + let badgeFrame = CGRect(origin: CGPoint(x: textFrame.maxX + badgeSpacing, y: floor((size.height - badgeSize.height) / 2.0)), size: badgeSize) + transition.updateFrame(node: self.badgeBackgroundNode, frame: badgeFrame) + transition.updateFrame(node: self.badgeTextNode, frame: CGRect(origin: CGPoint(x: badgeFrame.minX + floorToScreenPixels((badgeFrame.width - badgeTextSize.width) / 2.0), y: badgeFrame.minY + floor((badgeFrame.height - badgeTextSize.height) / 2.0)), size: badgeTextSize)) + + if !iconSize.width.isZero { + transition.updateFrameAdditive(node: self.iconNode, frame: CGRect(origin: CGPoint(x: size.width - standardIconWidth - iconSideInset + floor((standardIconWidth - iconSize.width) / 2.0), y: floor((size.height - iconSize.height) / 2.0)), size: iconSize)) + } + + transition.updateFrame(node: self.backgroundNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) + transition.updateFrame(node: self.highlightedBackgroundNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) + transition.updateFrame(node: self.buttonNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) + + if let iconSize = self.titleIconNode.image?.size { + transition.updateFrame(node: self.titleIconNode, frame: CGRect(origin: CGPoint(x: self.textNode.frame.maxX + 7.0, y: floorToScreenPixels(self.textNode.frame.midY - iconSize.height / 2.0)), size: iconSize)) + } + }) + } else { + return (CGSize(width: textSize.width + sideInset + rightTextInset + badgeWidthSpace, height: verticalInset * 2.0 + textSize.height), { size, transition in + let verticalOrigin = floor((size.height - textSize.height) / 2.0) + let textFrame = CGRect(origin: CGPoint(x: sideInset, y: verticalOrigin), size: textSize) + transition.updateFrameAdditive(node: self.textNode, frame: textFrame) + + if !iconSize.width.isZero { + transition.updateFrameAdditive(node: self.iconNode, frame: CGRect(origin: CGPoint(x: size.width - standardIconWidth - iconSideInset + floor((standardIconWidth - iconSize.width) / 2.0), y: floor((size.height - iconSize.height) / 2.0)), size: iconSize)) + } + + let badgeFrame = CGRect(origin: CGPoint(x: textFrame.maxX + badgeSpacing, y: floor((size.height - badgeSize.height) / 2.0)), size: badgeSize) + transition.updateFrame(node: self.badgeBackgroundNode, frame: badgeFrame) + transition.updateFrame(node: self.badgeTextNode, frame: CGRect(origin: CGPoint(x: badgeFrame.minX + floorToScreenPixels((badgeFrame.width - badgeTextSize.width) / 2.0), y: badgeFrame.minY + floor((badgeFrame.height - badgeTextSize.height) / 2.0)), size: badgeTextSize)) + + transition.updateFrame(node: self.backgroundNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) + transition.updateFrame(node: self.highlightedBackgroundNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) + transition.updateFrame(node: self.buttonNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) + + if let iconSize = self.titleIconNode.image?.size { + transition.updateFrame(node: self.titleIconNode, frame: CGRect(origin: CGPoint(x: self.textNode.frame.maxX + 7.0, y: floorToScreenPixels(self.textNode.frame.midY - iconSize.height / 2.0)), size: iconSize)) + } + }) + } + } + + public func updateTheme(presentationData: PresentationData) { + self.presentationData = presentationData + + self.backgroundNode.backgroundColor = presentationData.theme.contextMenu.itemBackgroundColor + self.highlightedBackgroundNode.backgroundColor = presentationData.theme.contextMenu.itemHighlightedBackgroundColor + + let textColor: UIColor + switch action.textColor { + case .primary: + textColor = presentationData.theme.contextMenu.primaryColor + case .destructive: + textColor = presentationData.theme.contextMenu.destructiveColor + case .disabled: + textColor = presentationData.theme.contextMenu.primaryColor.withMultipliedAlpha(0.4) + } + + let textFont = Font.regular(presentationData.listsFontSize.baseDisplaySize) + let smallTextFont = Font.regular(floor(presentationData.listsFontSize.baseDisplaySize * 14.0 / 17.0)) + let titleFont: UIFont + switch self.action.textFont { + case .regular: + titleFont = textFont + case .small: + titleFont = smallTextFont + case let .custom(customFont, _, _): + titleFont = customFont + } + + self.textNode.attributedText = NSAttributedString(string: self.action.text, font: titleFont, textColor: textColor) + + let subtitleFont = Font.regular(presentationData.listsFontSize.baseDisplaySize * 13.0 / 17.0) + switch self.action.textLayout { + case let .secondLineWithValue(value): + self.statusNode?.attributedText = NSAttributedString(string: value, font: subtitleFont, textColor: presentationData.theme.contextMenu.secondaryColor) + case let .secondLineWithAttributedValue(value): + let mutableString = value.mutableCopy() as! NSMutableAttributedString + mutableString.addAttribute(.foregroundColor, value: presentationData.theme.contextMenu.secondaryColor, range: NSRange(location: 0, length: mutableString.length)) + mutableString.addAttribute(.font, value: subtitleFont, range: NSRange(location: 0, length: mutableString.length)) + self.statusNode?.attributedText = mutableString + default: + break + } + + if self.action.iconSource == nil { + self.iconNode.image = self.action.icon(presentationData.theme) + } + + self.badgeBackgroundNode.image = generateStretchableFilledCircleImage(diameter: 18.0, color: presentationData.theme.contextMenu.badgeFillColor) + self.badgeTextNode.attributedText = NSAttributedString(string: self.badgeTextNode.attributedText?.string ?? "", font: Font.regular(14.0), textColor: presentationData.theme.contextMenu.badgeForegroundColor) + } + + @objc private func buttonPressed() { + self.performAction() + } + + func updateAction(item: ContextMenuActionItem) { + self.action = item + + let textColor: UIColor + switch self.action.textColor { + case .primary: + textColor = self.presentationData.theme.contextMenu.primaryColor + case .destructive: + textColor = self.presentationData.theme.contextMenu.destructiveColor + case .disabled: + textColor = self.presentationData.theme.contextMenu.primaryColor.withMultipliedAlpha(0.4) + } + + let textFont = Font.regular(self.presentationData.listsFontSize.baseDisplaySize) + let smallTextFont = Font.regular(floor(presentationData.listsFontSize.baseDisplaySize * 14.0 / 17.0)) + let titleFont: UIFont + switch self.action.textFont { + case .regular: + titleFont = textFont + case .small: + titleFont = smallTextFont + case let .custom(customFont, _, _): + titleFont = customFont + } + + self.textNode.attributedText = NSAttributedString(string: self.action.text, font: titleFont, textColor: textColor) + + if self.action.iconSource == nil { + self.iconNode.image = self.action.icon(self.presentationData.theme) + } + + self.requestLayout() + } + + private var performedAction = false + public func performAction() { + guard let controller = self.getController(), !self.performedAction else { + return + } + self.action.action?(ContextMenuActionItem.Action( + controller: controller, + dismissWithResult: { [weak self] result in + self?.performedAction = true + self?.actionSelected(result) + }, + updateAction: { [weak self] id, updatedAction in + guard let strongSelf = self else { + return + } + strongSelf.requestUpdateAction(id, updatedAction) + } + )) + } + + public func setIsHighlighted(_ value: Bool) { + if value && self.buttonNode.isUserInteractionEnabled { + self.highlightedBackgroundNode.alpha = 1.0 + } else { + self.highlightedBackgroundNode.alpha = 0.0 + } + } + + public func actionNode(at point: CGPoint) -> ContextActionNodeProtocol { + return self + } +} diff --git a/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextActionsContainerNode.swift b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextActionsContainerNode.swift new file mode 100644 index 00000000..bc21e267 --- /dev/null +++ b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextActionsContainerNode.swift @@ -0,0 +1,853 @@ +import Foundation +import UIKit +import AsyncDisplayKit +import Display +import TelegramCore +import TelegramPresentationData +import TextSelectionNode +import Markdown +import AppBundle +import TextFormat +import TextNodeWithEntities +import SwiftSignalKit +import ContextUI +import GlassBackgroundComponent +import ComponentFlow +import ComponentDisplayAdapters + +private final class ContextActionsSelectionGestureRecognizer: UIPanGestureRecognizer { + var updateLocation: ((CGPoint, Bool) -> Void)? + var completed: ((Bool) -> Void)? + + override func touchesBegan(_ touches: Set, with event: UIEvent) { + super.touchesBegan(touches, with: event) + + self.updateLocation?(touches.first!.location(in: self.view), false) + } + + override func touchesMoved(_ touches: Set, with event: UIEvent) { + super.touchesMoved(touches, with: event) + + self.updateLocation?(touches.first!.location(in: self.view), true) + } + + override func touchesEnded(_ touches: Set, with event: UIEvent) { + super.touchesEnded(touches, with: event) + + self.completed?(true) + } + + override func touchesCancelled(_ touches: Set, with event: UIEvent) { + super.touchesCancelled(touches, with: event) + + self.completed?(false) + } +} + +private enum ContextItemNode { + case action(ContextActionNode) + case custom(ContextMenuCustomNode) + case itemSeparator(ASDisplayNode) + case separator(ASDisplayNode) +} + +private final class InnerActionsContainerNode: ASDisplayNode { + private let blurBackground: Bool + private let presentationData: PresentationData + private let containerNode: ASDisplayNode + private var effectView: UIVisualEffectView? + private var itemNodes: [ContextItemNode] + private let feedbackTap: () -> Void + + private(set) var gesture: UIGestureRecognizer? + private var currentHighlightedActionNode: ContextActionNodeProtocol? + + var panSelectionGestureEnabled: Bool = true { + didSet { + if self.panSelectionGestureEnabled != oldValue, let gesture = self.gesture { + gesture.isEnabled = self.panSelectionGestureEnabled + + self.itemNodes.forEach({ itemNode in + switch itemNode { + case let .action(actionNode): + actionNode.isUserInteractionEnabled = !self.panSelectionGestureEnabled + default: + break + } + }) + } + } + } + + init(presentationData: PresentationData, items: [ContextMenuItem], getController: @escaping () -> ContextControllerProtocol?, actionSelected: @escaping (ContextMenuActionResult) -> Void, requestLayout: @escaping () -> Void, feedbackTap: @escaping () -> Void, blurBackground: Bool) { + self.presentationData = presentationData + self.feedbackTap = feedbackTap + self.blurBackground = blurBackground + + self.containerNode = ASDisplayNode() + self.containerNode.clipsToBounds = true + self.containerNode.cornerRadius = 14.0 + self.containerNode.backgroundColor = presentationData.theme.contextMenu.backgroundColor + + var requestUpdateAction: ((AnyHashable, ContextMenuActionItem) -> Void)? + + var itemNodes: [ContextItemNode] = [] + for i in 0 ..< items.count { + switch items[i] { + case let .action(action): + itemNodes.append(.action(ContextActionNode(presentationData: presentationData, action: action, getController: getController, actionSelected: actionSelected, requestLayout: requestLayout, requestUpdateAction: { id, action in + requestUpdateAction?(id, action) + }))) + case let .custom(item, _): + let itemNode = item.node(presentationData: presentationData, getController: getController, actionSelected: actionSelected) + itemNodes.append(.custom(itemNode)) + case .separator: + let separatorNode = ASDisplayNode() + separatorNode.backgroundColor = presentationData.theme.contextMenu.itemSeparatorColor + itemNodes.append(.separator(separatorNode)) + } + } + + self.itemNodes = itemNodes + + super.init() + + requestUpdateAction = { [weak self] id, action in + guard let strongSelf = self else { + return + } + loop: for itemNode in strongSelf.itemNodes { + switch itemNode { + case let .action(contextActionNode): + if contextActionNode.action.id == id { + contextActionNode.updateAction(item: action) + break loop + } + default: + break + } + } + } + + self.addSubnode(self.containerNode) + + self.itemNodes.forEach({ itemNode in + switch itemNode { + case let .action(actionNode): + actionNode.isUserInteractionEnabled = false + self.containerNode.addSubnode(actionNode) + case let .custom(itemNode): + self.containerNode.addSubnode(itemNode) + case let .itemSeparator(separatorNode): + self.containerNode.addSubnode(separatorNode) + case let .separator(separatorNode): + self.containerNode.addSubnode(separatorNode) + } + }) + + let gesture = ContextActionsSelectionGestureRecognizer(target: nil, action: nil) + self.gesture = gesture + gesture.updateLocation = { [weak self] point, moved in + guard let strongSelf = self else { + return + } + var actionNode = strongSelf.actionNode(at: point) + if let actionNodeValue = actionNode, !actionNodeValue.isActionEnabled { + actionNode = nil + } + if actionNode !== strongSelf.currentHighlightedActionNode { + if actionNode != nil, moved { + strongSelf.feedbackTap() + } + strongSelf.currentHighlightedActionNode?.setIsHighlighted(false) + } + strongSelf.currentHighlightedActionNode = actionNode + actionNode?.setIsHighlighted(true) + } + gesture.completed = { [weak self] performAction in + guard let strongSelf = self else { + return + } + if let currentHighlightedActionNode = strongSelf.currentHighlightedActionNode { + strongSelf.currentHighlightedActionNode = nil + currentHighlightedActionNode.setIsHighlighted(false) + if performAction { + currentHighlightedActionNode.performAction() + } + } + } + self.view.addGestureRecognizer(gesture) + gesture.isEnabled = self.panSelectionGestureEnabled + } + + func updateLayout(widthClass: ContainerViewLayoutSizeClass, constrainedWidth: CGFloat, constrainedHeight: CGFloat, minimalWidth: CGFloat?, transition: ContainedViewLayoutTransition) -> CGSize { + var minActionsWidth: CGFloat = 250.0 + if let minimalWidth = minimalWidth, minimalWidth > minActionsWidth { + minActionsWidth = minimalWidth + } + + switch widthClass { + case .compact: + minActionsWidth = max(minActionsWidth, floor(constrainedWidth / 3.0)) + if let effectView = self.effectView { + self.effectView = nil + effectView.removeFromSuperview() + } + case .regular: + if self.effectView == nil { + let effectView: UIVisualEffectView + if #available(iOS 13.0, *) { + if self.presentationData.theme.rootController.keyboardColor == .dark { + effectView = UIVisualEffectView(effect: UIBlurEffect(style: .systemMaterialDark)) + } else { + effectView = UIVisualEffectView(effect: UIBlurEffect(style: .systemMaterialLight)) + } + } else { + effectView = UIVisualEffectView(effect: UIBlurEffect(style: .light)) + } + self.effectView = effectView + self.containerNode.view.insertSubview(effectView, at: 0) + } + } + minActionsWidth = min(minActionsWidth, constrainedWidth) + let separatorHeight: CGFloat = 8.0 + + var maxWidth: CGFloat = 0.0 + var contentHeight: CGFloat = 0.0 + var heightsAndCompletions: [(CGFloat, (CGSize, ContainedViewLayoutTransition) -> Void)?] = [] + for i in 0 ..< self.itemNodes.count { + switch self.itemNodes[i] { + case let .action(itemNode): + let previous: ContextActionSibling + let next: ContextActionSibling + if i == 0 { + previous = .none + } else if case .separator = self.itemNodes[i - 1] { + previous = .separator + } else { + previous = .item + } + if i == self.itemNodes.count - 1 { + next = .none + } else if case .separator = self.itemNodes[i + 1] { + next = .separator + } else { + next = .item + } + let (minSize, complete) = itemNode.updateLayout(constrainedWidth: constrainedWidth, previous: previous, next: next) + maxWidth = max(maxWidth, minSize.width) + heightsAndCompletions.append((minSize.height, complete)) + contentHeight += minSize.height + case let .custom(itemNode): + let (minSize, complete) = itemNode.updateLayout(constrainedWidth: constrainedWidth, constrainedHeight: constrainedHeight) + maxWidth = max(maxWidth, minSize.width) + heightsAndCompletions.append((minSize.height, complete)) + contentHeight += minSize.height + case .itemSeparator: + heightsAndCompletions.append(nil) + contentHeight += UIScreenPixel + case .separator: + heightsAndCompletions.append(nil) + contentHeight += separatorHeight + } + } + + maxWidth = max(maxWidth, minActionsWidth) + + var verticalOffset: CGFloat = 0.0 + for i in 0 ..< heightsAndCompletions.count { + switch self.itemNodes[i] { + case let .action(itemNode): + if let (itemHeight, itemCompletion) = heightsAndCompletions[i] { + let itemSize = CGSize(width: maxWidth, height: itemHeight) + transition.updateFrame(node: itemNode, frame: CGRect(origin: CGPoint(x: 0.0, y: verticalOffset), size: itemSize)) + itemCompletion(itemSize, transition) + verticalOffset += itemHeight + } + case let .custom(itemNode): + if let (itemHeight, itemCompletion) = heightsAndCompletions[i] { + let itemSize = CGSize(width: maxWidth, height: itemHeight) + transition.updateFrame(node: itemNode, frame: CGRect(origin: CGPoint(x: 0.0, y: verticalOffset), size: itemSize)) + itemCompletion(itemSize, transition) + verticalOffset += itemHeight + } + case let .itemSeparator(separatorNode): + transition.updateFrame(node: separatorNode, frame: CGRect(origin: CGPoint(x: 0.0, y: verticalOffset), size: CGSize(width: maxWidth, height: UIScreenPixel))) + verticalOffset += UIScreenPixel + case let .separator(separatorNode): + transition.updateFrame(node: separatorNode, frame: CGRect(origin: CGPoint(x: 0.0, y: verticalOffset + floorToScreenPixels((separatorHeight - UIScreenPixel) * 0.5)), size: CGSize(width: maxWidth, height: UIScreenPixel))) + verticalOffset += separatorHeight + } + } + + let size = CGSize(width: maxWidth, height: verticalOffset) + let bounds = CGRect(origin: CGPoint(), size: size) + + transition.updateFrame(node: self.containerNode, frame: bounds) + if let effectView = self.effectView { + transition.updateFrame(view: effectView, frame: bounds) + } + return size + } + + func updateTheme(presentationData: PresentationData) { + for itemNode in self.itemNodes { + switch itemNode { + case let .action(action): + action.updateTheme(presentationData: presentationData) + case let .custom(item): + item.updateTheme(presentationData: presentationData) + case let .separator(separator): + separator.backgroundColor = presentationData.theme.contextMenu.sectionSeparatorColor + case let .itemSeparator(itemSeparator): + itemSeparator.backgroundColor = presentationData.theme.contextMenu.itemSeparatorColor + } + } + + self.containerNode.backgroundColor = presentationData.theme.contextMenu.backgroundColor + } + + func actionNode(at point: CGPoint) -> ContextActionNodeProtocol? { + for itemNode in self.itemNodes { + switch itemNode { + case let .action(actionNode): + if actionNode.frame.contains(point) { + return actionNode + } + case let .custom(node): + if let node = node as? ContextActionNodeProtocol, node.frame.contains(point) { + return node.actionNode(at: self.convert(point, to: node)) + } + default: + break + } + } + return nil + } +} + +final class InnerTextSelectionTipContainerNode: ASDisplayNode { + private let presentationData: PresentationData + private var background: (container: GlassBackgroundContainerView, background: GlassBackgroundView)? + private let textNode: TextNodeWithEntities + private var textSelectionNode: TextSelectionNode? + private let iconNode: ASImageNode + private let placeholderNode: ASDisplayNode + + var tip: ContextController.Tip + + private let text: String + private var arguments: TextNodeWithEntities.Arguments? + private var file: TelegramMediaFile? + private let targetSelectionIndex: Int? + + private var hapticFeedback: HapticFeedback? + + private var action: (() -> Void)? + var requestDismiss: (@escaping () -> Void) -> Void = { _ in } + + init(presentationData: PresentationData, tip: ContextController.Tip, isInline: Bool) { + self.tip = tip + self.presentationData = presentationData + + if !isInline { + self.background = (GlassBackgroundContainerView(), GlassBackgroundView()) + } else { + self.background = nil + } + + self.textNode = TextNodeWithEntities() + self.textNode.textNode.displaysAsynchronously = false + self.textNode.textNode.isUserInteractionEnabled = false + + var isUserInteractionEnabled = false + var icon: UIImage? + switch tip { + case .textSelection: + var rawText = self.presentationData.strings.ChatContextMenu_TextSelectionTip2 + if let range = rawText.range(of: "|") { + rawText.removeSubrange(range) + self.text = rawText + self.targetSelectionIndex = NSRange(range, in: rawText).lowerBound + } else { + self.text = rawText + self.targetSelectionIndex = 1 + } + icon = UIImage(bundleImageName: "Chat/Context Menu/Tip") + case .quoteSelection: + var rawText = presentationData.strings.ChatContextMenu_QuoteSelectionTip + if let range = rawText.range(of: "|") { + rawText.removeSubrange(range) + self.text = rawText + self.targetSelectionIndex = NSRange(range, in: rawText).lowerBound + } else { + self.text = rawText + self.targetSelectionIndex = 1 + } + icon = UIImage(bundleImageName: "Chat/Context Menu/Tip") + case .messageViewsPrivacy: + self.text = self.presentationData.strings.ChatContextMenu_MessageViewsPrivacyTip + self.targetSelectionIndex = nil + icon = UIImage(bundleImageName: "Chat/Context Menu/Tip") + case let .messageCopyProtection(isChannel): + self.text = isChannel ? self.presentationData.strings.Conversation_CopyProtectionInfoChannel : self.presentationData.strings.Conversation_CopyProtectionInfoGroup + self.targetSelectionIndex = nil + icon = UIImage(bundleImageName: "Chat/Context Menu/ReportCopyright") + case let .animatedEmoji(text, arguments, file, action): + self.action = action + self.text = text ?? "" + self.arguments = arguments + self.file = file + self.targetSelectionIndex = nil + icon = nil + isUserInteractionEnabled = text != nil + case let .notificationTopicExceptions(text, action): + self.action = action + self.text = text + self.targetSelectionIndex = nil + icon = nil + isUserInteractionEnabled = action != nil + case let .starsReactions(topCount): + self.action = nil + self.text = self.presentationData.strings.Chat_SendStarsToBecomeTopInfo("\(topCount)").string + self.targetSelectionIndex = nil + icon = nil + isUserInteractionEnabled = action != nil + case .videoProcessing: + self.action = nil + self.text = self.presentationData.strings.Chat_VideoProcessingInfo + self.targetSelectionIndex = nil + icon = nil + isUserInteractionEnabled = action != nil + case .collageReordering: + self.action = nil + self.text = self.presentationData.strings.Camera_CollageReorderingInfo + self.targetSelectionIndex = nil + icon = UIImage(bundleImageName: "Chat/Context Menu/Tip") + } + + self.iconNode = ASImageNode() + self.iconNode.displaysAsynchronously = false + self.iconNode.displayWithoutProcessing = true + self.iconNode.image = generateTintedImage(image: icon, color: presentationData.theme.contextMenu.primaryColor) + + self.placeholderNode = ASDisplayNode() + self.placeholderNode.clipsToBounds = true + self.placeholderNode.cornerRadius = 4.0 + self.placeholderNode.isUserInteractionEnabled = false + + super.init() + + let textSelectionNode = TextSelectionNode(theme: TextSelectionTheme(selection: presentationData.theme.contextMenu.primaryColor.withAlphaComponent(0.15), knob: presentationData.theme.contextMenu.primaryColor, knobDiameter: 8.0, isDark: presentationData.theme.overallDarkAppearance), strings: presentationData.strings, textNode: self.textNode.textNode, updateIsActive: { _ in + }, present: { _, _ in + }, rootNode: { [weak self] in + return self + }, performAction: { _, _ in + }) + self.textSelectionNode = textSelectionNode + + let parentView: UIView + if let background = self.background { + self.view.addSubview(background.container) + background.container.contentView.addSubview(background.background) + parentView = background.background.contentView + } else { + parentView = self.view + } + + parentView.addSubview(self.textNode.textNode.view) + parentView.addSubview(self.iconNode.view) + parentView.addSubview(self.placeholderNode.view) + + self.textSelectionNode.flatMap { parentView.addSubview($0.view) } + + parentView.addSubview(textSelectionNode.highlightAreaNode.view) + + parentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.onTapGesture(_:)))) + + let shimmeringForegroundColor: UIColor + if presentationData.theme.overallDarkAppearance { + let backgroundColor = presentationData.theme.contextMenu.backgroundColor.blitOver(presentationData.theme.list.plainBackgroundColor, alpha: 1.0) + shimmeringForegroundColor = presentationData.theme.contextMenu.primaryColor.blitOver(backgroundColor, alpha: 0.1) + } else { + shimmeringForegroundColor = presentationData.theme.contextMenu.primaryColor.withMultipliedAlpha(0.07) + } + + self.placeholderNode.backgroundColor = shimmeringForegroundColor + + self.isUserInteractionEnabled = isUserInteractionEnabled + } + + @objc func onTapGesture(_ recognizer: UITapGestureRecognizer) { + if case .ended = recognizer.state { + self.requestDismiss({ + self.action?() + }) + } + } + + func animateTransitionInside(other: InnerTextSelectionTipContainerNode) { + let nodes: [ASDisplayNode] = [ + self.textNode.textNode, + self.iconNode, + self.placeholderNode + ] + + for node in nodes { + if let background = other.background { + background.background.contentView.addSubview(node.view) + } else { + other.view.addSubview(node.view) + } + node.layer.animateAlpha(from: node.alpha, to: 0.0, duration: 0.2, removeOnCompletion: false, completion: { [weak node] _ in + node?.removeFromSupernode() + }) + } + } + + func animateContentIn() { + let nodes: [ASDisplayNode] = [ + self.textNode.textNode, + self.iconNode + ] + + for node in nodes { + node.layer.animateAlpha(from: 0.0, to: node.alpha, duration: 0.25) + } + } + + func updateLayout(widthClass: ContainerViewLayoutSizeClass, presentation: ContextControllerActionsStackNode.Presentation, width: CGFloat, transition: ContainedViewLayoutTransition) -> CGSize { + let topInset: CGFloat = self.background != nil ? 16.0 : 9.0 + let bottomInset: CGFloat = self.background != nil ? 16.0 : 9.0 + let horizontalInset: CGFloat = 18.0 + let standardIconWidth: CGFloat = 32.0 + let iconSideInset: CGFloat = 20.0 + + let textFont = Font.regular(floor(presentationData.listsFontSize.baseDisplaySize * 13.0 / 17.0)) + let boldTextFont = Font.bold(floor(presentationData.listsFontSize.baseDisplaySize * 13.0 / 17.0)) + let textColor = self.presentationData.theme.contextMenu.primaryColor + let linkColor = self.presentationData.theme.overallDarkAppearance ? UIColor(rgb: 0x64d2ff) : self.presentationData.theme.contextMenu.badgeFillColor + + let iconSize = self.iconNode.image?.size ?? CGSize(width: 16.0, height: 16.0) + + let text = self.text.replacingOccurrences(of: "#", with: "# ") + let attributedText = NSMutableAttributedString(attributedString: parseMarkdownIntoAttributedString(text, attributes: MarkdownAttributes(body: MarkdownAttributeSet(font: textFont, textColor: textColor), bold: MarkdownAttributeSet(font: boldTextFont, textColor: textColor), link: MarkdownAttributeSet(font: boldTextFont, textColor: linkColor), linkAttribute: { _ in + return nil + }))) + if let file = self.file { + let range = (attributedText.string as NSString).range(of: "#") + if range.location != NSNotFound { + attributedText.addAttribute(ChatTextInputAttributes.customEmoji, value: ChatTextInputTextCustomEmojiAttribute(interactivelySelectedFromPackId: nil, fileId: file.fileId.id, file: file), range: range) + } + } + + let shimmeringForegroundColor: UIColor + if presentationData.theme.overallDarkAppearance { + let backgroundColor = presentationData.theme.contextMenu.backgroundColor.blitOver(presentationData.theme.list.plainBackgroundColor, alpha: 1.0) + shimmeringForegroundColor = presentationData.theme.contextMenu.primaryColor.blitOver(backgroundColor, alpha: 0.1) + } else { + shimmeringForegroundColor = presentationData.theme.contextMenu.primaryColor.withMultipliedAlpha(0.07) + } + + let textRightInset: CGFloat + if let _ = self.iconNode.image { + textRightInset = iconSize.width - 2.0 + } else { + textRightInset = 0.0 + } + + let makeTextLayout = TextNodeWithEntities.asyncLayout(self.textNode) + let (textLayout, textApply) = makeTextLayout(TextNodeLayoutArguments(attributedString: attributedText, backgroundColor: nil, minimumNumberOfLines: 0, maximumNumberOfLines: 0, truncationType: .end, constrainedSize: CGSize(width: width - horizontalInset * 2.0 - textRightInset, height: .greatestFiniteMagnitude), alignment: .left, lineSpacing: 0.12, cutout: nil, insets: UIEdgeInsets(), lineColor: nil, textShadowColor: nil, textStroke: nil)) + let _ = textApply(self.arguments?.withUpdatedPlaceholderColor(shimmeringForegroundColor)) + + let textFrame = CGRect(origin: CGPoint(x: horizontalInset, y: topInset), size: textLayout.size) + transition.updateFrame(node: self.textNode.textNode, frame: textFrame) + if textFrame.size.height.isZero { + self.textNode.textNode.alpha = 0.0 + } else if self.textNode.textNode.alpha.isZero { + self.textNode.textNode.alpha = 1.0 + self.textNode.textNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2) + self.placeholderNode.layer.animateAlpha(from: self.placeholderNode.alpha, to: 1.0, duration: 0.2) + } + self.textNode.visibilityRect = CGRect.infinite + + var contentHeight = textLayout.size.height + if contentHeight.isZero { + contentHeight = 32.0 + } + + let size = CGSize(width: width, height: contentHeight + topInset + bottomInset) + + let lineHeight: CGFloat = 8.0 + transition.updateFrame(node: self.placeholderNode, frame: CGRect(origin: CGPoint(x: horizontalInset, y: floorToScreenPixels((size.height - lineHeight) / 2.0)), size: CGSize(width: width - horizontalInset * 2.0, height: lineHeight))) + transition.updateAlpha(node: self.placeholderNode, alpha: textFrame.height.isZero ? 1.0 : 0.0) + + let iconFrame = CGRect(origin: CGPoint(x: iconSideInset + floor((standardIconWidth - iconSize.width) / 2.0), y: floor((size.height - iconSize.height) / 2.0)), size: iconSize) + transition.updateFrame(node: self.iconNode, frame: iconFrame) + + if let textSelectionNode = self.textSelectionNode { + transition.updateFrame(node: textSelectionNode, frame: textFrame) + textSelectionNode.highlightAreaNode.frame = textFrame + } + + return size + } + + func setActualSize(size: CGSize, transition: ContainedViewLayoutTransition) { + let transition = ComponentTransition(transition) + + if let background = self.background { + background.container.update(size: size, isDark: self.presentationData.theme.overallDarkAppearance, transition: transition) + transition.setFrame(view: background.container, frame: CGRect(origin: CGPoint(), size: size)) + + background.background.update(size: size, cornerRadius: min(30.0, size.height * 0.5), isDark: self.presentationData.theme.overallDarkAppearance, tintColor: .init(kind: .panel), transition: transition) + transition.setFrame(view: background.background, frame: CGRect(origin: CGPoint(), size: size)) + } + } + + func updateTheme(presentationData: PresentationData) { + } + + func animateIn() { + if let textSelectionNode = self.textSelectionNode, let targetSelectionIndex = self.targetSelectionIndex { + textSelectionNode.pretendInitiateSelection() + DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: { [weak self] in + guard let strongSelf = self else { + return + } + strongSelf.textSelectionNode?.pretendExtendSelection(to: targetSelectionIndex) + }) + } + } + + func updateHighlight(animated: Bool) { + } + + private var isButtonHighlighted = false + private var isHighlighted = false + func setHighlighted(_ highlighted: Bool) { + guard self.isHighlighted != highlighted else { + return + } + self.isHighlighted = highlighted + + if highlighted { + if self.hapticFeedback == nil { + self.hapticFeedback = HapticFeedback() + } + self.hapticFeedback?.tap() + } + + self.updateHighlight(animated: false) + } + + func highlightGestureMoved(location: CGPoint) { + if self.bounds.contains(location) && self.isUserInteractionEnabled { + self.setHighlighted(true) + } else { + self.setHighlighted(false) + } + } + + func highlightGestureFinished(performAction: Bool) { + if self.isHighlighted { + self.setHighlighted(false) + if performAction { + self.requestDismiss({ + self.action?() + }) + } + } + } +} + +final class ContextActionsContainerNode: ASDisplayNode { + private let presentationData: PresentationData + private let getController: () -> ContextControllerProtocol? + private let blurBackground: Bool + private let shadowNode: ASImageNode + private let additionalShadowNode: ASImageNode? + private let additionalActionsNode: InnerActionsContainerNode? + private let actionsNode: InnerActionsContainerNode + private let scrollNode: ASScrollNode + + private var tip: ContextController.Tip? + private var textSelectionTipNode: InnerTextSelectionTipContainerNode? + private var textSelectionTipNodeDisposable: Disposable? + + var panSelectionGestureEnabled: Bool = true { + didSet { + if self.panSelectionGestureEnabled != oldValue { + self.actionsNode.panSelectionGestureEnabled = self.panSelectionGestureEnabled + } + } + } + + var hasAdditionalActions: Bool { + return self.additionalActionsNode != nil + } + + init(presentationData: PresentationData, items: ContextController.Items, getController: @escaping () -> ContextControllerProtocol?, actionSelected: @escaping (ContextMenuActionResult) -> Void, requestLayout: @escaping () -> Void, feedbackTap: @escaping () -> Void, blurBackground: Bool) { + self.presentationData = presentationData + self.getController = getController + self.blurBackground = blurBackground + self.shadowNode = ASImageNode() + self.shadowNode.displaysAsynchronously = false + self.shadowNode.displayWithoutProcessing = true + self.shadowNode.image = UIImage(bundleImageName: "Components/Context Menu/Shadow")?.stretchableImage(withLeftCapWidth: 60, topCapHeight: 60) + self.shadowNode.contentMode = .scaleToFill + self.shadowNode.isHidden = true + + var items = items + if case var .list(itemList) = items.content, let firstItem = itemList.first, case let .custom(_, additional) = firstItem, additional { + let additionalShadowNode = ASImageNode() + additionalShadowNode.displaysAsynchronously = false + additionalShadowNode.displayWithoutProcessing = true + additionalShadowNode.image = self.shadowNode.image + additionalShadowNode.contentMode = .scaleToFill + additionalShadowNode.isHidden = true + self.additionalShadowNode = additionalShadowNode + + self.additionalActionsNode = InnerActionsContainerNode(presentationData: presentationData, items: [firstItem], getController: getController, actionSelected: actionSelected, requestLayout: requestLayout, feedbackTap: feedbackTap, blurBackground: blurBackground) + itemList.removeFirst() + items.content = .list(itemList) + } else { + self.additionalShadowNode = nil + self.additionalActionsNode = nil + } + + var itemList: [ContextMenuItem] = [] + if case let .list(list) = items.content { + itemList = list + } + + self.actionsNode = InnerActionsContainerNode(presentationData: presentationData, items: itemList, getController: getController, actionSelected: actionSelected, requestLayout: requestLayout, feedbackTap: feedbackTap, blurBackground: blurBackground) + + self.tip = items.tip + + self.scrollNode = ASScrollNode() + self.scrollNode.canCancelAllTouchesInViews = true + self.scrollNode.view.delaysContentTouches = false + self.scrollNode.view.showsVerticalScrollIndicator = false + if #available(iOS 11.0, *) { + self.scrollNode.view.contentInsetAdjustmentBehavior = .never + } + + super.init() + + self.additionalActionsNode.flatMap(self.scrollNode.addSubnode) + self.scrollNode.addSubnode(self.actionsNode) + self.addSubnode(self.scrollNode) + + if let tipSignal = items.tipSignal { + self.textSelectionTipNodeDisposable = (tipSignal + |> deliverOnMainQueue).start(next: { [weak self] tip in + guard let strongSelf = self else { + return + } + + strongSelf.tip = tip + requestLayout() + }).strict() + } + } + + deinit { + self.textSelectionTipNodeDisposable?.dispose() + } + + func updateLayout(widthClass: ContainerViewLayoutSizeClass, presentation: ContextControllerActionsStackNode.Presentation, constrainedWidth: CGFloat, constrainedHeight: CGFloat, transition: ContainedViewLayoutTransition) -> CGSize { + var widthClass = widthClass + if !self.blurBackground { + widthClass = .regular + } + + var contentSize = CGSize() + let actionsSize = self.actionsNode.updateLayout(widthClass: widthClass, constrainedWidth: constrainedWidth, constrainedHeight: constrainedHeight, minimalWidth: nil, transition: transition) + + if let additionalActionsNode = self.additionalActionsNode, let additionalShadowNode = self.additionalShadowNode { + let additionalActionsSize = additionalActionsNode.updateLayout(widthClass: widthClass, constrainedWidth: actionsSize.width, constrainedHeight: constrainedHeight, minimalWidth: actionsSize.width, transition: transition) + contentSize = additionalActionsSize + + let bounds = CGRect(origin: CGPoint(), size: additionalActionsSize) + transition.updateFrame(node: additionalShadowNode, frame: bounds.insetBy(dx: -30.0, dy: -30.0)) + additionalShadowNode.isHidden = widthClass == .compact + + transition.updateFrame(node: additionalActionsNode, frame: CGRect(origin: CGPoint(), size: additionalActionsSize)) + contentSize.height += 8.0 + } + + let bounds = CGRect(origin: CGPoint(x: 0.0, y: contentSize.height), size: actionsSize) + transition.updateFrame(node: self.shadowNode, frame: bounds.insetBy(dx: -30.0, dy: -30.0)) + self.shadowNode.isHidden = widthClass == .compact + + contentSize.width = max(contentSize.width, actionsSize.width) + contentSize.height += actionsSize.height + + transition.updateFrame(node: self.actionsNode, frame: bounds) + + if let tip = self.tip { + if let textSelectionTipNode = self.textSelectionTipNode, textSelectionTipNode.tip == tip { + } else { + if let textSelectionTipNode = self.textSelectionTipNode { + self.textSelectionTipNode = nil + textSelectionTipNode.removeFromSupernode() + } + + let textSelectionTipNode = InnerTextSelectionTipContainerNode(presentationData: self.presentationData, tip: tip, isInline: false) + let getController = self.getController + textSelectionTipNode.requestDismiss = { completion in + getController()?.dismiss(completion: completion) + } + self.textSelectionTipNode = textSelectionTipNode + self.scrollNode.addSubnode(textSelectionTipNode) + } + } else { + if let textSelectionTipNode = self.textSelectionTipNode { + self.textSelectionTipNode = nil + textSelectionTipNode.removeFromSupernode() + } + } + + if let textSelectionTipNode = self.textSelectionTipNode { + contentSize.height += 8.0 + let textSelectionTipSize = textSelectionTipNode.updateLayout(widthClass: widthClass, presentation: presentation, width: actionsSize.width, transition: transition) + transition.updateFrame(node: textSelectionTipNode, frame: CGRect(origin: CGPoint(x: 0.0, y: contentSize.height), size: textSelectionTipSize)) + textSelectionTipNode.setActualSize(size: textSelectionTipSize, transition: transition) + contentSize.height += textSelectionTipSize.height + } + + return contentSize + } + + func updateSize(containerSize: CGSize, contentSize: CGSize) { + self.scrollNode.view.contentSize = contentSize + self.scrollNode.frame = CGRect(origin: CGPoint(), size: containerSize) + } + + func actionNode(at point: CGPoint) -> ContextActionNodeProtocol? { + return self.actionsNode.actionNode(at: self.view.convert(point, to: self.actionsNode.view)) + } + + func updateTheme(presentationData: PresentationData) { + self.actionsNode.updateTheme(presentationData: presentationData) + self.textSelectionTipNode?.updateTheme(presentationData: presentationData) + } + + func animateIn() { + self.textSelectionTipNode?.animateIn() + } + + func animateOut(offset: CGFloat, transition: ContainedViewLayoutTransition) { + guard let additionalActionsNode = self.additionalActionsNode, let additionalShadowNode = self.additionalShadowNode else { + return + } + + transition.animatePosition(node: additionalActionsNode, to: CGPoint(x: 0.0, y: offset / 2.0), additive: true) + transition.animatePosition(node: additionalShadowNode, to: CGPoint(x: 0.0, y: offset / 2.0), additive: true) + additionalActionsNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.15, removeOnCompletion: false) + additionalShadowNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.15, removeOnCompletion: false) + additionalActionsNode.layer.animateScale(from: 1.0, to: 0.75, duration: 0.15, removeOnCompletion: false) + additionalShadowNode.layer.animateScale(from: 1.0, to: 0.75, duration: 0.15, removeOnCompletion: false) + } +} diff --git a/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextControllerActionsStackNode.swift b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextControllerActionsStackNode.swift new file mode 100644 index 00000000..482829fc --- /dev/null +++ b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextControllerActionsStackNode.swift @@ -0,0 +1,2206 @@ +import Foundation +import UIKit +import AsyncDisplayKit +import Display +import TelegramPresentationData +import TextSelectionNode +import TelegramCore +import SwiftSignalKit +import AccountContext +import ReactionSelectionNode +import Markdown +import EntityKeyboard +import AnimationCache +import MultiAnimationRenderer +import AnimationUI +import ComponentFlow +import ComponentDisplayAdapters +import GlassBackgroundComponent +import LottieComponent +import TextNodeWithEntities +import ContextUI + +public protocol ContextControllerActionsListItemNode: ASDisplayNode { + func update(presentationData: PresentationData, constrainedSize: CGSize) -> (minSize: CGSize, apply: (_ size: CGSize, _ transition: ContainedViewLayoutTransition) -> Void) + + func canBeHighlighted() -> Bool + func updateIsHighlighted(isHighlighted: Bool) + func performAction() + + var needsPadding: Bool { get } +} + +public final class ContextControllerActionsListActionItemNode: HighlightTrackingButtonNode, ContextControllerActionsListItemNode { + private let context: AccountContext? + private let getController: () -> ContextControllerProtocol? + private let requestDismiss: (ContextMenuActionResult) -> Void + private let requestUpdateAction: (AnyHashable, ContextMenuActionItem) -> Void + private var item: ContextMenuActionItem + + private let titleLabelNode: ImmediateTextNodeWithEntities + private let subtitleNode: ImmediateTextNode + private let iconNode: ASImageNode + private let additionalIconNode: ASImageNode + private var badgeIconNode: ASImageNode? + private var animationNode: AnimationNode? + + private var currentAnimatedIconContent: ContextMenuActionItem.IconAnimation? + private var animatedIcon: ComponentView? + + private var currentBadge: (badge: ContextMenuActionBadge, image: UIImage)? + + private var iconDisposable: Disposable? + + public let needsPadding: Bool = true + + public init( + context: AccountContext?, + getController: @escaping () -> ContextControllerProtocol?, + requestDismiss: @escaping (ContextMenuActionResult) -> Void, + requestUpdateAction: @escaping (AnyHashable, ContextMenuActionItem) -> Void, + item: ContextMenuActionItem + ) { + self.context = context + self.getController = getController + self.requestDismiss = requestDismiss + self.requestUpdateAction = requestUpdateAction + self.item = item + + self.titleLabelNode = ImmediateTextNodeWithEntities() + self.titleLabelNode.isAccessibilityElement = false + self.titleLabelNode.displaysAsynchronously = false + + self.subtitleNode = ImmediateTextNode() + self.subtitleNode.isAccessibilityElement = false + self.subtitleNode.displaysAsynchronously = false + self.subtitleNode.isUserInteractionEnabled = false + + self.iconNode = ASImageNode() + self.iconNode.isAccessibilityElement = false + self.iconNode.isUserInteractionEnabled = false + + self.additionalIconNode = ASImageNode() + self.additionalIconNode.isAccessibilityElement = false + self.additionalIconNode.isUserInteractionEnabled = false + + super.init() + + self.isAccessibilityElement = true + self.accessibilityLabel = item.text + self.accessibilityTraits = [.button] + + self.addSubnode(self.titleLabelNode) + self.addSubnode(self.subtitleNode) + self.addSubnode(self.iconNode) + self.addSubnode(self.additionalIconNode) + + self.isEnabled = self.canBeHighlighted() + + self.highligthedChanged = { [weak self] highlighted in + guard let strongSelf = self else { + return + } + if highlighted { + strongSelf.startTimer() + } else { + strongSelf.invalidateTimer() + } + } + + self.addTarget(self, action: #selector(self.pressed), forControlEvents: .touchUpInside) + } + + deinit { + self.iconDisposable?.dispose() + } + + private var timer: SwiftSignalKit.Timer? + private func startTimer() { + self.invalidateTimer() + + self.timer = SwiftSignalKit.Timer(timeout: 1.0, repeat: false, completion: { [weak self] in + guard let self else { + return + } + self.invalidateTimer() + self.longPressed() + }, queue: Queue.mainQueue()) + self.timer?.start() + } + + private func invalidateTimer() { + self.timer?.invalidate() + self.timer = nil + } + + public override func didLoad() { + super.didLoad() + + self.view.isExclusiveTouch = true + } + + @objc private func pressed() { + self.invalidateTimer() + + self.item.action?(ContextMenuActionItem.Action( + controller: self.getController(), + dismissWithResult: { [weak self] result in + guard let strongSelf = self else { + return + } + strongSelf.requestDismiss(result) + }, + updateAction: { [weak self] id, updatedAction in + guard let strongSelf = self else { + return + } + strongSelf.requestUpdateAction(id, updatedAction) + } + )) + } + + private func longPressed() { + self.touchesCancelled(nil, with: nil) + + self.item.longPressAction?(ContextMenuActionItem.Action( + controller: self.getController(), + dismissWithResult: { [weak self] result in + guard let strongSelf = self else { + return + } + strongSelf.requestDismiss(result) + }, + updateAction: { [weak self] id, updatedAction in + guard let strongSelf = self else { + return + } + strongSelf.requestUpdateAction(id, updatedAction) + } + )) + } + + public func canBeHighlighted() -> Bool { + return self.item.action != nil + } + + public func updateIsHighlighted(isHighlighted: Bool) { + } + + public func performAction() { + self.pressed() + } + + public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + if self.titleLabelNode.tapAttributeAction != nil { + if let result = self.titleLabelNode.hitTest(self.view.convert(point, to: self.titleLabelNode.view), with: event) { + return result + } + } + + return super.hitTest(point, with: event) + } + + public func setItem(item: ContextMenuActionItem) { + self.item = item + self.accessibilityLabel = item.text + } + + public func update(presentationData: PresentationData, constrainedSize: CGSize) -> (minSize: CGSize, apply: (_ size: CGSize, _ transition: ContainedViewLayoutTransition) -> Void) { + let sideInset: CGFloat = 18.0 + let verticalInset: CGFloat = 11.0 + let titleSubtitleSpacing: CGFloat = 1.0 + let iconSideInset: CGFloat = 20.0 + let standardIconWidth: CGFloat = 32.0 + let iconSpacing: CGFloat = 8.0 + + var forcedHeight: CGFloat? + var titleVerticalOffset: CGFloat? + let titleFont: UIFont + let titleBoldFont: UIFont + switch self.item.textFont { + case let .custom(font, height, verticalOffset): + titleFont = font + titleBoldFont = font + forcedHeight = height + titleVerticalOffset = verticalOffset + case .small: + let smallTextFont = Font.regular(floor(presentationData.listsFontSize.baseDisplaySize * 14.0 / 17.0)) + titleFont = smallTextFont + titleBoldFont = Font.semibold(floor(presentationData.listsFontSize.baseDisplaySize * 14.0 / 17.0)) + case .regular: + titleFont = Font.regular(presentationData.listsFontSize.baseDisplaySize) + titleBoldFont = Font.semibold(presentationData.listsFontSize.baseDisplaySize) + } + + let subtitleFont = Font.regular(presentationData.listsFontSize.baseDisplaySize * 14.0 / 17.0) + let subtitleColor = presentationData.theme.contextMenu.secondaryColor + + if let context = self.context { + self.titleLabelNode.arguments = TextNodeWithEntities.Arguments( + context: context, + cache: context.animationCache, + renderer: context.animationRenderer, + placeholderColor: presentationData.theme.contextMenu.primaryColor.withMultipliedAlpha(0.1), + attemptSynchronous: true + ) + } + self.titleLabelNode.visibility = self.item.enableEntityAnimations + + var subtitle: NSAttributedString? + switch self.item.textLayout { + case .singleLine: + self.titleLabelNode.maximumNumberOfLines = 1 + case .twoLinesMax: + self.titleLabelNode.maximumNumberOfLines = 2 + case let .secondLineWithValue(subtitleValue): + self.titleLabelNode.maximumNumberOfLines = 1 + subtitle = NSAttributedString( + string: subtitleValue, + font: subtitleFont, + textColor: subtitleColor + ) + case let .secondLineWithAttributedValue(subtitleValue): + self.titleLabelNode.maximumNumberOfLines = 1 + let mutableString = subtitleValue.mutableCopy() as! NSMutableAttributedString + mutableString.addAttribute(.foregroundColor, value: subtitleColor, range: NSRange(location: 0, length: mutableString.length)) + mutableString.addAttribute(.font, value: subtitleFont, range: NSRange(location: 0, length: mutableString.length)) + subtitle = mutableString + case .multiline: + self.titleLabelNode.maximumNumberOfLines = 0 + self.titleLabelNode.lineSpacing = 0.1 + } + + let titleColor: UIColor + let linkColor = presentationData.theme.list.itemAccentColor + switch self.item.textColor { + case .primary: + titleColor = presentationData.theme.contextMenu.primaryColor + case .destructive: + titleColor = presentationData.theme.contextMenu.destructiveColor + case .disabled: + titleColor = presentationData.theme.contextMenu.primaryColor.withMultipliedAlpha(0.4) + } + + if self.item.parseMarkdown || !self.item.entities.isEmpty { + let attributedText: NSAttributedString + if !self.item.entities.isEmpty { + let inputStateText = ChatTextInputStateText(text: self.item.text, attributes: self.item.entities.compactMap { entity -> ChatTextInputStateTextAttribute? in + if case let .CustomEmoji(_, fileId) = entity.type { + return ChatTextInputStateTextAttribute(type: .customEmoji(stickerPack: nil, fileId: fileId, enableAnimation: true), range: entity.range) + } else if case .Bold = entity.type { + return ChatTextInputStateTextAttribute(type: .bold, range: entity.range) + } else if case .Italic = entity.type { + return ChatTextInputStateTextAttribute(type: .italic, range: entity.range) + } else if case .Url = entity.type { + return ChatTextInputStateTextAttribute(type: .textUrl(""), range: entity.range) + } + return nil + }) + let result = NSMutableAttributedString(attributedString: inputStateText.attributedText(files: self.item.entityFiles)) + result.addAttributes([ + .font: titleFont, + .foregroundColor: titleColor + ], range: NSRange(location: 0, length: result.length)) + for attribute in inputStateText.attributes { + if case .bold = attribute.type { + result.addAttribute(NSAttributedString.Key.font, value: titleBoldFont, range: NSRange(location: attribute.range.lowerBound, length: attribute.range.count)) + } else if case .italic = attribute.type { + result.addAttribute(NSAttributedString.Key.font, value: Font.semibold(15.0), range: NSRange(location: attribute.range.lowerBound, length: attribute.range.count)) + } else if case .textUrl = attribute.type { + result.addAttribute(NSAttributedString.Key.foregroundColor, value: linkColor, range: NSRange(location: attribute.range.lowerBound, length: attribute.range.count)) + result.addAttribute(NSAttributedString.Key.font, value: titleBoldFont, range: NSRange(location: attribute.range.lowerBound, length: attribute.range.count)) + } + } + attributedText = result + } else { + attributedText = parseMarkdownIntoAttributedString( + self.item.text, + attributes: MarkdownAttributes( + body: MarkdownAttributeSet(font: titleFont, textColor: titleColor), + bold: MarkdownAttributeSet(font: titleBoldFont, textColor: titleColor), + link: MarkdownAttributeSet(font: titleBoldFont, textColor: presentationData.theme.list.itemAccentColor), + linkAttribute: { value in return ("URL", value) } + ) + ) + } + self.titleLabelNode.attributedText = attributedText + self.titleLabelNode.linkHighlightColor = presentationData.theme.list.itemAccentColor.withMultipliedAlpha(0.5) + self.titleLabelNode.highlightAttributeAction = { attributes in + if let _ = attributes[NSAttributedString.Key(rawValue: "URL")] { + return NSAttributedString.Key(rawValue: "URL") + } else { + return nil + } + } + self.titleLabelNode.tapAttributeAction = { [weak item] attributes, _ in + if let _ = attributes[NSAttributedString.Key(rawValue: "URL")] { + item?.textLinkAction() + } + } + } else { + self.titleLabelNode.attributedText = NSAttributedString( + string: self.item.text, + font: titleFont, + textColor: titleColor) + } + + self.titleLabelNode.isUserInteractionEnabled = self.titleLabelNode.tapAttributeAction != nil && self.item.action == nil + + self.subtitleNode.attributedText = subtitle + + var iconSize: CGSize? + if let iconSource = self.item.iconSource { + iconSize = iconSource.size + self.iconNode.cornerRadius = iconSource.cornerRadius + self.iconNode.contentMode = iconSource.contentMode + self.iconNode.clipsToBounds = true + if self.iconDisposable == nil { + self.iconDisposable = (iconSource.signal |> deliverOnMainQueue).start(next: { [weak self] image in + guard let strongSelf = self else { + return + } + strongSelf.iconNode.image = image + }).strict() + } + } else if let image = self.iconNode.image { + iconSize = image.size + } else if let animationName = self.item.animationName { + if self.animationNode == nil { + let animationNode = AnimationNode(animation: animationName, colors: ["__allcolors__": titleColor], scale: 1.0) + animationNode.loop(count: 3) + self.addSubnode(animationNode) + self.animationNode = animationNode + } + iconSize = CGSize(width: 24.0, height: 24.0) + } else { + let iconImage = self.item.icon(presentationData.theme) + self.iconNode.image = iconImage + iconSize = iconImage?.size + } + + if let iconAnimation = self.item.iconAnimation { + let animatedIcon: ComponentView + if let current = self.animatedIcon { + animatedIcon = current + } else { + animatedIcon = ComponentView() + self.animatedIcon = animatedIcon + } + + let animatedIconSize = CGSize(width: 24.0, height: 24.0) + let _ = animatedIcon.update( + transition: .immediate, + component: AnyComponent(LottieComponent( + content: LottieComponent.AppBundleContent(name: iconAnimation.name), + color: titleColor, + startingPosition: iconAnimation.loop ? .begin : .end, + loop: iconAnimation.loop + )), + environment: {}, + containerSize: animatedIconSize + ) + + iconSize = animatedIconSize + } else if let animatedIcon = self.animatedIcon { + self.animatedIcon = nil + animatedIcon.view?.removeFromSuperview() + } + + let additionalIcon = self.item.additionalLeftIcon?(presentationData.theme) + var additionalIconSize: CGSize? + self.additionalIconNode.image = additionalIcon + + if let additionalIcon { + additionalIconSize = additionalIcon.size + } + + let badgeSize: CGSize? + if let badge = self.item.badge { + var badgeImage: UIImage? + if let currentBadge = self.currentBadge, currentBadge.badge == badge { + badgeImage = currentBadge.image + } else { + switch badge.style { + case .badge: + let badgeTextColor: UIColor = presentationData.theme.list.itemCheckColors.foregroundColor + let badgeString = NSAttributedString(string: badge.value, font: Font.regular(13.0), textColor: badgeTextColor) + let badgeTextBounds = badgeString.boundingRect(with: CGSize(width: 100.0, height: 100.0), options: [.usesLineFragmentOrigin], context: nil) + + let badgeSideInset: CGFloat = 5.0 + let badgeVerticalInset: CGFloat = 1.0 + var badgeBackgroundSize = CGSize(width: badgeSideInset * 2.0 + ceil(badgeTextBounds.width), height: badgeVerticalInset * 2.0 + ceil(badgeTextBounds.height)) + badgeBackgroundSize.width = max(badgeBackgroundSize.width, badgeBackgroundSize.height) + badgeImage = generateImage(badgeBackgroundSize, rotatedContext: { size, context in + context.clear(CGRect(origin: CGPoint(), size: size)) + context.setFillColor(presentationData.theme.list.itemCheckColors.fillColor.cgColor) + context.addPath(UIBezierPath(roundedRect: CGRect(origin: CGPoint(), size: size), cornerRadius: size.height * 0.5).cgPath) + context.fillPath() + + UIGraphicsPushContext(context) + + badgeString.draw(at: CGPoint(x: badgeTextBounds.minX + floor((badgeBackgroundSize.width - badgeTextBounds.width) * 0.5), y: badgeTextBounds.minY + badgeVerticalInset)) + + UIGraphicsPopContext() + }) + case .label: + let badgeTextColor: UIColor = presentationData.theme.list.itemCheckColors.foregroundColor + let badgeString = NSAttributedString(string: badge.value, font: Font.semibold(11.0), textColor: badgeTextColor) + let badgeTextBounds = badgeString.boundingRect(with: CGSize(width: 100.0, height: 100.0), options: [.usesLineFragmentOrigin], context: nil) + + let badgeSideInset: CGFloat = 3.0 + let badgeVerticalInset: CGFloat = 1.0 + let badgeBackgroundSize = CGSize(width: badgeSideInset * 2.0 + ceil(badgeTextBounds.width), height: badgeVerticalInset * 2.0 + ceil(badgeTextBounds.height)) + badgeImage = generateImage(badgeBackgroundSize, rotatedContext: { size, context in + context.clear(CGRect(origin: CGPoint(), size: size)) + context.setFillColor(presentationData.theme.list.itemCheckColors.fillColor.cgColor) + context.addPath(UIBezierPath(roundedRect: CGRect(origin: CGPoint(), size: size), cornerRadius: 5.0).cgPath) + context.fillPath() + + UIGraphicsPushContext(context) + + badgeString.draw(at: CGPoint(x: badgeTextBounds.minX + badgeSideInset + UIScreenPixel, y: badgeTextBounds.minY + badgeVerticalInset + UIScreenPixel)) + + UIGraphicsPopContext() + }) + } + } + + let badgeIconNode: ASImageNode + if let current = self.badgeIconNode { + badgeIconNode = current + } else { + badgeIconNode = ASImageNode() + self.badgeIconNode = badgeIconNode + self.addSubnode(badgeIconNode) + } + badgeIconNode.image = badgeImage + + badgeSize = badgeImage?.size + } else { + if let badgeIconNode = self.badgeIconNode { + self.badgeIconNode = nil + badgeIconNode.removeFromSupernode() + } + badgeSize = nil + } + + var maxTextWidth: CGFloat = constrainedSize.width + maxTextWidth -= sideInset + + if let iconSize = iconSize { + maxTextWidth -= max(standardIconWidth, iconSize.width) + maxTextWidth -= iconSpacing + } else { + maxTextWidth -= sideInset + } + + if let additionalIconSize { + maxTextWidth -= additionalIconSize.width + } + + if let badgeSize = badgeSize { + maxTextWidth -= badgeSize.width + maxTextWidth -= 8.0 + } + + maxTextWidth = max(1.0, maxTextWidth) + + let titleSize = self.titleLabelNode.updateLayout(CGSize(width: maxTextWidth, height: 1000.0)) + let subtitleSize = self.subtitleNode.updateLayout(CGSize(width: maxTextWidth, height: 1000.0)) + + var minSize = CGSize() + minSize.width += sideInset + minSize.width += max(titleSize.width, subtitleSize.width) + if let iconSize = iconSize { + minSize.width += max(standardIconWidth, iconSize.width) + minSize.width += iconSideInset + minSize.width += iconSpacing + } else { + minSize.width += sideInset + } + if let additionalIconSize { + minSize.width += additionalIconSize.width + minSize.width += iconSideInset + minSize.width += iconSpacing + } + if let forcedHeight { + minSize.height = forcedHeight + } else { + minSize.height += verticalInset * 2.0 + minSize.height += titleSize.height + if subtitle != nil { + minSize.height += titleSubtitleSpacing + minSize.height += subtitleSize.height + } + } + + return (minSize: minSize, apply: { size, transition in + var titleFrame = CGRect(origin: CGPoint(x: sideInset, y: verticalInset), size: titleSize) + if let customTextInsets = self.item.customTextInsets { + titleFrame.origin.x = customTextInsets.left + } + if let titleVerticalOffset { + titleFrame = titleFrame.offsetBy(dx: 0.0, dy: titleVerticalOffset) + } + var subtitleFrame = CGRect(origin: CGPoint(x: titleFrame.minX, y: titleFrame.maxY + titleSubtitleSpacing), size: subtitleSize) + if iconSize != nil { + titleFrame.origin.x = iconSideInset + 40.0 + subtitleFrame.origin.x = titleFrame.minX + } + + transition.updateFrameAdditive(node: self.titleLabelNode, frame: titleFrame) + transition.updateFrameAdditive(node: self.subtitleNode, frame: subtitleFrame) + + if let badgeIconNode = self.badgeIconNode, let iconSize = badgeIconNode.image?.size { + transition.updateFrame(node: badgeIconNode, frame: CGRect(origin: CGPoint(x: titleFrame.maxX + 8.0, y: titleFrame.minY + floor((titleFrame.height - iconSize.height) * 0.5)), size: iconSize)) + } + + if let iconSize { + let iconFrame = CGRect( + origin: CGPoint( + x: iconSideInset + floor((standardIconWidth - iconSize.width) * 0.5), + y: floor((size.height - iconSize.height) / 2.0) + ), + size: iconSize + ) + transition.updateFrame(node: self.iconNode, frame: iconFrame, beginWithCurrentState: true) + if let animationNode = self.animationNode { + transition.updateFrame(node: animationNode, frame: iconFrame, beginWithCurrentState: true) + } + if let animatedIconView = self.animatedIcon?.view { + if animatedIconView.superview == nil { + self.view.addSubview(animatedIconView) + animatedIconView.frame = iconFrame + } else { + transition.updateFrame(view: animatedIconView, frame: iconFrame, beginWithCurrentState: true) + if let currentAnimatedIconContent = self.currentAnimatedIconContent, currentAnimatedIconContent != self.item.iconAnimation { + if let animatedIconView = animatedIconView as? LottieComponent.View { + animatedIconView.playOnce() + } + } + } + + self.currentAnimatedIconContent = self.item.iconAnimation + } + } + + if let additionalIconSize { + let iconFrame = CGRect( + origin: CGPoint( + x: size.width - iconSideInset - additionalIconSize.width, + y: floor((size.height - additionalIconSize.height) / 2.0) + ), + size: additionalIconSize + ) + transition.updateFrame(node: self.additionalIconNode, frame: iconFrame, beginWithCurrentState: true) + } + }) + } +} + +private final class ContextControllerActionsListSeparatorItemNode: ASDisplayNode, ContextControllerActionsListItemNode { + private let separatorView: UIImageView + + let needsPadding: Bool = false + + func canBeHighlighted() -> Bool { + return false + } + + func updateIsHighlighted(isHighlighted: Bool) { + } + + func performAction() { + } + + override init() { + self.separatorView = UIImageView() + self.separatorView.image = generateImage(CGSize(width: 1.0, height: 1.0), rotatedContext: { size, context in + context.clear(CGRect(origin: CGPoint(), size: size)) + context.setFillColor(UIColor.white.cgColor) + context.fill(CGRect(origin: CGPoint(x: 0.0, y: floorToScreenPixels((size.height - 1.0) * 0.5)), size: CGSize(width: size.width, height: 1.0))) + })?.withRenderingMode(.alwaysTemplate) + + super.init() + + self.view.addSubview(self.separatorView) + } + + func update(presentationData: PresentationData, constrainedSize: CGSize) -> (minSize: CGSize, apply: (_ size: CGSize, _ transition: ContainedViewLayoutTransition) -> Void) { + return (minSize: CGSize(width: 0.0, height: 20.0), apply: { size, transition in + let sideInset: CGFloat = 18.0 + self.separatorView.tintColor = presentationData.theme.contextMenu.itemSeparatorColor + transition.updateFrame(view: self.separatorView, frame: CGRect(origin: CGPoint(x: sideInset, y: floorToScreenPixels((size.height - 1.0) * 0.5)), size: CGSize(width: max(0.0, size.width - sideInset * 2.0), height: 1.0))) + }) + } +} + +private final class ContextControllerActionsListCustomItemNode: ASDisplayNode, ContextControllerActionsListItemNode { + func canBeHighlighted() -> Bool { + if let itemNode = self.itemNode { + return itemNode.canBeHighlighted() + } else { + return false + } + } + + func updateIsHighlighted(isHighlighted: Bool) { + if let itemNode = self.itemNode { + itemNode.updateIsHighlighted(isHighlighted: isHighlighted) + } + } + + func performAction() { + if let itemNode = self.itemNode { + itemNode.performAction() + } + } + + var needsPadding: Bool { + if let itemNode = self.itemNode { + return itemNode.needsPadding + } else { + return true + } + } + + private let getController: () -> ContextControllerProtocol? + private let item: ContextMenuCustomItem + private let requestDismiss: (ContextMenuActionResult) -> Void + + private var presentationData: PresentationData? + private(set) var itemNode: ContextMenuCustomNode? + + init( + getController: @escaping () -> ContextControllerProtocol?, + item: ContextMenuCustomItem, + requestDismiss: @escaping (ContextMenuActionResult) -> Void + ) { + self.getController = getController + self.item = item + self.requestDismiss = requestDismiss + + super.init() + } + + func update(presentationData: PresentationData, constrainedSize: CGSize) -> (minSize: CGSize, apply: (_ size: CGSize, _ transition: ContainedViewLayoutTransition) -> Void) { + if self.presentationData?.theme !== presentationData.theme { + if let itemNode = self.itemNode { + itemNode.updateTheme(presentationData: presentationData) + } + } + self.presentationData = presentationData + + let itemNode: ContextMenuCustomNode + if let current = self.itemNode { + itemNode = current + } else { + itemNode = self.item.node( + presentationData: presentationData, + getController: self.getController, + actionSelected: { result in + switch result { + case .default, .dismissWithoutContent: + self.requestDismiss(result) + default: + break + } + } + ) + self.itemNode = itemNode + self.addSubnode(itemNode) + } + + let itemLayoutAndApply = itemNode.updateLayout(constrainedWidth: constrainedSize.width, constrainedHeight: constrainedSize.height) + + return (minSize: itemLayoutAndApply.0, apply: { size, transition in + transition.updateFrame(node: itemNode, frame: CGRect(origin: CGPoint(), size: size), beginWithCurrentState: true) + itemLayoutAndApply.1(size, transition) + }) + } +} + +public final class ContextControllerActionsListStackItem: ContextControllerActionsStackItem { + final class Node: ASDisplayNode, ContextControllerActionsStackItemNode { + private final class Params { + let presentationData: PresentationData + let constrainedSize: CGSize + let standardMinWidth: CGFloat + let standardMaxWidth: CGFloat + let additionalBottomInset: CGFloat + + init(presentationData: PresentationData, constrainedSize: CGSize, standardMinWidth: CGFloat, standardMaxWidth: CGFloat, additionalBottomInset: CGFloat) { + self.presentationData = presentationData + self.constrainedSize = constrainedSize + self.standardMinWidth = standardMinWidth + self.standardMaxWidth = standardMaxWidth + self.additionalBottomInset = additionalBottomInset + } + } + + private final class Item { + let node: ContextControllerActionsListItemNode + + init(node: ContextControllerActionsListItemNode) { + self.node = node + } + } + + private let context: AccountContext? + private let requestUpdate: (ContainedViewLayoutTransition) -> Void + private let getController: () -> ContextControllerProtocol? + private let requestDismiss: (ContextMenuActionResult) -> Void + private var items: [ContextMenuItem] + private var itemNodes: [Item] + + private var tip: ContextController.Tip? + private var tipDisposable: Disposable? + private var tipNode: InnerTextSelectionTipContainerNode? + private var tipSeparatorNode: ContextControllerActionsListSeparatorItemNode? + + private var hapticFeedback: HapticFeedback? + + private let highlightedItemBackgroundView: UIView + private var highlightedItemNode: Item? + + private var params: Params? + private var invalidatedItemNodes: Bool = false + + var wantsFullWidth: Bool { + return false + } + + init( + context: AccountContext?, + getController: @escaping () -> ContextControllerProtocol?, + requestDismiss: @escaping (ContextMenuActionResult) -> Void, + requestUpdate: @escaping (ContainedViewLayoutTransition) -> Void, + items: [ContextMenuItem], + tip: ContextController.Tip?, + tipSignal: Signal? + ) { + self.context = context + self.requestUpdate = requestUpdate + self.getController = getController + self.requestDismiss = requestDismiss + self.items = items + self.tip = tip + + var requestUpdateAction: ((AnyHashable, ContextMenuActionItem) -> Void)? + self.itemNodes = items.map { item -> Item in + switch item { + case let .action(actionItem): + return Item( + node: ContextControllerActionsListActionItemNode( + context: context, + getController: getController, + requestDismiss: requestDismiss, + requestUpdateAction: { id, action in + requestUpdateAction?(id, action) + }, + item: actionItem + ) + ) + case .separator: + return Item( + node: ContextControllerActionsListSeparatorItemNode() + ) + case let .custom(customItem, _): + return Item( + node: ContextControllerActionsListCustomItemNode( + getController: getController, + item: customItem, + requestDismiss: requestDismiss + ) + ) + } + } + + self.highlightedItemBackgroundView = UIView() + self.highlightedItemBackgroundView.alpha = 0.0 + + super.init() + + self.view.addSubview(self.highlightedItemBackgroundView) + + for item in self.itemNodes { + self.addSubnode(item.node) + } + + requestUpdateAction = { [weak self] id, action in + guard let self else { + return + } + self.requestUpdateAction(id: id, action: action) + } + } + + deinit { + self.tipDisposable?.dispose() + } + + func updateItems(items: [ContextMenuItem]) { + self.items = items + for i in 0 ..< items.count { + if self.itemNodes.count < i { + break + } + if case let .action(action) = items[i] { + if let itemNode = self.itemNodes[i].node as? ContextControllerActionsListActionItemNode { + itemNode.setItem(item: action) + } + } + } + } + + private func requestUpdateAction(id: AnyHashable, action: ContextMenuActionItem) { + loop: for i in 0 ..< self.items.count { + switch self.items[i] { + case let .action(currentAction): + if currentAction.id == id { + let previousNode = self.itemNodes[i] + previousNode.node.removeFromSupernode() + + let addedNode = Item( + node: ContextControllerActionsListActionItemNode( + context: self.context, + getController: self.getController, + requestDismiss: self.requestDismiss, + requestUpdateAction: { [weak self] id, action in + guard let self else { + return + } + self.requestUpdateAction(id: id, action: action) + }, + item: action + ) + ) + self.itemNodes[i] = addedNode + self.addSubnode(addedNode.node) + + self.requestUpdate(.immediate) + + break loop + } + default: + break + } + } + } + + private func update(transition: ContainedViewLayoutTransition) { + if let params = self.params { + let _ = self.update( + presentationData: params.presentationData, + constrainedSize: params.constrainedSize, + standardMinWidth: params.standardMinWidth, + standardMaxWidth: params.standardMaxWidth, + additionalBottomInset: params.additionalBottomInset, + transition: transition + ) + } + } + + func update( + presentationData: PresentationData, + constrainedSize: CGSize, + standardMinWidth: CGFloat, + standardMaxWidth: CGFloat, + additionalBottomInset: CGFloat, + transition: ContainedViewLayoutTransition + ) -> (size: CGSize, apparentHeight: CGFloat) { + self.params = Params( + presentationData: presentationData, + constrainedSize: constrainedSize, + standardMinWidth: standardMinWidth, + standardMaxWidth: standardMaxWidth, + additionalBottomInset: additionalBottomInset + ) + + var highlightedItemFrame: CGRect? + + let verticalInset: CGFloat = 10.0 + + var itemNodeLayouts: [(minSize: CGSize, apply: (_ size: CGSize, _ transition: ContainedViewLayoutTransition) -> Void)] = [] + var combinedSize = CGSize(width: 0.0, height: 0.0) + for i in 0 ..< self.itemNodes.count { + let item = self.itemNodes[i] + + let itemNodeLayout = item.node.update( + presentationData: presentationData, + constrainedSize: CGSize(width: standardMaxWidth, height: constrainedSize.height) + ) + + if item.node.needsPadding { + if i == 0 { + combinedSize.height += verticalInset + } + } + + itemNodeLayouts.append(itemNodeLayout) + combinedSize.width = max(combinedSize.width, itemNodeLayout.minSize.width) + combinedSize.height += itemNodeLayout.minSize.height + + if item.node.needsPadding { + if i == self.itemNodes.count - 1 { + combinedSize.height += verticalInset + } + } + } + self.invalidatedItemNodes = false + combinedSize.width = max(combinedSize.width, standardMinWidth) + + var nextItemOrigin = CGPoint(x: 0.0, y: 0.0) + for i in 0 ..< self.itemNodes.count { + let item = self.itemNodes[i] + let itemNodeLayout = itemNodeLayouts[i] + + var itemTransition = transition + if item.node.frame.isEmpty { + itemTransition = .immediate + } + + if item.node.needsPadding { + if i == 0 { + nextItemOrigin.y += verticalInset + } + } + + let itemSize = CGSize(width: combinedSize.width, height: itemNodeLayout.minSize.height) + let itemFrame = CGRect(origin: nextItemOrigin, size: itemSize) + itemTransition.updateFrame(node: item.node, frame: itemFrame, beginWithCurrentState: true) + + itemNodeLayout.apply(itemSize, itemTransition) + nextItemOrigin.y += itemSize.height + + if self.highlightedItemNode === item { + highlightedItemFrame = itemFrame + } + } + + if let tip = self.tip { + let tipNode: InnerTextSelectionTipContainerNode + var tipTransition = transition + if let current = self.tipNode { + tipNode = current + } else { + tipTransition = .immediate + tipNode = InnerTextSelectionTipContainerNode(presentationData: presentationData, tip: tip, isInline: true) + self.addSubnode(tipNode) + self.tipNode = tipNode + let getController = self.getController + tipNode.requestDismiss = { completion in + getController()?.dismiss(completion: completion) + } + } + + let tipSeparatorNode: ContextControllerActionsListSeparatorItemNode + if let current = self.tipSeparatorNode { + tipSeparatorNode = current + } else { + tipSeparatorNode = ContextControllerActionsListSeparatorItemNode() + self.addSubnode(tipSeparatorNode) + self.tipSeparatorNode = tipSeparatorNode + } + + let (tipSeparatorMinSize, tipSeparatorApply) = tipSeparatorNode.update(presentationData: presentationData, constrainedSize: CGSize(width: combinedSize.width, height: 10.0)) + let tipSeparatorSize = CGSize(width: combinedSize.width, height: tipSeparatorMinSize.height) + tipSeparatorApply(tipSeparatorSize, tipTransition) + let tipSeparatorFrame = CGRect(origin: nextItemOrigin, size: tipSeparatorSize) + tipTransition.updateFrame(node: tipSeparatorNode, frame: tipSeparatorFrame) + nextItemOrigin.y += tipSeparatorSize.height + combinedSize.height += tipSeparatorSize.height + + let tipSize = tipNode.updateLayout(widthClass: .compact, presentation: .inline, width: combinedSize.width, transition: tipTransition) + let tipFrame = CGRect(origin: nextItemOrigin, size: tipSize) + tipNode.setActualSize(size: tipFrame.size, transition: tipTransition) + tipTransition.updateFrame(node: tipNode, frame: tipFrame) + nextItemOrigin.y += tipSize.height + combinedSize.height += tipSize.height + } else { + if let tipSeparatorNode = self.tipSeparatorNode { + tipSeparatorNode.removeFromSupernode() + self.tipSeparatorNode = nil + } + if let tipNode = self.tipNode { + tipNode.removeFromSupernode() + self.tipNode = nil + } + } + + if let highlightedItemFrame { + self.highlightedItemBackgroundView.backgroundColor = presentationData.theme.overallDarkAppearance ? UIColor.white : UIColor.black + self.highlightedItemBackgroundView.setMonochromaticEffect(tintColor: self.highlightedItemBackgroundView.backgroundColor) + + var highlightTransition = ComponentTransition(transition) + var animateIn = false + if self.highlightedItemBackgroundView.alpha == 0.0 { + if self.highlightedItemBackgroundView.layer.animation(forKey: "opacity") == nil { + highlightTransition = .immediate + } + animateIn = true + } + let highlightFrame = CGRect(origin: CGPoint(x: 10.0, y: highlightedItemFrame.minY), size: CGSize(width: combinedSize.width - 10.0 * 2.0, height: highlightedItemFrame.height)) + highlightTransition.setFrame(view: self.highlightedItemBackgroundView, frame: highlightFrame) + highlightTransition.setCornerRadius(layer: self.highlightedItemBackgroundView.layer, cornerRadius: min(20.0, highlightFrame.height * 0.5)) + if animateIn { + var alphaTransition = transition + if transition.isAnimated { + alphaTransition = .animated(duration: 0.2, curve: .easeInOut) + } + ComponentTransition(alphaTransition).setAlpha(view: self.highlightedItemBackgroundView, alpha: 0.1) + } + } else if self.highlightedItemBackgroundView.alpha != 0.0 { + ComponentTransition(transition).setAlpha(view: self.highlightedItemBackgroundView, alpha: 0.0) + } + + return (combinedSize, combinedSize.height) + } + + func highlightGestureShouldBegin(location: CGPoint) -> Bool { + for itemNode in self.itemNodes { + if itemNode.node.frame.contains(location) { + if !itemNode.node.canBeHighlighted() { + return false + } + break + } + } + if let tipNode = self.tipNode { + if tipNode.frame.contains(location) { + return false + } + } + return true + } + + func highlightGestureMoved(location: CGPoint) { + var highlightedItemNode: Item? + for itemNode in self.itemNodes { + if itemNode.node.frame.contains(location) { + if itemNode.node.canBeHighlighted() { + highlightedItemNode = itemNode + } + break + } + } + if self.highlightedItemNode !== highlightedItemNode { + self.highlightedItemNode?.node.updateIsHighlighted(isHighlighted: false) + highlightedItemNode?.node.updateIsHighlighted(isHighlighted: true) + + self.highlightedItemNode = highlightedItemNode + if self.hapticFeedback == nil { + self.hapticFeedback = HapticFeedback() + } + self.hapticFeedback?.tap() + + self.update(transition: .animated(duration: 0.16, curve: .easeInOut)) + } + } + + func highlightGestureFinished(performAction: Bool) { + if let highlightedItemNode = self.highlightedItemNode { + self.highlightedItemNode = nil + highlightedItemNode.node.updateIsHighlighted(isHighlighted: false) + if performAction { + highlightedItemNode.node.performAction() + } + + self.update(transition: .animated(duration: 0.2, curve: .easeInOut)) + } + } + + func decreaseHighlightedIndex() { + let previousHighlightedItemNode: Item? = self.highlightedItemNode + if let highlightedItemNode = self.highlightedItemNode, let index = self.itemNodes.firstIndex(where: { $0 === highlightedItemNode }) { + self.highlightedItemNode = self.itemNodes[max(0, index - 1)] + } else { + self.highlightedItemNode = self.itemNodes.first + } + + if previousHighlightedItemNode !== self.highlightedItemNode { + previousHighlightedItemNode?.node.updateIsHighlighted(isHighlighted: false) + self.highlightedItemNode?.node.updateIsHighlighted(isHighlighted: true) + } + } + + func increaseHighlightedIndex() { + let previousHighlightedItemNode: Item? = self.highlightedItemNode + if let highlightedItemNode = self.highlightedItemNode, let index = self.itemNodes.firstIndex(where: { $0 === highlightedItemNode }) { + self.highlightedItemNode = self.itemNodes[min(self.itemNodes.count - 1, index + 1)] + } else { + self.highlightedItemNode = self.itemNodes.first + } + + if previousHighlightedItemNode !== self.highlightedItemNode { + previousHighlightedItemNode?.node.updateIsHighlighted(isHighlighted: false) + self.highlightedItemNode?.node.updateIsHighlighted(isHighlighted: true) + } + } + } + + public let id: AnyHashable? + public let items: [ContextMenuItem] + public let reactionItems: ContextControllerReactionItems? + public let previewReaction: ContextControllerPreviewReaction? + public let tip: ContextController.Tip? + public let tipSignal: Signal? + public let dismissed: (() -> Void)? + + public init( + id: AnyHashable?, + items: [ContextMenuItem], + reactionItems: ContextControllerReactionItems?, + previewReaction: ContextControllerPreviewReaction?, + tip: ContextController.Tip?, + tipSignal: Signal?, + dismissed: (() -> Void)? + ) { + self.id = id + self.items = items + self.reactionItems = reactionItems + self.previewReaction = previewReaction + self.tip = tip + self.tipSignal = tipSignal + self.dismissed = dismissed + } + + public func node( + context: AccountContext?, + getController: @escaping () -> ContextControllerProtocol?, + requestDismiss: @escaping (ContextMenuActionResult) -> Void, + requestUpdate: @escaping (ContainedViewLayoutTransition) -> Void, + requestUpdateApparentHeight: @escaping (ContainedViewLayoutTransition) -> Void + ) -> ContextControllerActionsStackItemNode { + return Node( + context: context, + getController: getController, + requestDismiss: requestDismiss, + requestUpdate: requestUpdate, + items: self.items, + tip: self.tip, + tipSignal: self.tipSignal + ) + } +} + +final class ContextControllerActionsCustomStackItem: ContextControllerActionsStackItem { + private final class Node: ASDisplayNode, ContextControllerActionsStackItemNode { + private let requestUpdate: (ContainedViewLayoutTransition) -> Void + private let contentNode: ContextControllerItemsNode + + init( + content: ContextControllerItemsContent, + getController: @escaping () -> ContextControllerProtocol?, + requestUpdate: @escaping (ContainedViewLayoutTransition) -> Void, + requestUpdateApparentHeight: @escaping (ContainedViewLayoutTransition) -> Void + ) { + self.requestUpdate = requestUpdate + self.contentNode = content.node(requestUpdate: { transition in + requestUpdate(transition) + }, requestUpdateApparentHeight: { transition in + requestUpdateApparentHeight(transition) + }) + + super.init() + + self.addSubnode(self.contentNode) + } + + var wantsFullWidth: Bool { + return true + } + + func update( + presentationData: PresentationData, + constrainedSize: CGSize, + standardMinWidth: CGFloat, + standardMaxWidth: CGFloat, + additionalBottomInset: CGFloat, + transition: ContainedViewLayoutTransition + ) -> (size: CGSize, apparentHeight: CGFloat) { + let contentLayout = self.contentNode.update( + presentationData: presentationData, + constrainedWidth: constrainedSize.width, + maxHeight: constrainedSize.height, + bottomInset: additionalBottomInset, + transition: transition + ) + transition.updateFrame(node: self.contentNode, frame: CGRect(origin: CGPoint(), size: contentLayout.cleanSize), beginWithCurrentState: true) + + return (contentLayout.cleanSize, contentLayout.apparentHeight) + } + + func highlightGestureShouldBegin(location: CGPoint) -> Bool { + return true + } + + func highlightGestureMoved(location: CGPoint) { + } + + func highlightGestureFinished(performAction: Bool) { + } + + func decreaseHighlightedIndex() { + } + + func increaseHighlightedIndex() { + } + } + + let id: AnyHashable? + private let content: ContextControllerItemsContent + let reactionItems: ContextControllerReactionItems? + let previewReaction: ContextControllerPreviewReaction? + let tip: ContextController.Tip? + let tipSignal: Signal? + let dismissed: (() -> Void)? + + init( + id: AnyHashable?, + content: ContextControllerItemsContent, + reactionItems: ContextControllerReactionItems?, + previewReaction: ContextControllerPreviewReaction?, + tip: ContextController.Tip?, + tipSignal: Signal?, + dismissed: (() -> Void)? + ) { + self.id = id + self.content = content + self.reactionItems = reactionItems + self.previewReaction = previewReaction + self.tip = tip + self.tipSignal = tipSignal + self.dismissed = dismissed + } + + func node( + context: AccountContext?, + getController: @escaping () -> ContextControllerProtocol?, + requestDismiss: @escaping (ContextMenuActionResult) -> Void, + requestUpdate: @escaping (ContainedViewLayoutTransition) -> Void, + requestUpdateApparentHeight: @escaping (ContainedViewLayoutTransition) -> Void + ) -> ContextControllerActionsStackItemNode { + return Node( + content: self.content, + getController: getController, + requestUpdate: requestUpdate, + requestUpdateApparentHeight: requestUpdateApparentHeight + ) + } +} + +func makeContextControllerActionsStackItem(items: ContextController.Items) -> [ContextControllerActionsStackItem] { + var reactionItems: ContextControllerReactionItems? + if let context = items.context, let animationCache = items.animationCache, !items.reactionItems.isEmpty { + reactionItems = ContextControllerReactionItems( + context: context, + reactionItems: items.reactionItems, + selectedReactionItems: items.selectedReactionItems, + reactionsTitle: items.reactionsTitle, + reactionsLocked: items.reactionsLocked, + animationCache: animationCache, + alwaysAllowPremiumReactions: items.alwaysAllowPremiumReactions, + allPresetReactionsAreAvailable: items.allPresetReactionsAreAvailable, + getEmojiContent: items.getEmojiContent + ) + } + var previewReaction: ContextControllerPreviewReaction? + if let context = items.context, let file = items.previewReaction { + previewReaction = ContextControllerPreviewReaction(context: context, file: file) + } + switch items.content { + case let .list(listItems): + return [ContextControllerActionsListStackItem(id: items.id, items: listItems, reactionItems: reactionItems, previewReaction: previewReaction, tip: items.tip, tipSignal: items.tipSignal, dismissed: items.dismissed)] + case let .twoLists(listItems1, listItems2): + return [ContextControllerActionsListStackItem(id: items.id, items: listItems1, reactionItems: nil, previewReaction: nil, tip: nil, tipSignal: nil, dismissed: items.dismissed), ContextControllerActionsListStackItem(id: nil, items: listItems2, reactionItems: nil, previewReaction: nil, tip: nil, tipSignal: nil, dismissed: nil)] + case let .custom(customContent): + return [ContextControllerActionsCustomStackItem(id: items.id, content: customContent, reactionItems: reactionItems, previewReaction: previewReaction, tip: items.tip, tipSignal: items.tipSignal, dismissed: items.dismissed)] + } +} + +private final class ItemSelectionRecognizer: UIGestureRecognizer { + var shouldBegin: ((CGPoint) -> Bool)? + + private var initialLocation: CGPoint? + private var currentLocation: CGPoint? + + public override init(target: Any?, action: Selector?) { + super.init(target: target, action: action) + + self.delaysTouchesBegan = false + self.delaysTouchesEnded = false + } + + public override func reset() { + super.reset() + + self.initialLocation = nil + } + + public override func touchesBegan(_ touches: Set, with event: UIEvent) { + super.touchesBegan(touches, with: event) + + if let location = touches.first?.location(in: self.view), let shouldBegin = self.shouldBegin, !shouldBegin(location) { + self.state = .failed + return + } + + if self.initialLocation == nil { + self.initialLocation = touches.first?.location(in: self.view) + } + self.currentLocation = self.initialLocation + + self.state = .began + } + + public override func touchesEnded(_ touches: Set, with event: UIEvent) { + super.touchesEnded(touches, with: event) + + self.state = .ended + } + + public override func touchesCancelled(_ touches: Set, with event: UIEvent) { + super.touchesCancelled(touches, with: event) + + self.state = .cancelled + } + + public override func touchesMoved(_ touches: Set, with event: UIEvent) { + super.touchesMoved(touches, with: event) + + self.currentLocation = touches.first?.location(in: self.view) + + self.state = .changed + } + + public func translation(in: UIView?) -> CGPoint { + if let initialLocation = self.initialLocation, let currentLocation = self.currentLocation { + return CGPoint(x: currentLocation.x - initialLocation.x, y: currentLocation.y - initialLocation.y) + } + return CGPoint() + } +} + +public final class ContextControllerActionsStackNodeImpl: ASDisplayNode, ContextControllerActionsStackNode { + final class NavigationContainer: ASDisplayNode, ASGestureRecognizerDelegate { + let backgroundContainer: GlassBackgroundContainerView + let backgroundContainerInset: CGFloat + let backgroundView: GlassBackgroundView + var sourceExtractableContainer: ContextExtractableContainer? + let contentContainer: UIView + + var requestUpdate: ((ContainedViewLayoutTransition) -> Void)? + var requestPop: (() -> Void)? + var transitionFraction: CGFloat = 0.0 + + private var panRecognizer: InteractiveTransitionGestureRecognizer? + + var isNavigationEnabled: Bool = false { + didSet { + self.panRecognizer?.isEnabled = self.isNavigationEnabled + } + } + + override init() { + self.backgroundContainer = GlassBackgroundContainerView() + self.backgroundView = GlassBackgroundView() + self.backgroundContainer.contentView.addSubview(self.backgroundView) + + self.contentContainer = UIView() + self.contentContainer.clipsToBounds = true + self.backgroundView.contentView.addSubview(self.contentContainer) + + self.backgroundContainerInset = 32.0 + + super.init() + + self.view.addSubview(self.backgroundContainer) + + let panRecognizer = InteractiveTransitionGestureRecognizer(target: self, action: #selector(self.panGesture(_:)), allowedDirections: { [weak self] point in + guard let strongSelf = self else { + return [] + } + let _ = strongSelf + return [.right] + }) + panRecognizer.delegate = self.wrappedGestureRecognizerDelegate + self.view.addGestureRecognizer(panRecognizer) + self.panRecognizer = panRecognizer + } + + func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { + return false + } + + func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { + if let _ = otherGestureRecognizer as? InteractiveTransitionGestureRecognizer { + return false + } + if let _ = otherGestureRecognizer as? UIPanGestureRecognizer { + return true + } + return false + } + + @objc private func panGesture(_ recognizer: UIPanGestureRecognizer) { + switch recognizer.state { + case .began: + self.transitionFraction = 0.0 + case .changed: + let distanceFactor: CGFloat = recognizer.translation(in: self.view).x / self.bounds.width + let transitionFraction = max(0.0, min(1.0, distanceFactor)) + if self.transitionFraction != transitionFraction { + self.transitionFraction = transitionFraction + self.requestUpdate?(.immediate) + } + case .ended, .cancelled: + let distanceFactor: CGFloat = recognizer.translation(in: self.view).x / self.bounds.width + let transitionFraction = max(0.0, min(1.0, distanceFactor)) + if transitionFraction > 0.2 { + self.transitionFraction = 0.0 + self.requestPop?() + } else { + self.transitionFraction = 0.0 + self.requestUpdate?(.animated(duration: 0.45, curve: .spring)) + } + default: + break + } + } + + func animateIn(fromExtractableContainer extractableContainer: ContextExtractableContainer, transition: ComponentTransition) { + let normalState = extractableContainer.normalState + let sourceSize = normalState.size + let normalCornerRadius: CGFloat = normalState.cornerRadius + + let currentSize = self.contentContainer.bounds.size + + self.sourceExtractableContainer = extractableContainer + self.backgroundView.isHidden = true + + self.backgroundContainer.contentView.addSubview(extractableContainer.extractableContentView) + for subview in extractableContainer.extractableContentView.subviews { + if let subview = subview as? GlassBackgroundView { + //TODO:release + subview.contentView.addSubview(self.contentContainer) + break + } + } + + self.sourceExtractableContainer = nil + self.contentContainer.frame = CGRect(origin: CGPoint(), size: sourceSize) + self.contentContainer.layer.cornerRadius = normalCornerRadius + + extractableContainer.extractableContentView.frame = CGRect(origin: CGPoint(x: (currentSize.width - sourceSize.width) * 0.5, y: (currentSize.height - sourceSize.height) * 0.5), size: sourceSize).offsetBy(dx: self.backgroundContainerInset, dy: self.backgroundContainerInset) + transition.setFrame(view: extractableContainer.extractableContentView, frame: CGRect(origin: CGPoint(x: self.backgroundContainerInset, y: self.backgroundContainerInset), size: currentSize)) + transition.setFrame(view: self.contentContainer, frame: CGRect(origin: CGPoint(), size: currentSize)) + transition.setCornerRadius(layer: self.contentContainer.layer, cornerRadius: 30.0) + self.contentContainer.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.15) + + extractableContainer.updateState(state: .extracted(size: sourceSize, cornerRadius: normalCornerRadius, state: .animatedOut), transition: .transition(.immediate), completion: nil) + let mappedTransition: ContextExtractableContainer.Transition + if case let .curve(duration, curve) = transition.animation, case let .bounce(stiffness, damping) = curve { + mappedTransition = .spring(duration: duration, stiffness: stiffness, damping: damping) + } else { + mappedTransition = .transition(transition.containedViewLayoutTransition) + } + extractableContainer.updateState(state: .extracted(size: currentSize, cornerRadius: 30.0, state: .animatedIn), transition: mappedTransition, completion: nil) + } + + func animateOut(toExtractableContainer extractableContainer: ContextExtractableContainer, transition: ComponentTransition) { + let normalState = extractableContainer.normalState + let normalSize = normalState.size + let normalCornerRadius: CGFloat = normalState.cornerRadius + + let currentSize = self.contentContainer.bounds.size + + transition.setFrame(view: extractableContainer.extractableContentView, frame: CGRect(origin: CGPoint(x: self.backgroundContainerInset, y: self.backgroundContainerInset), size: normalSize).offsetBy(dx: (currentSize.width - normalSize.width) * 0.5, dy: (currentSize.height - normalSize.height) * 0.5)) + + transition.setFrame(view: self.contentContainer, frame: CGRect(origin: CGPoint(), size: normalSize)) + transition.setCornerRadius(layer: self.contentContainer.layer, cornerRadius: normalCornerRadius) + transition.setAlpha(view: self.contentContainer, alpha: 0.0) + + let mappedTransition: ContextExtractableContainer.Transition + if case let .curve(duration, curve) = transition.animation, case let .bounce(stiffness, damping) = curve { + mappedTransition = .spring(duration: duration, stiffness: stiffness, damping: damping) + } else { + mappedTransition = .transition(transition.containedViewLayoutTransition) + } + extractableContainer.updateState(state: .extracted(size: normalSize, cornerRadius: normalCornerRadius, state: .animatedOut), transition: mappedTransition, completion: nil) + } + + func didAnimateOut(toExtractableContainer extractableContainer: ContextExtractableContainer) { + extractableContainer.addSubview(extractableContainer.extractableContentView) + extractableContainer.updateState(state: .normal, transition: .transition(.immediate), completion: nil) + } + + func update(presentationData: PresentationData, presentation: Presentation, size: CGSize, transition: ContainedViewLayoutTransition) { + let transition = ComponentTransition(transition) + + transition.setFrame(view: self.contentContainer, frame: CGRect(origin: CGPoint(), size: size)) + + let backgroundContainerFrame = CGRect(origin: CGPoint(), size: size).insetBy(dx: -self.backgroundContainerInset, dy: -self.backgroundContainerInset) + + if self.backgroundContainer.bounds.size != backgroundContainerFrame.size { + self.backgroundContainer.update(size: backgroundContainerFrame.size, isDark: presentationData.theme.overallDarkAppearance, transition: transition) + transition.setFrame(view: self.backgroundContainer, frame: backgroundContainerFrame) + } + + transition.setCornerRadius(layer: self.contentContainer.layer, cornerRadius: min(30.0, size.height * 0.5)) + + transition.setFrame(view: self.backgroundView, frame: CGRect(origin: CGPoint(x: self.backgroundContainerInset, y: self.backgroundContainerInset), size: size)) + self.backgroundView.update(size: size, cornerRadius: min(30.0, size.height * 0.5), isDark: presentationData.theme.overallDarkAppearance, tintColor: .init(kind: .panel), isInteractive: true, transition: transition) + + if let sourceExtractableContainer = self.sourceExtractableContainer { + transition.setFrame(view: sourceExtractableContainer.extractableContentView, frame: CGRect(origin: CGPoint(), size: size)) + sourceExtractableContainer.updateState(state: .extracted(size: size, cornerRadius: min(30.0, size.height * 0.5), state: .animatedIn), transition: .transition(transition.containedViewLayoutTransition), completion: nil) + } + } + } + + final class ItemContainer: ASDisplayNode { + let getController: () -> ContextControllerProtocol? + let requestUpdate: (ContainedViewLayoutTransition) -> Void + let item: ContextControllerActionsStackItem + let node: ContextControllerActionsStackItemNode + let dimNode: ASDisplayNode + var tip: ContextController.Tip? + let tipSignal: Signal? + var tipNode: InnerTextSelectionTipContainerNode? + let reactionItems: ContextControllerReactionItems? + let previewReaction: ContextControllerPreviewReaction? + let itemDismissed: (() -> Void)? + var storedScrollingState: CGFloat? + let positionLock: CGFloat? + + private var tipDisposable: Disposable? + + init( + context: AccountContext?, + getController: @escaping () -> ContextControllerProtocol?, + requestDismiss: @escaping (ContextMenuActionResult) -> Void, + requestUpdate: @escaping (ContainedViewLayoutTransition) -> Void, + requestUpdateApparentHeight: @escaping (ContainedViewLayoutTransition) -> Void, + item: ContextControllerActionsStackItem, + tip: ContextController.Tip?, + tipSignal: Signal?, + reactionItems: ContextControllerReactionItems?, + previewReaction: ContextControllerPreviewReaction?, + itemDismissed: (() -> Void)?, + positionLock: CGFloat? + ) { + self.getController = getController + self.requestUpdate = requestUpdate + self.item = item + self.node = item.node( + context: context, + getController: getController, + requestDismiss: requestDismiss, + requestUpdate: requestUpdate, + requestUpdateApparentHeight: requestUpdateApparentHeight + ) + + self.dimNode = ASDisplayNode() + self.dimNode.isUserInteractionEnabled = false + self.dimNode.alpha = 0.0 + + self.reactionItems = reactionItems + self.previewReaction = previewReaction + self.itemDismissed = itemDismissed + self.positionLock = positionLock + + self.tip = tip + self.tipSignal = tipSignal + + super.init() + + self.clipsToBounds = true + + self.addSubnode(self.node) + self.addSubnode(self.dimNode) + + if let tipSignal = tipSignal { + self.tipDisposable = (tipSignal + |> deliverOnMainQueue).start(next: { [weak self] tip in + guard let strongSelf = self else { + return + } + strongSelf.tip = tip + requestUpdate(.immediate) + }).strict() + } + } + + deinit { + self.tipDisposable?.dispose() + } + + func update( + presentationData: PresentationData, + constrainedSize: CGSize, + standardMinWidth: CGFloat, + standardMaxWidth: CGFloat, + additionalBottomInset: CGFloat, + transitionFraction: CGFloat, + transition: ContainedViewLayoutTransition + ) -> (size: CGSize, apparentHeight: CGFloat) { + let (size, apparentHeight) = self.node.update( + presentationData: presentationData, + constrainedSize: constrainedSize, + standardMinWidth: standardMinWidth, + standardMaxWidth: standardMaxWidth, + additionalBottomInset: additionalBottomInset, + transition: transition + ) + + let maxScaleOffset: CGFloat = 10.0 + let scaleOffset: CGFloat = 0.0 * transitionFraction + maxScaleOffset * (1.0 - transitionFraction) + let scale: CGFloat = (size.width - scaleOffset) / size.width + let yOffset: CGFloat = size.height * (1.0 - scale) + let transitionOffset = (1.0 - transitionFraction) * size.width / 2.0 + transition.updatePosition(node: self.node, position: CGPoint(x: size.width / 2.0 + scaleOffset / 2.0 + transitionOffset, y: size.height / 2.0 - yOffset / 2.0), beginWithCurrentState: true) + transition.updateBounds(node: self.node, bounds: CGRect(origin: CGPoint(), size: size), beginWithCurrentState: true) + transition.updateTransformScale(node: self.node, scale: scale, beginWithCurrentState: true) + + return (size, apparentHeight) + } + + func updateTip(presentationData: PresentationData, presentation: ContextControllerActionsStackNode.Presentation, width: CGFloat, transition: ContainedViewLayoutTransition) -> (node: InnerTextSelectionTipContainerNode, height: CGFloat)? { + if self.item is ContextControllerActionsListStackItem { + return nil + } + + if let tip = self.tip { + var updatedTransition = transition + if let tipNode = self.tipNode, tipNode.tip == tip { + } else { + let previousTipNode = self.tipNode + updatedTransition = .immediate + let tipNode = InnerTextSelectionTipContainerNode(presentationData: presentationData, tip: tip, isInline: false) + tipNode.requestDismiss = { [weak self] completion in + self?.getController()?.dismiss(completion: completion) + } + self.tipNode = tipNode + + if let previousTipNode = previousTipNode { + previousTipNode.animateTransitionInside(other: tipNode) + previousTipNode.removeFromSupernode() + + tipNode.animateContentIn() + } + } + + if let tipNode = self.tipNode { + let size = tipNode.updateLayout(widthClass: .compact, presentation: presentation, width: width, transition: updatedTransition) + return (tipNode, size.height) + } else { + return nil + } + } else { + return nil + } + } + + func updateDimNode(presentationData: PresentationData, size: CGSize, transitionFraction: CGFloat, transition: ContainedViewLayoutTransition) { + self.dimNode.backgroundColor = presentationData.theme.contextMenu.sectionSeparatorColor + + transition.updateFrame(node: self.dimNode, frame: CGRect(origin: CGPoint(), size: size), beginWithCurrentState: true) + transition.updateAlpha(node: self.dimNode, alpha: 1.0 - transitionFraction, beginWithCurrentState: true) + } + + func highlightGestureShouldBegin(at location: CGPoint) -> Bool { + return self.node.highlightGestureShouldBegin(location: self.view.convert(location, to: self.node.view)) + } + + func highlightGestureMoved(location: CGPoint) { + if let tipNode = self.tipNode { + let tipLocation = self.view.convert(location, to: tipNode.view) + tipNode.highlightGestureMoved(location: tipLocation) + } + self.node.highlightGestureMoved(location: self.view.convert(location, to: self.node.view)) + } + + func highlightGestureFinished(performAction: Bool) { + if let tipNode = self.tipNode { + tipNode.highlightGestureFinished(performAction: performAction) + } + self.node.highlightGestureFinished(performAction: performAction) + } + + func decreaseHighlightedIndex() { + self.node.decreaseHighlightedIndex() + } + + func increaseHighlightedIndex() { + self.node.increaseHighlightedIndex() + } + } + + private let context: AccountContext? + private let getController: () -> ContextControllerProtocol? + private let requestDismiss: (ContextMenuActionResult) -> Void + private let requestUpdate: (ContainedViewLayoutTransition) -> Void + + private let navigationContainer: NavigationContainer + private var itemContainers: [ItemContainer] = [] + private var dismissingItemContainers: [(container: ItemContainer, isPopped: Bool)] = [] + + private var selectionPanGesture: ItemSelectionRecognizer? + + public var topReactionItems: ContextControllerReactionItems? { + return self.itemContainers.last?.reactionItems + } + + public var topPreviewReaction: ContextControllerPreviewReaction? { + return self.itemContainers.last?.previewReaction + } + + public var topPositionLock: CGFloat? { + return self.itemContainers.last?.positionLock + } + + public var storedScrollingState: CGFloat? { + return self.itemContainers.last?.storedScrollingState + } + + public init( + context: AccountContext?, + getController: @escaping () -> ContextControllerProtocol?, + requestDismiss: @escaping (ContextMenuActionResult) -> Void, + requestUpdate: @escaping (ContainedViewLayoutTransition) -> Void + ) { + self.context = context + self.getController = getController + self.requestDismiss = requestDismiss + self.requestUpdate = requestUpdate + + self.navigationContainer = NavigationContainer() + + super.init() + + self.addSubnode(self.navigationContainer) + + self.navigationContainer.requestUpdate = { [weak self] transition in + guard let strongSelf = self else { + return + } + strongSelf.requestUpdate(transition) + } + + self.navigationContainer.requestPop = { [weak self] in + guard let strongSelf = self else { + return + } + strongSelf.pop() + } + + let selectionPanGesture = ItemSelectionRecognizer(target: self, action: #selector(self.panGesture(_:))) + selectionPanGesture.shouldBegin = { [weak self] point in + guard let self, let topItemContainer = self.itemContainers.last else { + return false + } + + if topItemContainer.item is ContextControllerActionsCustomStackItem { + return false + } + if !topItemContainer.highlightGestureShouldBegin(at: self.view.convert(point, to: topItemContainer.view)) { + return false + } + + return true + } + self.selectionPanGesture = selectionPanGesture + self.view.addGestureRecognizer(selectionPanGesture) + selectionPanGesture.isEnabled = false + } + + @objc private func panGesture(_ recognizer: UIPanGestureRecognizer) { + switch recognizer.state { + case .began, .changed: + let location = recognizer.location(in: self.view) + self.highlightGestureMoved(location: location) + case .ended: + self.highlightGestureFinished(performAction: true) + case .cancelled: + self.highlightGestureFinished(performAction: false) + default: + break + } + } + + public func replace(item: ContextControllerActionsStackItem, animated: Bool?) { + if let item = item as? ContextControllerActionsListStackItem, let topContainer = self.itemContainers.first, let topItem = topContainer.item as? ContextControllerActionsListStackItem, let topId = topItem.id, let id = item.id, topId == id, item.items.count == topItem.items.count { + if let topNode = topContainer.node as? ContextControllerActionsListStackItem.Node { + var matches = true + for i in 0 ..< item.items.count { + switch item.items[i] { + case .action: + if case .action = topItem.items[i] { + } else { + matches = false + } + case .custom: + if case .custom = topItem.items[i] { + } else { + matches = false + } + case .separator: + if case .separator = topItem.items[i] { + } else { + matches = false + } + } + } + + if matches { + topNode.updateItems(items: item.items) + self.requestUpdate(.animated(duration: 0.3, curve: .spring)) + return + } + } + } + + var resolvedAnimated = false + if let animated { + resolvedAnimated = animated + } else { + if let id = item.id, let lastId = self.itemContainers.last?.item.id { + if id != lastId { + resolvedAnimated = true + } + } + } + + for itemContainer in self.itemContainers { + if resolvedAnimated { + self.dismissingItemContainers.append((itemContainer, false)) + } else { + itemContainer.tipNode?.removeFromSupernode() + itemContainer.removeFromSupernode() + } + } + self.itemContainers.removeAll() + self.navigationContainer.isNavigationEnabled = self.itemContainers.count > 1 + + self.push(item: item, currentScrollingState: nil, positionLock: nil, animated: resolvedAnimated) + } + + public func push(item: ContextControllerActionsStackItem, currentScrollingState: CGFloat?, positionLock: CGFloat?, animated: Bool) { + if let itemContainer = self.itemContainers.last { + itemContainer.storedScrollingState = currentScrollingState + } + let itemContainer = ItemContainer( + context: self.context, + getController: self.getController, + requestDismiss: self.requestDismiss, + requestUpdate: self.requestUpdate, + requestUpdateApparentHeight: { [weak self] transition in + guard let strongSelf = self else { + return + } + strongSelf.requestUpdate(transition) + }, + item: item, + tip: item.tip, + tipSignal: item.tipSignal, + reactionItems: item.reactionItems, + previewReaction: item.previewReaction, + itemDismissed: item.dismissed, + positionLock: positionLock + ) + self.itemContainers.append(itemContainer) + self.navigationContainer.contentContainer.addSubview(itemContainer.view) + self.navigationContainer.isNavigationEnabled = self.itemContainers.count > 1 + + let transition: ContainedViewLayoutTransition + if animated { + transition = .animated(duration: self.itemContainers.count == 1 ? 0.3 : 0.45, curve: .spring) + } else { + transition = .immediate + } + self.requestUpdate(transition) + } + + public func clearStoredScrollingState() { + self.itemContainers.last?.storedScrollingState = nil + } + + public func pop() { + if self.itemContainers.count == 1 { + //dismiss + } else { + let itemContainer = self.itemContainers[self.itemContainers.count - 1] + self.itemContainers.remove(at: self.itemContainers.count - 1) + self.dismissingItemContainers.append((itemContainer, true)) + + itemContainer.itemDismissed?() + } + + self.navigationContainer.isNavigationEnabled = self.itemContainers.count > 1 + + let transition: ContainedViewLayoutTransition = .animated(duration: 0.45, curve: .spring) + self.requestUpdate(transition) + } + + public func update( + presentationData: PresentationData, + constrainedSize: CGSize, + presentation: Presentation, + transition: ContainedViewLayoutTransition + ) -> CGSize { + let tipSpacing: CGFloat = 10.0 + + let animateAppearingContainers = transition.isAnimated && !self.dismissingItemContainers.isEmpty + + struct TipLayout { + var tipNode: InnerTextSelectionTipContainerNode + var tipHeight: CGFloat + } + + struct ItemLayout { + var size: CGSize + var apparentHeight: CGFloat + var transitionFraction: CGFloat + var alphaTransitionFraction: CGFloat + var itemTransition: ContainedViewLayoutTransition + var animateAppearingContainer: Bool + var tip: TipLayout? + } + + var topItemSize = CGSize() + var itemLayouts: [ItemLayout] = [] + for i in 0 ..< self.itemContainers.count { + let itemContainer = self.itemContainers[i] + + var animateAppearingContainer = false + var itemContainerTransition = transition + if itemContainer.bounds.isEmpty { + itemContainerTransition = .immediate + animateAppearingContainer = i == self.itemContainers.count - 1 && animateAppearingContainers || self.itemContainers.count > 1 + } + + let itemConstrainedHeight: CGFloat = constrainedSize.height + + let transitionFraction: CGFloat + let alphaTransitionFraction: CGFloat + if i == self.itemContainers.count - 1 { + transitionFraction = self.navigationContainer.transitionFraction + alphaTransitionFraction = 1.0 + } else if i == self.itemContainers.count - 2 { + transitionFraction = self.navigationContainer.transitionFraction - 1.0 + alphaTransitionFraction = self.navigationContainer.transitionFraction + } else { + transitionFraction = 0.0 + alphaTransitionFraction = 0.0 + } + + var tip: TipLayout? + + let itemContainerConstrainedSize: CGSize + let standardMinWidth: CGFloat + let standardMaxWidth: CGFloat + let additionalBottomInset: CGFloat + + if itemContainer.node.wantsFullWidth { + itemContainerConstrainedSize = CGSize(width: constrainedSize.width, height: itemConstrainedHeight) + standardMaxWidth = 240.0 + standardMinWidth = standardMaxWidth + + if let (tipNode, tipHeight) = itemContainer.updateTip(presentationData: presentationData, presentation: presentation, width: standardMaxWidth, transition: itemContainerTransition) { + tip = TipLayout(tipNode: tipNode, tipHeight: tipHeight) + additionalBottomInset = tipHeight + 10.0 + } else { + additionalBottomInset = 0.0 + } + } else { + itemContainerConstrainedSize = CGSize(width: constrainedSize.width, height: itemConstrainedHeight) + standardMinWidth = 220.0 + standardMaxWidth = 240.0 + additionalBottomInset = 0.0 + } + + let itemSize = itemContainer.update( + presentationData: presentationData, + constrainedSize: itemContainerConstrainedSize, + standardMinWidth: standardMinWidth, + standardMaxWidth: standardMaxWidth, + additionalBottomInset: additionalBottomInset, + transitionFraction: alphaTransitionFraction, + transition: itemContainerTransition + ) + if i == self.itemContainers.count - 1 { + topItemSize = itemSize.size + } + + if !itemContainer.node.wantsFullWidth { + if let (tipNode, tipHeight) = itemContainer.updateTip(presentationData: presentationData, presentation: presentation, width: itemSize.size.width, transition: itemContainerTransition) { + tip = TipLayout(tipNode: tipNode, tipHeight: tipHeight) + } + } + + itemLayouts.append(ItemLayout( + size: itemSize.size, + apparentHeight: itemSize.apparentHeight, + transitionFraction: transitionFraction, + alphaTransitionFraction: alphaTransitionFraction, + itemTransition: itemContainerTransition, + animateAppearingContainer: animateAppearingContainer, + tip: tip + )) + } + + let topItemApparentHeight: CGFloat + let topItemWidth: CGFloat + if itemLayouts.isEmpty { + topItemApparentHeight = 0.0 + topItemWidth = 0.0 + } else if itemLayouts.count == 1 { + topItemApparentHeight = itemLayouts[0].apparentHeight + topItemWidth = itemLayouts[0].size.width + } else { + let lastItemLayout = itemLayouts[itemLayouts.count - 1] + let previousItemLayout = itemLayouts[itemLayouts.count - 2] + let transitionFraction = self.navigationContainer.transitionFraction + + topItemApparentHeight = lastItemLayout.apparentHeight * (1.0 - transitionFraction) + previousItemLayout.apparentHeight * transitionFraction + topItemWidth = lastItemLayout.size.width * (1.0 - transitionFraction) + previousItemLayout.size.width * transitionFraction + } + + let navigationContainerFrame: CGRect + if topItemApparentHeight > 0.0 { + navigationContainerFrame = CGRect(origin: CGPoint(), size: CGSize(width: topItemWidth, height: max(14 * 2.0, topItemApparentHeight))) + } else { + navigationContainerFrame = .zero + } + let previousNavigationContainerFrame = self.navigationContainer.frame + transition.updateFrame(node: self.navigationContainer, frame: navigationContainerFrame, beginWithCurrentState: true) + if !navigationContainerFrame.isEmpty { + self.navigationContainer.update(presentationData: presentationData, presentation: presentation, size: navigationContainerFrame.size, transition: transition) + } + + for i in 0 ..< self.itemContainers.count { + let xOffset: CGFloat + if itemLayouts[i].transitionFraction < 0.0 { + xOffset = itemLayouts[i].transitionFraction * itemLayouts[i].size.width + } else { + if i != 0 { + xOffset = itemLayouts[i].transitionFraction * itemLayouts[i - 1].size.width + } else { + xOffset = itemLayouts[i].transitionFraction * topItemWidth + } + } + let itemFrame = CGRect(origin: CGPoint(x: xOffset, y: 0.0), size: CGSize(width: itemLayouts[i].size.width, height: navigationContainerFrame.height)) + + itemLayouts[i].itemTransition.updateFrame(node: self.itemContainers[i], frame: itemFrame, beginWithCurrentState: true) + if itemLayouts[i].animateAppearingContainer { + transition.animatePositionAdditive(node: self.itemContainers[i], offset: CGPoint(x: itemFrame.width, y: 0.0)) + } + + self.itemContainers[i].updateDimNode(presentationData: presentationData, size: CGSize(width: itemLayouts[i].size.width, height: navigationContainerFrame.size.height), transitionFraction: itemLayouts[i].alphaTransitionFraction, transition: transition) + + if let tip = itemLayouts[i].tip { + let tipTransition = transition + var animateTipIn = false + if tip.tipNode.supernode == nil { + self.addSubnode(tip.tipNode) + animateTipIn = transition.isAnimated + let tipFrame = CGRect(origin: CGPoint(x: previousNavigationContainerFrame.minX, y: previousNavigationContainerFrame.maxY + tipSpacing), size: CGSize(width: itemLayouts[i].size.width, height: tip.tipHeight)) + tip.tipNode.frame = tipFrame + tip.tipNode.setActualSize(size: tipFrame.size, transition: .immediate) + } + + let tipAlpha: CGFloat = itemLayouts[i].alphaTransitionFraction + + let tipFrame = CGRect(origin: CGPoint(x: navigationContainerFrame.minX, y: navigationContainerFrame.maxY + tipSpacing), size: CGSize(width: itemLayouts[i].size.width, height: tip.tipHeight)) + tipTransition.updateFrame(node: tip.tipNode, frame: tipFrame, beginWithCurrentState: true) + + tip.tipNode.setActualSize(size: tip.tipNode.bounds.size, transition: tipTransition) + + if animateTipIn { + tip.tipNode.alpha = 0.0 + ComponentTransition.easeInOut(duration: 0.2).setAlpha(view: tip.tipNode.view, alpha: 1.0) + } else { + ComponentTransition(tipTransition).setAlpha(view: tip.tipNode.view, alpha: tipAlpha) + } + + if i == self.itemContainers.count - 1 { + topItemSize.height += tipSpacing + tip.tipHeight + } + } + } + + for (itemContainer, isPopped) in self.dismissingItemContainers { + var position = itemContainer.position + if isPopped { + position.x = itemContainer.bounds.width / 2.0 + topItemWidth + } else { + position.x = itemContainer.bounds.width / 2.0 - topItemWidth + } + transition.updatePosition(node: itemContainer, position: position, completion: { [weak itemContainer] _ in + itemContainer?.removeFromSupernode() + }) + if let tipNode = itemContainer.tipNode { + let tipFrame = CGRect(origin: CGPoint(x: navigationContainerFrame.minX, y: navigationContainerFrame.maxY + tipSpacing), size: tipNode.frame.size) + ComponentTransition(transition).setFrame(view: tipNode.view, frame: tipFrame) + + ComponentTransition(transition).setAlpha(view: tipNode.view, alpha: 0.01, completion: { [weak tipNode] _ in + tipNode?.removeFromSupernode() + }) + } + } + self.dismissingItemContainers.removeAll() + + return CGSize(width: topItemWidth, height: topItemSize.height) + } + + public func highlightGestureMoved(location: CGPoint) { + if let topItemContainer = self.itemContainers.last { + topItemContainer.highlightGestureMoved(location: self.view.convert(location, to: topItemContainer.view)) + } + } + + public func highlightGestureFinished(performAction: Bool) { + if let topItemContainer = self.itemContainers.last { + topItemContainer.highlightGestureFinished(performAction: performAction) + } + } + + public func decreaseHighlightedIndex() { + if let topItemContainer = self.itemContainers.last { + topItemContainer.decreaseHighlightedIndex() + } + } + + public func increaseHighlightedIndex() { + if let topItemContainer = self.itemContainers.last { + topItemContainer.increaseHighlightedIndex() + } + } + + public func updatePanSelection(isEnabled: Bool) { + if let selectionPanGesture = self.selectionPanGesture { + selectionPanGesture.isEnabled = isEnabled + } + } + + public func animateIn() { + for itemContainer in self.itemContainers { + if let tipNode = itemContainer.tipNode { + tipNode.animateIn() + } + } + } + + func animateIn(fromExtractableContainer extractableContainer: ContextExtractableContainer, transition: ComponentTransition) { + self.navigationContainer.animateIn(fromExtractableContainer: extractableContainer, transition: transition) + } + + func animateOut(toExtractableContainer extractableContainer: ContextExtractableContainer, transition: ComponentTransition) { + self.navigationContainer.animateOut(toExtractableContainer: extractableContainer, transition: transition) + } + + func didAnimateOut(toExtractableContainer extractableContainer: ContextExtractableContainer) { + self.navigationContainer.didAnimateOut(toExtractableContainer: extractableContainer) + } +} diff --git a/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextControllerCompatibility.swift b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextControllerCompatibility.swift new file mode 100644 index 00000000..4e02eb0a --- /dev/null +++ b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextControllerCompatibility.swift @@ -0,0 +1,6 @@ +import ContextUI + +public typealias ContextControllerImpl = ContextController +public typealias ContextControllerActionsStackNodeImpl = ContextControllerActionsStackNode +public typealias PeekControllerImpl = PeekController +public typealias PinchControllerImpl = PinchController diff --git a/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextControllerExtractedPresentationNode.swift b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextControllerExtractedPresentationNode.swift new file mode 100644 index 00000000..d7b3b69b --- /dev/null +++ b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextControllerExtractedPresentationNode.swift @@ -0,0 +1,1835 @@ +import Foundation +import UIKit +import AsyncDisplayKit +import Display +import TelegramPresentationData +import TextSelectionNode +import TelegramCore +import SwiftSignalKit +import ReactionSelectionNode +import UndoUI +import AccountContext +import ContextUI +import ComponentFlow +import ComponentDisplayAdapters + +private extension ContextControllerTakeViewInfo.ContainingItem { + var contentRect: CGRect { + switch self { + case let .node(containingNode): + return containingNode.contentRect + case let .view(containingView): + return containingView.contentRect + } + } + + var customHitTest: ((CGPoint) -> UIView?)? { + switch self { + case let .node(containingNode): + return containingNode.contentNode.customHitTest + case let .view(containingView): + return containingView.contentView.customHitTest + } + } + + var view: UIView { + switch self { + case let .node(containingNode): + return containingNode.view + case let .view(containingView): + return containingView + } + } + + var contentView: UIView { + switch self { + case let .node(containingNode): + return containingNode.contentNode.view + case let .view(containingView): + return containingView.contentView + } + } + + func contentHitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + switch self { + case let .node(containingNode): + return containingNode.contentNode.hitTest(point, with: event) + case let .view(containingView): + return containingView.contentView.hitTest(point, with: event) + } + } + + var isExtractedToContextPreview: Bool { + get { + switch self { + case let .node(containingNode): + return containingNode.isExtractedToContextPreview + case let .view(containingView): + return containingView.isExtractedToContextPreview + } + } set(value) { + switch self { + case let .node(containingNode): + containingNode.isExtractedToContextPreview = value + case let .view(containingView): + containingView.isExtractedToContextPreview = value + } + } + } + + var willUpdateIsExtractedToContextPreview: ((Bool, ContainedViewLayoutTransition) -> Void)? { + switch self { + case let .node(containingNode): + return containingNode.willUpdateIsExtractedToContextPreview + case let .view(containingView): + return containingView.willUpdateIsExtractedToContextPreview + } + } + + var isExtractedToContextPreviewUpdated: ((Bool) -> Void)? { + switch self { + case let .node(containingNode): + return containingNode.isExtractedToContextPreviewUpdated + case let .view(containingView): + return containingView.isExtractedToContextPreviewUpdated + } + } + + var onDismiss: (() -> Void)? { + switch self { + case let .node(containingNode): + return containingNode.onDismiss + case let .view(containingView): + return containingView.onDismiss + } + } + + var layoutUpdated: ((CGSize, ListViewItemUpdateAnimation) -> Void)? { + get { + switch self { + case let .node(containingNode): + return containingNode.layoutUpdated + case let .view(containingView): + return containingView.layoutUpdated + } + } set(value) { + switch self { + case let .node(containingNode): + containingNode.layoutUpdated = value + case let .view(containingView): + containingView.layoutUpdated = value + } + } + } +} + +final class ContextControllerExtractedPresentationNode: ASDisplayNode, ContextControllerPresentationNode, ASScrollViewDelegate { + enum ContentSource { + case location(ContextLocationContentSource) + case reference(ContextReferenceContentSource) + case extracted(ContextExtractedContentSource) + case controller(ContextControllerContentSource) + } + + private final class ItemContentNode: ASDisplayNode { + let offsetContainerNode: ASDisplayNode + var containingItem: ContextControllerTakeViewInfo.ContainingItem + + var animateClippingFromContentAreaInScreenSpace: CGRect? + var storedGlobalFrame: CGRect? + var storedGlobalBoundsFrame: CGRect? + + init(containingItem: ContextControllerTakeViewInfo.ContainingItem) { + self.offsetContainerNode = ASDisplayNode() + self.containingItem = containingItem + + super.init() + + self.addSubnode(self.offsetContainerNode) + } + + func update(presentationData: PresentationData, size: CGSize, transition: ContainedViewLayoutTransition) { + } + + func takeContainingNode() { + switch self.containingItem { + case let .node(containingNode): + if containingNode.contentNode.supernode !== self.offsetContainerNode { + self.offsetContainerNode.addSubnode(containingNode.contentNode) + } + case let .view(containingView): + if containingView.contentView.superview !== self.offsetContainerNode.view { + self.offsetContainerNode.view.addSubview(containingView.contentView) + } + } + } + + override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + if !self.bounds.contains(point) { + return nil + } + if !self.containingItem.contentRect.contains(point) { + return nil + } + return self.view + } + } + + private final class ControllerContentNode: ASDisplayNode { + let controller: ViewController + let passthroughTouches: Bool + var storedContentHeight: CGFloat? + + init(controller: ViewController, passthroughTouches: Bool) { + self.controller = controller + self.passthroughTouches = passthroughTouches + + super.init() + + self.clipsToBounds = true + self.cornerRadius = 30.0 + + self.addSubnode(self.controller.displayNode) + } + + func update(presentationData: PresentationData, parentLayout: ContainerViewLayout, size: CGSize, transition: ContainedViewLayoutTransition) { + transition.updateFrame(node: self.controller.displayNode, frame: CGRect(origin: CGPoint(), size: size)) + guard self.controller.navigationController == nil else { + return + } + self.controller.containerLayoutUpdated( + ContainerViewLayout( + size: size, + metrics: LayoutMetrics(widthClass: .compact, heightClass: .compact, orientation: nil), + deviceMetrics: parentLayout.deviceMetrics, + intrinsicInsets: UIEdgeInsets(), + safeInsets: UIEdgeInsets(), + additionalInsets: UIEdgeInsets(), + statusBarHeight: nil, + inputHeight: nil, + inputHeightIsInteractivellyChanging: false, + inVoiceOver: false + ), + transition: transition + ) + } + + override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + if !self.bounds.contains(point) { + return nil + } + if self.passthroughTouches { + let controllerPoint = self.view.convert(point, to: self.controller.view) + if let result = self.controller.view.hitTest(controllerPoint, with: event) { + return result + } + } + return self.view + } + } + + private final class AnimatingOutState { + var currentContentScreenFrame: CGRect + + init( + currentContentScreenFrame: CGRect + ) { + self.currentContentScreenFrame = currentContentScreenFrame + } + } + + private let _ready = Promise() + private var didSetReady: Bool = false + var ready: Signal { + return self._ready.get() + } + + private let context: AccountContext? + private let getController: () -> ContextControllerProtocol? + private let requestUpdate: (ContainedViewLayoutTransition) -> Void + private let requestUpdateOverlayWantsToBeBelowKeyboard: (ContainedViewLayoutTransition) -> Void + private let requestDismiss: (ContextMenuActionResult) -> Void + private let requestAnimateOut: (ContextMenuActionResult, @escaping () -> Void) -> Void + private let source: ContentSource + + private let dismissTapNode: ASDisplayNode + private let dismissAccessibilityArea: AccessibilityAreaNode + private let clippingNode: ASDisplayNode + private let scroller: UIScrollView + private let scrollNode: ASDisplayNode + + private var reactionContextNode: ReactionContextNode? + private var reactionPreviewView: ReactionPreviewView? + private var reactionContextNodeIsAnimatingOut: Bool = false + + private var itemContentNode: ItemContentNode? + private var controllerContentNode: ControllerContentNode? + private let contentRectDebugNode: ASDisplayNode + + private var actionsContainerNode: ASDisplayNode + private let actionsStackNode: ContextControllerActionsStackNodeImpl + private let additionalActionsStackNode: ContextControllerActionsStackNode + + private var validLayout: ContainerViewLayout? + private var animatingOutState: AnimatingOutState? + + private var strings: PresentationStrings? + + private enum OverscrollMode { + case unrestricted + case topOnly + case disabled + } + + private var overscrollMode: OverscrollMode = .unrestricted + + private weak var currentUndoController: ViewController? + + init( + context: AccountContext?, + getController: @escaping () -> ContextControllerProtocol?, + requestUpdate: @escaping (ContainedViewLayoutTransition) -> Void, + requestUpdateOverlayWantsToBeBelowKeyboard: @escaping (ContainedViewLayoutTransition) -> Void, + requestDismiss: @escaping (ContextMenuActionResult) -> Void, + requestAnimateOut: @escaping (ContextMenuActionResult, @escaping () -> Void) -> Void, + source: ContentSource + ) { + self.context = context + self.getController = getController + self.requestUpdate = requestUpdate + self.requestUpdateOverlayWantsToBeBelowKeyboard = requestUpdateOverlayWantsToBeBelowKeyboard + self.requestDismiss = requestDismiss + self.requestAnimateOut = requestAnimateOut + self.source = source + + self.dismissTapNode = ASDisplayNode() + + self.dismissAccessibilityArea = AccessibilityAreaNode() + self.dismissAccessibilityArea.accessibilityTraits = .button + + self.clippingNode = ASDisplayNode() + self.clippingNode.clipsToBounds = true + + self.scroller = UIScrollView() + self.scroller.canCancelContentTouches = true + self.scroller.delaysContentTouches = false + self.scroller.showsVerticalScrollIndicator = false + if #available(iOS 11.0, *) { + self.scroller.contentInsetAdjustmentBehavior = .never + } + self.scroller.alwaysBounceVertical = true + + self.scrollNode = ASDisplayNode() + self.scrollNode.view.addGestureRecognizer(self.scroller.panGestureRecognizer) + + self.contentRectDebugNode = ASDisplayNode() + self.contentRectDebugNode.isUserInteractionEnabled = false + self.contentRectDebugNode.backgroundColor = UIColor.red.withAlphaComponent(0.2) + + self.actionsContainerNode = ASDisplayNode() + self.actionsStackNode = ContextControllerActionsStackNodeImpl( + context: self.context, + getController: getController, + requestDismiss: { result in + requestDismiss(result) + }, + requestUpdate: requestUpdate + ) + + self.additionalActionsStackNode = ContextControllerActionsStackNodeImpl( + context: self.context, + getController: getController, + requestDismiss: { result in + requestDismiss(result) + }, + requestUpdate: requestUpdate + ) + + super.init() + + self.view.addSubview(self.scroller) + self.scroller.isHidden = true + + self.addSubnode(self.clippingNode) + self.clippingNode.addSubnode(self.scrollNode) + self.scrollNode.addSubnode(self.dismissTapNode) + self.scrollNode.addSubnode(self.dismissAccessibilityArea) + self.scrollNode.addSubnode(self.actionsContainerNode) + self.actionsContainerNode.addSubnode(self.additionalActionsStackNode) + self.actionsContainerNode.addSubnode(self.actionsStackNode) + + #if DEBUG + //self.addSubnode(self.contentRectDebugNode) + #endif + + self.scroller.delegate = self.wrappedScrollViewDelegate + + self.dismissTapNode.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dismissTapGesture(_:)))) + + self.dismissAccessibilityArea.activate = { [weak self] in + self?.requestDismiss(.default) + + return true + } + } + + @objc func dismissTapGesture(_ recognizer: UITapGestureRecognizer) { + if case .ended = recognizer.state { + self.requestDismiss(.default) + } + } + + override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + if self.bounds.contains(point) { + if let reactionContextNode = self.reactionContextNode { + if let result = reactionContextNode.hitTest(self.view.convert(point, to: reactionContextNode.view), with: event) { + return result + } + } + + if case let .extracted(source) = self.source, !source.ignoreContentTouches, let contentNode = self.itemContentNode { + let contentPoint = self.view.convert(point, to: contentNode.containingItem.contentView) + if let result = contentNode.containingItem.customHitTest?(contentPoint) { + return result + } else if let result = contentNode.containingItem.contentHitTest(contentPoint, with: event) { + if source.keepDefaultContentTouches { + return result + } else if result is TextSelectionNodeView { + return result + } else if contentNode.containingItem.contentRect.contains(contentPoint) { + return contentNode.containingItem.contentView + } + } + } else if case .controller = self.source, let contentNode = self.controllerContentNode { + let contentPoint = self.view.convert(point, to: contentNode.view) + let _ = contentPoint + //TODO: + } + + if let result = self.scrollNode.hitTest(self.view.convert(point, to: self.scrollNode.view), with: event) { + if let reactionContextNode = self.reactionContextNode, reactionContextNode.isExpanded { + if result === self.actionsContainerNode.view { + return self.dismissTapNode.view + } + } + return result + } + + return nil + } else { + return nil + } + } + + func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { + if let reactionContextNode = self.reactionContextNode, (reactionContextNode.isExpanded || !reactionContextNode.canBeExpanded) { + self.overscrollMode = .disabled + self.scroller.alwaysBounceVertical = false + } else { + if scrollView.contentSize.height > scrollView.bounds.height { + self.overscrollMode = .unrestricted + self.scroller.alwaysBounceVertical = true + } else { + if self.reactionContextNode != nil { + self.overscrollMode = .topOnly + self.scroller.alwaysBounceVertical = true + } else { + self.overscrollMode = .disabled + self.scroller.alwaysBounceVertical = false + } + } + } + } + + func scrollViewDidScroll(_ scrollView: UIScrollView) { + var adjustedBounds = scrollView.bounds + var topOverscroll: CGFloat = 0.0 + + switch self.overscrollMode { + case .unrestricted: + if adjustedBounds.origin.y < 0.0 { + topOverscroll = -adjustedBounds.origin.y + } + case .disabled: + break + case .topOnly: + if scrollView.contentSize.height <= scrollView.bounds.height { + if adjustedBounds.origin.y > 0.0 { + adjustedBounds.origin.y = 0.0 + } else { + adjustedBounds.origin.y = floorToScreenPixels(adjustedBounds.origin.y * 0.35) + topOverscroll = -adjustedBounds.origin.y + } + } else { + if adjustedBounds.origin.y < 0.0 { + adjustedBounds.origin.y = floorToScreenPixels(adjustedBounds.origin.y * 0.35) + topOverscroll = -adjustedBounds.origin.y + } else if adjustedBounds.origin.y + adjustedBounds.height > scrollView.contentSize.height { + adjustedBounds.origin.y = scrollView.contentSize.height - adjustedBounds.height + } + } + } + self.scrollNode.bounds = adjustedBounds + + if let reactionContextNode = self.reactionContextNode { + let isIntersectingContent = adjustedBounds.minY >= 10.0 + reactionContextNode.updateIsIntersectingContent(isIntersectingContent: isIntersectingContent, transition: .animated(duration: 0.25, curve: .easeInOut)) + + if !reactionContextNode.isExpanded && reactionContextNode.canBeExpanded { + if topOverscroll > 30.0 && self.scroller.isTracking { + self.scroller.panGestureRecognizer.state = .cancelled + reactionContextNode.expand() + } else { + reactionContextNode.updateExtension(distance: topOverscroll) + } + } + } + } + + func highlightGestureMoved(location: CGPoint, hover: Bool) { + self.actionsStackNode.highlightGestureMoved(location: self.view.convert(location, to: self.actionsStackNode.view)) + + if let reactionContextNode = self.reactionContextNode { + reactionContextNode.highlightGestureMoved(location: self.view.convert(location, to: reactionContextNode.view), hover: hover) + } + } + + func highlightGestureFinished(performAction: Bool) { + self.actionsStackNode.highlightGestureFinished(performAction: performAction) + + if let reactionContextNode = self.reactionContextNode { + reactionContextNode.highlightGestureFinished(performAction: performAction) + } + } + + func decreaseHighlightedIndex() { + self.actionsStackNode.decreaseHighlightedIndex() + } + + func increaseHighlightedIndex() { + self.actionsStackNode.increaseHighlightedIndex() + } + + func wantsDisplayBelowKeyboard() -> Bool { + if let reactionContextNode = self.reactionContextNode { + return reactionContextNode.wantsDisplayBelowKeyboard() + } else if case let .reference(source) = self.source { + return source.forceDisplayBelowKeyboard + } else { + return false + } + } + + func replaceItems(items: ContextController.Items, animated: Bool?) { + if case .twoLists = items.content { + let stackItems = makeContextControllerActionsStackItem(items: items) + self.actionsStackNode.replace(item: stackItems.first!, animated: animated) + self.additionalActionsStackNode.replace(item: stackItems.last!, animated: animated) + } else { + self.actionsStackNode.replace(item: makeContextControllerActionsStackItem(items: items).first!, animated: animated) + } + } + + func pushItems(items: ContextController.Items) { + let currentScrollingState = self.getCurrentScrollingState() + var positionLock: CGFloat? + if !items.disablePositionLock { + positionLock = self.getActionsStackPositionLock() + } + if self.actionsStackNode.topPositionLock == nil { + if let contentNode = self.controllerContentNode, contentNode.bounds.height != 0.0 { + contentNode.storedContentHeight = contentNode.bounds.height + } + } + self.actionsStackNode.push(item: makeContextControllerActionsStackItem(items: items).first!, currentScrollingState: currentScrollingState, positionLock: positionLock, animated: true) + } + + func popItems() { + self.actionsStackNode.pop() + if self.actionsStackNode.topPositionLock == nil { + if let contentNode = self.controllerContentNode { + contentNode.storedContentHeight = nil + } + } + } + + private func getCurrentScrollingState() -> CGFloat { + return self.scrollNode.bounds.minY + } + + private func getActionsStackPositionLock() -> CGFloat? { + switch self.source { + case .location, .reference: + return nil + case .extracted, .controller: + return self.actionsStackNode.view.convert(CGPoint(), to: self.view).y + } + } + + private var proposedReactionsPositionLock: CGFloat? + private var currentReactionsPositionLock: CGFloat? + + private func setCurrentReactionsPositionLock() { + self.currentReactionsPositionLock = self.proposedReactionsPositionLock + } + + private func getCurrentReactionsPositionLock() -> CGFloat? { + return self.currentReactionsPositionLock + } + + func update( + presentationData: PresentationData, + layout: ContainerViewLayout, + transition: ContainedViewLayoutTransition, + stateTransition: ContextControllerPresentationNodeStateTransition? + ) { + self.validLayout = layout + + var contentActionsSpacing: CGFloat = 7.0 + let actionsEdgeInset: CGFloat + let actionsSideInset: CGFloat + let topInset: CGFloat = layout.insets(options: .statusBar).top + 8.0 + var bottomInset: CGFloat = 10.0 + + let itemContentNode: ItemContentNode? + let controllerContentNode: ControllerContentNode? + var contentTransition = transition + + if self.strings !== presentationData.strings { + self.strings = presentationData.strings + + self.dismissAccessibilityArea.accessibilityLabel = presentationData.strings.VoiceOver_DismissContextMenu + } + + switch self.source { + case .location, .reference: + actionsEdgeInset = 16.0 + actionsSideInset = 6.0 + case .extracted: + actionsEdgeInset = 12.0 + actionsSideInset = 6.0 + case .controller: + actionsEdgeInset = 12.0 + actionsSideInset = -2.0 + contentActionsSpacing += 3.0 + } + + transition.updateFrame(node: self.clippingNode, frame: CGRect(origin: CGPoint(), size: layout.size), beginWithCurrentState: true) + if self.scrollNode.frame != CGRect(origin: CGPoint(), size: layout.size) { + transition.updateFrame(node: self.scrollNode, frame: CGRect(origin: CGPoint(), size: layout.size), beginWithCurrentState: true) + transition.updateFrame(view: self.scroller, frame: CGRect(origin: CGPoint(), size: layout.size), beginWithCurrentState: true) + } + + if let current = self.itemContentNode { + itemContentNode = current + } else { + switch self.source { + case .location, .reference, .controller: + itemContentNode = nil + case let .extracted(source): + guard let takeInfo = source.takeView() else { + return + } + let contentNodeValue = ItemContentNode(containingItem: takeInfo.containingItem) + contentNodeValue.animateClippingFromContentAreaInScreenSpace = takeInfo.contentAreaInScreenSpace + self.scrollNode.insertSubnode(contentNodeValue, aboveSubnode: self.actionsContainerNode) + self.itemContentNode = contentNodeValue + itemContentNode = contentNodeValue + contentTransition = .immediate + } + } + + if let current = self.controllerContentNode { + controllerContentNode = current + } else { + switch self.source { + case let .controller(source): + let controllerContentNodeValue = ControllerContentNode(controller: source.controller, passthroughTouches: source.passthroughTouches) + + //source.controller.viewWillAppear(false) + //source.controller.setIgnoreAppearanceMethodInvocations(true) + + self.scrollNode.insertSubnode(controllerContentNodeValue, aboveSubnode: self.actionsContainerNode) + self.controllerContentNode = controllerContentNodeValue + controllerContentNode = controllerContentNodeValue + contentTransition = .immediate + + //source.controller.setIgnoreAppearanceMethodInvocations(false) + //source.controller.viewDidAppear(false) + case .location, .reference, .extracted: + controllerContentNode = nil + } + } + + var animateReactionsIn = false + var contentTopInset: CGFloat = topInset + var removedReactionContextNode: ReactionContextNode? + + if let reactionItems = self.actionsStackNode.topReactionItems, !reactionItems.reactionItems.isEmpty, let controller = self.getController() as? ContextControllerImpl { + let reactionContextNode: ReactionContextNode + if let current = self.reactionContextNode { + reactionContextNode = current + } else { + reactionContextNode = ReactionContextNode( + context: reactionItems.context, + animationCache: reactionItems.animationCache, + presentationData: presentationData, + //style: .glass(isTinted: false), + items: reactionItems.reactionItems, + selectedItems: reactionItems.selectedReactionItems, + title: reactionItems.reactionsTitle, + reactionsLocked: reactionItems.reactionsLocked, + alwaysAllowPremiumReactions: reactionItems.alwaysAllowPremiumReactions, + allPresetReactionsAreAvailable: reactionItems.allPresetReactionsAreAvailable, + getEmojiContent: reactionItems.getEmojiContent, + isExpandedUpdated: { [weak self] transition in + guard let strongSelf = self else { + return + } + strongSelf.setCurrentReactionsPositionLock() + strongSelf.requestUpdate(transition) + }, + requestLayout: { [weak self] transition in + guard let strongSelf = self else { + return + } + strongSelf.requestUpdate(transition) + }, + requestUpdateOverlayWantsToBeBelowKeyboard: { [weak self] transition in + guard let strongSelf = self else { + return + } + strongSelf.requestUpdateOverlayWantsToBeBelowKeyboard(transition) + } + ) + reactionContextNode.displayTail = !controller.hideReactionPanelTail + self.reactionContextNode = reactionContextNode + self.addSubnode(reactionContextNode) + + if transition.isAnimated { + animateReactionsIn = true + } + + reactionContextNode.reactionSelected = { [weak self] reaction, isLarge in + guard let strongSelf = self, let controller = strongSelf.getController() as? ContextControllerImpl else { + return + } + controller.reactionSelected?(reaction, isLarge) + } + let context = reactionItems.context + reactionContextNode.premiumReactionsSelected = { [weak self] file in + guard let strongSelf = self, let validLayout = strongSelf.validLayout, let controller = strongSelf.getController() as? ContextControllerImpl else { + return + } + + if let reactionItems = strongSelf.actionsStackNode.topReactionItems, !reactionItems.reactionItems.isEmpty { + if reactionItems.allPresetReactionsAreAvailable { + controller.premiumReactionsSelected?() + return + } + } + + if let file = file, let reactionContextNode = strongSelf.reactionContextNode { + let position: UndoOverlayController.Position + let insets = validLayout.insets(options: .statusBar) + if reactionContextNode.hasSpaceInTheBottom(insets: insets, height: 100.0) { + position = .bottom + } else { + position = .top + } + + var animateInAsReplacement = false + if let currentUndoController = strongSelf.currentUndoController { + currentUndoController.dismiss() + animateInAsReplacement = true + } + + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + let undoController = UndoOverlayController(presentationData: presentationData, content: .sticker(context: context, file: file, loop: true, title: nil, text: presentationData.strings.Chat_PremiumReactionToastTitle, undoText: presentationData.strings.Chat_PremiumReactionToastAction, customAction: { [weak controller] in + controller?.premiumReactionsSelected?() + }), elevatedLayout: false, position: position, animateInAsReplacement: animateInAsReplacement, action: { _ in true }) + strongSelf.currentUndoController = undoController + controller.present(undoController, in: .current) + } else { + controller.premiumReactionsSelected?() + } + } + + reactionContextNode.updateLayout(size: layout.size, insets: UIEdgeInsets(top: topInset, left: layout.safeInsets.left, bottom: 0.0, right: layout.safeInsets.right), anchorRect: CGRect(origin: CGPoint(x: 0.0, y: layout.size.height), size: CGSize(width: 1.0, height: 1.0)), isCoveredByInput: false, isAnimatingOut: false, transition: .immediate) + } + contentTopInset += reactionContextNode.contentHeight + 18.0 + } else if let reactionContextNode = self.reactionContextNode { + self.reactionContextNode = nil + removedReactionContextNode = reactionContextNode + } + + let reactionPreviewSize = CGSize(width: 100.0, height: 100.0) + let reactionPreviewInset: CGFloat = 7.0 + var removedReactionPreviewView: ReactionPreviewView? + if self.reactionContextNode == nil, let previewReaction = self.actionsStackNode.topPreviewReaction { + let reactionPreviewView: ReactionPreviewView + if let current = self.reactionPreviewView { + reactionPreviewView = current + } else { + reactionPreviewView = ReactionPreviewView(context: previewReaction.context, file: previewReaction.file) + self.reactionPreviewView = reactionPreviewView + self.view.addSubview(reactionPreviewView) + } + + contentTopInset += reactionPreviewSize.height + reactionPreviewInset + } else { + removedReactionPreviewView = self.reactionPreviewView + self.reactionPreviewView = nil + } + + if let contentNode = itemContentNode { + switch stateTransition { + case .animateIn, .animateOut: + contentNode.storedGlobalFrame = convertFrame(contentNode.containingItem.contentRect, from: contentNode.containingItem.view, to: self.view) + + var rect = convertFrame(contentNode.containingItem.view.bounds, from: contentNode.containingItem.view, to: self.view) + if rect.origin.x < 0.0 { + rect.origin.x += layout.size.width + } + contentNode.storedGlobalBoundsFrame = rect + case .none: + if contentNode.storedGlobalFrame == nil { + contentNode.storedGlobalFrame = convertFrame(contentNode.containingItem.contentRect, from: contentNode.containingItem.view, to: self.view) + } + } + } + + var contentParentGlobalFrame: CGRect + var contentRect: CGRect + var isContentResizeableVertically: Bool = false + let _ = isContentResizeableVertically + var contextExtractableContainer: (container: ContextExtractableContainer, sourceRect: CGRect)? + + switch self.source { + case let .location(location): + if let transitionInfo = location.transitionInfo() { + contentRect = CGRect(origin: transitionInfo.location, size: CGSize(width: 1.0, height: 1.0)) + contentParentGlobalFrame = CGRect(origin: CGPoint(x: 0.0, y: contentRect.minY), size: CGSize(width: layout.size.width, height: contentRect.height)) + } else { + return + } + case let .reference(reference): + if let transitionInfo = reference.transitionInfo() { + if let referenceView = transitionInfo.referenceView as? ContextExtractableContainer { + contextExtractableContainer = (referenceView, convertFrame(transitionInfo.referenceView.bounds.inset(by: transitionInfo.insets), from: transitionInfo.referenceView, to: self.view)) + } + + contentRect = convertFrame(transitionInfo.referenceView.bounds.inset(by: transitionInfo.insets), from: transitionInfo.referenceView, to: self.view).insetBy(dx: -2.0, dy: 0.0) + contentRect.size.width += 5.0 + contentParentGlobalFrame = CGRect(origin: CGPoint(x: 0.0, y: contentRect.minY), size: CGSize(width: layout.size.width, height: contentRect.height)) + } else { + return + } + case .extracted: + if let contentNode = itemContentNode { + contentParentGlobalFrame = convertFrame(contentNode.containingItem.view.bounds, from: contentNode.containingItem.view, to: self.view) + if let frame = contentNode.storedGlobalBoundsFrame { + contentParentGlobalFrame.origin.x = frame.minX + } + let contentRectGlobalFrame = CGRect(origin: CGPoint(x: contentNode.containingItem.contentRect.minX, y: (contentNode.storedGlobalFrame?.maxY ?? 0.0) - contentNode.containingItem.contentRect.height), size: contentNode.containingItem.contentRect.size) + contentRect = CGRect(origin: CGPoint(x: contentRectGlobalFrame.minX, y: contentRectGlobalFrame.maxY - contentNode.containingItem.contentRect.size.height), size: contentNode.containingItem.contentRect.size) + if case .animateOut = stateTransition { + contentRect.origin.y = self.contentRectDebugNode.frame.maxY - contentRect.size.height + } + } else { + return + } + case let .controller(source): + if let contentNode = controllerContentNode { + var defaultContentSize = CGSize(width: layout.size.width - 12.0 * 2.0, height: layout.size.height - 12.0 * 2.0 - contentTopInset - layout.safeInsets.bottom) + if case .regular = layout.metrics.widthClass { + defaultContentSize.width = min(defaultContentSize.width, 400.0) + } + defaultContentSize.height = min(defaultContentSize.height, 460.0) + + let contentSize: CGSize + if let preferredSize = contentNode.controller.preferredContentSizeForLayout(ContainerViewLayout(size: defaultContentSize, metrics: LayoutMetrics(widthClass: .compact, heightClass: .compact, orientation: nil), deviceMetrics: layout.deviceMetrics, intrinsicInsets: UIEdgeInsets(), safeInsets: UIEdgeInsets(), additionalInsets: UIEdgeInsets(), statusBarHeight: nil, inputHeight: nil, inputHeightIsInteractivellyChanging: false, inVoiceOver: false)) { + contentSize = preferredSize + } else if let storedContentHeight = contentNode.storedContentHeight { + contentSize = CGSize(width: defaultContentSize.width, height: storedContentHeight) + } else { + contentSize = defaultContentSize + isContentResizeableVertically = true + } + + if case .regular = layout.metrics.widthClass { + if let transitionInfo = source.transitionInfo(), let (sourceView, sourceRect) = transitionInfo.sourceNode() { + let sourcePoint = sourceView.convert(sourceRect.center, to: self.view) + + contentRect = CGRect(origin: CGPoint(x: sourcePoint.x - floor(contentSize.width * 0.5), y: sourcePoint.y - floor(contentSize.height * 0.5)), size: contentSize) + if contentRect.origin.x < 0.0 { + contentRect.origin.x = 0.0 + } + if contentRect.origin.y < 0.0 { + contentRect.origin.y = 0.0 + } + if contentRect.origin.x + contentRect.width > layout.size.width { + contentRect.origin.x = layout.size.width - contentRect.width + } + if contentRect.origin.y + contentRect.height > layout.size.height { + contentRect.origin.y = layout.size.height - contentRect.height + } + } else { + contentRect = CGRect(origin: CGPoint(x: floor((layout.size.width - contentSize.width) * 0.5), y: floor((layout.size.height - contentSize.height) * 0.5)), size: contentSize) + } + } else { + contentRect = CGRect(origin: CGPoint(x: floor((layout.size.width - contentSize.width) * 0.5), y: floor((layout.size.height - contentSize.height) * 0.5)), size: contentSize) + } + + contentParentGlobalFrame = CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: layout.size.width, height: layout.size.height)) + } else { + return + } + } + + var contentParentGlobalFrameOffsetX: CGFloat = 0.0 + if case let .extracted(extracted) = self.source, extracted.adjustContentForSideInset { + let contentSideInset: CGFloat = actionsSideInset + 6.0 + + var updatedFrame = contentParentGlobalFrame + if updatedFrame.origin.x + updatedFrame.width > layout.size.width - contentSideInset { + updatedFrame.origin.x = layout.size.width - contentSideInset - updatedFrame.width + } + if updatedFrame.origin.x < contentSideInset { + updatedFrame.origin.x = contentSideInset + } + + contentParentGlobalFrameOffsetX = updatedFrame.minX - contentParentGlobalFrame.minX + contentParentGlobalFrame = updatedFrame + } + + let keepInPlace: Bool + let actionsHorizontalAlignment: ContextActionsHorizontalAlignment + switch self.source { + case .location, .reference: + keepInPlace = true + actionsHorizontalAlignment = .default + case let .extracted(source): + keepInPlace = source.keepInPlace + actionsHorizontalAlignment = source.actionsHorizontalAlignment + bottomInset += source.additionalInsets.bottom + case .controller: + //TODO: + keepInPlace = false + actionsHorizontalAlignment = .default + } + + var defaultScrollY: CGFloat = 0.0 + if self.animatingOutState == nil { + if let contentNode = itemContentNode { + contentNode.update( + presentationData: presentationData, + size: contentNode.containingItem.view.bounds.size, + transition: contentTransition + ) + } + + let actionsConstrainedHeight: CGFloat + if let actionsPositionLock = self.actionsStackNode.topPositionLock { + actionsConstrainedHeight = layout.size.height - bottomInset - layout.intrinsicInsets.bottom - actionsPositionLock + } else { + if case let .reference(reference) = self.source, reference.keepInPlace { + actionsConstrainedHeight = layout.size.height - contentRect.maxY - contentActionsSpacing - bottomInset - layout.intrinsicInsets.bottom + } else { + actionsConstrainedHeight = layout.size.height - contentTopInset - contentRect.height - contentActionsSpacing - bottomInset - layout.intrinsicInsets.bottom + } + } + + let actionsStackPresentation: ContextControllerActionsStackNode.Presentation + switch self.source { + case .location, .reference, .controller: + actionsStackPresentation = .inline + case let .extracted(extracted): + if extracted.blurBackground { + actionsStackPresentation = .modal + } else { + actionsStackPresentation = .inline + } + } + + let additionalActionsSize = self.additionalActionsStackNode.update( + presentationData: presentationData, + constrainedSize: CGSize(width: layout.size.width, height: actionsConstrainedHeight), + presentation: .additional, + transition: transition + ) + self.additionalActionsStackNode.isHidden = additionalActionsSize.height.isZero + + let actionsSize = self.actionsStackNode.update( + presentationData: presentationData, + constrainedSize: CGSize(width: layout.size.width, height: actionsConstrainedHeight), + presentation: actionsStackPresentation, + transition: transition + ) + + if isContentResizeableVertically && self.actionsStackNode.topPositionLock == nil { + var contentHeight = layout.size.height - contentTopInset - contentActionsSpacing - bottomInset - layout.intrinsicInsets.bottom - actionsSize.height + contentHeight = min(contentHeight, contentRect.height) + contentHeight = max(contentHeight, 200.0) + + if case .regular = layout.metrics.widthClass { + } else { + contentRect = CGRect(origin: CGPoint(x: contentRect.minX, y: floor(contentRect.midY - contentHeight * 0.5)), size: CGSize(width: contentRect.width, height: contentHeight)) + } + } + + var isAnimatingOut = false + if case .animateOut = stateTransition { + isAnimatingOut = true + } else { + if let currentReactionsPositionLock = self.currentReactionsPositionLock, let reactionContextNode = self.reactionContextNode { + contentRect.origin.y = currentReactionsPositionLock + reactionContextNode.contentHeight + 18.0 + reactionContextNode.visibleExtensionDistance + } else if let topPositionLock = self.actionsStackNode.topPositionLock { + contentRect.origin.y = topPositionLock - contentActionsSpacing - contentRect.height + } else if keepInPlace { + } else { + if contentRect.minY < contentTopInset { + contentRect.origin.y = contentTopInset + } + var combinedBounds = CGRect(origin: CGPoint(x: 0.0, y: contentRect.minY), size: CGSize(width: layout.size.width, height: contentRect.height + contentActionsSpacing + actionsSize.height)) + if combinedBounds.maxY > layout.size.height - bottomInset - layout.intrinsicInsets.bottom { + combinedBounds.origin.y = layout.size.height - bottomInset - layout.intrinsicInsets.bottom - combinedBounds.height + } + if combinedBounds.minY < contentTopInset { + combinedBounds.origin.y = contentTopInset + } + + contentRect.origin.y = combinedBounds.minY + } + } + + if let reactionContextNode = self.reactionContextNode { + var reactionContextNodeTransition = transition + if reactionContextNode.frame.isEmpty { + reactionContextNodeTransition = .immediate + } + reactionContextNodeTransition.updateFrame(node: reactionContextNode, frame: CGRect(origin: CGPoint(), size: layout.size), beginWithCurrentState: true) + + var reactionAnchorRect = contentRect.offsetBy(dx: contentParentGlobalFrame.minX, dy: 0.0) + + let bottomInset = layout.insets(options: [.input]).bottom + var isCoveredByInput = false + if reactionAnchorRect.minY > layout.size.height - bottomInset { + reactionAnchorRect.origin.y = layout.size.height - bottomInset + isCoveredByInput = true + } + + reactionContextNode.updateLayout(size: layout.size, insets: UIEdgeInsets(top: topInset, left: layout.safeInsets.left, bottom: 0.0, right: layout.safeInsets.right), anchorRect: reactionAnchorRect, isCoveredByInput: isCoveredByInput, isAnimatingOut: isAnimatingOut, transition: reactionContextNodeTransition) + + if reactionContextNode.alwaysAllowPremiumReactions { + self.proposedReactionsPositionLock = contentRect.minY - 18.0 - reactionContextNode.contentHeight + } else { + self.proposedReactionsPositionLock = contentRect.minY - 18.0 - reactionContextNode.contentHeight - (46.0 + 54.0 - 4.0) + } + } else { + self.proposedReactionsPositionLock = nil + } + + if let reactionPreviewView = self.reactionPreviewView { + let anchorRect = contentRect.offsetBy(dx: contentParentGlobalFrame.minX, dy: 0.0) + + let reactionPreviewFrame = CGRect(origin: CGPoint(x: floor((anchorRect.midX - reactionPreviewSize.width * 0.5)), y: anchorRect.minY - reactionPreviewInset - reactionPreviewSize.height), size: reactionPreviewSize) + transition.updateFrame(view: reactionPreviewView, frame: reactionPreviewFrame) + reactionPreviewView.update(size: reactionPreviewFrame.size) + } + + if let _ = self.currentReactionsPositionLock { + transition.updateAlpha(node: self.actionsStackNode, alpha: 0.0) + } else { + transition.updateAlpha(node: self.actionsStackNode, alpha: 1.0) + } + + if let removedReactionContextNode = removedReactionContextNode { + removedReactionContextNode.animateOut(to: contentRect, animatingOutToReaction: false) + transition.updateAlpha(node: removedReactionContextNode, alpha: 0.0, completion: { [weak removedReactionContextNode] _ in + removedReactionContextNode?.removeFromSupernode() + }) + } + + if let removedReactionPreviewView { + transition.updateAlpha(layer: removedReactionPreviewView.layer, alpha: 0.0, completion: { [weak removedReactionPreviewView] _ in + removedReactionPreviewView?.removeFromSuperview() + }) + } + + transition.updateFrame(node: self.contentRectDebugNode, frame: contentRect, beginWithCurrentState: true) + + var totalActionsHeight: CGFloat = actionsSize.height + if additionalActionsSize.height != 0.0 { + totalActionsHeight += 10.0 + additionalActionsSize.height + } + + var actionsFrame: CGRect + if let contextExtractableContainer { + let _ = contextExtractableContainer + actionsFrame = CGRect(origin: CGPoint(x: actionsSideInset, y: contentRect.minY), size: actionsSize) + } else if case let .reference(source) = self.source, let actionsPosition = source.transitionInfo()?.actionsPosition, case .top = actionsPosition { + actionsFrame = CGRect(origin: CGPoint(x: actionsSideInset, y: contentRect.minY - contentActionsSpacing - totalActionsHeight), size: actionsSize) + } else { + actionsFrame = CGRect(origin: CGPoint(x: actionsSideInset, y: contentRect.maxY + contentActionsSpacing), size: actionsSize) + } + var contentVerticalOffset: CGFloat = 0.0 + + if contextExtractableContainer == nil, keepInPlace, case .extracted = self.source { + actionsFrame.origin.y = contentRect.minY - contentActionsSpacing - actionsFrame.height + let statusBarHeight = (layout.statusBarHeight ?? 0.0) + if actionsFrame.origin.y < statusBarHeight { + let updatedActionsOriginY = statusBarHeight + contentActionsSpacing + let delta = updatedActionsOriginY - actionsFrame.origin.y + actionsFrame.origin.y = updatedActionsOriginY + contentVerticalOffset = delta + } + } + var additionalVisibleOffsetY: CGFloat = 0.0 + if let reactionContextNode = self.reactionContextNode { + additionalVisibleOffsetY += reactionContextNode.visibleExtensionDistance + } + if case .center = actionsHorizontalAlignment { + actionsFrame.origin.x = floor(contentParentGlobalFrame.minX + contentRect.midX - actionsFrame.width / 2.0) + if actionsFrame.maxX > layout.size.width - actionsEdgeInset { + actionsFrame.origin.x = layout.size.width - actionsEdgeInset - actionsFrame.width + } + if actionsFrame.minX < actionsEdgeInset { + actionsFrame.origin.x = actionsEdgeInset + } + } else { + if case .location = self.source { + actionsFrame.origin.x = contentParentGlobalFrame.minX + contentRect.minX + actionsSideInset - 4.0 + } else if case .right = actionsHorizontalAlignment { + actionsFrame.origin.x = contentParentGlobalFrame.minX + contentRect.maxX - actionsSideInset - actionsSize.width - 1.0 + } else { + if contentRect.midX < layout.size.width / 2.0 { + actionsFrame.origin.x = contentParentGlobalFrame.minX + contentRect.minX + actionsSideInset - 4.0 + } else { + switch self.source { + case .location, .reference: + actionsFrame.origin.x = floor(contentParentGlobalFrame.minX + contentRect.midX - actionsFrame.width / 2.0) + if actionsFrame.maxX > layout.size.width - actionsEdgeInset { + actionsFrame.origin.x = layout.size.width - actionsEdgeInset - actionsFrame.width + } + if actionsFrame.minX < actionsEdgeInset { + actionsFrame.origin.x = actionsEdgeInset + } + case .extracted: + actionsFrame.origin.x = contentParentGlobalFrame.minX + contentRect.maxX - actionsSideInset - actionsSize.width - 1.0 + case .controller: + //TODO: + actionsFrame.origin.x = contentParentGlobalFrame.minX + contentRect.maxX - actionsSideInset - actionsSize.width - 1.0 + } + } + } + if actionsFrame.maxX > layout.size.width - actionsEdgeInset { + actionsFrame.origin.x = layout.size.width - actionsEdgeInset - actionsFrame.width + } + if actionsFrame.minX < actionsEdgeInset { + actionsFrame.origin.x = actionsEdgeInset + } + } + + if case let .reference(reference) = self.source, let transitionInfo = reference.transitionInfo(), let customPosition = transitionInfo.customPosition { + actionsFrame = actionsFrame.offsetBy(dx: customPosition.x, dy: customPosition.y) + } + + var additionalActionsFrame: CGRect + let combinedActionsFrame: CGRect + if additionalActionsSize.height > 0.0 { + additionalActionsFrame = CGRect(origin: actionsFrame.origin, size: additionalActionsSize) + actionsFrame = actionsFrame.offsetBy(dx: 0.0, dy: additionalActionsSize.height + 10.0) + combinedActionsFrame = actionsFrame.union(additionalActionsFrame) + } else { + additionalActionsFrame = .zero + combinedActionsFrame = actionsFrame + } + + transition.updateFrame(node: self.actionsContainerNode, frame: combinedActionsFrame.offsetBy(dx: 0.0, dy: additionalVisibleOffsetY)) + transition.updateFrame(node: self.actionsStackNode, frame: CGRect(origin: CGPoint(x: 0.0, y: combinedActionsFrame.height - actionsSize.height), size: actionsSize), beginWithCurrentState: true) + transition.updateFrame(node: self.additionalActionsStackNode, frame: CGRect(origin: .zero, size: additionalActionsSize), beginWithCurrentState: true) + + if let contentNode = itemContentNode { + var contentFrame = CGRect(origin: CGPoint(x: contentParentGlobalFrame.minX + contentRect.minX - contentNode.containingItem.contentRect.minX, y: contentRect.minY - contentNode.containingItem.contentRect.minY + contentVerticalOffset + additionalVisibleOffsetY), size: contentNode.containingItem.view.bounds.size) + if case let .extracted(extracted) = self.source { + if extracted.adjustContentHorizontally { + contentFrame.origin.x = combinedActionsFrame.minX + if contentFrame.maxX > layout.size.width { + contentFrame.origin.x = layout.size.width - contentFrame.width - actionsEdgeInset + } + } + if extracted.centerVertically { + if combinedActionsFrame.height.isZero { + contentFrame.origin.y = floorToScreenPixels((layout.size.height - contentFrame.height) / 2.0) + } else if contentFrame.midX > layout.size.width / 2.0 { + contentFrame.origin.x = layout.size.width - contentFrame.maxX + } + } + } + contentTransition.updateFrame(node: contentNode, frame: contentFrame, beginWithCurrentState: true) + } + if let contentNode = controllerContentNode { + //TODO: + var contentFrame = CGRect(origin: CGPoint(x: contentRect.minX, y: contentRect.minY + contentVerticalOffset + additionalVisibleOffsetY), size: contentRect.size) + if case let .extracted(extracted) = self.source, extracted.centerVertically { + if combinedActionsFrame.height.isZero { + contentFrame.origin.y = floorToScreenPixels((layout.size.height - contentFrame.height) / 2.0) + } else if contentFrame.midX > layout.size.width / 2.0 { + contentFrame.origin.x = layout.size.width - contentFrame.maxX + } + } + contentTransition.updateFrame(node: contentNode, frame: contentFrame, beginWithCurrentState: true) + + contentNode.update( + presentationData: presentationData, + parentLayout: layout, + size: contentFrame.size, + transition: contentTransition + ) + } + + let contentHeight: CGFloat + if self.actionsStackNode.topPositionLock != nil || self.currentReactionsPositionLock != nil { + contentHeight = layout.size.height + } else { + if keepInPlace, case .extracted = self.source { + contentHeight = (layout.statusBarHeight ?? 0.0) + actionsFrame.height + abs(actionsFrame.minY) + bottomInset + layout.intrinsicInsets.bottom + } else { + contentHeight = actionsFrame.maxY + bottomInset + layout.intrinsicInsets.bottom + } + } + let contentSize = CGSize(width: layout.size.width, height: contentHeight) + + if self.scroller.contentSize != contentSize { + let previousContentOffset = self.scroller.contentOffset + self.scroller.contentSize = contentSize + if let storedScrollingState = self.actionsStackNode.storedScrollingState { + self.actionsStackNode.clearStoredScrollingState() + + self.scroller.contentOffset = CGPoint(x: 0.0, y: storedScrollingState) + } + if case .none = stateTransition, transition.isAnimated { + let contentOffset = self.scroller.contentOffset + transition.animateOffsetAdditive(layer: self.scrollNode.layer, offset: previousContentOffset.y - contentOffset.y) + } + } + + self.actionsStackNode.updatePanSelection(isEnabled: contentSize.height <= layout.size.height) + + defaultScrollY = contentSize.height - layout.size.height + if defaultScrollY < 0.0 { + defaultScrollY = 0.0 + } + + self.dismissTapNode.frame = CGRect(origin: CGPoint(), size: CGSize(width: contentSize.width, height: max(contentSize.height, layout.size.height))) + self.dismissAccessibilityArea.frame = CGRect(origin: CGPoint(), size: CGSize(width: contentSize.width, height: max(contentSize.height, layout.size.height))) + } + + switch stateTransition { + case .animateIn: + let actionsSize = self.actionsContainerNode.bounds.size + + if let contentNode = itemContentNode { + contentNode.takeContainingNode() + } + + let duration: Double = 0.42 + let springDamping: CGFloat = 104.0 + + self.scroller.contentOffset = CGPoint(x: 0.0, y: defaultScrollY) + + var animationInContentYDistance: CGFloat + let currentContentScreenFrame: CGRect + if let contentNode = itemContentNode { + if let animateClippingFromContentAreaInScreenSpace = contentNode.animateClippingFromContentAreaInScreenSpace { + self.clippingNode.layer.animateFrame(from: CGRect(origin: CGPoint(x: 0.0, y: animateClippingFromContentAreaInScreenSpace.minY), size: CGSize(width: layout.size.width, height: animateClippingFromContentAreaInScreenSpace.height)), to: CGRect(origin: CGPoint(), size: layout.size), duration: 0.2) + self.clippingNode.layer.animateBoundsOriginYAdditive(from: animateClippingFromContentAreaInScreenSpace.minY, to: 0.0, duration: 0.2) + } + + currentContentScreenFrame = convertFrame(contentNode.containingItem.contentRect, from: contentNode.containingItem.view, to: self.view) + let currentContentLocalFrame = convertFrame(contentRect, from: self.scrollNode.view, to: self.view) + animationInContentYDistance = currentContentLocalFrame.maxY - currentContentScreenFrame.maxY + + var animationInContentXDistance: CGFloat = 0.0 + let contentX = contentParentGlobalFrame.minX + contentRect.minX - contentNode.containingItem.contentRect.minX + let contentWidth = contentNode.containingItem.view.bounds.size.width + let contentHeight = contentNode.containingItem.view.bounds.size.height + if case let .extracted(extracted) = self.source, extracted.adjustContentHorizontally { + let fixedContentX = self.actionsContainerNode.frame.minX + animationInContentXDistance = fixedContentX - contentX + } else if case let .extracted(extracted) = self.source, extracted.centerVertically { + if actionsSize.height.isZero { + var initialContentRect = contentRect + initialContentRect.origin.y += extracted.initialAppearanceOffset.y + + let fixedContentY = floorToScreenPixels((layout.size.height - contentHeight) / 2.0) + animationInContentYDistance = fixedContentY - initialContentRect.minY + } else if contentX + contentWidth > layout.size.width / 2.0, actionsSize.height > 0.0 { + let fixedContentX = layout.size.width - (contentX + contentWidth) + animationInContentXDistance = fixedContentX - contentX + } + } else { + animationInContentXDistance = contentParentGlobalFrameOffsetX + } + + if animationInContentXDistance != 0.0 { + contentNode.layer.animateSpring( + from: -animationInContentXDistance as NSNumber, to: 0.0 as NSNumber, + keyPath: "position.x", + duration: duration, + delay: 0.0, + initialVelocity: 0.0, + damping: springDamping, + additive: true + ) + } + + contentNode.layer.animateSpring( + from: -animationInContentYDistance as NSNumber, to: 0.0 as NSNumber, + keyPath: "position.y", + duration: duration, + delay: 0.0, + initialVelocity: 0.0, + damping: springDamping, + additive: true + ) + + if let reactionPreviewView = self.reactionPreviewView { + reactionPreviewView.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2) + reactionPreviewView.layer.animateSpring( + from: -animationInContentYDistance as NSNumber, to: 0.0 as NSNumber, + keyPath: "position.y", + duration: duration, + delay: 0.0, + initialVelocity: 0.0, + damping: springDamping, + additive: true + ) + reactionPreviewView.layer.animateSpring( + from: 0.01 as NSNumber, + to: 1.0 as NSNumber, + keyPath: "transform.scale", + duration: duration, + delay: 0.0, + initialVelocity: 0.0, + damping: springDamping, + additive: false + ) + } + } else if let contentNode = controllerContentNode { + if case let .controller(source) = self.source, let transitionInfo = source.transitionInfo(), let (sourceView, sourceRect) = transitionInfo.sourceNode() { + let sourcePoint = sourceView.convert(sourceRect.center, to: self.view) + animationInContentYDistance = contentRect.midY - sourcePoint.y + } else { + animationInContentYDistance = 0.0 + } + currentContentScreenFrame = contentRect + + contentNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.15) + contentNode.layer.animateSpring( + from: -animationInContentYDistance as NSNumber, to: 0.0 as NSNumber, + keyPath: "position.y", + duration: duration, + delay: 0.0, + initialVelocity: 0.0, + damping: springDamping, + additive: true + ) + contentNode.layer.animateSpring( + from: 0.01 as NSNumber, to: 1.0 as NSNumber, + keyPath: "transform.scale", + duration: duration, + delay: 0.0, + initialVelocity: 0.0, + damping: springDamping, + additive: false + ) + } else { + animationInContentYDistance = 0.0 + currentContentScreenFrame = contentRect + } + + if let contextExtractableContainer { + let positionTransition = ComponentTransition(animation: .curve(duration: 0.4, curve: .bounce(stiffness: 900.0, damping: 95.0))) + let transition = ComponentTransition(animation: .curve(duration: 0.5, curve: .bounce(stiffness: 900.0, damping: 95.0))) + + positionTransition.animatePosition(layer: self.actionsContainerNode.layer, from: CGPoint( + x: contextExtractableContainer.sourceRect.midX - self.actionsContainerNode.frame.midX, + y: contextExtractableContainer.sourceRect.midY - self.actionsContainerNode.frame.midY + ), to: CGPoint(), additive: true) + + self.actionsStackNode.animateIn(fromExtractableContainer: contextExtractableContainer.container, transition: transition) + } else { + self.actionsContainerNode.layer.animateAlpha(from: 0.0, to: self.actionsContainerNode.alpha, duration: 0.05) + self.actionsContainerNode.layer.animateSpring( + from: 0.01 as NSNumber, + to: 1.0 as NSNumber, + keyPath: "transform.scale", + duration: duration, + delay: 0.0, + initialVelocity: 0.0, + damping: springDamping, + additive: false + ) + + var actionsPositionDeltaXDistance: CGFloat = 0.0 + if case .center = actionsHorizontalAlignment { + actionsPositionDeltaXDistance = currentContentScreenFrame.midX - self.actionsContainerNode.frame.midX + } + + if case .reference = self.source { + actionsPositionDeltaXDistance = currentContentScreenFrame.midX - self.actionsContainerNode.frame.midX + } + + let actionsVerticalTransitionDirection: CGFloat + if let contentNode = itemContentNode { + if contentNode.frame.minY < self.actionsContainerNode.frame.minY { + actionsVerticalTransitionDirection = -1.0 + } else { + actionsVerticalTransitionDirection = 1.0 + } + } else { + if contentRect.minY < self.actionsContainerNode.frame.minY { + actionsVerticalTransitionDirection = -1.0 + } else { + actionsVerticalTransitionDirection = 1.0 + } + } + let actionsPositionDeltaYDistance = -animationInContentYDistance + actionsVerticalTransitionDirection * actionsSize.height / 2.0 - contentActionsSpacing + self.actionsContainerNode.layer.animateSpring( + from: NSValue(cgPoint: CGPoint(x: actionsPositionDeltaXDistance, y: actionsPositionDeltaYDistance)), + to: NSValue(cgPoint: CGPoint()), + keyPath: "position", + duration: duration, + delay: 0.0, + initialVelocity: 0.0, + damping: springDamping, + additive: true + ) + + self.actionsStackNode.animateIn() + } + + if let reactionContextNode = self.reactionContextNode { + let reactionsPositionDeltaYDistance = -animationInContentYDistance + reactionContextNode.layer.animateSpring( + from: NSValue(cgPoint: CGPoint(x: 0.0, y: reactionsPositionDeltaYDistance)), + to: NSValue(cgPoint: CGPoint()), + keyPath: "position", + duration: duration, + delay: 0.0, + initialVelocity: 0.0, + damping: springDamping, + additive: true + ) + reactionContextNode.animateIn(from: currentContentScreenFrame) + } + + if let contentNode = itemContentNode { + contentNode.containingItem.isExtractedToContextPreview = true + contentNode.containingItem.isExtractedToContextPreviewUpdated?(true) + contentNode.containingItem.willUpdateIsExtractedToContextPreview?(true, transition) + + contentNode.containingItem.layoutUpdated = { [weak self] _, animation in + guard let strongSelf = self else { + return + } + + if let _ = strongSelf.animatingOutState { + } else { + strongSelf.requestUpdate(animation.transition) + } + } + } + + if let overlayViews = self.getController()?.getOverlayViews?(), !overlayViews.isEmpty { + for view in overlayViews { + if let snapshotView = view.snapshotView(afterScreenUpdates: false) { + snapshotView.frame = view.convert(view.bounds, to: nil) + self.view.addSubview(snapshotView) + snapshotView.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, removeOnCompletion: false, completion: { [weak snapshotView] _ in + snapshotView?.removeFromSuperview() + }) + } + } + } + case let .animateOut(result, completion): + let actionsSize = self.actionsContainerNode.bounds.size + + let duration: Double + let timingFunction: String + switch result { + case .default, .dismissWithoutContent: + duration = self.reactionContextNodeIsAnimatingOut ? 0.25 : 0.2 + timingFunction = CAMediaTimingFunctionName.easeInEaseOut.rawValue + case let .custom(customTransition): + switch customTransition { + case let .animated(customDuration, curve): + duration = customDuration + timingFunction = curve.timingFunction + case .immediate: + duration = self.reactionContextNodeIsAnimatingOut ? 0.25 : 0.2 + timingFunction = CAMediaTimingFunctionName.easeInEaseOut.rawValue + } + } + + let currentContentScreenFrame: CGRect + + switch self.source { + case let .location(location): + if let putBackInfo = location.transitionInfo() { + self.clippingNode.layer.animateFrame(from: CGRect(origin: CGPoint(), size: layout.size), to: CGRect(origin: CGPoint(x: 0.0, y: putBackInfo.contentAreaInScreenSpace.minY), size: CGSize(width: layout.size.width, height: putBackInfo.contentAreaInScreenSpace.height)), duration: duration, timingFunction: timingFunction, removeOnCompletion: false) + self.clippingNode.layer.animateBoundsOriginYAdditive(from: 0.0, to: putBackInfo.contentAreaInScreenSpace.minY, duration: duration, timingFunction: timingFunction, removeOnCompletion: false) + + currentContentScreenFrame = CGRect(origin: putBackInfo.location, size: CGSize(width: 1.0, height: 1.0)) + } else { + return + } + case let .reference(source): + if let putBackInfo = source.transitionInfo() { + self.clippingNode.layer.animateFrame(from: CGRect(origin: CGPoint(), size: layout.size), to: CGRect(origin: CGPoint(x: 0.0, y: putBackInfo.contentAreaInScreenSpace.minY), size: CGSize(width: layout.size.width, height: putBackInfo.contentAreaInScreenSpace.height)), duration: duration, timingFunction: timingFunction, removeOnCompletion: false) + self.clippingNode.layer.animateBoundsOriginYAdditive(from: 0.0, to: putBackInfo.contentAreaInScreenSpace.minY, duration: duration, timingFunction: timingFunction, removeOnCompletion: false) + + currentContentScreenFrame = convertFrame(putBackInfo.referenceView.bounds.inset(by: putBackInfo.insets), from: putBackInfo.referenceView, to: self.view) + } else { + return + } + case let .extracted(source): + let putBackInfo = source.putBack() + + if let putBackInfo = putBackInfo { + self.clippingNode.layer.animateFrame(from: CGRect(origin: CGPoint(), size: layout.size), to: CGRect(origin: CGPoint(x: 0.0, y: putBackInfo.contentAreaInScreenSpace.minY), size: CGSize(width: layout.size.width, height: putBackInfo.contentAreaInScreenSpace.height)), duration: duration, timingFunction: timingFunction, removeOnCompletion: false) + self.clippingNode.layer.animateBoundsOriginYAdditive(from: 0.0, to: putBackInfo.contentAreaInScreenSpace.minY, duration: duration, timingFunction: timingFunction, removeOnCompletion: false) + } + + if let contentNode = itemContentNode { + currentContentScreenFrame = convertFrame(contentNode.containingItem.contentRect, from: contentNode.containingItem.view, to: self.view) + if currentContentScreenFrame.origin.x < 0.0 { + contentParentGlobalFrameOffsetX = layout.size.width + } + } else { + return + } + case let .controller(source): + if let putBackInfo = source.transitionInfo() { + let _ = putBackInfo + /*self.clippingNode.layer.animateFrame(from: CGRect(origin: CGPoint(), size: layout.size), to: CGRect(origin: CGPoint(x: 0.0, y: putBackInfo.contentAreaInScreenSpace.minY), size: CGSize(width: layout.size.width, height: putBackInfo.contentAreaInScreenSpace.height)), duration: duration, timingFunction: timingFunction, removeOnCompletion: false) + self.clippingNode.layer.animateBoundsOriginYAdditive(from: 0.0, to: putBackInfo.contentAreaInScreenSpace.minY, duration: duration, timingFunction: timingFunction, removeOnCompletion: false)*/ + + //TODO: + currentContentScreenFrame = CGRect(origin: CGPoint(), size: CGSize(width: 1.0, height: 1.0)) + } else { + return + } + } + + self.animatingOutState = AnimatingOutState( + currentContentScreenFrame: currentContentScreenFrame + ) + + let currentContentLocalFrame = convertFrame(contentRect, from: self.scrollNode.view, to: self.view) + + var animationInContentYDistance: CGFloat + + switch result { + case .default, .custom: + animationInContentYDistance = currentContentLocalFrame.minY - currentContentScreenFrame.minY + case .dismissWithoutContent: + animationInContentYDistance = 0.0 + if let contentNode = itemContentNode { + contentNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: duration, timingFunction: CAMediaTimingFunctionName.easeInEaseOut.rawValue, removeOnCompletion: false) + } + } + + let actionsVerticalTransitionDirection: CGFloat + if let contentNode = itemContentNode { + if contentNode.frame.minY < self.actionsContainerNode.frame.minY { + actionsVerticalTransitionDirection = -1.0 + } else { + actionsVerticalTransitionDirection = 1.0 + } + } else { + if contentRect.minY < self.actionsContainerNode.frame.minY { + actionsVerticalTransitionDirection = -1.0 + } else { + actionsVerticalTransitionDirection = 1.0 + } + } + + var restoreOverlayViews: [() -> Void] = [] + if let overlayViews = self.getController()?.getOverlayViews?(), !overlayViews.isEmpty, let itemContentNode, let contentNodeSupernode = itemContentNode.supernode { + for view in overlayViews { + let originalFrame = view.frame + let originalSuperview = view.superview + let originalIndex = view.superview?.subviews.firstIndex(of: view) + let originalGroupOpacity = view.layer.allowsGroupOpacity + + contentNodeSupernode.view.insertSubview(view, aboveSubview: itemContentNode.view) + view.frame = view.convert(view.bounds, to: contentNodeSupernode.view) + view.layer.allowsGroupOpacity = true + view.layer.animateAlpha(from: 0.0, to: view.alpha, duration: 0.2) + + restoreOverlayViews.append({ + view.frame = originalFrame + view.layer.allowsGroupOpacity = originalGroupOpacity + if let originalIndex { + originalSuperview?.insertSubview(view, at: originalIndex) + } else { + originalSuperview?.addSubview(view) + } + }) + } + } + + let completeWithActionStack = itemContentNode == nil && controllerContentNode == nil + if let contentNode = itemContentNode { + contentNode.containingItem.willUpdateIsExtractedToContextPreview?(false, transition) + + var animationInContentXDistance: CGFloat = 0.0 + let contentX = contentParentGlobalFrame.minX + contentRect.minX - contentNode.containingItem.contentRect.minX + let contentWidth = contentNode.containingItem.view.bounds.size.width + if case let .extracted(extracted) = self.source, extracted.adjustContentHorizontally { + let fixedContentX = self.actionsContainerNode.frame.minX + animationInContentXDistance = contentX - fixedContentX + } else if case let .extracted(extracted) = self.source, extracted.centerVertically { + if actionsSize.height.isZero { +// let fixedContentY = floorToScreenPixels((layout.size.height - contentHeight) / 2.0) + animationInContentYDistance = 0.0 //contentY - fixedContentY + } else if contentX + contentWidth > layout.size.width / 2.0{ + let fixedContentX = layout.size.width - (contentX + contentWidth) + animationInContentXDistance = contentX - fixedContentX + } + } else { + animationInContentXDistance = -contentParentGlobalFrameOffsetX + } + + if animationInContentXDistance != 0.0 { + contentNode.offsetContainerNode.layer.animate( + from: -animationInContentXDistance as NSNumber, + to: 0.0 as NSNumber, + keyPath: "position.x", + timingFunction: timingFunction, + duration: duration, + delay: 0.0, + additive: true + ) + } + + contentNode.offsetContainerNode.position = contentNode.offsetContainerNode.position.offsetBy(dx: animationInContentXDistance, dy: -animationInContentYDistance) + let reactionContextNodeIsAnimatingOut = self.reactionContextNodeIsAnimatingOut + contentNode.offsetContainerNode.layer.animate( + from: animationInContentYDistance as NSNumber, + to: 0.0 as NSNumber, + keyPath: "position.y", + timingFunction: timingFunction, + duration: duration, + delay: 0.0, + additive: true, + completion: { [weak self] _ in + Queue.mainQueue().after(reactionContextNodeIsAnimatingOut ? 0.2 * UIView.animationDurationFactor() : 0.0, { + if let strongSelf = self, let contentNode = strongSelf.itemContentNode { + switch contentNode.containingItem { + case let .node(containingNode): + containingNode.addSubnode(containingNode.contentNode) + case let .view(containingView): + containingView.addSubview(containingView.contentView) + } + } + + contentNode.containingItem.isExtractedToContextPreview = false + contentNode.containingItem.isExtractedToContextPreviewUpdated?(false) + contentNode.containingItem.onDismiss?() + + restoreOverlayViews.forEach({ $0() }) + completion() + }) + } + ) + + if let reactionPreviewView = self.reactionPreviewView { + reactionPreviewView.layer.animate( + from: 0.0 as NSNumber, + to: -animationInContentYDistance as NSNumber, + keyPath: "position.y", + timingFunction: timingFunction, + duration: duration, + delay: 0.0, + removeOnCompletion: true, + additive: true, + completion: { _ in + } + ) + reactionPreviewView.layer.animate( + from: 1.0 as NSNumber, + to: 0.01 as NSNumber, + keyPath: "transform.scale", + timingFunction: timingFunction, + duration: duration, + delay: 0.0, + removeOnCompletion: false, + additive: false + ) + reactionPreviewView.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, removeOnCompletion: false, completion: { _ in }) + } + } + if let contentNode = controllerContentNode { + if case let .controller(source) = self.source, let transitionInfo = source.transitionInfo(), let (sourceView, sourceRect) = transitionInfo.sourceNode() { + let sourcePoint = sourceView.convert(sourceRect.center, to: self.view) + animationInContentYDistance = contentRect.midY - sourcePoint.y + } else { + animationInContentYDistance = 0.0 + } + + contentNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: duration * 0.8, removeOnCompletion: false, completion: { _ in + restoreOverlayViews.forEach({ $0() }) + completion() + }) + contentNode.layer.animate( + from: 0.0 as NSNumber, + to: -animationInContentYDistance as NSNumber, + keyPath: "position.y", + timingFunction: timingFunction, + duration: duration, + delay: 0.0, + removeOnCompletion: false, + additive: true + ) + contentNode.layer.animate( + from: 1.0 as NSNumber, + to: 0.01 as NSNumber, + keyPath: "transform.scale", + timingFunction: timingFunction, + duration: duration, + delay: 0.0, + removeOnCompletion: false, + additive: false + ) + } + + if let contextExtractableContainer { + let positionTransition = ComponentTransition(animation: .curve(duration: 0.5, curve: .bounce(stiffness: 900.0, damping: 95.0))) + let transition = ComponentTransition(animation: .curve(duration: 0.12, curve: .easeInOut)) + + let contextExtractableContainerView = contextExtractableContainer.container + + positionTransition.setPosition(view: self.actionsContainerNode.view, position: CGPoint(x: contextExtractableContainer.sourceRect.midX, y: contextExtractableContainer.sourceRect.midY), completion: { _ in + if completeWithActionStack { + restoreOverlayViews.forEach({ $0() }) + completion() + } + }) + + positionTransition.attachAnimation(view: self.actionsContainerNode.view, id: "animateOut", completion: { [weak self, weak contextExtractableContainerView] _ in + if let self, let contextExtractableContainerView { + self.actionsStackNode.didAnimateOut(toExtractableContainer: contextExtractableContainerView) + } + }) + + self.actionsStackNode.animateOut(toExtractableContainer: contextExtractableContainer.container, transition: transition) + } else { + self.actionsContainerNode.layer.animateAlpha(from: self.actionsContainerNode.alpha, to: 0.0, duration: duration, removeOnCompletion: false) + self.actionsContainerNode.layer.animate( + from: 1.0 as NSNumber, + to: 0.01 as NSNumber, + keyPath: "transform.scale", + timingFunction: timingFunction, + duration: duration, + delay: 0.0, + removeOnCompletion: false, + completion: { _ in + if completeWithActionStack { + restoreOverlayViews.forEach({ $0() }) + completion() + } + } + ) + + var actionsPositionDeltaXDistance: CGFloat = 0.0 + if case .center = actionsHorizontalAlignment { + actionsPositionDeltaXDistance = currentContentScreenFrame.midX - self.actionsContainerNode.frame.midX + } + if case .reference = self.source { + actionsPositionDeltaXDistance = currentContentScreenFrame.midX - self.actionsContainerNode.frame.midX + } + let actionsPositionDeltaYDistance = -animationInContentYDistance + actionsVerticalTransitionDirection * actionsSize.height / 2.0 - contentActionsSpacing + self.actionsContainerNode.layer.animate( + from: NSValue(cgPoint: CGPoint()), + to: NSValue(cgPoint: CGPoint(x: actionsPositionDeltaXDistance, y: actionsPositionDeltaYDistance)), + keyPath: "position", + timingFunction: timingFunction, + duration: duration, + delay: 0.0, + removeOnCompletion: false, + additive: true + ) + } + + if let reactionContextNode = self.reactionContextNode { + reactionContextNode.animateOut(to: currentContentScreenFrame, animatingOutToReaction: self.reactionContextNodeIsAnimatingOut) + } + case .none: + if animateReactionsIn, let reactionContextNode = self.reactionContextNode { + reactionContextNode.animateIn(from: contentRect) + } + } + } + + func animateOutToReaction(value: MessageReaction.Reaction, targetView: UIView, hideNode: Bool, animateTargetContainer: UIView?, addStandaloneReactionAnimation: ((StandaloneReactionAnimation) -> Void)?, reducedCurve: Bool, onHit: (() -> Void)?, completion: @escaping () -> Void) { + guard let reactionContextNode = self.reactionContextNode else { + self.requestAnimateOut(.default, completion) + return + } + + var contentCompleted = false + var reactionCompleted = false + let intermediateCompletion: () -> Void = { + if contentCompleted && reactionCompleted { + completion() + } + } + + self.reactionContextNodeIsAnimatingOut = true + reactionContextNode.willAnimateOutToReaction(value: value) + + let result: ContextMenuActionResult + if reducedCurve { + result = .custom(.animated(duration: 0.5, curve: .spring)) + } else { + result = .default + } + + self.requestAnimateOut(result, { + contentCompleted = true + intermediateCompletion() + }) + + reactionContextNode.animateOutToReaction(value: value, targetView: targetView, hideNode: hideNode, animateTargetContainer: animateTargetContainer, addStandaloneReactionAnimation: addStandaloneReactionAnimation, onHit: onHit, completion: { [weak self] in + guard let strongSelf = self else { + return + } + strongSelf.reactionContextNode?.removeFromSupernode() + strongSelf.reactionContextNode = nil + reactionCompleted = true + intermediateCompletion() + }) + } + + func cancelReactionAnimation() { + self.reactionContextNode?.cancelReactionAnimation() + } + + func addRelativeContentOffset(_ offset: CGPoint, transition: ContainedViewLayoutTransition) { + if self.reactionContextNodeIsAnimatingOut, let reactionContextNode = self.reactionContextNode { + reactionContextNode.bounds = reactionContextNode.bounds.offsetBy(dx: 0.0, dy: offset.y) + transition.animateOffsetAdditive(node: reactionContextNode, offset: -offset.y) + + if let itemContentNode = self.itemContentNode { + itemContentNode.bounds = itemContentNode.bounds.offsetBy(dx: 0.0, dy: offset.y) + transition.animateOffsetAdditive(node: itemContentNode, offset: -offset.y) + } + } + } +} + + diff --git a/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextControllerImpl.swift b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextControllerImpl.swift new file mode 100644 index 00000000..1bc22b48 --- /dev/null +++ b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextControllerImpl.swift @@ -0,0 +1,2203 @@ +import Foundation +import UIKit +import Display +import ContextUI +import SwiftSignalKit +import AccountContext +import TelegramPresentationData +import AsyncDisplayKit +import ReactionSelectionNode +import TelegramCore +import UIKitRuntimeUtils +import UndoUI +import TextSelectionNode + +private let animationDurationFactor: Double = 1.0 + +func convertFrame(_ frame: CGRect, from fromView: UIView, to toView: UIView) -> CGRect { + let sourceWindowFrame = fromView.convert(frame, to: nil) + var targetWindowFrame = toView.convert(sourceWindowFrame, from: nil) + + if let fromWindow = fromView.window, let toWindow = toView.window { + targetWindowFrame.origin.x += toWindow.bounds.width - fromWindow.bounds.width + } + return targetWindowFrame +} + +final class ContextControllerNode: ViewControllerTracingNode, ASScrollViewDelegate { + private weak var controller: ContextControllerImpl? + private let context: AccountContext? + private var presentationData: PresentationData + + private let configuration: ContextController.Configuration + + private let legacySource: ContextContentSource + private var legacyItems: Signal + + let beginDismiss: (ContextMenuActionResult) -> Void + private let beganAnimatingOut: () -> Void + private let attemptTransitionControllerIntoNavigation: () -> Void + var dismissedForCancel: (() -> Void)? + private let getController: () -> ContextControllerProtocol? + private weak var gesture: ContextGesture? + + private var didSetItemsReady = false + let itemsReady = Promise() + let contentReady = Promise() + + private var currentItems: ContextController.Items? + private var currentActionsMinHeight: ContextController.ActionsHeight? + + private var validLayout: ContainerViewLayout? + + private let effectView: UIVisualEffectView + private var propertyAnimator: AnyObject? + private var displayLinkAnimator: DisplayLinkAnimator? + private let dimNode: ASDisplayNode + private let withoutBlurDimNode: ASDisplayNode + private let dismissNode: ASDisplayNode + private let dismissAccessibilityArea: AccessibilityAreaNode + + private var sourceContainer: ContextSourceContainer? + + private let clippingNode: ASDisplayNode + private let scrollNode: ASScrollNode + + private var originalProjectedContentViewFrame: (CGRect, CGRect)? + private var contentAreaInScreenSpace: CGRect? + private var customPosition: CGPoint? + private let contentContainerNode: ContextContentContainerNode + private var actionsContainerNode: ContextActionsContainerNode + + private var didCompleteAnimationIn = false + private var initialContinueGesturePoint: CGPoint? + private var didMoveFromInitialGesturePoint = false + private var highlightedActionNode: ContextActionNodeProtocol? + private var highlightedReaction: ReactionItem.Reaction? + + private let hapticFeedback = HapticFeedback() + + private var animatedIn = false + private var isAnimatingOut = false + + private let itemsDisposable = MetaDisposable() + + private let blurBackground: Bool + + var overlayWantsToBeBelowKeyboard: Bool { + guard let sourceContainer = self.sourceContainer else { + return false + } + return sourceContainer.overlayWantsToBeBelowKeyboard + } + + init( + controller: ContextControllerImpl, + context: AccountContext?, + presentationData: PresentationData, + configuration: ContextController.Configuration, + beginDismiss: @escaping (ContextMenuActionResult) -> Void, + recognizer: TapLongTapOrDoubleTapGestureRecognizer?, + gesture: ContextGesture?, + beganAnimatingOut: @escaping () -> Void, + attemptTransitionControllerIntoNavigation: @escaping () -> Void + ) { + self.controller = controller + self.context = context + self.presentationData = presentationData + self.configuration = configuration + self.beginDismiss = beginDismiss + self.beganAnimatingOut = beganAnimatingOut + self.attemptTransitionControllerIntoNavigation = attemptTransitionControllerIntoNavigation + self.gesture = gesture + + self.legacySource = configuration.sources[0].source + self.legacyItems = configuration.sources[0].items + + self.getController = { [weak controller] in + return controller + } + + self.effectView = UIVisualEffectView() + if #available(iOS 9.0, *) { + } else { + if presentationData.theme.rootController.keyboardColor == .dark { + self.effectView.effect = UIBlurEffect(style: .dark) + } else { + self.effectView.effect = UIBlurEffect(style: .light) + } + self.effectView.alpha = 0.0 + } + + self.dimNode = ASDisplayNode() + self.dimNode.backgroundColor = presentationData.theme.contextMenu.dimColor + self.dimNode.alpha = 0.0 + + self.withoutBlurDimNode = ASDisplayNode() + self.withoutBlurDimNode.backgroundColor = UIColor(white: 0.0, alpha: 0.4) + self.withoutBlurDimNode.alpha = 0.0 + + self.dismissNode = ASDisplayNode() + self.dismissAccessibilityArea = AccessibilityAreaNode() + self.dismissAccessibilityArea.accessibilityLabel = presentationData.strings.VoiceOver_DismissContextMenu + self.dismissAccessibilityArea.accessibilityTraits = .button + + self.clippingNode = ASDisplayNode() + self.clippingNode.clipsToBounds = true + + self.scrollNode = ASScrollNode() + self.scrollNode.canCancelAllTouchesInViews = true + self.scrollNode.view.delaysContentTouches = false + self.scrollNode.view.showsVerticalScrollIndicator = false + if #available(iOS 11.0, *) { + self.scrollNode.view.contentInsetAdjustmentBehavior = .never + } + + self.contentContainerNode = ContextContentContainerNode() + + var feedbackTap: (() -> Void)? + var updateLayout: (() -> Void)? + + var blurBackground = true + if let mainSource = configuration.sources.first(where: { $0.id == configuration.initialId }) { + if case .reference = mainSource.source { + blurBackground = false + } else if case let .extracted(extractedSource) = mainSource.source, !extractedSource.blurBackground { + blurBackground = false + } + } + self.blurBackground = blurBackground + + self.actionsContainerNode = ContextActionsContainerNode(presentationData: presentationData, items: ContextController.Items(), getController: { [weak controller] in + return controller + }, actionSelected: { result in + beginDismiss(result) + }, requestLayout: { + updateLayout?() + }, feedbackTap: { + feedbackTap?() + }, blurBackground: blurBackground) + + super.init() + + feedbackTap = { [weak self] in + self?.hapticFeedback.tap() + } + + updateLayout = { [weak self] in + self?.updateLayout() + } + + self.scrollNode.view.delegate = self.wrappedScrollViewDelegate + + if blurBackground { + self.view.addSubview(self.effectView) + self.addSubnode(self.dimNode) + self.addSubnode(self.withoutBlurDimNode) + } + + self.addSubnode(self.clippingNode) + + self.clippingNode.addSubnode(self.scrollNode) + self.scrollNode.addSubnode(self.dismissNode) + self.scrollNode.addSubnode(self.dismissAccessibilityArea) + + self.scrollNode.addSubnode(self.actionsContainerNode) + + if let recognizer = recognizer { + recognizer.externalUpdated = { [weak self, weak recognizer] view, point in + guard let strongSelf = self, let _ = recognizer else { + return + } + let localPoint = strongSelf.view.convert(point, from: view) + let initialPoint: CGPoint + if let current = strongSelf.initialContinueGesturePoint { + initialPoint = current + } else { + initialPoint = localPoint + strongSelf.initialContinueGesturePoint = localPoint + } + if strongSelf.didCompleteAnimationIn { + if !strongSelf.didMoveFromInitialGesturePoint { + let distance = abs(localPoint.y - initialPoint.y) + if distance > 12.0 { + strongSelf.didMoveFromInitialGesturePoint = true + } + } + if strongSelf.didMoveFromInitialGesturePoint { + if let sourceContainer = strongSelf.sourceContainer { + let presentationPoint = strongSelf.view.convert(localPoint, to: sourceContainer.view) + sourceContainer.highlightGestureMoved(location: presentationPoint, hover: false) + } else { + let actionPoint = strongSelf.view.convert(localPoint, to: strongSelf.actionsContainerNode.view) + let actionNode = strongSelf.actionsContainerNode.actionNode(at: actionPoint) + if strongSelf.highlightedActionNode !== actionNode { + strongSelf.highlightedActionNode?.setIsHighlighted(false) + strongSelf.highlightedActionNode = actionNode + if let actionNode = actionNode { + actionNode.setIsHighlighted(true) + strongSelf.hapticFeedback.tap() + } + } + } + } + } + } + recognizer.externalEnded = { [weak self, weak recognizer] viewAndPoint in + guard let strongSelf = self, let recognizer = recognizer else { + return + } + recognizer.externalUpdated = nil + if strongSelf.didMoveFromInitialGesturePoint { + if let sourceContainer = strongSelf.sourceContainer { + sourceContainer.highlightGestureFinished(performAction: viewAndPoint != nil) + } else { + if let (_, _) = viewAndPoint { + if let highlightedActionNode = strongSelf.highlightedActionNode { + strongSelf.highlightedActionNode = nil + highlightedActionNode.performAction() + } + } else { + if let highlightedActionNode = strongSelf.highlightedActionNode { + strongSelf.highlightedActionNode = nil + highlightedActionNode.setIsHighlighted(false) + } + } + } + } + } + } else if let gesture = gesture { + gesture.externalUpdated = { [weak self, weak gesture] view, point in + guard let strongSelf = self, let _ = gesture else { + return + } + let localPoint: CGPoint + if let layout = strongSelf.validLayout, layout.metrics.isTablet, layout.size.width > layout.size.height, let view { + localPoint = view.convert(point, to: nil) + } else { + localPoint = strongSelf.view.convert(point, from: view) + } + let initialPoint: CGPoint + if let current = strongSelf.initialContinueGesturePoint { + initialPoint = current + } else { + initialPoint = localPoint + strongSelf.initialContinueGesturePoint = localPoint + } + if strongSelf.didCompleteAnimationIn { + if !strongSelf.didMoveFromInitialGesturePoint { + let distance = abs(localPoint.y - initialPoint.y) + if distance > 4.0 { + strongSelf.didMoveFromInitialGesturePoint = true + } + } + if strongSelf.didMoveFromInitialGesturePoint { + if let sourceContainer = strongSelf.sourceContainer { + let presentationPoint = strongSelf.view.convert(localPoint, to: sourceContainer.view) + sourceContainer.highlightGestureMoved(location: presentationPoint, hover: false) + } else { + let actionPoint = strongSelf.view.convert(localPoint, to: strongSelf.actionsContainerNode.view) + var actionNode = strongSelf.actionsContainerNode.actionNode(at: actionPoint) + if let actionNodeValue = actionNode, !actionNodeValue.isActionEnabled { + actionNode = nil + } + + if strongSelf.highlightedActionNode !== actionNode { + strongSelf.highlightedActionNode?.setIsHighlighted(false) + strongSelf.highlightedActionNode = actionNode + if let actionNode = actionNode { + actionNode.setIsHighlighted(true) + strongSelf.hapticFeedback.tap() + } + } + } + } + } + } + gesture.externalEnded = { [weak self, weak gesture] viewAndPoint in + guard let strongSelf = self, let gesture = gesture else { + return + } + gesture.externalUpdated = nil + if strongSelf.didMoveFromInitialGesturePoint { + if let sourceContainer = strongSelf.sourceContainer { + sourceContainer.highlightGestureFinished(performAction: viewAndPoint != nil) + } else { + if let (_, _) = viewAndPoint { + if let highlightedActionNode = strongSelf.highlightedActionNode { + strongSelf.highlightedActionNode = nil + highlightedActionNode.performAction() + } + } else { + if let highlightedActionNode = strongSelf.highlightedActionNode { + strongSelf.highlightedActionNode = nil + highlightedActionNode.setIsHighlighted(false) + } + } + } + } + } + } + + self.initializeContent() + + self.dismissAccessibilityArea.activate = { [weak self] in + self?.dimNodeTapped() + return true + } + + if controller.disableScreenshots { + setLayerDisableScreenshots(self.layer, true) + } + } + + deinit { + if let propertyAnimator = self.propertyAnimator { + if #available(iOSApplicationExtension 10.0, iOS 10.0, *) { + let propertyAnimator = propertyAnimator as? UIViewPropertyAnimator + propertyAnimator?.stopAnimation(true) + } + } + + self.itemsDisposable.dispose() + } + + override func didLoad() { + super.didLoad() + + self.dismissNode.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dimNodeTapped))) + + if #available(iOS 13.0, *) { + self.view.addGestureRecognizer(UIHoverGestureRecognizer(target: self, action: #selector(self.hoverGesture(_:)))) + } + } + + @objc private func dimNodeTapped() { + guard self.animatedIn else { + return + } + self.dismissedForCancel?() + self.beginDismiss(.default) + } + + @available(iOS 13.0, *) + @objc private func hoverGesture(_ gestureRecognizer: UIHoverGestureRecognizer) { + guard self.didCompleteAnimationIn else { + return + } + + let localPoint = gestureRecognizer.location(in: self.view) + + switch gestureRecognizer.state { + case .changed: + if let sourceContainer = self.sourceContainer { + let presentationPoint = self.view.convert(localPoint, to: sourceContainer.view) + sourceContainer.highlightGestureMoved(location: presentationPoint, hover: true) + } else { + let actionPoint = self.view.convert(localPoint, to: self.actionsContainerNode.view) + let actionNode = self.actionsContainerNode.actionNode(at: actionPoint) + if self.highlightedActionNode !== actionNode { + self.highlightedActionNode?.setIsHighlighted(false) + self.highlightedActionNode = actionNode + if let actionNode = actionNode { + actionNode.setIsHighlighted(true) + } + } + } + case .ended, .cancelled: + if let sourceContainer = self.sourceContainer { + sourceContainer.highlightGestureMoved(location: CGPoint(x: -1, y: -1), hover: true) + } else { + if let highlightedActionNode = self.highlightedActionNode { + self.highlightedActionNode = nil + highlightedActionNode.setIsHighlighted(false) + } + } + default: + break + } + } + + private func initializeContent() { + if self.configuration.sources.count == 1 { + switch self.configuration.sources[0].source { + case .location: + break + case let .reference(source): + if let controller = self.getController() as? ContextControllerImpl, controller.workaroundUseLegacyImplementation { + self.contentReady.set(.single(true)) + + let transitionInfo = source.transitionInfo() + if let transitionInfo { + let referenceView = transitionInfo.referenceView + self.contentContainerNode.contentNode = .reference(view: referenceView) + self.contentAreaInScreenSpace = transitionInfo.contentAreaInScreenSpace + self.customPosition = transitionInfo.customPosition + + var projectedFrame = convertFrame(referenceView.bounds, from: referenceView, to: self.view) + projectedFrame.origin.x += transitionInfo.insets.left + projectedFrame.size.width -= transitionInfo.insets.left + transitionInfo.insets.right + projectedFrame.origin.y += transitionInfo.insets.top + projectedFrame.size.width -= transitionInfo.insets.top + transitionInfo.insets.bottom + self.originalProjectedContentViewFrame = (projectedFrame, projectedFrame) + } + + self.itemsDisposable.set((self.configuration.sources[0].items + |> deliverOnMainQueue).start(next: { [weak self] items in + self?.setItems(items: items, minHeight: nil, previousActionsTransition: .scale) + })) + + return + } + case .extracted: + break + case let .controller(source): + if let controller = self.getController() as? ContextControllerImpl, controller.workaroundUseLegacyImplementation { + self.contentReady.set(source.controller.ready.get()) + + let transitionInfo = source.transitionInfo() + if let transitionInfo = transitionInfo, let (sourceView, sourceNodeRect) = transitionInfo.sourceNode() { + let contentParentNode = ContextControllerContentNode(sourceView: sourceView, controller: source.controller, tapped: { [weak self] in + self?.attemptTransitionControllerIntoNavigation() + }) + self.contentContainerNode.contentNode = .controller(contentParentNode) + self.scrollNode.addSubnode(self.contentContainerNode) + self.contentContainerNode.clipsToBounds = true + self.contentContainerNode.cornerRadius = 30.0 + self.contentContainerNode.addSubnode(contentParentNode) + + let projectedFrame = convertFrame(sourceNodeRect, from: sourceView, to: self.view) + self.originalProjectedContentViewFrame = (projectedFrame, projectedFrame) + } + + self.itemsDisposable.set((self.configuration.sources[0].items + |> deliverOnMainQueue).start(next: { [weak self] items in + self?.setItems(items: items, minHeight: nil, previousActionsTransition: .scale) + })) + + return + } + } + } + + if let controller = self.controller { + let sourceContainer = ContextSourceContainer(controller: controller, configuration: self.configuration, context: self.context) + self.contentReady.set(sourceContainer.ready.get()) + self.itemsReady.set(.single(true)) + self.sourceContainer = sourceContainer + self.addSubnode(sourceContainer) + } + } + + func animateIn() { + self.gesture?.endPressedAppearance() + self.hapticFeedback.impact() + + if let sourceContainer = self.sourceContainer { + self.didCompleteAnimationIn = true + sourceContainer.animateIn() + return + } + + switch self.legacySource { + case .location, .reference: + break + case .extracted: + if let contentAreaInScreenSpace = self.contentAreaInScreenSpace, let maybeContentNode = self.contentContainerNode.contentNode, case .extracted = maybeContentNode { + var updatedContentAreaInScreenSpace = contentAreaInScreenSpace + updatedContentAreaInScreenSpace.origin.x = 0.0 + updatedContentAreaInScreenSpace.size.width = self.bounds.width + + self.clippingNode.layer.animateFrame(from: updatedContentAreaInScreenSpace, to: self.clippingNode.frame, duration: 0.18 * animationDurationFactor, timingFunction: CAMediaTimingFunctionName.easeInEaseOut.rawValue) + self.clippingNode.layer.animateBoundsOriginYAdditive(from: updatedContentAreaInScreenSpace.minY, to: 0.0, duration: 0.18 * animationDurationFactor, timingFunction: CAMediaTimingFunctionName.easeInEaseOut.rawValue) + } + case let .controller(source): + let transitionInfo = source.transitionInfo() + if let transitionInfo = transitionInfo, let (sourceView, sourceNodeRect) = transitionInfo.sourceNode() { + let projectedFrame = convertFrame(sourceNodeRect, from: sourceView, to: self.view) + self.originalProjectedContentViewFrame = (projectedFrame, projectedFrame) + + var updatedContentAreaInScreenSpace = transitionInfo.contentAreaInScreenSpace + updatedContentAreaInScreenSpace.origin.x = 0.0 + updatedContentAreaInScreenSpace.size.width = self.bounds.width + self.contentAreaInScreenSpace = updatedContentAreaInScreenSpace + } + } + + if let validLayout = self.validLayout { + self.updateLayout(layout: validLayout, transition: .immediate, previousActionsContainerNode: nil) + } + + if !self.dimNode.isHidden { + self.dimNode.alpha = 1.0 + self.dimNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2 * animationDurationFactor) + } else { + self.withoutBlurDimNode.alpha = 1.0 + self.withoutBlurDimNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2 * animationDurationFactor) + } + + if #available(iOS 10.0, *) { + if let propertyAnimator = self.propertyAnimator { + let propertyAnimator = propertyAnimator as? UIViewPropertyAnimator + propertyAnimator?.stopAnimation(true) + } + self.effectView.effect = makeCustomZoomBlurEffect(isLight: presentationData.theme.rootController.keyboardColor == .light) + self.effectView.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2 * animationDurationFactor) + self.propertyAnimator = UIViewPropertyAnimator(duration: 0.2 * animationDurationFactor * UIView.animationDurationFactor(), curve: .easeInOut, animations: { + }) + } + + if let _ = self.propertyAnimator { + if #available(iOSApplicationExtension 10.0, iOS 10.0, *) { + self.displayLinkAnimator = DisplayLinkAnimator(duration: 0.2 * animationDurationFactor * UIView.animationDurationFactor(), from: 0.0, to: 1.0, update: { [weak self] value in + (self?.propertyAnimator as? UIViewPropertyAnimator)?.fractionComplete = value + }, completion: { [weak self] in + self?.didCompleteAnimationIn = true + self?.hapticFeedback.prepareTap() + self?.actionsContainerNode.animateIn() + }) + } + } else { + UIView.animate(withDuration: 0.2 * animationDurationFactor, animations: { + self.effectView.effect = makeCustomZoomBlurEffect(isLight: self.presentationData.theme.rootController.keyboardColor == .light) + }, completion: { [weak self] _ in + self?.didCompleteAnimationIn = true + self?.actionsContainerNode.animateIn() + }) + } + + if let contentNode = self.contentContainerNode.contentNode { + switch contentNode { + case .reference: + let springDuration: Double = 0.42 * animationDurationFactor + let springDamping: CGFloat = 104.0 + + self.actionsContainerNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2 * animationDurationFactor) + self.actionsContainerNode.layer.animateSpring(from: 0.1 as NSNumber, to: 1.0 as NSNumber, keyPath: "transform.scale", duration: springDuration, initialVelocity: 0.0, damping: springDamping) + + if let originalProjectedContentViewFrame = self.originalProjectedContentViewFrame { + let localSourceFrame = self.view.convert(originalProjectedContentViewFrame.1, to: self.scrollNode.view) + + let localContentSourceFrame = self.view.convert(originalProjectedContentViewFrame.1, to: self.contentContainerNode.view.superview) + + self.actionsContainerNode.layer.animateSpring(from: NSValue(cgPoint: CGPoint(x: localSourceFrame.center.x - self.actionsContainerNode.position.x, y: localSourceFrame.center.y - self.actionsContainerNode.position.y)), to: NSValue(cgPoint: CGPoint()), keyPath: "position", duration: springDuration, initialVelocity: 0.0, damping: springDamping, additive: true) + let contentContainerOffset = CGPoint(x: localContentSourceFrame.center.x - self.contentContainerNode.frame.center.x, y: localContentSourceFrame.center.y - self.contentContainerNode.frame.center.y) + self.contentContainerNode.layer.animateSpring(from: NSValue(cgPoint: contentContainerOffset), to: NSValue(cgPoint: CGPoint()), keyPath: "position", duration: springDuration, initialVelocity: 0.0, damping: springDamping, additive: true, completion: { [weak self] _ in + self?.animatedIn = true + }) + } + case .extractedContainer: + break + case let .extracted(extracted, keepInPlace): + let springDuration: Double = 0.42 * animationDurationFactor + var springDamping: CGFloat = 104.0 + if case let .extracted(source) = self.legacySource, source.centerVertically { + springDamping = 124.0 + } + + self.actionsContainerNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2 * animationDurationFactor) + self.actionsContainerNode.layer.animateSpring(from: 0.1 as NSNumber, to: 1.0 as NSNumber, keyPath: "transform.scale", duration: springDuration, initialVelocity: 0.0, damping: springDamping) + + if let originalProjectedContentViewFrame = self.originalProjectedContentViewFrame { + let contentParentNode = extracted + let localSourceFrame = self.view.convert(originalProjectedContentViewFrame.1, to: self.scrollNode.view) + + var actionsDuration = springDuration + var actionsOffset: CGFloat = 0.0 + var contentDuration = springDuration + if case let .extracted(source) = self.legacySource, source.centerVertically { + actionsOffset = -(originalProjectedContentViewFrame.1.height - originalProjectedContentViewFrame.0.height) * 0.57 + actionsDuration *= 1.0 + contentDuration *= 0.9 + } + + let localContentSourceFrame: CGRect + if keepInPlace { + localContentSourceFrame = self.view.convert(originalProjectedContentViewFrame.1, to: self.contentContainerNode.view.superview) + } else { + localContentSourceFrame = localSourceFrame + } + + self.actionsContainerNode.layer.animateSpring(from: NSValue(cgPoint: CGPoint(x: localSourceFrame.center.x - self.actionsContainerNode.position.x, y: localSourceFrame.center.y - self.actionsContainerNode.position.y + actionsOffset)), to: NSValue(cgPoint: CGPoint()), keyPath: "position", duration: actionsDuration, initialVelocity: 0.0, damping: springDamping, additive: true) + let contentContainerOffset = CGPoint(x: localContentSourceFrame.center.x - self.contentContainerNode.frame.center.x - contentParentNode.contentRect.minX, y: localContentSourceFrame.center.y - self.contentContainerNode.frame.center.y - contentParentNode.contentRect.minY) + self.contentContainerNode.layer.animateSpring(from: NSValue(cgPoint: contentContainerOffset), to: NSValue(cgPoint: CGPoint()), keyPath: "position", duration: contentDuration, initialVelocity: 0.0, damping: springDamping, additive: true, completion: { [weak self] _ in + self?.clippingNode.view.mask = nil + self?.animatedIn = true + }) + contentParentNode.applyAbsoluteOffsetSpring?(-contentContainerOffset.y, springDuration, springDamping) + } + + extracted.willUpdateIsExtractedToContextPreview?(true, .animated(duration: 0.2, curve: .easeInOut)) + case .controller: + let springDuration: Double = 0.52 * animationDurationFactor + let springDamping: CGFloat = 110.0 + + self.actionsContainerNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2 * animationDurationFactor) + self.actionsContainerNode.layer.animateSpring(from: 0.1 as NSNumber, to: 1.0 as NSNumber, keyPath: "transform.scale", duration: springDuration, initialVelocity: 0.0, damping: springDamping) + self.contentContainerNode.allowsGroupOpacity = true + self.contentContainerNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2 * animationDurationFactor, completion: { [weak self] _ in + self?.contentContainerNode.allowsGroupOpacity = false + }) + + if let originalProjectedContentViewFrame = self.originalProjectedContentViewFrame { + let localSourceFrame = self.view.convert(CGRect(origin: CGPoint(x: originalProjectedContentViewFrame.1.minX, y: originalProjectedContentViewFrame.1.minY), size: CGSize(width: originalProjectedContentViewFrame.1.width, height: originalProjectedContentViewFrame.1.height)), to: self.scrollNode.view) + + self.contentContainerNode.layer.animateSpring(from: min(localSourceFrame.width / self.contentContainerNode.frame.width, localSourceFrame.height / self.contentContainerNode.frame.height) as NSNumber, to: 1.0 as NSNumber, keyPath: "transform.scale", duration: springDuration, initialVelocity: 0.0, damping: springDamping) + + switch self.legacySource { + case let .controller(controller): + controller.animatedIn() + default: + break + } + + let contentContainerOffset = CGPoint(x: localSourceFrame.center.x - self.contentContainerNode.frame.center.x, y: localSourceFrame.center.y - self.contentContainerNode.frame.center.y) + if let contentNode = self.contentContainerNode.contentNode, case let .controller(controller) = contentNode { + let snapshotView: UIView? = nil// controller.sourceNode.view.snapshotContentTree() + if let snapshotView = snapshotView { + controller.sourceView.isHidden = true + + self.view.insertSubview(snapshotView, belowSubview: self.contentContainerNode.view) + snapshotView.layer.animateSpring(from: NSValue(cgPoint: localSourceFrame.center), to: NSValue(cgPoint: CGPoint(x: self.contentContainerNode.frame.midX, y: self.contentContainerNode.frame.minY + localSourceFrame.height / 2.0)), keyPath: "position", duration: springDuration, initialVelocity: 0.0, damping: springDamping, removeOnCompletion: false) + //snapshotView.layer.animateSpring(from: 1.0 as NSNumber, to: (self.contentContainerNode.frame.width / localSourceFrame.width) as NSNumber, keyPath: "transform.scale", duration: springDuration, initialVelocity: 0.0, damping: springDamping, removeOnCompletion: false) + snapshotView.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2 * animationDurationFactor, removeOnCompletion: false, completion: { [weak snapshotView] _ in + snapshotView?.removeFromSuperview() + }) + } + } + self.actionsContainerNode.layer.animateSpring(from: NSValue(cgPoint: CGPoint(x: localSourceFrame.center.x - self.actionsContainerNode.position.x, y: localSourceFrame.center.y - self.actionsContainerNode.position.y)), to: NSValue(cgPoint: CGPoint()), keyPath: "position", duration: springDuration, initialVelocity: 0.0, damping: springDamping, additive: true) + self.contentContainerNode.layer.animateSpring(from: NSValue(cgPoint: contentContainerOffset), to: NSValue(cgPoint: CGPoint()), keyPath: "position", duration: springDuration, initialVelocity: 0.0, damping: springDamping, additive: true, completion: { [weak self] _ in + self?.animatedIn = true + }) + } + } + } + } + + private var delayLayoutUpdate = false + func animateOut(result initialResult: ContextMenuActionResult, completion: @escaping () -> Void) { + self.isUserInteractionEnabled = false + + self.beganAnimatingOut() + + if let sourceContainer = self.sourceContainer { + sourceContainer.animateOut(result: initialResult, completion: completion) + return + } + + var transitionDuration: Double = 0.2 + var transitionCurve: ContainedViewLayoutTransitionCurve = .easeInOut + + var result = initialResult + + switch self.legacySource { + case let .location(source): + let transitionInfo = source.transitionInfo() + if transitionInfo == nil { + result = .dismissWithoutContent + } + + switch result { + case let .custom(value): + switch value { + case let .animated(duration, curve): + transitionDuration = duration + transitionCurve = curve + default: + break + } + default: + break + } + + self.isUserInteractionEnabled = false + self.isAnimatingOut = true + + self.scrollNode.view.setContentOffset(self.scrollNode.view.contentOffset, animated: false) + + if !self.dimNode.isHidden { + self.dimNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: transitionDuration * animationDurationFactor, removeOnCompletion: false) + } else { + self.withoutBlurDimNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: transitionDuration * animationDurationFactor, removeOnCompletion: false) + } + + self.actionsContainerNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.15 * animationDurationFactor, removeOnCompletion: false, completion: { _ in + completion() + }) + self.actionsContainerNode.layer.animateScale(from: 1.0, to: 0.1, duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false) + + let animateOutToItem: Bool + switch result { + case .default, .custom: + animateOutToItem = true + case .dismissWithoutContent: + animateOutToItem = false + } + + if animateOutToItem, let originalProjectedContentViewFrame = self.originalProjectedContentViewFrame { + let localSourceFrame = self.view.convert(originalProjectedContentViewFrame.1, to: self.scrollNode.view) + self.actionsContainerNode.layer.animatePosition(from: CGPoint(), to: CGPoint(x: localSourceFrame.center.x - self.actionsContainerNode.position.x, y: localSourceFrame.center.y - self.actionsContainerNode.position.y), duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false, additive: true) + } + case let .reference(source): + guard let maybeContentNode = self.contentContainerNode.contentNode, case let .reference(referenceView) = maybeContentNode else { + return + } + + let transitionInfo = source.transitionInfo() + if transitionInfo == nil { + result = .dismissWithoutContent + } + + switch result { + case let .custom(value): + switch value { + case let .animated(duration, curve): + transitionDuration = duration + transitionCurve = curve + default: + break + } + default: + break + } + + self.isUserInteractionEnabled = false + self.isAnimatingOut = true + + self.scrollNode.view.setContentOffset(self.scrollNode.view.contentOffset, animated: false) + + if let transitionInfo = transitionInfo, let parentSuperview = referenceView.superview { + self.originalProjectedContentViewFrame = (convertFrame(referenceView.frame, from: parentSuperview, to: self.view), convertFrame(referenceView.bounds, from: referenceView, to: self.view)) + + var updatedContentAreaInScreenSpace = transitionInfo.contentAreaInScreenSpace + updatedContentAreaInScreenSpace.origin.x = 0.0 + updatedContentAreaInScreenSpace.size.width = self.bounds.width + + self.clippingNode.layer.animateFrame(from: self.clippingNode.frame, to: updatedContentAreaInScreenSpace, duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false) + self.clippingNode.layer.animateBoundsOriginYAdditive(from: 0.0, to: updatedContentAreaInScreenSpace.minY, duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false) + } + + if !self.dimNode.isHidden { + self.dimNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: transitionDuration * animationDurationFactor, removeOnCompletion: false) + } else { + self.withoutBlurDimNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: transitionDuration * animationDurationFactor, removeOnCompletion: false) + } + + self.actionsContainerNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.15 * animationDurationFactor, removeOnCompletion: false, completion: { _ in + completion() + }) + self.actionsContainerNode.layer.animateScale(from: 1.0, to: 0.1, duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false) + + let animateOutToItem: Bool + switch result { + case .default, .custom: + animateOutToItem = true + case .dismissWithoutContent: + animateOutToItem = false + } + + if animateOutToItem, let originalProjectedContentViewFrame = self.originalProjectedContentViewFrame { + let localSourceFrame = self.view.convert(originalProjectedContentViewFrame.1, to: self.scrollNode.view) + self.actionsContainerNode.layer.animatePosition(from: CGPoint(), to: CGPoint(x: localSourceFrame.center.x - self.actionsContainerNode.position.x, y: localSourceFrame.center.y - self.actionsContainerNode.position.y), duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false, additive: true) + } + case let .extracted(source): + guard let maybeContentNode = self.contentContainerNode.contentNode, case let .extracted(contentParentNode, keepInPlace) = maybeContentNode else { + return + } + + let putBackInfo = source.putBack() + + if putBackInfo == nil { + result = .dismissWithoutContent + } + + switch result { + case let .custom(value): + switch value { + case let .animated(duration, curve): + transitionDuration = duration + transitionCurve = curve + default: + break + } + default: + break + } + + self.isUserInteractionEnabled = false + self.isAnimatingOut = true + + self.scrollNode.view.setContentOffset(self.scrollNode.view.contentOffset, animated: false) + + var completedEffect = false + var completedContentNode = false + var completedActionsNode = false + + if let putBackInfo = putBackInfo, let parentSupernode = contentParentNode.supernode { + self.originalProjectedContentViewFrame = (convertFrame(contentParentNode.frame, from: parentSupernode.view, to: self.view), convertFrame(contentParentNode.contentRect, from: contentParentNode.view, to: self.view)) + + var updatedContentAreaInScreenSpace = putBackInfo.contentAreaInScreenSpace + updatedContentAreaInScreenSpace.origin.x = 0.0 + updatedContentAreaInScreenSpace.size.width = self.bounds.width + + self.clippingNode.view.mask = putBackInfo.maskView + let previousFrame = self.clippingNode.frame + self.clippingNode.position = updatedContentAreaInScreenSpace.center + self.clippingNode.bounds = CGRect(origin: CGPoint(), size: updatedContentAreaInScreenSpace.size) + self.clippingNode.layer.animatePosition(from: previousFrame.center, to: updatedContentAreaInScreenSpace.center, duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: true) + self.clippingNode.layer.animateBounds(from: CGRect(origin: CGPoint(), size: previousFrame.size), to: CGRect(origin: CGPoint(), size: updatedContentAreaInScreenSpace.size), duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: true) + //self.clippingNode.layer.animateFrame(from: previousFrame, to: updatedContentAreaInScreenSpace, duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false) + //self.clippingNode.layer.animateBoundsOriginYAdditive(from: 0.0, to: updatedContentAreaInScreenSpace.minY, duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false) + } + + let intermediateCompletion: () -> Void = { [weak self, weak contentParentNode] in + if completedEffect && completedContentNode && completedActionsNode { + switch result { + case .default, .custom: + if let contentParentNode = contentParentNode { + contentParentNode.addSubnode(contentParentNode.contentNode) + contentParentNode.isExtractedToContextPreview = false + contentParentNode.isExtractedToContextPreviewUpdated?(false) + } + case .dismissWithoutContent: + break + } + + self?.clippingNode.view.mask = nil + + completion() + } + } + + if #available(iOS 10.0, *) { + if let propertyAnimator = self.propertyAnimator { + let propertyAnimator = propertyAnimator as? UIViewPropertyAnimator + propertyAnimator?.stopAnimation(true) + } + self.propertyAnimator = UIViewPropertyAnimator(duration: transitionDuration * UIView.animationDurationFactor(), curve: .easeInOut, animations: { + //self?.effectView.effect = nil + }) + } + + if let _ = self.propertyAnimator { + if #available(iOSApplicationExtension 10.0, iOS 10.0, *) { + self.displayLinkAnimator = DisplayLinkAnimator(duration: 0.2 * animationDurationFactor * UIView.animationDurationFactor(), from: 0.0, to: 0.999, update: { [weak self] value in + (self?.propertyAnimator as? UIViewPropertyAnimator)?.fractionComplete = value + }, completion: { + completedEffect = true + intermediateCompletion() + }) + } + self.effectView.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2 * animationDurationFactor, delay: 0.0, timingFunction: CAMediaTimingFunctionName.easeInEaseOut.rawValue, removeOnCompletion: false) + } else { + UIView.animate(withDuration: 0.21 * animationDurationFactor, animations: { + if #available(iOS 9.0, *) { + self.effectView.effect = nil + } else { + self.effectView.alpha = 0.0 + } + }, completion: { _ in + completedEffect = true + intermediateCompletion() + }) + } + + if !self.dimNode.isHidden { + self.dimNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: transitionDuration * animationDurationFactor, removeOnCompletion: false) + } else { + self.withoutBlurDimNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: transitionDuration * animationDurationFactor, removeOnCompletion: false) + } + + self.actionsContainerNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.15 * animationDurationFactor, removeOnCompletion: false, completion: { _ in + completedActionsNode = true + intermediateCompletion() + }) + self.actionsContainerNode.layer.animateScale(from: 1.0, to: 0.1, duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false) + + let animateOutToItem: Bool + switch result { + case .default, .custom: + animateOutToItem = true + case .dismissWithoutContent: + animateOutToItem = false + } + + if animateOutToItem, let originalProjectedContentViewFrame = self.originalProjectedContentViewFrame { + let localSourceFrame = self.view.convert(originalProjectedContentViewFrame.1, to: self.scrollNode.view) + let localContentSourceFrame: CGRect + if keepInPlace { + localContentSourceFrame = self.view.convert(originalProjectedContentViewFrame.1, to: self.contentContainerNode.view.superview) + } else { + localContentSourceFrame = localSourceFrame + } + + var actionsOffset: CGFloat = 0.0 + if case let .extracted(source) = self.legacySource, source.centerVertically { + actionsOffset = -localSourceFrame.width * 0.6 + } + + self.actionsContainerNode.layer.animatePosition(from: CGPoint(), to: CGPoint(x: localSourceFrame.center.x - self.actionsContainerNode.position.x, y: localSourceFrame.center.y - self.actionsContainerNode.position.y + actionsOffset), duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false, additive: true) + let contentContainerOffset = CGPoint(x: localContentSourceFrame.center.x - self.contentContainerNode.frame.center.x - contentParentNode.contentRect.minX, y: localContentSourceFrame.center.y - self.contentContainerNode.frame.center.y - contentParentNode.contentRect.minY) + self.contentContainerNode.layer.animatePosition(from: CGPoint(), to: contentContainerOffset, duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false, additive: true, completion: { _ in + completedContentNode = true + intermediateCompletion() + }) + contentParentNode.updateAbsoluteRect?(self.contentContainerNode.frame.offsetBy(dx: 0.0, dy: -self.scrollNode.view.contentOffset.y + contentContainerOffset.y), self.bounds.size) + contentParentNode.applyAbsoluteOffset?(CGPoint(x: 0.0, y: -contentContainerOffset.y), transitionCurve, transitionDuration) + + contentParentNode.willUpdateIsExtractedToContextPreview?(false, .animated(duration: 0.2, curve: .easeInOut)) + } else { + if let snapshotView = contentParentNode.contentNode.view.snapshotContentTree(keepTransform: true) { + self.contentContainerNode.view.addSubview(snapshotView) + } + + contentParentNode.addSubnode(contentParentNode.contentNode) + contentParentNode.isExtractedToContextPreview = false + contentParentNode.isExtractedToContextPreviewUpdated?(false) + + self.contentContainerNode.allowsGroupOpacity = true + self.contentContainerNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: transitionDuration * animationDurationFactor, removeOnCompletion: false, completion: { _ in + completedContentNode = true + intermediateCompletion() + }) + + contentParentNode.contentNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2) + contentParentNode.willUpdateIsExtractedToContextPreview?(false, .animated(duration: 0.2, curve: .easeInOut)) + } + case let .controller(source): + guard let maybeContentNode = self.contentContainerNode.contentNode, case let .controller(controller) = maybeContentNode else { + return + } + + let transitionInfo = source.transitionInfo() + + if transitionInfo == nil { + result = .dismissWithoutContent + } + + switch result { + case let .custom(value): + switch value { + case let .animated(duration, curve): + transitionDuration = duration + transitionCurve = curve + default: + break + } + default: + break + } + + self.isUserInteractionEnabled = false + self.isAnimatingOut = true + + self.scrollNode.view.setContentOffset(self.scrollNode.view.contentOffset, animated: false) + + var completedEffect = false + var completedContentNode = false + var completedActionsNode = false + + if let transitionInfo = transitionInfo, let (sourceView, sourceNodeRect) = transitionInfo.sourceNode() { + let projectedFrame = convertFrame(sourceNodeRect, from: sourceView, to: self.view) + self.originalProjectedContentViewFrame = (projectedFrame, projectedFrame) + + var updatedContentAreaInScreenSpace = transitionInfo.contentAreaInScreenSpace + updatedContentAreaInScreenSpace.origin.x = 0.0 + updatedContentAreaInScreenSpace.size.width = self.bounds.width + } + + let intermediateCompletion: () -> Void = { + if completedEffect && completedContentNode && completedActionsNode { + switch result { + case .default, .custom: + break + case .dismissWithoutContent: + break + } + + completion() + } + } + + if #available(iOS 10.0, *) { + if let propertyAnimator = self.propertyAnimator { + let propertyAnimator = propertyAnimator as? UIViewPropertyAnimator + propertyAnimator?.stopAnimation(true) + } + self.propertyAnimator = UIViewPropertyAnimator(duration: transitionDuration * UIView.animationDurationFactor(), curve: .easeInOut, animations: { [weak self] in + self?.effectView.effect = nil + }) + } + + if let _ = self.propertyAnimator { + if #available(iOSApplicationExtension 10.0, iOS 10.0, *) { + self.displayLinkAnimator = DisplayLinkAnimator(duration: 0.2 * animationDurationFactor * UIView.animationDurationFactor(), from: 0.0, to: 0.999, update: { [weak self] value in + (self?.propertyAnimator as? UIViewPropertyAnimator)?.fractionComplete = value + }, completion: { + completedEffect = true + intermediateCompletion() + }) + } + self.effectView.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.05 * animationDurationFactor, delay: 0.15, timingFunction: CAMediaTimingFunctionName.easeInEaseOut.rawValue, removeOnCompletion: false) + } else { + UIView.animate(withDuration: 0.21 * animationDurationFactor, animations: { + if #available(iOS 9.0, *) { + self.effectView.effect = nil + } else { + self.effectView.alpha = 0.0 + } + }, completion: { _ in + completedEffect = true + intermediateCompletion() + }) + } + + if !self.dimNode.isHidden { + self.dimNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: transitionDuration * animationDurationFactor, removeOnCompletion: false) + } else { + self.withoutBlurDimNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: transitionDuration * animationDurationFactor, removeOnCompletion: false) + } + self.actionsContainerNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2 * animationDurationFactor, removeOnCompletion: false, completion: { _ in + completedActionsNode = true + intermediateCompletion() + }) + self.contentContainerNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2 * animationDurationFactor, removeOnCompletion: false, completion: { _ in + }) + self.actionsContainerNode.layer.animateScale(from: 1.0, to: 0.1, duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false) + self.contentContainerNode.layer.animateScale(from: 1.0, to: 0.01, duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false) + + let animateOutToItem: Bool + switch result { + case .default, .custom: + animateOutToItem = true + case .dismissWithoutContent: + animateOutToItem = false + } + + if animateOutToItem, let originalProjectedContentViewFrame = self.originalProjectedContentViewFrame { + let localSourceFrame = self.view.convert(CGRect(origin: CGPoint(x: originalProjectedContentViewFrame.1.minX, y: originalProjectedContentViewFrame.1.minY), size: CGSize(width: originalProjectedContentViewFrame.1.width, height: originalProjectedContentViewFrame.1.height)), to: self.scrollNode.view) + + self.actionsContainerNode.layer.animatePosition(from: CGPoint(), to: CGPoint(x: localSourceFrame.center.x - self.actionsContainerNode.position.x, y: localSourceFrame.center.y - self.actionsContainerNode.position.y), duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false, additive: true) + let contentContainerOffset = CGPoint(x: localSourceFrame.center.x - self.contentContainerNode.frame.center.x, y: localSourceFrame.center.y - self.contentContainerNode.frame.center.y) + self.contentContainerNode.layer.animatePosition(from: CGPoint(), to: contentContainerOffset, duration: transitionDuration * animationDurationFactor, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false, additive: true, completion: { [weak self] _ in + completedContentNode = true + if let strongSelf = self, let contentNode = strongSelf.contentContainerNode.contentNode, case let .controller(controller) = contentNode { + controller.sourceView.isHidden = false + } + intermediateCompletion() + }) + } else { + if let contentNode = self.contentContainerNode.contentNode, case let .controller(controller) = contentNode { + controller.sourceView.isHidden = false + } + + if let snapshotView = controller.view.snapshotContentTree(keepTransform: true) { + self.contentContainerNode.view.addSubview(snapshotView) + } + + self.contentContainerNode.allowsGroupOpacity = true + self.contentContainerNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: transitionDuration * animationDurationFactor, removeOnCompletion: false, completion: { _ in + completedContentNode = true + intermediateCompletion() + }) + } + } + } + + func addRelativeContentOffset(_ offset: CGPoint, transition: ContainedViewLayoutTransition) { + if let sourceContainer = self.sourceContainer { + sourceContainer.addRelativeContentOffset(offset, transition: transition) + } + } + + func cancelReactionAnimation() { + if let sourceContainer = self.sourceContainer { + sourceContainer.cancelReactionAnimation() + } + } + + func animateOutToReaction(value: MessageReaction.Reaction, targetView: UIView, hideNode: Bool, animateTargetContainer: UIView?, addStandaloneReactionAnimation: ((StandaloneReactionAnimation) -> Void)?, reducedCurve: Bool, onHit: (() -> Void)?, completion: @escaping () -> Void) { + if let sourceContainer = self.sourceContainer { + sourceContainer.animateOutToReaction(value: value, targetView: targetView, hideNode: hideNode, animateTargetContainer: animateTargetContainer, addStandaloneReactionAnimation: addStandaloneReactionAnimation, reducedCurve: reducedCurve, onHit: onHit, completion: completion) + } + } + + func animateDismissalIfNeeded() { + guard let layout = self.validLayout, layout.metrics.isTablet else { + return + } + if let sourceContainer = self.sourceContainer { + sourceContainer.animateOut(result: .dismissWithoutContent, completion: {}) + return + } + } + + func getActionsMinHeight() -> ContextController.ActionsHeight? { + if !self.actionsContainerNode.bounds.height.isZero { + return ContextController.ActionsHeight( + minY: self.actionsContainerNode.frame.minY, + contentOffset: self.scrollNode.view.contentOffset.y + ) + } else { + return nil + } + } + + func setItemsSignal(items: Signal, minHeight: ContextController.ActionsHeight?, previousActionsTransition: ContextController.PreviousActionsTransition, animated: Bool) { + if let sourceContainer = self.sourceContainer { + sourceContainer.setItems(items: items, animated: animated) + } else { + self.legacyItems = items + self.itemsDisposable.set((items + |> deliverOnMainQueue).start(next: { [weak self] items in + guard let strongSelf = self else { + return + } + strongSelf.setItems(items: items, minHeight: minHeight, previousActionsTransition: previousActionsTransition) + })) + } + } + + private func setItems(items: ContextController.Items, minHeight: ContextController.ActionsHeight?, previousActionsTransition: ContextController.PreviousActionsTransition) { + if let sourceContainer = self.sourceContainer { + let disableAnimations = self.getController()?.immediateItemsTransitionAnimation == true + sourceContainer.setItems(items: .single(items), animated: !disableAnimations) + + if !self.didSetItemsReady { + self.didSetItemsReady = true + self.itemsReady.set(.single(true)) + } + return + } + + if let _ = self.currentItems, !self.didCompleteAnimationIn && self.getController()?.immediateItemsTransitionAnimation == true { + return + } + + self.currentItems = items + self.currentActionsMinHeight = minHeight + + let previousActionsContainerNode = self.actionsContainerNode + let previousActionsContainerFrame = previousActionsContainerNode.view.convert(previousActionsContainerNode.bounds, to: self.view) + self.actionsContainerNode = ContextActionsContainerNode(presentationData: self.presentationData, items: items, getController: { [weak self] in + return self?.getController() + }, actionSelected: { [weak self] result in + self?.beginDismiss(result) + }, requestLayout: { [weak self] in + self?.updateLayout() + }, feedbackTap: { [weak self] in + self?.hapticFeedback.tap() + }, blurBackground: self.blurBackground) + self.scrollNode.insertSubnode(self.actionsContainerNode, aboveSubnode: previousActionsContainerNode) + + if let layout = self.validLayout { + self.updateLayout(layout: layout, transition: self.didSetItemsReady ? .animated(duration: 0.3, curve: .spring) : .immediate, previousActionsContainerNode: previousActionsContainerNode, previousActionsContainerFrame: previousActionsContainerFrame, previousActionsTransition: previousActionsTransition) + } else { + previousActionsContainerNode.removeFromSupernode() + } + + if !self.didSetItemsReady { + self.didSetItemsReady = true + self.itemsReady.set(.single(true)) + } + } + + func pushItems(items: Signal) { + if let sourceContainer = self.sourceContainer { + sourceContainer.pushItems(items: items) + } + } + + func popItems() { + if let sourceContainer = self.sourceContainer { + sourceContainer.popItems() + } + } + + func updateTheme(presentationData: PresentationData) { + self.presentationData = presentationData + + self.dimNode.backgroundColor = presentationData.theme.contextMenu.dimColor + self.actionsContainerNode.updateTheme(presentationData: presentationData) + + if let validLayout = self.validLayout { + self.updateLayout(layout: validLayout, transition: .immediate, previousActionsContainerNode: nil, previousActionsContainerFrame: nil) + } + } + + func updateLayout() { + if let layout = self.validLayout { + self.updateLayout(layout: layout, transition: .immediate, previousActionsContainerNode: nil) + } + } + + func updateLayout(layout: ContainerViewLayout, transition: ContainedViewLayoutTransition, previousActionsContainerNode: ContextActionsContainerNode?, previousActionsContainerFrame: CGRect? = nil, previousActionsTransition: ContextController.PreviousActionsTransition = .scale) { + if self.isAnimatingOut || self.delayLayoutUpdate { + return + } + + self.validLayout = layout + + if let sourceContainer = self.sourceContainer { + transition.updateFrame(node: sourceContainer, frame: CGRect(origin: CGPoint(), size: layout.size)) + sourceContainer.update( + presentationData: self.presentationData, + layout: layout, + transition: transition + ) + return + } + + var actionsContainerTransition = transition + if previousActionsContainerNode != nil { + actionsContainerTransition = .immediate + } + + transition.updateFrame(view: self.effectView, frame: CGRect(origin: CGPoint(), size: layout.size)) + transition.updateFrame(node: self.dimNode, frame: CGRect(origin: CGPoint(), size: layout.size)) + transition.updateFrame(node: self.withoutBlurDimNode, frame: CGRect(origin: CGPoint(), size: layout.size)) + + switch layout.metrics.widthClass { + case .compact: + if case .reference = self.legacySource { + } else if case let .extracted(extractedSource) = self.legacySource, !extractedSource.blurBackground { + } else if self.effectView.superview == nil { + self.view.insertSubview(self.effectView, at: 0) + if #available(iOS 10.0, *) { + if let propertyAnimator = self.propertyAnimator { + let propertyAnimator = propertyAnimator as? UIViewPropertyAnimator + propertyAnimator?.stopAnimation(true) + } + } + self.effectView.effect = makeCustomZoomBlurEffect(isLight: presentationData.theme.rootController.keyboardColor == .light) + self.dimNode.alpha = 1.0 + } + self.dimNode.isHidden = false + self.withoutBlurDimNode.isHidden = true + case .regular: + if case .reference = self.legacySource { + } else if case let .extracted(extractedSource) = self.legacySource, !extractedSource.blurBackground { + } else if self.effectView.superview != nil { + self.effectView.removeFromSuperview() + self.withoutBlurDimNode.alpha = 1.0 + } + self.dimNode.isHidden = true + self.withoutBlurDimNode.isHidden = false + } + transition.updateFrame(node: self.clippingNode, frame: CGRect(origin: CGPoint(), size: layout.size)) + + transition.updateFrame(node: self.scrollNode, frame: CGRect(origin: CGPoint(), size: layout.size)) + + let actionsSideInset: CGFloat = layout.safeInsets.left + 12.0 + let contentTopInset: CGFloat = max(11.0, layout.statusBarHeight ?? 0.0) + + let actionsBottomInset: CGFloat = 11.0 + + if let contentNode = self.contentContainerNode.contentNode { + switch contentNode { + case let .reference(referenceNode): + let contentActionsSpacing: CGFloat = 8.0 + if let originalProjectedContentViewFrame = self.originalProjectedContentViewFrame { + let isInitialLayout = self.actionsContainerNode.frame.size.width.isZero + let previousContainerFrame = self.view.convert(self.contentContainerNode.frame, from: self.scrollNode.view) + + let realActionsSize = self.actionsContainerNode.updateLayout(widthClass: layout.metrics.widthClass, presentation: .inline, constrainedWidth: layout.size.width - actionsSideInset * 2.0, constrainedHeight: layout.size.height, transition: actionsContainerTransition) + let adjustedActionsSize = realActionsSize + + self.actionsContainerNode.updateSize(containerSize: realActionsSize, contentSize: realActionsSize) + let contentSize = originalProjectedContentViewFrame.1.size + self.contentContainerNode.updateLayout(size: contentSize, scaledSize: contentSize, transition: transition) + + let maximumActionsFrameOrigin = max(60.0, layout.size.height - layout.intrinsicInsets.bottom - actionsBottomInset - adjustedActionsSize.height) + + let originalActionsY = min(originalProjectedContentViewFrame.1.maxY + contentActionsSpacing, maximumActionsFrameOrigin) + let preferredActionsX = originalProjectedContentViewFrame.1.minX + + var originalActionsFrame = CGRect(origin: CGPoint(x: max(actionsSideInset, min(layout.size.width - adjustedActionsSize.width - actionsSideInset, preferredActionsX)), y: originalActionsY), size: realActionsSize) + let originalContentX: CGFloat = originalProjectedContentViewFrame.1.minX + let originalContentY = originalProjectedContentViewFrame.1.minY + + var originalContentFrame = CGRect(origin: CGPoint(x: originalContentX, y: originalContentY), size: originalProjectedContentViewFrame.1.size) + let topEdge = max(contentTopInset, self.contentAreaInScreenSpace?.minY ?? 0.0) + let bottomEdge = min(layout.size.height - layout.intrinsicInsets.bottom, self.contentAreaInScreenSpace?.maxY ?? layout.size.height) + + if originalContentFrame.minY < topEdge { + let requiredOffset = topEdge - originalContentFrame.minY + let availableOffset = max(0.0, layout.size.height - layout.intrinsicInsets.bottom - actionsBottomInset - originalActionsFrame.maxY) + let offset = min(requiredOffset, availableOffset) + originalActionsFrame = originalActionsFrame.offsetBy(dx: 0.0, dy: offset) + originalContentFrame = originalContentFrame.offsetBy(dx: 0.0, dy: offset) + } else if originalActionsFrame.maxY > bottomEdge { + let requiredOffset = bottomEdge - originalActionsFrame.maxY + let offset = requiredOffset + originalActionsFrame = originalActionsFrame.offsetBy(dx: 0.0, dy: offset) + originalContentFrame = originalContentFrame.offsetBy(dx: 0.0, dy: offset) + } + + var contentHeight = max(layout.size.height, max(layout.size.height, originalActionsFrame.maxY + actionsBottomInset) - originalContentFrame.minY + contentTopInset) + contentHeight = max(contentHeight, adjustedActionsSize.height + originalActionsFrame.minY + actionsBottomInset) + + var overflowOffset: CGFloat + var contentContainerFrame: CGRect + + overflowOffset = min(0.0, originalActionsFrame.minY - contentTopInset) + let contentParentNode = referenceNode + contentContainerFrame = originalContentFrame + if !overflowOffset.isZero { + let offsetDelta = contentParentNode.frame.height + 4.0 + overflowOffset += offsetDelta + overflowOffset = min(0.0, overflowOffset) + + originalActionsFrame.origin.x -= contentParentNode.frame.width + 14.0 + originalActionsFrame.origin.x = max(actionsSideInset, originalActionsFrame.origin.x) + + if originalActionsFrame.minX < contentContainerFrame.minX { + contentContainerFrame.origin.x = min(originalActionsFrame.maxX + 14.0, layout.size.width - actionsSideInset) + } + originalActionsFrame.origin.y += offsetDelta + if originalActionsFrame.maxY < originalContentFrame.maxY { + originalActionsFrame.origin.y += contentParentNode.frame.height + originalActionsFrame.origin.y = min(originalActionsFrame.origin.y, layout.size.height - originalActionsFrame.height - actionsBottomInset) + } + contentHeight -= offsetDelta + } + + if let customPosition = self.customPosition { + originalActionsFrame.origin.x = floor(originalContentFrame.center.x - originalActionsFrame.width / 2.0) + customPosition.x + originalActionsFrame.origin.y = floor(originalContentFrame.center.y - originalActionsFrame.height / 2.0) + customPosition.y + } + + let scrollContentSize = CGSize(width: layout.size.width, height: contentHeight) + if self.scrollNode.view.contentSize != scrollContentSize { + self.scrollNode.view.contentSize = scrollContentSize + } + self.actionsContainerNode.panSelectionGestureEnabled = scrollContentSize.height <= layout.size.height + + transition.updateFrame(node: self.contentContainerNode, frame: contentContainerFrame) + actionsContainerTransition.updateFrame(node: self.actionsContainerNode, frame: originalActionsFrame.offsetBy(dx: 0.0, dy: -overflowOffset)) + + if isInitialLayout { + let currentContainerFrame = self.view.convert(self.contentContainerNode.frame, from: self.scrollNode.view) + if overflowOffset < 0.0 { + transition.animateOffsetAdditive(node: self.scrollNode, offset: currentContainerFrame.minY - previousContainerFrame.minY) + } + } + } + case .extractedContainer: + break + case let .extracted(contentParentNode, keepInPlace): + var centerVertically = false + if case let .extracted(source) = self.legacySource, source.centerVertically { + centerVertically = true + } + let contentActionsSpacing: CGFloat = keepInPlace ? 16.0 : 8.0 + if let originalProjectedContentViewFrame = self.originalProjectedContentViewFrame { + let isInitialLayout = self.actionsContainerNode.frame.size.width.isZero + let previousContainerFrame = self.view.convert(self.contentContainerNode.frame, from: self.scrollNode.view) + + let constrainedActionsHeight: CGFloat + let constrainedActionsBottomInset: CGFloat + if let currentActionsMinHeight = self.currentActionsMinHeight { + constrainedActionsBottomInset = actionsBottomInset + layout.intrinsicInsets.bottom + constrainedActionsHeight = layout.size.height - currentActionsMinHeight.minY - constrainedActionsBottomInset + } else { + constrainedActionsHeight = layout.size.height + constrainedActionsBottomInset = 0.0 + } + + let realActionsSize = self.actionsContainerNode.updateLayout(widthClass: layout.metrics.widthClass, presentation: .inline, constrainedWidth: layout.size.width - actionsSideInset * 2.0, constrainedHeight: constrainedActionsHeight, transition: actionsContainerTransition) + let adjustedActionsSize = realActionsSize + + self.actionsContainerNode.updateSize(containerSize: realActionsSize, contentSize: realActionsSize) + let contentSize = originalProjectedContentViewFrame.1.size + self.contentContainerNode.updateLayout(size: contentSize, scaledSize: contentSize, transition: transition) + + let maximumActionsFrameOrigin = max(60.0, layout.size.height - layout.intrinsicInsets.bottom - actionsBottomInset - adjustedActionsSize.height) + let preferredActionsX: CGFloat + var originalActionsY: CGFloat + if centerVertically { + originalActionsY = min(originalProjectedContentViewFrame.1.maxY + contentActionsSpacing, maximumActionsFrameOrigin) + preferredActionsX = originalProjectedContentViewFrame.1.maxX - adjustedActionsSize.width + } else if keepInPlace { + originalActionsY = originalProjectedContentViewFrame.1.minY - contentActionsSpacing - adjustedActionsSize.height + preferredActionsX = max(actionsSideInset, originalProjectedContentViewFrame.1.maxX - adjustedActionsSize.width) + } else { + originalActionsY = min(originalProjectedContentViewFrame.1.maxY + contentActionsSpacing, maximumActionsFrameOrigin) + preferredActionsX = originalProjectedContentViewFrame.1.minX + } + + if let currentActionsMinHeight = self.currentActionsMinHeight { + originalActionsY = currentActionsMinHeight.minY + } + + var originalActionsFrame = CGRect(origin: CGPoint(x: max(actionsSideInset, min(layout.size.width - adjustedActionsSize.width - actionsSideInset, preferredActionsX)), y: originalActionsY), size: realActionsSize) + let originalContentX: CGFloat = originalProjectedContentViewFrame.1.minX + let originalContentY: CGFloat + if keepInPlace { + originalContentY = originalProjectedContentViewFrame.1.minY + } else { + originalContentY = originalActionsFrame.minY - contentActionsSpacing - originalProjectedContentViewFrame.1.size.height + } + var originalContentFrame = CGRect(origin: CGPoint(x: originalContentX, y: originalContentY), size: originalProjectedContentViewFrame.1.size) + let topEdge = max(contentTopInset, self.contentAreaInScreenSpace?.minY ?? 0.0) + if originalContentFrame.minY < topEdge { + let requiredOffset = topEdge - originalContentFrame.minY + let availableOffset = max(0.0, layout.size.height - layout.intrinsicInsets.bottom - actionsBottomInset - originalActionsFrame.maxY) + let offset = min(requiredOffset, availableOffset) + originalActionsFrame = originalActionsFrame.offsetBy(dx: 0.0, dy: offset) + originalContentFrame = originalContentFrame.offsetBy(dx: 0.0, dy: offset) + } + + var contentHeight: CGFloat + if keepInPlace { + contentHeight = max(layout.size.height, max(layout.size.height, originalActionsFrame.maxY + actionsBottomInset) - originalActionsFrame.minY + contentTopInset) + } else { + if self.currentActionsMinHeight != nil { + contentHeight = max(layout.size.height, max(layout.size.height, originalActionsFrame.maxY + actionsBottomInset + layout.intrinsicInsets.bottom)) + } else { + contentHeight = max(layout.size.height, max(layout.size.height, originalActionsFrame.maxY + actionsBottomInset + layout.intrinsicInsets.bottom) - originalContentFrame.minY + contentTopInset) + } + } + + var overflowOffset: CGFloat + var contentContainerFrame: CGRect + if centerVertically { + overflowOffset = 0.0 + if layout.size.width > layout.size.height, case .compact = layout.metrics.widthClass { + let totalWidth = originalContentFrame.width + originalActionsFrame.width + contentActionsSpacing + contentContainerFrame = CGRect(origin: CGPoint(x: floor((layout.size.width - totalWidth) / 2.0 + originalContentFrame.width * 0.1), y: floor((layout.size.height - originalContentFrame.height) / 2.0)), size: originalContentFrame.size) + originalActionsFrame.origin.x = contentContainerFrame.maxX + contentActionsSpacing + 14.0 + originalActionsFrame.origin.y = contentContainerFrame.origin.y + contentHeight = layout.size.height + } else { + let totalHeight = originalContentFrame.height + originalActionsFrame.height + contentContainerFrame = CGRect(origin: CGPoint(x: floor((layout.size.width - originalContentFrame.width) / 2.0), y: floor((layout.size.height - totalHeight) / 2.0)), size: originalContentFrame.size) + originalActionsFrame.origin.y = contentContainerFrame.maxY + contentActionsSpacing + } + } else if keepInPlace { + overflowOffset = min(0.0, originalActionsFrame.minY - contentTopInset) + contentContainerFrame = originalContentFrame.offsetBy(dx: -contentParentNode.contentRect.minX, dy: -contentParentNode.contentRect.minY) + if !overflowOffset.isZero { + let offsetDelta = contentParentNode.contentRect.height + 4.0 + overflowOffset += offsetDelta + overflowOffset = min(0.0, overflowOffset) + + originalActionsFrame.origin.x -= contentParentNode.contentRect.maxX - contentParentNode.contentRect.minX + 14.0 + originalActionsFrame.origin.x = max(actionsSideInset, originalActionsFrame.origin.x) + //originalActionsFrame.origin.y += contentParentNode.contentRect.height + if originalActionsFrame.minX < contentContainerFrame.minX { + contentContainerFrame.origin.x = min(originalActionsFrame.maxX + 14.0, layout.size.width - actionsSideInset) + } + originalActionsFrame.origin.y += offsetDelta + if originalActionsFrame.maxY < originalContentFrame.maxY { + originalActionsFrame.origin.y += contentParentNode.contentRect.height + originalActionsFrame.origin.y = min(originalActionsFrame.origin.y, layout.size.height - originalActionsFrame.height - actionsBottomInset) + } + contentHeight -= offsetDelta + } + } else { + overflowOffset = min(0.0, originalContentFrame.minY - contentTopInset) + contentContainerFrame = originalContentFrame.offsetBy(dx: -contentParentNode.contentRect.minX, dy: -overflowOffset - contentParentNode.contentRect.minY) + + if contentContainerFrame.maxX > layout.size.width { + contentContainerFrame = CGRect(origin: CGPoint(x: layout.size.width - contentContainerFrame.width - 11.0, y: contentContainerFrame.minY), size: contentContainerFrame.size) + } + } + + let scrollContentSize = CGSize(width: layout.size.width, height: contentHeight) + if self.scrollNode.view.contentSize != scrollContentSize { + self.scrollNode.view.contentSize = scrollContentSize + } + self.actionsContainerNode.panSelectionGestureEnabled = scrollContentSize.height <= layout.size.height + + transition.updateFrame(node: self.contentContainerNode, frame: contentContainerFrame) + actionsContainerTransition.updateFrame(node: self.actionsContainerNode, frame: originalActionsFrame.offsetBy(dx: 0.0, dy: -overflowOffset)) + + if isInitialLayout { + //let previousContentOffset = self.scrollNode.view.contentOffset.y + if !keepInPlace { + if let currentActionsMinHeight = self.currentActionsMinHeight { + self.scrollNode.view.contentOffset = CGPoint(x: 0.0, y: currentActionsMinHeight.contentOffset) + } else { + self.scrollNode.view.contentOffset = CGPoint(x: 0.0, y: -overflowOffset) + } + } + let currentContainerFrame = self.view.convert(self.contentContainerNode.frame, from: self.scrollNode.view) + var offset: CGFloat = 0.0 + //offset -= previousContentOffset - self.scrollNode.view.contentOffset.y + offset += previousContainerFrame.minY - currentContainerFrame.minY + transition.animatePositionAdditive(node: self.contentContainerNode, offset: CGPoint(x: 0.0, y: offset)) + if overflowOffset < 0.0 { + let _ = currentContainerFrame + let _ = previousContainerFrame + } + } + + let absoluteContentRect = contentContainerFrame.offsetBy(dx: 0.0, dy: -self.scrollNode.view.contentOffset.y) + + contentParentNode.updateAbsoluteRect?(absoluteContentRect, layout.size) + } + case let .controller(contentParentNode): + var projectedFrame: CGRect = convertFrame(contentParentNode.sourceView.bounds, from: contentParentNode.sourceView, to: self.view) + switch self.legacySource { + case let .controller(source): + let transitionInfo = source.transitionInfo() + if let (sourceView, sourceRect) = transitionInfo?.sourceNode() { + projectedFrame = convertFrame(sourceRect, from: sourceView, to: self.view) + } + default: + break + } + self.originalProjectedContentViewFrame = (projectedFrame, projectedFrame) + + if let originalProjectedContentViewFrame = self.originalProjectedContentViewFrame { + let contentActionsSpacing: CGFloat = actionsSideInset + let topEdge = max(contentTopInset, self.contentAreaInScreenSpace?.minY ?? 0.0) + + let isInitialLayout = self.actionsContainerNode.frame.size.width.isZero + let previousContainerFrame = self.view.convert(self.contentContainerNode.frame, from: self.scrollNode.view) + + let constrainedWidth: CGFloat + if layout.size.width < layout.size.height { + constrainedWidth = layout.size.width + } else { + constrainedWidth = floor(layout.size.width / 2.0) + } + + let actionsSize = self.actionsContainerNode.updateLayout(widthClass: layout.metrics.widthClass, presentation: .inline, constrainedWidth: constrainedWidth - actionsSideInset * 2.0, constrainedHeight: layout.size.height, transition: actionsContainerTransition) + let contentScale = (constrainedWidth - actionsSideInset * 2.0) / constrainedWidth + var contentUnscaledSize: CGSize + if case .compact = layout.metrics.widthClass { + self.actionsContainerNode.updateSize(containerSize: actionsSize, contentSize: actionsSize) + + let proposedContentHeight: CGFloat + if layout.size.width < layout.size.height { + proposedContentHeight = layout.size.height - topEdge - contentActionsSpacing - actionsSize.height - layout.intrinsicInsets.bottom - actionsBottomInset + } else { + proposedContentHeight = layout.size.height - topEdge - topEdge + + let maxActionsHeight = layout.size.height - topEdge - topEdge + self.actionsContainerNode.updateSize(containerSize: CGSize(width: actionsSize.width, height: min(actionsSize.height, maxActionsHeight)), contentSize: actionsSize) + } + contentUnscaledSize = CGSize(width: constrainedWidth, height: max(100.0, proposedContentHeight)) + + if let preferredSize = contentParentNode.controller.preferredContentSizeForLayout(ContainerViewLayout(size: contentUnscaledSize, metrics: LayoutMetrics(widthClass: .compact, heightClass: .compact, orientation: nil), deviceMetrics: layout.deviceMetrics, intrinsicInsets: UIEdgeInsets(), safeInsets: UIEdgeInsets(), additionalInsets: UIEdgeInsets(), statusBarHeight: nil, inputHeight: nil, inputHeightIsInteractivellyChanging: false, inVoiceOver: false)) { + contentUnscaledSize = preferredSize + } + } else { + let maxActionsHeight = layout.size.height - layout.intrinsicInsets.bottom - actionsBottomInset - actionsSize.height + self.actionsContainerNode.updateSize(containerSize: CGSize(width: actionsSize.width, height: min(actionsSize.height, maxActionsHeight)), contentSize: actionsSize) + + let proposedContentHeight = layout.size.height - topEdge - contentActionsSpacing - actionsSize.height - layout.intrinsicInsets.bottom - actionsBottomInset + contentUnscaledSize = CGSize(width: min(layout.size.width, 340.0), height: min(568.0, proposedContentHeight)) + + if let preferredSize = contentParentNode.controller.preferredContentSizeForLayout(ContainerViewLayout(size: contentUnscaledSize, metrics: LayoutMetrics(widthClass: .compact, heightClass: .compact, orientation: nil), deviceMetrics: layout.deviceMetrics, intrinsicInsets: UIEdgeInsets(), safeInsets: UIEdgeInsets(), additionalInsets: UIEdgeInsets(), statusBarHeight: nil, inputHeight: nil, inputHeightIsInteractivellyChanging: false, inVoiceOver: false)) { + contentUnscaledSize = preferredSize + } + } + let contentSize = CGSize(width: floor(contentUnscaledSize.width * contentScale), height: floor(contentUnscaledSize.height * contentScale)) + + self.contentContainerNode.updateLayout(size: contentUnscaledSize, scaledSize: contentSize, transition: transition) + + let maximumActionsFrameOrigin = max(60.0, layout.size.height - layout.intrinsicInsets.bottom - actionsBottomInset - actionsSize.height) + var originalActionsFrame: CGRect + var originalContentFrame: CGRect + var contentHeight: CGFloat + if case .compact = layout.metrics.widthClass { + if layout.size.width < layout.size.height { + let sideInset = floor((layout.size.width - max(contentSize.width, actionsSize.width)) / 2.0) + originalActionsFrame = CGRect(origin: CGPoint(x: sideInset, y: min(maximumActionsFrameOrigin, floor((layout.size.height - contentActionsSpacing - contentSize.height) / 2.0) + contentSize.height + contentActionsSpacing)), size: actionsSize) + originalContentFrame = CGRect(origin: CGPoint(x: sideInset, y: originalActionsFrame.minY - contentActionsSpacing - contentSize.height), size: contentSize) + if originalContentFrame.minY < topEdge { + let requiredOffset = topEdge - originalContentFrame.minY + let availableOffset = max(0.0, layout.size.height - layout.intrinsicInsets.bottom - actionsBottomInset - originalActionsFrame.maxY) + let offset = min(requiredOffset, availableOffset) + originalActionsFrame = originalActionsFrame.offsetBy(dx: 0.0, dy: offset) + originalContentFrame = originalContentFrame.offsetBy(dx: 0.0, dy: offset) + } + contentHeight = max(layout.size.height, max(layout.size.height, originalActionsFrame.maxY + actionsBottomInset) - originalContentFrame.minY + contentTopInset) + } else { + originalContentFrame = CGRect(origin: CGPoint(x: floor((layout.size.width - contentSize.width - actionsSideInset - actionsSize.width) / 2.0), y: floor((layout.size.height - contentSize.height) / 2.0)), size: contentSize) + originalActionsFrame = CGRect(origin: CGPoint(x: originalContentFrame.maxX + actionsSideInset, y: max(topEdge, originalContentFrame.minY)), size: actionsSize) + contentHeight = max(layout.size.height, max(originalContentFrame.maxY, originalActionsFrame.maxY)) + } + } else { + originalContentFrame = CGRect(origin: CGPoint(x: floor(originalProjectedContentViewFrame.1.midX - contentSize.width / 2.0), y: floor(originalProjectedContentViewFrame.1.midY - contentSize.height / 2.0)), size: contentSize) + originalContentFrame.origin.x = min(originalContentFrame.origin.x, layout.size.width - actionsSideInset - contentSize.width) + originalContentFrame.origin.x = max(originalContentFrame.origin.x, actionsSideInset) + originalContentFrame.origin.y = min(originalContentFrame.origin.y, layout.size.height - layout.intrinsicInsets.bottom - actionsSideInset - contentSize.height) + originalContentFrame.origin.y = max(originalContentFrame.origin.y, contentTopInset) + if originalContentFrame.maxX <= layout.size.width - actionsSideInset - actionsSize.width - contentActionsSpacing { + originalActionsFrame = CGRect(origin: CGPoint(x: originalContentFrame.maxX + contentActionsSpacing, y: originalContentFrame.minY), size: actionsSize) + if originalActionsFrame.maxX > layout.size.width - actionsSideInset { + let offset = originalActionsFrame.maxX - (layout.size.width - actionsSideInset) + originalActionsFrame.origin.x -= offset + originalContentFrame.origin.x -= offset + } + } else { + originalActionsFrame = CGRect(origin: CGPoint(x: originalContentFrame.minX - contentActionsSpacing - actionsSize.width, y: originalContentFrame.minY), size: actionsSize) + if originalActionsFrame.minX < actionsSideInset { + let offset = actionsSideInset - originalActionsFrame.minX + originalActionsFrame.origin.x += offset + originalContentFrame.origin.x += offset + } + } + contentHeight = layout.size.height + contentHeight = max(contentHeight, originalActionsFrame.maxY + actionsBottomInset) + contentHeight = max(contentHeight, originalContentFrame.maxY + actionsBottomInset) + } + + let scrollContentSize = CGSize(width: layout.size.width, height: contentHeight) + if self.scrollNode.view.contentSize != scrollContentSize { + self.scrollNode.view.contentSize = scrollContentSize + } + self.actionsContainerNode.panSelectionGestureEnabled = true + + let overflowOffset = min(0.0, originalContentFrame.minY - contentTopInset) + + let contentContainerFrame = originalContentFrame + transition.updateFrame(node: self.contentContainerNode, frame: contentContainerFrame.offsetBy(dx: 0.0, dy: -overflowOffset)) + actionsContainerTransition.updateFrame(node: self.actionsContainerNode, frame: originalActionsFrame.offsetBy(dx: 0.0, dy: -overflowOffset)) + + if isInitialLayout { + self.scrollNode.view.contentOffset = CGPoint(x: 0.0, y: -overflowOffset) + let currentContainerFrame = self.view.convert(self.contentContainerNode.frame, from: self.scrollNode.view) + if overflowOffset < 0.0 { + transition.animateOffsetAdditive(node: self.scrollNode, offset: currentContainerFrame.minY - previousContainerFrame.minY) + } + } + } + } + } + + if let previousActionsContainerNode = previousActionsContainerNode { + if transition.isAnimated && self.getController()?.immediateItemsTransitionAnimation == false { + if previousActionsContainerNode.hasAdditionalActions && !self.actionsContainerNode.hasAdditionalActions && self.getController()?.useComplexItemsTransitionAnimation == true { + var initialFrame = self.actionsContainerNode.frame + let delta = (previousActionsContainerNode.frame.height - self.actionsContainerNode.frame.height) + initialFrame.origin.y = self.actionsContainerNode.frame.minY + previousActionsContainerNode.frame.height - self.actionsContainerNode.frame.height + transition.animateFrame(node: self.actionsContainerNode, from: initialFrame) + transition.animatePosition(node: previousActionsContainerNode, to: CGPoint(x: 0.0, y: -delta), removeOnCompletion: false, additive: true) + previousActionsContainerNode.animateOut(offset: delta, transition: transition) + + previousActionsContainerNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, removeOnCompletion: false, completion: { [weak previousActionsContainerNode] _ in + previousActionsContainerNode?.removeFromSupernode() + }) + self.actionsContainerNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2) + } else { + if let previousActionsContainerFrame = previousActionsContainerFrame { + previousActionsContainerNode.frame = self.view.convert(previousActionsContainerFrame, to: self.actionsContainerNode.view.superview!) + } + + switch previousActionsTransition { + case .scale: + transition.updateTransformScale(node: previousActionsContainerNode, scale: 0.1) + previousActionsContainerNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, removeOnCompletion: false, completion: { [weak previousActionsContainerNode] _ in + previousActionsContainerNode?.removeFromSupernode() + }) + + transition.animateTransformScale(node: self.actionsContainerNode, from: 0.1) + self.actionsContainerNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2) + case let .slide(forward): + let deltaY = self.actionsContainerNode.frame.minY - previousActionsContainerNode.frame.minY + var previousNodePosition = previousActionsContainerNode.position.offsetBy(dx: 0.0, dy: deltaY) + let additionalHorizontalOffset: CGFloat = 20.0 + let currentNodeOffset: CGFloat + if forward { + previousNodePosition = previousNodePosition.offsetBy(dx: -previousActionsContainerNode.frame.width / 2.0 - additionalHorizontalOffset, dy: -previousActionsContainerNode.frame.height / 2.0) + currentNodeOffset = self.actionsContainerNode.bounds.width / 2.0 + additionalHorizontalOffset + } else { + previousNodePosition = previousNodePosition.offsetBy(dx: previousActionsContainerNode.frame.width / 2.0 + additionalHorizontalOffset, dy: -previousActionsContainerNode.frame.height / 2.0) + currentNodeOffset = -self.actionsContainerNode.bounds.width / 2.0 - additionalHorizontalOffset + } + transition.updatePosition(node: previousActionsContainerNode, position: previousNodePosition) + transition.updateTransformScale(node: previousActionsContainerNode, scale: 0.01) + previousActionsContainerNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, removeOnCompletion: false, completion: { [weak previousActionsContainerNode] _ in + previousActionsContainerNode?.removeFromSupernode() + }) + + transition.animatePositionAdditive(node: self.actionsContainerNode, offset: CGPoint(x: currentNodeOffset, y: -deltaY - self.actionsContainerNode.bounds.height / 2.0)) + transition.animateTransformScale(node: self.actionsContainerNode, from: 0.01) + self.actionsContainerNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2) + } + } + } else { + previousActionsContainerNode.removeFromSupernode() + } + } + + transition.updateFrame(node: self.dismissNode, frame: CGRect(origin: CGPoint(), size: self.scrollNode.view.contentSize)) + self.dismissAccessibilityArea.frame = CGRect(origin: CGPoint(), size: self.scrollNode.view.contentSize) + } + + func scrollViewDidScroll(_ scrollView: UIScrollView) { + guard let layout = self.validLayout else { + return + } + if let maybeContentNode = self.contentContainerNode.contentNode, case let .extracted(contentParentNode, keepInPlace) = maybeContentNode { + let contentContainerFrame = self.contentContainerNode.frame + let absoluteRect: CGRect + if keepInPlace { + absoluteRect = contentContainerFrame + } else { + absoluteRect = contentContainerFrame.offsetBy(dx: 0.0, dy: -self.scrollNode.view.contentOffset.y) + } + contentParentNode.updateAbsoluteRect?(absoluteRect, layout.size) + } + } + + override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + if !self.bounds.contains(point) { + return nil + } + if !self.isUserInteractionEnabled { + return nil + } + + if let controller = self.getController() as? ContextController { + var innerResult: UIView? + controller.forEachController { c in + if let c = c as? UndoOverlayController { + if let result = c.view.hitTest(self.view.convert(point, to: c.view), with: event) { + innerResult = result + return false + } + } + return true + } + if let innerResult = innerResult { + return innerResult + } + } + + if let sourceContainer = self.sourceContainer { + return sourceContainer.hitTest(self.view.convert(point, to: sourceContainer.view), with: event) + } + + let mappedPoint = self.view.convert(point, to: self.scrollNode.view) + var maybePassthrough: ContextControllerImpl.HandledTouchEvent? + if let maybeContentNode = self.contentContainerNode.contentNode { + switch maybeContentNode { + case .reference: + if let controller = self.getController() as? ContextControllerImpl, let passthroughTouchEvent = controller.passthroughTouchEvent { + maybePassthrough = passthroughTouchEvent(self.view, point) + } + case let .extracted(contentParentNode, _): + if case let .extracted(source) = self.legacySource { + if !source.ignoreContentTouches { + let contentPoint = self.view.convert(point, to: contentParentNode.contentNode.view) + if let result = contentParentNode.contentNode.customHitTest?(contentPoint) { + return result + } else if let result = contentParentNode.contentNode.hitTest(contentPoint, with: event) { + if result is TextSelectionNodeView { + return result + } else if contentParentNode.contentRect.contains(contentPoint) { + return contentParentNode.contentNode.view + } + } + } + } + case .extractedContainer: + break + case let .controller(controller): + var passthrough = false + switch self.legacySource { + case let .controller(controllerSource): + passthrough = controllerSource.passthroughTouches + default: + break + } + if passthrough { + let controllerPoint = self.view.convert(point, to: controller.controller.view) + if let result = controller.controller.view.hitTest(controllerPoint, with: event) { + return result + } + } + } + } + + if self.actionsContainerNode.frame.contains(mappedPoint) { + return self.actionsContainerNode.hitTest(self.view.convert(point, to: self.actionsContainerNode.view), with: event) + } + + if let maybePassthrough = maybePassthrough { + switch maybePassthrough { + case .ignore: + break + case let .dismiss(consume, hitTestResult): + self.getController()?.dismiss(completion: nil) + + if let hitTestResult = hitTestResult { + return hitTestResult + } + if !consume { + return nil + } + } + } + + return self.dismissNode.view + } + + fileprivate func performHighlightedAction() { + self.sourceContainer?.performHighlightedAction() + } + + fileprivate func decreaseHighlightedIndex() { + self.sourceContainer?.decreaseHighlightedIndex() + } + + fileprivate func increaseHighlightedIndex() { + self.sourceContainer?.increaseHighlightedIndex() + } +} + +public final class ContextControllerImpl: ViewController, ContextController, StandalonePresentableController, ContextControllerProtocol, KeyShortcutResponder { + private let context: AccountContext? + private var presentationData: PresentationData + private let configuration: ContextController.Configuration + + private let _ready = Promise() + override public var ready: Promise { + return self._ready + } + + private weak var recognizer: TapLongTapOrDoubleTapGestureRecognizer? + private weak var gesture: ContextGesture? + + private var animatedDidAppear = false + private var wasDismissed = false + private var dismissOnInputClose: (result: ContextMenuActionResult, completion: (() -> Void)?)? + private var dismissToReactionOnInputClose: (value: MessageReaction.Reaction, targetView: UIView, hideNode: Bool, animateTargetContainer: UIView?, addStandaloneReactionAnimation: ((StandaloneReactionAnimation) -> Void)?, completion: (() -> Void)?)? + + override public var overlayWantsToBeBelowKeyboard: Bool { + if self.isNodeLoaded { + return self.controllerNode.overlayWantsToBeBelowKeyboard + } else { + return false + } + } + + var controllerNode: ContextControllerNode { + return self.displayNode as! ContextControllerNode + } + + public var dismissed: (() -> Void)? + public var dismissedForCancel: (() -> Void)? { + didSet { + self.controllerNode.dismissedForCancel = self.dismissedForCancel + } + } + + public var useComplexItemsTransitionAnimation = false + public var immediateItemsTransitionAnimation = false + let workaroundUseLegacyImplementation: Bool + let disableScreenshots: Bool + let hideReactionPanelTail: Bool + + public var passthroughTouchEvent: ((UIView, CGPoint) -> HandledTouchEvent)? + + private var shouldBeDismissedDisposable: Disposable? + + public var reactionSelected: ((UpdateMessageReaction, Bool) -> Void)? + public var premiumReactionsSelected: (() -> Void)? + + public var getOverlayViews: (() -> [UIView])? + + public init( + context: AccountContext? = nil, + presentationData: PresentationData, + configuration: ContextController.Configuration, + recognizer: TapLongTapOrDoubleTapGestureRecognizer? = nil, + gesture: ContextGesture? = nil, + workaroundUseLegacyImplementation: Bool = false, + disableScreenshots: Bool = false, + hideReactionPanelTail: Bool = false + ) { + self.context = context + self.presentationData = presentationData + self.configuration = configuration + self.recognizer = recognizer + self.gesture = gesture + self.workaroundUseLegacyImplementation = workaroundUseLegacyImplementation + self.disableScreenshots = disableScreenshots + self.hideReactionPanelTail = hideReactionPanelTail + + super.init(navigationBarPresentationData: nil) + + if let mainSource = configuration.sources.first(where: { $0.id == configuration.initialId }) { + switch mainSource.source { + case let .location(locationSource): + self.statusBar.statusBarStyle = .Ignore + + self.shouldBeDismissedDisposable = (locationSource.shouldBeDismissed + |> filter { $0 } + |> take(1) + |> deliverOnMainQueue).start(next: { [weak self] _ in + guard let strongSelf = self else { + return + } + strongSelf.dismiss(result: .default, completion: {}) + }).strict() + case let .reference(referenceSource): + self.statusBar.statusBarStyle = .Ignore + + self.shouldBeDismissedDisposable = (referenceSource.shouldBeDismissed + |> filter { $0 } + |> take(1) + |> deliverOnMainQueue).start(next: { [weak self] _ in + guard let strongSelf = self else { + return + } + strongSelf.dismiss(result: .default, completion: {}) + }).strict() + case let .extracted(extractedSource): + if extractedSource.blurBackground { + self.statusBar.statusBarStyle = .Hide + } else { + self.statusBar.statusBarStyle = .Ignore + } + self.shouldBeDismissedDisposable = (extractedSource.shouldBeDismissed + |> filter { $0 } + |> take(1) + |> deliverOnMainQueue).start(next: { [weak self] _ in + guard let strongSelf = self else { + return + } + strongSelf.dismiss(result: .default, completion: {}) + }).strict() + case .controller: + self.statusBar.statusBarStyle = .Hide + } + } + + self.lockOrientation = true + self.blocksBackgroundWhenInOverlay = true + } + + required init(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + deinit { + self.shouldBeDismissedDisposable?.dispose() + } + + override public func loadDisplayNode() { + self.displayNode = ContextControllerNode(controller: self, context: self.context, presentationData: self.presentationData, configuration: self.configuration, beginDismiss: { [weak self] result in + self?.dismiss(result: result, completion: nil) + }, recognizer: self.recognizer, gesture: self.gesture, beganAnimatingOut: { [weak self] in + guard let strongSelf = self else { + return + } + + strongSelf.statusBar.statusBarStyle = .Ignore + + strongSelf.forEachController { c in + if let c = c as? UndoOverlayController { + c.dismiss() + } + return true + } + }, attemptTransitionControllerIntoNavigation: { + }) + self.controllerNode.dismissedForCancel = self.dismissedForCancel + self.displayNodeDidLoad() + + self._ready.set(combineLatest(queue: .mainQueue(), self.controllerNode.itemsReady.get(), self.controllerNode.contentReady.get()) + |> map { values in + return values.0 && values.1 + }) + } + + override public func containerLayoutUpdated(_ layout: ContainerViewLayout, transition: ContainedViewLayoutTransition) { + super.containerLayoutUpdated(layout, transition: transition) + + self.controllerNode.updateLayout(layout: layout, transition: transition, previousActionsContainerNode: nil) + + if (layout.inputHeight ?? 0.0) == 0.0 { + if let dismissOnInputClose = self.dismissOnInputClose { + self.dismissOnInputClose = nil + DispatchQueue.main.async { + self.dismiss(result: dismissOnInputClose.result, completion: dismissOnInputClose.completion) + } + } else if let args = self.dismissToReactionOnInputClose { + self.dismissToReactionOnInputClose = nil + DispatchQueue.main.async { + self.dismissWithReactionImpl(value: args.value, targetView: args.targetView, hideNode: args.hideNode, animateTargetContainer: args.animateTargetContainer, addStandaloneReactionAnimation: args.addStandaloneReactionAnimation, reducedCurve: true, onHit: nil, completion: args.completion) + } + } + } + } + + override public func viewDidAppear(_ animated: Bool) { + if self.ignoreAppearanceMethodInvocations() { + return + } + super.viewDidAppear(animated) + + if !self.wasDismissed && !self.animatedDidAppear { + self.animatedDidAppear = true + self.controllerNode.animateIn() + } + } + + public func getActionsMinHeight() -> ContextController.ActionsHeight? { + if self.isNodeLoaded { + return self.controllerNode.getActionsMinHeight() + } + return nil + } + + public func setItems(_ items: Signal, minHeight: ContextController.ActionsHeight?, animated: Bool) { + //self.items = items + + if self.isNodeLoaded { + self.immediateItemsTransitionAnimation = false + self.controllerNode.setItemsSignal(items: items, minHeight: minHeight, previousActionsTransition: .scale, animated: animated) + } else { + assertionFailure() + } + } + + public func setItems(_ items: Signal, minHeight: ContextController.ActionsHeight?, previousActionsTransition: ContextController.PreviousActionsTransition) { + //self.items = items + + if self.isNodeLoaded { + self.controllerNode.setItemsSignal(items: items, minHeight: minHeight, previousActionsTransition: previousActionsTransition, animated: true) + } else { + assertionFailure() + } + } + + public func pushItems(items: Signal) { + if !self.isNodeLoaded { + return + } + self.controllerNode.pushItems(items: items) + } + + public func popItems() { + if !self.isNodeLoaded { + return + } + self.controllerNode.popItems() + } + + public func updateTheme(presentationData: PresentationData) { + self.presentationData = presentationData + if self.isNodeLoaded { + self.controllerNode.updateTheme(presentationData: presentationData) + } + } + + public func dismiss(result: ContextMenuActionResult, completion: (() -> Void)?) { + if let mainSource = self.configuration.sources.first(where: { $0.id == self.configuration.initialId }), case let .reference(source) = mainSource.source, source.forceDisplayBelowKeyboard { + + } else if viewTreeContainsFirstResponder(view: self.view) { + self.dismissOnInputClose = (result, completion) + self.view.endEditing(true) + return + } + + if !self.wasDismissed { + self.wasDismissed = true + + self.controllerNode.animateOut(result: result, completion: { [weak self] in + self?.presentingViewController?.dismiss(animated: false, completion: nil) + completion?() + }) + self.dismissed?() + } + } + + override public func dismiss(completion: (() -> Void)? = nil) { + self.dismiss(result: .default, completion: completion) + } + + public func dismissWithCustomTransition(transition: ContainedViewLayoutTransition, completion: (() -> Void)? = nil) { + self.dismiss(result: .custom(transition), completion: nil) + } + + public func dismissWithoutContent() { + self.dismiss(result: .dismissWithoutContent, completion: nil) + } + + public func dismissNow() { + self.presentingViewController?.dismiss(animated: false, completion: nil) + self.dismissed?() + } + + public func dismissWithReaction(value: MessageReaction.Reaction, targetView: UIView, hideNode: Bool, animateTargetContainer: UIView?, addStandaloneReactionAnimation: ((StandaloneReactionAnimation) -> Void)?, onHit: (() -> Void)?, completion: (() -> Void)?) { + self.dismissWithReactionImpl(value: value, targetView: targetView, hideNode: hideNode, animateTargetContainer: animateTargetContainer, addStandaloneReactionAnimation: addStandaloneReactionAnimation, reducedCurve: false, onHit: onHit, completion: completion) + } + + private func dismissWithReactionImpl(value: MessageReaction.Reaction, targetView: UIView, hideNode: Bool, animateTargetContainer: UIView?, addStandaloneReactionAnimation: ((StandaloneReactionAnimation) -> Void)?, reducedCurve: Bool, onHit: (() -> Void)?, completion: (() -> Void)?) { + if viewTreeContainsFirstResponder(view: self.view) { + self.dismissToReactionOnInputClose = (value, targetView, hideNode, animateTargetContainer, addStandaloneReactionAnimation, completion) + self.view.endEditing(true) + return + } + + if !self.wasDismissed { + self.wasDismissed = true + self.controllerNode.animateOutToReaction(value: value, targetView: targetView, hideNode: hideNode, animateTargetContainer: animateTargetContainer, addStandaloneReactionAnimation: addStandaloneReactionAnimation, reducedCurve: reducedCurve, onHit: onHit, completion: { [weak self] in + self?.presentingViewController?.dismiss(animated: false, completion: nil) + completion?() + }) + self.dismissed?() + } + } + + public func animateDismissalIfNeeded() { + self.controllerNode.animateDismissalIfNeeded() + } + + public func cancelReactionAnimation() { + self.controllerNode.cancelReactionAnimation() + } + + public func addRelativeContentOffset(_ offset: CGPoint, transition: ContainedViewLayoutTransition) { + self.controllerNode.addRelativeContentOffset(offset, transition: transition) + } + + public var keyShortcuts: [KeyShortcut] { + return [ + KeyShortcut( + input: UIKeyCommand.inputEscape, + modifiers: [], + action: { [weak self] in + self?.dismissWithoutContent() + } + ), + KeyShortcut( + input: "W", + modifiers: [.command], + action: { [weak self] in + self?.dismissWithoutContent() + } + ), + KeyShortcut( + input: "\r", + modifiers: [], + action: { [weak self] in + self?.controllerNode.performHighlightedAction() + } + ), + KeyShortcut( + input: UIKeyCommand.inputUpArrow, + modifiers: [], + action: { [weak self] in + self?.controllerNode.decreaseHighlightedIndex() + } + ), + KeyShortcut( + input: UIKeyCommand.inputDownArrow, + modifiers: [], + action: { [weak self] in + self?.controllerNode.increaseHighlightedIndex() + } + ) + ] + } +} diff --git a/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextControllerPresentationNode.swift b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextControllerPresentationNode.swift new file mode 100644 index 00000000..a216c408 --- /dev/null +++ b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextControllerPresentationNode.swift @@ -0,0 +1,42 @@ +import Foundation +import UIKit +import AsyncDisplayKit +import Display +import TelegramPresentationData +import TextSelectionNode +import TelegramCore +import SwiftSignalKit +import ReactionSelectionNode +import ContextUI + +enum ContextControllerPresentationNodeStateTransition { + case animateIn + case animateOut(result: ContextMenuActionResult, completion: () -> Void) +} + +protocol ContextControllerPresentationNode: ASDisplayNode { + var ready: Signal { get } + + func replaceItems(items: ContextController.Items, animated: Bool?) + func pushItems(items: ContextController.Items) + func popItems() + func wantsDisplayBelowKeyboard() -> Bool + + func update( + presentationData: PresentationData, + layout: ContainerViewLayout, + transition: ContainedViewLayoutTransition, + stateTransition: ContextControllerPresentationNodeStateTransition? + ) + + func animateOutToReaction(value: MessageReaction.Reaction, targetView: UIView, hideNode: Bool, animateTargetContainer: UIView?, addStandaloneReactionAnimation: ((StandaloneReactionAnimation) -> Void)?, reducedCurve: Bool, onHit: (() -> Void)?, completion: @escaping () -> Void) + func cancelReactionAnimation() + + func highlightGestureMoved(location: CGPoint, hover: Bool) + func highlightGestureFinished(performAction: Bool) + + func decreaseHighlightedIndex() + func increaseHighlightedIndex() + + func addRelativeContentOffset(_ offset: CGPoint, transition: ContainedViewLayoutTransition) +} diff --git a/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextSourceContainer.swift b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextSourceContainer.swift new file mode 100644 index 00000000..eb911f2e --- /dev/null +++ b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ContextSourceContainer.swift @@ -0,0 +1,886 @@ +import Foundation +import UIKit +import AsyncDisplayKit +import Display +import TelegramPresentationData +import SwiftSignalKit +import TelegramCore +import ReactionSelectionNode +import ComponentFlow +import TabSelectorComponent +import PlainButtonComponent +import MultilineTextComponent +import ComponentDisplayAdapters +import AccountContext +import ContextUI + +final class ContextSourceContainer: ASDisplayNode { + final class Source { + weak var controller: ContextControllerImpl? + + let id: AnyHashable + let title: String + let footer: String? + let context: AccountContext? + let source: ContextContentSource + let closeActionTitle: String? + let closeAction: (() -> Void)? + + private var _presentationNode: ContextControllerPresentationNode? + var presentationNode: ContextControllerPresentationNode { + return self._presentationNode! + } + + var currentPresentationStateTransition: ContextControllerPresentationNodeStateTransition? + + var validLayout: ContainerViewLayout? + var presentationData: PresentationData? + var delayLayoutUpdate: Bool = false + var isAnimatingOut: Bool = false + + var itemsDisposables = DisposableSet() + + let ready = Promise() + private let contentReady = Promise() + private let actionsReady = Promise() + + init( + controller: ContextControllerImpl, + id: AnyHashable, + title: String, + footer: String?, + context: AccountContext?, + source: ContextContentSource, + items: Signal, + closeActionTitle: String? = nil, + closeAction: (() -> Void)? = nil + ) { + self.controller = controller + self.id = id + self.title = title + self.footer = footer + self.context = context + self.source = source + self.closeActionTitle = closeActionTitle + self.closeAction = closeAction + + self.ready.set(combineLatest(queue: .mainQueue(), self.contentReady.get(), self.actionsReady.get()) + |> map { a, b -> Bool in + return a && b + } + |> distinctUntilChanged) + + switch source { + case let .location(source): + self.contentReady.set(.single(true)) + + let presentationNode = ContextControllerExtractedPresentationNode( + context: self.context, + getController: { [weak self] in + guard let self else { + return nil + } + return self.controller + }, + requestUpdate: { [weak self] transition in + guard let self else { + return + } + self.update(transition: transition) + }, + requestUpdateOverlayWantsToBeBelowKeyboard: { [weak self] transition in + guard let self else { + return + } + if let controller = self.controller { + controller.overlayWantsToBeBelowKeyboardUpdated(transition: transition) + } + }, + requestDismiss: { [weak self] result in + guard let self, let controller = self.controller else { + return + } + controller.controllerNode.dismissedForCancel?() + controller.controllerNode.beginDismiss(result) + }, + requestAnimateOut: { [weak self] result, completion in + guard let self, let controller = self.controller else { + return + } + controller.controllerNode.animateOut(result: result, completion: completion) + }, + source: .location(source) + ) + self._presentationNode = presentationNode + case let .reference(source): + self.contentReady.set(.single(true)) + + let presentationNode = ContextControllerExtractedPresentationNode( + context: self.context, + getController: { [weak self] in + guard let self else { + return nil + } + return self.controller + }, + requestUpdate: { [weak self] transition in + guard let self else { + return + } + self.update(transition: transition) + }, + requestUpdateOverlayWantsToBeBelowKeyboard: { [weak self] transition in + guard let self else { + return + } + if let controller = self.controller { + controller.overlayWantsToBeBelowKeyboardUpdated(transition: transition) + } + }, + requestDismiss: { [weak self] result in + guard let self, let controller = self.controller else { + return + } + controller.controllerNode.dismissedForCancel?() + controller.controllerNode.beginDismiss(result) + }, + requestAnimateOut: { [weak self] result, completion in + guard let self, let controller = self.controller else { + return + } + controller.controllerNode.animateOut(result: result, completion: completion) + }, + source: .reference(source) + ) + self._presentationNode = presentationNode + case let .extracted(source): + self.contentReady.set(.single(true)) + + let presentationNode = ContextControllerExtractedPresentationNode( + context: self.context, + getController: { [weak self] in + guard let self else { + return nil + } + return self.controller + }, + requestUpdate: { [weak self] transition in + guard let self else { + return + } + self.update(transition: transition) + }, + requestUpdateOverlayWantsToBeBelowKeyboard: { [weak self] transition in + guard let self else { + return + } + if let controller = self.controller { + controller.overlayWantsToBeBelowKeyboardUpdated(transition: transition) + } + }, + requestDismiss: { [weak self] result in + guard let self, let controller = self.controller else { + return + } + if let _ = self.closeActionTitle { + } else { + controller.controllerNode.dismissedForCancel?() + controller.controllerNode.beginDismiss(result) + } + }, + requestAnimateOut: { [weak self] result, completion in + guard let self, let controller = self.controller else { + return + } + controller.controllerNode.animateOut(result: result, completion: completion) + }, + source: .extracted(source) + ) + self._presentationNode = presentationNode + case let .controller(source): + self.contentReady.set(source.controller.ready.get()) + + let presentationNode = ContextControllerExtractedPresentationNode( + context: self.context, + getController: { [weak self] in + guard let self else { + return nil + } + return self.controller + }, + requestUpdate: { [weak self] transition in + guard let self else { + return + } + self.update(transition: transition) + }, + requestUpdateOverlayWantsToBeBelowKeyboard: { [weak self] transition in + guard let self else { + return + } + if let controller = self.controller { + controller.overlayWantsToBeBelowKeyboardUpdated(transition: transition) + } + }, + requestDismiss: { [weak self] result in + guard let self, let controller = self.controller else { + return + } + controller.controllerNode.dismissedForCancel?() + controller.controllerNode.beginDismiss(result) + }, + requestAnimateOut: { [weak self] result, completion in + guard let self, let controller = self.controller else { + return + } + controller.controllerNode.animateOut(result: result, completion: completion) + }, + source: .controller(source) + ) + self._presentationNode = presentationNode + } + + self.itemsDisposables.add((items |> deliverOnMainQueue).start(next: { [weak self] items in + guard let self else { + return + } + + self.setItems(items: items, animated: nil) + self.actionsReady.set(.single(true)) + })) + } + + deinit { + self.itemsDisposables.dispose() + } + + func animateIn() { + self.currentPresentationStateTransition = .animateIn + self.update(transition: .animated(duration: 0.5, curve: .spring)) + } + + func animateOut(result: ContextMenuActionResult, completion: @escaping () -> Void) { + self.currentPresentationStateTransition = .animateOut(result: result, completion: completion) + if let _ = self.validLayout { + if case let .custom(transition) = result { + self.delayLayoutUpdate = true + Queue.mainQueue().after(0.1) { + self.delayLayoutUpdate = false + self.update(transition: transition) + self.isAnimatingOut = true + } + } else { + self.update(transition: .animated(duration: 0.35, curve: .easeInOut)) + } + } + } + + func addRelativeContentOffset(_ offset: CGPoint, transition: ContainedViewLayoutTransition) { + self.presentationNode.addRelativeContentOffset(offset, transition: transition) + } + + func cancelReactionAnimation() { + self.presentationNode.cancelReactionAnimation() + } + + func animateOutToReaction(value: MessageReaction.Reaction, targetView: UIView, hideNode: Bool, animateTargetContainer: UIView?, addStandaloneReactionAnimation: ((StandaloneReactionAnimation) -> Void)?, reducedCurve: Bool, onHit: (() -> Void)?, completion: @escaping () -> Void) { + self.presentationNode.animateOutToReaction(value: value, targetView: targetView, hideNode: hideNode, animateTargetContainer: animateTargetContainer, addStandaloneReactionAnimation: addStandaloneReactionAnimation, reducedCurve: reducedCurve, onHit: onHit, completion: completion) + } + + func setItems(items: Signal, animated: Bool) { + self.itemsDisposables.dispose() + self.itemsDisposables = DisposableSet() + self.itemsDisposables.add((items + |> deliverOnMainQueue).start(next: { [weak self] items in + guard let self else { + return + } + self.setItems(items: items, animated: animated) + })) + } + + func setItems(items: ContextController.Items, animated: Bool?) { + self.presentationNode.replaceItems(items: items, animated: animated) + } + + func pushItems(items: Signal) { + self.itemsDisposables.add((items + |> deliverOnMainQueue).start(next: { [weak self] items in + guard let self else { + return + } + self.presentationNode.pushItems(items: items) + })) + } + + func popItems() { + self.itemsDisposables.removeLast() + self.presentationNode.popItems() + } + + func update(transition: ContainedViewLayoutTransition) { + guard let validLayout = self.validLayout else { + return + } + guard let presentationData = self.presentationData else { + return + } + self.update(presentationData: presentationData, layout: validLayout, transition: transition) + } + + func update( + presentationData: PresentationData, + layout: ContainerViewLayout, + transition: ContainedViewLayoutTransition + ) { + if self.isAnimatingOut || self.delayLayoutUpdate { + return + } + + self.validLayout = layout + self.presentationData = presentationData + + let presentationStateTransition = self.currentPresentationStateTransition + self.currentPresentationStateTransition = .none + + self.presentationNode.update( + presentationData: presentationData, + layout: layout, + transition: transition, + stateTransition: presentationStateTransition + ) + } + } + + private struct PanState { + var fraction: CGFloat + + init(fraction: CGFloat) { + self.fraction = fraction + } + } + + private weak var controller: ContextControllerImpl? + + private let backgroundNode: NavigationBackgroundNode + + var sources: [Source] = [] + var activeIndex: Int = 0 + + private var tabSelector: ComponentView? + private var footer: ComponentView? + private var closeButton: ComponentView? + + private var presentationData: PresentationData? + private var validLayout: ContainerViewLayout? + private var panState: PanState? + + let ready = Promise() + + var activeSource: Source? { + if self.activeIndex >= self.sources.count { + return nil + } + return self.sources[self.activeIndex] + } + + var overlayWantsToBeBelowKeyboard: Bool { + return self.activeSource?.presentationNode.wantsDisplayBelowKeyboard() ?? false + } + + init(controller: ContextControllerImpl, configuration: ContextController.Configuration, context: AccountContext?) { + self.controller = controller + + self.backgroundNode = NavigationBackgroundNode(color: .clear, enableBlur: false) + + super.init() + + self.addSubnode(self.backgroundNode) + + for i in 0 ..< configuration.sources.count { + let source = configuration.sources[i] + + let mappedSource = Source( + controller: controller, + id: source.id, + title: source.title, + footer: source.footer, + context: context, + source: source.source, + items: source.items, + closeActionTitle: source.closeActionTitle, + closeAction: source.closeAction + ) + self.sources.append(mappedSource) + self.addSubnode(mappedSource.presentationNode) + + if source.id == configuration.initialId { + self.activeIndex = i + } + } + + self.ready.set(self.sources[self.activeIndex].ready.get()) + + self.view.addGestureRecognizer(InteractiveTransitionGestureRecognizer(target: self, action: #selector(self.panGesture(_:)), allowedDirections: { [weak self] _ in + guard let self else { + return [] + } + if self.sources.count <= 1 { + return [] + } + return [.left, .right] + })) + } + + @objc private func panGesture(_ recognizer: InteractiveTransitionGestureRecognizer) { + switch recognizer.state { + case .began, .changed: + if let validLayout = self.validLayout { + var translationX = recognizer.translation(in: self.view).x + if self.activeIndex == 0 && translationX > 0.0 { + translationX = scrollingRubberBandingOffset(offset: abs(translationX), bandingStart: 0.0, range: 20.0) + } else if self.activeIndex == self.sources.count - 1 && translationX < 0.0 { + translationX = -scrollingRubberBandingOffset(offset: abs(translationX), bandingStart: 0.0, range: 20.0) + } + + self.panState = PanState(fraction: translationX / validLayout.size.width) + self.update(transition: .immediate) + } + case .cancelled, .ended: + if let panState = self.panState { + self.panState = nil + + let velocity = recognizer.velocity(in: self.view) + + var nextIndex = self.activeIndex + if panState.fraction < -0.4 { + nextIndex += 1 + } else if panState.fraction > 0.4 { + nextIndex -= 1 + } else if abs(velocity.x) >= 200.0 { + if velocity.x < 0.0 { + nextIndex += 1 + } else { + nextIndex -= 1 + } + } + if nextIndex < 0 { + nextIndex = 0 + } + if nextIndex > self.sources.count - 1 { + nextIndex = self.sources.count - 1 + } + if nextIndex != self.activeIndex { + self.activeIndex = nextIndex + } + + self.update(transition: .animated(duration: 0.4, curve: .spring)) + } + default: + break + } + } + + func animateIn() { + self.backgroundNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2) + +// if let activeSource = self.activeSource { +// activeSource.animateIn() +// } + for source in self.sources { + source.animateIn() + } + if let footerView = self.footer?.view { + footerView.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2) + } + if let tabSelectorView = self.tabSelector?.view { + tabSelectorView.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2) + } + if let closeButtonView = self.closeButton?.view { + closeButtonView.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2) + } + } + + func animateOut(result: ContextMenuActionResult, completion: @escaping () -> Void) { + let delayDismissal = self.activeSource?.closeAction != nil + let delay: Double = delayDismissal ? 0.2 : 0.0 + let duration: Double = delayDismissal ? 0.35 : 0.2 + + self.backgroundNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: duration, delay: delay, removeOnCompletion: false, completion: { _ in + if delayDismissal { + Queue.mainQueue().after(0.55) { + completion() + } + } + }) + + if let footerView = self.footer?.view { + footerView.layer.animateAlpha(from: 1.0, to: 0.0, duration: duration, delay: delay, removeOnCompletion: false) + } + if let tabSelectorView = self.tabSelector?.view { + tabSelectorView.layer.animateAlpha(from: 1.0, to: 0.0, duration: duration, delay: delay, removeOnCompletion: false) + } + if let closeButtonView = self.closeButton?.view { + closeButtonView.layer.animateAlpha(from: 1.0, to: 0.0, duration: duration, delay: delay, removeOnCompletion: false) + } + + for source in self.sources { + if source !== self.activeSource { + source.animateOut(result: result, completion: {}) + } + } + + if let activeSource = self.activeSource { + activeSource.animateOut(result: result, completion: delayDismissal ? {} : completion) + } else { + completion() + } + } + + func highlightGestureMoved(location: CGPoint, hover: Bool) { + if self.activeIndex >= self.sources.count { + return + } + self.sources[self.activeIndex].presentationNode.highlightGestureMoved(location: location, hover: hover) + } + + func highlightGestureFinished(performAction: Bool) { + if self.activeIndex >= self.sources.count { + return + } + self.sources[self.activeIndex].presentationNode.highlightGestureFinished(performAction: performAction) + } + + func performHighlightedAction() { + self.activeSource?.presentationNode.highlightGestureFinished(performAction: true) + } + + func decreaseHighlightedIndex() { + self.activeSource?.presentationNode.decreaseHighlightedIndex() + } + + func increaseHighlightedIndex() { + self.activeSource?.presentationNode.increaseHighlightedIndex() + } + + func addRelativeContentOffset(_ offset: CGPoint, transition: ContainedViewLayoutTransition) { + if let activeSource = self.activeSource { + activeSource.addRelativeContentOffset(offset, transition: transition) + } + } + + func cancelReactionAnimation() { + if let activeSource = self.activeSource { + activeSource.cancelReactionAnimation() + } + } + + func animateOutToReaction(value: MessageReaction.Reaction, targetView: UIView, hideNode: Bool, animateTargetContainer: UIView?, addStandaloneReactionAnimation: ((StandaloneReactionAnimation) -> Void)?, reducedCurve: Bool, onHit: (() -> Void)?, completion: @escaping () -> Void) { + if let activeSource = self.activeSource { + activeSource.animateOutToReaction(value: value, targetView: targetView, hideNode: hideNode, animateTargetContainer: animateTargetContainer, addStandaloneReactionAnimation: addStandaloneReactionAnimation, reducedCurve: reducedCurve, onHit: onHit, completion: completion) + } else { + completion() + } + } + + func setItems(items: Signal, animated: Bool) { + if let activeSource = self.activeSource { + activeSource.setItems(items: items, animated: animated) + } + } + + func pushItems(items: Signal) { + if let activeSource = self.activeSource { + activeSource.pushItems(items: items) + } + } + + func popItems() { + if let activeSource = self.activeSource { + activeSource.popItems() + } + } + + private func update(transition: ContainedViewLayoutTransition) { + if let presentationData = self.presentationData, let validLayout = self.validLayout { + self.update(presentationData: presentationData, layout: validLayout, transition: transition) + } + } + + func update( + presentationData: PresentationData, + layout: ContainerViewLayout, + transition: ContainedViewLayoutTransition + ) { + self.presentationData = presentationData + self.validLayout = layout + + var childLayout = layout + + if let activeSource = self.activeSource { + switch activeSource.source { + case .location, .reference: + self.backgroundNode.updateColor( + color: .clear, + enableBlur: false, + forceKeepBlur: false, + transition: .immediate + ) + case let .extracted(extracted): + self.backgroundNode.updateColor( + color: extracted.blurBackground ? presentationData.theme.contextMenu.dimColor : .clear, + enableBlur: extracted.blurBackground, + forceKeepBlur: extracted.blurBackground, + transition: .immediate + ) + case .controller: + if case .regular = layout.metrics.widthClass { + self.backgroundNode.updateColor( + color: UIColor(white: 0.0, alpha: 0.4), + enableBlur: false, + forceKeepBlur: false, + transition: .immediate + ) + } else { + self.backgroundNode.updateColor( + color: presentationData.theme.contextMenu.dimColor, + enableBlur: true, + forceKeepBlur: true, + transition: .immediate + ) + } + } + } + + transition.updateFrame(node: self.backgroundNode, frame: CGRect(origin: CGPoint(), size: layout.size), beginWithCurrentState: true) + self.backgroundNode.update(size: layout.size, transition: transition) + + if self.sources.count > 1 { + let tabSelector: ComponentView + if let current = self.tabSelector { + tabSelector = current + } else { + tabSelector = ComponentView() + self.tabSelector = tabSelector + } + let mappedItems = self.sources.map { source -> TabSelectorComponent.Item in + return TabSelectorComponent.Item(id: source.id, title: source.title) + } + let tabSelectorSize = tabSelector.update( + transition: ComponentTransition(transition), + component: AnyComponent(TabSelectorComponent( + colors: TabSelectorComponent.Colors( + foreground: presentationData.theme.contextMenu.primaryColor.withMultipliedAlpha(0.8), + selection: presentationData.theme.contextMenu.primaryColor.withMultipliedAlpha(0.1) + ), + theme: presentationData.theme, + customLayout: TabSelectorComponent.CustomLayout( + font: Font.medium(14.0), + spacing: 9.0 + ), + items: mappedItems, + selectedId: self.activeSource?.id, + setSelectedId: { [weak self] id in + guard let self else { + return + } + if let index = self.sources.firstIndex(where: { $0.id == id }) { + self.activeIndex = index + self.update(transition: .animated(duration: 0.4, curve: .spring)) + } + } + )), + environment: {}, + containerSize: CGSize(width: layout.size.width, height: 44.0) + ) + childLayout.intrinsicInsets.bottom += 30.0 + + if let footerText = self.activeSource?.footer { + var footerTransition = transition + let footer: ComponentView + if let current = self.footer { + footer = current + } else { + footerTransition = .immediate + footer = ComponentView() + self.footer = footer + } + + let footerSize = footer.update( + transition: ComponentTransition(footerTransition), + component: AnyComponent( + MultilineTextComponent( + text: .plain(NSAttributedString(string: footerText, font: Font.regular(13.0), textColor: presentationData.theme.contextMenu.primaryColor.withMultipliedAlpha(0.4))), + horizontalAlignment: .center, + maximumNumberOfLines: 0, + lineSpacing: 0.1 + ) + ), + environment: {}, + containerSize: CGSize(width: layout.size.width, height: 144.0) + ) + + let spacing: CGFloat = 20.0 + childLayout.intrinsicInsets.bottom += footerSize.height + spacing + + if let footerView = footer.view { + if footerView.superview == nil { + self.view.addSubview(footerView) + + footerView.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.25) + } + footerTransition.updateFrame(view: footerView, frame: CGRect(origin: CGPoint(x: floor((layout.size.width - footerSize.width) * 0.5), y: layout.size.height - layout.intrinsicInsets.bottom - tabSelectorSize.height - footerSize.height - spacing), size: footerSize)) + } + } else if let footer = self.footer { + self.footer = nil + footer.view?.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.25, removeOnCompletion: false, completion: { _ in + footer.view?.removeFromSuperview() + }) + } + + if let tabSelectorView = tabSelector.view { + if tabSelectorView.superview == nil { + self.view.addSubview(tabSelectorView) + } + transition.updateFrame(view: tabSelectorView, frame: CGRect(origin: CGPoint(x: floor((layout.size.width - tabSelectorSize.width) * 0.5), y: layout.size.height - layout.intrinsicInsets.bottom - tabSelectorSize.height), size: tabSelectorSize)) + } + } else if let source = self.sources.first, let closeActionTitle = source.closeActionTitle { + let closeButton: ComponentView + if let current = self.closeButton { + closeButton = current + } else { + closeButton = ComponentView() + self.closeButton = closeButton + } + + let closeButtonSize = closeButton.update( + transition: ComponentTransition(transition), + component: AnyComponent(PlainButtonComponent( + content: AnyComponent( + CloseButtonComponent( + backgroundColor: presentationData.theme.contextMenu.primaryColor.withMultipliedAlpha(0.1), + text: closeActionTitle + ) + ), + effectAlignment: .center, + action: { [weak self, weak source] in + guard let self else { + return + } + if let source, let closeAction = source.closeAction { + closeAction() + } else { + self.controller?.dismiss(result: .dismissWithoutContent, completion: nil) + } + }, + animateAlpha: false + )), + environment: {}, + containerSize: CGSize(width: layout.size.width, height: 44.0) + ) + childLayout.intrinsicInsets.bottom += 30.0 + + if let closeButtonView = closeButton.view { + if closeButtonView.superview == nil { + self.view.addSubview(closeButtonView) + } + transition.updateFrame(view: closeButtonView, frame: CGRect(origin: CGPoint(x: floor((layout.size.width - closeButtonSize.width) * 0.5), y: layout.size.height - layout.intrinsicInsets.bottom - closeButtonSize.height - 10.0), size: closeButtonSize)) + } + } else if let tabSelector = self.tabSelector { + self.tabSelector = nil + tabSelector.view?.removeFromSuperview() + } + + for i in 0 ..< self.sources.count { + var itemFrame = CGRect(origin: CGPoint(), size: childLayout.size) + itemFrame.origin.x += CGFloat(i - self.activeIndex) * childLayout.size.width + if let panState = self.panState { + itemFrame.origin.x += panState.fraction * childLayout.size.width + } + + let itemTransition = transition + itemTransition.updateFrame(node: self.sources[i].presentationNode, frame: itemFrame) + self.sources[i].update( + presentationData: presentationData, + layout: childLayout, + transition: itemTransition + ) + } + } + + override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + if let tabSelectorView = self.tabSelector?.view { + if let result = tabSelectorView.hitTest(self.view.convert(point, to: tabSelectorView), with: event) { + return result + } + } + if let closeButtonView = self.closeButton?.view { + if let result = closeButtonView.hitTest(self.view.convert(point, to: closeButtonView), with: event) { + return result + } + } + + guard let activeSource = self.activeSource else { + return nil + } + return activeSource.presentationNode.view.hitTest(point, with: event) + } +} + + +private final class CloseButtonComponent: CombinedComponent { + let backgroundColor: UIColor + let text: String + + init( + backgroundColor: UIColor, + text: String + ) { + self.backgroundColor = backgroundColor + self.text = text + } + + static func ==(lhs: CloseButtonComponent, rhs: CloseButtonComponent) -> Bool { + if lhs.backgroundColor != rhs.backgroundColor { + return false + } + if lhs.text != rhs.text { + return false + } + return true + } + + static var body: Body { + let background = Child(RoundedRectangle.self) + let text = Child(Text.self) + + return { context in + let text = text.update( + component: Text( + text: "\(context.component.text)", + font: Font.regular(17.0), + color: .white + ), + availableSize: CGSize(width: 200.0, height: 100.0), + transition: .immediate + ) + + let backgroundSize = CGSize(width: text.size.width + 34.0, height: 36.0) + let background = background.update( + component: RoundedRectangle(color: context.component.backgroundColor, cornerRadius: 18.0), + availableSize: backgroundSize, + transition: .immediate + ) + + context.add(background + .position(CGPoint(x: backgroundSize.width / 2.0, y: backgroundSize.height / 2.0)) + ) + + context.add(text + .position(CGPoint(x: backgroundSize.width / 2.0, y: backgroundSize.height / 2.0)) + ) + + return backgroundSize + } + } +} diff --git a/submodules/TelegramUI/Components/ContextControllerImpl/Sources/PeekController.swift b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/PeekController.swift new file mode 100644 index 00000000..6ce55e63 --- /dev/null +++ b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/PeekController.swift @@ -0,0 +1,120 @@ +import Foundation +import UIKit +import AsyncDisplayKit +import Display +import SwiftSignalKit +import TelegramPresentationData +import ContextUI + +public final class PeekControllerImpl: ViewController, PeekController, ContextControllerProtocol { + public var useComplexItemsTransitionAnimation: Bool = false + public var immediateItemsTransitionAnimation = false + + public func getActionsMinHeight() -> ContextController.ActionsHeight? { + return nil + } + + public func setItems(_ items: Signal, minHeight: ContextController.ActionsHeight?, animated: Bool) { + } + + public func setItems(_ items: Signal, minHeight: ContextController.ActionsHeight?, previousActionsTransition: ContextController.PreviousActionsTransition) { + } + + public func pushItems(items: Signal) { + self.controllerNode.pushItems(items: items) + } + + public func popItems() { + self.controllerNode.popItems() + } + + private var controllerNode: PeekControllerNode { + return self.displayNode as! PeekControllerNode + } + + public var contentNode: PeekControllerContentNode & ASDisplayNode { + return self.controllerNode.contentNode + } + + private let presentationData: PresentationData + private let content: PeekControllerContent + public var sourceView: () -> (UIView, CGRect)? + private let activateImmediately: Bool + + public var visibilityUpdated: ((Bool) -> Void)? + + public var getOverlayViews: (() -> [UIView])? + + public var appeared: (() -> Void)? + public var disappeared: (() -> Void)? + + private var animatedIn = false + + private let _ready = Promise() + override public var ready: Promise { + return self._ready + } + + public init(presentationData: PresentationData, content: PeekControllerContent, sourceView: @escaping () -> (UIView, CGRect)?, activateImmediately: Bool = false) { + self.presentationData = presentationData + self.content = content + self.sourceView = sourceView + self.activateImmediately = activateImmediately + + super.init(navigationBarPresentationData: nil) + + self.statusBar.statusBarStyle = .Ignore + } + + required public init(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override public func loadDisplayNode() { + self.displayNode = PeekControllerNode(presentationData: self.presentationData, controller: self, content: self.content, requestDismiss: { [weak self] in + self?.dismiss() + }) + self.displayNodeDidLoad() + } + + private func getSourceRect() -> CGRect { + if let (sourceView, sourceRect) = self.sourceView() { + return sourceView.convert(sourceRect, to: self.view) + } else { + let size = self.displayNode.bounds.size + return CGRect(origin: CGPoint(x: floor((size.width - 10.0) / 2.0), y: floor((size.height - 10.0) / 2.0)), size: CGSize(width: 10.0, height: 10.0)) + } + } + + override public func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + + if !self.animatedIn { + self.animatedIn = true + self.controllerNode.animateIn(from: self.getSourceRect()) + + self.visibilityUpdated?(true) + + if self.activateImmediately { + self.controllerNode.activateMenu(immediately: true) + } + } + } + + override public func containerLayoutUpdated(_ layout: ContainerViewLayout, transition: ContainedViewLayoutTransition) { + super.containerLayoutUpdated(layout, transition: transition) + + self.controllerNode.containerLayoutUpdated(layout, transition: transition) + } + + override public func dismiss(completion: (() -> Void)? = nil) { + self.visibilityUpdated?(false) + self.controllerNode.animateOut(to: self.getSourceRect(), completion: { [weak self] in + self?.presentingViewController?.dismiss(animated: false, completion: nil) + }) + } + + public func dismiss(result: ContextMenuActionResult, completion: (() -> Void)?) { + self.dismiss(completion: completion) + } +} diff --git a/submodules/TelegramUI/Components/ContextControllerImpl/Sources/PeekControllerNode.swift b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/PeekControllerNode.swift new file mode 100644 index 00000000..fb5e8701 --- /dev/null +++ b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/PeekControllerNode.swift @@ -0,0 +1,483 @@ +import Foundation +import UIKit +import AsyncDisplayKit +import Display +import SwiftSignalKit +import TelegramPresentationData +import ContextUI + +private let animationDurationFactor: Double = 1.0 + +final class PeekControllerNode: ViewControllerTracingNode, PeekControllerNodeProtocol { + private let requestDismiss: () -> Void + + private let presentationData: PresentationData + private let theme: PeekControllerTheme + + private weak var controller: PeekController? + + private let blurView: UIView + private let dimNode: ASDisplayNode + private let containerBackgroundNode: ASImageNode + private let containerNode: ASDisplayNode + private let darkDimNode: ASDisplayNode + + private var validLayout: ContainerViewLayout? + + private var content: PeekControllerContent + var contentNode: PeekControllerContentNode & ASDisplayNode + private var contentNodeHasValidLayout = false + + private var topAccessoryNode: ASDisplayNode? + private var fullScreenAccessoryNode: (PeekControllerAccessoryNode & ASDisplayNode)? + + private var actionsStackNode: ContextControllerActionsStackNode + + private var hapticFeedback = HapticFeedback() + + private var initialContinueGesturePoint: CGPoint? + private var didMoveFromInitialGesturePoint = false + private var highlightedActionNode: ContextActionNodeProtocol? + + init(presentationData: PresentationData, controller: PeekController, content: PeekControllerContent, requestDismiss: @escaping () -> Void) { + self.presentationData = presentationData + self.requestDismiss = requestDismiss + self.theme = PeekControllerTheme(presentationTheme: presentationData.theme) + self.controller = controller + + self.dimNode = ASDisplayNode() + + let blurView = UIVisualEffectView(effect: UIBlurEffect(style: self.theme.isDark ? .dark : .light)) + blurView.isUserInteractionEnabled = false + self.blurView = blurView + + self.darkDimNode = ASDisplayNode() + self.darkDimNode.alpha = 0.0 + self.darkDimNode.backgroundColor = presentationData.theme.contextMenu.dimColor + self.darkDimNode.isUserInteractionEnabled = false + + switch content.menuActivation() { + case .drag: + self.dimNode.backgroundColor = nil + self.blurView.alpha = 1.0 + case .press: + self.dimNode.backgroundColor = UIColor(white: self.theme.isDark ? 0.0 : 1.0, alpha: 0.5) + self.blurView.alpha = 0.0 + } + + self.containerBackgroundNode = ASImageNode() + self.containerBackgroundNode.isLayerBacked = true + self.containerBackgroundNode.displaysAsynchronously = false + + self.containerNode = ASDisplayNode() + + self.content = content + self.contentNode = content.node() + self.topAccessoryNode = content.topAccessoryNode() + self.fullScreenAccessoryNode = content.fullScreenAccessoryNode(blurView: blurView) + self.fullScreenAccessoryNode?.alpha = 0.0 + + var activatedActionImpl: (() -> Void)? + var requestLayoutImpl: ((ContainedViewLayoutTransition) -> Void)? + + self.actionsStackNode = ContextControllerActionsStackNodeImpl( + context: nil, + getController: { [weak controller] in + return controller + }, + requestDismiss: { result in + activatedActionImpl?() + }, + requestUpdate: { transition in + requestLayoutImpl?(transition) + } + ) + self.actionsStackNode.alpha = 0.0 + + let items = ContextController.Items( + id: 0, + content: .list(content.menuItems()), + context: nil, + reactionItems: [], + selectedReactionItems: Set(), + reactionsTitle: nil, + reactionsLocked: false, + animationCache: nil, + alwaysAllowPremiumReactions: false, + allPresetReactionsAreAvailable: false, + getEmojiContent: nil, + disablePositionLock: false, + tip: nil, + tipSignal: nil, + dismissed: nil + ) + if let item = makeContextControllerActionsStackItem(items: items).first { + self.actionsStackNode.replace( + item: item, + animated: false + ) + } + + super.init() + + requestLayoutImpl = { [weak self] transition in + self?.updateLayout(transition: transition) + } + + if content.presentation() == .freeform { + self.containerNode.isUserInteractionEnabled = false + } else { + self.containerNode.clipsToBounds = true + self.containerNode.cornerRadius = 16.0 + } + + self.addSubnode(self.dimNode) + self.view.addSubview(self.blurView) + self.addSubnode(self.darkDimNode) + self.containerNode.addSubnode(self.contentNode) + + self.addSubnode(self.actionsStackNode) + self.addSubnode(self.containerNode) + + + if let fullScreenAccessoryNode = self.fullScreenAccessoryNode { + self.fullScreenAccessoryNode?.dismiss = { [weak self] in + self?.requestDismiss() + } + self.addSubnode(fullScreenAccessoryNode) + } + + activatedActionImpl = { [weak self] in + self?.requestDismiss() + } + + self.hapticFeedback.prepareTap() + + controller.ready.set(self.contentNode.ready()) + } + + deinit { + } + + override func didLoad() { + super.didLoad() + + self.dimNode.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dimNodeTap(_:)))) + self.view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(self.panGesture(_:)))) + } + + func updateLayout(transition: ContainedViewLayoutTransition = .immediate) { + if let layout = self.validLayout { + self.containerLayoutUpdated(layout, transition: transition) + } + } + + func replaceItem(items: Signal) { + let _ = (items + |> deliverOnMainQueue).start(next: { [weak self] items in + guard let self else { + return + } + if let item = makeContextControllerActionsStackItem(items: items).first { + self.actionsStackNode.replace(item: item, animated: false) + } + }) + } + + func pushItems(items: Signal) { + let _ = (items + |> deliverOnMainQueue).start(next: { [weak self] items in + guard let self else { + return + } + if let item = makeContextControllerActionsStackItem(items: items).first { + self.actionsStackNode.push(item: item, currentScrollingState: nil, positionLock: nil, animated: true) + } + }) + } + + func popItems() { + self.actionsStackNode.pop() + } + + func containerLayoutUpdated(_ layout: ContainerViewLayout, transition: ContainedViewLayoutTransition) { + self.validLayout = layout + + transition.updateFrame(node: self.dimNode, frame: CGRect(origin: CGPoint(), size: layout.size)) + transition.updateFrame(node: self.darkDimNode, frame: CGRect(origin: CGPoint(), size: layout.size)) + transition.updateFrame(view: self.blurView, frame: CGRect(origin: CGPoint(), size: layout.size)) + + var layoutInsets = layout.insets(options: []) + let containerWidth = horizontalContainerFillingSizeForLayout(layout: layout, sideInset: layout.safeInsets.left) + + layoutInsets.left = floor((layout.size.width - containerWidth) / 2.0) + layoutInsets.right = layoutInsets.left + if !layoutInsets.bottom.isZero { + layoutInsets.bottom -= 12.0 + } + + let maxContainerSize = CGSize(width: layout.size.width - 14.0 * 2.0, height: layout.size.height - layoutInsets.top - layoutInsets.bottom - 90.0) + + let contentSize = self.contentNode.updateLayout(size: maxContainerSize, transition: self.contentNodeHasValidLayout ? transition : .immediate) + if self.contentNodeHasValidLayout { + transition.updateFrame(node: self.contentNode, frame: CGRect(origin: CGPoint(), size: contentSize)) + } else { + self.contentNode.frame = CGRect(origin: CGPoint(), size: contentSize) + } + + let actionsSideInset: CGFloat = layout.safeInsets.left + 11.0 + + let actionsSize = self.actionsStackNode.update( + presentationData: self.presentationData, + constrainedSize: CGSize(width: layout.size.width - actionsSideInset * 2.0, height: layout.size.height), + presentation: .inline, + transition: transition + ) + + let containerFrame: CGRect + let actionsFrame: CGRect + if layout.size.width > layout.size.height { + if self.actionsStackNode.alpha.isZero { + containerFrame = CGRect(origin: CGPoint(x: floor((layout.size.width - contentSize.width) / 2.0), y: floor((layout.size.height - contentSize.height) / 2.0)), size: contentSize) + } else { + containerFrame = CGRect(origin: CGPoint(x: floor((layout.size.width - contentSize.width) / 3.0), y: floor((layout.size.height - contentSize.height) / 2.0)), size: contentSize) + } + actionsFrame = CGRect(origin: CGPoint(x: containerFrame.maxX + 32.0, y: floor((layout.size.height - actionsSize.height) / 2.0)), size: actionsSize) + } else { + switch self.content.presentation() { + case .contained: + containerFrame = CGRect(origin: CGPoint(x: floor((layout.size.width - contentSize.width) / 2.0), y: floor((layout.size.height - contentSize.height) / 2.0)), size: contentSize) + case .freeform: + var fraction: CGFloat = 1.0 / 3.0 + if let _ = self.controller?.appeared { + fraction *= 1.33 + } + containerFrame = CGRect(origin: CGPoint(x: floor((layout.size.width - contentSize.width) / 2.0), y: floor((layout.size.height - contentSize.height) * fraction)), size: contentSize) + } + actionsFrame = CGRect(origin: CGPoint(x: floor((layout.size.width - actionsSize.width) / 2.0), y: containerFrame.maxY + 64.0), size: actionsSize) + } + transition.updateFrame(node: self.containerNode, frame: containerFrame) + + transition.updateFrame(node: self.actionsStackNode, frame: actionsFrame) + + if let fullScreenAccessoryNode = self.fullScreenAccessoryNode { + transition.updateFrame(node: fullScreenAccessoryNode, frame: CGRect(origin: .zero, size: layout.size)) + fullScreenAccessoryNode.updateLayout(size: layout.size, transition: transition) + } + + self.contentNodeHasValidLayout = true + } + + func animateIn(from rect: CGRect) { + self.dimNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.3) + self.blurView.layer.animateAlpha(from: 0.0, to: self.blurView.alpha, duration: 0.3) + + let offset = CGPoint(x: rect.midX - self.containerNode.position.x, y: rect.midY - self.containerNode.position.y) + self.containerNode.layer.animateSpring(from: NSValue(cgPoint: offset), to: NSValue(cgPoint: CGPoint()), keyPath: "position", duration: 0.4, initialVelocity: 0.0, damping: 110.0, additive: true) + + if let appeared = self.controller?.appeared { + appeared() + let scale = rect.width / self.contentNode.frame.width + self.containerNode.layer.animateSpring(from: scale as NSNumber, to: 1.0 as NSNumber, keyPath: "transform.scale", duration: 0.4, initialVelocity: 0.0, damping: 110.0) + } else { + self.containerNode.layer.animateSpring(from: 0.1 as NSNumber, to: 1.0 as NSNumber, keyPath: "transform.scale", duration: 0.4, initialVelocity: 0.0, damping: 110.0) + self.containerNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.15) + } + + if let topAccessoryNode = self.topAccessoryNode { + topAccessoryNode.layer.animateSpring(from: NSValue(cgPoint: offset), to: NSValue(cgPoint: CGPoint()), keyPath: "position", duration: 0.4, initialVelocity: 0.0, damping: 110.0, additive: true) + topAccessoryNode.layer.animateSpring(from: 0.1 as NSNumber, to: 1.0 as NSNumber, keyPath: "transform.scale", duration: 0.4, initialVelocity: 0.0, damping: 110.0) + topAccessoryNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.15) + } + + if case .press = self.content.menuActivation() { + self.hapticFeedback.tap() + } else { + self.hapticFeedback.impact() + } + } + + func animateOut(to rect: CGRect, completion: @escaping () -> Void) { + self.isUserInteractionEnabled = false + + self.dimNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, removeOnCompletion: false) + self.blurView.layer.animateAlpha(from: self.blurView.alpha, to: 0.0, duration: 0.25, removeOnCompletion: false) + self.darkDimNode.layer.animateAlpha(from: self.darkDimNode.alpha, to: 0.0, duration: 0.2, removeOnCompletion: false) + + let springDuration: Double = 0.42 * animationDurationFactor + let springDamping: CGFloat = 104.0 + + var scaleCompleted = false + var positionCompleted = false + let outCompletion = { + if scaleCompleted && positionCompleted { + } + } + + let offset = CGPoint(x: rect.midX - self.containerNode.position.x, y: rect.midY - self.containerNode.position.y) + self.containerNode.layer.animateSpring(from: NSValue(cgPoint: CGPoint()), to: NSValue(cgPoint: offset), keyPath: "position", duration: springDuration, initialVelocity: 0.0, damping: springDamping, removeOnCompletion: false, additive: true, completion: { _ in + positionCompleted = true + outCompletion() + completion() + }) + + if let _ = self.controller?.disappeared { + self.controller?.disappeared?() + let scale = rect.width / self.contentNode.frame.width + self.containerNode.layer.animateScale(from: 1.0, to: scale, duration: 0.25, removeOnCompletion: false, completion: { _ in + scaleCompleted = true + outCompletion() + }) + } else { + self.containerNode.layer.animateScale(from: 1.0, to: 0.1, duration: 0.25, removeOnCompletion: false, completion: { _ in + scaleCompleted = true + outCompletion() + }) + self.containerNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, removeOnCompletion: false) + } + + if !self.actionsStackNode.alpha.isZero { + let actionsOffset = CGPoint(x: rect.midX - self.actionsStackNode.position.x, y: rect.midY - self.actionsStackNode.position.y) + self.actionsStackNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2 * animationDurationFactor, removeOnCompletion: false) + self.actionsStackNode.layer.animateSpring(from: 1.0 as NSNumber, to: 0.0 as NSNumber, keyPath: "transform.scale", duration: springDuration, initialVelocity: 0.0, damping: springDamping, removeOnCompletion: false) + self.actionsStackNode.layer.animateSpring(from: NSValue(cgPoint: CGPoint()), to: NSValue(cgPoint: actionsOffset), keyPath: "position", duration: springDuration, initialVelocity: 0.0, damping: springDamping, additive: true) + } + + if let fullScreenAccessoryNode = self.fullScreenAccessoryNode, !fullScreenAccessoryNode.alpha.isZero { + fullScreenAccessoryNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2 * animationDurationFactor, removeOnCompletion: false) + } + } + + @objc func dimNodeTap(_ recognizer: UITapGestureRecognizer) { + if case .ended = recognizer.state { + self.requestDismiss() + } + } + + @objc func panGesture(_ recognizer: UIPanGestureRecognizer) { + guard case .drag = self.content.menuActivation() else { + return + } + + let location = recognizer.location(in: self.view) + switch recognizer.state { + case .began: + break + case .changed: + self.applyDraggingOffset(location) + case .cancelled, .ended: + self.endDragging(location) + default: + break + } + } + + func applyDraggingOffset(_ offset: CGPoint) { + let localPoint = offset + let initialPoint: CGPoint + if let current = self.initialContinueGesturePoint { + initialPoint = current + } else { + initialPoint = localPoint + self.initialContinueGesturePoint = localPoint + } + if !self.actionsStackNode.alpha.isZero { + if !self.didMoveFromInitialGesturePoint { + let distance = abs(localPoint.y - initialPoint.y) + if distance > 12.0 { + self.didMoveFromInitialGesturePoint = true + } + } + if self.didMoveFromInitialGesturePoint { + let actionPoint = self.view.convert(localPoint, to: self.actionsStackNode.view) + self.actionsStackNode.highlightGestureMoved(location: actionPoint) + } + } + } + + func endDragging(_ location: CGPoint) { + if self.didMoveFromInitialGesturePoint { + self.actionsStackNode.highlightGestureFinished(performAction: true) + } else if self.actionsStackNode.alpha.isZero { + if let fullScreenAccessoryNode = self.fullScreenAccessoryNode, !fullScreenAccessoryNode.alpha.isZero { + } else { + self.requestDismiss() + } + } + } + + func activateMenu(immediately: Bool) { + if self.content.menuItems().isEmpty { + if let fullScreenAccessoryNode = self.fullScreenAccessoryNode { + fullScreenAccessoryNode.alpha = 1.0 + fullScreenAccessoryNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.15) + + let previousBlurAlpha = self.blurView.alpha + self.blurView.alpha = 1.0 + self.blurView.layer.animateAlpha(from: previousBlurAlpha, to: self.blurView.alpha, duration: 0.3) + } + return + } else { + if let fullScreenAccessoryNode = self.fullScreenAccessoryNode { + fullScreenAccessoryNode.alpha = 1.0 + fullScreenAccessoryNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.15) + } + } + if case .press = self.content.menuActivation() { + self.hapticFeedback.impact() + } + + let springDuration: Double = 0.42 * animationDurationFactor + let springDamping: CGFloat = 104.0 + + let previousBlurAlpha = self.blurView.alpha + self.blurView.alpha = 1.0 + self.blurView.layer.animateAlpha(from: previousBlurAlpha, to: self.blurView.alpha, duration: 0.25) + + let previousDarkDimAlpha = self.darkDimNode.alpha + self.darkDimNode.alpha = 1.0 + self.darkDimNode.layer.animateAlpha(from: previousDarkDimAlpha, to: 1.0, duration: 0.3) + + if let layout = self.validLayout { + self.containerLayoutUpdated(layout, transition: .animated(duration: springDuration, curve: .spring)) + } + + let animateIn = { + self.actionsStackNode.alpha = 1.0 + self.actionsStackNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2 * animationDurationFactor) + self.actionsStackNode.layer.animateSpring(from: 0.1 as NSNumber, to: 1.0 as NSNumber, keyPath: "transform.scale", duration: springDuration, initialVelocity: 0.0, damping: springDamping) + + let localContentSourceFrame = self.containerNode.frame + self.actionsStackNode.layer.animateSpring(from: NSValue(cgPoint: CGPoint(x: localContentSourceFrame.center.x - self.actionsStackNode.position.x, y: localContentSourceFrame.center.y - self.actionsStackNode.position.y)), to: NSValue(cgPoint: CGPoint()), keyPath: "position", duration: springDuration, initialVelocity: 0.0, damping: springDamping, additive: true) + } + if immediately { + animateIn() + } else { + Queue.mainQueue().after(0.02, animateIn) + } + } + + func updateContent(content: PeekControllerContent) { + let contentNode = self.contentNode + contentNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.15, removeOnCompletion: false, completion: { [weak contentNode] _ in + contentNode?.removeFromSupernode() + }) + contentNode.layer.animateScale(from: 1.0, to: 0.2, duration: 0.15, removeOnCompletion: false) + + self.content = content + self.contentNode = content.node() + self.containerNode.addSubnode(self.contentNode) + self.contentNodeHasValidLayout = false + + self.replaceItem(items: .single(ContextController.Items(content: .list(content.menuItems())))) + + self.contentNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.1) + self.contentNode.layer.animateSpring(from: 0.35 as NSNumber, to: 1.0 as NSNumber, keyPath: "transform.scale", duration: 0.5) + + if let layout = self.validLayout { + self.containerLayoutUpdated(layout, transition: .animated(duration: 0.15, curve: .easeInOut)) + } + + self.hapticFeedback.tap() + } +} diff --git a/submodules/TelegramUI/Components/ContextControllerImpl/Sources/PinchController.swift b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/PinchController.swift new file mode 100644 index 00000000..886e11d0 --- /dev/null +++ b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/PinchController.swift @@ -0,0 +1,262 @@ +import Foundation +import UIKit +import AsyncDisplayKit +import Display +import TelegramPresentationData +import TextSelectionNode +import TelegramCore +import SwiftSignalKit +import UIKitRuntimeUtils +import ContextUI + +private final class PinchControllerNode: ViewControllerTracingNode { + private weak var controller: PinchController? + + private var initialSourceFrame: CGRect? + + private let clippingNode: ASDisplayNode + private let scrollingContainer: ASDisplayNode + + private let sourceNode: PinchSourceContainerNode + private let disableScreenshots: Bool + private let getContentAreaInScreenSpace: () -> CGRect + + private let dimNode: ASDisplayNode + + private var validLayout: ContainerViewLayout? + private var isAnimatingOut: Bool = false + + private var hapticFeedback: HapticFeedback? + + init(controller: PinchController, sourceNode: PinchSourceContainerNode, disableScreenshots: Bool, getContentAreaInScreenSpace: @escaping () -> CGRect) { + self.controller = controller + self.sourceNode = sourceNode + self.disableScreenshots = disableScreenshots + self.getContentAreaInScreenSpace = getContentAreaInScreenSpace + + self.dimNode = ASDisplayNode() + self.dimNode.backgroundColor = UIColor(white: 0.0, alpha: 0.5) + self.dimNode.alpha = 0.0 + + self.clippingNode = ASDisplayNode() + self.clippingNode.clipsToBounds = true + + self.scrollingContainer = ASDisplayNode() + + super.init() + + self.addSubnode(self.dimNode) + self.addSubnode(self.clippingNode) + self.clippingNode.addSubnode(self.scrollingContainer) + + self.sourceNode.deactivate = { [weak self] in + guard let strongSelf = self else { + return + } + strongSelf.controller?.dismiss() + } + + self.sourceNode.updated = { [weak self] scale, pinchLocation, offset in + guard let strongSelf = self, let initialSourceFrame = strongSelf.initialSourceFrame else { + return + } + strongSelf.dimNode.alpha = max(0.0, min(1.0, scale - 1.0)) + + let pinchOffset = CGPoint( + x: pinchLocation.x - initialSourceFrame.width / 2.0, + y: pinchLocation.y - initialSourceFrame.height / 2.0 + ) + + var transform = CATransform3DIdentity + transform = CATransform3DTranslate(transform, offset.x - pinchOffset.x * (scale - 1.0), offset.y - pinchOffset.y * (scale - 1.0), 0.0) + transform = CATransform3DScale(transform, scale, scale, 0.0) + + strongSelf.sourceNode.contentNode.transform = transform + } + + if self.disableScreenshots { + setLayerDisableScreenshots(self.layer, true) + } + } + + deinit { + } + + override func didLoad() { + super.didLoad() + } + + func updateLayout(layout: ContainerViewLayout, transition: ContainedViewLayoutTransition, previousActionsContainerNode: ContextActionsContainerNode?) { + if self.isAnimatingOut { + return + } + + self.validLayout = layout + + transition.updateFrame(node: self.dimNode, frame: CGRect(origin: CGPoint(), size: layout.size)) + transition.updateFrame(node: self.clippingNode, frame: CGRect(origin: CGPoint(), size: layout.size)) + } + + func animateIn() { + let convertedFrame = convertFrame(self.sourceNode.bounds, from: self.sourceNode.view, to: self.view) + self.sourceNode.contentNode.frame = convertedFrame + self.initialSourceFrame = convertedFrame + self.scrollingContainer.addSubnode(self.sourceNode.contentNode) + + var updatedContentAreaInScreenSpace = self.getContentAreaInScreenSpace() + updatedContentAreaInScreenSpace.origin.x = 0.0 + updatedContentAreaInScreenSpace.size.width = self.bounds.width + + self.clippingNode.layer.animateFrame(from: updatedContentAreaInScreenSpace, to: self.clippingNode.frame, duration: 0.18 * 1.0, timingFunction: CAMediaTimingFunctionName.easeInEaseOut.rawValue) + self.clippingNode.layer.animateBoundsOriginYAdditive(from: updatedContentAreaInScreenSpace.minY, to: 0.0, duration: 0.18 * 1.0, timingFunction: CAMediaTimingFunctionName.easeInEaseOut.rawValue) + } + + func animateOut(completion: @escaping () -> Void) { + self.isAnimatingOut = true + + let performCompletion: () -> Void = { [weak self] in + guard let strongSelf = self else { + return + } + + strongSelf.isAnimatingOut = false + + strongSelf.sourceNode.restoreToNaturalSize() + strongSelf.sourceNode.addSubnode(strongSelf.sourceNode.contentNode) + + strongSelf.sourceNode.animatedOut?() + + completion() + } + + let convertedFrame = convertFrame(self.sourceNode.bounds, from: self.sourceNode.view, to: self.view) + self.sourceNode.contentNode.frame = convertedFrame + self.initialSourceFrame = convertedFrame + + if let (scale, pinchLocation, offset) = self.sourceNode.gesture.currentTransform, let initialSourceFrame = self.initialSourceFrame { + let duration = 0.3 + let transitionCurve: ContainedViewLayoutTransitionCurve = .easeInOut + + var updatedContentAreaInScreenSpace = self.getContentAreaInScreenSpace() + updatedContentAreaInScreenSpace.origin.x = 0.0 + updatedContentAreaInScreenSpace.size.width = self.bounds.width + + self.clippingNode.layer.animateFrame(from: self.clippingNode.frame, to: updatedContentAreaInScreenSpace, duration: duration * 1.0, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false) + self.clippingNode.layer.animateBoundsOriginYAdditive(from: 0.0, to: updatedContentAreaInScreenSpace.minY, duration: duration * 1.0, timingFunction: transitionCurve.timingFunction, removeOnCompletion: false) + + let transition: ContainedViewLayoutTransition = .animated(duration: duration, curve: .spring) + if self.hapticFeedback == nil { + self.hapticFeedback = HapticFeedback() + } + self.hapticFeedback?.prepareImpact(.light) + self.hapticFeedback?.impact(.light) + + self.sourceNode.scaleUpdated?(1.0, transition) + + let pinchOffset = CGPoint( + x: pinchLocation.x - initialSourceFrame.width / 2.0, + y: pinchLocation.y - initialSourceFrame.height / 2.0 + ) + + var transform = CATransform3DIdentity + transform = CATransform3DScale(transform, scale, scale, 0.0) + + self.sourceNode.contentNode.transform = CATransform3DIdentity + self.sourceNode.contentNode.position = CGPoint(x: initialSourceFrame.midX, y: initialSourceFrame.midY) + self.sourceNode.contentNode.layer.animateSpring(from: scale as NSNumber, to: 1.0 as NSNumber, keyPath: "transform.scale", duration: duration * 1.2, damping: 110.0) + self.sourceNode.contentNode.layer.animatePosition(from: CGPoint(x: offset.x - pinchOffset.x * (scale - 1.0), y: offset.y - pinchOffset.y * (scale - 1.0)), to: CGPoint(), duration: duration, timingFunction: kCAMediaTimingFunctionSpring, additive: true, force: true, completion: { _ in + performCompletion() + }) + + let dimNodeTransition: ContainedViewLayoutTransition = .animated(duration: 0.3, curve: transitionCurve) + dimNodeTransition.updateAlpha(node: self.dimNode, alpha: 0.0) + } else { + performCompletion() + } + } + + func addRelativeContentOffset(_ offset: CGPoint, transition: ContainedViewLayoutTransition) { + if self.isAnimatingOut { + self.scrollingContainer.bounds = self.scrollingContainer.bounds.offsetBy(dx: 0.0, dy: offset.y) + transition.animateOffsetAdditive(node: self.scrollingContainer, offset: -offset.y) + } + } + + override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + return nil + } +} + +public final class PinchControllerImpl: ViewController, PinchController, StandalonePresentableController { + private let _ready = Promise() + override public var ready: Promise { + return self._ready + } + + private let sourceNode: PinchSourceContainerNode + private let disableScreenshots: Bool + private let getContentAreaInScreenSpace: () -> CGRect + + private var wasDismissed = false + + private var controllerNode: PinchControllerNode { + return self.displayNode as! PinchControllerNode + } + + public init(sourceNode: PinchSourceContainerNode, disableScreenshots: Bool = false, getContentAreaInScreenSpace: @escaping () -> CGRect) { + self.sourceNode = sourceNode + self.disableScreenshots = disableScreenshots + self.getContentAreaInScreenSpace = getContentAreaInScreenSpace + + super.init(navigationBarPresentationData: nil) + + self.statusBar.statusBarStyle = .Ignore + + self.lockOrientation = true + self.blocksBackgroundWhenInOverlay = true + } + + required init(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + deinit { + } + + override public func loadDisplayNode() { + self.displayNode = PinchControllerNode(controller: self, sourceNode: self.sourceNode, disableScreenshots: self.disableScreenshots, getContentAreaInScreenSpace: self.getContentAreaInScreenSpace) + + self.displayNodeDidLoad() + + self._ready.set(.single(true)) + } + + override public func containerLayoutUpdated(_ layout: ContainerViewLayout, transition: ContainedViewLayoutTransition) { + super.containerLayoutUpdated(layout, transition: transition) + + self.controllerNode.updateLayout(layout: layout, transition: transition, previousActionsContainerNode: nil) + } + + override public func viewDidAppear(_ animated: Bool) { + if self.ignoreAppearanceMethodInvocations() { + return + } + super.viewDidAppear(animated) + + self.controllerNode.animateIn() + } + + override public func dismiss(completion: (() -> Void)? = nil) { + if !self.wasDismissed { + self.wasDismissed = true + self.controllerNode.animateOut(completion: { [weak self] in + self?.presentingViewController?.dismiss(animated: false, completion: nil) + completion?() + }) + } + } + + public func addRelativeContentOffset(_ offset: CGPoint, transition: ContainedViewLayoutTransition) { + self.controllerNode.addRelativeContentOffset(offset, transition: transition) + } +} diff --git a/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ReactionPreviewView.swift b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ReactionPreviewView.swift new file mode 100644 index 00000000..1e12087a --- /dev/null +++ b/submodules/TelegramUI/Components/ContextControllerImpl/Sources/ReactionPreviewView.swift @@ -0,0 +1,55 @@ +import Foundation +import UIKit +import SwiftSignalKit +import Display +import ComponentFlow +import TelegramCore +import AccountContext +import EmojiStatusComponent + +final class ReactionPreviewView: UIView { + private let context: AccountContext + private let file: TelegramMediaFile + + private let icon = ComponentView() + + init(context: AccountContext, file: TelegramMediaFile) { + self.context = context + self.file = file + + super.init(frame: CGRect()) + } + + required init(coder: NSCoder) { + preconditionFailure() + } + + func update(size: CGSize) { + let iconSize = self.icon.update( + transition: .immediate, + component: AnyComponent(EmojiStatusComponent( + context: self.context, + animationCache: self.context.animationCache, + animationRenderer: self.context.animationRenderer, + content: .animation( + content: .file(file: self.file), + size: size, + placeholderColor: .clear, + themeColor: .white, + loopMode: .forever + ), + isVisibleForAnimations: true, + action: nil + )), + environment: {}, + containerSize: size + ) + let iconFrame = CGRect(origin: CGPoint(x: floor((size.width - iconSize.width) * 0.5), y: floor((size.height - iconSize.height) * 0.5)), size: iconSize) + if let iconView = self.icon.view { + if iconView.superview == nil { + self.addSubview(iconView) + } + iconView.frame = iconFrame + } + } +} diff --git a/submodules/TelegramUI/Components/EntityKeyboard/BUILD b/submodules/TelegramUI/Components/EntityKeyboard/BUILD index 0ca5c0ae..2b4b4725 100644 --- a/submodules/TelegramUI/Components/EntityKeyboard/BUILD +++ b/submodules/TelegramUI/Components/EntityKeyboard/BUILD @@ -1,15 +1,23 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + +sgsrc = [ + "//Swiftgram/SGEmojiKeyboardDefaultFirst:SGEmojiKeyboardDefaultFirst" +] + swift_library( name = "EntityKeyboard", module_name = "EntityKeyboard", - srcs = glob([ + srcs = sgsrc + glob([ "Sources/**/*.swift", ]), copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", "//submodules/Display:Display", "//submodules/ComponentFlow:ComponentFlow", diff --git a/submodules/TelegramUI/Components/EntityKeyboard/Sources/EmojiPagerContentComponent.swift b/submodules/TelegramUI/Components/EntityKeyboard/Sources/EmojiPagerContentComponent.swift index 2ab6b15e..7eec8f0c 100644 --- a/submodules/TelegramUI/Components/EntityKeyboard/Sources/EmojiPagerContentComponent.swift +++ b/submodules/TelegramUI/Components/EntityKeyboard/Sources/EmojiPagerContentComponent.swift @@ -126,9 +126,9 @@ public final class EntityKeyboardAnimationData: Equatable { var file: TelegramMediaFile? var color: UIColor? for attribute in gift.attributes { - if case let .model(_, fileValue, _) = attribute { + if case let StarGift.UniqueGift.Attribute.model(_, fileValue, _, _) = attribute { file = fileValue - } else if case let .backdrop(_, _, innerColor, outerColor, _, _, _) = attribute { + } else if case let StarGift.UniqueGift.Attribute.backdrop(_, _, innerColor, outerColor, _, _, _) = attribute { color = UIColor(rgb: UInt32(bitPattern: innerColor)) let _ = outerColor } diff --git a/submodules/TelegramUI/Components/EntityKeyboard/Sources/EntityKeyboard.swift b/submodules/TelegramUI/Components/EntityKeyboard/Sources/EntityKeyboard.swift index 12ec0cfb..34dc8468 100644 --- a/submodules/TelegramUI/Components/EntityKeyboard/Sources/EntityKeyboard.swift +++ b/submodules/TelegramUI/Components/EntityKeyboard/Sources/EntityKeyboard.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import Display @@ -558,9 +559,22 @@ public final class EntityKeyboardComponent: Component { let emojiContentItemIdUpdated = ActionSlot<(AnyHashable, AnyHashable?, ComponentTransition)>() if let emojiContent = component.emojiContent { - contents.append(AnyComponentWithIdentity(id: "emoji", component: AnyComponent(emojiContent))) + let effectiveEmojiContent: EmojiPagerContentComponent + // MARK: Swiftgram + if SGSimpleSettings.shared.defaultEmojisFirst { + effectiveEmojiContent = emojiContent.withUpdatedItemGroups( + panelItemGroups: sgPatchEmojiKeyboardItems(emojiContent.panelItemGroups), + contentItemGroups: sgPatchEmojiKeyboardItems(emojiContent.contentItemGroups), + itemContentUniqueId: emojiContent.itemContentUniqueId, + emptySearchResults: emojiContent.emptySearchResults, + searchState: emojiContent.searchState + ) + } else { + effectiveEmojiContent = emojiContent + } + contents.append(AnyComponentWithIdentity(id: "emoji", component: AnyComponent(effectiveEmojiContent))) var topEmojiItems: [EntityKeyboardTopPanelComponent.Item] = [] - for itemGroup in emojiContent.panelItemGroups { + for itemGroup in effectiveEmojiContent.panelItemGroups { if !itemGroup.items.isEmpty { if let id = itemGroup.groupId.base as? String, id != "peerSpecific" { if id == "recent" || id == "liked" || id == "collectible" { @@ -612,12 +626,12 @@ public final class EntityKeyboardComponent: Component { id: itemGroup.supergroupId, isReorderable: !itemGroup.isFeatured, content: AnyComponent(EntityKeyboardAnimationTopPanelComponent( - context: emojiContent.context, + context: effectiveEmojiContent.context, item: itemGroup.headerItem ?? animationData, isFeatured: itemGroup.isFeatured, isPremiumLocked: itemGroup.isPremiumLocked, - animationCache: emojiContent.animationCache, - animationRenderer: emojiContent.animationRenderer, + animationCache: effectiveEmojiContent.animationCache, + animationRenderer: effectiveEmojiContent.animationRenderer, theme: component.theme, title: itemGroup.title ?? "", customTintColor: component.customTintColor ?? itemGroup.customTintColor, diff --git a/submodules/TelegramUI/Components/Gifts/GiftAnimationComponent/Sources/GiftCompositionComponent.swift b/submodules/TelegramUI/Components/Gifts/GiftAnimationComponent/Sources/GiftCompositionComponent.swift index c570354d..ffd24ea6 100644 --- a/submodules/TelegramUI/Components/Gifts/GiftAnimationComponent/Sources/GiftCompositionComponent.swift +++ b/submodules/TelegramUI/Components/Gifts/GiftAnimationComponent/Sources/GiftCompositionComponent.swift @@ -219,7 +219,7 @@ public final class GiftCompositionComponent: Component { _ attribute: StarGift.UniqueGift.Attribute, animDuration: Double ) { - guard let geom = self.spinGeom, case let .model(_, file, _) = attribute else { + guard let geom = self.spinGeom, case let StarGift.UniqueGift.Attribute.model(_, file, _, _) = attribute else { return } @@ -340,7 +340,7 @@ public final class GiftCompositionComponent: Component { self.decelItemHosts.removeAll() for (i, attribute) in tail.reversed().enumerated() { - guard case let .model(_, file, _) = attribute else { continue } + guard case let StarGift.UniqueGift.Attribute.model(_, file, _, _) = attribute else { continue } let node = DefaultAnimatedStickerNodeImpl() node.isUserInteractionEnabled = false @@ -648,7 +648,7 @@ public final class GiftCompositionComponent: Component { for attribute in gift.attributes { switch attribute { - case let .model(_, file, _): + case let .model(_, file, _, _): animationFile = file if !self.fetchedFiles.contains(file.fileId.id) { self.disposables.add(freeMediaFileResourceInteractiveFetched(account: component.context.account, userLocation: .other, fileReference: .standalone(media: file), resource: file.resource).start()) @@ -705,7 +705,7 @@ public final class GiftCompositionComponent: Component { self.previewBackdrops = backdrops } - for case let .model(_, file, _) in self.previewModels where !self.fetchedFiles.contains(file.fileId.id) { + for case let StarGift.UniqueGift.Attribute.model(_, file, _, _) in self.previewModels where !self.fetchedFiles.contains(file.fileId.id) { self.disposables.add(freeMediaFileResourceInteractiveFetched(account: component.context.account, userLocation: .other, fileReference: .standalone(media: file), resource: file.resource).start()) self.fetchedFiles.insert(file.fileId.id) } @@ -722,7 +722,7 @@ public final class GiftCompositionComponent: Component { if self.previewBackdropIndex < 0 { self.previewBackdropIndex = 0 } - if case let .model(_, file, _) = self.previewModels[Int(self.previewModelIndex)] { + if case let StarGift.UniqueGift.Attribute.model(_, file, _, _) = self.previewModels[Int(self.previewModelIndex)] { animationFile = file component.externalState?.previewModel = self.previewModels[Int(self.previewModelIndex)] } @@ -851,12 +851,12 @@ public final class GiftCompositionComponent: Component { if let (previewAttributes, mainGift) = uniqueSpinContext { var mainModelFile: TelegramMediaFile? for attribute in mainGift.attributes { - if case let .model(_, file, _) = attribute { mainModelFile = file; break } + if case let StarGift.UniqueGift.Attribute.model(_, file, _, _) = attribute { mainModelFile = file; break } } var models: [StarGift.UniqueGift.Attribute] = [] for attribute in previewAttributes { - if case let .model(_, file, _) = attribute, + if case let StarGift.UniqueGift.Attribute.model(_, file, _, _) = attribute, file.fileId.id != mainModelFile?.fileId.id { models.append(attribute) } @@ -866,7 +866,7 @@ public final class GiftCompositionComponent: Component { return availableSize } - for case let .model(_, file, _) in models where !self.fetchedFiles.contains(file.fileId.id) { + for case let StarGift.UniqueGift.Attribute.model(_, file, _, _) in models where !self.fetchedFiles.contains(file.fileId.id) { self.disposables.add(freeMediaFileResourceInteractiveFetched( account: component.context.account, userLocation: .other, @@ -912,7 +912,7 @@ public final class GiftCompositionComponent: Component { } else if !nowAnimating && wasAnimating { var tail = Array(models.shuffled().prefix(6)) if let mainModelFile { - tail.append(.model(name: "", file: mainModelFile, rarity: 0)) + tail.append(.model(name: "", file: mainModelFile, rarity: .permille(0), crafted: false)) } self.beginDecelerationWithQueue( tail: tail, diff --git a/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/BUILD b/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/BUILD new file mode 100644 index 00000000..43a8d7c5 --- /dev/null +++ b/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/BUILD @@ -0,0 +1,32 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "GiftCraftScreen", + module_name = "GiftCraftScreen", + srcs = [ + "Sources/GiftCraftScreen.swift", + ], + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/AsyncDisplayKit", + "//submodules/Display", + "//submodules/TelegramCore", + "//submodules/TelegramPresentationData", + "//submodules/AccountContext", + "//submodules/ComponentFlow", + "//submodules/Components/ViewControllerComponent", + "//submodules/Components/SheetComponent", + "//submodules/Components/BundleIconComponent", + "//submodules/Components/BalancedTextComponent", + "//submodules/Components/MultilineTextComponent", + "//submodules/TelegramUI/Components/PlainButtonComponent", + "//submodules/TelegramUI/Components/ButtonComponent", + "//submodules/TelegramUI/Components/Gifts/GiftItemComponent", + "//submodules/TelegramUI/Components/GlassBarButtonComponent", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/CraftTableComponent.swift b/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/CraftTableComponent.swift new file mode 100644 index 00000000..ee783d14 --- /dev/null +++ b/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/CraftTableComponent.swift @@ -0,0 +1,833 @@ +import Foundation +import UIKit +import Display +import ComponentFlow +import SwiftSignalKit +import TelegramCore +import AccountContext +import GiftItemComponent +import GlassBackgroundComponent +import GlassBarButtonComponent +import BundleIconComponent +import LottieComponent + +private let cubeSide: CGFloat = 110.0 + +struct GiftItem: Equatable { + let gift: StarGift.UniqueGift + let reference: StarGiftReference +} + +final class CraftTableComponent: Component { + enum Result { + case gift(ProfileGiftsContext.State.StarGift) + case fail + } + + let context: AccountContext + let gifts: [Int32: GiftItem] + let buttonColor: UIColor + let isCrafting: Bool + let result: Result? + let select: (Int32) -> Void + let remove: (Int32) -> Void + let willFinish: (Bool) -> Void + let finished: (UIView?) -> Void + + public init( + context: AccountContext, + gifts: [Int32: GiftItem], + buttonColor: UIColor, + isCrafting: Bool, + result: Result?, + select: @escaping (Int32) -> Void, + remove: @escaping (Int32) -> Void, + willFinish: @escaping (Bool) -> Void, + finished: @escaping (UIView?) -> Void + ) { + self.context = context + self.gifts = gifts + self.buttonColor = buttonColor + self.isCrafting = isCrafting + self.result = result + self.select = select + self.remove = remove + self.willFinish = willFinish + self.finished = finished + } + + public static func ==(lhs: CraftTableComponent, rhs: CraftTableComponent) -> Bool { + if lhs.context !== rhs.context { + return false + } + if lhs.gifts != rhs.gifts { + return false + } + if lhs.buttonColor != rhs.buttonColor { + return false + } + if lhs.isCrafting != rhs.isCrafting { + return false + } + return true + } + + public final class View: UIView { + private var selectedGifts: [AnyHashable: ComponentView] = [:] + private var faces: [AnyHashable: ComponentView] = [:] + private let successFace = ComponentView() + + private let anvilPlayOnce = ActionSlot() + private let animationView = CubeAnimationView() + private let craftFailPlayOnce = ActionSlot() + + private var didSetupFinishAnimation = false + private var flipFaces = false + + private var isSuccess = false + private var isFailed = false + private var failDidStartCrossAnimation = false + private var failDidBringToFront = false + private var failWillFinish = false + private var failDidFinish = false + + private var component: CraftTableComponent? + private weak var state: EmptyComponentState? + + override init(frame: CGRect) { + super.init(frame: frame) + + self.addSubview(self.animationView) + + self.animationView.onStickerLaunch = { + HapticFeedback().impact(.soft) + } + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func setupFailureAnimation() { + guard !self.didSetupFinishAnimation else { + return + } + self.didSetupFinishAnimation = true + + self.animationView.onFinishApproach = { [weak self] isUpsideDown, isClockwise in + guard let self, let component = self.component else { + return + } + self.isFailed = true + self.animationView.setSticker(nil, face: 0, mirror: false) + + var availableStickers: [ComponentView] = [] + for (id, gift) in self.selectedGifts { + if let id = id.base as? Int, component.gifts[Int32(id)] != nil { + availableStickers.append(gift) + } + } + let wrappingCount = min(2, availableStickers.count) + for i in 0 ..< wrappingCount { + if let sticker = availableStickers[i].view { + let face: Int + if isClockwise { + face = i + 1 + } else { + face = 3 - i + } + self.animationView.setSticker(sticker, face: face, mirror: isUpsideDown, animated: true) + } + } + + self.flipFaces = isUpsideDown + + Queue.mainQueue().after(0.3, { + self.failWillFinish = true + self.component?.willFinish(false) + + self.craftFailPlayOnce.invoke(Void()) + }) + + Queue.mainQueue().after(0.5, { + self.failDidFinish = true + self.component?.finished(nil) + }) + + self.state?.updated(transition: .easeInOut(duration: 0.4)) + } + } + + func setupSuccessAnimation(_ gift: StarGift.UniqueGift) { + guard !self.didSetupFinishAnimation, let component = self.component else { + return + } + self.didSetupFinishAnimation = true + + self.animationView.isSuccess = true + + self.animationView.onFinishApproach = { [weak self] isUpsideDown, isClockwise in + guard let self else { + return + } + self.isSuccess = true + + var availableStickers: [ComponentView] = [] + for (id, gift) in self.selectedGifts { + if let id = id.base as? Int, component.gifts[Int32(id)] != nil { + availableStickers.append(gift) + } + } + let wrappingCount = min(2, availableStickers.count) + for i in 0 ..< wrappingCount { + if let sticker = availableStickers[i].view { + let face: Int + if isClockwise { + face = i + 1 + } else { + face = 3 - i + } + self.animationView.setSticker(sticker, face: face, mirror: isUpsideDown, animated: true) + } + } + + self.flipFaces = isUpsideDown + + let presentationData = component.context.sharedContext.currentPresentationData.with { $0 } + let _ = self.successFace.update( + transition: .immediate, + component: AnyComponent( + GiftItemComponent( + context: component.context, + style: .glass, + theme: presentationData.theme, + strings: presentationData.strings, + peer: nil, + subject: .uniqueGift(gift: gift, price: nil), + ribbon: nil, + resellPrice: nil, + isHidden: false, + isSelected: false, + isPinned: false, + isEditing: false, + mode: .grid, + cornerRadius: 28.0, + action: nil, + contextAction: nil + ) + ), + environment: {}, + containerSize: CGSize(width: cubeSide, height: cubeSide) + ) + if let successView = self.successFace.view as? GiftItemComponent.View { + let backgroundLayer = successView.backgroundLayer + if let patternView = successView.pattern { + backgroundLayer.opacity = 0.0 + patternView.alpha = 0.0 + Queue.mainQueue().after(1.0, { + let transition = ComponentTransition.easeInOut(duration: 0.3) + + transition.animateBlur(layer: backgroundLayer, fromRadius: 10.0, toRadius: 0.0) + transition.setAlpha(layer: backgroundLayer, alpha: 1.0) + + transition.setAlpha(view: patternView, alpha: 1.0) + transition.animateBlur(layer: patternView.layer, fromRadius: 10.0, toRadius: 0.0) + + Queue.mainQueue().after(1.0, { + self.component?.finished(successView) + }) + }) + } + + self.animationView.setSticker(successView, face: 0, mirror: isUpsideDown) + } + self.state?.updated() + } + } + + func update(component: CraftTableComponent, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + let previousComponent = self.component + self.component = component + self.state = state + + self.animationView.frame = CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: availableSize) + + let permilleValue = component.gifts.reduce(0, { $0 + Int($1.value.gift.craftChancePermille ?? 0) }) + + for index in 0 ..< 6 { + let face: ComponentView + if let current = self.faces[index] { + face = current + } else { + face = ComponentView() + self.faces[index] = face + } + + let faceComponent: AnyComponent + var faceItems: [AnyComponentWithIdentity] = [] + if index == 0 { + faceItems.append( + AnyComponentWithIdentity(id: "background", component: AnyComponent( + CubeFaceComponent(color: component.buttonColor, cornerRadius: 28.0) + )) + ) + if !component.isCrafting || self.isFailed { + faceItems.append( + AnyComponentWithIdentity(id: "glass", component: AnyComponent( + GlassBackgroundComponent(size: CGSize(width: cubeSide, height: cubeSide), cornerRadius: 28.0, isDark: true, tintColor: .init(kind: .custom, color: component.buttonColor)) + )) + ) + } + if self.isFailed { + faceItems.append( + AnyComponentWithIdentity(id: "faildial", component: AnyComponent( + DialIndicatorComponent( + content: AnyComponentWithIdentity(id: "gift", component: AnyComponent( + LottieComponent( + content: LottieComponent.AppBundleContent(name: "CraftFail"), + color: .white, + size: CGSize(width: 52.0, height: 52.0), + playOnce: self.craftFailPlayOnce + ) + )), + backgroundColor: .white.withAlphaComponent(0.1), + foregroundColor: .white, + diameter: 84.0, + contentSize: CGSize(width: 44.0, height: 44.0), + lineWidth: 5.0, + fontSize: 18.0, + progress: 0.0, + value: component.gifts.count, + suffix: "", + isVisible: true, + isFlipped: self.flipFaces + ) + )) + ) + } else if !self.isSuccess { + faceItems.append( + AnyComponentWithIdentity(id: "dial", component: AnyComponent( + DialIndicatorComponent( + content: AnyComponentWithIdentity(id: "empty", component: AnyComponent(Rectangle(color: .clear))), + backgroundColor: .white.withAlphaComponent(0.1), + foregroundColor: .white, + diameter: 84.0, + lineWidth: 5.0, + fontSize: 18.0, + progress: CGFloat(permilleValue) / 10.0 / 100.0, + value: permilleValue / 10, + suffix: "%", + isVisible: !component.isCrafting + ) + )) + ) + faceItems.append( + AnyComponentWithIdentity(id: "icon", component: AnyComponent( + LottieComponent( + content: LottieComponent.AppBundleContent(name: "Anvil"), + size: CGSize(width: 52.0, height: 52.0), + playOnce: self.anvilPlayOnce + ) + )) + ) + } + } else { + faceItems.append( + AnyComponentWithIdentity(id: "background", component: AnyComponent( + CubeFaceComponent(color: component.buttonColor, cornerRadius: 28.0) + )) + ) + faceItems.append( + AnyComponentWithIdentity(id: "icon", component: AnyComponent( + BundleIconComponent(name: "Components/CubeSide", tintColor: nil, flipVertically: index < 4 ? self.flipFaces : false) + )) + ) + } + faceComponent = AnyComponent( + ZStack(faceItems) + ) + + let _ = face.update( + transition: transition, + component: faceComponent, + environment: {}, + containerSize: CGSize(width: cubeSide, height: cubeSide) + ) + } + + if previousComponent == nil { + var faceViews: [UIView] = [] + for index in 0 ..< 6 { + if let faceView = self.faces[index]?.view { + faceView.bounds = CGRect(origin: .zero, size: CGSize(width: cubeSide, height: cubeSide)) + faceView.clipsToBounds = true + faceView.layer.rasterizationScale = UIScreenScale + faceView.layer.cornerRadius = 28.0 + faceViews.append(faceView) + } + } + self.animationView.setFaces(faceViews) + } + + var stickerViews: [UIView] = [] + for index in 0 ..< 4 { + let itemId = AnyHashable(index) + + var itemTransition = transition + let visibleItem: ComponentView + if let current = self.selectedGifts[itemId] { + visibleItem = current + } else { + visibleItem = ComponentView() + self.selectedGifts[itemId] = visibleItem + itemTransition = .immediate + } + + let gift = component.gifts[Int32(index)] + + let _ = visibleItem.update( + transition: itemTransition, + component: AnyComponent( + GiftSlotComponent( + context: component.context, + gift: gift, + buttonColor: component.buttonColor, + isCrafting: component.isCrafting, + action: { + component.select(Int32(index)) + }, + removeAction: index > 0 ? { + component.remove(Int32(index)) + } : nil + ) + ), + environment: {}, + containerSize: CGSize(width: cubeSide, height: cubeSide) + ) + if let itemView = visibleItem.view { + stickerViews.append(itemView) + } + } + + if previousComponent == nil { + self.animationView.setStickers(stickerViews) + } + + if let previousComponent, previousComponent.isCrafting != component.isCrafting { + var indices: [Int] = [] + for index in component.gifts.keys.sorted() { + indices.append(Int(index)) + } + + Queue.mainQueue().after(0.55) { + HapticFeedback().impact(.light) + } + + self.anvilPlayOnce.invoke(Void()) + Queue.mainQueue().after(0.75, { + self.animationView.startStickerSequence(indices: indices) + + switch component.result { + case let .gift(gift): + if case let .unique(uniqueGift) = gift.gift { + self.setupSuccessAnimation(uniqueGift) + } + case .fail: + self.setupFailureAnimation() + default: + break + } + }) + } + + return availableSize + } + } + + public func makeView() -> View { + return View(frame: CGRect()) + } + + public func update(view: View, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + return view.update(component: self, availableSize: availableSize, state: state, environment: environment, transition: transition) + } +} + + +final class GiftSlotComponent: Component { + let context: AccountContext + let gift: GiftItem? + let buttonColor: UIColor + let isCrafting: Bool + let action: () -> Void + let removeAction: (() -> Void)? + + public init( + context: AccountContext, + gift: GiftItem?, + buttonColor: UIColor, + isCrafting: Bool, + action: @escaping () -> Void, + removeAction: (() -> Void)? + ) { + self.context = context + self.gift = gift + self.buttonColor = buttonColor + self.isCrafting = isCrafting + self.action = action + self.removeAction = removeAction + } + + public static func ==(lhs: GiftSlotComponent, rhs: GiftSlotComponent) -> Bool { + if lhs.context !== rhs.context { + return false + } + if lhs.gift != rhs.gift { + return false + } + if lhs.buttonColor != rhs.buttonColor { + return false + } + if lhs.isCrafting != rhs.isCrafting { + return false + } + return true + } + + public final class View: UIView { + private let backgroundView = GlassBackgroundView() + private let addIcon = UIImageView() + private var icon: ComponentView? + private let button = HighlightTrackingButton() + + private var badge: ComponentView? + private var removeIcon: ComponentView? + private let removeButton = HighlightTrackingButton() + + private var component: GiftSlotComponent? + private weak var state: EmptyComponentState? + + override init(frame: CGRect) { + super.init(frame: frame) + + self.addIcon.image = generateAddIcon(backgroundColor: .white) + + self.addSubview(self.backgroundView) + self.backgroundView.contentView.addSubview(self.addIcon) + self.backgroundView.contentView.addSubview(self.button) + self.addSubview(self.removeButton) + + self.button.addTarget(self, action: #selector(self.buttonPressed), for: .touchUpInside) + self.removeButton.addTarget(self, action: #selector(self.removeButtonPressed), for: .touchUpInside) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + @objc private func buttonPressed() { + guard let _ = self.component?.removeAction else { + return + } + self.component?.action() + } + + @objc private func removeButtonPressed() { + self.component?.removeAction?() + } + + func update(component: GiftSlotComponent, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + let previousComponent = self.component + self.component = component + self.state = state + + let backgroundFrame = CGRect(origin: .zero, size: availableSize).insetBy(dx: 1.0, dy: 1.0) + self.backgroundView.update(size: backgroundFrame.size, cornerRadius: 28.0, isDark: true, tintColor: .init(kind: .custom, color: component.buttonColor), isInteractive: true, transition: .immediate) + transition.setFrame(view: self.backgroundView, frame: backgroundFrame) + if component.gift == nil && component.isCrafting && previousComponent?.isCrafting == false { + transition.setBlur(layer: self.backgroundView.layer, radius: 10.0) + self.backgroundView.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.35, removeOnCompletion: false) + transition.setBlur(layer: self.addIcon.layer, radius: 10.0) + } + transition.setAlpha(view: self.addIcon, alpha: component.isCrafting ? 0.0 : 1.0) + + if let icon = self.addIcon.image { + transition.setFrame(view: self.addIcon, frame: CGRect(origin: CGPoint(x: floor((backgroundFrame.width - icon.size.width) / 2.0), y: floor((backgroundFrame.height - icon.size.height) / 2.0)), size: icon.size)) + } + + if previousComponent?.gift?.gift.id != component.gift?.gift.id { + if let iconView = self.icon?.view { + if transition.animation.isImmediate { + iconView.removeFromSuperview() + } else { + transition.setScale(view: iconView, scale: 0.01) + transition.setAlpha(view: iconView, alpha: 0.0, completion: { _ in + iconView.removeFromSuperview() + }) + } + } + self.icon = nil + } + + if (previousComponent?.gift?.gift.id == nil) != (component.gift?.gift.id == nil) || ((previousComponent?.isCrafting ?? false) != component.isCrafting && component.isCrafting) { + if let badgeView = self.badge?.view { + if transition.animation.isImmediate { + badgeView.removeFromSuperview() + } else { + transition.setBlur(layer: badgeView.layer, radius: 10.0) + transition.setAlpha(view: badgeView, alpha: 0.0, completion: { _ in + badgeView.removeFromSuperview() + }) + } + } + self.badge = nil + + if let removeButtonView = self.removeIcon?.view { + if transition.animation.isImmediate { + removeButtonView.removeFromSuperview() + } else { + transition.setBlur(layer: removeButtonView.layer, radius: 10.0) + transition.setAlpha(view: removeButtonView, alpha: 0.0, completion: { _ in + removeButtonView.removeFromSuperview() + }) + } + } + self.removeIcon = nil + } + + if let gift = component.gift { + let icon: ComponentView + var iconTransition = transition + if let current = self.icon { + icon = current + } else { + iconTransition = .immediate + icon = ComponentView() + self.icon = icon + } + + let presentationData = component.context.sharedContext.currentPresentationData.with { $0 } + let iconSize = icon.update( + transition: iconTransition, + component: AnyComponent( + GiftItemComponent( + context: component.context, + style: .glass, + theme: presentationData.theme, + strings: presentationData.strings, + peer: nil, + subject: .uniqueGift(gift: gift.gift, price: nil), + ribbon: nil, + resellPrice: nil, + isHidden: false, + isSelected: false, + isPinned: false, + isEditing: false, + mode: .grid, + cornerRadius: 28.0, + action: nil, + contextAction: nil + ) + ), + environment: {}, + containerSize: CGSize(width: availableSize.width, height: availableSize.height) + ) + let iconFrame = CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: iconSize) + if let iconView = icon.view { + if iconView.superview == nil { + iconView.isUserInteractionEnabled = false + if let badgeView = self.badge?.view { + self.backgroundView.contentView.insertSubview(iconView, belowSubview: badgeView) + } else { + self.backgroundView.contentView.addSubview(iconView) + } + + if !transition.animation.isImmediate { + transition.animateAlpha(view: iconView, from: 0.0, to: 1.0) + transition.animateScale(view: iconView, from: 0.01, to: 1.0) + } + } + iconTransition.setFrame(view: iconView, frame: iconFrame) + } + + if !component.isCrafting { + var buttonColor: UIColor = component.buttonColor + if let backdropAttribute = gift.gift.attributes.first(where: { attribute in + if case .backdrop = attribute { + return true + } else { + return false + } + }), case let .backdrop(_, _, innerColor, _, _, _, _) = backdropAttribute { + buttonColor = UIColor(rgb: UInt32(bitPattern: innerColor)).withMultipliedBrightnessBy(0.65) + } + + let badge: ComponentView + var badgeTransition = transition + if let current = self.badge { + badge = current + } else { + badgeTransition = .immediate + badge = ComponentView() + self.badge = badge + } + + let badgeSize = badge.update( + transition: badgeTransition, + component: AnyComponent( + ZStack([ + AnyComponentWithIdentity(id: "background", component: AnyComponent( + RoundedRectangle(color: buttonColor, cornerRadius: 13.5, size: CGSize(width: 54.0, height: 27.0)) + )), + AnyComponentWithIdentity(id: "icon", component: AnyComponent( + Text(text: "\((gift.gift.craftChancePermille ?? 0) / 10)%", font: Font.semibold(17.0), color: .white) + )) + ]) + ), + environment: {}, + containerSize: CGSize(width: 54.0, height: 27.0) + ) + let badgeFrame = CGRect(origin: CGPoint(x: -6.0, y: -6.0 - UIScreenPixel), size: badgeSize) + if let badgeView = badge.view { + if badgeView.superview == nil { + badgeView.isUserInteractionEnabled = false + self.backgroundView.contentView.addSubview(badgeView) + + if !transition.animation.isImmediate { + transition.animateAlpha(view: badgeView, from: 0.0, to: 1.0) + transition.animateScale(view: badgeView, from: 0.01, to: 1.0) + } + } + badgeTransition.setFrame(view: badgeView, frame: badgeFrame) + } + + + if let _ = component.removeAction { + let removeButton: ComponentView + var removeButtonTransition = transition + if let current = self.removeIcon { + removeButton = current + } else { + removeButtonTransition = .immediate + removeButton = ComponentView() + self.removeIcon = removeButton + } + + let removeButtonSize = removeButton.update( + transition: removeButtonTransition, + component: AnyComponent( + ZStack([ + AnyComponentWithIdentity(id: "background", component: AnyComponent( + RoundedRectangle(color: buttonColor, cornerRadius: 13.5, size: CGSize(width: 27.0, height: 27.0)) + )), + AnyComponentWithIdentity(id: "icon", component: AnyComponent( + BundleIconComponent(name: "Media Gallery/PictureInPictureClose", tintColor: .white) + )) + ]) + ), + environment: {}, + containerSize: CGSize(width: 27.0, height: 27.0) + ) + let removeButtonFrame = CGRect(origin: CGPoint(x: availableSize.width - 21.0, y: -6.0 - UIScreenPixel), size: removeButtonSize) + if let removeButtonView = removeButton.view { + if removeButtonView.superview == nil { + removeButtonView.isUserInteractionEnabled = false + self.backgroundView.contentView.addSubview(removeButtonView) + + if !transition.animation.isImmediate { + transition.animateAlpha(view: removeButtonView, from: 0.0, to: 1.0) + transition.animateScale(view: removeButtonView, from: 0.01, to: 1.0) + } + } + removeButtonTransition.setFrame(view: removeButtonView, frame: removeButtonFrame) + } + } + } + } + + self.isUserInteractionEnabled = !component.isCrafting + self.button.frame = CGRect(origin: .zero, size: availableSize) + + self.removeButton.isUserInteractionEnabled = component.removeAction != nil + if let removeIcon = self.removeIcon?.view { + self.removeButton.frame = removeIcon.frame.insetBy(dx: -8.0, dy: -8.0) + } + + return availableSize + } + } + + public func makeView() -> View { + return View(frame: CGRect()) + } + + public func update(view: View, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + return view.update(component: self, availableSize: availableSize, state: state, environment: environment, transition: transition) + } +} + +private func generateAddIcon(backgroundColor: UIColor) -> UIImage? { + return generateImage(CGSize(width: 46.0, height: 46.0), contextGenerator: { size, context in + context.clear(CGRect(origin: .zero, size: size)) + + context.setFillColor(backgroundColor.cgColor) + context.fillEllipse(in: CGRect(origin: .zero, size: size)) + + context.setBlendMode(.clear) + context.setStrokeColor(UIColor.clear.cgColor) + context.setLineWidth(4.0) + context.setLineCap(.round) + + context.move(to: CGPoint(x: 23.0, y: 13.0)) + context.addLine(to: CGPoint(x: 23.0, y: 33.0)) + context.strokePath() + + context.move(to: CGPoint(x: 13.0, y: 23.0)) + context.addLine(to: CGPoint(x: 33.0, y: 23.0)) + context.strokePath() + }) +} + +private final class CubeFaceComponent: Component { + private let color: UIColor + private let cornerRadius: CGFloat + + public init(color: UIColor, cornerRadius: CGFloat) { + self.color = color + self.cornerRadius = cornerRadius + } + + public static func ==(lhs: CubeFaceComponent, rhs: CubeFaceComponent) -> Bool { + if !lhs.color.isEqual(rhs.color) { + return false + } + if lhs.cornerRadius != rhs.cornerRadius { + return false + } + return true + } + + public final class View: UIView { + override public init(frame: CGRect) { + super.init(frame: frame) + + self.clipsToBounds = true + self.layer.cornerCurve = .continuous + } + + required public init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + } + + public func makeView() -> View { + return View(frame: CGRect()) + } + + public func update(view: View, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + transition.setBackgroundColor(view: view, color: self.color) + transition.setCornerRadius(layer: view.layer, cornerRadius: self.cornerRadius) + + return availableSize + } +} diff --git a/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/CubeAnimationView.swift b/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/CubeAnimationView.swift new file mode 100644 index 00000000..077ba9d3 --- /dev/null +++ b/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/CubeAnimationView.swift @@ -0,0 +1,792 @@ +import UIKit +import simd +import Display + +final class Transform3DView: UIView { + override class var layerClass: AnyClass { CATransformLayer.self } +} + +final class PassthroughView: UIView { + override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { + for subview in self.subviews where !subview.isHidden && subview.alpha > 0 && subview.isUserInteractionEnabled { + let converted = self.convert(point, to: subview) + if subview.point(inside: converted, with: event) { + return true + } + } + return false + } +} + +final class CubeAnimationView: UIView { + private let cubeSize: CGFloat + private var perspective: CGFloat = 400.0 + private let stickerSize: CGFloat + private let stickerGap: CGFloat + + private let camera = UIView() + private let cubeContainer = Transform3DView() + private var faces: [UIView] = [] + private var faceOccupants: [Int: UIView] = [:] + + let stickerContainer = PassthroughView() + + private var stickers: [UIView] = [] + private var isRunning = false + + private var displayLink: SharedDisplayLinkDriver.Link? + private var lastTimestamp: CFTimeInterval = 0 + private var warpDisplayLink: SharedDisplayLinkDriver.Link? + private weak var warpView: UIView? + private var warpStartQuad: Quad? + private var warpEndQuad: Quad? + private var warpDuration: TimeInterval = 0 + private var warpDynamicTarget: (() -> Quad)? + private var warpCompletion: (() -> Void)? + private var warpStartTimestamp: CFTimeInterval = 0 + private var warpLastProgress: CGFloat = 0 + private var warpCurrentQuad: Quad? + private var warpHasCompleted = false + private var warpSnapshot: UIView? + + private var rotation = SIMD3(repeating: 0) + private var angularVelocity = SIMD3(repeating: 0) + + private let dampingPerSecond: Float = 0.66 + private let finishSpringX: Float = 28.0 + private let finishSpringY: Float = 18.0 + private let finishDampingX: Float = 2.0 * sqrt(28.0) + private let finishDampingY: Float = 2.0 * sqrt(18.0) + private let finishWobbleAmplitudeZ: Float = 10.0 * .pi / 180.0 + private let finishWobbleCycles: Float = 1.0 + private let finishWobbleDampingExponent: Float = 0.6 + private let finishSuccessScale: Float = 1.3 + private let finishSuccessScaleTriggerAngle: Float = 0.4 * .pi + private let finishApproachTriggerAngle: Float = 1.5 * .pi + private let baseImpulseStrength: Float = 4.0 + private let impactNudgeDistance: CGFloat = 20.0 + private let impactNudgeEmphasis: CGFloat = 28.0 + + private var isFinishingX = false + private var isFinishingY = false + private var finishTargetX: Float = 0.0 + private var finishTargetY: Float = 0.0 + private var finishDirectionY: Float = 1.0 + private var finishRotationY: Float = 0.0 + private var finishTargetYUnwrapped: Float = 0.0 + private var finishRemainingYStart: Float = 0.0 + private var finishDelayTimerX: Timer? + private var finishDelayTimerY: Timer? + private var cubeScale: Float = 1.0 + private var hasFiredFinishApproach = false + + var isSuccess = false + + var onStickerLaunch: (() -> Void)? + var onFinishApproach: ((Bool, Bool) -> Void)? + + private let defaultStickOrder: [Int] = [0, 5, 4, 3] + private let sequenceStickOrders: [String: [Int]] = [ + "0": [0], + "0,1": [0, 5], + "0,2": [0, 5], + "0,3": [0, 5], + "0,1,2": [0, 5, 4], + "0,1,3": [0, 5, 2], + "0,2,3": [0, 5, 1], + "0,1,2,3": [0, 5, 4, 3] + ] + private var activeStickOrder: [Int] = [] + + init(cubeSize: CGFloat = 110.0, stickerSize: CGFloat = 76.0, stickerGap: CGFloat = 30.0) { + self.cubeSize = cubeSize + self.stickerSize = stickerSize + self.stickerGap = stickerGap + + super.init(frame: .zero) + + self.activeStickOrder = self.defaultStickOrder + + self.camera.backgroundColor = .clear + self.camera.clipsToBounds = false + self.addSubview(self.camera) + + self.cubeContainer.backgroundColor = .clear + self.cubeContainer.clipsToBounds = false + self.camera.addSubview(self.cubeContainer) + + var p = CATransform3DIdentity + p.m34 = -1.0 / self.perspective + self.camera.layer.sublayerTransform = p + self.stickerContainer.layer.sublayerTransform = p + + self.stickerContainer.backgroundColor = .clear + self.stickerContainer.clipsToBounds = false + self.addSubview(self.stickerContainer) + +#if DEBUG + let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:))) + self.camera.addGestureRecognizer(pan) +#endif + } + + required init?(coder: NSCoder) { + preconditionFailure() + } + + override func layoutSubviews() { + super.layoutSubviews() + + self.camera.bounds = CGRect(x: 0, y: 0, width: self.cubeSize, height: self.cubeSize) + self.camera.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY) + + self.cubeContainer.frame = self.camera.bounds + self.stickerContainer.frame = self.bounds + + self.layoutStickers() + self.layoutFaces() + self.applyCubeRotation() + } + + func setStickers(_ views: [UIView]) { + self.stickers = views + for view in views { + view.layer.anchorPoint = .zero + view.isUserInteractionEnabled = true + + if view.superview !== self.stickerContainer { + self.stickerContainer.addSubview(view) + } + } + self.layoutStickers() + } + + func setSticker(_ sticker: UIView?, face index: Int, mirror: Bool, animated: Bool = false) { + guard self.faces.indices.contains(index) else { + return + } + + if let existing = self.faceOccupants[index] { + existing.removeFromSuperview() + self.faceOccupants[index] = nil + } + + guard let sticker else { + return + } + + if let priorIndex = self.faceOccupants.first(where: { $0.value === sticker })?.key { + self.faceOccupants[priorIndex] = nil + } + + if animated, let stickerSuperview = sticker.superview, let snapshotView = sticker.snapshotView(afterScreenUpdates: false) { + stickerSuperview.addSubview(snapshotView) + snapshotView.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, removeOnCompletion: false, completion: { _ in + snapshotView.removeFromSuperview() + }) + } + sticker.removeFromSuperview() + + let targetFace = self.faces[index] + targetFace.addSubview(sticker) + self.faceOccupants[index] = sticker + + sticker.layer.removeAllAnimations() + sticker.transform = .identity + sticker.layer.transform = CATransform3DIdentity + sticker.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) + sticker.layer.isDoubleSided = false + sticker.clipsToBounds = false + sticker.isUserInteractionEnabled = false + + let faceStickerSize = self.cubeSize + sticker.bounds = CGRect(x: 0, y: 0, width: faceStickerSize, height: faceStickerSize) + sticker.center = CGPoint(x: self.cubeSize / 2, y: self.cubeSize / 2) + + var snappedAngle: CGFloat = 0.0 + if mirror { + snappedAngle += .pi + } + sticker.transform = CGAffineTransform(rotationAngle: snappedAngle) + + if animated { + sticker.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2) + } + } + + func startStickerSequence(indices: [Int]? = nil) { + guard !self.isRunning else { + return + } + guard self.stickers.contains(where: { $0.superview === self.stickerContainer }) else { + return + } + self.isRunning = true + + let sequence: [Int] + if let indices, !indices.isEmpty { + var seen = Set() + var result: [Int] = [] + for index in indices where self.stickers.indices.contains(index) { + if seen.insert(index).inserted { + result.append(index) + } + } + sequence = result + } else { + sequence = Array(self.stickers.indices) + } + + var stickOrder: [Int] + let key = sequence.map(String.init).joined(separator: ",") + if let order = self.sequenceStickOrders[key] { + stickOrder = order + } else { + stickOrder = Array(self.defaultStickOrder.prefix(sequence.count)) + } + self.activeStickOrder = stickOrder + + self.scheduleStickerSequence(from: 0, indices: sequence) + } + + func resetAll() { + self.isRunning = false + self.resetStickers() + self.resetCube() + self.activeStickOrder = self.defaultStickOrder + } + + func setFaces(_ views: [UIView]) { + guard views.count == 6 else { + return + } + self.faces.forEach { $0.removeFromSuperview() } + self.faces = views + for face in views { + face.layer.isDoubleSided = false + self.cubeContainer.addSubview(face) + } + self.layoutFaces() + } + + private func layoutFaces() { + guard self.faces.count == 6 else { + return + } + let half = self.cubeSize / 2 + + for face in self.faces { + face.bounds = CGRect(x: 0, y: 0, width: self.cubeSize, height: self.cubeSize) + face.center = CGPoint(x: self.cubeSize / 2, y: self.cubeSize / 2) + } + + func faceTransform(rx: CGFloat, ry: CGFloat) -> CATransform3D { + var m = CATransform3DIdentity + m = CATransform3DRotate(m, rx, 1, 0, 0) + m = CATransform3DRotate(m, ry, 0, 1, 0) + m = CATransform3DTranslate(m, 0, 0, half) + return m + } + + self.faces[0].layer.transform = faceTransform(rx: 0, ry: 0) + self.faces[1].layer.transform = faceTransform(rx: 0, ry: .pi / 2) + self.faces[2].layer.transform = faceTransform(rx: 0, ry: .pi) + self.faces[3].layer.transform = faceTransform(rx: 0, ry: -.pi / 2) + self.faces[4].layer.transform = faceTransform(rx: -.pi / 2, ry: 0) + self.faces[5].layer.transform = faceTransform(rx: .pi / 2, ry: 0) + } + + private func animateWarp(for view: UIView, from startQuad: Quad, to targetQuad: Quad, duration: TimeInterval, dynamicTarget: (() -> Quad)? = nil, completion: @escaping () -> Void) { + self.cancelWarp() + self.warpView = view + self.warpStartQuad = startQuad + self.warpEndQuad = targetQuad + self.warpDuration = duration + self.warpDynamicTarget = dynamicTarget + self.warpCompletion = completion + self.warpStartTimestamp = 0 + self.warpLastProgress = 0 + self.warpHasCompleted = false + self.warpCurrentQuad = startQuad + startQuad.apply(to: view) + + let link = SharedDisplayLinkDriver.shared.add(framesPerSecond: .max) { [weak self] _ in + self?.stepWarp() + } + link.isPaused = false + self.warpDisplayLink = link + } + + private func stepWarp() { + guard let view = self.warpView, let currentQuad = self.warpCurrentQuad, let endQuad = self.warpEndQuad else { + self.finishWarp() + return + } + + if self.warpStartTimestamp == 0 { + self.warpStartTimestamp = CACurrentMediaTime() + } + + let elapsed = CACurrentMediaTime() - self.warpStartTimestamp + let progress = self.warpDuration > 0 ? min(1.0, elapsed / self.warpDuration) : 1.0 + let t = CGFloat(progress) + let eased = t * t * (3 - 2 * t) + let target = self.warpDynamicTarget?() ?? endQuad + let delta = eased - self.warpLastProgress + let remaining = max(1 - self.warpLastProgress, 0.0001) + let weight = max(0, min(1, delta / remaining)) + let nextQuad = currentQuad.interpolated(to: target, t: weight) + nextQuad.apply(to: view) + self.warpCurrentQuad = nextQuad + self.warpLastProgress = eased + + if progress >= 1.0 { + self.finishWarp() + } + } + + private func cancelWarp() { + self.warpHasCompleted = true + self.warpDisplayLink?.invalidate() + self.warpDisplayLink = nil + self.warpCompletion = nil + self.clearWarpState() + } + + private func finishWarp() { + guard !self.warpHasCompleted else { return } + self.warpHasCompleted = true + self.warpDisplayLink?.invalidate() + self.warpDisplayLink = nil + self.warpCompletion?() + self.warpCompletion = nil + self.clearWarpState() + } + + private func clearWarpState() { + self.warpView = nil + self.warpStartQuad = nil + self.warpEndQuad = nil + self.warpDynamicTarget = nil + self.warpStartTimestamp = 0 + self.warpLastProgress = 0 + self.warpCurrentQuad = nil + } + + private func projectedQuad(for face: UIView) -> ProjectedFace { + let bounds = face.bounds + + func project(_ p: CGPoint) -> CGPoint { + let inRoot = face.layer.convert(p, to: self.layer) + return self.stickerContainer.layer.convert(inRoot, from: self.layer) + } + + var topLeft = project(CGPoint(x: bounds.minX, y: bounds.minY)) + var topRight = project(CGPoint(x: bounds.maxX, y: bounds.minY)) + var bottomLeft = project(CGPoint(x: bounds.minX, y: bounds.maxY)) + var bottomRight = project(CGPoint(x: bounds.maxX, y: bounds.maxY)) + + func center(_ a: CGPoint, _ b: CGPoint) -> CGPoint { + CGPoint(x: (a.x + b.x) * 0.5, y: (a.y + b.y) * 0.5) + } + + func normalized(_ v: CGPoint) -> CGPoint? { + let len = hypot(v.x, v.y) + guard len > 1e-5 else { return nil } + return CGPoint(x: v.x / len, y: v.y / len) + } + + func dot(_ a: CGPoint, _ b: CGPoint) -> CGFloat { + a.x * b.x + a.y * b.y + } + + let screenUp = CGPoint(x: 0, y: -1) + let screenRight = CGPoint(x: 1, y: 0) + + if let up = normalized(CGPoint( + x: center(topLeft, topRight).x - center(bottomLeft, bottomRight).x, + y: center(topLeft, topRight).y - center(bottomLeft, bottomRight).y + )), dot(up, screenUp) < 0 { + swap(&topLeft, &bottomLeft) + swap(&topRight, &bottomRight) + } + + let faceOrigin = project(.zero) + let faceX = project(CGPoint(x: 1, y: 0)) + + if let right = normalized(CGPoint( + x: center(topRight, bottomRight).x - center(topLeft, bottomLeft).x, + y: center(topRight, bottomRight).y - center(topLeft, bottomLeft).y + )), dot(right, screenRight) < 0 { + swap(&topLeft, &topRight) + swap(&bottomLeft, &bottomRight) + } + + let quad = Quad(topLeft: topLeft, topRight: topRight, bottomLeft: bottomLeft, bottomRight: bottomRight) + + let desiredTopVector = CGPoint(x: quad.topRight.x - quad.topLeft.x, y: quad.topRight.y - quad.topLeft.y) + let baseTopVector = CGPoint(x: faceX.x - faceOrigin.x, y: faceX.y - faceOrigin.y) + + let desiredAngle = atan2(desiredTopVector.y, desiredTopVector.x) + let baseAngle = atan2(baseTopVector.y, baseTopVector.x) + let rotation = normalizeAngle(desiredAngle - baseAngle) + + return ProjectedFace(quad: quad, rotation: rotation) + } + + private func layoutStickers() { + guard !self.stickers.isEmpty else { + return + } + + let cubeCenterInSticker = self.stickerContainer.convert(self.camera.center, from: self) + let r = self.cubeSize / 2 + self.stickerGap + self.stickerSize / 2 + let scale = self.stickerSize / self.cubeSize + + let positions = [ + CGPoint(x: cubeCenterInSticker.x - r, y: cubeCenterInSticker.y - r * 0.4), + CGPoint(x: cubeCenterInSticker.x + r, y: cubeCenterInSticker.y - r * 0.4), + CGPoint(x: cubeCenterInSticker.x - r, y: cubeCenterInSticker.y + r * 0.4), + CGPoint(x: cubeCenterInSticker.x + r, y: cubeCenterInSticker.y + r * 0.4) + ] + + for (i, view) in self.stickers.enumerated() { + if view.superview !== self.stickerContainer { + continue + } + view.bounds = CGRect(x: 0, y: 0, width: self.cubeSize, height: self.cubeSize) + view.transform = CGAffineTransform(scaleX: scale, y: scale) + view.center = CGPoint(x: positions[i].x - self.stickerSize * 0.5, y: positions[i].y - self.stickerSize * 0.5) + } + } + + @objc private func handlePan(_ gesture: UIPanGestureRecognizer) { + let translation = gesture.translation(in: self.camera) + switch gesture.state { + case .changed: + let delta = CGPoint(x: translation.x, y: translation.y) + + self.rotation.y += Float(delta.x) * 0.018 + self.rotation.x += Float(-delta.y) * 0.018 + self.rotation = normalizedRotation(self.rotation) + self.applyCubeRotation() + + gesture.setTranslation(.zero, in: self.camera) + default: + break + } + } + + func launchStickerView(_ sticker: UIView, emphasized: Bool, willFinish: Bool = false) { + guard sticker.superview === self.stickerContainer else { + return + } + var number = 0 + if self.faceOccupants.count < self.activeStickOrder.count { + number = self.activeStickOrder[self.faceOccupants.count] + } + let faceIndex = number + guard self.faces.count > faceIndex else { return } + let targetFace = self.faces[faceIndex] + + let startCenterInSticker = sticker.center + let cubeCenterInSticker = self.stickerContainer.convert(self.camera.center, from: self) + + sticker.isUserInteractionEnabled = false + sticker.layer.isDoubleSided = false + + let faceStickerSize = self.cubeSize + let duration: TimeInterval = 0.2 + let startQuad = Quad(rect: sticker.frame) + let animationView: UIView + if let snapshot = sticker.snapshotView(afterScreenUpdates: false) { + self.warpSnapshot?.removeFromSuperview() + self.warpSnapshot = snapshot + + snapshot.bounds = sticker.bounds + snapshot.center = sticker.center + snapshot.layer.anchorPoint = sticker.layer.anchorPoint + snapshot.layer.transform = sticker.layer.transform + snapshot.layer.isDoubleSided = sticker.layer.isDoubleSided + snapshot.isUserInteractionEnabled = false + self.stickerContainer.addSubview(snapshot) + + sticker.isHidden = true + animationView = snapshot + } else { + animationView = sticker + } + sticker.transform = .identity + + let projectedFace = self.projectedQuad(for: targetFace) + let targetQuad = projectedFace.quad + let dynamicTarget: () -> Quad = { [weak self, weak targetFace] in + guard let self, let face = targetFace else { + return targetQuad + } + return self.projectedQuad(for: face).quad + } + + self.animateWarp(for: animationView, from: startQuad, to: targetQuad, duration: duration, dynamicTarget: dynamicTarget) { [weak self, weak sticker, weak targetFace, weak animationView] in + guard let self, let sticker, let targetFace else { + return + } + + self.onStickerLaunch?() + + if let animationView, animationView !== sticker { + animationView.removeFromSuperview() + self.warpSnapshot = nil + sticker.isHidden = false + } + + sticker.removeFromSuperview() + targetFace.addSubview(sticker) + self.faceOccupants[faceIndex] = sticker + + sticker.bounds = CGRect(x: 0, y: 0, width: faceStickerSize, height: faceStickerSize) + sticker.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) + sticker.center = CGPoint(x: self.cubeSize / 2, y: self.cubeSize / 2) + sticker.layer.transform = CATransform3DIdentity + let finalProjection = self.projectedQuad(for: targetFace) + let snappedAngle = snappedRightAngle(finalProjection.rotation) + sticker.transform = CGAffineTransform(rotationAngle: snappedAngle) + + let delta = SIMD2(Float(cubeCenterInSticker.x - startCenterInSticker.x), Float(cubeCenterInSticker.y - startCenterInSticker.y)) + let direction = normalize2(delta) + self.applyImpulse(direction: direction, emphasized: emphasized, replace: true) + self.applyImpactSpring(direction: direction, emphasized: emphasized) + if willFinish { + self.startFinishingAnimation() + } + self.startSpinLoopIfNeeded() + } + } + + private func resetStickers() { + self.cancelWarp() + self.warpSnapshot?.removeFromSuperview() + self.warpSnapshot = nil + + for sticker in self.stickers { + sticker.layer.removeAllAnimations() + sticker.transform = .identity + sticker.layer.transform = CATransform3DIdentity + sticker.layer.anchorPoint = .zero + sticker.layer.isDoubleSided = true + sticker.clipsToBounds = false + sticker.isUserInteractionEnabled = true + sticker.removeFromSuperview() + self.stickerContainer.addSubview(sticker) + } + + self.faceOccupants.removeAll() + self.layoutStickers() + } + + private func resetCube() { + self.displayLink?.invalidate() + self.displayLink = nil + self.angularVelocity = .zero + self.lastTimestamp = 0 + self.isFinishingX = false + self.isFinishingY = false + self.finishDelayTimerX?.invalidate() + self.finishDelayTimerX = nil + self.finishDelayTimerY?.invalidate() + self.finishDelayTimerY = nil + self.cubeScale = 1.0 + self.hasFiredFinishApproach = false + + self.rotation = SIMD3(repeating: 0) + self.cubeScale = 1.0 + self.applyCubeRotation() + } + + private func scheduleStickerSequence(from index: Int, indices: [Int]) { + guard self.isRunning else { + return + } + guard index < indices.count else { + self.isRunning = false + return + } + + let delay: TimeInterval = index == 0 ? 0.0 : 1.0 + DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in + guard let self else { + return + } + guard self.isRunning else { + return + } + let stickerIndex = indices[index] + if self.stickers.indices.contains(stickerIndex) { + let isLast = index == indices.count - 1 + self.launchStickerView(self.stickers[stickerIndex], emphasized: isLast, willFinish: isLast) + } + self.scheduleStickerSequence(from: index + 1, indices: indices) + } + } + + private func applyImpulse(direction: SIMD2, emphasized: Bool, replace: Bool) { + var xStrength = self.baseImpulseStrength + var yStrength = self.baseImpulseStrength + if emphasized { + xStrength *= 10.0 + yStrength *= 4.0 + } + let impulseX: Float = -direction.y * xStrength + let impulseY: Float = direction.x * yStrength + let impulseZ: Float = 0.0 + + if replace { + self.angularVelocity = SIMD3(impulseX, impulseY, impulseZ) + } else { + self.angularVelocity += SIMD3(impulseX, impulseY, impulseZ) + } + } + + private func applyImpactSpring(direction: SIMD2, emphasized: Bool) { + guard simd_length(direction) > 0.0001 else { + return + } + let distance = emphasized ? self.impactNudgeEmphasis : self.impactNudgeDistance + let offsetX = CGFloat(direction.x) * distance + let offsetY = CGFloat(direction.y) * distance + + let currentTransform = self.camera.layer.presentation()?.affineTransform() ?? self.camera.transform + self.camera.layer.removeAllAnimations() + let impactTransform = currentTransform.translatedBy(x: offsetX, y: offsetY) + + UIView.animate(withDuration: 0.08, delay: 0.0, options: [.curveEaseOut, .beginFromCurrentState]) { + self.camera.transform = impactTransform + } completion: { _ in + UIView.animate(withDuration: 0.55, delay: 0, usingSpringWithDamping: 0.72, initialSpringVelocity: 0.2, options: .beginFromCurrentState) { + self.camera.transform = .identity + } + } + } + + private func startSpinLoopIfNeeded() { + if self.displayLink == nil { + let link = SharedDisplayLinkDriver.shared.add(framesPerSecond: .max) { [weak self] _ in + self?.tick() + } + link.isPaused = false + self.displayLink = link + self.lastTimestamp = 0.0 + } + } + + private func tick() { + let ts = CACurrentMediaTime() + if self.lastTimestamp == 0 { self.lastTimestamp = ts; return } + let dt = Float(ts - self.lastTimestamp) + self.lastTimestamp = ts + + self.rotation += self.angularVelocity * dt + if self.isFinishingX { + let delta = shortestAngleDelta(from: self.rotation.x, to: self.finishTargetX) + let accel = self.finishSpringX * delta - self.finishDampingX * self.angularVelocity.x + self.angularVelocity.x += accel * dt + if abs(delta) < 0.0006 && abs(self.angularVelocity.x) < 0.001 { + self.rotation.x = self.finishTargetX + self.angularVelocity.x = 0.0 + self.isFinishingX = false + } + } + if self.isFinishingY { + self.finishRotationY += self.angularVelocity.y * dt + let remaining = self.finishTargetYUnwrapped - self.finishRotationY + let accel = self.finishSpringY * remaining - self.finishDampingY * self.angularVelocity.y + self.angularVelocity.y += accel * dt + self.rotation.y = normalizeAngle(self.finishRotationY) + let total = max(abs(self.finishRemainingYStart), 0.0001) + let progress = min(max(1.0 - abs(remaining) / total, 0.0), 1.0) + let damping = pow(1.0 - progress, self.finishWobbleDampingExponent) + let phase = 2.0 * Float.pi * self.finishWobbleCycles * progress + self.rotation.z = self.finishWobbleAmplitudeZ * sin(phase) * damping + let absRemaining = abs(remaining) + if !self.hasFiredFinishApproach && absRemaining <= self.finishApproachTriggerAngle { + self.hasFiredFinishApproach = true + let upsideDown = abs(shortestAngleDelta(from: self.rotation.x, to: Float.pi)) < (Float.pi / 2) + let isClockwise = self.finishDirectionY > 0 + self.onFinishApproach?(upsideDown, isClockwise) + } + if self.isSuccess, absRemaining <= self.finishSuccessScaleTriggerAngle { + let raw = (self.finishSuccessScaleTriggerAngle - absRemaining) / self.finishSuccessScaleTriggerAngle + let eased = raw * raw * (3 - 2 * raw) + self.cubeScale = 1.0 + (self.finishSuccessScale - 1.0) * eased + } else if !self.isSuccess { + self.cubeScale = 1.0 + } + if abs(remaining) < 0.0008 && abs(self.angularVelocity.y) < 0.0015 { + self.finishRotationY = self.finishTargetYUnwrapped + self.rotation.y = self.finishTargetY + self.angularVelocity.y = 0.0 + self.isFinishingY = false + self.rotation.z = 0.0 + self.angularVelocity.z = 0.0 + } + } else if self.rotation.z != 0 { + self.rotation.z = 0.0 + } + self.rotation = normalizedRotation(self.rotation) + + let damp = pow(self.dampingPerSecond, dt) + self.angularVelocity *= damp + + self.applyCubeRotation() + } + + private func startFinishingAnimation() { + self.finishDelayTimerX?.invalidate() + self.finishDelayTimerX = Timer.scheduledTimer(withTimeInterval: 0.75, repeats: false) { [weak self] _ in + self?.beginFinishingX() + } + } + + private func beginFinishingX() { + let deltaToZero = abs(shortestAngleDelta(from: self.rotation.x, to: 0)) + let deltaToPi = abs(shortestAngleDelta(from: self.rotation.x, to: Float.pi)) + self.finishTargetX = deltaToZero <= deltaToPi ? 0 : Float.pi + self.finishTargetY = self.finishTargetX == 0 ? 0 : Float.pi + self.isFinishingX = true + self.finishDelayTimerY?.invalidate() + self.finishDelayTimerY = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { [weak self] _ in + self?.beginFinishingY() + } + } + + private func beginFinishingY() { + self.finishRotationY = self.rotation.y + let directionY = nonZeroSign(self.angularVelocity.y, fallback: 1) + self.finishDirectionY = directionY + let startMod = normalizeAnglePositive(self.finishRotationY) + let targetMod = normalizeAnglePositive(self.finishTargetY) + let baseDelta: Float + if directionY >= 0 { + baseDelta = targetMod >= startMod ? targetMod - startMod : (Float.pi * 2) - (startMod - targetMod) + } else { + baseDelta = startMod >= targetMod ? startMod - targetMod : (Float.pi * 2) - (targetMod - startMod) + } + var delta = baseDelta + if delta < Float.pi { + delta += Float.pi * 2 + } + self.finishTargetYUnwrapped = self.finishRotationY + directionY * delta + self.finishRemainingYStart = self.finishTargetYUnwrapped - self.finishRotationY + self.isFinishingY = true + self.hasFiredFinishApproach = false + } + + private func applyCubeRotation() { + var m = CATransform3DIdentity + m = CATransform3DRotate(m, CGFloat(self.rotation.x), 1, 0, 0) + m = CATransform3DRotate(m, CGFloat(self.rotation.y), 0, 1, 0) + m = CATransform3DRotate(m, CGFloat(self.rotation.z), 0, 0, 1) + m = CATransform3DScale(m, CGFloat(self.cubeScale), CGFloat(self.cubeScale), 1) + self.cubeContainer.layer.transform = m + } +} diff --git a/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/CubeUtils.swift b/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/CubeUtils.swift new file mode 100644 index 00000000..af8ff126 --- /dev/null +++ b/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/CubeUtils.swift @@ -0,0 +1,193 @@ +import UIKit +import simd + +func normalize2(_ v: SIMD2) -> SIMD2 { + let l = simd_length(v) + return l > 1e-5 ? v / l : SIMD2(0, 0) +} + +func normalizedRotation(_ r: SIMD3) -> SIMD3 { + SIMD3(normalizeAngle(r.x), normalizeAngle(r.y), normalizeAngle(r.z)) +} + +struct ProjectedFace { + let quad: Quad + let rotation: CGFloat +} + +struct Quad { + var topLeft: CGPoint + var topRight: CGPoint + var bottomLeft: CGPoint + var bottomRight: CGPoint + + init(topLeft: CGPoint, topRight: CGPoint, bottomLeft: CGPoint, bottomRight: CGPoint) { + self.topLeft = topLeft + self.topRight = topRight + self.bottomLeft = bottomLeft + self.bottomRight = bottomRight + } + + init(rect: CGRect) { + self.init( + topLeft: rect.origin, + topRight: CGPoint(x: rect.maxX, y: rect.minY), + bottomLeft: CGPoint(x: rect.minX, y: rect.maxY), + bottomRight: CGPoint(x: rect.maxX, y: rect.maxY) + ) + } + + func boundingBox() -> CGRect { + let xs = [topLeft.x, topRight.x, bottomLeft.x, bottomRight.x] + let ys = [topLeft.y, topRight.y, bottomLeft.y, bottomRight.y] + guard let minX = xs.min(), let maxX = xs.max(), let minY = ys.min(), let maxY = ys.max() else { + return .zero + } + return CGRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY) + } + + func offsetting(dx: CGFloat, dy: CGFloat) -> Quad { + return Quad( + topLeft: CGPoint(x: topLeft.x + dx, y: topLeft.y + dy), + topRight: CGPoint(x: topRight.x + dx, y: topRight.y + dy), + bottomLeft: CGPoint(x: bottomLeft.x + dx, y: bottomLeft.y + dy), + bottomRight: CGPoint(x: bottomRight.x + dx, y: bottomRight.y + dy) + ) + } + + func interpolated(to other: Quad, t: CGFloat) -> Quad { + return Quad( + topLeft: lerp(topLeft, other.topLeft, t), + topRight: lerp(topRight, other.topRight, t), + bottomLeft: lerp(bottomLeft, other.bottomLeft, t), + bottomRight: lerp(bottomRight, other.bottomRight, t) + ) + } + + func apply(to view: UIView) { + let bounds = boundingBox() + let localQuad = offsetting(dx: -bounds.origin.x, dy: -bounds.origin.y) + + CATransaction.begin() + CATransaction.setDisableActions(true) + view.frame = bounds + let transform = rectToQuad(rect: view.bounds, quad: localQuad) + view.layer.transform = transform + CATransaction.commit() + } +} + +func lerp(_ a: CGFloat, _ b: CGFloat, _ t: CGFloat) -> CGFloat { + return a + (b - a) * t +} + +func lerp(_ a: CGPoint, _ b: CGPoint, _ t: CGFloat) -> CGPoint { + return CGPoint(x: lerp(a.x, b.x, t), y: lerp(a.y, b.y, t)) +} + +func normalizeAngle(_ angle: CGFloat) -> CGFloat { + var result = angle + let twoPi = CGFloat.pi * 2 + while result > CGFloat.pi { + result -= twoPi + } + while result <= -CGFloat.pi { + result += twoPi + } + return result +} + +func normalizeAngle(_ angle: Float) -> Float { + var result = angle + let twoPi = Float.pi * 2 + while result > Float.pi { + result -= twoPi + } + while result <= -Float.pi { + result += twoPi + } + return result +} + +func normalizeAnglePositive(_ angle: Float) -> Float { + var result = angle + let twoPi = Float.pi * 2 + while result < 0 { result += twoPi } + while result >= twoPi { result -= twoPi } + return result +} + +func shortestAngleDelta(from: Float, to: Float) -> Float { + return normalizeAngle(to - from) +} + +func nonZeroSign(_ value: Float, fallback: Float) -> Float { + if value > 0 { return 1 } + if value < 0 { return -1 } + return fallback +} + +func snappedRightAngle(_ angle: CGFloat) -> CGFloat { + let quarter = CGFloat.pi / 2 + let normalized = normalizeAngle(angle) + let step = round(normalized / quarter) + return step * quarter +} + +func rectToQuad(rect: CGRect, quad: Quad) -> CATransform3D { + let x1a = quad.topLeft.x + let y1a = quad.topLeft.y + let x2a = quad.topRight.x + let y2a = quad.topRight.y + let x3a = quad.bottomLeft.x + let y3a = quad.bottomLeft.y + let x4a = quad.bottomRight.x + let y4a = quad.bottomRight.y + + let X = rect.origin.x + let Y = rect.origin.y + let W = rect.size.width + let H = rect.size.height + + let y21 = y2a - y1a + let y32 = y3a - y2a + let y43 = y4a - y3a + let y14 = y1a - y4a + let y31 = y3a - y1a + let y42 = y4a - y2a + + let a = -H * (x2a * x3a * y14 + x2a * x4a * y31 - x1a * x4a * y32 + x1a * x3a * y42) + let b = W * (x2a * x3a * y14 + x3a * x4a * y21 + x1a * x4a * y32 + x1a * x2a * y43) + let c = H * X * (x2a * x3a * y14 + x2a * x4a * y31 - x1a * x4a * y32 + x1a * x3a * y42) + - H * W * x1a * (x4a * y32 - x3a * y42 + x2a * y43) + - W * Y * (x2a * x3a * y14 + x3a * x4a * y21 + x1a * x4a * y32 + x1a * x2a * y43) + + let d = H * (-x4a * y21 * y3a + x2a * y1a * y43 - x1a * y2a * y43 - x3a * y1a * y4a + x3a * y2a * y4a) + let e = W * (x4a * y2a * y31 - x3a * y1a * y42 - x2a * y31 * y4a + x1a * y3a * y42) + let f = -( + W * (x4a * (Y * y2a * y31 + H * y1a * y32) + - x3a * (H + Y) * y1a * y42 + + H * x2a * y1a * y43 + + x2a * Y * (y1a - y3a) * y4a + + x1a * Y * y3a * (-y2a + y4a)) + - H * X * (x4a * y21 * y3a - x2a * y1a * y43 + x3a * (y1a - y2a) * y4a + x1a * y2a * (-y3a + y4a)) + ) + + let g = H * (x3a * y21 - x4a * y21 + (-x1a + x2a) * y43) + let h = W * (-x2a * y31 + x4a * y31 + (x1a - x3a) * y42) + var i = W * Y * (x2a * y31 - x4a * y31 - x1a * y42 + x3a * y42) + + H * (X * (-(x3a * y21) + x4a * y21 + x1a * y43 - x2a * y43) + + W * (-(x3a * y2a) + x4a * y2a + x2a * y3a - x4a * y3a - x2a * y4a + x3a * y4a)) + + let epsilon: CGFloat = 0.0001 + if abs(i) < epsilon { + i = i >= 0 ? epsilon : -epsilon + } + + return CATransform3D( + m11: a / i, m12: d / i, m13: 0, m14: g / i, + m21: b / i, m22: e / i, m23: 0, m24: h / i, + m31: 0, m32: 0, m33: 1, m34: 0, + m41: c / i, m42: f / i, m43: 0, m44: 1 + ) +} diff --git a/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/DialIndicatorComponent.swift b/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/DialIndicatorComponent.swift new file mode 100644 index 00000000..b07fad8c --- /dev/null +++ b/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/DialIndicatorComponent.swift @@ -0,0 +1,295 @@ +import Foundation +import UIKit +import Display +import ComponentFlow +import SwiftSignalKit +import TelegramCore +import AccountContext +import MultilineTextComponent +import AnimatedTextComponent + +final class DialIndicatorComponent: Component { + let content: AnyComponentWithIdentity + let backgroundColor: UIColor + let foregroundColor: UIColor + let diameter: CGFloat + let contentSize: CGSize? + let lineWidth: CGFloat + let fontSize: CGFloat + let progress: CGFloat + let value: Int + let suffix: String + let isVisible: Bool + let isFlipped: Bool + + public init( + content: AnyComponentWithIdentity, + backgroundColor: UIColor, + foregroundColor: UIColor, + diameter: CGFloat, + contentSize: CGSize? = nil, + lineWidth: CGFloat, + fontSize: CGFloat, + progress: CGFloat, + value: Int, + suffix: String, + isVisible: Bool = true, + isFlipped: Bool = false + ) { + self.content = content + self.backgroundColor = backgroundColor + self.foregroundColor = foregroundColor + self.diameter = diameter + self.contentSize = contentSize + self.lineWidth = lineWidth + self.fontSize = fontSize + self.progress = progress + self.value = value + self.suffix = suffix + self.isVisible = isVisible + self.isFlipped = isFlipped + } + + public static func ==(lhs: DialIndicatorComponent, rhs: DialIndicatorComponent) -> Bool { + if lhs.content != rhs.content { + return false + } + if lhs.backgroundColor != rhs.backgroundColor { + return false + } + if lhs.foregroundColor != rhs.foregroundColor { + return false + } + if lhs.diameter != rhs.diameter { + return false + } + if lhs.contentSize != rhs.contentSize { + return false + } + if lhs.lineWidth != rhs.lineWidth { + return false + } + if lhs.fontSize != rhs.fontSize { + return false + } + if lhs.progress != rhs.progress { + return false + } + if lhs.value != rhs.value { + return false + } + if lhs.suffix != rhs.suffix { + return false + } + if lhs.isVisible != rhs.isVisible { + return false + } + if lhs.isFlipped != rhs.isFlipped { + return false + } + return true + } + + public final class View: UIView { + private let containerView = UIView() + private let backgroundLayer = SimpleShapeLayer() + private let foregroundLayer = SimpleShapeLayer() + + private var content = ComponentView() + private let label = ComponentView() + + private var component: DialIndicatorComponent? + private weak var state: EmptyComponentState? + + override init(frame: CGRect) { + super.init(frame: frame) + + self.backgroundLayer.lineCap = .round + self.foregroundLayer.lineCap = .round + + self.addSubview(self.containerView) + + self.containerView.layer.addSublayer(self.backgroundLayer) + self.containerView.layer.addSublayer(self.foregroundLayer) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func update(component: DialIndicatorComponent, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + let previousComponent = self.component + self.component = component + self.state = state + + let pathSize = CGSize(width: component.diameter, height: component.diameter) + let pathFrame = CGRect(origin: .zero, size: pathSize).insetBy(dx: component.lineWidth * 0.5, dy: component.lineWidth * 0.5) + + let strokeStart: CGFloat = 0.125 + let strokeEnd: CGFloat = 1.0 - strokeStart + + self.backgroundLayer.lineWidth = component.lineWidth + self.backgroundLayer.strokeColor = component.backgroundColor.cgColor + self.backgroundLayer.fillColor = UIColor.clear.cgColor + self.backgroundLayer.path = CGPath(ellipseIn: pathFrame, transform: nil) + self.backgroundLayer.transform = CATransform3DMakeRotation(.pi / 2.0, 0.0, 0.0, 1.0) + self.backgroundLayer.strokeStart = strokeStart + self.backgroundLayer.strokeEnd = strokeEnd + self.backgroundLayer.frame = CGRect(origin: .zero, size: pathSize) + + self.foregroundLayer.lineWidth = component.lineWidth + self.foregroundLayer.strokeColor = component.foregroundColor.cgColor + self.foregroundLayer.fillColor = UIColor.clear.cgColor + self.foregroundLayer.path = CGPath(ellipseIn: pathFrame, transform: nil) + self.foregroundLayer.transform = CATransform3DMakeRotation(.pi / 2.0, 0.0, 0.0, 1.0) + self.foregroundLayer.strokeStart = strokeStart + transition.setShapeLayerStrokeEnd(layer: self.foregroundLayer, strokeEnd: strokeStart + (strokeEnd - strokeStart) * component.progress) + self.foregroundLayer.frame = CGRect(origin: .zero, size: pathSize) + + if previousComponent?.content.id != component.content.id { + if let contentView = self.content.view { + if transition.animation.isImmediate { + contentView.removeFromSuperview() + } else { + transition.setScale(view: contentView, scale: 0.01) + transition.setAlpha(view: contentView, alpha: 0.0, completion: { _ in + contentView.removeFromSuperview() + }) + } + } + self.content = ComponentView() + } + + let contentSize = component.contentSize ?? CGSize(width: component.diameter - 16.0, height: component.diameter - 16.0) + let contentFrame = CGRect(origin: CGPoint(x: floorToScreenPixels((pathSize.width - contentSize.width) / 2.0), y: floorToScreenPixels((pathSize.height - contentSize.height) / 2.0)), size: contentSize) + let _ = self.content.update( + transition: .immediate, + component: component.content.component, + environment: {}, + containerSize: contentFrame.size + ) + if let contentView = self.content.view { + if contentView.superview == nil { + self.containerView.addSubview(contentView) + if !transition.animation.isImmediate { + transition.animateScale(view: contentView, from: 0.01, to: 1.0) + transition.animateAlpha(view: contentView, from: 0.0, to: 1.0) + } + } + contentView.frame = contentFrame + } + + var labelItems: [AnimatedTextComponent.Item] = [ + AnimatedTextComponent.Item(id: "percent", content: .number(component.value, minDigits: 1)) + ] + if !component.suffix.isEmpty { + labelItems.append(AnimatedTextComponent.Item(id: "suffix", content: .text(component.suffix))) + } + + let labelSize = self.label.update( + transition: transition, + component: AnyComponent( + AnimatedTextComponent( + font: Font.semibold(component.fontSize), + color: component.foregroundColor, + items: labelItems + ) + ), + environment: {}, + containerSize: availableSize + ) + if let labelView = self.label.view { + if labelView.superview == nil { + self.containerView.addSubview(labelView) + } + transition.setFrame(view: labelView, frame: CGRect(origin: CGPoint(x: floorToScreenPixels((pathSize.width - labelSize.width) / 2.0) + 1.0 - UIScreenPixel, y: pathSize.height - labelSize.height + 2.0 - UIScreenPixel), size: labelSize)) + } + + transition.setAlpha(view: self.containerView, alpha: component.isVisible ? 1.0 : 0.0) + transition.setBlur(layer: self.containerView.layer, radius: component.isVisible ? 0.0 : 10.0) + + self.containerView.transform = CGAffineTransform(rotationAngle: component.isFlipped ? .pi : 0.0) + + self.containerView.frame = CGRect(origin: .zero, size: pathSize) + + return pathSize + } + } + + public func makeView() -> View { + return View(frame: CGRect()) + } + + public func update(view: View, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + return view.update(component: self, availableSize: availableSize, state: state, environment: environment, transition: transition) + } +} + + +final class ColorSwatchComponent: Component { + let innerColor: UIColor + let outerColor: UIColor + + public init( + innerColor: UIColor, + outerColor: UIColor + ) { + self.innerColor = innerColor + self.outerColor = outerColor + } + + public static func ==(lhs: ColorSwatchComponent, rhs: ColorSwatchComponent) -> Bool { + if lhs.innerColor != rhs.innerColor { + return false + } + if lhs.outerColor != rhs.outerColor { + return false + } + return true + } + + public final class View: UIImageView { + private var component: ColorSwatchComponent? + private weak var state: EmptyComponentState? + + override init(frame: CGRect) { + super.init(frame: frame) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func update(component: ColorSwatchComponent, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + let previousComponent = self.component + self.component = component + self.state = state + + if previousComponent?.innerColor != component.innerColor || previousComponent?.outerColor != component.outerColor { + self.image = generateImage(availableSize, contextGenerator: { size, context in + context.clear(CGRect(origin: .zero, size: size)) + if let image = UIImage(bundleImageName: "Premium/Craft/DialColorMask"), let cgImage = image.cgImage { + context.clip(to: CGRect(origin: .zero, size: size), mask: cgImage) + } + var locations: [CGFloat] = [1.0, 0.95, 0.1, 0.0] + let colors: [CGColor] = [component.innerColor.cgColor, component.innerColor.cgColor, component.outerColor.cgColor, component.outerColor.cgColor] + + let colorSpace = CGColorSpaceCreateDeviceRGB() + let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: &locations)! + + context.drawLinearGradient(gradient, start: CGPoint(x: 0.0, y: 0.0), end: CGPoint(x: 0.0, y: size.height), options: CGGradientDrawingOptions()) + }) + } + + return availableSize + } + } + + public func makeView() -> View { + return View(frame: CGRect()) + } + + public func update(view: View, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + return view.update(component: self, availableSize: availableSize, state: state, environment: environment, transition: transition) + } +} diff --git a/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/GiftCraftScreen.swift b/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/GiftCraftScreen.swift new file mode 100644 index 00000000..18e68606 --- /dev/null +++ b/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/GiftCraftScreen.swift @@ -0,0 +1,330 @@ +import Foundation +import UIKit +import Display +import ComponentFlow +import TelegramCore +import TelegramPresentationData +import ViewControllerComponent +import SheetComponent +import BundleIconComponent +import BalancedTextComponent +import MultilineTextComponent +import ButtonComponent +import GiftItemComponent +import AccountContext +import GlassBarButtonComponent + +private func giftCraftRibbonColor(for gift: StarGift.UniqueGift) -> GiftItemComponent.Ribbon.Color { + for attribute in gift.attributes { + if case let .backdrop(_, _, innerColor, outerColor, _, _, _) = attribute { + return .custom(outerColor, innerColor) + } + } + return .blue +} + +private final class GiftCraftSheetContent: CombinedComponent { + typealias EnvironmentType = ViewControllerComponentContainer.Environment + + let context: AccountContext + let gift: StarGift.UniqueGift + let dismiss: () -> Void + + init( + context: AccountContext, + gift: StarGift.UniqueGift, + dismiss: @escaping () -> Void + ) { + self.context = context + self.gift = gift + self.dismiss = dismiss + } + + static func ==(lhs: GiftCraftSheetContent, rhs: GiftCraftSheetContent) -> Bool { + if lhs.context !== rhs.context { + return false + } + if lhs.gift != rhs.gift { + return false + } + return true + } + + static var body: Body { + let closeButton = Child(GlassBarButtonComponent.self) + let title = Child(BalancedTextComponent.self) + let text = Child(MultilineTextComponent.self) + let gift = Child(GiftItemComponent.self) + let button = Child(ButtonComponent.self) + + return { context in + let environment = context.environment[EnvironmentType.self] + let component = context.component + let theme = environment.theme + + var contentSize = CGSize(width: context.availableSize.width, height: 18.0) + + let closeButton = closeButton.update( + component: GlassBarButtonComponent( + size: CGSize(width: 40.0, height: 40.0), + backgroundColor: theme.rootController.navigationBar.glassBarButtonBackgroundColor, + isDark: theme.overallDarkAppearance, + state: .generic, + component: AnyComponentWithIdentity( + id: "close", + component: AnyComponent( + BundleIconComponent( + name: "Navigation/Close", + tintColor: theme.chat.inputPanel.panelControlColor + ) + ) + ), + action: { _ in + component.dismiss() + } + ), + availableSize: CGSize(width: 40.0, height: 40.0), + transition: context.transition + ) + context.add(closeButton.position(CGPoint(x: environment.safeInsets.left + 16.0 + closeButton.size.width / 2.0, y: 36.0))) + + let title = title.update( + component: BalancedTextComponent( + text: .plain(NSAttributedString(string: "Gift Crafting", font: Font.semibold(17.0), textColor: theme.actionSheet.primaryTextColor)), + horizontalAlignment: .center, + maximumNumberOfLines: 1, + lineSpacing: 0.1 + ), + availableSize: CGSize(width: context.availableSize.width - 96.0, height: context.availableSize.height), + transition: context.transition + ) + context.add(title.position(CGPoint(x: context.availableSize.width / 2.0, y: contentSize.height + title.size.height / 2.0))) + contentSize.height += title.size.height + 16.0 + + let giftSize = CGSize(width: 140.0, height: 140.0) + let gift = gift.update( + component: GiftItemComponent( + context: component.context, + style: .glass, + theme: theme, + strings: environment.strings, + subject: .uniqueGift(gift: component.gift, price: nil), + ribbon: GiftItemComponent.Ribbon( + text: "#\(component.gift.number)", + font: .monospaced, + color: giftCraftRibbonColor(for: component.gift) + ), + mode: .grid + ), + availableSize: giftSize, + transition: context.transition + ) + context.add(gift.position(CGPoint(x: context.availableSize.width / 2.0, y: contentSize.height + gift.size.height / 2.0))) + contentSize.height += gift.size.height + 16.0 + + let text = text.update( + component: MultilineTextComponent( + text: .plain( + NSAttributedString( + string: "This Swiftgram gift crafting flow is temporarily disabled in the merged build while the underlying APIs are being adapted.", + font: Font.regular(15.0), + textColor: theme.actionSheet.secondaryTextColor, + paragraphAlignment: .center + ) + ), + maximumNumberOfLines: 0 + ), + availableSize: CGSize(width: context.availableSize.width - 48.0, height: context.availableSize.height), + transition: context.transition + ) + context.add(text.position(CGPoint(x: context.availableSize.width / 2.0, y: contentSize.height + text.size.height / 2.0))) + contentSize.height += text.size.height + 24.0 + + let button = button.update( + component: ButtonComponent( + background: ButtonComponent.Background( + style: .glass, + color: theme.list.itemCheckColors.fillColor, + foreground: theme.list.itemCheckColors.foregroundColor, + pressedColor: theme.list.itemCheckColors.fillColor.withMultipliedAlpha(0.9) + ), + content: AnyComponentWithIdentity( + id: "ok", + component: AnyComponent( + MultilineTextComponent( + text: .plain( + NSAttributedString( + string: environment.strings.Common_OK, + font: Font.semibold(17.0), + textColor: theme.list.itemCheckColors.foregroundColor, + paragraphAlignment: .center + ) + ) + ) + ) + ), + action: { + component.dismiss() + } + ), + availableSize: CGSize(width: context.availableSize.width - 60.0, height: 52.0), + transition: context.transition + ) + context.add(button.position(CGPoint(x: context.availableSize.width / 2.0, y: contentSize.height + button.size.height / 2.0)).cornerRadius(10.0)) + contentSize.height += button.size.height + 16.0 + environment.safeInsets.bottom + + return contentSize + } + } +} + +private final class GiftCraftScreenComponent: Component { + typealias EnvironmentType = ViewControllerComponentContainer.Environment + + let context: AccountContext + let gift: StarGift.UniqueGift + + init(context: AccountContext, gift: StarGift.UniqueGift) { + self.context = context + self.gift = gift + } + + static func ==(lhs: GiftCraftScreenComponent, rhs: GiftCraftScreenComponent) -> Bool { + if lhs.context !== rhs.context { + return false + } + if lhs.gift != rhs.gift { + return false + } + return true + } + + final class View: UIView { + private let sheet = ComponentView<(ViewControllerComponentContainer.Environment, SheetComponentEnvironment)>() + private let sheetAnimateOut = ActionSlot>() + + private var component: GiftCraftScreenComponent? + private var environment: EnvironmentType? + + override init(frame: CGRect) { + super.init(frame: frame) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func update( + component: GiftCraftScreenComponent, + availableSize: CGSize, + state: EmptyComponentState, + environment: Environment, + transition: ComponentTransition + ) -> CGSize { + self.component = component + + let environment = environment[ViewControllerComponentContainer.Environment.self].value + self.environment = environment + + let sheetEnvironment = SheetComponentEnvironment( + isDisplaying: environment.isVisible, + isCentered: environment.metrics.widthClass == .regular, + hasInputHeight: !environment.inputHeight.isZero, + regularMetricsSize: CGSize(width: 430.0, height: 900.0), + dismiss: { [weak self] _ in + guard let self, let environment = self.environment else { + return + } + self.sheetAnimateOut.invoke(Action { _ in + environment.controller()?.dismiss(completion: nil) + }) + } + ) + let _ = self.sheet.update( + transition: transition, + component: AnyComponent( + SheetComponent( + content: AnyComponent( + GiftCraftSheetContent( + context: component.context, + gift: component.gift, + dismiss: { [weak self] in + guard let self, let environment = self.environment else { + return + } + self.sheetAnimateOut.invoke(Action { _ in + environment.controller()?.dismiss(completion: nil) + }) + } + ) + ), + backgroundColor: .color(environment.theme.actionSheet.opaqueItemBackgroundColor), + animateOut: self.sheetAnimateOut + ) + ), + environment: { + environment + sheetEnvironment + }, + containerSize: availableSize + ) + if let sheetView = self.sheet.view { + if sheetView.superview == nil { + self.addSubview(sheetView) + } + transition.setFrame(view: sheetView, frame: CGRect(origin: CGPoint(), size: availableSize)) + } + + return availableSize + } + } + + func makeView() -> View { + return View(frame: CGRect()) + } + + func update( + view: View, + availableSize: CGSize, + state: EmptyComponentState, + environment: Environment, + transition: ComponentTransition + ) -> CGSize { + return view.update(component: self, availableSize: availableSize, state: state, environment: environment, transition: transition) + } +} + +public final class GiftCraftScreen: ViewControllerComponentContainer { + fileprivate weak var profileGiftsContext: ProfileGiftsContext? + + public init( + context: AccountContext, + gift: StarGift.UniqueGift, + profileGiftsContext: ProfileGiftsContext? + ) { + self.profileGiftsContext = profileGiftsContext + + super.init( + context: context, + component: GiftCraftScreenComponent(context: context, gift: gift), + navigationBarAppearance: .none, + statusBarStyle: .ignore, + presentationMode: .modal, + theme: .default + ) + + self.navigationPresentation = .flatModal + } + + required public init(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + public func dismissAnimated() { + if let view = self.node.hostView.findTaggedView(tag: SheetComponent.View.Tag()) as? SheetComponent.View { + view.dismissAnimated() + } else { + self.dismiss(completion: nil) + } + } +} diff --git a/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/SelectCraftGiftScreen.swift b/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/SelectCraftGiftScreen.swift new file mode 100644 index 00000000..456486ac --- /dev/null +++ b/submodules/TelegramUI/Components/Gifts/GiftCraftScreen/Sources/SelectCraftGiftScreen.swift @@ -0,0 +1,714 @@ +import Foundation +import UIKit +import Display +import ComponentFlow +import SwiftSignalKit +import TelegramCore +import TelegramPresentationData +import TelegramStringFormatting +import ViewControllerComponent +import BundleIconComponent +import MultilineTextComponent +import GiftItemComponent +import AccountContext +import AnimatedTextComponent +import Markdown +import PresentationDataUtils +import GiftViewScreen +import NavigationStackComponent +import GiftStoreScreen +import ResizableSheetComponent +import TooltipUI +import GlassBarButtonComponent +import ConfettiEffect +import GiftLoadingShimmerView + +final class SelectGiftPageContent: Component { + typealias EnvironmentType = ViewControllerComponentContainer.Environment + + let context: AccountContext + let craftContext: CraftGiftsContext + let resaleContext: ResaleGiftsContext + let gift: StarGift.UniqueGift + let genericGift: StarGift.Gift + let selectedGiftIds: Set + let starsTopUpOptions: Signal<[StarsTopUpOption]?, NoError> + let selectGift: (GiftItem) -> Void + let dismiss: () -> Void + let boundsUpdated: ActionSlot + + init( + context: AccountContext, + craftContext: CraftGiftsContext, + resaleContext: ResaleGiftsContext, + gift: StarGift.UniqueGift, + genericGift: StarGift.Gift, + selectedGiftIds: Set, + starsTopUpOptions: Signal<[StarsTopUpOption]?, NoError>, + selectGift: @escaping (GiftItem) -> Void, + dismiss: @escaping () -> Void, + boundsUpdated: ActionSlot + ) { + self.context = context + self.craftContext = craftContext + self.resaleContext = resaleContext + self.gift = gift + self.genericGift = genericGift + self.selectedGiftIds = selectedGiftIds + self.starsTopUpOptions = starsTopUpOptions + self.selectGift = selectGift + self.dismiss = dismiss + self.boundsUpdated = boundsUpdated + } + + static func ==(lhs: SelectGiftPageContent, rhs: SelectGiftPageContent) -> Bool { + if lhs.context !== rhs.context { + return false + } + if lhs.gift != rhs.gift { + return false + } + if lhs.selectedGiftIds != rhs.selectedGiftIds { + return false + } + return true + } + + final class View: UIView, UIScrollViewDelegate { + private let myGiftsTitle = ComponentView() + private var gifts: [AnyHashable: ComponentView] = [:] + private let myGiftsPlaceholder = ComponentView() + private let loadingView = GiftLoadingShimmerView() + + private let storeGiftsTitle = ComponentView() + private let storeGifts = ComponentView() + + private var craftState: CraftGiftsContext.State? + private var craftStateDisposable: Disposable? + + private var availableGifts: [GiftItem] = [] + private var giftMap: [Int64: ProfileGiftsContext.State.StarGift] = [:] + + private var availableSize: CGSize? + private var currentBounds: CGRect? + + private var component: SelectGiftPageContent? + private weak var state: EmptyComponentState? + private var environment: ViewControllerComponentContainer.Environment? + private var isUpdating: Bool = false + + override init(frame: CGRect) { + super.init(frame: frame) + + self.layer.cornerRadius = 40.0 + self.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] + + self.addSubview(self.loadingView) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + deinit { + self.craftStateDisposable?.dispose() + } + + func updateScrolling(interactive: Bool, transition: ComponentTransition) -> CGFloat { + guard let bounds = self.currentBounds, let availableSize = self.availableSize, let component = self.component, let environment = self.environment else { + return 0.0 + } + + let visibleBounds = bounds.insetBy(dx: 0.0, dy: -10.0) + + var contentHeight: CGFloat = 88.0 + 32.0 + + let itemSpacing: CGFloat = 10.0 + let itemSideInset = 16.0 + let itemsInRow: Int + if availableSize.width > availableSize.height || availableSize.width > 480.0 { + if case .tablet = environment.deviceMetrics.type { + itemsInRow = 4 + } else { + itemsInRow = 5 + } + } else { + itemsInRow = 3 + } + let itemWidth = (availableSize.width - itemSideInset * 2.0 - itemSpacing * CGFloat(itemsInRow - 1)) / CGFloat(itemsInRow) + let itemSize = CGSize(width: itemWidth, height: itemWidth) + + var isLoading = false + if self.availableGifts.isEmpty, case .loading = (self.craftState?.dataState ?? .loading) { + isLoading = true + } + let loadingTransition: ComponentTransition = .easeInOut(duration: 0.25) + let loadingSize = CGSize(width: availableSize.width, height: 180.0) + if isLoading { + contentHeight += 120.0 + self.loadingView.update(size: loadingSize, theme: environment.theme, itemSize: itemSize, showFilters: false, isPlain: true, transition: .immediate) + loadingTransition.setAlpha(view: self.loadingView, alpha: 1.0) + } else { + loadingTransition.setAlpha(view: self.loadingView, alpha: 0.0) + } + transition.setFrame(view: self.loadingView, frame: CGRect(origin: CGPoint(x: 0.0, y: contentHeight - 170.0), size: loadingSize)) + + var itemFrame = CGRect(origin: CGPoint(x: itemSideInset, y: contentHeight), size: itemSize) + var itemsHeight: CGFloat = 0.0 + var validIds: [AnyHashable] = [] + for gift in self.availableGifts { + var isVisible = false + if visibleBounds.intersects(itemFrame) { + isVisible = true + } + if isVisible { + let itemId = AnyHashable(gift.gift.id) + validIds.append(itemId) + + var itemTransition = transition + let visibleItem: ComponentView + if let current = self.gifts[itemId] { + visibleItem = current + } else { + visibleItem = ComponentView() + self.gifts[itemId] = visibleItem + itemTransition = .immediate + } + + var ribbonColor: GiftItemComponent.Ribbon.Color = .blue + let ribbonText = "#\(gift.gift.number)" + for attribute in gift.gift.attributes { + if case let .backdrop(_, _, innerColor, outerColor, _, _, _) = attribute { + ribbonColor = .custom(outerColor, innerColor) + break + } + } + + let _ = visibleItem.update( + transition: itemTransition, + component: AnyComponent( + GiftItemComponent( + context: component.context, + style: .glass, + theme: environment.theme, + strings: environment.strings, + peer: nil, + subject: .uniqueGift(gift: gift.gift, price: nil), + ribbon: GiftItemComponent.Ribbon(text: ribbonText, font: .monospaced, color: ribbonColor, outline: nil), + badge: gift.gift.craftChancePermille.flatMap { "+\($0 / 10)%" }, + resellPrice: nil, + isHidden: false, + isSelected: false, + isPinned: false, + isEditing: false, + mode: .grid, + action: { [weak self] in + guard let self, let component = self.component, let environment = self.environment else { + return + } + HapticFeedback().impact(.light) + + let currentTime = Int32(CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970) + if let profileGift = self.giftMap[gift.gift.id], let canCraftDate = profileGift.canCraftAt, currentTime < canCraftDate { + let dateString = stringForFullDate(timestamp: canCraftDate, strings: environment.strings, dateTimeFormat: environment.dateTimeFormat) + let alertController = textAlertController( + context: component.context, + title: environment.strings.Gift_Craft_Unavailable_Title, + text: environment.strings.Gift_Craft_Unavailable_Text(dateString).string, + actions: [ + TextAlertAction(type: .defaultAction, title: environment.strings.Common_OK, action: {}) + ], + parseMarkdown: true + ) + environment.controller()?.present(alertController, in: .window(.root)) + return + } + + component.selectGift(gift) + component.dismiss() + }, + contextAction: { _, _ in } + ) + ), + environment: {}, + containerSize: itemSize + ) + if let itemView = visibleItem.view { + if itemView.superview == nil { + if let _ = self.loadingView.superview { + self.insertSubview(itemView, belowSubview: self.loadingView) + } else { + self.addSubview(itemView) + } + if !transition.animation.isImmediate { + itemView.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.25) + } + } + itemTransition.setFrame(view: itemView, frame: itemFrame) + } + } + + itemsHeight = itemFrame.maxY - contentHeight + + itemFrame.origin.x += itemFrame.width + itemSpacing + if itemFrame.maxX > availableSize.width { + itemFrame.origin.x = itemSideInset + itemFrame.origin.y += itemSize.height + itemSpacing + } + } + + var removeIds: [AnyHashable] = [] + for (id, item) in self.gifts { + if !validIds.contains(id) { + removeIds.append(id) + if let itemView = item.view { + if !transition.animation.isImmediate { + itemView.layer.animateScale(from: 1.0, to: 0.01, duration: 0.25, removeOnCompletion: false) + itemView.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.25, removeOnCompletion: false, completion: { _ in + itemView.removeFromSuperview() + }) + } else { + itemView.removeFromSuperview() + } + } + } + } + for id in removeIds { + self.gifts.removeValue(forKey: id) + } + + if let state = self.craftState, case .ready = state.dataState, self.availableGifts.isEmpty { + contentHeight += 10.0 + let myGiftsPlaceholderSize = self.myGiftsPlaceholder.update( + transition: .immediate, + component: AnyComponent( + MultilineTextComponent( + text: .plain(NSAttributedString(string: environment.strings.Gift_Craft_Select_NoGiftsFromCollection, font: Font.regular(13.0), textColor: environment.theme.list.itemSecondaryTextColor)), + horizontalAlignment: .center, + maximumNumberOfLines: 3, + lineSpacing: 0.1 + ) + ), + environment: {}, + containerSize: CGSize(width: availableSize.width - 32.0, height: .greatestFiniteMagnitude) + ) + let myGiftsPlaceholderFrame = CGRect(origin: CGPoint(x: floor((availableSize.width - myGiftsPlaceholderSize.width) / 2.0), y: contentHeight), size: myGiftsPlaceholderSize) + if let myGiftsPlaceholderView = self.myGiftsPlaceholder.view { + if myGiftsPlaceholderView.superview == nil { + self.addSubview(myGiftsPlaceholderView) + } + myGiftsPlaceholderView.frame = myGiftsPlaceholderFrame + } + contentHeight += myGiftsPlaceholderSize.height + contentHeight += 32.0 + } else { + contentHeight += itemsHeight + contentHeight += 24.0 + } + + if let storeGiftsView = self.storeGifts.view as? GiftStoreContentComponent.View { + storeGiftsView.updateScrolling(bounds: bounds.offsetBy(dx: 0.0, dy: -contentHeight), interactive: interactive, transition: .immediate) + } + + let bottomContentOffset = max(0.0, contentHeight - bounds.origin.y - bounds.height) + if interactive, bottomContentOffset < 800.0 { + Queue.mainQueue().justDispatch { + component.craftContext.loadMore() + } + } + + return contentHeight + } + + func update(component: SelectGiftPageContent, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + self.isUpdating = true + defer { + self.isUpdating = false + } + + self.availableSize = availableSize + if self.component == nil { + self.currentBounds = CGRect(origin: .zero, size: availableSize) + + component.boundsUpdated.connect { [weak self] update in + guard let self else { + return + } + self.currentBounds = update.bounds + let _ = self.updateScrolling(interactive: update.isInteractive, transition: .immediate) + } + + let initialGiftItem = GiftItem( + gift: component.gift, + reference: .slug(slug: component.gift.slug) + ) + self.availableGifts = [ + initialGiftItem + ] + + self.craftStateDisposable = (component.craftContext.state + |> deliverOnMainQueue).start(next: { [weak self] state in + guard let self else { + return + } + self.craftState = state + + var items: [GiftItem] = [] + var giftMap: [Int64: ProfileGiftsContext.State.StarGift] = [:] + var existingIds = Set() + for gift in state.gifts { + guard let reference = gift.reference, case let .unique(uniqueGift) = gift.gift, !existingIds.contains(uniqueGift.id) else { + continue + } + existingIds.insert(uniqueGift.id) + + let giftItem = GiftItem( + gift: uniqueGift, + reference: reference + ) + giftMap[uniqueGift.id] = gift + + if component.selectedGiftIds.contains(uniqueGift.id) { + continue + } + items.append(giftItem) + } + + self.availableGifts = items + self.giftMap = giftMap + + if !self.isUpdating { + self.state?.updated(transition: .spring(duration: 0.4)) + } + }) + } + + let environment = environment[ViewControllerComponentContainer.Environment.self].value + + let sideInset: CGFloat = 16.0 + environment.safeInsets.left + + self.component = component + self.state = state + self.environment = environment + + self.backgroundColor = environment.theme.actionSheet.opaqueItemBackgroundColor + + var contentHeight: CGFloat = 88.0 + + let myGiftsTitleSize = self.myGiftsTitle.update( + transition: transition, + component: AnyComponent( + MultilineTextComponent(text: .plain(NSAttributedString(string: environment.strings.Gift_Craft_Select_YourGifts.uppercased(), font: Font.semibold(14.0), textColor: environment.theme.actionSheet.secondaryTextColor))) + ), + environment: {}, + containerSize: CGSize(width: availableSize.width - sideInset * 2.0, height: 100.0) + ) + let myGiftsTitleFrame = CGRect(origin: CGPoint(x: 26.0, y: contentHeight), size: myGiftsTitleSize) + if let myGiftsTitleView = self.myGiftsTitle.view { + if myGiftsTitleView.superview == nil { + self.addSubview(myGiftsTitleView) + } + transition.setFrame(view: myGiftsTitleView, frame: myGiftsTitleFrame) + } + + contentHeight += 32.0 + + contentHeight = self.updateScrolling(interactive: false, transition: transition) + + let resaleCount = component.genericGift.availability?.resale ?? 0 + let saleTitle = environment.strings.Gift_Craft_Select_SaleGiftsCount(Int32(clamping: resaleCount)).uppercased() + + let storeGiftsTitleSize = self.storeGiftsTitle.update( + transition: transition, + component: AnyComponent( + MultilineTextComponent(text: .plain(NSAttributedString(string: saleTitle, font: Font.semibold(14.0), textColor: environment.theme.actionSheet.secondaryTextColor))) + ), + environment: {}, + containerSize: CGSize(width: availableSize.width - sideInset * 2.0, height: 100.0) + ) + let storeGiftsTitleFrame = CGRect(origin: CGPoint(x: 26.0, y: contentHeight), size: storeGiftsTitleSize) + if let storeGiftsTitleView = self.storeGiftsTitle.view { + if storeGiftsTitleView.superview == nil { + self.addSubview(storeGiftsTitleView) + } + transition.setFrame(view: storeGiftsTitleView, frame: storeGiftsTitleFrame) + } + contentHeight += 28.0 + + self.storeGifts.parentState = state + let storeGiftsSize = self.storeGifts.update( + transition: transition, + component: AnyComponent( + GiftStoreContentComponent( + context: component.context, + resaleGiftsContext: component.resaleContext, + theme: environment.theme, + strings: environment.strings, + dateTimeFormat: environment.dateTimeFormat, + safeInsets: UIEdgeInsets(), + statusBarHeight: contentHeight - 62.0, + navigationHeight: 0.0, + overNavigationContainer: self, + starsContext: component.context.starsContext!, + peerId: component.context.account.peerId, + gift: component.genericGift, + isPlain: true, + confirmPurchaseImmediately: true, + starsTopUpOptions: component.starsTopUpOptions, + scrollToTop: {}, + controller: environment.controller, + completion: { [weak self] uniqueGift in + guard let self, let component = self.component, let controller = self.environment?.controller() as? SelectCraftGiftScreen, let navigationController = controller.navigationController else { + return + } + let giftItem = GiftItem(gift: uniqueGift, reference: .slug(slug: uniqueGift.slug)) + component.selectGift(giftItem) + component.dismiss() + + navigationController.view.addSubview(ConfettiView(frame: navigationController.view.bounds)) + + Queue.mainQueue().after(1.0) { + component.craftContext.reload() + } + } + ) + ), + environment: {}, + containerSize: CGSize(width: availableSize.width, height: .greatestFiniteMagnitude) + ) + let storeGiftsFrame = CGRect(origin: CGPoint(x: 0.0, y: contentHeight), size: storeGiftsSize) + if let storeGiftsView = self.storeGifts.view as? GiftStoreContentComponent.View { + if storeGiftsView.superview == nil { + self.insertSubview(storeGiftsView, at: 0) + } + transition.setFrame(view: storeGiftsView, frame: storeGiftsFrame) + + storeGiftsView.updateScrolling(bounds: CGRect(origin: .zero, size: availableSize), transition: .immediate) + } + contentHeight += storeGiftsSize.height + contentHeight += 90.0 + + return CGSize(width: availableSize.width, height: contentHeight) + } + } + + func makeView() -> View { + return View(frame: CGRect()) + } + + func update(view: View, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + return view.update(component: self, availableSize: availableSize, state: state, environment: environment, transition: transition) + } +} + +private final class SheetContainerComponent: CombinedComponent { + typealias EnvironmentType = ViewControllerComponentContainer.Environment + + let context: AccountContext + let craftContext: CraftGiftsContext + let resaleContext: ResaleGiftsContext + let gift: StarGift.UniqueGift + let genericGift: StarGift.Gift + let selectedGiftIds: Set + let starsTopUpOptions: Signal<[StarsTopUpOption]?, NoError> + let selectGift: (GiftItem) -> Void + + init( + context: AccountContext, + craftContext: CraftGiftsContext, + resaleContext: ResaleGiftsContext, + gift: StarGift.UniqueGift, + genericGift: StarGift.Gift, + selectedGiftIds: Set, + starsTopUpOptions: Signal<[StarsTopUpOption]?, NoError>, + selectGift: @escaping (GiftItem) -> Void + ) { + self.context = context + self.craftContext = craftContext + self.resaleContext = resaleContext + self.gift = gift + self.genericGift = genericGift + self.selectedGiftIds = selectedGiftIds + self.starsTopUpOptions = starsTopUpOptions + self.selectGift = selectGift + } + + static func ==(lhs: SheetContainerComponent, rhs: SheetContainerComponent) -> Bool { + if lhs.context !== rhs.context { + return false + } + if lhs.gift != rhs.gift { + return false + } + return true + } + + final class State: ComponentState { + } + + func makeState() -> State { + return State() + } + + static var body: Body { + let sheet = Child(ResizableSheetComponent.self) + let animateOut = StoredActionSlot(Action.self) + + let boundsUpdated = ActionSlot() + + return { context in + let component = context.component + let environment = context.environment[EnvironmentType.self] + + let controller = environment.controller + + let dismiss: (Bool) -> Void = { animated in + if animated { + animateOut.invoke(Action { _ in + if let controller = controller() { + controller.dismiss(completion: nil) + } + }) + } else { + if let controller = controller() { + controller.dismiss(completion: nil) + } + } + } + + let theme = environment.theme + + let backgroundColor = environment.theme.list.modalPlainBackgroundColor + + let sheet = sheet.update( + component: ResizableSheetComponent( + content: AnyComponent( + SelectGiftPageContent( + context: component.context, + craftContext: component.craftContext, + resaleContext: component.resaleContext, + gift: component.gift, + genericGift: component.genericGift, + selectedGiftIds: component.selectedGiftIds, + starsTopUpOptions: component.starsTopUpOptions, + selectGift: component.selectGift, + dismiss: { + dismiss(true) + }, + boundsUpdated: boundsUpdated + ) + ), + titleItem: AnyComponent( + MultilineTextComponent(text: .plain(NSAttributedString(string: environment.strings.Gift_Craft_Select_Title, font: Font.semibold(17.0), textColor: environment.theme.actionSheet.primaryTextColor))) + ), + leftItem: AnyComponent( + GlassBarButtonComponent( + size: CGSize(width: 44.0, height: 44.0), + backgroundColor: nil, + isDark: theme.overallDarkAppearance, + state: .glass, + component: AnyComponentWithIdentity(id: "close", component: AnyComponent( + BundleIconComponent( + name: "Navigation/Close", + tintColor: theme.chat.inputPanel.panelControlColor + ) + )), + action: { _ in + dismiss(true) + } + ) + ), + rightItem: nil, + bottomItem: nil, + backgroundColor: .color(backgroundColor), + isFullscreen: false, + animateOut: animateOut + ), + environment: { + environment + ResizableSheetComponentEnvironment( + theme: theme, + statusBarHeight: environment.statusBarHeight, + safeInsets: environment.safeInsets, + metrics: environment.metrics, + deviceMetrics: environment.deviceMetrics, + isDisplaying: environment.value.isVisible, + isCentered: environment.metrics.widthClass == .regular, + screenSize: context.availableSize, + regularMetricsSize: CGSize(width: 430.0, height: 900.0), + dismiss: { animated in + dismiss(animated) + }, + boundsUpdated: boundsUpdated + ) + }, + availableSize: context.availableSize, + transition: context.transition + ) + + context.add(sheet + .position(CGPoint(x: context.availableSize.width / 2.0, y: context.availableSize.height / 2.0)) + ) + + return context.availableSize + } + } +} + +final class SelectCraftGiftScreen: ViewControllerComponentContainer { + public init( + context: AccountContext, + craftContext: CraftGiftsContext, + resaleContext: ResaleGiftsContext, + gift: StarGift.UniqueGift, + genericGift: StarGift.Gift, + selectedGiftIds: Set, + starsTopUpOptions: Signal<[StarsTopUpOption]?, NoError>, + selectGift: @escaping (GiftItem) -> Void + ) { + super.init( + context: context, + component: SheetContainerComponent( + context: context, + craftContext: craftContext, + resaleContext: resaleContext, + gift: gift, + genericGift: genericGift, + selectedGiftIds: selectedGiftIds, + starsTopUpOptions: starsTopUpOptions, + selectGift: selectGift + ), + navigationBarAppearance: .none, + statusBarStyle: .ignore, + theme: .default + ) + + self.navigationPresentation = .flatModal + } + + required public init(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + fileprivate func dismissAllTooltips() { + self.window?.forEachController({ controller in + if let controller = controller as? TooltipScreen { + controller.dismiss(inPlace: false) + } + }) + self.forEachController({ controller in + if let controller = controller as? TooltipScreen { + controller.dismiss(inPlace: false) + } + return true + }) + } + + public func dismissAnimated() { + self.dismissAllTooltips() + + if let view = self.node.hostView.findTaggedView(tag: ResizableSheetComponent.View.Tag()) as? ResizableSheetComponent.View { + view.dismissAnimated() + } + } +} diff --git a/submodules/TelegramUI/Components/Gifts/GiftItemComponent/Sources/GiftItemComponent.swift b/submodules/TelegramUI/Components/Gifts/GiftItemComponent/Sources/GiftItemComponent.swift index 94cb8836..88a75470 100644 --- a/submodules/TelegramUI/Components/Gifts/GiftItemComponent/Sources/GiftItemComponent.swift +++ b/submodules/TelegramUI/Components/Gifts/GiftItemComponent/Sources/GiftItemComponent.swift @@ -515,7 +515,7 @@ public final class GiftItemComponent: Component { animationOffset = 16.0 for attribute in gift.attributes { switch attribute { - case let .model(_, file, _): + case let .model(_, file, _, _): animationFile = file if !self.fetchedFiles.contains(file.fileId.id) { self.disposables.add(freeMediaFileResourceInteractiveFetched(account: component.context.account, userLocation: .other, fileReference: .standalone(media: file), resource: file.resource).start()) @@ -606,7 +606,7 @@ public final class GiftItemComponent: Component { } for attribute in attributes { switch attribute { - case let .model(_, file, _): + case let .model(_, file, _, _): animationFile = file if !self.fetchedFiles.contains(file.fileId.id) { self.disposables.add(freeMediaFileResourceInteractiveFetched(account: component.context.account, userLocation: .other, fileReference: .standalone(media: file), resource: file.resource).start()) diff --git a/submodules/TelegramUI/Components/Gifts/GiftSetupScreen/Sources/GiftSetupScreen.swift b/submodules/TelegramUI/Components/Gifts/GiftSetupScreen/Sources/GiftSetupScreen.swift index dc774f1c..a095f544 100644 --- a/submodules/TelegramUI/Components/Gifts/GiftSetupScreen/Sources/GiftSetupScreen.swift +++ b/submodules/TelegramUI/Components/Gifts/GiftSetupScreen/Sources/GiftSetupScreen.swift @@ -755,6 +755,7 @@ private final class GiftSetupScreenComponent: Component { let presentationInterfaceState = ChatPresentationInterfaceState( chatWallpaper: .builtin(WallpaperSettings()), theme: presentationData.theme, + preferredGlassType: .default, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameDisplayOrder: presentationData.nameDisplayOrder, @@ -1604,7 +1605,7 @@ private final class GiftSetupScreenComponent: Component { guard let self, let component = self.component, let controller = self.environment?.controller(), let upgradePreview else { return } - let previewController = component.context.sharedContext.makeGiftUpgradePreviewScreen(context: component.context, attributes: upgradePreview.attributes, peerName: peerName) + let previewController = component.context.sharedContext.makeGiftUpgradePreviewScreen(context: component.context, gift: gift, attributes: upgradePreview.attributes, peerName: peerName) controller.push(previewController) }) } diff --git a/submodules/TelegramUI/Components/Gifts/GiftStoreScreen/Sources/GiftAttributeListContextItem.swift b/submodules/TelegramUI/Components/Gifts/GiftStoreScreen/Sources/GiftAttributeListContextItem.swift index da821644..174049ff 100644 --- a/submodules/TelegramUI/Components/Gifts/GiftStoreScreen/Sources/GiftAttributeListContextItem.swift +++ b/submodules/TelegramUI/Components/Gifts/GiftStoreScreen/Sources/GiftAttributeListContextItem.swift @@ -50,7 +50,7 @@ private func actionForAttribute(attribute: StarGift.UniqueGift.Attribute, presen let searchComponents = searchQuery.lowercased().components(separatedBy: .whitespaces).filter { !$0.isEmpty } switch attribute { - case let .model(name, file, _), let .pattern(name, file, _): + case let .model(name, file, _, _), let .pattern(name, file, _): let attributeId: ResaleGiftsContext.Attribute if case .model = attribute { attributeId = .model(file.fileId.id) @@ -320,7 +320,7 @@ private final class GiftAttributeListContextItemNode: ASDisplayNode, ContextMenu private func getAttributeId(from attribute: StarGift.UniqueGift.Attribute) -> AnyHashable { switch attribute { - case let .model(_, file, _): + case let .model(_, file, _, _): return AnyHashable("model_\(file.fileId.id)") case let .pattern(_, file, _): return AnyHashable("pattern_\(file.fileId.id)") @@ -582,7 +582,7 @@ private func filteredAttributes(attributes: [StarGift.UniqueGift.Attribute], que for attribute in attributes { let string: String switch attribute { - case let .model(name, _, _): + case let .model(name, _, _, _): string = name case let .pattern(name, _, _): string = name diff --git a/submodules/TelegramUI/Components/Gifts/GiftStoreScreen/Sources/GiftStoreScreen.swift b/submodules/TelegramUI/Components/Gifts/GiftStoreScreen/Sources/GiftStoreScreen.swift index 313b5508..c5251e21 100644 --- a/submodules/TelegramUI/Components/Gifts/GiftStoreScreen/Sources/GiftStoreScreen.swift +++ b/submodules/TelegramUI/Components/Gifts/GiftStoreScreen/Sources/GiftStoreScreen.swift @@ -537,8 +537,8 @@ final class GiftStoreScreenComponent: Component { } else { return false } - }.sorted(by: { lhs, rhs in - if case let .model(_, lhsFile, _) = lhs, case let .model(_, rhsFile, _) = rhs, let lhsCount = self.state?.starGiftsState?.attributeCount[.model(lhsFile.fileId.id)], let rhsCount = self.state?.starGiftsState?.attributeCount[.model(rhsFile.fileId.id)] { + }.sorted(by: { (lhs: StarGift.UniqueGift.Attribute, rhs: StarGift.UniqueGift.Attribute) in + if case let .model(_, lhsFile, _, _) = lhs, case let .model(_, rhsFile, _, _) = rhs, let lhsCount = self.state?.starGiftsState?.attributeCount[.model(lhsFile.fileId.id)], let rhsCount = self.state?.starGiftsState?.attributeCount[.model(rhsFile.fileId.id)] { return lhsCount > rhsCount } else { return false @@ -1231,7 +1231,7 @@ final class GiftStoreScreenComponent: Component { self.context = context self.peerId = peerId self.gift = gift - self.starGiftsContext = ResaleGiftsContext(account: context.account, giftId: gift.id) + self.starGiftsContext = ResaleGiftsContext(account: context.account, giftId: gift.id, forCrafting: false) super.init() diff --git a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftAuctionViewScreen.swift b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftAuctionViewScreen.swift index 9f6a5f72..c4098412 100644 --- a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftAuctionViewScreen.swift +++ b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftAuctionViewScreen.swift @@ -164,7 +164,7 @@ private final class GiftAuctionViewSheetContent: CombinedComponent { }).shuffled().prefix(5)) self.previewSymbols = randomSymbols - for case let .model(_, file, _) in self.previewModels where !self.fetchedFiles.contains(file.fileId.id) { + for case let .model(_, file, _, _) in self.previewModels where !self.fetchedFiles.contains(file.fileId.id) { self.disposables.add(freeMediaFileResourceInteractiveFetched(account: context.account, userLocation: .other, fileReference: .standalone(media: file), resource: file.resource).start()) self.fetchedFiles.insert(file.fileId.id) } @@ -725,9 +725,9 @@ private final class GiftAuctionViewSheetContent: CombinedComponent { if let genericGift { var attributes: [StarGift.UniqueGift.Attribute] = [] if state.previewModelIndex == -1 { - attributes.append(.model(name: "", file: genericGift.file, rarity: 0)) + attributes.append(.model(name: "", file: genericGift.file, rarity: .permille(0), crafted: false)) if let background = genericGift.background { - attributes.append(.backdrop(name: "", id: 0, innerColor: background.centerColor, outerColor: background.edgeColor, patternColor: 0, textColor: 0, rarity: 0)) + attributes.append(.backdrop(name: "", id: 0, innerColor: background.centerColor, outerColor: background.edgeColor, patternColor: 0, textColor: 0, rarity: .permille(0))) } } else if !state.previewModels.isEmpty { attributes.append(state.previewModels[state.previewModelIndex]) @@ -1082,7 +1082,7 @@ private final class GiftAuctionViewSheetContent: CombinedComponent { guard let state, let attributes = state.giftUpgradeAttributes else { return } - let variantsController = component.context.sharedContext.makeGiftUpgradeVariantsScreen(context: component.context, gift: .generic(gift), attributes: attributes, selectedAttributes: nil, focusedAttribute: nil) + let variantsController = component.context.sharedContext.makeGiftUpgradeVariantsScreen(context: component.context, gift: .generic(gift), crafted: false, attributes: attributes, selectedAttributes: nil, focusedAttribute: nil) environment.controller()?.push(variantsController) }, animateScale: false), availableSize: CGSize(width: context.availableSize.width - 64.0, height: context.availableSize.height), diff --git a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftOfferAlertController.swift b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftOfferAlertController.swift index ee3580ce..8e27c2e2 100644 --- a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftOfferAlertController.swift +++ b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftOfferAlertController.swift @@ -83,23 +83,23 @@ public func giftOfferAlertController( let tag: AnyObject? switch attribute { - case let .model(name, _, rarity): + case let .model(name, _, rarity, _): id = "model" title = strings.Gift_Unique_Model value = NSAttributedString(string: name, font: tableFont, textColor: tableTextColor) - percentage = Float(rarity) * 0.1 + percentage = Float(rarity.permilleValue) * 0.1 tag = modelButtonTag case let .backdrop(name, _, _, _, _, _, rarity): id = "backdrop" title = strings.Gift_Unique_Backdrop value = NSAttributedString(string: name, font: tableFont, textColor: tableTextColor) - percentage = Float(rarity) * 0.1 + percentage = Float(rarity.permilleValue) * 0.1 tag = backdropButtonTag case let .pattern(name, _, rarity): id = "pattern" title = strings.Gift_Unique_Symbol value = NSAttributedString(string: name, font: tableFont, textColor: tableTextColor) - percentage = Float(rarity) * 0.1 + percentage = Float(rarity.permilleValue) * 0.1 tag = symbolButtonTag case .originalInfo: continue diff --git a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftTransferAlertController.swift b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftTransferAlertController.swift index 511e008a..fb0aa890 100644 --- a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftTransferAlertController.swift +++ b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftTransferAlertController.swift @@ -68,23 +68,23 @@ public func giftTransferAlertController( let tag: AnyObject? switch attribute { - case let .model(name, _, rarity): + case let .model(name, _, rarity, _): id = "model" title = strings.Gift_Unique_Model value = NSAttributedString(string: name, font: tableFont, textColor: tableTextColor) - percentage = Float(rarity) * 0.1 + percentage = Float(rarity.permilleValue) * 0.1 tag = modelButtonTag case let .backdrop(name, _, _, _, _, _, rarity): id = "backdrop" title = strings.Gift_Unique_Backdrop value = NSAttributedString(string: name, font: tableFont, textColor: tableTextColor) - percentage = Float(rarity) * 0.1 + percentage = Float(rarity.permilleValue) * 0.1 tag = backdropButtonTag case let .pattern(name, _, rarity): id = "pattern" title = strings.Gift_Unique_Symbol value = NSAttributedString(string: name, font: tableFont, textColor: tableTextColor) - percentage = Float(rarity) * 0.1 + percentage = Float(rarity.permilleValue) * 0.1 tag = symbolButtonTag case .originalInfo: continue diff --git a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftUpgradePreviewScreen.swift b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftUpgradePreviewScreen.swift index 9665708a..e166fe36 100644 --- a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftUpgradePreviewScreen.swift +++ b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftUpgradePreviewScreen.swift @@ -419,11 +419,11 @@ private final class GiftUpgradePreviewScreenComponent: Component { var isSelected = false for attribute in attributeList { switch attribute { - case let .model(name, file, rarityValue): + case let .model(name, file, rarityValue, _): itemId += "\(file.fileId.id)" if self.selectedSection == .models { title = name - rarity = rarityValue + rarity = rarityValue.permilleValue modelAttribute = attribute isSelected = self.selectedModel == attribute @@ -432,7 +432,7 @@ private final class GiftUpgradePreviewScreenComponent: Component { itemId += "\(id)" if self.selectedSection == .backdrops { title = name - rarity = rarityValue + rarity = rarityValue.permilleValue backdropAttribute = attribute isSelected = self.selectedBackdrop == attribute @@ -441,7 +441,7 @@ private final class GiftUpgradePreviewScreenComponent: Component { itemId += "\(file.fileId.id)" if self.selectedSection == .symbols { title = name - rarity = rarityValue + rarity = rarityValue.permilleValue symbolAttribute = attribute isSelected = self.selectedSymbol == attribute @@ -1210,18 +1210,18 @@ private final class AttributeInfoComponent: Component { let subtitle: String let rarity: Int32 switch component.attribute { - case let .model(name, _, rarityValue): + case let .model(name, _, rarityValue, _): title = name subtitle = component.strings.Gift_Variants_Model - rarity = rarityValue + rarity = rarityValue.permilleValue case let .backdrop(name, _, _, _, _, _, rarityValue): title = name subtitle = component.strings.Gift_Variants_Backdrop - rarity = rarityValue + rarity = rarityValue.permilleValue case let .pattern(name, _, rarityValue): title = name subtitle = component.strings.Gift_Variants_Symbol - rarity = rarityValue + rarity = rarityValue.permilleValue default: title = "" subtitle = "" diff --git a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftUpgradeVariantsScreen.swift b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftUpgradeVariantsScreen.swift index b0d45858..64a999c9 100644 --- a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftUpgradeVariantsScreen.swift +++ b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftUpgradeVariantsScreen.swift @@ -425,14 +425,14 @@ private final class GiftUpgradeVariantsScreenComponent: Component { var isSelected = false for attribute in attributeList { switch attribute { - case let .model(name, file, rarityValue): + case let .model(name, file, rarityValue, _): itemId += "\(file.fileId.id)" if self.selectedSection == .models { title = name - rarity = rarityValue + rarity = rarityValue.permilleValue modelAttribute = attribute - if case let .model(_, selectedFile, _) = self.selectedModel { + if case let .model(_, selectedFile, _, _) = self.selectedModel { isSelected = file.fileId == selectedFile.fileId } else { isSelected = false @@ -442,7 +442,7 @@ private final class GiftUpgradeVariantsScreenComponent: Component { itemId += "\(id)" if self.selectedSection == .backdrops { title = name - rarity = rarityValue + rarity = rarityValue.permilleValue backdropAttribute = attribute if case let .backdrop(_, selectedId, _, _, _, _, _) = self.selectedBackdrop { @@ -455,7 +455,7 @@ private final class GiftUpgradeVariantsScreenComponent: Component { itemId += "\(file.fileId.id)" if self.selectedSection == .symbols { title = name - rarity = rarityValue + rarity = rarityValue.permilleValue symbolAttribute = attribute if case let .pattern(_, selectedFile, _) = self.selectedSymbol { @@ -1270,18 +1270,18 @@ private final class AttributeInfoComponent: Component { let subtitle: String let rarity: Int32 switch component.attribute { - case let .model(name, _, rarityValue): + case let .model(name, _, rarityValue, _): title = name subtitle = component.strings.Gift_Variants_Model - rarity = rarityValue + rarity = rarityValue.permilleValue case let .backdrop(name, _, _, _, _, _, rarityValue): title = name subtitle = component.strings.Gift_Variants_Backdrop - rarity = rarityValue + rarity = rarityValue.permilleValue case let .pattern(name, _, rarityValue): title = name subtitle = component.strings.Gift_Variants_Symbol - rarity = rarityValue + rarity = rarityValue.permilleValue default: title = "" subtitle = "" diff --git a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftValueScreen.swift b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftValueScreen.swift index c267b6f2..77376bdd 100644 --- a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftValueScreen.swift +++ b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftValueScreen.swift @@ -214,7 +214,7 @@ private final class GiftValueSheetContent: CombinedComponent { giftIconSubject = .starGift(gift: gift, price: "") case let .unique(gift): for attribute in gift.attributes { - if case let .model(_, file, _) = attribute { + if case let .model(_, file, _, _) = attribute { animationFile = file } } diff --git a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftViewScreen.swift b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftViewScreen.swift index cd942adc..6851c541 100644 --- a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftViewScreen.swift +++ b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftViewScreen.swift @@ -234,8 +234,9 @@ private final class GiftViewSheetContent: CombinedComponent { if self.testUpgradeAnimation { if gift.giftId != 0 { - self.upgradePreviewDisposable.add((context.engine.payments.starGiftUpgradePreview(giftId: gift.giftId) - |> deliverOnMainQueue).start(next: { [weak self] upgradePreview in + let upgradePreviewSignal = context.engine.payments.starGiftUpgradePreview(giftId: gift.giftId) + |> deliverOnMainQueue + self.upgradePreviewDisposable.add(upgradePreviewSignal.start(next: { [weak self] upgradePreview in guard let self, let upgradePreview else { return } @@ -243,7 +244,7 @@ private final class GiftViewSheetContent: CombinedComponent { for attribute in upgradePreview.attributes { switch attribute { - case let .model(_, file, _): + case let .model(_, file, _, _): self.upgradePreviewDisposable.add(freeMediaFileResourceInteractiveFetched(account: self.context.account, userLocation: .other, fileReference: .standalone(media: file), resource: file.resource).start()) case let .pattern(_, file, _): self.upgradePreviewDisposable.add(freeMediaFileResourceInteractiveFetched(account: self.context.account, userLocation: .other, fileReference: .standalone(media: file), resource: file.resource).start()) @@ -261,8 +262,9 @@ private final class GiftViewSheetContent: CombinedComponent { peerIds.append(releasedBy) } if arguments.canUpgrade || arguments.upgradeStars != nil || arguments.prepaidUpgradeHash != nil { - self.upgradePreviewDisposable.add((context.engine.payments.starGiftUpgradePreview(giftId: gift.id) - |> deliverOnMainQueue).start(next: { [weak self] upgradePreview in + let upgradePreviewSignal = context.engine.payments.starGiftUpgradePreview(giftId: gift.id) + |> deliverOnMainQueue + self.upgradePreviewDisposable.add(upgradePreviewSignal.start(next: { [weak self] upgradePreview in guard let self, let upgradePreview else { return } @@ -270,7 +272,7 @@ private final class GiftViewSheetContent: CombinedComponent { for attribute in upgradePreview.attributes { switch attribute { - case let .model(_, file, _): + case let .model(_, file, _, _): self.upgradePreviewDisposable.add(freeMediaFileResourceInteractiveFetched(account: self.context.account, userLocation: .other, fileReference: .standalone(media: file), resource: file.resource).start()) case let .pattern(_, file, _): self.upgradePreviewDisposable.add(freeMediaFileResourceInteractiveFetched(account: self.context.account, userLocation: .other, fileReference: .standalone(media: file), resource: file.resource).start()) @@ -501,7 +503,7 @@ private final class GiftViewSheetContent: CombinedComponent { animationFile = gift.file case let .unique(gift): for attribute in gift.attributes { - if case let .model(_, file, _) = attribute { + if case let .model(_, file, _, _) = attribute { animationFile = file break } @@ -718,7 +720,7 @@ private final class GiftViewSheetContent: CombinedComponent { let context = self.context let presentationData = context.sharedContext.currentPresentationData.with { $0 } - let proceed = { [weak self, weak starsContext, weak controller] in + let proceed: () -> Void = { [weak self, weak starsContext, weak controller] in guard let self, let controller else { return } @@ -745,7 +747,7 @@ private final class GiftViewSheetContent: CombinedComponent { let updatedAttributes = uniqueGift.attributes.filter { $0.attributeType != .originalInfo } self.subject = .profileGift(peerId, gift.withGift(.unique(uniqueGift.withAttributes(updatedAttributes)))) case let .message(message): - if let action = message.media.first(where: { $0 is TelegramMediaAction }) as? TelegramMediaAction, case let .starGiftUnique(gift, isUpgrade, isTransferred, savedToProfile, canExportDate, transferStars, isRefunded, isPrepaidUpgrade, peerId, senderId, savedId, resaleAmount, canTransferDate, canResaleDate, _, assigned, fromOffer) = action.action, case let .unique(uniqueGift) = gift { + if let action = message.media.first(where: { $0 is TelegramMediaAction }) as? TelegramMediaAction, case let .starGiftUnique(gift, isUpgrade, isTransferred, savedToProfile, canExportDate, transferStars, isRefunded, isPrepaidUpgrade, peerId, senderId, savedId, resaleAmount, canTransferDate, canResaleDate, _, assigned, fromOffer, _, _) = action.action, case let .unique(uniqueGift) = gift { let updatedAttributes = uniqueGift.attributes.filter { $0.attributeType != .originalInfo } let updatedMedia: [Media] = [ TelegramMediaAction( @@ -766,7 +768,9 @@ private final class GiftViewSheetContent: CombinedComponent { canResaleDate: canResaleDate, dropOriginalDetailsStars: nil, assigned: assigned, - fromOffer: fromOffer + fromOffer: fromOffer, + canCraftAt: nil, + isCrafted: false ) ) ] @@ -1008,7 +1012,10 @@ private final class GiftViewSheetContent: CombinedComponent { |> then( context.engine.payments.getUniqueStarGift(slug: gift.slug) |> map { gift in - return gift?.themePeerId + return gift.themePeerId + } + |> `catch` { _ -> Signal in + return .single(nil) } ) ) @@ -1376,6 +1383,7 @@ private final class GiftViewSheetContent: CombinedComponent { let variantsController = self.context.sharedContext.makeGiftUpgradeVariantsScreen( context: self.context, gift: arguments.gift, + crafted: false, attributes: attributes, selectedAttributes: selectedAttributes, focusedAttribute: attribute @@ -1443,7 +1451,7 @@ private final class GiftViewSheetContent: CombinedComponent { } if case let .unique(gift) = arguments.gift, let resellAmount = gift.resellAmounts?.first, resellAmount.amount.value > 0 { - if arguments.reference != nil || gift.owner.peerId == context.account.peerId { + if arguments.reference != nil || gift.owner?.peerId == context.account.peerId { items.append(.action(ContextMenuActionItem(text: presentationData.strings.Gift_View_Context_ChangePrice, icon: { theme in return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/PriceTag"), color: theme.contextMenu.primaryColor) }, action: { [weak self] c, _ in @@ -1703,7 +1711,7 @@ private final class GiftViewSheetContent: CombinedComponent { let giftTitle = "\(uniqueGift.title) #\(formatCollectibleNumber(uniqueGift.number, dateTimeFormat: presentationData.dateTimeFormat))" let recipientPeerId = self.recipientPeerId ?? self.context.account.peerId - let action: (CurrencyAmount.Currency) -> Void = { currency in + let action: (CurrencyAmount.Currency) -> Void = { (currency: CurrencyAmount.Currency) in guard let resellAmount = uniqueGift.resellAmounts?.first(where: { $0.currency == currency }) else { guard let controller = self.getController() as? GiftViewScreen else { return @@ -1802,10 +1810,10 @@ private final class GiftViewSheetContent: CombinedComponent { var animationFile: TelegramMediaFile? for attribute in uniqueGift.attributes { - if case let .model(_, file, _) = attribute { - animationFile = file - break - } + if case let .model(_, file, _, _) = attribute { + animationFile = file + break + } } if let navigationController = controller.navigationController as? NavigationController { @@ -3671,7 +3679,7 @@ private final class GiftViewSheetContent: CombinedComponent { if state.pendingWear { var fileId: Int64? for attribute in uniqueGift.attributes { - if case let .model(_, file, _) = attribute { + if case let .model(_, file, _, _) = attribute { fileId = file.fileId.id } if case let .backdrop(_, _, innerColor, _, _, _, _) = attribute { @@ -3780,6 +3788,8 @@ private final class GiftViewSheetContent: CombinedComponent { ) ) )) + case .none: + break } if let peerId = uniqueGift.hostPeerId, let peer = state.peerMap[peerId] { @@ -4113,17 +4123,17 @@ private final class GiftViewSheetContent: CombinedComponent { var otherValuesAndPercentages: [(value: String, percentage: Float)] = [] switch attribute { - case let .model(name, _, rarity): + case let .model(name, _, rarity, _): id = "model" title = strings.Gift_Unique_Model value = NSAttributedString(string: name, font: tableFont, textColor: tableTextColor) - percentage = Float(rarity) * 0.1 + percentage = Float(rarity.permilleValue) * 0.1 tag = state.modelButtonTag if state.justUpgraded, let sampleAttributes = state.upgradePreview?.attributes { for sampleAttribute in sampleAttributes { - if case let .model(name, _, rarity) = sampleAttribute { - otherValuesAndPercentages.append((name, Float(rarity) * 0.1)) + if case let .model(name, _, rarity, _) = sampleAttribute { + otherValuesAndPercentages.append((name, Float(rarity.permilleValue) * 0.1)) } } } @@ -4131,13 +4141,13 @@ private final class GiftViewSheetContent: CombinedComponent { id = "backdrop" title = strings.Gift_Unique_Backdrop value = NSAttributedString(string: name, font: tableFont, textColor: tableTextColor) - percentage = Float(rarity) * 0.1 + percentage = Float(rarity.permilleValue) * 0.1 tag = state.backdropButtonTag if state.justUpgraded, let sampleAttributes = state.upgradePreview?.attributes { for sampleAttribute in sampleAttributes { if case let .backdrop(name, _, _, _, _, _, rarity) = sampleAttribute { - otherValuesAndPercentages.append((name, Float(rarity) * 0.1)) + otherValuesAndPercentages.append((name, Float(rarity.permilleValue) * 0.1)) } } } @@ -4145,13 +4155,13 @@ private final class GiftViewSheetContent: CombinedComponent { id = "pattern" title = strings.Gift_Unique_Symbol value = NSAttributedString(string: name, font: tableFont, textColor: tableTextColor) - percentage = Float(rarity) * 0.1 + percentage = Float(rarity.permilleValue) * 0.1 tag = state.symbolButtonTag if state.justUpgraded, let sampleAttributes = state.upgradePreview?.attributes { for sampleAttribute in sampleAttributes { if case let .pattern(name, _, rarity) = sampleAttribute { - otherValuesAndPercentages.append((name, Float(rarity) * 0.1)) + otherValuesAndPercentages.append((name, Float(rarity.permilleValue) * 0.1)) } } } @@ -5500,7 +5510,7 @@ public class GiftViewScreen: ViewControllerComponentContainer { let fromPeerId = senderId ?? message.author?.id return (message.id.peerId, fromPeerId, message.author?.debugDisplayTitle, message.author?.compactDisplayTitle, message.id, reference, message.flags.contains(.Incoming), gift, message.timestamp, convertStars, text, entities, nameHidden, savedToProfile, nil, converted, upgraded, isRefunded, canUpgrade, upgradeStars, nil, nil, nil, upgradeMessageId, nil, nil, prepaidUpgradeHash, upgradeSeparate, nil, toPeerId, number) - case let .starGiftUnique(gift, isUpgrade, isTransferred, savedToProfile, canExportDate, transferStars, _, _, peerId, senderId, savedId, _, canTransferDate, canResaleDate, dropOriginalDetailsStars, _, _): + case let .starGiftUnique(gift, isUpgrade, isTransferred, savedToProfile, canExportDate, transferStars, _, _, peerId, senderId, savedId, _, canTransferDate, canResaleDate, dropOriginalDetailsStars, _, _, _, _): var reference: StarGiftReference if let peerId, let savedId { reference = .peer(peerId: peerId, id: savedId) diff --git a/submodules/TelegramUI/Components/GlassBackgroundComponent/Sources/GlassBackgroundComponent.swift b/submodules/TelegramUI/Components/GlassBackgroundComponent/Sources/GlassBackgroundComponent.swift index ce271441..11005de7 100644 --- a/submodules/TelegramUI/Components/GlassBackgroundComponent/Sources/GlassBackgroundComponent.swift +++ b/submodules/TelegramUI/Components/GlassBackgroundComponent/Sources/GlassBackgroundComponent.swift @@ -262,6 +262,12 @@ public class GlassBackgroundView: UIView { self.color = color self.innerColor = innerColor } + + public init(kind: Kind, innerColor: UIColor? = nil) { + self.kind = kind + self.color = .clear + self.innerColor = innerColor + } } public enum Shape: Equatable { diff --git a/submodules/TelegramUI/Components/GlobalControlPanelsContext/Sources/GlobalControlPanelsContext.swift b/submodules/TelegramUI/Components/GlobalControlPanelsContext/Sources/GlobalControlPanelsContext.swift index d42d3910..338b14f8 100644 --- a/submodules/TelegramUI/Components/GlobalControlPanelsContext/Sources/GlobalControlPanelsContext.swift +++ b/submodules/TelegramUI/Components/GlobalControlPanelsContext/Sources/GlobalControlPanelsContext.swift @@ -68,6 +68,7 @@ public final class GlobalControlPanelsContext { public enum ChatListNotice: Equatable { case clearStorage(sizeFraction: Double) + case sgUrl(id: String, title: String, text: String?, url: String, needAuth: Bool, permanent: Bool) case setupPassword case premiumUpgrade(discount: Int32) case premiumAnnualDiscount(discount: Int32) @@ -329,6 +330,7 @@ public final class GlobalControlPanelsContext { let starsSubscriptionsContextPromise = Promise(nil) let suggestedChatListNoticeSignal: Signal = combineLatest( + getSGProvidedSuggestions(account: context.account), context.engine.notices.getServerProvidedSuggestions(), context.engine.notices.getServerDismissedSuggestions(), twoStepData, @@ -341,9 +343,18 @@ public final class GlobalControlPanelsContext { starsSubscriptionsContextPromise.get(), accountFreezeConfiguration ) - |> mapToSignal { suggestions, dismissedSuggestions, configuration, newSessionReviews, data, birthdays, starsSubscriptionsContext, accountFreezeConfiguration -> Signal in + |> mapToSignal { sgSuggestionsData, suggestions, dismissedSuggestions, configuration, newSessionReviews, data, birthdays, starsSubscriptionsContext, accountFreezeConfiguration -> Signal in let (accountPeer, birthday) = data + + // MARK: Swiftgram + if let sgSuggestionsData = sgSuggestionsData, let dictionary = try? JSONSerialization.jsonObject(with: sgSuggestionsData, options: []), let sgSuggestions = dictionary as? [[String: Any]], let sgSuggestion = sgSuggestions.first, let sgSuggestionId = sgSuggestion["id"] as? String { + if let sgSuggestionType = sgSuggestion["type"] as? String, sgSuggestionType == "SG_URL", let sgSuggestionTitle = sgSuggestion["title"] as? String, let sgSuggestionUrl = sgSuggestion["url"] as? String { + return .single(.sgUrl(id: sgSuggestionId, title: sgSuggestionTitle, text: sgSuggestion["text"] as? String, url: sgSuggestionUrl, needAuth: sgSuggestion["need_auth"] as? Bool ?? false, permanent: sgSuggestion["permanent"] as? Bool ?? false)) + + } + } + // if let newSessionReview = newSessionReviews.first { return .single(.reviewLogin(newSessionReview: newSessionReview, totalCount: newSessionReviews.count)) } @@ -401,8 +412,12 @@ public final class GlobalControlPanelsContext { } else if suggestions.contains(.gracePremium) { return .single(.premiumGrace) } else if suggestions.contains(.xmasPremiumGift) { + // MARK: Swiftgram + if ({ return true }()) { return .single(nil) } return .single(.xmasPremiumGift) } else if suggestions.contains(.annualPremium) || suggestions.contains(.upgradePremium) || suggestions.contains(.restorePremium), let inAppPurchaseManager = context.inAppPurchaseManager { + // MARK: Swiftgram + if ({ return true }()) { return .single(nil) } return inAppPurchaseManager.availableProducts |> map { products -> ChatListNotice? in if products.count > 1 { @@ -475,6 +490,7 @@ public final class GlobalControlPanelsContext { self.notifyStateUpdated() } }) + } if let callManager = context.sharedContext.callManager, let peerId = groupCalls { diff --git a/submodules/TelegramUI/Components/HorizontalTabsComponent/BUILD b/submodules/TelegramUI/Components/HorizontalTabsComponent/BUILD index 7f31dd2d..cdbf721a 100644 --- a/submodules/TelegramUI/Components/HorizontalTabsComponent/BUILD +++ b/submodules/TelegramUI/Components/HorizontalTabsComponent/BUILD @@ -1,5 +1,9 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + swift_library( name = "HorizontalTabsComponent", module_name = "HorizontalTabsComponent", @@ -9,7 +13,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/Display", "//submodules/ComponentFlow", "//submodules/TelegramPresentationData", diff --git a/submodules/TelegramUI/Components/HorizontalTabsComponent/Sources/HorizontalTabsComponent.swift b/submodules/TelegramUI/Components/HorizontalTabsComponent/Sources/HorizontalTabsComponent.swift index 789b2613..08b3a80e 100644 --- a/submodules/TelegramUI/Components/HorizontalTabsComponent/Sources/HorizontalTabsComponent.swift +++ b/submodules/TelegramUI/Components/HorizontalTabsComponent/Sources/HorizontalTabsComponent.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import Display @@ -305,6 +306,8 @@ public final class HorizontalTabsComponent: Component { private var tabSwitchFraction: CGFloat = 0.0 private var isDraggingTabs: Bool = false private var temporaryLiftTimer: Foundation.Timer? + private var didTapOnAnItem: Bool = false + private var didTapOnAnItemTimer: Foundation.Timer? private var tapRecognizer: UITapGestureRecognizer? @@ -531,6 +534,14 @@ public final class HorizontalTabsComponent: Component { for (id, itemView) in self.itemViews { if self.scrollView.convert(itemView.selectionFrame, to: self).contains(point) { if let tab = component.tabs.first(where: { $0.id == id }) { + self.didTapOnAnItem = true + self.didTapOnAnItemTimer?.invalidate() + self.didTapOnAnItemTimer = Foundation.Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: { [weak self] _ in + guard let self else { + return + } + self.didTapOnAnItem = false + }) tab.action() } } @@ -609,7 +620,7 @@ public final class HorizontalTabsComponent: Component { self.temporaryLiftTimer?.invalidate() self.temporaryLiftTimer = nil - if !transition.animation.isImmediate { + if !transition.animation.isImmediate && self.didTapOnAnItem { self.temporaryLiftTimer = Foundation.Timer.scheduledTimer(withTimeInterval: 0.3, repeats: false, block: { [weak self] _ in guard let self else { return @@ -627,6 +638,12 @@ public final class HorizontalTabsComponent: Component { self.component = component self.state = state + self.didTapOnAnItem = false + if let didTapOnAnItemTimer = self.didTapOnAnItemTimer { + self.didTapOnAnItemTimer = nil + didTapOnAnItemTimer.invalidate() + } + self.reorderingGesture?.isEnabled = component.isEditing let sizeHeight: CGFloat = availableSize.height @@ -1059,7 +1076,7 @@ private final class ItemComponent: Component { self.containerView.isGestureEnabled = component.editing == nil self.tapRecognizer?.isEnabled = component.editing == nil - let sideInset: CGFloat = 16.0 + let sideInset: CGFloat = 16.0 / (SGSimpleSettings.shared.compactFolderNames ? 2.0 : 1.0) let badgeSpacing: CGFloat = 5.0 var size = CGSize(width: sideInset, height: availableSize.height) diff --git a/submodules/TelegramUI/Components/LegacyInstantVideoController/BUILD b/submodules/TelegramUI/Components/LegacyInstantVideoController/BUILD index 4ffab8ae..2bc571ea 100644 --- a/submodules/TelegramUI/Components/LegacyInstantVideoController/BUILD +++ b/submodules/TelegramUI/Components/LegacyInstantVideoController/BUILD @@ -1,5 +1,9 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + swift_library( name = "LegacyInstantVideoController", module_name = "LegacyInstantVideoController", @@ -9,7 +13,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/AsyncDisplayKit", "//submodules/Display", "//submodules/TelegramCore", diff --git a/submodules/TelegramUI/Components/LegacyInstantVideoController/Sources/LegacyInstantVideoController.swift b/submodules/TelegramUI/Components/LegacyInstantVideoController/Sources/LegacyInstantVideoController.swift index 798088a4..3973c994 100644 --- a/submodules/TelegramUI/Components/LegacyInstantVideoController/Sources/LegacyInstantVideoController.swift +++ b/submodules/TelegramUI/Components/LegacyInstantVideoController/Sources/LegacyInstantVideoController.swift @@ -1,3 +1,6 @@ +// MARK: Swiftgram +import SGSimpleSettings + import Foundation import UIKit import AsyncDisplayKit diff --git a/submodules/TelegramUI/Components/MediaEditorScreen/BUILD b/submodules/TelegramUI/Components/MediaEditorScreen/BUILD index 448ecd6c..9b317dcc 100644 --- a/submodules/TelegramUI/Components/MediaEditorScreen/BUILD +++ b/submodules/TelegramUI/Components/MediaEditorScreen/BUILD @@ -1,5 +1,9 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + swift_library( name = "MediaEditorScreen", module_name = "MediaEditorScreen", @@ -9,7 +13,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/AsyncDisplayKit:AsyncDisplayKit", "//submodules/Display:Display", "//submodules/Postbox:Postbox", @@ -70,6 +74,7 @@ swift_library( "//submodules/TelegramNotices", "//submodules/TelegramUI/Components/AttachmentFileController", "//submodules/SaveToCameraRoll", + "//submodules/TelegramUI/Components/ContextControllerImpl", ], visibility = [ "//visibility:public", diff --git a/submodules/TelegramUI/Components/MediaEditorScreen/Sources/EditStories.swift b/submodules/TelegramUI/Components/MediaEditorScreen/Sources/EditStories.swift index e8cc73e5..63493490 100644 --- a/submodules/TelegramUI/Components/MediaEditorScreen/Sources/EditStories.swift +++ b/submodules/TelegramUI/Components/MediaEditorScreen/Sources/EditStories.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import Display @@ -187,7 +188,7 @@ public extension MediaEditorScreenImpl { defer { TempBox.shared.dispose(tempFile) } - if let imageData = compressImageToJPEG(image, quality: 0.7, tempFilePath: tempFile.path) { + if let imageData = compressImageToJPEG(image, quality: Float(SGSimpleSettings.shared.outgoingPhotoQuality) / 100.0, tempFilePath: tempFile.path) { update((context.engine.messages.editStory(peerId: peer.id, id: storyItem.id, media: .image(dimensions: dimensions, data: imageData, stickers: result.stickers), mediaAreas: result.mediaAreas, text: updatedText, entities: updatedEntities, privacy: nil) |> deliverOnMainQueue).startStrict(next: { result in switch result { @@ -226,7 +227,7 @@ public extension MediaEditorScreenImpl { defer { TempBox.shared.dispose(tempFile) } - let firstFrameImageData = firstFrameImage.flatMap { compressImageToJPEG($0, quality: 0.6, tempFilePath: tempFile.path) } + let firstFrameImageData = firstFrameImage.flatMap { compressImageToJPEG($0, quality: Float(SGSimpleSettings.shared.outgoingPhotoQuality) / 100.0, tempFilePath: tempFile.path) } let firstFrameFile = firstFrameImageData.flatMap { data -> TempBoxFile? in let file = TempBox.shared.tempFile(fileName: "image.jpg") if let _ = try? data.write(to: URL(fileURLWithPath: file.path)) { diff --git a/submodules/TelegramUI/Components/MediaEditorScreen/Sources/MediaEditorScreen.swift b/submodules/TelegramUI/Components/MediaEditorScreen/Sources/MediaEditorScreen.swift index 3291c6ca..85224940 100644 --- a/submodules/TelegramUI/Components/MediaEditorScreen/Sources/MediaEditorScreen.swift +++ b/submodules/TelegramUI/Components/MediaEditorScreen/Sources/MediaEditorScreen.swift @@ -1244,6 +1244,7 @@ final class MediaEditorScreenComponent: Component { let presentationInterfaceState = ChatPresentationInterfaceState( chatWallpaper: .builtin(WallpaperSettings()), theme: presentationData.theme, + preferredGlassType: .default, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameDisplayOrder: presentationData.nameDisplayOrder, @@ -3733,7 +3734,7 @@ public final class MediaEditorScreenImpl: ViewController, MediaEditorScreen, UID } } else if case let .gift(gift) = subject { isGift = true - let media: [Media] = [TelegramMediaAction(action: .starGiftUnique(gift: .unique(gift), isUpgrade: false, isTransferred: false, savedToProfile: false, canExportDate: nil, transferStars: nil, isRefunded: false, isPrepaidUpgrade: false, peerId: nil, senderId: nil, savedId: nil, resaleAmount: nil, canTransferDate: nil, canResaleDate: nil, dropOriginalDetailsStars: nil, assigned: false, fromOffer: false))] + let media: [Media] = [TelegramMediaAction(action: .starGiftUnique(gift: .unique(gift), isUpgrade: false, isTransferred: false, savedToProfile: false, canExportDate: nil, transferStars: nil, isRefunded: false, isPrepaidUpgrade: false, peerId: nil, senderId: nil, savedId: nil, resaleAmount: nil, canTransferDate: nil, canResaleDate: nil, dropOriginalDetailsStars: nil, assigned: false, fromOffer: false, canCraftAt: nil, isCrafted: false))] let message = Message(stableId: 0, stableVersion: 0, id: MessageId(peerId: self.context.account.peerId, namespace: Namespaces.Message.Cloud, id: -1), globallyUniqueId: nil, groupingKey: nil, groupInfo: nil, threadId: nil, timestamp: 0, flags: [], tags: [], globalTags: [], localTags: [], customTags: [], forwardInfo: nil, author: nil, text: "", attributes: [], media: media, peers: SimpleDictionary(), associatedMessages: SimpleDictionary(), associatedMessageIds: [], associatedMedia: [:], associatedThreadInfo: nil, associatedStories: [:]) messages = .single([message]) } else { diff --git a/submodules/TelegramUI/Components/MessageInputPanelComponent/BUILD b/submodules/TelegramUI/Components/MessageInputPanelComponent/BUILD index 612caada..fce1ed77 100644 --- a/submodules/TelegramUI/Components/MessageInputPanelComponent/BUILD +++ b/submodules/TelegramUI/Components/MessageInputPanelComponent/BUILD @@ -1,5 +1,11 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgDeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//Swiftgram/SGInputToolbar:SGInputToolbar" +] + + swift_library( name = "MessageInputPanelComponent", module_name = "MessageInputPanelComponent", @@ -9,7 +15,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgDeps + [ "//submodules/Display", "//submodules/ComponentFlow", "//submodules/AppBundle", diff --git a/submodules/TelegramUI/Components/MessageInputPanelComponent/Sources/MessageInputPanelComponent.swift b/submodules/TelegramUI/Components/MessageInputPanelComponent/Sources/MessageInputPanelComponent.swift index 870d8f3e..add23a72 100644 --- a/submodules/TelegramUI/Components/MessageInputPanelComponent/Sources/MessageInputPanelComponent.swift +++ b/submodules/TelegramUI/Components/MessageInputPanelComponent/Sources/MessageInputPanelComponent.swift @@ -1,3 +1,8 @@ +// MARK: Swiftgram +import class SwiftUI.UIHostingController +import SGSimpleSettings +import SGInputToolbar + import Foundation import UIKit import Display @@ -603,6 +608,9 @@ public final class MessageInputPanelComponent: Component { private let counter = ComponentView() private var header: ComponentView? + // MARK: Swiftgram + private var toolbarView: UIView? + private var disabledPlaceholder: ComponentView? private var textClippingView = UIView() private let textField = ComponentView() @@ -659,7 +667,7 @@ public final class MessageInputPanelComponent: Component { return (self.likeButton.view as? MessageInputActionButtonComponent.View)?.likeIconView } - override init(frame: CGRect) { + init(context: AccountContext, frame: CGRect) { self.fieldBackgroundView = BlurredBackgroundView(color: nil, enableBlur: true) self.fieldBackgroundTint = UIView() self.fieldBackgroundTint.backgroundColor = UIColor(white: 1.0, alpha: 0.1) @@ -706,6 +714,9 @@ public final class MessageInputPanelComponent: Component { self.state?.updated() } ) + + // MARK: Swiftgram + self.initToolbarIfNeeded(context: context) } required init?(coder: NSCoder) { @@ -914,6 +925,11 @@ public final class MessageInputPanelComponent: Component { if result == nil, let contextQueryResultPanel = self.contextQueryResultPanel?.view, let panelResult = contextQueryResultPanel.hitTest(self.convert(point, to: contextQueryResultPanel), with: event), panelResult !== contextQueryResultPanel { return panelResult } + + // MARK: Swiftgram + if result == nil, let toolbarView = self.toolbarView, let toolbarResult = toolbarView.hitTest(self.convert(point, to: toolbarView), with: event) { + return toolbarResult + } return result } @@ -1508,7 +1524,7 @@ public final class MessageInputPanelComponent: Component { self.fieldBackgroundTint.isHidden = true } if let fieldGlassBackgroundView = self.fieldGlassBackgroundView { - fieldGlassBackgroundView.update(size: fieldBackgroundFrame.size, cornerRadius: baseFieldHeight * 0.5, isDark: component.theme.overallDarkAppearance, tintColor: .init(kind: .panel, color: component.theme.chat.inputPanel.inputBackgroundColor.withMultipliedAlpha(0.7)), transition: transition) + fieldGlassBackgroundView.update(size: fieldBackgroundFrame.size, cornerRadius: baseFieldHeight * 0.5, isDark: component.theme.overallDarkAppearance, tintColor: .init(kind: .panel), transition: transition) transition.setFrame(view: fieldGlassBackgroundView, frame: fieldBackgroundFrame) } case .videoChat: @@ -2983,12 +2999,15 @@ public final class MessageInputPanelComponent: Component { } } + // MARK: Swiftgram + size = self.layoutToolbar(transition: transition, layoutFromTop: layoutFromTop, size: size, availableSize: availableSize, defaultInsets: defaultInsets, textFieldSize: textFieldSize, previousComponent: previousComponent) + return size } } public func makeView() -> View { - return View(frame: CGRect()) + return View(context: self.context, frame: CGRect()) } public func update(view: View, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { @@ -3036,3 +3055,109 @@ final class ViewForOverlayContent: UIView { return nil } } + + +extension MessageInputPanelComponent.View { + func initToolbarIfNeeded(context: AccountContext) { + guard #available(iOS 13.0, *) else { return } + guard SGSimpleSettings.shared.inputToolbar else { return } + guard context.sharedContext.immediateSGStatus.status > 1 else { return } + guard self.toolbarView == nil else { return } + let notificationName = Notification.Name("sgToolbarAction") + let toolbar = ChatToolbarView( + onQuote: { [weak self] in + guard let _ = self else { return } + NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["action": "quote"]) + }, + onSpoiler: { [weak self] in + guard let _ = self else { return } + NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["action": "spoiler"]) + }, + onBold: { [weak self] in + guard let _ = self else { return } + NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["action": "bold"]) + }, + onItalic: { [weak self] in + guard let _ = self else { return } + NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["action": "italic"]) + }, + onMonospace: { [weak self] in + guard let _ = self else { return } + NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["action": "monospace"]) + }, + onLink: { [weak self] in + guard let _ = self else { return } + NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["action": "link"]) + }, + onStrikethrough: { [weak self] + in guard let _ = self else { return } + NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["action": "strikethrough"]) + }, + onUnderline: { [weak self] in + guard let _ = self else { return } + NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["action": "underline"]) + }, + onCode: { [weak self] in + guard let _ = self else { return } + NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["action": "code"]) + }, + onNewLine: { [weak self] in + guard let _ = self else { return } + NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["action": "newline"]) + }, + // TODO(swiftgram): Binding + showNewLine: .constant(true), //.constant(self.sendWithReturnKey) + onClearFormatting: { [weak self] in + guard let _ = self else { return } + NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["action": "clearFormatting"]) + } + ).colorScheme(.dark) + + let toolbarHostingController = UIHostingController(rootView: toolbar) + toolbarHostingController.view.backgroundColor = .clear + let toolbarView = toolbarHostingController.view + self.toolbarView = toolbarView + // assigning toolbarHostingController bugs responsivness and overrides layout + // self.toolbarHostingController = toolbarHostingController + + // Disable "Swipe to go back" gesture when touching scrollview + self.interactiveTransitionGestureRecognizerTest = { [weak self] point in + if let self, let _ = self.toolbarView?.hitTest(point, with: nil) { + return false + } + return true + } + if let toolbarView = self.toolbarView { + self.addSubview(toolbarView) + } + } + + func layoutToolbar(transition: ComponentTransition, layoutFromTop: Bool, size: CGSize, availableSize: CGSize, defaultInsets: UIEdgeInsets, textFieldSize: CGSize, previousComponent: MessageInputPanelComponent?) -> CGSize { + // TODO(swiftgram): Do not show if locked formatting + var transition = transition + if let previousComponent = previousComponent { + let previousLayoutFromTop = previousComponent.attachmentButtonMode == .captionDown + if previousLayoutFromTop != layoutFromTop { + // attachmentButtonMode changed + transition = .immediate + } + } + var size = size + if let toolbarView = self.toolbarView { + let toolbarHeight: CGFloat = 44.0 + let toolbarSpacing: CGFloat = 1.0 + let toolbarSize = CGSize(width: availableSize.width, height: toolbarHeight) + let hasFirstResponder = self.hasFirstResponder() + transition.setAlpha(view: toolbarView, alpha: hasFirstResponder ? 1.0 : 0.0) + if layoutFromTop { + transition.setFrame(view: toolbarView, frame: CGRect(origin: CGPoint(x: .zero, y: availableSize.height + toolbarSpacing), size: toolbarSize)) + } else { + transition.setFrame(view: toolbarView, frame: CGRect(origin: CGPoint(x: .zero, y: textFieldSize.height + defaultInsets.top + toolbarSpacing), size: toolbarSize)) + if hasFirstResponder { + size.height += toolbarHeight + toolbarSpacing + } + } + } + return size + } +} diff --git a/submodules/TelegramUI/Components/PeerInfo/AccountPeerContextItem/BUILD b/submodules/TelegramUI/Components/PeerInfo/AccountPeerContextItem/BUILD new file mode 100644 index 00000000..074697e8 --- /dev/null +++ b/submodules/TelegramUI/Components/PeerInfo/AccountPeerContextItem/BUILD @@ -0,0 +1,29 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "AccountPeerContextItem", + module_name = "AccountPeerContextItem", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + "//submodules/AsyncDisplayKit", + "//submodules/Display", + "//submodules/Postbox", + "//submodules/TelegramCore", + "//submodules/PresentationDataUtils", + "//submodules/TelegramPresentationData", + "//submodules/ComponentFlow", + "//submodules/TelegramUI/Components/EmojiStatusComponent", + "//submodules/AvatarNode", + "//submodules/ContextUI", + "//submodules/AccountContext", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/submodules/TelegramUI/Components/PeerInfo/AccountPeerContextItem/Sources/AccountPeerContextItem.swift b/submodules/TelegramUI/Components/PeerInfo/AccountPeerContextItem/Sources/AccountPeerContextItem.swift new file mode 100644 index 00000000..69e5fedd --- /dev/null +++ b/submodules/TelegramUI/Components/PeerInfo/AccountPeerContextItem/Sources/AccountPeerContextItem.swift @@ -0,0 +1,174 @@ +import Foundation +import UIKit +import Display +import AsyncDisplayKit +import SwiftSignalKit +import ComponentFlow +import TelegramCore +import TelegramPresentationData +import PresentationDataUtils +import ContextUI +import AvatarNode +import EmojiStatusComponent +import AccountContext + +public final class AccountPeerContextItem: ContextMenuCustomItem { + let context: AccountContext + let account: Account + let peer: EnginePeer + let action: (ContextControllerProtocol, @escaping (ContextMenuActionResult) -> Void) -> Void + + public init(context: AccountContext, account: Account, peer: EnginePeer, action: @escaping (ContextControllerProtocol, @escaping (ContextMenuActionResult) -> Void) -> Void) { + self.context = context + self.account = account + self.peer = peer + self.action = action + } + + public func node(presentationData: PresentationData, getController: @escaping () -> ContextControllerProtocol?, actionSelected: @escaping (ContextMenuActionResult) -> Void) -> ContextMenuCustomNode { + return AccountPeerContextItemNode(presentationData: presentationData, item: self, getController: getController, actionSelected: actionSelected) + } +} + +private final class AccountPeerContextItemNode: ASDisplayNode, ContextMenuCustomNode { + private let item: AccountPeerContextItem + private let presentationData: PresentationData + private let getController: () -> ContextControllerProtocol? + private let actionSelected: (ContextMenuActionResult) -> Void + + private let buttonNode: HighlightTrackingButtonNode + private let textNode: ImmediateTextNode + private let avatarNode: AvatarNode + private let emojiStatusView: ComponentView + + init(presentationData: PresentationData, item: AccountPeerContextItem, getController: @escaping () -> ContextControllerProtocol?, actionSelected: @escaping (ContextMenuActionResult) -> Void) { + self.item = item + self.presentationData = presentationData + self.getController = getController + self.actionSelected = actionSelected + + let textFont = Font.regular(presentationData.listsFontSize.baseDisplaySize * 17.0 / 17.0) + + self.textNode = ImmediateTextNode() + self.textNode.isAccessibilityElement = false + self.textNode.isUserInteractionEnabled = false + self.textNode.displaysAsynchronously = false + let peerTitle = item.peer.displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder) + self.textNode.attributedText = NSAttributedString(string: peerTitle, font: textFont, textColor: presentationData.theme.contextMenu.primaryColor) + self.textNode.maximumNumberOfLines = 1 + + self.avatarNode = AvatarNode(font: avatarPlaceholderFont(size: 14.0)) + + self.emojiStatusView = ComponentView() + + self.buttonNode = HighlightTrackingButtonNode() + self.buttonNode.isAccessibilityElement = true + self.buttonNode.accessibilityLabel = peerTitle + + super.init() + + self.addSubnode(self.textNode) + self.addSubnode(self.avatarNode) + self.addSubnode(self.buttonNode) + + self.buttonNode.addTarget(self, action: #selector(self.buttonPressed), forControlEvents: .touchUpInside) + } + + func updateLayout(constrainedWidth: CGFloat, constrainedHeight: CGFloat) -> (CGSize, (CGSize, ContainedViewLayoutTransition) -> Void) { + let sideInset: CGFloat = 18.0 + let iconSideInset: CGFloat = 20.0 + let verticalInset: CGFloat = 11.0 + + let iconSize = CGSize(width: 28.0, height: 28.0) + + let standardIconWidth: CGFloat = 32.0 + var rightTextInset: CGFloat = sideInset + if !iconSize.width.isZero { + rightTextInset = max(iconSize.width, standardIconWidth) + iconSideInset + sideInset - 12.0 + } + + self.avatarNode.setPeer(context: self.item.context, account: self.item.account, theme: self.presentationData.theme, peer: self.item.peer) + + if self.item.peer.emojiStatus != nil { + rightTextInset += 32.0 + } + + let textSize = self.textNode.updateLayout(CGSize(width: constrainedWidth - sideInset - rightTextInset, height: .greatestFiniteMagnitude)) + + return (CGSize(width: textSize.width + sideInset + rightTextInset, height: verticalInset * 2.0 + textSize.height), { size, transition in + let verticalOrigin = floor((size.height - textSize.height) / 2.0) + let textFrame = CGRect(origin: CGPoint(x: iconSideInset + 40.0, y: verticalOrigin), size: textSize) + transition.updateFrameAdditive(node: self.textNode, frame: textFrame) + + var iconContent: EmojiStatusComponent.Content? + if case let .user(user) = self.item.peer { + if let emojiStatus = user.emojiStatus { + iconContent = .animation(content: .customEmoji(fileId: emojiStatus.fileId), size: CGSize(width: 28.0, height: 28.0), placeholderColor: self.presentationData.theme.list.mediaPlaceholderColor, themeColor: self.presentationData.theme.list.itemAccentColor, loopMode: .forever) + } else if user.isPremium { + iconContent = .premium(color: self.presentationData.theme.list.itemAccentColor) + } + } else if case let .channel(channel) = self.item.peer { + if let emojiStatus = channel.emojiStatus { + iconContent = .animation(content: .customEmoji(fileId: emojiStatus.fileId), size: CGSize(width: 28.0, height: 28.0), placeholderColor: self.presentationData.theme.list.mediaPlaceholderColor, themeColor: self.presentationData.theme.list.itemAccentColor, loopMode: .forever) + } + } + if let iconContent { + let emojiStatusSize = self.emojiStatusView.update( + transition: .immediate, + component: AnyComponent(EmojiStatusComponent( + context: self.item.context, + animationCache: self.item.context.animationCache, + animationRenderer: self.item.context.animationRenderer, + content: iconContent, + isVisibleForAnimations: true, + action: nil + )), + environment: {}, + containerSize: CGSize(width: 24.0, height: 24.0) + ) + if let view = self.emojiStatusView.view { + if view.superview == nil { + self.view.addSubview(view) + } + transition.updateFrame(view: view, frame: CGRect(origin: CGPoint(x: textFrame.maxX + 2.0, y: textFrame.minY + floor((textFrame.height - emojiStatusSize.height) / 2.0)), size: emojiStatusSize)) + } + } + + transition.updateFrame(node: self.avatarNode, frame: CGRect(origin: CGPoint(x: iconSideInset + floor((standardIconWidth - iconSize.width) / 2.0), y: floor((size.height - iconSize.height) / 2.0)), size: iconSize)) + + transition.updateFrame(node: self.buttonNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) + }) + } + + func updateTheme(presentationData: PresentationData) { + if let attributedText = self.textNode.attributedText { + let updatedAttributedText = NSMutableAttributedString(attributedString: attributedText) + updatedAttributedText.addAttribute(.foregroundColor, value: presentationData.theme.contextMenu.primaryColor.cgColor, range: NSRange(location: 0, length: updatedAttributedText.length)) + self.textNode.attributedText = updatedAttributedText + } + } + + @objc private func buttonPressed() { + self.performAction() + } + + func canBeHighlighted() -> Bool { + return true + } + + func setIsHighlighted(_ value: Bool) { + } + + func updateIsHighlighted(isHighlighted: Bool) { + self.setIsHighlighted(isHighlighted) + } + + func performAction() { + guard let controller = self.getController() else { + return + } + self.item.action(controller, { [weak self] result in + self?.actionSelected(result) + }) + } +} diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoCoverComponent/Sources/PeerInfoGiftsCoverComponent.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoCoverComponent/Sources/PeerInfoGiftsCoverComponent.swift index 6a1135e1..02aa6d2b 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoCoverComponent/Sources/PeerInfoGiftsCoverComponent.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoCoverComponent/Sources/PeerInfoGiftsCoverComponent.swift @@ -504,7 +504,7 @@ private class GiftIconLayer: SimpleLayer { file = gift.file case let .unique(gift): for attribute in gift.attributes { - if case let .model(_, fileValue, _) = attribute { + if case let .model(_, fileValue, _, _) = attribute { file = fileValue } else if case let .backdrop(_, _, innerColor, _, _, _, _) = attribute { color = UIColor(rgb: UInt32(bitPattern: innerColor)) @@ -570,7 +570,7 @@ private class GiftIconLayer: SimpleLayer { file = gift.file case let .unique(gift): for attribute in gift.attributes { - if case let .model(_, fileValue, _) = attribute { + if case let .model(_, fileValue, _, _) = attribute { file = fileValue } else if case let .backdrop(_, _, innerColor, _, _, _, _) = attribute { color = UIColor(rgb: UInt32(bitPattern: innerColor)) diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/BUILD b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/BUILD index 532cde91..0a1ae904 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/BUILD +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/BUILD @@ -1,5 +1,16 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSettingsUI:SGSettingsUI", + "//Swiftgram/SGStrings:SGStrings", + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + + "//Swiftgram/SGRegDate:SGRegDate", + "//Swiftgram/SGRegDateScheme:SGRegDateScheme", + "//Swiftgram/SGDebugUI:SGDebugUI", +] + + swift_library( name = "PeerInfoScreen", module_name = "PeerInfoScreen", @@ -9,7 +20,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/AccountContext", "//submodules/AccountUtils", "//submodules/ActionSheetPeerItem", @@ -173,6 +184,7 @@ swift_library( "//submodules/TelegramUI/Components/AvatarComponent", "//submodules/TelegramUI/Components/AlertComponent/AlertTransferHeaderComponent", "//submodules/TelegramUI/Components/HorizontalTabsComponent", + "//submodules/TelegramUI/Components/PeerInfo/AccountPeerContextItem", ], visibility = [ "//visibility:public", diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoData.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoData.swift index 3f92596c..3a900eb8 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoData.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoData.swift @@ -1,3 +1,5 @@ +import SGRegDateScheme +import SGRegDate import Foundation import UIKit import Postbox @@ -383,6 +385,8 @@ final class PeerInfoPersonalChannelData: Equatable { } final class PeerInfoScreenData { + let regDate: RegDate? + let channelCreationTimestamp: Int32? let peer: Peer? let chatPeer: Peer? let savedMessagesPeer: Peer? @@ -437,6 +441,8 @@ final class PeerInfoScreenData { } init( + regDate: RegDate? = nil, + channelCreationTimestamp: Int32? = nil, peer: Peer?, chatPeer: Peer?, savedMessagesPeer: Peer?, @@ -480,6 +486,8 @@ final class PeerInfoScreenData { savedMusicContext: ProfileSavedMusicContext?, savedMusicState: ProfileSavedMusicContext.State? ) { + self.regDate = regDate + self.channelCreationTimestamp = channelCreationTimestamp self.peer = peer self.chatPeer = chatPeer self.savedMessagesPeer = savedMessagesPeer @@ -937,6 +945,7 @@ func peerInfoScreenSettingsData(context: AccountContext, peerId: EnginePeer.Id, combineLatest(notificationExceptions, notificationsAuthorizationStatus.get(), notificationsWarningSuppressed.get()), combineLatest(context.account.viewTracker.featuredStickerPacks(), archivedStickerPacks), hasPassport, + (context.watchManager?.watchAppInstalled ?? .single(false)), context.account.postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]), context.engine.notices.getServerProvidedSuggestions(), context.engine.data.get( @@ -955,7 +964,7 @@ func peerInfoScreenSettingsData(context: AccountContext, peerId: EnginePeer.Id, starsState, tonState ) - |> map { peerView, accountsAndPeers, accountSessions, privacySettings, sharedPreferences, notifications, stickerPacks, hasPassport, accountPreferences, suggestions, limits, hasPassword, isPowerSavingEnabled, hasStories, bots, personalChannel, starsState, tonState -> PeerInfoScreenData in + |> map { peerView, accountsAndPeers, accountSessions, privacySettings, sharedPreferences, notifications, stickerPacks, hasPassport, hasWatchApp, accountPreferences, suggestions, limits, hasPassword, isPowerSavingEnabled, hasStories, bots, personalChannel, starsState, tonState -> PeerInfoScreenData in let (notificationExceptions, notificationsAuthorizationStatus, notificationsWarningSuppressed) = notifications let (featuredStickerPacks, archivedStickerPacks) = stickerPacks @@ -968,6 +977,10 @@ func peerInfoScreenSettingsData(context: AccountContext, peerId: EnginePeer.Id, var enableQRLogin = false let appConfiguration = accountPreferences.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) + // MARK: Swiftgram + if let appConfiguration, appConfiguration.sgWebSettings.global.qrLogin { + enableQRLogin = true + } if let appConfiguration, let data = appConfiguration.data, let enableQR = data["qr_login_camera"] as? Bool, enableQR { enableQRLogin = true } @@ -998,7 +1011,7 @@ func peerInfoScreenSettingsData(context: AccountContext, peerId: EnginePeer.Id, userLimits: peer?.isPremium == true ? limits.1 : limits.0, bots: bots, hasPassport: hasPassport, - hasWatchApp: false, + hasWatchApp: hasWatchApp, enableQRLogin: enableQRLogin ) @@ -1443,6 +1456,7 @@ func peerInfoScreenData( let savedMusicContext = ProfileSavedMusicContext(account: context.account, peerId: peerId) return combineLatest( + Signal.single(nil) |> then (getRegDate(context: context, peerId: peerId.id._internalGetInt64Value())), context.account.viewTracker.peerView(peerId, updateData: true), peerInfoAvailableMediaPanes(context: context, peerId: peerId, chatLocation: chatLocation, isMyProfile: isMyProfile, chatLocationContextHolder: chatLocationContextHolder, sharedMediaFromForumTopic: sharedMediaFromForumTopic), context.engine.data.subscribe(TelegramEngine.EngineData.Item.NotificationSettings.Global()), @@ -1465,7 +1479,7 @@ func peerInfoScreenData( webAppPermissions, savedMusicContext.state ) - |> map { peerView, availablePanes, globalNotificationSettings, encryptionKeyFingerprint, status, hasStories, hasStoryArchive, recommendedBots, accountIsPremium, savedMessagesPeer, hasSavedMessagesChats, hasSavedMessages, hasSavedMessageTags, hasBotPreviewItems, personalChannel, privacySettings, starsRevenueContextAndState, revenueContextAndState, premiumGiftOptions, webAppPermissions, savedMusicState -> PeerInfoScreenData in + |> map { regDate, peerView, availablePanes, globalNotificationSettings, encryptionKeyFingerprint, status, hasStories, hasStoryArchive, recommendedBots, accountIsPremium, savedMessagesPeer, hasSavedMessagesChats, hasSavedMessages, hasSavedMessageTags, hasBotPreviewItems, personalChannel, privacySettings, starsRevenueContextAndState, revenueContextAndState, premiumGiftOptions, webAppPermissions, savedMusicState -> PeerInfoScreenData in var availablePanes = availablePanes if isMyProfile { availablePanes?.insert(.stories, at: 0) @@ -1562,6 +1576,7 @@ func peerInfoScreenData( } return PeerInfoScreenData( + regDate: regDate, peer: peer, chatPeer: peerView.peers[peerId], savedMessagesPeer: savedMessagesPeer?._asPeer(), @@ -1715,6 +1730,7 @@ func peerInfoScreenData( let personalChannel = peerInfoPersonalOrLinkedChannel(context: context, peerId: peerId, isSettings: false) return combineLatest( + getFirstMessage(context: context, peerId: peerId), context.account.viewTracker.peerView(peerId, updateData: true), peerInfoAvailableMediaPanes(context: context, peerId: peerId, chatLocation: chatLocation, isMyProfile: false, chatLocationContextHolder: chatLocationContextHolder, sharedMediaFromForumTopic: sharedMediaFromForumTopic), context.engine.data.subscribe(TelegramEngine.EngineData.Item.NotificationSettings.Global()), @@ -1735,7 +1751,7 @@ func peerInfoScreenData( profileGiftsContext.state, personalChannel ) - |> map { peerView, availablePanes, globalNotificationSettings, status, currentInvitationsContext, invitations, currentRequestsContext, requests, hasStories, accountIsPremium, recommendedChannels, hasSavedMessages, hasSavedMessagesChats, hasSavedMessageTags, isPremiumRequiredForStoryPosting, starsRevenueContextAndState, revenueContextAndState, profileGiftsState, personalChannel -> PeerInfoScreenData in + |> map { firstMessage, peerView, availablePanes, globalNotificationSettings, status, currentInvitationsContext, invitations, currentRequestsContext, requests, hasStories, accountIsPremium, recommendedChannels, hasSavedMessages, hasSavedMessagesChats, hasSavedMessageTags, isPremiumRequiredForStoryPosting, starsRevenueContextAndState, revenueContextAndState, profileGiftsState, personalChannel -> PeerInfoScreenData in var availablePanes = availablePanes if let hasStories { if hasStories { @@ -1807,6 +1823,7 @@ func peerInfoScreenData( } return PeerInfoScreenData( + channelCreationTimestamp: firstMessage?.timestamp, peer: peerView.peers[peerId], chatPeer: peerView.peers[peerId], savedMessagesPeer: nil, @@ -2049,6 +2066,7 @@ func peerInfoScreenData( let isPremiumRequiredForStoryPosting: Signal = isPremiumRequiredForStoryPosting(context: context) return combineLatest(queue: .mainQueue(), + Signal.single(nil) |> then (getFirstMessage(context: context, peerId: peerId)), context.account.viewTracker.peerView(groupId, updateData: true), peerInfoAvailableMediaPanes(context: context, peerId: groupId, chatLocation: chatLocation, isMyProfile: false, chatLocationContextHolder: chatLocationContextHolder, sharedMediaFromForumTopic: sharedMediaFromForumTopic), context.engine.data.subscribe(TelegramEngine.EngineData.Item.NotificationSettings.Global()), @@ -2068,7 +2086,7 @@ func peerInfoScreenData( isPremiumRequiredForStoryPosting, starsRevenueContextAndState ) - |> mapToSignal { peerView, availablePanes, globalNotificationSettings, status, membersData, currentInvitationsContext, invitations, currentRequestsContext, requests, hasStories, threadData, preferencesView, accountIsPremium, hasSavedMessages, hasSavedMessagesChats, hasSavedMessageTags, isPremiumRequiredForStoryPosting, starsRevenueContextAndState -> Signal in + |> mapToSignal { firstMessage, peerView, availablePanes, globalNotificationSettings, status, membersData, currentInvitationsContext, invitations, currentRequestsContext, requests, hasStories, threadData, preferencesView, accountIsPremium, hasSavedMessages, hasSavedMessagesChats, hasSavedMessageTags, isPremiumRequiredForStoryPosting, starsRevenueContextAndState -> Signal in var discussionPeer: Peer? if case let .known(maybeLinkedDiscussionPeerId) = (peerView.cachedData as? CachedChannelData)?.linkedDiscussionPeerId, let linkedDiscussionPeerId = maybeLinkedDiscussionPeerId, let peer = peerView.peers[linkedDiscussionPeerId] { discussionPeer = peer @@ -2142,7 +2160,24 @@ func peerInfoScreenData( let appConfiguration: AppConfiguration = preferencesView.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? .defaultValue + // MARK: Swiftgram + var channelCreationTimestamp = firstMessage?.timestamp + if groupId.namespace == Namespaces.Peer.CloudChannel, let firstMessage { + for media in firstMessage.media { + if let action = media as? TelegramMediaAction { + if case let .channelMigratedFromGroup(_, legacyGroupId) = action.action { + if let legacyGroup = firstMessage.peers[legacyGroupId] as? TelegramGroup { + if legacyGroup.creationDate != 0 { + channelCreationTimestamp = legacyGroup.creationDate + } + } + } + } + } + } + return .single(PeerInfoScreenData( + channelCreationTimestamp: channelCreationTimestamp, peer: peerView.peers[groupId], chatPeer: peerView.peers[groupId], savedMessagesPeer: nil, @@ -2425,8 +2460,8 @@ func peerInfoHeaderButtons(peer: Peer?, cachedData: CachedPeerData?, isOpenedFro result.append(.message) } result.append(.mute) - if case let .broadcast(info) = channel.info, info.flags.contains(.hasMonoforum), !channel.hasPermission(.manageDirect) { - } else if hasDiscussion { + /* /* MARK: Swiftgram */ if case let .broadcast(info) = channel.info, info.flags.contains(.hasMonoforum), !channel.hasPermission(.manageDirect) { + } else*/ if hasDiscussion { result.append(.discussion) } result.append(.search) @@ -2596,3 +2631,20 @@ private func isPremiumRequiredForStoryPosting(context: AccountContext) -> Signal } ) } + + +// MARK: Swiftgram +private func getFirstMessage(context: AccountContext, peerId: PeerId) -> Signal { + return context.engine.messages.getMessagesLoadIfNecessary([MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: 1)]) + |> `catch` { _ in + return .single(.result([])) + } + |> mapToSignal { result -> Signal<[Message], NoError> in + guard case let .result(result) = result else { + return .complete() + } + return .single(result) + } + |> map { $0.first } +} + diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoHeaderNode.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoHeaderNode.swift index d6911343..590cc0c2 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoHeaderNode.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoHeaderNode.swift @@ -28,6 +28,7 @@ import AnimationCache import MultiAnimationRenderer import ComponentDisplayAdapters import ChatTitleView +import SGSimpleSettings import AppBundle import AvatarVideoNode import PeerInfoVisualMediaPaneNode @@ -207,7 +208,7 @@ final class PeerInfoHeaderNode: ASDisplayNode { private var currentStarRating: TelegramStarRating? private var currentPendingStarRating: TelegramStarPendingRating? - init(context: AccountContext, controller: PeerInfoScreenImpl, avatarInitiallyExpanded: Bool, isOpenedFromChat: Bool, isMediaOnly: Bool, isSettings: Bool, isMyProfile: Bool, forumTopicThreadId: Int64?, chatLocation: ChatLocation) { + init(hidePhoneInSettings: Bool = false, context: AccountContext, controller: PeerInfoScreenImpl, avatarInitiallyExpanded: Bool, isOpenedFromChat: Bool, isMediaOnly: Bool, isSettings: Bool, isMyProfile: Bool, forumTopicThreadId: Int64?, chatLocation: ChatLocation) { self.context = context self.controller = controller self.isAvatarExpanded = avatarInitiallyExpanded @@ -1236,11 +1237,15 @@ final class PeerInfoHeaderNode: ASDisplayNode { smallTitleAttributes = MultiScaleTextState.Attributes(font: Font.medium(28.0), color: .white, shadowColor: titleShadowColor) if self.isSettings, let user = peer as? TelegramUser { - var subtitle = formatPhoneNumber(context: self.context, number: user.phone ?? "") - - if let mainUsername = user.addressName, !mainUsername.isEmpty { - subtitle = "\(subtitle) • @\(mainUsername)" + let hidePhoneInSettings = SGSimpleSettings.shared.hidePhoneInSettings + var subtitleComponents: [String] = [] + if !hidePhoneInSettings, let phone = user.phone, !phone.isEmpty { + subtitleComponents.append(formatPhoneNumber(context: self.context, number: phone)) } + if let mainUsername = user.addressName, !mainUsername.isEmpty { + subtitleComponents.append("@\(mainUsername)") + } + let subtitle = subtitleComponents.joined(separator: " • ") subtitleStringText = subtitle subtitleAttributes = MultiScaleTextState.Attributes(font: Font.regular(17.0), color: .white) smallSubtitleAttributes = MultiScaleTextState.Attributes(font: Font.regular(16.0), color: .white, shadowColor: titleShadowColor) @@ -2859,4 +2864,3 @@ final class PeerInfoHeaderNode: ASDisplayNode { transition.updateAnchorPoint(layer: self.avatarListNode.maskNode.layer, anchorPoint: maskAnchorPoint) } } - diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoInteraction.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoInteraction.swift index d92de16e..643662cc 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoInteraction.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoInteraction.swift @@ -9,6 +9,7 @@ import AccountContext import StatisticsUI final class PeerInfoInteraction { + let notifyTextCopied: () -> Void let openChat: (EnginePeer.Id?) -> Void let openUsername: (String, Bool, Promise?) -> Void let openPhone: (String, ASDisplayNode, ContextGesture?, Promise?) -> Void @@ -85,6 +86,7 @@ final class PeerInfoInteraction { let getController: () -> ViewController? init( + notifyTextCopied: @escaping () -> Void, openUsername: @escaping (String, Bool, Promise?) -> Void, openPhone: @escaping (String, ASDisplayNode, ContextGesture?, Promise?) -> Void, editingOpenNotificationSettings: @escaping () -> Void, @@ -160,6 +162,7 @@ final class PeerInfoInteraction { displayAutoTranslateLocked: @escaping () -> Void, getController: @escaping () -> ViewController? ) { + self.notifyTextCopied = notifyTextCopied self.openUsername = openUsername self.openPhone = openPhone self.editingOpenNotificationSettings = editingOpenNotificationSettings diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoPaneContainerNode.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoPaneContainerNode.swift index 152ed248..58291000 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoPaneContainerNode.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoPaneContainerNode.swift @@ -129,7 +129,7 @@ private final class GiftsTabItemComponent: Component { file = gift.file case let .unique(gift): for attribute in gift.attributes { - if case let .model(_, fileValue, _) = attribute { + if case let .model(_, fileValue, _, _) = attribute { file = fileValue } } @@ -270,7 +270,7 @@ final class PeerInfoPaneTabsContainerPaneNode: ASDisplayNode { file = gift.file case let .unique(gift): for attribute in gift.attributes { - if case let .model(_, fileValue, _) = attribute { + if case let .model(_, fileValue, _, _) = attribute { file = fileValue } } @@ -653,7 +653,7 @@ final class PeerInfoPaneContainerNode: ASDisplayNode, ASGestureRecognizerDelegat private let initialPaneKey: PeerInfoPaneKey? - init(context: AccountContext, updatedPresentationData: (initial: PresentationData, signal: Signal)?, peerId: PeerId, chatLocation: ChatLocation, sharedMediaFromForumTopic: (EnginePeer.Id, Int64)?, chatLocationContextHolder: Atomic, isMediaOnly: Bool, initialPaneKey: PeerInfoPaneKey?, initialStoryFolderId: Int64?, initialGiftCollectionId: Int64?) { + init(context: AccountContext, updatedPresentationData: (initial: PresentationData, signal: Signal)?, peerId: PeerId, chatLocation: ChatLocation, sharedMediaFromForumTopic: (EnginePeer.Id, Int64)?, chatLocationContextHolder: Atomic, isMediaOnly: Bool, initialPaneKey: PeerInfoPaneKey?, initialStoryFolderId: Int64?, initialGiftCollectionId: Int64?, switchToMediaTarget: PeerInfoSwitchToMediaTarget? = nil) { self.context = context self.updatedPresentationData = updatedPresentationData self.peerId = peerId diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoProfileItems.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoProfileItems.swift index abde525b..53398cd9 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoProfileItems.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoProfileItems.swift @@ -1,3 +1,8 @@ +// MARK: Swiftgram +import SGSimpleSettings +import SGSettingsUI +import SGStrings +import CountrySelectionUI import Foundation import UIKit import Display @@ -19,9 +24,10 @@ import PeerNameColorItem import BoostLevelIconComponent private let enabledPublicBioEntities: EnabledEntityTypes = [.allUrl, .mention, .hashtag] -private let enabledPrivateBioEntities: EnabledEntityTypes = [.internalUrl, .mention, .hashtag] +private let enabledPrivateBioEntities: EnabledEntityTypes = [.allUrl, .mention, .hashtag] // MARK: Swiftgram enum InfoSection: Int, CaseIterable { + case swiftgram case groupLocation case calls case personalChannel @@ -35,12 +41,19 @@ enum InfoSection: Int, CaseIterable { case botAffiliateProgram } -func infoItems(data: PeerInfoScreenData?, context: AccountContext, presentationData: PresentationData, interaction: PeerInfoInteraction, nearbyPeerDistance: Int32?, reactionSourceMessageId: MessageId?, callMessages: [Message], chatLocation: ChatLocation, isOpenedFromChat: Bool, isMyProfile: Bool) -> [(AnyHashable, [PeerInfoScreenItem])] { +func infoItems(nearestChatParticipant: (String?, Int32?), showProfileId: Bool, data: PeerInfoScreenData?, context: AccountContext, presentationData: PresentationData, interaction: PeerInfoInteraction, nearbyPeerDistance: Int32?, reactionSourceMessageId: MessageId?, callMessages: [Message], chatLocation: ChatLocation, isOpenedFromChat: Bool, isMyProfile: Bool) -> [(AnyHashable, [PeerInfoScreenItem])] { guard let data = data else { return [] } var currentPeerInfoSection: InfoSection = .peerInfo + + // MARK: Swiftgram + var sgItemId = 0 + var idText = "" + var isMutualContact = false + // var isUser = false + // let lang = presentationData.strings.baseLanguageCode var items: [InfoSection: [PeerInfoScreenItem]] = [:] for section in InfoSection.allCases { @@ -98,6 +111,11 @@ func infoItems(data: PeerInfoScreenData?, context: AccountContext, presentationD let ItemBotAddToChatInfo = 9003 let ItemVerification = 9004 + // MARK: Swiftgram + isMutualContact = user.flags.contains(.mutualContact) + idText = String(user.id.id._internalGetInt64Value()) +// isUser = true + if !callMessages.isEmpty { items[.calls]!.append(PeerInfoScreenCallListItem(id: ItemCallList, messages: callMessages)) } @@ -122,7 +140,7 @@ func infoItems(data: PeerInfoScreenData?, context: AccountContext, presentationD })) } - if let phone = user.phone { + if let phone = user.phone, !(SGSimpleSettings.shared.hidePhoneInSettings && isMyProfile) { let formattedPhone = formatPhoneNumber(context: context, number: phone) let label: String if formattedPhone.hasPrefix("+888 ") { @@ -516,6 +534,10 @@ func infoItems(data: PeerInfoScreenData?, context: AccountContext, presentationD } } } else if let channel = data.peer as? TelegramChannel { + // MARK: Swiftgram + idText = "-100" + String(channel.id.id._internalGetInt64Value()) + let ItemSGRecentActions = 20 + let ItemUsername = 1 let ItemUsernameInfo = 2 let ItemAbout = 3 @@ -681,7 +703,7 @@ func infoItems(data: PeerInfoScreenData?, context: AccountContext, presentationD if case .broadcast = channel.info { var canEditMembers = false - if channel.hasPermission(.banMembers) { + if channel.adminRights != nil || channel.flags.contains(.isCreator) { // MARK: Swiftgram canEditMembers = true } if canEditMembers { @@ -763,6 +785,14 @@ func infoItems(data: PeerInfoScreenData?, context: AccountContext, presentationD items[section]!.append(PeerInfoScreenDisclosureItem(id: ItemEdit, label: .none, text: settingsTitle, icon: UIImage(bundleImageName: "Chat/Info/SettingsIcon"), action: { interaction.openEditing() })) + + // MARK: Swiftgram + if channel.hasPermission(.banMembers) || channel.flags.contains(.isCreator) { + items[section]!.append(PeerInfoScreenDisclosureItem(id: ItemSGRecentActions, label: .none, text: presentationData.strings.Group_Info_AdminLog, icon: UIImage(bundleImageName: "Chat/Info/RecentActionsIcon"), action: { + interaction.openRecentActions() + })) + } + // } if channel.hasPermission(.manageDirect), let personalChannel = data.personalChannel { @@ -782,6 +812,9 @@ func infoItems(data: PeerInfoScreenData?, context: AccountContext, presentationD } } } else if let group = data.peer as? TelegramGroup { + // MARK: Swiftgram + idText = String(group.id.id._internalGetInt64Value()) + if let cachedData = data.cachedData as? CachedGroupData { let aboutText: String? if group.isFake { @@ -852,6 +885,139 @@ func infoItems(data: PeerInfoScreenData?, context: AccountContext, presentationD } } + // MARK: Swiftgram + if showProfileId { + items[.swiftgram]!.append(PeerInfoScreenLabeledValueItem(id: sgItemId, label: "id: \(idText)", text: "", textColor: .primary, action: nil, longTapAction: { sourceNode in + interaction.openPeerInfoContextMenu(.copy(idText), sourceNode, nil) + }, requestLayout: { _ in + interaction.requestLayout(false) + })) + sgItemId += 1 + } + + if SGSimpleSettings.shared.showDC { + var dcId: Int? = nil +// var dcLocation: String = "" + var phoneCountryText = "" + + var dcLabel = "" + var dcText: String = "" + + if let cachedData = data.cachedData as? CachedUserData, let phoneCountry = cachedData.peerStatusSettings?.phoneCountry { + var countryName = "" + let countriesConfiguration = context.currentCountriesConfiguration.with { $0 } + if let country = countriesConfiguration.countries.first(where: { $0.id == phoneCountry }) { + countryName = country.localizedName ?? country.name + } else if phoneCountry == "FT" { + countryName = presentationData.strings.Chat_NonContactUser_AnonymousNumber + } else if phoneCountry == "TS" { + countryName = "Test" + } + phoneCountryText = emojiFlagForISOCountryCode(phoneCountry) + " " + countryName + } + if let peer = data.peer, let smallProfileImage = peer.smallProfileImage, let cloudResource = smallProfileImage.resource as? CloudPeerPhotoSizeMediaResource { + dcId = cloudResource.datacenterId + +// switch (dcId) { +// case 1: +// dcLocation = "Miami" +// case 2: +// dcLocation = "Amsterdam" +// case 3: +// dcLocation = "Miami" +// case 4: +// dcLocation = "Amsterdam" +// case 5: +// dcLocation = "Singapore" +// default: +// break +// } + } + + if let dcId = dcId { + dcLabel = "dc: \(dcId)" + if phoneCountryText.isEmpty { +// if !dcLocation.isEmpty { +// dcLabel += " \(dcLocation)" +// } + } else { + dcText = "\(phoneCountryText)" + } + } else if !phoneCountryText.isEmpty { + dcLabel = "dc: ?" + dcText = phoneCountryText + } + + if !dcText.isEmpty || !dcLabel.isEmpty { + items[.swiftgram]!.append(PeerInfoScreenLabeledValueItem(id: sgItemId, label: dcLabel, text: dcText, textColor: .primary, action: nil, longTapAction: { sourceNode in + interaction.openPeerInfoContextMenu(.aboutDC, sourceNode, nil) + }, requestLayout: { _ in + interaction.requestLayout(false) + })) + sgItemId += 1 + } + } + + if SGSimpleSettings.shared.showCreationDate { + if let channelCreationTimestamp = data.channelCreationTimestamp { + let creationDateString = stringForDate(timestamp: channelCreationTimestamp, strings: presentationData.strings) + items[.swiftgram]!.append(PeerInfoScreenLabeledValueItem(id: sgItemId, label: i18n("Chat.Created", presentationData.strings.baseLanguageCode, creationDateString), text: "", action: nil, longTapAction: { sourceNode in + interaction.openPeerInfoContextMenu(.copy(creationDateString), sourceNode, nil) + }, requestLayout: { _ in + interaction.requestLayout(false) + })) + sgItemId += 1 + } + } + + if let invitedAt = nearestChatParticipant.1 { + let joinedDateString = stringForDate(timestamp: invitedAt, strings: presentationData.strings) + items[.swiftgram]!.append(PeerInfoScreenLabeledValueItem(id: sgItemId, label: i18n("Chat.JoinedDateTitle", presentationData.strings.baseLanguageCode, nearestChatParticipant.0 ?? "chat") , text: joinedDateString, action: nil, longTapAction: { sourceNode in + interaction.openPeerInfoContextMenu(.copy(joinedDateString), sourceNode, nil) + }, requestLayout: { _ in + interaction.requestLayout(false) + })) + sgItemId += 1 + } + + if SGSimpleSettings.shared.showRegDate { + var regDateString = "" + if let cachedData = data.cachedData as? CachedUserData, let registrationDate = cachedData.peerStatusSettings?.registrationDate { + let components = registrationDate.components(separatedBy: ".") + if components.count == 2, let first = Int32(components[0]), let second = Int32(components[1]) { + let month = first - 1 + let year = second - 1900 + regDateString = stringForMonth(strings: presentationData.strings, month: month, ofYear: year) + } + } + if let regDate = data.regDate, regDateString.isEmpty { + let regTimestamp = Int32((regDate.from + regDate.to) / 2) + switch (context.currentAppConfiguration.with { $0 }.sgWebSettings.global.regdateFormat) { + case "year": + regDateString = stringForDateWithoutDayAndMonth(date: Date(timeIntervalSince1970: Double(regTimestamp)), strings: presentationData.strings) + case "month": + regDateString = stringForDateWithoutDay(date: Date(timeIntervalSince1970: Double(regTimestamp)), strings: presentationData.strings) + default: + regDateString = stringForDate(timestamp: regTimestamp, strings: presentationData.strings) + } + } + if !regDateString.isEmpty { + items[.swiftgram]!.append(PeerInfoScreenLabeledValueItem(id: sgItemId, label: i18n("Chat.RegDate", presentationData.strings.baseLanguageCode), text: regDateString, action: nil, longTapAction: { sourceNode in + interaction.openPeerInfoContextMenu(.copy(regDateString), sourceNode, nil) + }, requestLayout: { _ in + interaction.requestLayout(false) + })) + sgItemId += 1 + } + } + if isMutualContact { + items[.swiftgram]!.append(PeerInfoScreenLabeledValueItem(id: sgItemId, label: i18n("MutualContact.Label", presentationData.strings.baseLanguageCode), text: "", action: nil, longTapAction: { _ in }, requestLayout: { _ in + interaction.requestLayout(false) + })) + sgItemId += 1 + } + + var result: [(AnyHashable, [PeerInfoScreenItem])] = [] for section in InfoSection.allCases { if let sectionItems = items[section], !sectionItems.isEmpty { @@ -1226,7 +1392,7 @@ func editingItems(data: PeerInfoScreenData?, boostStatus: ChannelBoostStatus?, s } var canEditMembers = false - if channel.hasPermission(.banMembers) && (channel.adminRights != nil || channel.flags.contains(.isCreator)) { + if /*channel.hasPermission(.banMembers) &&*/ (channel.adminRights != nil || channel.flags.contains(.isCreator)) { // MARK: Swiftgram canEditMembers = true } if canEditMembers { diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift index 379ed713..a91f04dc 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift @@ -1,3 +1,9 @@ +// MARK: Swiftgram +import SGDebugUI +import SGSimpleSettings +import SGSettingsUI +import SGStrings +import CountrySelectionUI import Foundation import UIKit import Display @@ -114,6 +120,7 @@ import GiftViewScreen import PeerMessagesMediaPlaylist import EdgeEffect import Pasteboard +import AccountPeerContextItem public enum PeerInfoAvatarEditingMode { case generic @@ -144,6 +151,8 @@ enum PeerInfoMemberAction { } enum PeerInfoContextSubject { + case copy(String) + case aboutDC case bio case phone(String) case link(customLink: String?) @@ -153,6 +162,9 @@ enum PeerInfoContextSubject { } enum PeerInfoSettingsSection { + case swiftgram + case swiftgramPro + case ghostgram case avatar case edit case proxy @@ -188,7 +200,6 @@ enum PeerInfoSettingsSection { case premiumManagement case stars case ton - case ghostgram } enum PeerInfoReportType { @@ -213,13 +224,14 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro let chatLocation: ChatLocation let chatLocationContextHolder: Atomic let switchToStoryFolder: Int64? + let switchToMediaTarget: PeerInfoSwitchToMediaTarget? let switchToGiftsTarget: PeerInfoSwitchToGiftsTarget? let sharedMediaFromForumTopic: (EnginePeer.Id, Int64)? let isSettings: Bool let isMyProfile: Bool let isMediaOnly: Bool - let initialExpandPanes: Bool + var initialExpandPanes: Bool private(set) var presentationData: PresentationData @@ -229,6 +241,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro let edgeEffectView: EdgeEffectView let headerNode: PeerInfoHeaderNode + var underHeaderContentsAlpha: CGFloat = 1.0 var regularSections: [AnyHashable: PeerInfoScreenItemSectionContainerNode] = [:] var editingSections: [AnyHashable: PeerInfoScreenItemSectionContainerNode] = [:] let paneContainerNode: PeerInfoPaneContainerNode @@ -262,6 +275,8 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro let enqueueMediaMessageDisposable = MetaDisposable() private(set) var validLayout: (ContainerViewLayout, CGFloat)? + private(set) var nearestChatParticipant: (String?, Int32?) = (nil, nil) + private(set) var showProfileId: Bool = SGSimpleSettings.shared.showProfileId // MARK: Swiftgram private(set) var data: PeerInfoScreenData? var state = PeerInfoState( @@ -311,7 +326,9 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro let twoStepAuthData = Promise(nil) let supportPeerDisposable = MetaDisposable() let tipsPeerDisposable = MetaDisposable() + let cachedFaq = Promise(nil) + var didSetCachedFaq = false weak var copyProtectionTooltipController: TooltipController? weak var emojiStatusSelectionController: ViewController? @@ -343,7 +360,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro } private var didSetReady = false - init(controller: PeerInfoScreenImpl, context: AccountContext, peerId: PeerId, avatarInitiallyExpanded: Bool, isOpenedFromChat: Bool, nearbyPeerDistance: Int32?, reactionSourceMessageId: MessageId?, callMessages: [Message], isSettings: Bool, isMyProfile: Bool, hintGroupInCommon: PeerId?, requestsContext: PeerInvitationImportersContext?, profileGiftsContext: ProfileGiftsContext?, starsContext: StarsContext?, tonContext: StarsContext?, chatLocation: ChatLocation, chatLocationContextHolder: Atomic, switchToGiftsTarget: PeerInfoSwitchToGiftsTarget?, switchToStoryFolder: Int64?, initialPaneKey: PeerInfoPaneKey?, sharedMediaFromForumTopic: (EnginePeer.Id, Int64)?) { + init(hidePhoneInSettings: Bool /* MARK: Swiftgram */, controller: PeerInfoScreenImpl, context: AccountContext, peerId: PeerId, avatarInitiallyExpanded: Bool, isOpenedFromChat: Bool, nearbyPeerDistance: Int32?, reactionSourceMessageId: MessageId?, callMessages: [Message], isSettings: Bool, isMyProfile: Bool, hintGroupInCommon: PeerId?, requestsContext: PeerInvitationImportersContext?, profileGiftsContext: ProfileGiftsContext?, starsContext: StarsContext?, tonContext: StarsContext?, chatLocation: ChatLocation, chatLocationContextHolder: Atomic, switchToGiftsTarget: PeerInfoSwitchToGiftsTarget?, switchToStoryFolder: Int64?, switchToMediaTarget: PeerInfoSwitchToMediaTarget?, initialPaneKey: PeerInfoPaneKey?, sharedMediaFromForumTopic: (EnginePeer.Id, Int64)?) { self.controller = controller self.context = context self.peerId = peerId @@ -360,6 +377,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro self.isMediaOnly = context.account.peerId == peerId && !isSettings && !isMyProfile self.initialExpandPanes = initialPaneKey != nil self.switchToStoryFolder = switchToStoryFolder + self.switchToMediaTarget = switchToMediaTarget self.switchToGiftsTarget = switchToGiftsTarget self.sharedMediaFromForumTopic = sharedMediaFromForumTopic @@ -373,7 +391,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro if case let .replyThread(message) = chatLocation { forumTopicThreadId = message.threadId } - self.headerNode = PeerInfoHeaderNode(context: context, controller: controller, avatarInitiallyExpanded: avatarInitiallyExpanded, isOpenedFromChat: isOpenedFromChat, isMediaOnly: self.isMediaOnly, isSettings: isSettings, isMyProfile: isMyProfile, forumTopicThreadId: forumTopicThreadId, chatLocation: self.chatLocation) + self.headerNode = PeerInfoHeaderNode(hidePhoneInSettings: hidePhoneInSettings, context: context, controller: controller, avatarInitiallyExpanded: avatarInitiallyExpanded, isOpenedFromChat: isOpenedFromChat, isMediaOnly: self.isMediaOnly, isSettings: isSettings, isMyProfile: isMyProfile, forumTopicThreadId: forumTopicThreadId, chatLocation: self.chatLocation) var switchToGiftCollection: Int64? switch switchToGiftsTarget { @@ -383,13 +401,17 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro break } - self.paneContainerNode = PeerInfoPaneContainerNode(context: context, updatedPresentationData: controller.updatedPresentationData, peerId: peerId, chatLocation: chatLocation, sharedMediaFromForumTopic: sharedMediaFromForumTopic, chatLocationContextHolder: chatLocationContextHolder, isMediaOnly: self.isMediaOnly, initialPaneKey: initialPaneKey, initialStoryFolderId: switchToStoryFolder, initialGiftCollectionId: switchToGiftCollection) + self.paneContainerNode = PeerInfoPaneContainerNode(context: context, updatedPresentationData: controller.updatedPresentationData, peerId: peerId, chatLocation: chatLocation, sharedMediaFromForumTopic: sharedMediaFromForumTopic, chatLocationContextHolder: chatLocationContextHolder, isMediaOnly: self.isMediaOnly, initialPaneKey: initialPaneKey, initialStoryFolderId: switchToStoryFolder, initialGiftCollectionId: switchToGiftCollection, switchToMediaTarget: switchToMediaTarget) super.init() self.paneContainerNode.parentController = controller self._interaction = PeerInfoInteraction( + notifyTextCopied: { [weak self] in + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + self?.controller?.present(UndoOverlayController(presentationData: presentationData, content: .copy(text: presentationData.strings.Conversation_TextCopied), elevatedLayout: false, animateInAsReplacement: false, action: { _ in return false }), in: .current) + }, openUsername: { [weak self] value, isMainUsername, progress in self?.openUsername(value: value, isMainUsername: isMainUsername, progress: progress) }, @@ -851,7 +873,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro }))) } - let controller = ContextController(presentationData: strongSelf.presentationData, source: .extracted(MessageContextExtractedContentSource(sourceNode: node)), items: .single(ContextController.Items(content: .list(items))), recognizer: nil, gesture: gesture) + let controller = makeContextController(presentationData: strongSelf.presentationData, source: .extracted(MessageContextExtractedContentSource(sourceNode: node)), items: .single(ContextController.Items(content: .list(items))), recognizer: nil, gesture: gesture) strongSelf.controller?.window?.presentInGlobalOverlay(controller) }) }, openMessageReactionContextMenu: { _, _, _, _ in @@ -1007,7 +1029,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro switch previewData { case let .gallery(gallery): gallery.setHintWillBePresentedInPreviewingContext(true) - let contextController = ContextController(presentationData: strongSelf.presentationData, source: .controller(ContextControllerContentSourceImpl(controller: gallery, sourceNode: node, sourceRect: rect)), items: items |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) + let contextController = makeContextController(presentationData: strongSelf.presentationData, source: .controller(ContextControllerContentSourceImpl(controller: gallery, sourceNode: node, sourceRect: rect)), items: items |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) strongSelf.controller?.presentInGlobalOverlay(contextController) case .instantPage: break @@ -1294,7 +1316,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro })) ] } - let contextController = ContextController(presentationData: presentationData, source: .controller(ContextControllerContentSourceImpl(controller: chatController, sourceNode: node, passthroughTouches: true)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) + let contextController = makeContextController(presentationData: presentationData, source: .controller(ContextControllerContentSourceImpl(controller: chatController, sourceNode: node, passthroughTouches: true)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) controller.presentInGlobalOverlay(contextController) } @@ -1590,35 +1612,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro strongSelf.controller?.push(controller) } } else { - (strongSelf.controller?.parent as? TabBarController)?.updateIsTabBarHidden(true, transition: .animated(duration: 0.3, curve: .linear)) - strongSelf.state = strongSelf.state.withIsEditing(true) - var updateOnCompletion = false - if strongSelf.headerNode.isAvatarExpanded { - updateOnCompletion = true - strongSelf.headerNode.skipCollapseCompletion = true - strongSelf.headerNode.avatarListNode.avatarContainerNode.canAttachVideo = false - strongSelf.headerNode.editingContentNode.avatarNode.canAttachVideo = false - strongSelf.headerNode.avatarListNode.listContainerNode.isCollapsing = true - strongSelf.headerNode.updateIsAvatarExpanded(false, transition: .immediate) - strongSelf.updateNavigationExpansionPresentation(isExpanded: false, animated: true) - } - if let (layout, navigationHeight) = strongSelf.validLayout { - strongSelf.scrollNode.view.setContentOffset(CGPoint(), animated: false) - strongSelf.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: .immediate, additive: false) - } - UIView.transition(with: strongSelf.view, duration: 0.3, options: [.transitionCrossDissolve], animations: { - }, completion: { _ in - if updateOnCompletion { - strongSelf.headerNode.skipCollapseCompletion = false - strongSelf.headerNode.avatarListNode.listContainerNode.isCollapsing = false - strongSelf.headerNode.avatarListNode.avatarContainerNode.canAttachVideo = true - strongSelf.headerNode.editingContentNode.avatarNode.canAttachVideo = true - strongSelf.headerNode.editingContentNode.avatarNode.reset() - if let (layout, navigationHeight) = strongSelf.validLayout { - strongSelf.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: .immediate, additive: false) - } - } - }) + strongSelf.activateEdit() } case .done, .cancel: strongSelf.view.endEditing(true) @@ -2003,7 +1997,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro UIView.transition(with: strongSelf.view, duration: 0.3, options: [.transitionCrossDissolve], animations: { }, completion: nil) } - (strongSelf.controller?.parent as? TabBarController)?.updateIsTabBarHidden(false, transition: .animated(duration: 0.3, curve: .linear)) + (strongSelf.controller?.parent as? TabBarController)?.updateIsTabBarHidden(SGSimpleSettings.shared.hideTabBar ? true : false, transition: .animated(duration: 0.3, curve: .linear)) case .select: strongSelf.state = strongSelf.state.withSelectedMessageIds(Set()) if let (layout, navigationHeight) = strongSelf.validLayout { @@ -2060,6 +2054,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro guard let self else { return } + self.underHeaderContentsAlpha = alpha if !self.state.isEditing { for (_, section) in self.regularSections { transition.updateAlpha(node: section, alpha: alpha) @@ -2094,9 +2089,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro |> map { data -> Bool in return data?.hasSecretValues ?? false } - - self.cachedFaq.set(.single(nil) |> then(cachedFaqInstantPage(context: self.context) |> map(Optional.init))) - + screenData = peerInfoScreenSettingsData(context: context, peerId: peerId, accountsAndPeers: self.accountsAndPeers.get(), activeSessionsContextAndCount: self.activeSessionsContextAndCount.get(), notificationExceptions: self.notificationExceptions.get(), privacySettings: self.privacySettings.get(), archivedStickerPacks: self.archivedPacks.get(), hasPassport: hasPassport, starsContext: starsContext, tonContext: tonContext) @@ -2326,7 +2319,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro }, synchronousLoad: true) galleryController.setHintWillBePresentedInPreviewingContext(true) - let contextController = ContextController(presentationData: strongSelf.presentationData, source: .controller(ContextControllerContentSourceImpl(controller: galleryController, sourceNode: node)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) + let contextController = makeContextController(presentationData: strongSelf.presentationData, source: .controller(ContextControllerContentSourceImpl(controller: galleryController, sourceNode: node)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) strongSelf.controller?.presentInGlobalOverlay(contextController) } @@ -2456,14 +2449,29 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro self?.updateNavigation(transition: .immediate, additive: true, animateHeader: true) } + let nearestChatParticipantSignal = .single((nil, nil)) |> then(self.fetchNearestChatParticipant()) |> distinctUntilChanged { lhs, rhs in + if lhs.0 != rhs.0 { + return false + } + if lhs.1 != rhs.1 { + return false + } + return true + } + self.dataDisposable = combineLatest( queue: Queue.mainQueue(), + nearestChatParticipantSignal, screenData, self.forceIsContactPromise.get() - ).startStrict(next: { [weak self] data, forceIsContact in + ).startStrict(next: { [weak self] nearestChatParticipant, data, forceIsContact in guard let strongSelf = self else { return } + // MARK: Swiftgram + strongSelf.showProfileId = SGSimpleSettings.shared.showProfileId + // + strongSelf.nearestChatParticipant = nearestChatParticipant if data.isContact && forceIsContact { strongSelf.forceIsContactPromise.set(false) } else { @@ -2645,6 +2653,38 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro var canAttachVideo: Bool? + func activateEdit() { + (self.controller?.parent as? TabBarController)?.updateIsTabBarHidden(true, transition: .animated(duration: 0.3, curve: .linear)) + self.state = self.state.withIsEditing(true) + var updateOnCompletion = false + if self.headerNode.isAvatarExpanded { + updateOnCompletion = true + self.headerNode.skipCollapseCompletion = true + self.headerNode.avatarListNode.avatarContainerNode.canAttachVideo = false + self.headerNode.editingContentNode.avatarNode.canAttachVideo = false + self.headerNode.avatarListNode.listContainerNode.isCollapsing = true + self.headerNode.updateIsAvatarExpanded(false, transition: .immediate) + self.updateNavigationExpansionPresentation(isExpanded: false, animated: true) + } + if let (layout, navigationHeight) = self.validLayout { + self.scrollNode.view.setContentOffset(CGPoint(), animated: false) + self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: .immediate, additive: false) + } + UIView.transition(with: self.view, duration: 0.3, options: [.transitionCrossDissolve], animations: { + }, completion: { _ in + if updateOnCompletion { + self.headerNode.skipCollapseCompletion = false + self.headerNode.avatarListNode.listContainerNode.isCollapsing = false + self.headerNode.avatarListNode.avatarContainerNode.canAttachVideo = true + self.headerNode.editingContentNode.avatarNode.canAttachVideo = true + self.headerNode.editingContentNode.avatarNode.reset() + if let (layout, navigationHeight) = self.validLayout { + self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: .immediate, additive: false) + } + } + }) + } + private func updateData(_ data: PeerInfoScreenData) { let previousData = self.data var previousMemberCount: Int? @@ -2820,6 +2860,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro self.ignoreScrolling = true transition.updateBounds(node: self.scrollNode, bounds: CGRect(origin: CGPoint(x: 0.0, y: paneAreaExpansionFinalPoint), size: self.scrollNode.bounds.size)) self.ignoreScrolling = false + self.headerNode.headerEdgeEffectContainer.center = CGPoint(x: 0.0, y: self.scrollNode.view.contentOffset.y) self.updateNavigation(transition: transition, additive: false, animateHeader: true) if let (layout, navigationHeight) = self.validLayout { self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: transition, additive: true) @@ -4111,7 +4152,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro } } - private func openParticipantsSection(section: PeerInfoParticipantsSection) { + public func openParticipantsSection(section: PeerInfoParticipantsSection) { // MARK: Swiftgram guard let data = self.data, let peer = data.peer else { return } @@ -4660,7 +4701,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro } if let rootController = self.context.sharedContext.mainWindow?.viewController as? TelegramRootControllerInterface { - let coordinator = rootController.openStoryCamera(customTarget: self.peerId == self.context.account.peerId ? nil : .peer(self.peerId), resumeLiveStream: false, transitionIn: cameraTransitionIn, transitionedIn: {}, transitionOut: self.storyCameraTransitionOut()) + let coordinator = rootController.openStoryCamera(mode: .photo, customTarget: self.peerId == self.context.account.peerId ? nil : .peer(self.peerId), resumeLiveStream: false, transitionIn: cameraTransitionIn, transitionedIn: {}, transitionOut: self.storyCameraTransitionOut()) coordinator?.animateIn() } case .channelBoostRequired: @@ -4799,35 +4840,57 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro self.headerNode.navigationButtonContainer.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.3, timingFunction: CAMediaTimingFunctionName.easeOut.rawValue) if self.isSettings { + self.setupFaqIfNeeded() + if let settings = self.data?.globalSettings { - self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, mode: .navigation, placeholder: self.presentationData.strings.Settings_Search, hasBackground: true, hasSeparator: true, contentNode: SettingsSearchContainerNode(context: self.context, openResult: { [weak self] result in - if let strongSelf = self, let navigationController = strongSelf.controller?.navigationController as? NavigationController { - result.present(strongSelf.context, navigationController, { [weak self] mode, controller in - if let strongSelf = self { - switch mode { - case .push: - if let controller = controller { - strongSelf.controller?.push(controller) + self.searchDisplayController = SearchDisplayController( + presentationData: self.presentationData, + mode: .navigation, + placeholder: self.presentationData.strings.Settings_Search, + hasBackground: true, + hasSeparator: true, + contentNode: SettingsSearchContainerNode( + context: self.context, + openResult: { [weak self] result in + if let strongSelf = self, let navigationController = strongSelf.controller?.navigationController as? NavigationController { + result.present(strongSelf.context, navigationController, { [weak self] mode, controller in + if let strongSelf = self { + switch mode { + case .push: + if let controller = controller { + strongSelf.controller?.push(controller) + } + case .modal: + if let controller = controller { + strongSelf.controller?.present(controller, in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet, completion: { [weak self] in + self?.deactivateSearch() + })) + } + case .immediate: + if let controller = controller { + strongSelf.controller?.present(controller, in: .window(.root), with: nil) + } + case .dismiss: + strongSelf.deactivateSearch() } - case .modal: - if let controller = controller { - strongSelf.controller?.present(controller, in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet, completion: { [weak self] in - self?.deactivateSearch() - })) - } - case .immediate: - if let controller = controller { - strongSelf.controller?.present(controller, in: .window(.root), with: nil) - } - case .dismiss: - strongSelf.deactivateSearch() - } + } + }) } - }) - } - }, resolvedFaqUrl: self.cachedFaq.get(), exceptionsList: .single(settings.notificationExceptions), archivedStickerPacks: .single(settings.archivedStickerPacks), privacySettings: .single(settings.privacySettings), hasTwoStepAuth: self.hasTwoStepAuth.get(), twoStepAuthData: self.twoStepAccessConfiguration.get(), activeSessionsContext: self.activeSessionsContextAndCount.get() |> map { $0?.0 }, webSessionsContext: self.activeSessionsContextAndCount.get() |> map { $0?.2 }), cancel: { [weak self] in - self?.deactivateSearch() - }, searchBarIsExternal: true) + }, + resolvedFaqUrl: self.cachedFaq.get(), + exceptionsList: .single(settings.notificationExceptions), + archivedStickerPacks: .single(settings.archivedStickerPacks), + privacySettings: .single(settings.privacySettings), + hasTwoStepAuth: self.hasTwoStepAuth.get(), + twoStepAuthData: self.twoStepAccessConfiguration.get(), + activeSessionsContext: self.activeSessionsContextAndCount.get() |> map { $0?.0 }, + webSessionsContext: self.activeSessionsContextAndCount.get() |> map { $0?.2 } + ), + cancel: { [weak self] in + self?.deactivateSearch() + }, + searchBarIsExternal: true + ) } } else if let currentPaneKey = self.paneContainerNode.currentPaneKey, case .members = currentPaneKey { self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, mode: .navigation, placeholder: self.presentationData.strings.Common_Search, hasBackground: true, hasSeparator: true, contentNode: ChannelMembersSearchContainerNode(context: self.context, forceTheme: nil, peerId: self.peerId, mode: .searchMembers, filters: [], searchContext: self.groupMembersSearchContext, openPeer: { [weak self] peer, participant in @@ -4971,8 +5034,10 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro self.searchDisplayController = nil searchDisplayController.deactivate(placeholder: nil) + controller.dismissAllTooltips() + if self.isSettings { - (self.controller?.parent as? TabBarController)?.updateIsTabBarHidden(false, transition: .animated(duration: 0.4, curve: .spring)) + (self.controller?.parent as? TabBarController)?.updateIsTabBarHidden(SGSimpleSettings.shared.hideTabBar ? true : false, transition: .animated(duration: 0.4, curve: .spring)) controller.updateTabBarSearchState(ViewController.TabBarSearchState(isActive: false), transition: .animated(duration: 0.4, curve: .spring)) } @@ -5076,7 +5141,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro let chatController = strongSelf.context.sharedContext.makeChatController(context: strongSelf.context, chatLocation: .peer(id: strongSelf.peerId), subject: .message(id: .id(index.id), highlight: nil, timecode: nil, setupReply: false), botStart: nil, mode: .standard(.previewing), params: nil) chatController.canReadHistory.set(false) - let contextController = ContextController(presentationData: strongSelf.presentationData, source: .controller(ContextControllerContentSourceImpl(controller: chatController, sourceNode: sourceNode, sourceRect: sourceRect, passthroughTouches: true)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) + let contextController = makeContextController(presentationData: strongSelf.presentationData, source: .controller(ContextControllerContentSourceImpl(controller: chatController, sourceNode: sourceNode, sourceRect: sourceRect, passthroughTouches: true)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) strongSelf.controller?.presentInGlobalOverlay(contextController) } ) @@ -5268,7 +5333,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro insets.left += sectionInset insets.right += sectionInset - let items = self.isSettings ? settingsItems(data: self.data, context: self.context, presentationData: self.presentationData, interaction: self.interaction, isExpanded: self.headerNode.isAvatarExpanded) : infoItems(data: self.data, context: self.context, presentationData: self.presentationData, interaction: self.interaction, nearbyPeerDistance: self.nearbyPeerDistance, reactionSourceMessageId: self.reactionSourceMessageId, callMessages: self.callMessages, chatLocation: self.chatLocation, isOpenedFromChat: self.isOpenedFromChat, isMyProfile: self.isMyProfile) + let items = self.isSettings ? settingsItems(showProfileId: self.showProfileId, data: self.data, context: self.context, presentationData: self.presentationData, interaction: self.interaction, isExpanded: self.headerNode.isAvatarExpanded) : infoItems(nearestChatParticipant: self.nearestChatParticipant, showProfileId: self.showProfileId, data: self.data, context: self.context, presentationData: self.presentationData, interaction: self.interaction, nearbyPeerDistance: self.nearbyPeerDistance, reactionSourceMessageId: self.reactionSourceMessageId, callMessages: self.callMessages, chatLocation: self.chatLocation, isOpenedFromChat: self.isOpenedFromChat, isMyProfile: self.isMyProfile) contentHeight += headerHeight if !((self.isSettings || self.isMyProfile) && self.state.isEditing) { @@ -5294,7 +5359,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro if wasAdded && transition.isAnimated && (self.isSettings || self.isMyProfile) && !self.state.isEditing { sectionNode.alpha = 0.0 - transition.updateAlpha(node: sectionNode, alpha: 1.0, delay: 0.1) + transition.updateAlpha(node: sectionNode, alpha: self.underHeaderContentsAlpha, delay: 0.1) } let sectionWidth = layout.size.width - insets.left - insets.right @@ -5313,7 +5378,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro if wasAdded && transition.isAnimated && (self.isSettings || self.isMyProfile) && !self.state.isEditing { } else { - transition.updateAlpha(node: sectionNode, alpha: self.state.isEditing ? 0.0 : 1.0) + transition.updateAlpha(node: sectionNode, alpha: self.state.isEditing ? 0.0 : self.underHeaderContentsAlpha) } if !sectionHeight.isZero && !self.state.isEditing { contentHeight += sectionHeight @@ -5689,7 +5754,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro let navigationBarHeight: CGFloat = !self.isSettings && layout.isModalOverlay ? 68.0 : 60.0 let paneContainerTopInset = navigationBarHeight + (layout.statusBarHeight ?? 0.0) - self.paneContainerNode.update(size: self.paneContainerNode.bounds.size, sideInset: layout.safeInsets.left, topInset: paneContainerTopInset, bottomInset: bottomInset, deviceMetrics: layout.deviceMetrics, visibleHeight: visibleHeight, expansionFraction: effectiveAreaExpansionFraction, presentationData: self.presentationData, data: self.data, areTabsHidden: self.headerNode.customNavigationContentNode != nil, disableTabSwitching: disableTabSwitching, navigationHeight: navigationHeight, transition: transition) + self.paneContainerNode.update(size: self.paneContainerNode.bounds.size, sideInset: layout.safeInsets.left, topInset: paneContainerTopInset, bottomInset: bottomInset, deviceMetrics: layout.deviceMetrics, visibleHeight: visibleHeight, expansionFraction: self.initialExpandPanes ? 1.0 : effectiveAreaExpansionFraction, presentationData: self.presentationData, data: self.data, areTabsHidden: self.headerNode.customNavigationContentNode != nil, disableTabSwitching: disableTabSwitching, navigationHeight: navigationHeight, transition: transition) transition.updateFrame(node: self.headerNode.navigationButtonContainer, frame: CGRect(origin: CGPoint(x: layout.safeInsets.left, y: layout.statusBarHeight ?? 0.0), size: CGSize(width: layout.size.width - layout.safeInsets.left * 2.0, height: navigationBarHeight))) var searchBarContainerY: CGFloat = layout.statusBarHeight ?? 0.0 @@ -5705,6 +5770,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro } else { if self.isSettings { leftNavigationButtons.append(PeerInfoHeaderNavigationButtonSpec(key: .qrCode, isForExpandedView: false)) + if SGSimpleSettings.shared.hideTabBar { leftNavigationButtons.append(PeerInfoHeaderNavigationButtonSpec(key: .back, isForExpandedView: false)) } rightNavigationButtons.append(PeerInfoHeaderNavigationButtonSpec(key: .edit, isForExpandedView: false)) } else if self.isMyProfile { rightNavigationButtons.append(PeerInfoHeaderNavigationButtonSpec(key: .edit, isForExpandedView: false)) @@ -6159,6 +6225,21 @@ public enum PeerInfoSwitchToGiftsTarget { case collection(Int64) } +public struct PeerInfoSwitchToMediaTarget { + public enum Kind { + case photoVideo + case file + } + + public let kind: Kind + public let messageIndex: EngineMessage.Index + + public init(kind: Kind, messageIndex: EngineMessage.Index) { + self.kind = kind + self.messageIndex = messageIndex + } +} + public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortcutResponder { let context: AccountContext let updatedPresentationData: (initial: PresentationData, signal: Signal)? @@ -6179,6 +6260,7 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortc private let switchToGiftsTarget: PeerInfoSwitchToGiftsTarget? private let switchToGroupsInCommon: Bool private let switchToStoryFolder: Int64? + private let switchToMediaTarget: PeerInfoSwitchToMediaTarget? private let sharedMediaFromForumTopic: (EnginePeer.Id, Int64)? let chatLocation: ChatLocation private let chatLocationContextHolder = Atomic(value: nil) @@ -6199,6 +6281,8 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortc var avatarPickerHolder: Any? + private let hidePhoneInSettings: Bool + var controllerNode: PeerInfoScreenNode { return self.displayNode as! PeerInfoScreenNode } @@ -6214,6 +6298,10 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortc return self.controllerNode.privacySettings } + public var twoStepAuthData: Promise { + return self.controllerNode.twoStepAuthData + } + override public var customNavigationData: CustomViewControllerNavigationData? { get { if !self.isSettings { @@ -6237,8 +6325,9 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortc var didAppear: Bool = false private var validLayout: (layout: ContainerViewLayout, navigationHeight: CGFloat)? - + public init( + hidePhoneInSettings: Bool = SGSimpleSettings.defaultValues[SGSimpleSettings.Keys.hidePhoneInSettings.rawValue] as! Bool, context: AccountContext, updatedPresentationData: (initial: PresentationData, signal: Signal)?, peerId: PeerId, @@ -6258,8 +6347,10 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortc switchToGiftsTarget: PeerInfoSwitchToGiftsTarget? = nil, switchToGroupsInCommon: Bool = false, switchToStoryFolder: Int64? = nil, + switchToMediaTarget: PeerInfoSwitchToMediaTarget? = nil, ) { self.context = context + self.hidePhoneInSettings = hidePhoneInSettings self.updatedPresentationData = updatedPresentationData self.peerId = peerId self.avatarInitiallyExpanded = avatarInitiallyExpanded @@ -6276,6 +6367,7 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortc self.switchToGiftsTarget = switchToGiftsTarget self.switchToGroupsInCommon = switchToGroupsInCommon self.switchToStoryFolder = switchToStoryFolder + self.switchToMediaTarget = switchToMediaTarget self.sharedMediaFromForumTopic = sharedMediaFromForumTopic if let forumTopicThread = forumTopicThread { @@ -6621,8 +6713,15 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortc initialPaneKey = .groupsInCommon } else if self.switchToStoryFolder != nil { initialPaneKey = .stories + } else if let switchToMediaTarget = self.switchToMediaTarget { + switch switchToMediaTarget.kind { + case .photoVideo: + initialPaneKey = .media + case .file: + initialPaneKey = .files + } } - self.displayNode = PeerInfoScreenNode(controller: self, context: self.context, peerId: self.peerId, avatarInitiallyExpanded: self.avatarInitiallyExpanded, isOpenedFromChat: self.isOpenedFromChat, nearbyPeerDistance: self.nearbyPeerDistance, reactionSourceMessageId: self.reactionSourceMessageId, callMessages: self.callMessages, isSettings: self.isSettings, isMyProfile: self.isMyProfile, hintGroupInCommon: self.hintGroupInCommon, requestsContext: self.requestsContext, profileGiftsContext: self.profileGiftsContext, starsContext: self.starsContext, tonContext: self.tonContext, chatLocation: self.chatLocation, chatLocationContextHolder: self.chatLocationContextHolder, switchToGiftsTarget: self.switchToGiftsTarget, switchToStoryFolder: self.switchToStoryFolder, initialPaneKey: initialPaneKey, sharedMediaFromForumTopic: self.sharedMediaFromForumTopic) + self.displayNode = PeerInfoScreenNode(hidePhoneInSettings: self.hidePhoneInSettings, controller: self, context: self.context, peerId: self.peerId, avatarInitiallyExpanded: self.avatarInitiallyExpanded, isOpenedFromChat: self.isOpenedFromChat, nearbyPeerDistance: self.nearbyPeerDistance, reactionSourceMessageId: self.reactionSourceMessageId, callMessages: self.callMessages, isSettings: self.isSettings, isMyProfile: self.isMyProfile, hintGroupInCommon: self.hintGroupInCommon, requestsContext: self.requestsContext, profileGiftsContext: self.profileGiftsContext, starsContext: self.starsContext, tonContext: self.tonContext, chatLocation: self.chatLocation, chatLocationContextHolder: self.chatLocationContextHolder, switchToGiftsTarget: self.switchToGiftsTarget, switchToStoryFolder: self.switchToStoryFolder, switchToMediaTarget: self.switchToMediaTarget, initialPaneKey: initialPaneKey, sharedMediaFromForumTopic: self.sharedMediaFromForumTopic) self.controllerNode.accountsAndPeers.set(self.accountsAndPeers.get() |> map { $0.1 }) self.controllerNode.activeSessionsContextAndCount.set(self.activeSessionsContextAndCount.get()) self.cachedDataPromise.set(self.controllerNode.cachedDataPromise.get()) @@ -6656,7 +6755,7 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortc } } - private func dismissAllTooltips() { + fileprivate func dismissAllTooltips() { self.window?.forEachController({ controller in if let controller = controller as? UndoOverlayController, !controller.keepOnParentDismissal { controller.dismissWithCommitAction() @@ -6687,6 +6786,10 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortc } } + public func activateEdit() { + self.controllerNode.activateEdit() + } + public func openAvatarSetup(completedWithUploadingImage: @escaping (UIImage, Signal) -> UIView?) { let proceed = { [weak self] in self?.openAvatarForEditing(completedWithUploadingImage: completedWithUploadingImage) @@ -6828,7 +6931,7 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortc })) }))) } - let contextController = ContextController(presentationData: presentationData, source: .reference(PeerInfoControllerContextReferenceContentSource(controller: parentController, sourceView: backButtonView, insets: UIEdgeInsets(), contentInsets: UIEdgeInsets(top: 0.0, left: -15.0, bottom: 0.0, right: -15.0))), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) + let contextController = makeContextController(presentationData: presentationData, source: .reference(PeerInfoControllerContextReferenceContentSource(controller: parentController, sourceView: backButtonView, insets: UIEdgeInsets(), contentInsets: UIEdgeInsets(top: 0.0, left: -15.0, bottom: 0.0, right: -15.0))), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) parentController.presentInGlobalOverlay(contextController) }) } @@ -6867,6 +6970,7 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortc } self.controllerNode.refreshHasPersonalChannelsIfNeeded() + self.controllerNode.initialExpandPanes = false } override public func containerLayoutUpdated(_ layout: ContainerViewLayout, transition: ContainedViewLayoutTransition) { @@ -6886,6 +6990,22 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortc let strings = self.presentationData.strings var items: [ContextMenuItem] = [] + + // MARK: Swiftgram + #if DEBUG + items.append(.action(ContextMenuActionItem(text: "Swiftgram Debug", icon: { theme in + return generateTintedImage(image: nil, color: theme.contextMenu.primaryColor) + }, action: { [weak self] _, f in + guard let self = self else { + return + } + self.push(sgDebugController(context: self.context)) + + f(.dismissWithoutContent) + }))) + #endif + // + items.append(.action(ContextMenuActionItem(text: strings.Settings_AddAccount, icon: { theme in return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Add"), color: theme.contextMenu.primaryColor) }, action: { [weak self] _, f in @@ -6929,7 +7049,7 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortc })))*/ } - let controller = ContextController(presentationData: self.presentationData, source: .reference(SettingsTabBarContextReferenceContentSource(controller: self, sourceView: sourceView)), items: .single(ContextController.Items(content: .list(items))), recognizer: nil, gesture: gesture) + let controller = makeContextController(presentationData: self.presentationData, source: .reference(SettingsTabBarContextReferenceContentSource(controller: self, sourceView: sourceView)), items: .single(ContextController.Items(content: .list(items))), recognizer: nil, gesture: gesture) self.context.sharedContext.mainWindow?.presentInGlobalOverlay(controller) } @@ -6964,6 +7084,10 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortc } } + public func openEmojiStatusSetup() { + self.controllerNode.openSettings(section: .emojiStatus) + } + public func openBirthdaySetup() { self.controllerNode.interaction.updateIsEditingBirthdate(true) self.controllerNode.headerNode.navigationButtonContainer.performAction?(.edit, nil, nil) @@ -7044,7 +7168,7 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen, KeyShortc }))) let presentationData = context.sharedContext.currentPresentationData.with { $0 } - let contextController = ContextController(presentationData: presentationData, source: .reference(HeaderContextReferenceContentSource(controller: sourceController, sourceView: sourceView)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) + let contextController = makeContextController(presentationData: presentationData, source: .reference(HeaderContextReferenceContentSource(controller: sourceController, sourceView: sourceView)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) sourceController.presentInGlobalOverlay(contextController) }) } @@ -7178,15 +7302,20 @@ final class PeerInfoContextExtractedContentSource: ContextExtractedContentSource final class PeerInfoContextReferenceContentSource: ContextReferenceContentSource { private let controller: ViewController - private let sourceNode: ContextReferenceContentNode + private let sourceView: UIView - init(controller: ViewController, sourceNode: ContextReferenceContentNode) { + init(controller: ViewController, sourceNode: ASDisplayNode) { self.controller = controller - self.sourceNode = sourceNode + self.sourceView = sourceNode.view + } + + init(controller: ViewController, sourceView: UIView) { + self.controller = controller + self.sourceView = sourceView } func transitionInfo() -> ContextControllerReferenceViewInfo? { - return ContextControllerReferenceViewInfo(referenceView: self.sourceNode.view, contentAreaInScreenSpace: UIScreen.main.bounds) + return ContextControllerReferenceViewInfo(referenceView: self.sourceView, contentAreaInScreenSpace: UIScreen.main.bounds) } } @@ -7259,3 +7388,93 @@ struct ClearPeerHistory { } } } + + + + + +// MARK: Swiftgram +extension PeerInfoScreenImpl { + + public func tabBarItemContextActionRawUIView(sourceView: UIView, gesture: ContextGesture?) { + guard let (maybePrimary, other) = self.accountsAndPeersValue, let primary = maybePrimary else { + return + } + + let strings = self.presentationData.strings + + var items: [ContextMenuItem] = [] + + // MARK: Swiftgram + #if DEBUG + items.append(.action(ContextMenuActionItem(text: "Swiftgram Debug", icon: { theme in + return generateTintedImage(image: nil, color: theme.contextMenu.primaryColor) + }, action: { [weak self] _, f in + guard let self = self else { + return + } + self.push(sgDebugController(context: self.context)) + + f(.dismissWithoutContent) + }))) + #endif + // + + items.append(.action(ContextMenuActionItem(text: strings.Settings_AddAccount, icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Add"), color: theme.contextMenu.primaryColor) + }, action: { [weak self] _, f in + guard let strongSelf = self else { + return + } + strongSelf.controllerNode.openSettings(section: .addAccount) + f(.dismissWithoutContent) + }))) + + + items.append(.custom(AccountPeerContextItem(context: self.context, account: self.context.account, peer: primary.1, action: { _, f in + f(.default) + }), true)) + + if !other.isEmpty { + items.append(.separator) + } + + for account in other { + let id = account.0.account.id + items.append(.custom(AccountPeerContextItem(context: self.context, account: account.0.account, peer: account.1, action: { [weak self] _, f in + guard let strongSelf = self else { + return + } + strongSelf.controllerNode.switchToAccount(id: id) + f(.dismissWithoutContent) + }), true)) + } + + let controller = makeContextController(presentationData: presentationData, source: .reference(HeaderContextReferenceContentSource(controller: self, sourceView: sourceView)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) + self.context.sharedContext.mainWindow?.presentInGlobalOverlay(controller) + } +} + +extension PeerInfoScreenNode { + + public func fetchNearestChatParticipant() -> Signal<(String?, Int32?), NoError> { + guard let navigationController = self.controller?.navigationController as? NavigationController else { + return .single((nil, nil)) + } + + for controller in navigationController.viewControllers.reversed() { + if let chatController = controller as? ChatController, let chatPeerId = chatController.chatLocation.peerId, [Namespaces.Peer.CloudGroup, Namespaces.Peer.CloudChannel].contains(chatPeerId.namespace) { + return self.context.engine.peers.fetchChannelParticipant(peerId: chatPeerId, participantId: self.peerId) + |> mapToSignal { participant -> Signal<(String?, Int32?), NoError> in + if let participant = participant, case let .member(_, invitedAt, _, _, _, _) = participant { + return .single((chatController.overlayTitle, invitedAt)) + } else { + return .single((nil, nil)) + } + } + + } + } + return .single((nil, nil)) + } +} diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenAvatarSetup.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenAvatarSetup.swift index 4705dc95..22cc5cb2 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenAvatarSetup.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenAvatarSetup.swift @@ -463,7 +463,7 @@ extension PeerInfoScreenImpl { case .accept: (strongSelf.parentController?.topViewController as? ViewController)?.present(UndoOverlayController(presentationData: strongSelf.presentationData, content: .image(image: image, title: strongSelf.presentationData.strings.Conversation_SuggestedPhotoSuccess, text: strongSelf.presentationData.strings.Conversation_SuggestedPhotoSuccessText, round: true, undoText: nil), elevatedLayout: false, animateInAsReplacement: true, action: { [weak self] action in if case .info = action { - self?.parentController?.openSettings() + self?.parentController?.openSettings(edit: false) } return false }), in: .current) @@ -662,7 +662,7 @@ extension PeerInfoScreenImpl { case .accept: (strongSelf.parentController?.topViewController as? ViewController)?.present(UndoOverlayController(presentationData: strongSelf.presentationData, content: .image(image: image, title: strongSelf.presentationData.strings.Conversation_SuggestedVideoSuccess, text: strongSelf.presentationData.strings.Conversation_SuggestedVideoSuccessText, round: true, undoText: nil), elevatedLayout: false, animateInAsReplacement: true, action: { [weak self] action in if case .info = action { - self?.parentController?.openSettings() + self?.parentController?.openSettings(edit: false) } return false }), in: .current) @@ -874,7 +874,7 @@ extension PeerInfoScreenImpl { case .accept: (strongSelf.parentController?.topViewController as? ViewController)?.present(UndoOverlayController(presentationData: strongSelf.presentationData, content: .image(image: image, title: strongSelf.presentationData.strings.Conversation_SuggestedVideoSuccess, text: strongSelf.presentationData.strings.Conversation_SuggestedVideoSuccessText, round: true, undoText: nil), elevatedLayout: false, animateInAsReplacement: true, action: { [weak self] action in if case .info = action { - self?.parentController?.openSettings() + self?.parentController?.openSettings(edit: false) } return false }), in: .current) diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenOpenPeerInfoContextMenu.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenOpenPeerInfoContextMenu.swift index b810ae58..17542861 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenOpenPeerInfoContextMenu.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenOpenPeerInfoContextMenu.swift @@ -18,6 +18,39 @@ extension PeerInfoScreenNode { } let context = self.context switch subject { + case let .copy(text): + let contextMenuController = makeContextMenuController(actions: [ContextMenuAction(content: .text(title: self.presentationData.strings.Conversation_ContextMenuCopy, accessibilityLabel: self.presentationData.strings.Conversation_ContextMenuCopy), action: { [weak self] in + UIPasteboard.general.string = text + + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + self?.controller?.present(UndoOverlayController(presentationData: presentationData, content: .copy(text: presentationData.strings.Conversation_TextCopied), elevatedLayout: false, animateInAsReplacement: false, action: { _ in return false }), in: .current) + })]) + controller.present(contextMenuController, in: .window(.root), with: ContextMenuControllerPresentationArguments(sourceNodeAndRect: { [weak self, weak sourceNode] in + if let controller = self?.controller, let sourceNode = sourceNode { + var rect = sourceNode.bounds.insetBy(dx: 0.0, dy: 2.0) + if let sourceRect = sourceRect { + rect = sourceRect.insetBy(dx: 0.0, dy: 2.0) + } + return (sourceNode, rect, controller.displayNode, controller.view.bounds) + } else { + return nil + } + })) + case .aboutDC: + let contextMenuController = makeContextMenuController(actions: [ContextMenuAction(content: .text(title: self.presentationData.strings.Passport_InfoLearnMore, accessibilityLabel: self.presentationData.strings.Passport_InfoLearnMore), action: { [weak self] in + self?.openUrl(url: "https://core.telegram.org/api/datacenter", concealed: false, external: false) + })]) + controller.present(contextMenuController, in: .window(.root), with: ContextMenuControllerPresentationArguments(sourceNodeAndRect: { [weak self, weak sourceNode] in + if let controller = self?.controller, let sourceNode = sourceNode { + var rect = sourceNode.bounds.insetBy(dx: 0.0, dy: 2.0) + if let sourceRect = sourceRect { + rect = sourceRect.insetBy(dx: 0.0, dy: 2.0) + } + return (sourceNode, rect, controller.displayNode, controller.view.bounds) + } else { + return nil + } + })) case .birthday: if let cachedData = data.cachedData as? CachedUserData, let birthday = cachedData.birthday { let presentationData = context.sharedContext.currentPresentationData.with { $0 } diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenPerformButtonAction.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenPerformButtonAction.swift index 8ac338ed..ce55e8d5 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenPerformButtonAction.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenPerformButtonAction.swift @@ -750,7 +750,7 @@ extension PeerInfoScreenNode { guard let self else { return } - self.context.sharedContext.openResolvedUrl(.settings(.autoremoveMessages), context: self.context, urlContext: .generic, navigationController: self.controller?.navigationController as? NavigationController, forceExternal: false, forceUpdate: false, openPeer: { _, _ in }, sendFile: nil, sendSticker: nil, sendEmoji: nil, requestMessageActionUrlAuth: nil, joinVoiceChat: nil, present: { _, _ in }, dismissInput: { [weak self] in + self.context.sharedContext.openResolvedUrl(.settings(.legacy(.autoremoveMessages)), context: self.context, urlContext: .generic, navigationController: self.controller?.navigationController as? NavigationController, forceExternal: false, forceUpdate: false, openPeer: { _, _ in }, sendFile: nil, sendSticker: nil, sendEmoji: nil, requestMessageActionUrlAuth: nil, joinVoiceChat: nil, present: { _, _ in }, dismissInput: { [weak self] in guard let self else { return } @@ -966,7 +966,7 @@ extension PeerInfoScreenNode { guard let self else { return } - self.context.sharedContext.openResolvedUrl(.settings(.autoremoveMessages), context: self.context, urlContext: .generic, navigationController: self.controller?.navigationController as? NavigationController, forceExternal: false, forceUpdate: false, openPeer: { _, _ in }, sendFile: nil, sendSticker: nil, sendEmoji: nil, requestMessageActionUrlAuth: nil, joinVoiceChat: nil, present: { _, _ in }, dismissInput: { [weak self] in + self.context.sharedContext.openResolvedUrl(.settings(.legacy(.autoremoveMessages)), context: self.context, urlContext: .generic, navigationController: self.controller?.navigationController as? NavigationController, forceExternal: false, forceUpdate: false, openPeer: { _, _ in }, sendFile: nil, sendSticker: nil, sendEmoji: nil, requestMessageActionUrlAuth: nil, joinVoiceChat: nil, present: { _, _ in }, dismissInput: { [weak self] in guard let self else { return } @@ -1096,7 +1096,7 @@ extension PeerInfoScreenNode { guard let self else { return } - self.context.sharedContext.openResolvedUrl(.settings(.autoremoveMessages), context: self.context, urlContext: .generic, navigationController: self.controller?.navigationController as? NavigationController, forceExternal: false, forceUpdate: false, openPeer: { _, _ in }, sendFile: nil, sendSticker: nil, sendEmoji: nil, requestMessageActionUrlAuth: nil, joinVoiceChat: nil, present: { _, _ in }, dismissInput: { [weak self] in + self.context.sharedContext.openResolvedUrl(.settings(.legacy(.autoremoveMessages)), context: self.context, urlContext: .generic, navigationController: self.controller?.navigationController as? NavigationController, forceExternal: false, forceUpdate: false, openPeer: { _, _ in }, sendFile: nil, sendSticker: nil, sendEmoji: nil, requestMessageActionUrlAuth: nil, joinVoiceChat: nil, present: { _, _ in }, dismissInput: { [weak self] in guard let self else { return } diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenSettingsActions.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenSettingsActions.swift index be447bae..442097c3 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenSettingsActions.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenSettingsActions.swift @@ -1,3 +1,5 @@ +import SGStrings +import SGSettingsUI import Foundation import UIKit import Display @@ -15,6 +17,7 @@ import PremiumUI import TelegramPresentationData import PresentationDataUtils import PasswordSetupUI +import InstantPageCache extension PeerInfoScreenNode { func openSettings(section: PeerInfoSettingsSection) { @@ -44,6 +47,20 @@ extension PeerInfoScreenNode { } } switch section { + case .swiftgram: + self.controller?.push(sgSettingsController(context: self.context)) + case .swiftgramPro: + if self.context.sharedContext.immediateSGStatus.status > 1 { + self.controller?.push(self.context.sharedContext.makeSGProController(context: self.context)) + } else { + if let payWallController = self.context.sharedContext.makeSGPayWallController(context: self.context) { + self.controller?.present(payWallController, in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + } else { + self.controller?.present(self.context.sharedContext.makeSGUpdateIOSController(), animated: true) + } + } + case .ghostgram: + push(ghostgramSettingsController(context: self.context)) case .avatar: self.controller?.openAvatarForEditing() case .edit: @@ -218,15 +235,15 @@ extension PeerInfoScreenNode { guard let strongSelf = self else { return } - var maximumAvailableAccounts: Int = 3 + var maximumAvailableAccounts: Int = maximumSwiftgramNumberOfAccounts if accountAndPeer?.1.isPremium == true && !strongSelf.context.account.testingEnvironment { - maximumAvailableAccounts = 4 + maximumAvailableAccounts = maximumSwiftgramNumberOfAccounts } var count: Int = 1 for (accountContext, peer, _) in accountsAndPeers { if !accountContext.account.testingEnvironment { if peer.isPremium { - maximumAvailableAccounts = 4 + maximumAvailableAccounts = maximumSwiftgramNumberOfAccounts } count += 1 } @@ -246,7 +263,23 @@ extension PeerInfoScreenNode { navigationController.pushViewController(controller) } } else { - strongSelf.context.sharedContext.beginNewAuth(testingEnvironment: strongSelf.context.account.testingEnvironment) + // MARK: Swiftgram + if count + 1 > maximumSafeNumberOfAccounts { + let presentationData = strongSelf.context.sharedContext.currentPresentationData.with { $0 } + let alertController = textAlertController(context: strongSelf.context, updatedPresentationData: strongSelf.controller?.updatedPresentationData, title: presentationData.strings.ChatList_DeleteSavedMessagesConfirmationTitle, text: i18n("Auth.AccountBackupReminder", presentationData.strings.baseLanguageCode), actions: [ + TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: { + strongSelf.context.sharedContext.beginNewAuth(testingEnvironment: strongSelf.context.account.testingEnvironment) + }) + ]) + if let controller = strongSelf.controller { + controller.present(alertController, in: .window(.root)) + } else { + strongSelf.context.sharedContext.beginNewAuth(testingEnvironment: strongSelf.context.account.testingEnvironment) + } + } else { + strongSelf.context.sharedContext.beginNewAuth(testingEnvironment: strongSelf.context.account.testingEnvironment) + } + // } }) case .logout: @@ -295,12 +328,19 @@ extension PeerInfoScreenNode { if let tonContext = self.controller?.tonContext { push(self.context.sharedContext.makeStarsTransactionsScreen(context: self.context, starsContext: tonContext)) } - case .ghostgram: - push(ghostgramSettingsController(context: self.context)) } } + func setupFaqIfNeeded() { + if !self.didSetCachedFaq { + self.cachedFaq.set(.single(nil) |> then(cachedFaqInstantPage(context: self.context) |> map(Optional.init))) + self.didSetCachedFaq = true + } + } + func openFaq(anchor: String? = nil) { + self.setupFaqIfNeeded() + let presentationData = self.presentationData let progressSignal = Signal { [weak self] subscriber in let controller = OverlayStatusController(theme: presentationData.theme, type: .loading(cancelled: nil)) @@ -316,6 +356,7 @@ extension PeerInfoScreenNode { let progressDisposable = progressSignal.start() let _ = (self.cachedFaq.get() + |> filter { $0 != nil } |> take(1) |> deliverOnMainQueue).start(next: { [weak self] resolvedUrl in progressDisposable.dispose() diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoSelectionPanelNode.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoSelectionPanelNode.swift index 2e029773..957e0679 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoSelectionPanelNode.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoSelectionPanelNode.swift @@ -55,10 +55,10 @@ final class PeerInfoSelectionPanelNode: ASDisplayNode { }, blockMessageAuthor: { _, _ in }, deleteMessages: { _, _, f in f(.default) - }, forwardSelectedMessages: { + }, forwardSelectedMessages: { _ in forwardMessages() }, forwardCurrentForwardMessages: { - }, forwardMessages: { _ in + }, forwardMessages: { _, _ in }, updateForwardOptionsState: { _ in }, presentForwardOptions: { _ in }, presentReplyOptions: { _ in @@ -193,7 +193,7 @@ final class PeerInfoSelectionPanelNode: ASDisplayNode { self.backgroundNode.updateColor(color: presentationData.theme.rootController.navigationBar.blurredBackgroundColor, transition: .immediate) self.separatorNode.backgroundColor = presentationData.theme.rootController.navigationBar.separatorColor - let interfaceState = ChatPresentationInterfaceState(chatWallpaper: .color(0), theme: presentationData.theme, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameDisplayOrder: presentationData.nameDisplayOrder, limitsConfiguration: .defaultValue, fontSize: .regular, bubbleCorners: PresentationChatBubbleCorners(mainRadius: 16.0, auxiliaryRadius: 8.0, mergeBubbleCorners: true), accountPeerId: self.context.account.peerId, mode: .standard(.default), chatLocation: .peer(id: self.peerId), subject: nil, peerNearbyData: nil, greetingData: nil, pendingUnpinnedAllMessages: false, activeGroupCallInfo: nil, hasActiveGroupCall: false, threadData: nil, isGeneralThreadClosed: nil, replyMessage: nil, accountPeerColor: nil, businessIntro: nil) + let interfaceState = ChatPresentationInterfaceState(chatWallpaper: .color(0), theme: presentationData.theme, preferredGlassType: .default, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameDisplayOrder: presentationData.nameDisplayOrder, limitsConfiguration: .defaultValue, fontSize: .regular, bubbleCorners: PresentationChatBubbleCorners(mainRadius: 16.0, auxiliaryRadius: 8.0, mergeBubbleCorners: true), accountPeerId: self.context.account.peerId, mode: .standard(.default), chatLocation: .peer(id: self.peerId), subject: nil, peerNearbyData: nil, greetingData: nil, pendingUnpinnedAllMessages: false, activeGroupCallInfo: nil, hasActiveGroupCall: false, threadData: nil, isGeneralThreadClosed: nil, replyMessage: nil, accountPeerColor: nil, businessIntro: nil) let panelHeight = self.selectionPanel.updateLayout(width: layout.size.width, leftInset: layout.safeInsets.left, rightInset: layout.safeInsets.right, bottomInset: layout.intrinsicInsets.bottom, additionalSideInsets: UIEdgeInsets(), maxHeight: layout.size.height, maxOverlayHeight: layout.size.height, isSecondary: false, transition: transition, interfaceState: interfaceState, metrics: layout.metrics, isMediaInputExpanded: false) transition.updateFrame(node: self.selectionPanel, frame: CGRect(origin: CGPoint(), size: CGSize(width: layout.size.width, height: panelHeight))) diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoSettingsItems.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoSettingsItems.swift index 7cf4c722..53ba3bed 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoSettingsItems.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoSettingsItems.swift @@ -13,6 +13,25 @@ import ItemListPeerItem import DeviceAccess import TelegramStringFormatting import PeerNameColorItem +import SGSimpleSettings + +private func ghostgramSettingsMenuIcon() -> UIImage? { + let bundle = Bundle.main + let candidates: [(String, String)] = [ + ("GhostgramIcon@2x", "png"), + ("GhostgramIcon@3x", "png"), + ("GhostIcon@60x60", "png"), + ("GhostIcon@58x58", "png") + ] + for (name, ext) in candidates { + if let path = bundle.path(forResource: name, ofType: ext), let image = UIImage(contentsOfFile: path) { + return generateImage(CGSize(width: 29.0, height: 29.0), contextGenerator: { size, _ in + image.draw(in: CGRect(origin: .zero, size: size)) + }) + } + } + return PresentationResourcesSettings.ghostgram +} enum SettingsSection: Int, CaseIterable { case edit @@ -20,6 +39,8 @@ enum SettingsSection: Int, CaseIterable { case accounts case myProfile case proxy + case swiftgram + case swiftgramPro case apps case shortcuts case advanced @@ -28,7 +49,7 @@ enum SettingsSection: Int, CaseIterable { case support } -func settingsItems(data: PeerInfoScreenData?, context: AccountContext, presentationData: PresentationData, interaction: PeerInfoInteraction, isExpanded: Bool) -> [(AnyHashable, [PeerInfoScreenItem])] { +func settingsItems(showProfileId: Bool, data: PeerInfoScreenData?, context: AccountContext, presentationData: PresentationData, interaction: PeerInfoInteraction, isExpanded: Bool) -> [(AnyHashable, [PeerInfoScreenItem])] { guard let data = data else { return [] } @@ -80,6 +101,28 @@ func settingsItems(data: PeerInfoScreenData?, context: AccountContext, presentat })) } + // MARK: Swiftgram + if showProfileId { + var idText = "" + + if let user = data.peer as? TelegramUser { + idText = String(user.id.id._internalGetInt64Value()) + } + + items[.edit]!.append( + PeerInfoScreenActionItem( + id: 100, + text: "ID: \(idText)", + color: .accent, + action: { + UIPasteboard.general.string = idText + + interaction.notifyTextCopied() + } + ) + ) + } + if let settings = data.globalSettings { if settings.premiumGracePeriod { items[.phone]!.append(PeerInfoScreenInfoItem(id: 0, title: "Your access to Telegram Premium will expire soon!", text: .markdown("Unfortunately, your latest payment didn't come through. To keep your access to exclusive features, please renew the subscription."), isWarning: true, linkAction: nil)) @@ -144,15 +187,19 @@ func settingsItems(data: PeerInfoScreenData?, context: AccountContext, presentat })) } - items[.accounts]!.append(PeerInfoScreenActionItem(id: 100, text: presentationData.strings.Settings_AddAccount, icon: PresentationResourcesItemList.plusIconImage(presentationData.theme), action: { - interaction.openSettings(.addAccount) - })) +// items[.accounts]!.append(PeerInfoScreenActionItem(id: 100, text: presentationData.strings.Settings_AddAccount, icon: PresentationResourcesItemList.plusIconImage(presentationData.theme), action: { +// interaction.openSettings(.addAccount) +// })) } + // MARK: Swiftgram + items[.accounts]!.append(PeerInfoScreenActionItem(id: 1000, text: presentationData.strings.Settings_AddAccount, icon: PresentationResourcesItemList.plusIconImage(presentationData.theme), action: { + interaction.openSettings(.addAccount) + })) items[.myProfile]!.append(PeerInfoScreenDisclosureItem(id: 0, text: presentationData.strings.Settings_MyProfile, icon: PresentationResourcesSettings.myProfile, action: { interaction.openSettings(.profile) })) - items[.myProfile]!.append(PeerInfoScreenDisclosureItem(id: 1001, text: "Ghostgram Settings", icon: UIImage(bundleImageName: "Settings/Menu/GhostgramSettings"), action: { + items[.myProfile]!.append(PeerInfoScreenDisclosureItem(id: 1001, text: "Ghostgram Settings", icon: ghostgramSettingsMenuIcon(), action: { interaction.openSettings(.ghostgram) })) @@ -174,6 +221,39 @@ func settingsItems(data: PeerInfoScreenData?, context: AccountContext, presentat } } + // let locale = presentationData.strings.baseLanguageCode + // MARK: Swiftgram + let hasNewSGFeatures = { + return false + } + let swiftgramLabel: PeerInfoScreenDisclosureItem.Label + if hasNewSGFeatures() { + swiftgramLabel = .titleBadge(presentationData.strings.Settings_New, presentationData.theme.list.itemAccentColor) + } else { + swiftgramLabel = .none + } + + let hasNewSGProFeatures = { + return false + } + let swiftgramProLabel: PeerInfoScreenDisclosureItem.Label + if hasNewSGProFeatures() { + swiftgramProLabel = .titleBadge(presentationData.strings.Settings_New, presentationData.theme.list.itemAccentColor) + } else { + swiftgramProLabel = .none + } + + + let sgWebSettings = context.currentAppConfiguration.with({ $0 }).sgWebSettings + if sgWebSettings.global.paymentsEnabled || context.sharedContext.immediateSGStatus.status > 1 { + items[.swiftgram]!.append(PeerInfoScreenDisclosureItem(id: 0, label: swiftgramProLabel, text: "Swiftgram Pro", icon: nil, action: { + interaction.openSettings(.swiftgramPro) + })) + } + items[.swiftgram]!.append(PeerInfoScreenDisclosureItem(id: 1, label: swiftgramLabel, text: "Swiftgram", icon: nil, action: { + interaction.openSettings(.swiftgram) + })) + var appIndex = 1000 if let settings = data.globalSettings { for bot in settings.bots { @@ -298,8 +378,8 @@ func settingsItems(data: PeerInfoScreenData?, context: AccountContext, presentat })) } if let starsState = data.starsState { - if !isPremiumDisabled || starsState.balance > StarsAmount.zero { - items[.payment]!.append(PeerInfoScreenDisclosureItem(id: 105, label: .text(""), text: presentationData.strings.Settings_SendGift, icon: PresentationResourcesSettings.premiumGift, action: { + if (!isPremiumDisabled || starsState.balance > StarsAmount.zero) && sgWebSettings.global.canGrant { + items[.payment]!.append(PeerInfoScreenDisclosureItem(id: 105, label: .text(""), text: "Telegram Gifts", icon: PresentationResourcesSettings.premiumGift, action: { interaction.openSettings(.premiumGift) })) } @@ -422,7 +502,7 @@ func settingsEditingItems(data: PeerInfoScreenData?, state: PeerInfoState, conte interaction.openBirthdatePrivacy() })) - if let user = data.peer as? TelegramUser { + if let user = data.peer as? TelegramUser, !SGSimpleSettings.shared.hidePhoneInSettings { items[.info]!.append(PeerInfoScreenDisclosureItem(id: ItemPhoneNumber, label: .text(user.phone.flatMap({ formatPhoneNumber(context: context, number: $0) }) ?? ""), text: presentationData.strings.Settings_PhoneNumber, action: { interaction.openSettings(.phoneNumber) })) diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoStoryGridScreen/Sources/PeerInfoStoryGridScreen.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoStoryGridScreen/Sources/PeerInfoStoryGridScreen.swift index 925c3098..6fd9cbcf 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoStoryGridScreen/Sources/PeerInfoStoryGridScreen.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoStoryGridScreen/Sources/PeerInfoStoryGridScreen.swift @@ -310,7 +310,7 @@ final class PeerInfoStoryGridScreenComponent: Component { return } if let rootController = component.context.sharedContext.mainWindow?.viewController as? TelegramRootControllerInterface { - let coordinator = rootController.openStoryCamera(customTarget: nil, resumeLiveStream: false, transitionIn: nil, transitionedIn: {}, transitionOut: { _, _ in return nil }) + let coordinator = rootController.openStoryCamera(mode: .photo, customTarget: nil, resumeLiveStream: false, transitionIn: nil, transitionedIn: {}, transitionOut: { _, _ in return nil }) coordinator?.animateIn() } } diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoVisualMediaPaneNode/Sources/PeerInfoGiftsPaneNode.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoVisualMediaPaneNode/Sources/PeerInfoGiftsPaneNode.swift index d9a85eb9..8384c784 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoVisualMediaPaneNode/Sources/PeerInfoGiftsPaneNode.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoVisualMediaPaneNode/Sources/PeerInfoGiftsPaneNode.swift @@ -988,7 +988,7 @@ public final class PeerInfoGiftsPaneNode: ASDisplayNode, PeerInfoPaneNode, UIScr var items: [ContextMenuItem] = [] if canManage { - items.append(.action(ContextMenuActionItem(text: strings.PeerInfo_Gifts_Context_AddToCollection, textLayout: .twoLinesMax, icon: { theme in generateTintedImage(image: UIImage(bundleImageName: "Peer Info/Gifts/AddToCollection"), color: theme.contextMenu.primaryColor) }, action: { [weak self] c, f in + let addToCollectionItem: ContextMenuActionItem = ContextMenuActionItem(text: strings.PeerInfo_Gifts_Context_AddToCollection, textLayout: .twoLinesMax, icon: { theme in generateTintedImage(image: UIImage(bundleImageName: "Peer Info/Gifts/AddToCollection"), color: theme.contextMenu.primaryColor) }, action: { [weak self] c, f in var subItems: [ContextMenuItem] = [] subItems.append(.action(ContextMenuActionItem(text: strings.Common_Back, textColor: .primary, icon: { theme in @@ -1054,7 +1054,7 @@ public final class PeerInfoGiftsPaneNode: ASDisplayNode, PeerInfoPaneNode, UIScr case let .unique(uniqueGift): giftTitle = uniqueGift.title + " #\(formatCollectibleNumber(uniqueGift.number, dateTimeFormat: currentParams.presentationData.dateTimeFormat))" for attribute in uniqueGift.attributes { - if case let .model(_, file, _) = attribute { + if case let .model(_, file, _, _) = attribute { giftFile = file } } @@ -1089,7 +1089,8 @@ public final class PeerInfoGiftsPaneNode: ASDisplayNode, PeerInfoPaneNode, UIScr } c?.pushItems(items: .single(ContextController.Items(content: .list(subItems)))) - }))) + }) + items.append(.action(addToCollectionItem)) items.append(.separator) } @@ -1274,7 +1275,7 @@ public final class PeerInfoGiftsPaneNode: ASDisplayNode, PeerInfoPaneNode, UIScr } if canManage { - items.append(.action(ContextMenuActionItem(text: gift.savedToProfile ? strings.PeerInfo_Gifts_Context_Hide : strings.PeerInfo_Gifts_Context_Show, icon: { theme in generateTintedImage(image: UIImage(bundleImageName: gift.savedToProfile ? "Peer Info/HideIcon" : "Peer Info/ShowIcon"), color: theme.contextMenu.primaryColor) }, action: { [weak self] c, f in + let toggleVisibilityItem: ContextMenuActionItem = ContextMenuActionItem(text: gift.savedToProfile ? strings.PeerInfo_Gifts_Context_Hide : strings.PeerInfo_Gifts_Context_Show, icon: { theme in generateTintedImage(image: UIImage(bundleImageName: gift.savedToProfile ? "Peer Info/HideIcon" : "Peer Info/ShowIcon"), color: theme.contextMenu.primaryColor) }, action: { [weak self] c, f in c?.dismiss(completion: { [weak self] in guard let self else { return @@ -1289,7 +1290,7 @@ public final class PeerInfoGiftsPaneNode: ASDisplayNode, PeerInfoPaneNode, UIScr animationFile = gift.file case let .unique(gift): for attribute in gift.attributes { - if case let .model(_, file, _) = attribute { + if case let .model(_, file, _, _) = attribute { animationFile = file break } @@ -1316,7 +1317,8 @@ public final class PeerInfoGiftsPaneNode: ASDisplayNode, PeerInfoPaneNode, UIScr } } }) - }))) + }) + items.append(.action(toggleVisibilityItem)) if case let .unique(uniqueGift) = gift.gift { items.append(.action(ContextMenuActionItem(text: strings.PeerInfo_Gifts_Context_Transfer, icon: { theme in generateTintedImage(image: UIImage(bundleImageName: "Peer Info/TransferIcon"), color: theme.contextMenu.primaryColor) }, action: { [weak self] c, f in @@ -1374,7 +1376,7 @@ public final class PeerInfoGiftsPaneNode: ASDisplayNode, PeerInfoPaneNode, UIScr } if canManage, case let .collection(id) = self.currentCollection { - items.append(.action(ContextMenuActionItem(text: strings.PeerInfo_Gifts_Context_RemoveFromCollection, textColor: .destructive, textLayout: .twoLinesMax, icon: { theme in generateTintedImage(image: UIImage(bundleImageName: "Peer Info/Gifts/RemoveFromCollection"), color: theme.contextMenu.destructiveColor) }, action: { [weak self] c, f in + let removeFromCollectionItem: ContextMenuActionItem = ContextMenuActionItem(text: strings.PeerInfo_Gifts_Context_RemoveFromCollection, textColor: .destructive, textLayout: .twoLinesMax, icon: { theme in generateTintedImage(image: UIImage(bundleImageName: "Peer Info/Gifts/RemoveFromCollection"), color: theme.contextMenu.destructiveColor) }, action: { [weak self] c, f in f(.default) guard let self else { @@ -1393,7 +1395,7 @@ public final class PeerInfoGiftsPaneNode: ASDisplayNode, PeerInfoPaneNode, UIScr case let .unique(uniqueGift): giftTitle = uniqueGift.title + " #\(formatCollectibleNumber(uniqueGift.number, dateTimeFormat: currentParams.presentationData.dateTimeFormat))" for attribute in uniqueGift.attributes { - if case let .model(_, file, _) = attribute { + if case let .model(_, file, _, _) = attribute { giftFile = file } } @@ -1415,7 +1417,8 @@ public final class PeerInfoGiftsPaneNode: ASDisplayNode, PeerInfoPaneNode, UIScr ) self.parentController?.present(undoController, in: .current) } - }))) + }) + items.append(.action(removeFromCollectionItem)) } guard !items.isEmpty else { diff --git a/submodules/TelegramUI/Components/PeerSelectionController/Sources/PeerSelectionController.swift b/submodules/TelegramUI/Components/PeerSelectionController/Sources/PeerSelectionController.swift index 689ea8ca..6c7148bb 100644 --- a/submodules/TelegramUI/Components/PeerSelectionController/Sources/PeerSelectionController.swift +++ b/submodules/TelegramUI/Components/PeerSelectionController/Sources/PeerSelectionController.swift @@ -8,10 +8,8 @@ import TelegramPresentationData import ProgressNavigationButtonNode import AccountContext import SearchUI -import func ChatListUI.chatListFilterItems -import enum ChatListUI.ChatListContainerNodeFilter +import ChatListUI import CounterControllerTitleView -import ChatListFilterTabContainerNode public final class PeerSelectionControllerImpl: ViewController, PeerSelectionController { private let context: AccountContext @@ -70,6 +68,7 @@ public final class PeerSelectionControllerImpl: ViewController, PeerSelectionCon let multipleSelectionLimit: Int32? private let hasCreation: Bool let immediatelyActivateMultipleSelection: Bool + private let initialForwardOptionsState: ChatInterfaceForwardOptionsState? override public var _presentedInModal: Bool { get { @@ -107,6 +106,7 @@ public final class PeerSelectionControllerImpl: ViewController, PeerSelectionCon self.createNewGroup = params.createNewGroup self.pretendPresentedInModal = params.pretendPresentedInModal self.forwardedMessageIds = params.forwardedMessageIds + self.initialForwardOptionsState = params.initialForwardOptionsState self.hasTypeHeaders = params.hasTypeHeaders self.selectForumThreads = params.selectForumThreads self.requestPeerType = params.requestPeerType @@ -259,7 +259,7 @@ public final class PeerSelectionControllerImpl: ViewController, PeerSelectionCon override public func loadDisplayNode() { self.navigationBar?.secondaryContentHeight = 44.0 + 10.0 - self.displayNode = PeerSelectionControllerNode(context: self.context, controller: self, presentationData: self.presentationData, filter: self.filter, forumPeerId: self.forumPeerId, hasFilters: self.hasFilters, hasChatListSelector: self.hasChatListSelector, hasContactSelector: self.hasContactSelector, hasGlobalSearch: self.hasGlobalSearch, forwardedMessageIds: self.forwardedMessageIds, hasTypeHeaders: self.hasTypeHeaders, requestPeerType: self.requestPeerType, hasCreation: self.hasCreation, createNewGroup: self.createNewGroup, present: { [weak self] c, a in + self.displayNode = PeerSelectionControllerNode(context: self.context, controller: self, presentationData: self.presentationData, filter: self.filter, forumPeerId: self.forumPeerId, hasFilters: self.hasFilters, hasChatListSelector: self.hasChatListSelector, hasContactSelector: self.hasContactSelector, hasGlobalSearch: self.hasGlobalSearch, forwardedMessageIds: self.forwardedMessageIds, initialForwardOptionsState: self.initialForwardOptionsState, hasTypeHeaders: self.hasTypeHeaders, requestPeerType: self.requestPeerType, hasCreation: self.hasCreation, createNewGroup: self.createNewGroup, present: { [weak self] c, a in self?.present(c, in: .window(.root), with: a) }, presentInGlobalOverlay: { [weak self] c, a in self?.presentInGlobalOverlay(c, with: a) @@ -507,7 +507,7 @@ public final class PeerSelectionControllerImpl: ViewController, PeerSelectionCon wasEmpty = true } - var selectedEntryId = !strongSelf.initializedFilters ? .all : (strongSelf.peerSelectionNode.mainContainerNode?.currentItemFilter ?? .all) + var selectedEntryId: ChatListFilterTabEntryId = !strongSelf.initializedFilters ? .all : (strongSelf.peerSelectionNode.mainContainerNode?.currentItemFilter ?? .all) var resetCurrentEntry = false if !resolvedItems.contains(where: { $0.id == selectedEntryId }) { resetCurrentEntry = true diff --git a/submodules/TelegramUI/Components/PeerSelectionController/Sources/PeerSelectionControllerNode.swift b/submodules/TelegramUI/Components/PeerSelectionController/Sources/PeerSelectionControllerNode.swift index dbf4b785..d9ec0e38 100644 --- a/submodules/TelegramUI/Components/PeerSelectionController/Sources/PeerSelectionControllerNode.swift +++ b/submodules/TelegramUI/Components/PeerSelectionController/Sources/PeerSelectionControllerNode.swift @@ -113,7 +113,7 @@ final class PeerSelectionControllerNode: ASDisplayNode { return (self.presentationData, self.presentationDataPromise.get()) } - init(context: AccountContext, controller: PeerSelectionControllerImpl, presentationData: PresentationData, filter: ChatListNodePeersFilter, forumPeerId: (id: EnginePeer.Id, isMonoforum: Bool)?, hasFilters: Bool, hasChatListSelector: Bool, hasContactSelector: Bool, hasGlobalSearch: Bool, forwardedMessageIds: [EngineMessage.Id], hasTypeHeaders: Bool, requestPeerType: [ReplyMarkupButtonRequestPeerType]?, hasCreation: Bool, createNewGroup: (() -> Void)?, present: @escaping (ViewController, Any?) -> Void, presentInGlobalOverlay: @escaping (ViewController, Any?) -> Void, dismiss: @escaping () -> Void) { + init(context: AccountContext, controller: PeerSelectionControllerImpl, presentationData: PresentationData, filter: ChatListNodePeersFilter, forumPeerId: (id: EnginePeer.Id, isMonoforum: Bool)?, hasFilters: Bool, hasChatListSelector: Bool, hasContactSelector: Bool, hasGlobalSearch: Bool, forwardedMessageIds: [EngineMessage.Id], initialForwardOptionsState: ChatInterfaceForwardOptionsState?, hasTypeHeaders: Bool, requestPeerType: [ReplyMarkupButtonRequestPeerType]?, hasCreation: Bool, createNewGroup: (() -> Void)?, present: @escaping (ViewController, Any?) -> Void, presentInGlobalOverlay: @escaping (ViewController, Any?) -> Void, dismiss: @escaping () -> Void) { self.context = context self.controller = controller self.present = present @@ -131,9 +131,14 @@ final class PeerSelectionControllerNode: ASDisplayNode { self.animationCache = context.animationCache self.animationRenderer = context.animationRenderer - self.presentationInterfaceState = ChatPresentationInterfaceState(chatWallpaper: .builtin(WallpaperSettings()), theme: self.presentationData.theme, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, limitsConfiguration: self.context.currentLimitsConfiguration.with { $0 }, fontSize: self.presentationData.chatFontSize, bubbleCorners: self.presentationData.chatBubbleCorners, accountPeerId: self.context.account.peerId, mode: .standard(.default), chatLocation: .peer(id: PeerId(0)), subject: nil, peerNearbyData: nil, greetingData: nil, pendingUnpinnedAllMessages: false, activeGroupCallInfo: nil, hasActiveGroupCall: false, threadData: nil, isGeneralThreadClosed: nil, replyMessage: nil, accountPeerColor: nil, businessIntro: nil) + self.presentationInterfaceState = ChatPresentationInterfaceState(chatWallpaper: .builtin(WallpaperSettings()), theme: self.presentationData.theme, preferredGlassType: .default, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, limitsConfiguration: self.context.currentLimitsConfiguration.with { $0 }, fontSize: self.presentationData.chatFontSize, bubbleCorners: self.presentationData.chatBubbleCorners, accountPeerId: self.context.account.peerId, mode: .standard(.default), chatLocation: .peer(id: PeerId(0)), subject: nil, peerNearbyData: nil, greetingData: nil, pendingUnpinnedAllMessages: false, activeGroupCallInfo: nil, hasActiveGroupCall: false, threadData: nil, isGeneralThreadClosed: nil, replyMessage: nil, accountPeerColor: nil, businessIntro: nil) self.presentationInterfaceState = self.presentationInterfaceState.updatedInterfaceState { $0.withUpdatedForwardMessageIds(forwardedMessageIds) } + if let initialForwardOptionsState { + self.presentationInterfaceState = self.presentationInterfaceState.updatedInterfaceState { + $0.withUpdatedForwardOptionsState(initialForwardOptionsState) + } + } self.presentationInterfaceStatePromise.set(self.presentationInterfaceState) if let _ = self.requestPeerType { @@ -387,9 +392,9 @@ final class PeerSelectionControllerNode: ASDisplayNode { }, blockMessageAuthor: { _, _ in }, deleteMessages: { _, _, f in f(.default) - }, forwardSelectedMessages: { + }, forwardSelectedMessages: { _ in }, forwardCurrentForwardMessages: { - }, forwardMessages: { _ in + }, forwardMessages: { _, _ in }, updateForwardOptionsState: { [weak self] f in if let strongSelf = self { strongSelf.updateChatPresentationInterfaceState(animated: true, { $0.updatedInterfaceState({ $0.withUpdatedForwardOptionsState(f($0.forwardOptionsState ?? ChatInterfaceForwardOptionsState(hideNames: false, hideCaptions: false, unhideNamesOnCaptionChange: false))) }) }) diff --git a/submodules/TelegramUI/Components/ProxyServerPreviewScreen/BUILD b/submodules/TelegramUI/Components/ProxyServerPreviewScreen/BUILD new file mode 100644 index 00000000..a74ad127 --- /dev/null +++ b/submodules/TelegramUI/Components/ProxyServerPreviewScreen/BUILD @@ -0,0 +1,35 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "ProxyServerPreviewScreen", + module_name = "ProxyServerPreviewScreen", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/AsyncDisplayKit", + "//submodules/Display", + "//submodules/Postbox", + "//submodules/TelegramCore", + "//submodules/SSignalKit/SwiftSignalKit", + "//submodules/ComponentFlow", + "//submodules/Components/ViewControllerComponent", + "//submodules/Components/ComponentDisplayAdapters", + "//submodules/Components/MultilineTextComponent", + "//submodules/TelegramPresentationData", + "//submodules/AccountContext", + "//submodules/TelegramUI/Components/ButtonComponent", + "//submodules/TelegramUI/Components/GlassBarButtonComponent", + "//submodules/Components/SheetComponent", + "//submodules/TelegramUI/Components/Gifts/TableComponent", + "//submodules/PresentationDataUtils", + "//submodules/Components/BundleIconComponent", + "//submodules/OverlayStatusController", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/submodules/TelegramUI/Components/ProxyServerPreviewScreen/Sources/ProxyServerPreviewScreen.swift b/submodules/TelegramUI/Components/ProxyServerPreviewScreen/Sources/ProxyServerPreviewScreen.swift new file mode 100644 index 00000000..e142e77a --- /dev/null +++ b/submodules/TelegramUI/Components/ProxyServerPreviewScreen/Sources/ProxyServerPreviewScreen.swift @@ -0,0 +1,526 @@ +import Foundation +import UIKit +import Display +import AsyncDisplayKit +import TelegramCore +import SwiftSignalKit +import AccountContext +import TelegramPresentationData +import ComponentFlow +import ViewControllerComponent +import SheetComponent +import MultilineTextComponent +import GlassBarButtonComponent +import ButtonComponent +import TableComponent +import PresentationDataUtils +import BundleIconComponent +import OverlayStatusController + +private final class ProxyServerPreviewSheetContent: CombinedComponent { + typealias EnvironmentType = ViewControllerComponentContainer.Environment + + let context: AccountContext + let server: ProxyServerSettings + let cancel: (Bool) -> Void + + init( + context: AccountContext, + server: ProxyServerSettings, + cancel: @escaping (Bool) -> Void + ) { + self.context = context + self.server = server + self.cancel = cancel + } + + static func ==(lhs: ProxyServerPreviewSheetContent, rhs: ProxyServerPreviewSheetContent) -> Bool { + if lhs.context !== rhs.context { + return false + } + if lhs.server != rhs.server { + return false + } + return true + } + + final class State: ComponentState { + private let context: AccountContext + private let server: ProxyServerSettings + + private var disposable = MetaDisposable() + private var statusDisposable = MetaDisposable() + fileprivate var status: ProxyServerStatus? + private var statusesContext: ProxyServersStatuses? + + fileprivate var inProgress = false + + fileprivate weak var controller: ProxyServerPreviewScreen? + + private var revertSettings: ProxySettings? + + init(context: AccountContext, server: ProxyServerSettings) { + self.context = context + self.server = server + + super.init() + } + + deinit { + self.disposable.dispose() + self.statusDisposable.dispose() + + if let revertSettings = self.revertSettings { + let _ = updateProxySettingsInteractively(accountManager: self.context.sharedContext.accountManager, { _ in + return revertSettings + }) + } + } + + var isChecked: Bool { + return self.statusesContext != nil + } + + func check() { + guard self.statusesContext == nil else { + return + } + + self.displayWarningIfNeeded { [weak self] in + guard let self else { + return + } + + let statusesContext = ProxyServersStatuses(network: self.context.account.network, servers: .single([self.server])) + self.statusesContext = statusesContext + + self.status = .checking + self.updated() + + self.statusDisposable.set((statusesContext.statuses() + |> map { return $0.first?.value } + |> distinctUntilChanged + |> deliverOnMainQueue).start(next: { [weak self] status in + if let self, let status { + self.status = status + self.updated() + } + })) + } + } + + func connect() { + guard !self.inProgress else { + return + } + + let presentationData = self.context.sharedContext.currentPresentationData.with { $0 } + + self.displayWarningIfNeeded { [weak self] in + guard let self else { + return + } + let accountManager = self.context.sharedContext.accountManager + let proxyServerSettings = self.server + let _ = (accountManager.transaction { transaction -> ProxySettings in + var currentSettings: ProxySettings? + let _ = updateProxySettingsInteractively(transaction: transaction, { settings in + currentSettings = settings + var settings = settings + if let index = settings.servers.firstIndex(of: proxyServerSettings) { + settings.servers[index] = proxyServerSettings + settings.activeServer = proxyServerSettings + } else { + settings.servers.insert(proxyServerSettings, at: 0) + settings.activeServer = proxyServerSettings + } + settings.enabled = true + return settings + }) + return currentSettings ?? ProxySettings.defaultSettings + } |> deliverOnMainQueue).start(next: { [weak self] previousSettings in + if let self { + self.revertSettings = previousSettings + + self.inProgress = true + self.updated() + + let signal = self.context.account.network.connectionStatus + |> filter { status in + switch status { + case let .online(proxyAddress): + if proxyAddress == proxyServerSettings.host { + return true + } else { + return false + } + default: + return false + } + } + |> map { _ -> Bool in + return true + } + |> distinctUntilChanged + |> timeout(15.0, queue: Queue.mainQueue(), alternate: .single(false)) + |> deliverOnMainQueue + self.disposable.set(signal.start(next: { [weak self] value in + if let self { + self.inProgress = false + self.updated() + + self.revertSettings = nil + if value { + if let navigationController = self.controller?.navigationController as? NavigationController { + Queue.mainQueue().after(0.5) { + (navigationController.topViewController as? ViewController)?.present(OverlayStatusController(theme: presentationData.theme, type: .shieldSuccess(presentationData.strings.SocksProxySetup_ProxyEnabled, false)), in: .window(.root)) + } + } + self.controller?.dismissAnimated() + } else { + let _ = updateProxySettingsInteractively(accountManager: accountManager, { _ in + return previousSettings + }).start() + self.controller?.present(textAlertController(sharedContext: self.context.sharedContext, title: nil, text: presentationData.strings.SocksProxySetup_FailedToConnect, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), in: .window(.root)) + } + } + })) + } + }) + } + } + + func displayWarningIfNeeded(commit: @escaping () -> Void) { + commit() + } + } + + func makeState() -> State { + return State(context: self.context, server: self.server) + } + + static var body: Body { + let closeButton = Child(GlassBarButtonComponent.self) + let title = Child(MultilineTextComponent.self) + let table = Child(TableComponent.self) + let button = Child(ButtonComponent.self) + + return { context in + let environment = context.environment[ViewControllerComponentContainer.Environment.self].value + let component = context.component + let theme = environment.theme + let strings = environment.strings + let state = context.state + if state.controller == nil { + state.controller = environment.controller() as? ProxyServerPreviewScreen + } + + let sideInset: CGFloat = 16.0 + environment.safeInsets.left + + let closeButton = closeButton.update( + component: GlassBarButtonComponent( + size: CGSize(width: 44.0, height: 44.0), + backgroundColor: nil, + isDark: theme.overallDarkAppearance, + state: .glass, + component: AnyComponentWithIdentity(id: "close", component: AnyComponent( + BundleIconComponent( + name: "Navigation/Close", + tintColor: theme.chat.inputPanel.panelControlColor + ) + )), + action: { _ in + component.cancel(true) + } + ), + availableSize: CGSize(width: 44.0, height: 44.0), + transition: .immediate + ) + + let title = title.update( + component: MultilineTextComponent( + text: .plain(NSAttributedString( + string: strings.SocksProxySetup_Title, + font: Font.semibold(17.0), + textColor: theme.actionSheet.primaryTextColor, + paragraphAlignment: .center + )), + horizontalAlignment: .center, + maximumNumberOfLines: 1 + ), + availableSize: CGSize(width: context.availableSize.width - sideInset * 2.0 - 60.0, height: CGFloat.greatestFiniteMagnitude), + transition: .immediate + ) + + let tableFont = Font.regular(15.0) + let tableTextColor = theme.list.itemPrimaryTextColor + let tableLinkColor = theme.list.itemAccentColor + var tableItems: [TableComponent.Item] = [] + + tableItems.append(.init( + id: "server", + title: strings.SocksProxySetup_Hostname, + component: AnyComponent( + MultilineTextComponent(text: .plain(NSAttributedString(string: component.server.host, font: tableFont, textColor: tableTextColor))) + ) + )) + + tableItems.append(.init( + id: "port", + title: strings.SocksProxySetup_Port, + component: AnyComponent( + MultilineTextComponent(text: .plain(NSAttributedString(string: "\(component.server.port)", font: tableFont, textColor: tableTextColor))) + ) + )) + + switch component.server.connection { + case let .socks5(username, password): + if let username { + tableItems.append(.init( + id: "username", + title: strings.SocksProxySetup_Username, + component: AnyComponent( + MultilineTextComponent(text: .plain(NSAttributedString(string: username, font: tableFont, textColor: tableTextColor))) + ) + )) + } + if let password { + tableItems.append(.init( + id: "password", + title: strings.SocksProxySetup_Password, + component: AnyComponent( + MultilineTextComponent(text: .plain(NSAttributedString(string: password, font: tableFont, textColor: tableTextColor))) + ) + )) + } + case .mtp: + tableItems.append(.init( + id: "secret", + title: strings.SocksProxySetup_Secret, + component: AnyComponent( + MultilineTextComponent(text: .plain(NSAttributedString(string: "•••••", font: tableFont, textColor: tableTextColor))) + ) + )) + } + + var statusText = strings.SocksProxySetup_Status + var statusColor = tableLinkColor + var statusIsActive = true + if let status = state.status { + statusIsActive = false + switch status { + case let .available(rtt): + let pingTime = Int(rtt * 1000.0) + statusText = strings.SocksProxySetup_ProxyStatusPing("\(pingTime)").string + statusColor = tableTextColor + case .checking: + statusText = strings.SocksProxySetup_ProxyStatusChecking + statusColor = tableTextColor + case .notAvailable: + statusText = strings.SocksProxySetup_ProxyStatusUnavailable + statusColor = environment.theme.list.itemDestructiveColor + } + } + + tableItems.append(.init( + id: "status", + title: strings.SocksProxySetup_Status, + component: AnyComponent( + Button( + content: AnyComponent(MultilineTextComponent(text: .plain(NSAttributedString(string: statusText, font: tableFont, textColor: statusColor)))), + automaticHighlight: statusIsActive, + action: { + if statusIsActive { + state.check() + } + } + ) + ) + )) + let table = table.update( + component: TableComponent( + theme: environment.theme, + items: tableItems + ), + availableSize: CGSize(width: context.availableSize.width - sideInset * 2.0, height: .greatestFiniteMagnitude), + transition: .immediate + ) + + let buttonInsets = ContainerViewLayout.concentricInsets(bottomInset: environment.safeInsets.bottom, innerDiameter: 52.0, sideInset: 30.0) + let button = button.update( + component: ButtonComponent( + background: ButtonComponent.Background( + style: .glass, + color: theme.list.itemCheckColors.fillColor, + foreground: theme.list.itemCheckColors.foregroundColor, + pressedColor: theme.list.itemCheckColors.fillColor.withMultipliedAlpha(0.9), + cornerRadius: 10.0, + ), + content: AnyComponentWithIdentity( + id: AnyHashable(0), + component: AnyComponent(MultilineTextComponent(text: .plain(NSMutableAttributedString(string: strings.SocksProxySetup_ConnectAndSave, font: Font.semibold(17.0), textColor: theme.list.itemCheckColors.foregroundColor, paragraphAlignment: .center)))) + ), + displaysProgress: state.inProgress, + action: { + state.connect() + } + ), + availableSize: CGSize(width: context.availableSize.width - buttonInsets.left - buttonInsets.right, height: 52.0), + transition: .immediate + ) + + context.add(title + .position(CGPoint(x: context.availableSize.width / 2.0, y: 38.0)) + ) + + var originY: CGFloat = 88.0 + context.add(table + .position(CGPoint(x: context.availableSize.width / 2.0, y: originY + table.size.height / 2.0)) + ) + originY += table.size.height + 28.0 + + context.add(button + .position(CGPoint(x: context.availableSize.width / 2.0, y: originY + button.size.height / 2.0)) + ) + originY += button.size.height + originY += buttonInsets.bottom + + context.add(closeButton + .position(CGPoint(x: 16.0 + closeButton.size.width / 2.0, y: 16.0 + closeButton.size.height / 2.0)) + ) + + let contentSize = CGSize(width: context.availableSize.width, height: originY) + return contentSize + } + } +} + +private final class ProxyServerPreviewSheetComponent: CombinedComponent { + typealias EnvironmentType = ViewControllerComponentContainer.Environment + + let context: AccountContext + let server: ProxyServerSettings + + init( + context: AccountContext, + server: ProxyServerSettings + ) { + self.context = context + self.server = server + } + + static func ==(lhs: ProxyServerPreviewSheetComponent, rhs: ProxyServerPreviewSheetComponent) -> Bool { + if lhs.context !== rhs.context { + return false + } + if lhs.server != rhs.server { + return false + } + return true + } + + static var body: Body { + let sheet = Child(SheetComponent.self) + let animateOut = StoredActionSlot(Action.self) + + return { context in + let environment = context.environment[EnvironmentType.self] + let controller = environment.controller + + let sheet = sheet.update( + component: SheetComponent( + content: AnyComponent(ProxyServerPreviewSheetContent( + context: context.component.context, + server: context.component.server, + cancel: { animate in + if animate { + animateOut.invoke(Action { _ in + if let controller = controller() { + controller.dismiss(completion: nil) + } + }) + } else if let controller = controller() { + controller.dismiss(animated: false, completion: nil) + } + } + )), + style: .glass, + backgroundColor: .color(environment.theme.actionSheet.opaqueItemBackgroundColor), + followContentSizeChanges: true, + clipsContent: true, + animateOut: animateOut + ), + environment: { + environment + SheetComponentEnvironment( + isDisplaying: environment.value.isVisible, + isCentered: environment.metrics.widthClass == .regular, + hasInputHeight: !environment.inputHeight.isZero, + regularMetricsSize: CGSize(width: 430.0, height: 900.0), + dismiss: { animated in + if animated { + animateOut.invoke(Action { _ in + if let controller = controller() { + controller.dismiss(completion: nil) + } + }) + } else { + if let controller = controller() { + controller.dismiss(completion: nil) + } + } + } + ) + }, + availableSize: context.availableSize, + transition: context.transition + ) + + context.add(sheet + .position(CGPoint(x: context.availableSize.width / 2.0, y: context.availableSize.height / 2.0)) + ) + + return context.availableSize + } + } +} + +public class ProxyServerPreviewScreen: ViewControllerComponentContainer { + private let context: AccountContext + + public init( + context: AccountContext, + server: ProxyServerSettings + ) { + self.context = context + + super.init( + context: context, + component: ProxyServerPreviewSheetComponent( + context: context, + server: server + ), + navigationBarAppearance: .none, + statusBarStyle: .ignore, + theme: .default + ) + + self.navigationPresentation = .flatModal + } + + required public init(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + public override func viewDidLoad() { + super.viewDidLoad() + + self.view.disablesInteractiveModalDismiss = true + } + + public func dismissAnimated() { + if let view = self.node.hostView.findTaggedView(tag: SheetComponent.View.Tag()) as? SheetComponent.View { + view.dismissAnimated() + } + } +} diff --git a/submodules/TelegramUI/Components/Settings/BusinessIntroSetupScreen/Sources/ChatIntroItemComponent.swift b/submodules/TelegramUI/Components/Settings/BusinessIntroSetupScreen/Sources/ChatIntroItemComponent.swift index 996ed9f9..e1a568e5 100644 --- a/submodules/TelegramUI/Components/Settings/BusinessIntroSetupScreen/Sources/ChatIntroItemComponent.swift +++ b/submodules/TelegramUI/Components/Settings/BusinessIntroSetupScreen/Sources/ChatIntroItemComponent.swift @@ -111,6 +111,7 @@ final class ChatIntroItemComponent: Component { let interfaceState = ChatPresentationInterfaceState( chatWallpaper: presentationData.chatWallpaper, theme: component.theme, + preferredGlassType: .default, strings: component.strings, dateTimeFormat: presentationData.dateTimeFormat, nameDisplayOrder: presentationData.nameDisplayOrder, diff --git a/submodules/TelegramUI/Components/Settings/PeerNameColorScreen/Sources/GiftListItemComponent.swift b/submodules/TelegramUI/Components/Settings/PeerNameColorScreen/Sources/GiftListItemComponent.swift index 4f3676d0..208793d7 100644 --- a/submodules/TelegramUI/Components/Settings/PeerNameColorScreen/Sources/GiftListItemComponent.swift +++ b/submodules/TelegramUI/Components/Settings/PeerNameColorScreen/Sources/GiftListItemComponent.swift @@ -168,7 +168,7 @@ final class GiftListItemComponent: Component { if let current = self.resaleGiftsContexts[id] { resaleGiftsContext = current } else { - resaleGiftsContext = ResaleGiftsContext(account: component.context.account, giftId: id) + resaleGiftsContext = ResaleGiftsContext(account: component.context.account, giftId: id, forCrafting: false) self.resaleGiftsContexts[id] = resaleGiftsContext } diff --git a/submodules/TelegramUI/Components/Settings/PeerNameColorScreen/Sources/UserApperanceScreen.swift b/submodules/TelegramUI/Components/Settings/PeerNameColorScreen/Sources/UserApperanceScreen.swift index f1f1f24b..2526b8d2 100644 --- a/submodules/TelegramUI/Components/Settings/PeerNameColorScreen/Sources/UserApperanceScreen.swift +++ b/submodules/TelegramUI/Components/Settings/PeerNameColorScreen/Sources/UserApperanceScreen.swift @@ -762,9 +762,9 @@ final class UserAppearanceScreenComponent: Component { slug: slug, owner: .peerId(component.context.account.peerId), attributes: [ - .model(name: "", file: file, rarity: 0), - .pattern(name: "", file: patternFile, rarity: 0), - .backdrop(name: "", id: 0, innerColor: innerColor, outerColor: outerColor, patternColor: patternColor, textColor: textColor, rarity: 0) + .model(name: "", file: file, rarity: .permille(0), crafted: false), + .pattern(name: "", file: patternFile, rarity: .permille(0)), + .backdrop(name: "", id: 0, innerColor: innerColor, outerColor: outerColor, patternColor: patternColor, textColor: textColor, rarity: .permille(0)) ], availability: StarGift.UniqueGift.Availability(issued: 0, total: 0), giftAddress: nil, @@ -778,7 +778,8 @@ final class UserAppearanceScreenComponent: Component { themePeerId: nil, peerColor: nil, hostPeerId: nil, - minOfferStars: nil + minOfferStars: nil, + craftChancePermille: nil ) signal = component.context.engine.accountData.setStarGiftStatus(starGift: gift, expirationDate: emojiStatus.expirationDate) } else { @@ -1406,7 +1407,7 @@ final class UserAppearanceScreenComponent: Component { } let listTransition = transition.withUserData(ListSectionComponent.TransitionHint(forceUpdate: forceGiftsUpdate)) - let giftsSectionSize = self.profileGiftsSection.update( + let giftsSectionSize: CGSize = self.profileGiftsSection.update( transition: listTransition, component: AnyComponent(ListSectionComponent( theme: environment.theme, @@ -1442,7 +1443,7 @@ final class UserAppearanceScreenComponent: Component { var textColor: Int32? for attribute in gift.attributes { switch attribute { - case let .model(_, file, _): + case let .model(_, file, _, _): fileId = file.fileId.id self.cachedIconFiles[file.fileId.id] = file case let .pattern(_, file, _): diff --git a/submodules/TelegramUI/Components/Stars/StarsTransactionsScreen/Sources/StarsTransactionsListPanelComponent.swift b/submodules/TelegramUI/Components/Stars/StarsTransactionsScreen/Sources/StarsTransactionsListPanelComponent.swift index 040bbfa9..820b5ce5 100644 --- a/submodules/TelegramUI/Components/Stars/StarsTransactionsScreen/Sources/StarsTransactionsListPanelComponent.swift +++ b/submodules/TelegramUI/Components/Stars/StarsTransactionsScreen/Sources/StarsTransactionsListPanelComponent.swift @@ -345,7 +345,7 @@ final class StarsTransactionsListPanelComponent: Component { itemSubtitle = item.count.amount > StarsAmount.zero ? environment.strings.Stars_Intro_Transaction_ConvertedGift : environment.strings.Stars_Intro_Transaction_Gift case let .unique(gift): for attribute in gift.attributes { - if case let .model(_, file, _) = attribute { + if case let .model(_, file, _, _) = attribute { itemFile = file break } diff --git a/submodules/TelegramUI/Components/Stories/StoryContainerScreen/BUILD b/submodules/TelegramUI/Components/Stories/StoryContainerScreen/BUILD index 797719a4..07697b0e 100644 --- a/submodules/TelegramUI/Components/Stories/StoryContainerScreen/BUILD +++ b/submodules/TelegramUI/Components/Stories/StoryContainerScreen/BUILD @@ -1,5 +1,10 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGStrings:SGStrings", + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + swift_library( name = "StoryContainerScreen", module_name = "StoryContainerScreen", @@ -9,7 +14,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/Display", "//submodules/AsyncDisplayKit", "//submodules/ComponentFlow", diff --git a/submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/SGStoryWarningComponent.swift b/submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/SGStoryWarningComponent.swift new file mode 100644 index 00000000..6909e589 --- /dev/null +++ b/submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/SGStoryWarningComponent.swift @@ -0,0 +1,194 @@ +import Foundation +import UIKit +import Display +import ComponentFlow +import TelegramCore +import TelegramPresentationData +import AccountContext + +final class SGStoryWarningComponent: Component { + typealias EnvironmentType = Empty + + let context: AccountContext + let theme: PresentationTheme + let strings: PresentationStrings + let peer: EnginePeer? + let isInStealthMode: Bool + let action: () -> Void + let close: () -> Void + + init( + context: AccountContext, + theme: PresentationTheme, + strings: PresentationStrings, + peer: EnginePeer?, + isInStealthMode: Bool, + action: @escaping () -> Void, + close: @escaping () -> Void + ) { + self.context = context + self.theme = theme + self.strings = strings + self.peer = peer + self.isInStealthMode = isInStealthMode + self.action = action + self.close = close + } + + static func ==(lhs: SGStoryWarningComponent, rhs: SGStoryWarningComponent) -> Bool { + if lhs.context !== rhs.context { + return false + } + if lhs.theme !== rhs.theme { + return false + } + if lhs.strings !== rhs.strings { + return false + } + if lhs.peer?.id != rhs.peer?.id { + return false + } + if lhs.isInStealthMode != rhs.isInStealthMode { + return false + } + return true + } + + final class View: UIView { + private let dimView = UIView() + private let panelView = UIView() + private let titleLabel = UILabel() + private let textLabel = UILabel() + private let continueButton = UIButton(type: .system) + private let closeButton = UIButton(type: .system) + + private var component: SGStoryWarningComponent? + + override init(frame: CGRect) { + super.init(frame: frame) + + self.dimView.backgroundColor = UIColor(white: 0.0, alpha: 0.5) + self.addSubview(self.dimView) + + self.panelView.layer.cornerRadius = 22.0 + self.panelView.layer.masksToBounds = true + self.addSubview(self.panelView) + + self.titleLabel.numberOfLines = 0 + self.titleLabel.textAlignment = .center + self.panelView.addSubview(self.titleLabel) + + self.textLabel.numberOfLines = 0 + self.textLabel.textAlignment = .center + self.panelView.addSubview(self.textLabel) + + self.continueButton.layer.cornerRadius = 11.0 + self.continueButton.layer.masksToBounds = true + self.continueButton.titleLabel?.font = Font.semibold(17.0) + self.continueButton.addTarget(self, action: #selector(self.continuePressed), for: .touchUpInside) + self.panelView.addSubview(self.continueButton) + + self.closeButton.titleLabel?.font = Font.regular(15.0) + self.closeButton.addTarget(self, action: #selector(self.closePressed), for: .touchUpInside) + self.panelView.addSubview(self.closeButton) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + @objc private func continuePressed() { + self.component?.action() + } + + @objc private func closePressed() { + self.component?.close() + } + + func animateIn() { + self.dimView.alpha = 0.0 + self.panelView.alpha = 0.0 + self.panelView.transform = CGAffineTransform(scaleX: 0.92, y: 0.92) + UIView.animate(withDuration: 0.22, delay: 0.0, options: [.curveEaseOut]) { + self.dimView.alpha = 1.0 + self.panelView.alpha = 1.0 + self.panelView.transform = .identity + } + } + + func animateOut(completion: @escaping () -> Void) { + UIView.animate(withDuration: 0.18, delay: 0.0, options: [.curveEaseIn], animations: { + self.dimView.alpha = 0.0 + self.panelView.alpha = 0.0 + self.panelView.transform = CGAffineTransform(scaleX: 0.92, y: 0.92) + }, completion: { _ in + completion() + }) + } + + func update(component: SGStoryWarningComponent, availableSize: CGSize, transition: ComponentTransition) -> CGSize { + self.component = component + + self.dimView.frame = CGRect(origin: .zero, size: availableSize) + self.panelView.backgroundColor = component.theme.actionSheet.opaqueItemBackgroundColor + + self.titleLabel.textColor = component.theme.actionSheet.primaryTextColor + self.textLabel.textColor = component.theme.actionSheet.secondaryTextColor + + let title = component.isInStealthMode ? "Stealth Mode Is Enabled" : "Story View Warning" + let text: String + if component.isInStealthMode { + text = "You are about to continue viewing stories while stealth mode is active. Swiftgram story actions may differ until migration is fully finished." + } else { + text = "Swiftgram story-specific warning UI is running in compatibility mode in this merged build. You can continue, but verify story actions carefully." + } + + self.titleLabel.attributedText = NSAttributedString( + string: title, + font: Font.semibold(20.0), + textColor: component.theme.actionSheet.primaryTextColor + ) + self.textLabel.attributedText = NSAttributedString( + string: text, + font: Font.regular(15.0), + textColor: component.theme.actionSheet.secondaryTextColor + ) + + self.continueButton.backgroundColor = component.theme.list.itemCheckColors.fillColor + self.continueButton.setTitleColor(component.theme.list.itemCheckColors.foregroundColor, for: .normal) + self.continueButton.setTitle("Continue", for: .normal) + + self.closeButton.setTitleColor(component.theme.list.itemAccentColor, for: .normal) + self.closeButton.setTitle("Close", for: .normal) + + let panelWidth = min(availableSize.width - 32.0, 360.0) + let titleSize = self.titleLabel.sizeThatFits(CGSize(width: panelWidth - 32.0, height: CGFloat.greatestFiniteMagnitude)) + let textSize = self.textLabel.sizeThatFits(CGSize(width: panelWidth - 32.0, height: CGFloat.greatestFiniteMagnitude)) + let buttonHeight: CGFloat = 50.0 + let closeHeight: CGFloat = 22.0 + let panelHeight = 24.0 + titleSize.height + 12.0 + textSize.height + 20.0 + buttonHeight + 12.0 + closeHeight + 20.0 + let panelFrame = CGRect( + x: floor((availableSize.width - panelWidth) * 0.5), + y: floor((availableSize.height - panelHeight) * 0.5), + width: panelWidth, + height: panelHeight + ) + transition.setFrame(view: self.panelView, frame: panelFrame) + + self.titleLabel.frame = CGRect(x: 16.0, y: 24.0, width: panelWidth - 32.0, height: titleSize.height) + self.textLabel.frame = CGRect(x: 16.0, y: self.titleLabel.frame.maxY + 12.0, width: panelWidth - 32.0, height: textSize.height) + self.continueButton.frame = CGRect(x: 16.0, y: self.textLabel.frame.maxY + 20.0, width: panelWidth - 32.0, height: buttonHeight) + self.closeButton.frame = CGRect(x: 16.0, y: self.continueButton.frame.maxY + 12.0, width: panelWidth - 32.0, height: closeHeight) + + return availableSize + } + } + + func makeView() -> View { + return View(frame: CGRect()) + } + + func update(view: View, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + return view.update(component: self, availableSize: availableSize, transition: transition) + } +} diff --git a/submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryContainerScreen.swift b/submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryContainerScreen.swift index 68a5ca4a..477e1220 100644 --- a/submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryContainerScreen.swift +++ b/submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryContainerScreen.swift @@ -1,3 +1,7 @@ +// MARK: Swiftgram +import TelegramUIPreferences +import SGSimpleSettings + import Foundation import UIKit import Display @@ -426,7 +430,12 @@ private final class StoryContainerScreenComponent: Component { var longPressRecognizer: StoryLongPressRecognizer? private var pendingNavigationToItemId: StoryId? - + + private let storiesWarning = ComponentView() + private var requestedDisplayStoriesWarning: Bool = SGSimpleSettings.shared.warnOnStoriesOpen // MARK: Swiftgram + private var displayStoriesWarningDisposable: Disposable? + private var isDisplayingStoriesWarning: Bool = false + private let interactionGuide = ComponentView() private var isDisplayingInteractionGuide: Bool = false private var displayInteractionGuideDisposable: Disposable? @@ -459,7 +468,7 @@ private final class StoryContainerScreenComponent: Component { guard let self, let stateValue = self.stateValue, let slice = stateValue.slice, let itemSetView = self.visibleItemSetViews[slice.peer.id], let itemSetComponentView = itemSetView.view.view as? StoryItemSetContainerComponent.View else { return [] } - if self.isDisplayingInteractionGuide { + if self.isDisplayingInteractionGuide || self.isDisplayingStoriesWarning { return [] } if let environment = self.environment, case .regular = environment.metrics.widthClass { @@ -592,7 +601,7 @@ private final class StoryContainerScreenComponent: Component { guard let self else { return false } - if self.isDisplayingInteractionGuide { + if self.isDisplayingInteractionGuide || self.isDisplayingStoriesWarning { return false } if let stateValue = self.stateValue, let slice = stateValue.slice, let itemSetView = self.visibleItemSetViews[slice.peer.id] { @@ -745,6 +754,7 @@ private final class StoryContainerScreenComponent: Component { deinit { self.contentUpdatedDisposable?.dispose() + self.displayStoriesWarningDisposable?.dispose() self.volumeButtonsListenerShouldBeActiveDisposable?.dispose() self.headphonesDisposable?.dispose() self.stealthModeDisposable?.dispose() @@ -1073,7 +1083,7 @@ private final class StoryContainerScreenComponent: Component { guard let self else { return } - if !value && !self.isDisplayingInteractionGuide { + if !value && (!self.isDisplayingInteractionGuide || !self.isDisplayingStoriesWarning) { if let stateValue = self.stateValue, let slice = stateValue.slice, let itemSetView = self.visibleItemSetViews[slice.peer.id], let currentItemView = itemSetView.view.view as? StoryItemSetContainerComponent.View { currentItemView.maybeDisplayReactionTooltip() } @@ -1317,6 +1327,16 @@ private final class StoryContainerScreenComponent: Component { } }) + // MARK: Swiftgram + self.requestedDisplayStoriesWarning = SGSimpleSettings.shared.warnOnStoriesOpen + if self.requestedDisplayStoriesWarning { + self.isDisplayingStoriesWarning = true + if update { + self.state?.updated(transition: .immediate) + } + } + // + update = true } @@ -1375,6 +1395,11 @@ private final class StoryContainerScreenComponent: Component { if case .file = slice.item.storyItem.media { isVideo = true } + // TODO(swiftgram): Show warning on each new peerId story + /* if self.requestedDisplayStoriesWarning, let previousSlice = stateValue?.previousSlice, previousSlice.peer.id != slice.peer.id { + self.isDisplayingStoriesWarning = self.requestedDisplayStoriesWarning + update = false + }*/ } self.focusedItem.set(focusedItemId) self.contentWantsVolumeButtonMonitoring.set(isVideo) @@ -1503,7 +1528,7 @@ private final class StoryContainerScreenComponent: Component { if self.pendingNavigationToItemId != nil { isProgressPaused = true } - if self.isDisplayingInteractionGuide { + if self.isDisplayingInteractionGuide || self.isDisplayingStoriesWarning { isProgressPaused = true } @@ -1968,6 +1993,54 @@ private final class StoryContainerScreenComponent: Component { controller.presentationContext.containerLayoutUpdated(subLayout, transition: transition.containedViewLayoutTransition) } + // MARK: Swiftgram + if self.isDisplayingStoriesWarning { + let _ = self.storiesWarning.update( + transition: .immediate, + component: AnyComponent( + SGStoryWarningComponent( + context: component.context, + theme: environment.theme, + strings: environment.strings, + peer: component.content.stateValue?.slice?.peer, + isInStealthMode: stealthModeTimeout != nil || SGSimpleSettings.shared.isStealthModeEnabled, + action: { [weak self] in + self?.isDisplayingStoriesWarning = false + self?.state?.updated(transition: .immediate) + if let view = self?.storiesWarning.view as? SGStoryWarningComponent.View { + view.animateOut(completion: { + view.removeFromSuperview() + }) + } + }, + close: { [weak self] in + self?.environment?.controller()?.dismiss() + if let view = self?.storiesWarning.view as? SGStoryWarningComponent.View { + view.animateOut(completion: { + view.removeFromSuperview() + }) + } + } + ) + ), + environment: {}, + containerSize: availableSize + ) + if let view = self.storiesWarning.view as? SGStoryWarningComponent.View { + if view.superview == nil { + self.addSubview(view) + + view.animateIn() + } + view.layer.zPosition = 1000.0 + view.frame = CGRect(origin: .zero, size: availableSize) + } + } else if let view = self.storiesWarning.view as? SGStoryWarningComponent.View, view.superview != nil { + view.animateOut(completion: { + view.removeFromSuperview() + }) + } + if self.isDisplayingInteractionGuide { let _ = self.interactionGuide.update( transition: .immediate, diff --git a/submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerComponent.swift b/submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerComponent.swift index a037a504..fe0d4c7e 100644 --- a/submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerComponent.swift +++ b/submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerComponent.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import Display @@ -3826,7 +3827,7 @@ public final class StoryItemSetContainerComponent: Component { let items = ContextController.Items(content: .list(itemList)) - let controller = ContextController( + let controller = makeContextController( presentationData: presentationData, source: .extracted(ListContextExtractedContentSource(contentView: sourceView)), items: .single(items), @@ -6761,7 +6762,7 @@ public final class StoryItemSetContainerComponent: Component { return .single(ContextController.Items(id: 0, content: .list(items), tip: tip, tipSignal: tipSignal)) } - let contextController = ContextController(presentationData: presentationData, source: .reference(HeaderContextReferenceContentSource(controller: controller, sourceView: sourceView, position: .bottom)), items: contextItems, gesture: gesture) + let contextController = makeContextController(presentationData: presentationData, source: .reference(HeaderContextReferenceContentSource(controller: controller, sourceView: sourceView, position: .bottom)), items: contextItems, gesture: gesture) contextController.dismissed = { [weak self] in guard let self else { return @@ -7095,7 +7096,7 @@ public final class StoryItemSetContainerComponent: Component { return .single(ContextController.Items(id: 0, content: .list(items), tip: tip, tipSignal: tipSignal)) } - let contextController = ContextController(presentationData: presentationData, source: .reference(HeaderContextReferenceContentSource(controller: controller, sourceView: sourceView, position: .bottom)), items: contextItems, gesture: gesture) + let contextController = makeContextController(presentationData: presentationData, source: .reference(HeaderContextReferenceContentSource(controller: controller, sourceView: sourceView, position: .bottom)), items: contextItems, gesture: gesture) contextController.dismissed = { [weak self] in guard let self else { return @@ -7526,7 +7527,7 @@ public final class StoryItemSetContainerComponent: Component { let contextItems = ContextController.Items(id: 0, content: .list(items), tip: tip, tipSignal: tipSignal) - let contextController = ContextController(presentationData: presentationData, source: .reference(HeaderContextReferenceContentSource(controller: controller, sourceView: sourceView, position: .bottom)), items: .single(contextItems), gesture: gesture) + let contextController = makeContextController(presentationData: presentationData, source: .reference(HeaderContextReferenceContentSource(controller: controller, sourceView: sourceView, position: .bottom)), items: .single(contextItems), gesture: gesture) contextController.dismissed = { [weak self] in guard let self else { return diff --git a/submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerViewSendMessage.swift b/submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerViewSendMessage.swift index 619f13e4..c7301c6c 100644 --- a/submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerViewSendMessage.swift +++ b/submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerViewSendMessage.swift @@ -345,6 +345,7 @@ final class StoryItemSetContainerSendMessage: @unchecked(Sendable) { let presentationInterfaceState = ChatPresentationInterfaceState( chatWallpaper: .builtin(WallpaperSettings()), theme: presentationData.theme, + preferredGlassType: .default, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameDisplayOrder: presentationData.nameDisplayOrder, diff --git a/submodules/TelegramUI/Components/TabBarComponent/BUILD b/submodules/TelegramUI/Components/TabBarComponent/BUILD index ad24d1f7..93521ddb 100644 --- a/submodules/TelegramUI/Components/TabBarComponent/BUILD +++ b/submodules/TelegramUI/Components/TabBarComponent/BUILD @@ -1,5 +1,9 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings" +] + swift_library( name = "TabBarComponent", module_name = "TabBarComponent", @@ -9,7 +13,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/Display", "//submodules/TelegramPresentationData", "//submodules/ComponentFlow", diff --git a/submodules/TelegramUI/Components/TabBarComponent/Sources/TabBarComponent.swift b/submodules/TelegramUI/Components/TabBarComponent/Sources/TabBarComponent.swift index 9d97455e..abd5febd 100644 --- a/submodules/TelegramUI/Components/TabBarComponent/Sources/TabBarComponent.swift +++ b/submodules/TelegramUI/Components/TabBarComponent/Sources/TabBarComponent.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import Display @@ -111,7 +112,7 @@ public final class NavigationSearchView: UIView { transition.setFrame(view: self.backgroundView, frame: CGRect(origin: CGPoint(), size: backgroundSize)) let alphaTransition: ComponentTransition = transition.animation.isImmediate ? .immediate : .easeInOut(duration: 0.25) - self.backgroundView.update(size: backgroundSize, cornerRadius: backgroundSize.height * 0.5, isDark: params.theme.overallDarkAppearance, tintColor: .init(kind: .panel, color: UIColor(white: params.theme.overallDarkAppearance ? 0.0 : 1.0, alpha: 0.6)), isInteractive: true, transition: transition) + self.backgroundView.update(size: backgroundSize, cornerRadius: backgroundSize.height * 0.5, isDark: params.theme.overallDarkAppearance, tintColor: .init(kind: .panel), isInteractive: true, transition: transition) if self.iconView.image == nil { self.iconView.image = UIImage(bundleImageName: "Navigation/Search")?.withRenderingMode(.alwaysTemplate) @@ -215,7 +216,7 @@ public final class NavigationSearchView: UIView { } close.background.frame = closeFrame.size.centered(in: previousBackgroundFrame) - close.background.update(size: close.background.bounds.size, cornerRadius: close.background.bounds.height * 0.5, isDark: params.theme.overallDarkAppearance, tintColor: .init(kind: .panel, color: UIColor(white: params.theme.overallDarkAppearance ? 0.0 : 1.0, alpha: 0.6)), isInteractive: true, transition: .immediate) + close.background.update(size: close.background.bounds.size, cornerRadius: close.background.bounds.height * 0.5, isDark: params.theme.overallDarkAppearance, tintColor: .init(kind: .panel), isInteractive: true, transition: .immediate) ComponentTransition.immediate.setScale(view: close.background, scale: 0.001) } @@ -229,7 +230,7 @@ public final class NavigationSearchView: UIView { transition.setFrame(view: close.icon, frame: image.size.centered(in: CGRect(origin: CGPoint(), size: closeFrame.size))) } - close.background.update(size: closeFrame.size, cornerRadius: closeFrame.height * 0.5, isDark: params.theme.overallDarkAppearance, tintColor: .init(kind: .panel, color: UIColor(white: params.theme.overallDarkAppearance ? 0.0 : 1.0, alpha: 0.6)), isInteractive: true, transition: closeTransition) + close.background.update(size: closeFrame.size, cornerRadius: closeFrame.height * 0.5, isDark: params.theme.overallDarkAppearance, tintColor: .init(kind: .panel), isInteractive: true, transition: closeTransition) } else { if let close = self.close { self.close = nil @@ -237,7 +238,7 @@ public final class NavigationSearchView: UIView { let closeFrame = CGSize(width: 48.0, height: 48.0).centered(in: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: params.size)) transition.setPosition(view: closeBackground, position: closeFrame.center) transition.setBounds(view: closeBackground, bounds: CGRect(origin: CGPoint(), size: closeFrame.size)) - closeBackground.update(size: closeFrame.size, cornerRadius: closeFrame.height * 0.5, isDark: params.theme.overallDarkAppearance, tintColor: .init(kind: .panel, color: UIColor(white: params.theme.overallDarkAppearance ? 0.0 : 1.0, alpha: 0.6)), isInteractive: true, transition: transition) + closeBackground.update(size: closeFrame.size, cornerRadius: closeFrame.height * 0.5, isDark: params.theme.overallDarkAppearance, tintColor: .init(kind: .panel), isInteractive: true, transition: transition) transition.setScale(view: closeBackground, scale: 0.001, completion: { [weak closeBackground] _ in closeBackground?.removeFromSuperview() }) @@ -556,7 +557,28 @@ public final class TabBarComponent: Component { let _ = alphaTransition let innerInset: CGFloat = 4.0 - let availableSize = CGSize(width: min(500.0, availableSize.width), height: availableSize.height) + var availableSize = CGSize(width: min(500.0, availableSize.width), height: availableSize.height) + if !(SGSimpleSettings.shared.wideTabBar || component.search?.isActive ?? false) { + let widthReducer: CGFloat + + switch component.items.count { + case 1: + widthReducer = 1.75 + case 2: + widthReducer = 1.5 + case 3: + widthReducer = 1.25 + case 4: + widthReducer = 1.0 + default: + widthReducer = 1.0 + } + availableSize.width = availableSize.width / widthReducer + if !SGSimpleSettings.shared.tabBarSearchEnabled { + availableSize.width -= 48.0 + availableSize.width -= innerInset * 2.0 + } + } let previousComponent = self.component self.component = component @@ -564,7 +586,7 @@ public final class TabBarComponent: Component { self.overrideUserInterfaceStyle = component.theme.overallDarkAppearance ? .dark : .light - let barHeight: CGFloat = 56.0 + innerInset * 2.0 + let barHeight: CGFloat = (SGSimpleSettings.shared.showTabNames ? 56.0 : 40.0) + innerInset * 2.0 var availableItemsWidth: CGFloat = availableSize.width - innerInset * 2.0 if component.search != nil { @@ -597,7 +619,7 @@ public final class TabBarComponent: Component { isUnconstrained: true )), environment: {}, - containerSize: CGSize(width: 200.0, height: 56.0) + containerSize: CGSize(width: 200.0, height: SGSimpleSettings.shared.showTabNames ? 56.0 : 40.0) ) unboundItemWidths.append(itemSize.width) @@ -626,7 +648,7 @@ public final class TabBarComponent: Component { totalItemsWidth = total } - let itemHeight: CGFloat = 56.0 + let itemHeight: CGFloat = (SGSimpleSettings.shared.showTabNames ? 56.0 : 40.0) let contentWidth: CGFloat = innerInset * 2.0 + totalItemsWidth let tabsSize = CGSize(width: min(availableSize.width, contentWidth), height: itemHeight + innerInset * 2.0) @@ -767,7 +789,7 @@ public final class TabBarComponent: Component { } else if let selectionFrame { lensSelection = (selectionFrame.minX - innerInset, selectionFrame.width + innerInset * 2.0) } else { - lensSelection = (0.0, 56.0) + lensSelection = (0.0, (SGSimpleSettings.shared.showTabNames ? 56.0 : 40.0)) } var lensSize: CGSize = tabsSize @@ -1060,7 +1082,7 @@ private final class ItemComponent: Component { containerSize: CGSize(width: availableSize.width, height: 100.0) ) let titleFrame = CGRect(origin: CGPoint(x: floor((availableSize.width - titleSize.width) * 0.5), y: availableSize.height - 8.0 - titleSize.height), size: titleSize) - if let titleView = self.title.view { + if SGSimpleSettings.shared.showTabNames, let titleView = self.title.view { if titleView.superview == nil { self.contextContainerView.contentView.addSubview(titleView) } diff --git a/submodules/TelegramUI/Components/TextFieldComponent/Sources/TextFieldComponent.swift b/submodules/TelegramUI/Components/TextFieldComponent/Sources/TextFieldComponent.swift index ac25591b..90a52636 100644 --- a/submodules/TelegramUI/Components/TextFieldComponent/Sources/TextFieldComponent.swift +++ b/submodules/TelegramUI/Components/TextFieldComponent/Sources/TextFieldComponent.swift @@ -334,6 +334,9 @@ public final class TextFieldComponent: Component { return InputState(inputText: stateAttributedStringForText(self.textView.attributedText ?? NSAttributedString()), selectionRange: selectionRange) } + // MARK: Swiftgram + var sgToolbarActionObserver: NSObjectProtocol? = nil + private var component: TextFieldComponent? private weak var state: EmptyComponentState? private var isUpdating: Bool = false @@ -412,6 +415,21 @@ public final class TextFieldComponent: Component { ) } } + + // MARK: Swiftgram + self.sgToolbarActionObserver = NotificationCenter.default.addObserver(forName: Notification.Name("sgToolbarAction"), object: nil, queue: .main, using: { [weak self] notification in + guard let self = self else { return } + if let action = notification.userInfo?["action"] as? String { + self.sgToolbarAction(action) + } + }) + } + + // MARK: Swiftgram + deinit { + if let sgToolbarActionObserver = self.sgToolbarActionObserver { + NotificationCenter.default.removeObserver(sgToolbarActionObserver) + } } required init?(coder: NSCoder) { @@ -588,8 +606,16 @@ public final class TextFieldComponent: Component { self.state?.updated(transition: ComponentTransition(animation: .curve(duration: 0.4, curve: .spring)).withUserData(AnimationHint(view: self, kind: .textChanged))) } } - + public func chatInputTextNodeShouldReturn() -> Bool { + return self.chatInputTextNodeShouldReturnInternal(modifierFlags: []) + } + + public func chatInputTextNodeShouldReturn(modifierFlags: UIKeyModifierFlags) -> Bool { + return self.chatInputTextNodeShouldReturnInternal(modifierFlags: modifierFlags) + } + + private func chatInputTextNodeShouldReturnInternal(modifierFlags: UIKeyModifierFlags) -> Bool { guard let component = self.component else { return true } @@ -1793,3 +1819,134 @@ extension TextFieldComponent.InputState { } } } + + +extension TextFieldComponent.View { + + func sgToolbarAction(_ action: String) { + switch action { + case "quote": + self.sgSelectLastWordIfIdle() + self.toggleAttribute(key: ChatTextInputAttributes.block, value: ChatTextInputTextQuoteAttribute(kind: .quote, isCollapsed: false)) + case "spoiler": + self.sgSelectLastWordIfIdle() + self.toggleAttribute(key: ChatTextInputAttributes.spoiler) + case "bold": + self.sgSelectLastWordIfIdle() + self.toggleAttribute(key: ChatTextInputAttributes.bold) + case "italic": + self.sgSelectLastWordIfIdle() + self.toggleAttribute(key: ChatTextInputAttributes.italic) + case "monospace": + self.sgSelectLastWordIfIdle() + self.toggleAttribute(key: ChatTextInputAttributes.monospace) + case "link": + self.sgSelectLastWordIfIdle() + self.openLinkEditing() + case "strikethrough": + self.sgSelectLastWordIfIdle() + self.toggleAttribute(key: ChatTextInputAttributes.strikethrough) + case "underline": + self.sgSelectLastWordIfIdle() + self.toggleAttribute(key: ChatTextInputAttributes.underline) + case "code": + self.sgSelectLastWordIfIdle() + self.toggleAttribute(key: ChatTextInputAttributes.block, value: ChatTextInputTextQuoteAttribute(kind: .code(language: nil), isCollapsed: false)) + case "newline": + self.sgSetNewLine() + case "clearFormatting": + self.updateInputState { current in + return current.clearFormattingAttributes() + } + default: + assert(false, "Unhandled action \(action)") + } + } + + func sgSelectLastWordIfIdle() { + self.updateInputState { current in + // No changes to current selection + if !current.selectionRange.isEmpty { + return current + } + + let inputText = (current.inputText.mutableCopy() as? NSMutableAttributedString) ?? NSMutableAttributedString() + + // If text is empty or cursor is at the start, return current state + guard inputText.length > 0, current.selectionRange.lowerBound > 0 else { + return current + } + + let plainText = inputText.string + let nsString = plainText as NSString + + // Create character set for word boundaries + let wordBoundaries = CharacterSet.whitespacesAndNewlines + + // Start from cursor position instead of end of text + var endIndex = current.selectionRange.lowerBound - 1 + + // Find last non-whitespace character before cursor + while endIndex >= 0 && + (nsString.substring(with: NSRange(location: endIndex, length: 1)) as NSString) + .rangeOfCharacter(from: wordBoundaries).location != NSNotFound { + endIndex -= 1 + } + + // If we only had whitespace before cursor, return current state + guard endIndex >= 0 else { + return current + } + + // Find start of the current word by looking backwards for whitespace + var startIndex = endIndex + while startIndex > 0 { + let char = nsString.substring(with: NSRange(location: startIndex - 1, length: 1)) + if (char as NSString).rangeOfCharacter(from: wordBoundaries).location != NSNotFound { + break + } + startIndex -= 1 + } + + // Create range for the word at cursor + let wordLength = endIndex - startIndex + 1 + let wordRange = NSRange(location: startIndex, length: wordLength) + + // Create new selection range + let newSelectionRange = wordRange.location ..< (wordRange.location + wordLength) + + return TextFieldComponent.InputState(inputText: inputText, selectionRange: newSelectionRange) + } + } + + func sgSetNewLine() { + self.updateInputState { current in + let inputText = (current.inputText.mutableCopy() as? NSMutableAttributedString) ?? NSMutableAttributedString() + + // Check if there's selected text + let hasSelection = current.selectionRange.count > 0 + + if hasSelection { + // Move selected text to new line + let selectedText = inputText.attributedSubstring(from: NSRange(current.selectionRange)) + let newLineAttr = NSAttributedString(string: "\n") + + // Insert newline and selected text + inputText.replaceCharacters(in: NSRange(current.selectionRange), with: newLineAttr) + inputText.insert(selectedText, at: current.selectionRange.lowerBound + 1) + + // Update selection range to end of moved text + let newPosition = current.selectionRange.lowerBound + 1 + selectedText.length + return TextFieldComponent.InputState(inputText: inputText, selectionRange: newPosition ..< newPosition) + } else { + // Simple newline insertion at current position + let attributedString = NSAttributedString(string: "\n") + inputText.replaceCharacters(in: NSRange(current.selectionRange), with: attributedString) + + // Update cursor position + let newPosition = current.selectionRange.lowerBound + attributedString.length + return TextFieldComponent.InputState(inputText: inputText, selectionRange: newPosition ..< newPosition) + } + } + } +} diff --git a/submodules/TelegramUI/Components/TranslateHeaderPanelComponent/Sources/ChatTranslationPanelNode.swift b/submodules/TelegramUI/Components/TranslateHeaderPanelComponent/Sources/ChatTranslationPanelNode.swift index 42b05c81..36c3cf31 100644 --- a/submodules/TelegramUI/Components/TranslateHeaderPanelComponent/Sources/ChatTranslationPanelNode.swift +++ b/submodules/TelegramUI/Components/TranslateHeaderPanelComponent/Sources/ChatTranslationPanelNode.swift @@ -21,6 +21,17 @@ import ComponentFlow import ComponentDisplayAdapters import LocalMediaResources import AppBundle +import SGSimpleSettings + +private func sgChatTranslationAvailable(isPremium: Bool, peer: EnginePeer?) -> Bool { + if isPremium || SGSimpleSettings.shared.translationBackendEnum != .default { + return true + } + if case let .channel(channel)? = peer, channel.flags.contains(.autoTranslateEnabled) { + return true + } + return false +} final class ChatTranslationPanelNode: ASDisplayNode { private let context: AccountContext @@ -179,7 +190,7 @@ final class ChatTranslationPanelNode: ASDisplayNode { let closeButtonSize = self.closeButton.measure(CGSize(width: 100.0, height: 100.0)) self.closeButton.frame = CGRect(origin: CGPoint(x: width - contentRightInset - closeButtonSize.width, y: floorToScreenPixels((panelHeight - closeButtonSize.height) / 2.0)), size: closeButtonSize) - if info.isPremium { + if sgChatTranslationAvailable(isPremium: info.isPremium, peer: info.peer) { self.moreButton.isHidden = false self.closeButton.isHidden = true } else { @@ -212,11 +223,7 @@ final class ChatTranslationPanelNode: ASDisplayNode { return } let isPremium = info.isPremium - - var translationAvailable = isPremium - if case let .channel(channel) = info.peer, channel.flags.contains(.autoTranslateEnabled) { - translationAvailable = true - } + let translationAvailable = sgChatTranslationAvailable(isPremium: isPremium, peer: info.peer) if translationAvailable { self.close() @@ -231,11 +238,7 @@ final class ChatTranslationPanelNode: ASDisplayNode { } let isPremium = info.isPremium - - var translationAvailable = isPremium - if case let .channel(channel) = info.peer, channel.flags.contains(.autoTranslateEnabled) { - translationAvailable = true - } + let translationAvailable = sgChatTranslationAvailable(isPremium: isPremium, peer: info.peer) if translationAvailable { self.toggle() diff --git a/submodules/TelegramUI/Components/VideoMessageCameraScreen/BUILD b/submodules/TelegramUI/Components/VideoMessageCameraScreen/BUILD index 3a207371..13a713a5 100644 --- a/submodules/TelegramUI/Components/VideoMessageCameraScreen/BUILD +++ b/submodules/TelegramUI/Components/VideoMessageCameraScreen/BUILD @@ -1,5 +1,9 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgDeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings" +] + swift_library( name = "VideoMessageCameraScreen", module_name = "VideoMessageCameraScreen", @@ -9,7 +13,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgDeps + [ "//submodules/AsyncDisplayKit", "//submodules/Display", "//submodules/Postbox", diff --git a/submodules/TelegramUI/Components/VideoMessageCameraScreen/Sources/VideoMessageCameraScreen.swift b/submodules/TelegramUI/Components/VideoMessageCameraScreen/Sources/VideoMessageCameraScreen.swift index d97c26a6..2eec6b75 100644 --- a/submodules/TelegramUI/Components/VideoMessageCameraScreen/Sources/VideoMessageCameraScreen.swift +++ b/submodules/TelegramUI/Components/VideoMessageCameraScreen/Sources/VideoMessageCameraScreen.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import Display @@ -599,7 +600,7 @@ private final class VideoMessageCameraScreenComponent: CombinedComponent { size: CGSize(width: 40.0, height: 40.0), cornerRadius: 40.0 * 0.5, isDark: environment.theme.overallDarkAppearance, - tintColor: .init(kind: .panel, color: environment.theme.chat.inputPanel.inputBackgroundColor.withMultipliedAlpha(0.7)) + tintColor: .init(kind: .panel) ), availableSize: CGSize(width: 40.0, height: 40.0), transition: .immediate @@ -702,7 +703,7 @@ private final class VideoMessageCameraScreenComponent: CombinedComponent { size: CGSize(width: 40.0, height: 40.0), cornerRadius: 40.0 * 0.5, isDark: environment.theme.overallDarkAppearance, - tintColor: .init(kind: .panel, color: environment.theme.chat.inputPanel.inputBackgroundColor.withMultipliedAlpha(0.7)) + tintColor: .init(kind: .panel) ), availableSize: CGSize(width: 40.0, height: 40.0), transition: .immediate @@ -734,7 +735,7 @@ private final class VideoMessageCameraScreenComponent: CombinedComponent { size: CGSize(width: 40.0, height: 40.0), cornerRadius: 40.0 * 0.5, isDark: environment.theme.overallDarkAppearance, - tintColor: .init(kind: .panel, color: environment.theme.chat.inputPanel.inputBackgroundColor.withMultipliedAlpha(0.7)) + tintColor: .init(kind: .panel) ) ) ), @@ -779,7 +780,7 @@ private final class VideoMessageCameraScreenComponent: CombinedComponent { size: CGSize(width: 40.0, height: 40.0), cornerRadius: 40.0 * 0.5, isDark: environment.theme.overallDarkAppearance, - tintColor: .init(kind: .panel, color: environment.theme.chat.inputPanel.inputBackgroundColor.withMultipliedAlpha(0.7)) + tintColor: .init(kind: .panel) )) ), AnyComponentWithIdentity( @@ -947,7 +948,8 @@ public class VideoMessageCameraScreen: ViewController { self.previewContainerView.addSubview(self.previewContainerContentView) let isDualCameraEnabled = Camera.isDualCameraSupported(forRoundVideo: true) - let isFrontPosition = "".isEmpty + // MARK: Swiftgram + let isFrontPosition = !SGSimpleSettings.shared.startTelescopeWithRearCam self.mainPreviewView = CameraSimplePreviewView(frame: .zero, main: true, roundVideo: true) self.additionalPreviewView = CameraSimplePreviewView(frame: .zero, main: false, roundVideo: true) @@ -1649,7 +1651,7 @@ public class VideoMessageCameraScreen: ViewController { private var validLayout: ContainerViewLayout? - fileprivate var camera: Camera? { + public var camera: Camera? { return self.node.camera } diff --git a/submodules/TelegramUI/Components/VideoPlaybackControlsComponent/BUILD b/submodules/TelegramUI/Components/VideoPlaybackControlsComponent/BUILD new file mode 100644 index 00000000..e4b28c07 --- /dev/null +++ b/submodules/TelegramUI/Components/VideoPlaybackControlsComponent/BUILD @@ -0,0 +1,25 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "VideoPlaybackControlsComponent", + module_name = "VideoPlaybackControlsComponent", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/Display", + "//submodules/TelegramPresentationData", + "//submodules/Components/ComponentDisplayAdapters", + "//submodules/ComponentFlow", + "//submodules/TelegramUI/Components/GlassBackgroundComponent", + "//submodules/AppBundle", + "//submodules/ManagedAnimationNode", + "//submodules/Components/MultilineTextComponent", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/submodules/TelegramUI/Components/VideoPlaybackControlsComponent/Sources/VideoPlaybackControlsComponent.swift b/submodules/TelegramUI/Components/VideoPlaybackControlsComponent/Sources/VideoPlaybackControlsComponent.swift new file mode 100644 index 00000000..6f386e98 --- /dev/null +++ b/submodules/TelegramUI/Components/VideoPlaybackControlsComponent/Sources/VideoPlaybackControlsComponent.swift @@ -0,0 +1,334 @@ +import Foundation +import UIKit +import Display +import TelegramPresentationData +import ComponentFlow +import GlassBackgroundComponent +import ManagedAnimationNode +import MultilineTextComponent +import AppBundle + +public final class VideoPlaybackControlsComponent: Component { + public struct LayoutParams: Equatable { + public var sideButtonSize: CGFloat + public var centerButtonSize: CGFloat + public var spacing: CGFloat + + public init(sideButtonSize: CGFloat, centerButtonSize: CGFloat, spacing: CGFloat) { + self.sideButtonSize = sideButtonSize + self.centerButtonSize = centerButtonSize + self.spacing = spacing + } + } + + let layoutParams: LayoutParams + let isVisible: Bool + let isPlaying: Bool + let displaySeekControls: Bool + let togglePlayback: () -> Void + let seek: (Bool) -> Void + + public init( + layoutParams: LayoutParams, + isVisible: Bool, + isPlaying: Bool, + displaySeekControls: Bool, + togglePlayback: @escaping () -> Void, + seek: @escaping (Bool) -> Void + ) { + self.layoutParams = layoutParams + self.isVisible = isVisible + self.isPlaying = isPlaying + self.displaySeekControls = displaySeekControls + self.togglePlayback = togglePlayback + self.seek = seek + } + + public static func ==(lhs: VideoPlaybackControlsComponent, rhs: VideoPlaybackControlsComponent) -> Bool { + if lhs.layoutParams != rhs.layoutParams { + return false + } + if lhs.isVisible != rhs.isVisible { + return false + } + if lhs.isPlaying != rhs.isPlaying { + return false + } + if lhs.displaySeekControls != rhs.displaySeekControls { + return false + } + return true + } + + public final class View: UIView { + private let backgroundContainer: GlassBackgroundContainerView + private let leftButtonBackgroundView: GlassBackgroundView + private let leftIconView: PlaybackIconView + private let rightButtonBackgroundView: GlassBackgroundView + private let rightIconView: PlaybackIconView + private let centerButtonBackgroundView: GlassBackgroundView + private var centerButtonIconNode: PlayPauseIconNode? + + private var component: VideoPlaybackControlsComponent? + private weak var state: EmptyComponentState? + + public override init(frame: CGRect) { + self.backgroundContainer = GlassBackgroundContainerView() + + self.leftButtonBackgroundView = GlassBackgroundView() + self.leftIconView = PlaybackIconView(isForward: false) + self.leftIconView.isUserInteractionEnabled = false + self.leftButtonBackgroundView.contentView.addSubview(self.leftIconView) + + self.rightButtonBackgroundView = GlassBackgroundView() + self.rightIconView = PlaybackIconView(isForward: true) + self.rightIconView.isUserInteractionEnabled = false + self.rightButtonBackgroundView.contentView.addSubview(self.rightIconView) + + self.centerButtonBackgroundView = GlassBackgroundView() + + super.init(frame: frame) + + self.addSubview(self.backgroundContainer) + + self.backgroundContainer.contentView.addSubview(self.leftButtonBackgroundView) + self.backgroundContainer.contentView.addSubview(self.rightButtonBackgroundView) + self.backgroundContainer.contentView.addSubview(self.centerButtonBackgroundView) + + self.leftButtonBackgroundView.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.onLeftTapGesture(_:)))) + self.rightButtonBackgroundView.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.onRightTapGesture(_:)))) + self.centerButtonBackgroundView.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.onTapGesture(_:)))) + } + + required public init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + deinit { + } + + @objc private func onLeftTapGesture(_ gesture: UITapGestureRecognizer) { + guard let component = self.component else { + return + } + if case .ended = gesture.state { + component.seek(false) + } + } + + @objc private func onRightTapGesture(_ gesture: UITapGestureRecognizer) { + guard let component = self.component else { + return + } + if case .ended = gesture.state { + component.seek(true) + } + } + + @objc private func onTapGesture(_ gesture: UITapGestureRecognizer) { + guard let component = self.component else { + return + } + if case .ended = gesture.state { + component.togglePlayback() + } + } + + func update(component: VideoPlaybackControlsComponent, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + let isVisibleChanged = self.component?.isVisible != component.isVisible + + self.component = component + self.state = state + + self.isUserInteractionEnabled = component.isVisible + + let containerInset: CGFloat = 32.0 + + let size = CGSize(width: component.layoutParams.sideButtonSize * 2.0 + component.layoutParams.centerButtonSize + component.layoutParams.spacing * 2.0, height: component.layoutParams.centerButtonSize) + + let leftButtonFrame = CGRect(origin: CGPoint(x: 0.0, y: floorToScreenPixels((size.height - component.layoutParams.sideButtonSize) * 0.5)), size: CGSize(width: component.layoutParams.sideButtonSize, height: component.layoutParams.sideButtonSize)).offsetBy(dx: containerInset, dy: containerInset) + let centerButtonFrame = CGRect(origin: CGPoint(x: component.layoutParams.sideButtonSize + component.layoutParams.spacing, y: floorToScreenPixels((size.height - component.layoutParams.centerButtonSize) * 0.5)), size: CGSize(width: component.layoutParams.centerButtonSize, height: component.layoutParams.centerButtonSize)).offsetBy(dx: containerInset, dy: containerInset) + let rightButtonFrame = CGRect(origin: CGPoint(x: size.width - component.layoutParams.sideButtonSize, y: floorToScreenPixels((size.height - component.layoutParams.sideButtonSize) * 0.5)), size: CGSize(width: component.layoutParams.sideButtonSize, height: component.layoutParams.sideButtonSize)).offsetBy(dx: containerInset, dy: containerInset) + + if isVisibleChanged && !transition.animation.isImmediate { + self.backgroundContainer.isHidden = true + self.backgroundContainer.isHidden = false + } + + transition.setFrame(view: self.backgroundContainer, frame: CGRect(origin: CGPoint(), size: size).insetBy(dx: -containerInset, dy: -containerInset)) + self.backgroundContainer.update(size: CGSize(width: size.width + containerInset * 2.0, height: size.height + containerInset * 2.0), isDark: true, transition: transition) + + let areSideButtonsVisible = component.isVisible && component.displaySeekControls + let buttonsTintColor: GlassBackgroundView.TintColor = .init(kind: .custom, color: UIColor(white: 0.0, alpha: 0.2)) + + transition.setFrame(view: self.leftButtonBackgroundView, frame: leftButtonFrame) + self.leftButtonBackgroundView.update(size: leftButtonFrame.size, cornerRadius: leftButtonFrame.height * 0.5, isDark: true, tintColor: buttonsTintColor, isInteractive: true, isVisible: areSideButtonsVisible, transition: transition) + transition.setFrame(view: self.leftIconView, frame: CGRect(origin: CGPoint(), size: leftButtonFrame.size)) + self.leftIconView.update(size: leftButtonFrame.size) + transition.setAlpha(view: self.leftIconView, alpha: areSideButtonsVisible ? 1.0 : 0.0) + transition.setBlur(layer: self.leftIconView.layer, radius: areSideButtonsVisible ? 0.0 : 10.0) + + transition.setFrame(view: self.rightButtonBackgroundView, frame: rightButtonFrame) + self.rightButtonBackgroundView.update(size: rightButtonFrame.size, cornerRadius: rightButtonFrame.height * 0.5, isDark: true, tintColor: buttonsTintColor, isInteractive: true, isVisible: areSideButtonsVisible, transition: transition) + transition.setFrame(view: self.rightIconView, frame: CGRect(origin: CGPoint(), size: rightButtonFrame.size)) + self.rightIconView.update(size: rightButtonFrame.size) + transition.setAlpha(view: self.rightIconView, alpha: areSideButtonsVisible ? 1.0 : 0.0) + transition.setBlur(layer: self.rightIconView.layer, radius: areSideButtonsVisible ? 0.0 : 10.0) + + transition.setFrame(view: self.centerButtonBackgroundView, frame: centerButtonFrame) + self.centerButtonBackgroundView.update(size: centerButtonFrame.size, cornerRadius: centerButtonFrame.height * 0.5, isDark: true, tintColor: buttonsTintColor, isInteractive: true, isVisible: component.isVisible, transition: transition) + + let centerButtonIconNode: PlayPauseIconNode + let centerIconFactor: CGFloat = 0.9 + let centerButtonIconSize = CGSize(width: centerButtonFrame.width * centerIconFactor, height: centerButtonFrame.height * centerIconFactor) + if let current = self.centerButtonIconNode, current.size == centerButtonIconSize { + centerButtonIconNode = current + } else { + centerButtonIconNode = PlayPauseIconNode(size: centerButtonIconSize) + if let current = self.centerButtonIconNode { + centerButtonIconNode.frame = current.frame + current.view.removeFromSuperview() + } + self.centerButtonIconNode = centerButtonIconNode + centerButtonIconNode.isUserInteractionEnabled = false + self.centerButtonBackgroundView.contentView.addSubview(centerButtonIconNode.view) + centerButtonIconNode.enqueueState(component.isPlaying ? .pause : .play, animated: false) + } + transition.setFrame(view: centerButtonIconNode.view, frame: centerButtonIconSize.centered(in: CGRect(origin: CGPoint(), size: centerButtonFrame.size)).offsetBy(dx: component.isPlaying ? 0.0 : 5.0, dy: 0.0)) + centerButtonIconNode.enqueueState(component.isPlaying ? .pause : .play, animated: !transition.animation.isImmediate && component.isVisible && !isVisibleChanged) + transition.setAlpha(view: centerButtonIconNode.view, alpha: component.isVisible ? 1.0 : 0.0) + transition.setBlur(layer: centerButtonIconNode.layer, radius: component.isVisible ? 0.0 : 10.0) + + return size + } + } + + public func makeView() -> View { + return View(frame: CGRect()) + } + + public func update(view: View, availableSize: CGSize, state: EmptyComponentState, environment: Environment, transition: ComponentTransition) -> CGSize { + return view.update(component: self, availableSize: availableSize, state: state, environment: environment, transition: transition) + } +} + +private enum PlayPauseIconNodeState: Equatable { + case play + case pause +} + +private final class PlayPauseIconNode: ManagedAnimationNode { + let size: CGSize + + private let duration: Double = 0.35 + private var iconState: PlayPauseIconNodeState = .pause + + override init(size: CGSize) { + self.size = size + + super.init(size: size) + + self.trackTo(item: ManagedAnimationItem(source: .local("anim_playpause"), frames: .range(startFrame: 41, endFrame: 41), duration: 0.01)) + } + + func enqueueState(_ state: PlayPauseIconNodeState, animated: Bool) { + guard self.iconState != state else { + return + } + + let previousState = self.iconState + self.iconState = state + + switch previousState { + case .pause: + switch state { + case .play: + if animated { + self.trackTo(item: ManagedAnimationItem(source: .local("anim_playpause"), frames: .range(startFrame: 41, endFrame: 83), duration: self.duration)) + } else { + self.trackTo(item: ManagedAnimationItem(source: .local("anim_playpause"), frames: .range(startFrame: 0, endFrame: 0), duration: 0.01)) + } + case .pause: + break + } + case .play: + switch state { + case .pause: + if animated { + self.trackTo(item: ManagedAnimationItem(source: .local("anim_playpause"), frames: .range(startFrame: 0, endFrame: 41), duration: self.duration)) + } else { + self.trackTo(item: ManagedAnimationItem(source: .local("anim_playpause"), frames: .range(startFrame: 41, endFrame: 41), duration: 0.01)) + } + case .play: + break + } + } + } +} + +private let circleDiameter: CGFloat = 80.0 + +private final class PlaybackIconView: HighlightTrackingButton { + let backgroundIconView: UIImageView + let text = ComponentView() + + let isForward: Bool + + var isPressing = false { + didSet { + if self.isPressing != oldValue && !self.isPressing { + self.highligthedChanged(false) + } + } + } + + init(isForward: Bool) { + self.isForward = isForward + + self.backgroundIconView = UIImageView(image: UIImage(bundleImageName: isForward ? "Media Gallery/ForwardButton" : "Media Gallery/BackwardButton")) + + super.init(frame: CGRect()) + + self.addSubview(self.backgroundIconView) + + self.highligthedChanged = { [weak self] highlighted in + guard let self else { + return + } + if highlighted { + let transition: ContainedViewLayoutTransition = .animated(duration: 0.18, curve: .linear) + let angle = CGFloat.pi / 4.0 + 0.226 + transition.updateTransformRotation(view: self.backgroundIconView, angle: self.isForward ? angle : -angle) + } else if !self.isPressing { + let transition: ContainedViewLayoutTransition = .animated(duration: 0.2, curve: .linear) + transition.updateTransformRotation(view: self.backgroundIconView, angle: 0.0) + } + } + } + + required public init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func update(size: CGSize) { + if let image = self.backgroundIconView.image { + let factor: CGFloat = 1.4 + self.backgroundIconView.frame = CGSize(width: floor(image.size.width * factor), height: floor(image.size.height * factor)).centered(in: CGRect(origin: CGPoint(), size: size)) + } + + let textSize = self.text.update( + transition: .immediate, + component: AnyComponent(MultilineTextComponent( + text: .plain(NSAttributedString(string: "15", font: Font.with(size: 16.0, design: .round, weight: .semibold, traits: []), textColor: .white)) + )), + environment: {}, + containerSize: size + ) + if let textView = self.text.view { + if textView.superview == nil { + self.addSubview(textView) + } + textView.frame = CGRect(origin: CGPoint(x: floorToScreenPixels((size.width - textSize.width) / 2.0), y: floorToScreenPixels((size.height - textSize.height) / 2.0) + UIScreenPixel), size: textSize) + } + } +} diff --git a/submodules/TelegramUI/Sources/AccountContext.swift b/submodules/TelegramUI/Sources/AccountContext.swift index eca7ccd5..0ee70082 100644 --- a/submodules/TelegramUI/Sources/AccountContext.swift +++ b/submodules/TelegramUI/Sources/AccountContext.swift @@ -1,3 +1,6 @@ +import SGStrings +import SGSimpleSettings + import Foundation import SwiftSignalKit import UIKit @@ -156,6 +159,8 @@ public final class AccountContextImpl: AccountContext { return self._countriesConfiguration.get() } + public var watchManager: WatchManager? + private var storedPassword: (String, CFAbsoluteTime, SwiftSignalKit.Timer)? private var limitsConfigurationDisposable: Disposable? private var contentSettingsDisposable: Disposable? @@ -830,6 +835,8 @@ public final class AccountContextImpl: AccountContext { } public func requestCall(peerId: PeerId, isVideo: Bool, completion: @escaping () -> Void) { + // MARK: Swiftgram + let makeCall = { guard let callResult = self.sharedContext.callManager?.requestCall(context: self, peerId: peerId, isVideo: isVideo, endCurrentIfAny: false) else { return } @@ -897,6 +904,19 @@ public final class AccountContextImpl: AccountContext { } else { completion() } + // MARK: Swiftgram + } + if SGSimpleSettings.shared.confirmCalls { + let presentationData = self.sharedContext.currentPresentationData.with { $0 } + self.sharedContext.mainWindow?.present(textAlertController(context: self, title: nil, text: isVideo ? i18n("CallConfirmation.Video.Title", presentationData.strings.baseLanguageCode) : i18n("CallConfirmation.Audio.Title", presentationData.strings.baseLanguageCode), actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Common_No, action: {}), TextAlertAction(type: .destructiveAction, title: presentationData.strings.Common_Yes, action: { [weak self] in + guard let _ = self else { + return + } + makeCall() + })]), on: .root) + } else { + makeCall() + } } } diff --git a/submodules/TelegramUI/Sources/AppDelegate.swift b/submodules/TelegramUI/Sources/AppDelegate.swift index 99b50385..c9c62a90 100644 --- a/submodules/TelegramUI/Sources/AppDelegate.swift +++ b/submodules/TelegramUI/Sources/AppDelegate.swift @@ -1,5 +1,20 @@ +// MARK: Swiftgram +import StoreKit +import SGIAP +import SGAPI +import SGDeviceToken +import SGAPIToken + +import SGActionRequestHandlerSanitizer +import SGGHSettings +import SGAPIWebSettings +import SGLogging +import SGStrings +import SGSimpleSettings +import SGStatus +import SGSwiftSignalKit import UIKit -@preconcurrency import SwiftSignalKit +import SwiftSignalKit import Display import TelegramCore import UserNotifications @@ -19,6 +34,7 @@ import OverlayStatusController import UndoUI import LegacyUI import PassportUI +import WatchBridge import SettingsUI import AppBundle import UrlHandling @@ -41,8 +57,10 @@ import MediaEditor import TelegramUIDeclareEncodables import ContextMenuScreen import MetalEngine -import RecaptchaEnterpriseSDK +import RecaptchaEnterprise import NavigationBarImpl +import ContextUI +import ContextControllerImpl #if canImport(AppCenter) import AppCenter @@ -150,6 +168,22 @@ private func legacyDocumentsPath() -> String { return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/legacy" } +private func getContextForUserId(context: AccountContext, userId: Int64) -> Signal { + return context.sharedContext.activeAccountContexts + |> take(1) + |> mapToSignal { primary, accounts, _ -> Signal in + if let primary, primary.account.peerId.id._internalGetInt64Value() == userId { + return .single(primary) + } + if let match = accounts.first(where: { account in + account.1.account.peerId.id._internalGetInt64Value() == userId + })?.1 { + return .single(match) + } + return .complete() + } +} + protocol SupportedStartCallIntent { @available(iOS 10.0, *) var contacts: [INPerson]? { get } @@ -228,6 +262,7 @@ private func extractAccountManagerState(records: AccountRecordsView(false) private let sharedContextPromise = Promise() + private let watchCommunicationManagerPromise = Promise() private var accountManager: AccountManager? private var accountManagerState: AccountManagerState? @@ -589,6 +624,12 @@ private func extractAccountManagerState(records: AccountRecordsView mapToSignal { context -> Signal in + if let context = context, let watchManager = context.context.watchManager { + let accountId = context.context.account.id + let runningTasks: Signal = .single(nil) + |> then(watchManager.runningTasks) + return runningTasks + |> distinctUntilChanged + |> map { value -> AccountRecordId? in + if let value = value, value.running { + return accountId + } else { + return nil + } + } + |> distinctUntilChanged + } else { + return .single(nil) + } + } let wakeupManager = SharedWakeupManager(beginBackgroundTask: { name, expiration in let id = application.beginBackgroundTask(withName: name, expirationHandler: expiration) Logger.shared.log("App \(self.episodeId)", "Begin background task \(name): \(id)") @@ -1064,7 +1149,7 @@ private func extractAccountManagerState(records: AccountRecordsView map { ($0.0?.account, $0.1.map { ($0.0, $0.1.account) }) }, liveLocationPolling: liveLocationPolling, watchTasks: .single(nil), inForeground: applicationBindings.applicationInForeground, hasActiveAudioSession: self.hasActiveAudioSession.get(), notificationManager: notificationManager, mediaManager: sharedContext.mediaManager, callManager: sharedContext.callManager, accountUserInterfaceInUse: { id in + }, activeAccounts: sharedContext.activeAccountContexts |> map { ($0.0?.account, $0.1.map { ($0.0, $0.1.account) }) }, liveLocationPolling: liveLocationPolling, watchTasks: watchTasks /* MARK: Swiftgram */, inForeground: applicationBindings.applicationInForeground, hasActiveAudioSession: self.hasActiveAudioSession.get(), notificationManager: notificationManager, mediaManager: sharedContext.mediaManager, callManager: sharedContext.callManager, accountUserInterfaceInUse: { id in return sharedContext.accountUserInterfaceInUse(id) }) let sharedApplicationContext = SharedApplicationContext(sharedContext: sharedContext, notificationManager: notificationManager, wakeupManager: wakeupManager) @@ -1075,13 +1160,16 @@ private func extractAccountManagerState(records: AccountRecordsView mapToSignal { sharedApplicationContext, loggingSettings -> Signal in + |> mapToSignal { value -> Signal in + let (sharedApplicationContext, loggingSettings) = value Logger.shared.logToFile = loggingSettings.logToFile Logger.shared.logToConsole = loggingSettings.logToConsole Logger.shared.redactSensitiveData = loggingSettings.redactSensitiveData return .single(sharedApplicationContext) }) + + let watchManagerArgumentsPromise = Promise() self.context.set(self.sharedContextPromise.get() |> deliverOnMainQueue @@ -1096,7 +1184,7 @@ private func extractAccountManagerState(records: AccountRecordsView mapToSignal { context -> Signal<(AccountContext, CallListSettings)?, NoError> in + |> mapToSignal { (context: AccountContext?) -> Signal<(AccountContext, CallListSettings)?, NoError> in return sharedApplicationContext.sharedContext.accountManager.transaction { transaction -> CallListSettings? in return transaction.getSharedData(ApplicationSpecificSharedDataKeys.callListSettings)?.get(CallListSettings.self) } @@ -1118,9 +1206,9 @@ private func extractAccountManagerState(records: AccountRecordsView deliverOnMainQueue - |> map { accountAndSettings -> AuthorizedApplicationContext? in + |> map { (accountAndSettings: (AccountContext, CallListSettings)?) -> AuthorizedApplicationContext? in return accountAndSettings.flatMap { context, callListSettings in - return AuthorizedApplicationContext(sharedApplicationContext: sharedApplicationContext, mainWindow: self.mainWindow, context: context as! AccountContextImpl, accountManager: sharedApplicationContext.sharedContext.accountManager, showCallsTab: callListSettings.showTab, reinitializedNotificationSettings: { + return AuthorizedApplicationContext(sharedApplicationContext: sharedApplicationContext, mainWindow: self.mainWindow, watchManagerArguments: watchManagerArgumentsPromise.get(), context: context as! AccountContextImpl, accountManager: sharedApplicationContext.sharedContext.accountManager, showContactsTab: callListSettings.showContactsTab, showCallsTab: callListSettings.showTab, reinitializedNotificationSettings: { let _ = (self.context.get() |> take(1) |> deliverOnMainQueue).start(next: { context in @@ -1197,6 +1285,8 @@ private func extractAccountManagerState(records: AccountRecordsView), NoError> = self.sharedContextPromise.get() @@ -1346,6 +1457,20 @@ private func extractAccountManagerState(records: AccountRecordsView flatMap { WatchCommunicationManagerContext(context: $0.context) }, allowBackgroundTimeExtension: { timeout in + let _ = (self.sharedContextPromise.get() + |> take(1)).start(next: { sharedContext in + sharedContext.wakeupManager.allowBackgroundTimeExtension(timeout: timeout) + }) + })) + let _ = self.watchCommunicationManagerPromise.get().start(next: { manager in + if let manager = manager { + watchManagerArgumentsPromise.set(.single(manager.arguments)) + } else { + watchManagerArgumentsPromise.set(.single(nil)) + } + }) + self.resetBadge() if #available(iOS 9.1, *) { @@ -1392,7 +1517,7 @@ private func extractAccountManagerState(records: AccountRecordsView take(1) |> deliverOnMainQueue).start(next: { sharedApplicationContext in @@ -1899,6 +2028,12 @@ private func extractAccountManagerState(records: AccountRecordsView take(1) |> deliverOnMainQueue).start(next: { activeAccounts in for (_, context, _) in activeAccounts.accounts { + // MARK: Swiftgram + if !sgTasksLaunched { + updateSGWebSettingsInteractivelly(context: context) + updateSGGHSettingsInteractivelly(context: context) + sgTasksLaunched = true + } (context.downloadedMediaStoreManager as? DownloadedMediaStoreManagerImpl)?.runTasks() } }) @@ -2414,6 +2549,7 @@ private func extractAccountManagerState(records: AccountRecordsView deliverOnMainQueue).start(next: { sharedContext, context, authContext in + let url = sgActionRequestHandlerSanitizer(url) if let authContext = authContext, let confirmationCode = parseConfirmationCodeUrl(sharedContext: sharedContext, url: url) { authContext.rootController.applyConfirmationCode(confirmationCode) } else if let context = context { @@ -3211,3 +3347,179 @@ final class UpdateSettings: Codable, Equatable { return lhs.url == rhs.url } } + +// MARK: Swiftgram +@available(iOS 13.0, *) +extension AppDelegate { + + func setupIAP() { + NotificationCenter.default.addObserver(forName: .SGIAPHelperPurchaseNotification, object: nil, queue: nil) { [weak self] notification in + SGLogger.shared.log("SGIAP", "Got SGIAPHelperPurchaseNotification") + guard let strongSelf = self else { return } + if let transactions = notification.object as? [SKPaymentTransaction] { + let _ = (strongSelf.context.get() + |> take(1) + |> deliverOnMainQueue).start(next: { [weak strongSelf] context in + guard let veryStrongSelf = strongSelf else { + SGLogger.shared.log("SGIAP", "Finishing transactions \(transactions.map({ $0.transactionIdentifier ?? "nil" }).joined(separator: ", "))") + let defaultPaymentQueue = SKPaymentQueue.default() + for transaction in transactions { + defaultPaymentQueue.finishTransaction(transaction) + } + return + } + guard let context = context else { + SGLogger.shared.log("SGIAP", "Empty app context (how?)") + + SGLogger.shared.log("SGIAP", "Finishing transactions \(transactions.map({ $0.transactionIdentifier ?? "nil" }).joined(separator: ", "))") + let defaultPaymentQueue = SKPaymentQueue.default() + for transaction in transactions { + defaultPaymentQueue.finishTransaction(transaction) + } + return + } + SGLogger.shared.log("SGIAP", "Got context for SGIAPHelperPurchaseNotification") + let _ = Task { + await veryStrongSelf.sendReceiptForVerification(primaryContext: context.context) + await veryStrongSelf.fetchSGStatus(primaryContext: context.context) + + SGLogger.shared.log("SGIAP", "Finishing transactions \(transactions.map({ $0.transactionIdentifier ?? "nil" }).joined(separator: ", "))") + let defaultPaymentQueue = SKPaymentQueue.default() + for transaction in transactions { + defaultPaymentQueue.finishTransaction(transaction) + } + } + }) + } else { + SGLogger.shared.log("SGIAP", "Wrong object in SGIAPHelperPurchaseNotification") + #if DEBUG + preconditionFailure("Wrong object in SGIAPHelperPurchaseNotification") + #endif + } + } + } + + func getPrimaryContext(anyContext context: AccountContext, fallbackToCurrent: Bool = false) async -> AccountContext { + var primaryUserId: Int64 = Int64(SGSimpleSettings.shared.primaryUserId) ?? 0 + if primaryUserId == 0 { + primaryUserId = context.account.peerId.id._internalGetInt64Value() + } + + var primaryContext = try? await getContextForUserId(context: context, userId: primaryUserId).awaitable() + if let primaryContext = primaryContext { + SGLogger.shared.log("SGIAP", "Got primary context for user id: \(primaryContext.account.peerId.id._internalGetInt64Value())") + return primaryContext + } else { + primaryContext = context + let newPrimaryUserId = context.account.peerId.id._internalGetInt64Value() + SGLogger.shared.log("SGIAP", "Primary context for user id \(primaryUserId) is nil! Falling back to current context with user id: \(newPrimaryUserId)") + return context + } + } + + func sendReceiptForVerification(primaryContext: AccountContext) async { + guard let receiptData = getPurchaceReceiptData() else { + return + } + + let encodedReceiptData = receiptData.base64EncodedData(options: []) + + var deviceToken: String? + var apiToken: String? + do { + async let deviceTokenTask = getDeviceToken().awaitable() + async let apiTokenTask = getSGApiToken(context: primaryContext).awaitable() + + (deviceToken, apiToken) = try await (deviceTokenTask, apiTokenTask) + } catch { + SGLogger.shared.log("SGIAP", "Error getting device token or API token: \(error)") + return + } + + if let deviceToken, let apiToken { + do { + let _ = try await postSGReceipt(token: apiToken, + deviceToken: deviceToken, + encodedReceiptData: encodedReceiptData).awaitable() + } catch let error as SignalCompleted { + let _ = error + } catch { + SGLogger.shared.log("SGIAP", "Error: \(error)") + } + } + } + + func fetchSGStatus(primaryContext: AccountContext) async { + // TODO(swiftgram): Stuck on getting shouldKeepConnection + // Perhaps, we can drop on some timeout? +// let currentShouldKeepConnection = await (primaryContext.account.network.shouldKeepConnection.get() |> take(1) |> deliverOnMainQueue).awaitable() + guard !primaryContext.account.testingEnvironment else { + return + } + let currentShouldKeepConnection = false + let userId = primaryContext.account.peerId.id._internalGetInt64Value() +// SGLogger.shared.log("SGIAP", "User id \(userId) currently keeps connection: \(currentShouldKeepConnection)") + if !currentShouldKeepConnection { + SGLogger.shared.log("SGIAP", "Asking user id \(userId) to keep connection: true") + primaryContext.account.network.shouldKeepConnection.set(.single(true)) + } + // MARK: Swiftgram + let sgIqtpQueryString = makeIqtpQuery("s") + // + let iqtpResponse = try? await sgIqtpQuery(engine: primaryContext.engine, query: sgIqtpQueryString).awaitable() + guard let iqtpResponse = iqtpResponse else { + SGLogger.shared.log("SGIAP", "IQTP response is nil!") +// if !currentShouldKeepConnection { +// SGLogger.shared.log("SGIAP", "Setting user id \(userId) keep connection back to false") +// primaryContext.account.network.shouldKeepConnection.set(.single(false)) +// } + DispatchQueue.main.async { + NotificationCenter.default.post(name: .SGIAPHelperValidationErrorNotification, object: nil, userInfo: ["error": "PayWall.ValidationError.TryAgain"]) + } + return + } + SGLogger.shared.log("SGIAP", "Got IQTP response: \(iqtpResponse)") + let _ = try? await updateSGStatusInteractively(accountManager: primaryContext.sharedContext.accountManager, { value in + var value = value + + let newStatus: Int64 + if let status = Int64(iqtpResponse.value) { + newStatus = status + } else { + SGLogger.shared.log("SGIAP", "Can't parse IQTP response into status!") + newStatus = value.status // unparseable + } + + let userId = primaryContext.account.peerId.id._internalGetInt64Value() + if value.status != newStatus { + SGLogger.shared.log("SGIAP", "Updating \(userId) status \(value.status) -> \(newStatus)") + if newStatus > 1 { + let stringUserId = String(userId) + if SGSimpleSettings.shared.primaryUserId != stringUserId { + SGLogger.shared.log("SGIAP", "Setting new primary user id: \(userId)") + SGSimpleSettings.shared.primaryUserId = stringUserId + } + } else { + SGLogger.shared.log("SGIAP", "Status expired") + DispatchQueue.main.async { + NotificationCenter.default.post(name: .SGIAPHelperValidationErrorNotification, object: nil, userInfo: ["error": "PayWall.ValidationError.Expired"]) + } + } + value.status = newStatus + } else { + SGLogger.shared.log("SGIAP", "Status \(value.status) for \(userId) hasn't changed") + if newStatus < 2 { + DispatchQueue.main.async { + NotificationCenter.default.post(name: .SGIAPHelperValidationErrorNotification, object: nil, userInfo: ["error": "PayWall.ValidationError.TryAgain"]) + } + } + } + return value + }).awaitable() + +// if !currentShouldKeepConnection { +// SGLogger.shared.log("SGIAP", "Setting user id \(userId) keep connection back to false") +// primaryContext.account.network.shouldKeepConnection.set(.single(false)) +// } + } +} diff --git a/submodules/TelegramUI/Sources/ApplicationContext.swift b/submodules/TelegramUI/Sources/ApplicationContext.swift index e57aa4b1..1b1f6de5 100644 --- a/submodules/TelegramUI/Sources/ApplicationContext.swift +++ b/submodules/TelegramUI/Sources/ApplicationContext.swift @@ -1,3 +1,5 @@ +// MARK: Swiftgram +import SGSimpleSettings import Foundation import UIKit import Intents @@ -20,6 +22,7 @@ import TelegramPermissionsUI import PasscodeUI import ImageBlur import FastBlur +import WatchBridge import SettingsUI import AppLock import AccountUtils @@ -151,11 +154,12 @@ final class AuthorizedApplicationContext { private var applicationInForegroundDisposable: Disposable? + private var showContactsTab: Bool private var showCallsTab: Bool private var showCallsTabDisposable: Disposable? private var enablePostboxTransactionsDiposable: Disposable? - init(sharedApplicationContext: SharedApplicationContext, mainWindow: Window1, context: AccountContextImpl, accountManager: AccountManager, showCallsTab: Bool, reinitializedNotificationSettings: @escaping () -> Void) { + init(sharedApplicationContext: SharedApplicationContext, mainWindow: Window1, watchManagerArguments: Signal, context: AccountContextImpl, accountManager: AccountManager, showContactsTab: Bool, showCallsTab: Bool, reinitializedNotificationSettings: @escaping () -> Void) { self.sharedApplicationContext = sharedApplicationContext setupLegacyComponents(context: context) @@ -166,6 +170,8 @@ final class AuthorizedApplicationContext { self.context = context + self.showContactsTab = showContactsTab + self.showCallsTab = showCallsTab self.notificationController = NotificationContainerController(context: context) @@ -249,7 +255,7 @@ final class AuthorizedApplicationContext { } if self.rootController.rootTabController == nil { - self.rootController.addRootControllers(showCallsTab: self.showCallsTab) + self.rootController.addRootControllers(hidePhoneInSettings: SGSimpleSettings.shared.hidePhoneInSettings, showContactsTab: self.showContactsTab, showCallsTab: self.showCallsTab) } if let tabsController = self.rootController.viewControllers.first as? TabBarController, !tabsController.controllers.isEmpty, tabsController.selectedIndex >= 0 { let controller = tabsController.controllers[tabsController.selectedIndex] @@ -782,22 +788,81 @@ final class AuthorizedApplicationContext { }) let showCallsTabSignal = context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.callListSettings]) - |> map { sharedData -> Bool in - var value = CallListSettings.defaultSettings.showTab + |> map { sharedData -> (Bool, Bool) in + var showCallsTabValue = CallListSettings.defaultSettings.showTab + var showContactsTabValue = CallListSettings.defaultSettings.showContactsTab if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.callListSettings]?.get(CallListSettings.self) { - value = settings.showTab + showCallsTabValue = settings.showTab + showContactsTabValue = settings.showContactsTab } - return value + return (showContactsTabValue, showCallsTabValue) } - self.showCallsTabDisposable = (showCallsTabSignal |> deliverOnMainQueue).start(next: { [weak self] value in + self.showCallsTabDisposable = (showCallsTabSignal |> deliverOnMainQueue).start(next: { [weak self] values in if let strongSelf = self { - if strongSelf.showCallsTab != value { - strongSelf.showCallsTab = value - strongSelf.rootController.updateRootControllers(showCallsTab: value) + let (showContactsTabValue, showCallsTabValue) = values + var needControllersUpdate = false + if strongSelf.showCallsTab != showCallsTabValue { + needControllersUpdate = true + strongSelf.showCallsTab = showCallsTabValue + } + if strongSelf.showContactsTab != showContactsTabValue { + needControllersUpdate = true + strongSelf.showContactsTab = showContactsTabValue + } + if needControllersUpdate { + strongSelf.rootController.updateRootControllers(showContactsTab: showContactsTabValue, showCallsTab: showCallsTabValue) } } }) + let _ = (watchManagerArguments + |> deliverOnMainQueue).start(next: { [weak self] arguments in + guard let strongSelf = self else { + return + } + + let watchManager = WatchManagerImpl(arguments: arguments) + strongSelf.context.watchManager = watchManager + + strongSelf.watchNavigateToMessageDisposable.set((strongSelf.context.sharedContext.applicationBindings.applicationInForeground |> mapToSignal({ applicationInForeground -> Signal<(Bool, MessageId), NoError> in + return watchManager.navigateToMessageRequested + |> map { messageId in + return (applicationInForeground, messageId) + } + |> deliverOnMainQueue + })).start(next: { [weak self] applicationInForeground, messageId in + if let strongSelf = self { + if applicationInForeground { + var chatIsVisible = false + if let controller = strongSelf.rootController.viewControllers.last as? ChatControllerImpl, case .peer(messageId.peerId) = controller.chatLocation { + chatIsVisible = true + } + + let navigateToMessage = { + let _ = (strongSelf.context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: messageId.peerId)) + |> deliverOnMainQueue).start(next: { peer in + guard let peer = peer else { + return + } + + strongSelf.context.sharedContext.navigateToChatController(NavigateToChatControllerParams(navigationController: strongSelf.rootController, context: strongSelf.context, chatLocation: .peer(peer), subject: .message(id: .id(messageId), highlight: ChatControllerSubject.MessageHighlight(quote: nil), timecode: nil, setupReply: false))) + }) + } + + if chatIsVisible { + navigateToMessage() + } else { + let presentationData = strongSelf.context.sharedContext.currentPresentationData.with { $0 } + let controller = textAlertController(context: strongSelf.context, title: presentationData.strings.WatchRemote_AlertTitle, text: presentationData.strings.WatchRemote_AlertText, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_Cancel, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.WatchRemote_AlertOpen, action:navigateToMessage)]) + (strongSelf.rootController.viewControllers.last as? ViewController)?.present(controller, in: .window(.root)) + } + } else { + //strongSelf.notificationManager.presentWatchContinuityNotification(context: strongSelf.context, messageId: messageId) + } + } + })) + }) + self.rootController.setForceInCallStatusBar((self.context.sharedContext as! SharedAccountContextImpl).currentCallStatusBarNode) if let groupCallController = self.context.sharedContext.currentGroupCallController as? VoiceChatController { if let overlayController = groupCallController.currentOverlayController { diff --git a/submodules/TelegramUI/Sources/Chat/ChatControllerLoadDisplayNode.swift b/submodules/TelegramUI/Sources/Chat/ChatControllerLoadDisplayNode.swift index 042a3c4f..635fe1e8 100644 --- a/submodules/TelegramUI/Sources/Chat/ChatControllerLoadDisplayNode.swift +++ b/submodules/TelegramUI/Sources/Chat/ChatControllerLoadDisplayNode.swift @@ -2008,7 +2008,7 @@ extension ChatControllerImpl { } } })) - }, forwardSelectedMessages: { [weak self] in + }, forwardSelectedMessages: { [weak self] _ in if let strongSelf = self { strongSelf.commitPurposefulAction() if let forwardMessageIdsSet = strongSelf.presentationInterfaceState.interfaceState.selectionState?.selectedIds { @@ -2023,7 +2023,7 @@ extension ChatControllerImpl { strongSelf.forwardMessages(messageIds: forwardMessageIds, options: strongSelf.presentationInterfaceState.interfaceState.forwardOptionsState, resetCurrent: true) } } - }, forwardMessages: { [weak self] messages in + }, forwardMessages: { [weak self] messages, action in if let strongSelf = self, !messages.isEmpty { guard !strongSelf.presentAccountFrozenInfoIfNeeded(delay: true) else { return @@ -2031,7 +2031,16 @@ extension ChatControllerImpl { strongSelf.commitPurposefulAction() let forwardMessageIds = messages.map { $0.id }.sorted() - strongSelf.forwardMessages(messageIds: forwardMessageIds) + switch action { + case "forwardMessagesToCloud": + strongSelf.forwardMessagesToCloud(messageIds: forwardMessageIds, removeNames: false, openCloud: false) + case "forwardMessagesWithNoNames": + strongSelf.forwardMessages(messageIds: forwardMessageIds, options: ChatInterfaceForwardOptionsState(hideNames: true, hideCaptions: false, unhideNamesOnCaptionChange: false)) + case "forwardMessagesToCloudWithNoNamesAndOpen": + strongSelf.forwardMessagesToCloud(messageIds: forwardMessageIds, removeNames: true, openCloud: true) + default: + strongSelf.forwardMessages(messageIds: forwardMessageIds) + } } }, updateForwardOptionsState: { [weak self] f in if let strongSelf = self { diff --git a/submodules/TelegramUI/Sources/Chat/ChatMessageDisplaySendMessageOptions.swift b/submodules/TelegramUI/Sources/Chat/ChatMessageDisplaySendMessageOptions.swift index 996bfe69..f7e343d0 100644 --- a/submodules/TelegramUI/Sources/Chat/ChatMessageDisplaySendMessageOptions.swift +++ b/submodules/TelegramUI/Sources/Chat/ChatMessageDisplaySendMessageOptions.swift @@ -1,3 +1,7 @@ +// MARK: Swiftgram +import SGSimpleSettings +import TextFormat +import TranslateUI import Foundation import UIKit import AsyncDisplayKit @@ -84,6 +88,47 @@ func chatMessageDisplaySendMessageOptions(selfController: ChatControllerImpl, no return } + // MARK: Swiftgram + let outgoingMessageTranslateToLang = SGSimpleSettings.shared.outgoingLanguageTranslation[SGSimpleSettings.makeOutgoingLanguageTranslationKey(accountId: selfController.context.account.peerId.id._internalGetInt64Value(), peerId: peer.id.id._internalGetInt64Value())] ?? selfController.contentData?.state.predictedChatLanguage + + let sgTranslationContext: (outgoingMessageTranslateToLang: String?, translate: (() -> Void)?, changeTranslationLanguage: (() -> ())?) = (outgoingMessageTranslateToLang: outgoingMessageTranslateToLang, translate: { [weak selfController] in + guard let selfController else { return } + let textToTranslate = selfController.presentationInterfaceState.interfaceState.effectiveInputState.inputText.string + let textEntities = selfController.presentationInterfaceState.interfaceState.synchronizeableInputState?.entities ?? [] + if let outgoingMessageTranslateToLang = outgoingMessageTranslateToLang { + let _ = (selfController.context.engine.messages.translate(text: textToTranslate, toLang: outgoingMessageTranslateToLang, entities: textEntities) |> deliverOnMainQueue).start(next: { [weak selfController] translatedTextAndEntities in + guard let selfController, let translatedTextAndEntities else { return } + let newInputText = chatInputStateStringWithAppliedEntities(translatedTextAndEntities.0, entities: translatedTextAndEntities.1) + let newTextInputState = ChatTextInputState(inputText: newInputText, selectionRange: 0 ..< newInputText.length) + selfController.updateChatPresentationInterfaceState(interactive: true, { state in + return state.updatedInterfaceState { interfaceState in + return interfaceState.withUpdatedEffectiveInputState(newTextInputState) + } + }) + }) + } + }, changeTranslationLanguage: { [weak selfController] in + guard let selfController else { return } + let controller = languageSelectionController(context: selfController.context, forceTheme: selfController.presentationData.theme, fromLanguage: "", toLanguage: selfController.presentationInterfaceState.translationState?.fromLang ?? "", completion: { _, toLang in + guard let peerId = selfController.chatLocation.peerId else { + return + } + var langCode = toLang + if langCode == "nb" { + langCode = "no" + } else if langCode == "pt-br" { + langCode = "pt" + } + + if !toLang.isEmpty { + SGSimpleSettings.shared.outgoingLanguageTranslation[SGSimpleSettings.makeOutgoingLanguageTranslationKey(accountId: selfController.context.account.peerId.id._internalGetInt64Value(), peerId: peerId.id._internalGetInt64Value())] = langCode + } + chatMessageDisplaySendMessageOptions(selfController: selfController, node: node, gesture: gesture) + }) + controller.navigationPresentation = .modal + selfController.push(controller) + }) + if let editMessage = selfController.presentationInterfaceState.interfaceState.editMessage { if editMessages.isEmpty { return @@ -122,6 +167,7 @@ func chatMessageDisplaySendMessageOptions(selfController: ChatControllerImpl, no } let controller = makeChatSendMessageActionSheetController( + sgTranslationContext: sgTranslationContext, initialData: initialData, context: selfController.context, updatedPresentationData: selfController.updatedPresentationData, @@ -213,6 +259,7 @@ func chatMessageDisplaySendMessageOptions(selfController: ChatControllerImpl, no } let controller = makeChatSendMessageActionSheetController( + sgTranslationContext: sgTranslationContext, initialData: initialData, context: selfController.context, updatedPresentationData: selfController.updatedPresentationData, diff --git a/submodules/TelegramUI/Sources/ChatController.swift b/submodules/TelegramUI/Sources/ChatController.swift index 02d4268a..ffcaf143 100644 --- a/submodules/TelegramUI/Sources/ChatController.swift +++ b/submodules/TelegramUI/Sources/ChatController.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import Postbox @@ -146,6 +147,35 @@ import ChatTextInputPanelNode import ChatInputAccessoryPanel import GlobalControlPanelsContext import ChatSearchNavigationContentNode +import ChatAgeRestrictionAlertController + +private func chatNavigationBarTheme(presentationTheme: PresentationTheme, hideBadge: Bool) -> NavigationBarTheme { + let baseTheme = NavigationBarTheme(rootControllerTheme: presentationTheme, hideBackground: false, hideBadge: hideBadge, edgeEffectColor: .clear, style: .glass) + let backgroundColor: UIColor + let opaqueBackgroundColor: UIColor + if presentationTheme.overallDarkAppearance { + backgroundColor = UIColor(white: 0.0, alpha: 0.38) + opaqueBackgroundColor = UIColor(white: 0.0, alpha: 0.78) + } else { + backgroundColor = UIColor(white: 1.0, alpha: 0.68) + opaqueBackgroundColor = UIColor(white: 1.0, alpha: 0.92) + } + return NavigationBarTheme( + overallDarkAppearance: baseTheme.overallDarkAppearance, + buttonColor: baseTheme.buttonColor, + disabledButtonColor: baseTheme.disabledButtonColor, + primaryTextColor: baseTheme.primaryTextColor, + backgroundColor: backgroundColor, + opaqueBackgroundColor: opaqueBackgroundColor, + enableBackgroundBlur: baseTheme.enableBackgroundBlur, + separatorColor: baseTheme.separatorColor, + badgeBackgroundColor: baseTheme.badgeBackgroundColor, + badgeStrokeColor: baseTheme.badgeStrokeColor, + badgeTextColor: baseTheme.badgeTextColor, + edgeEffectColor: baseTheme.edgeEffectColor, + style: baseTheme.style + ) +} public final class ChatControllerOverlayPresentationData { public let expandData: (ASDisplayNode?, () -> Void) @@ -570,6 +600,20 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G var translationStateDisposable: Disposable? var premiumGiftSuggestionDisposable: Disposable? + // MARK: Swiftgram + private var sgShowHiddenPinnedMessagesObserver: NSObjectProtocol? + public var overlayTitle: String? { + var title: String? + if let threadInfo = self.contentData?.state.threadInfo { + title = threadInfo.title + } else if let peerView = self.contentData?.state.peerView { + if let peer = peerViewMainPeer(peerView) { + title = EnginePeer(peer).displayTitle(strings: self.presentationData.strings, displayOrder: self.presentationData.nameDisplayOrder) + } + } + return title + } + var currentSpeechHolder: SpeechSynthesizerHolder? var powerSavingMonitoringDisposable: Disposable? @@ -690,7 +734,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G self.stickerSettings = ChatInterfaceStickerSettings() - self.presentationInterfaceState = ChatPresentationInterfaceState(chatWallpaper: self.presentationData.chatWallpaper, theme: self.presentationData.theme, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, limitsConfiguration: context.currentLimitsConfiguration.with { $0 }, fontSize: self.presentationData.chatFontSize, bubbleCorners: self.presentationData.chatBubbleCorners, accountPeerId: context.account.peerId, mode: mode, chatLocation: chatLocation, subject: subject, peerNearbyData: peerNearbyData, greetingData: context.prefetchManager?.preloadedGreetingSticker, pendingUnpinnedAllMessages: false, activeGroupCallInfo: nil, hasActiveGroupCall: false, threadData: nil, isGeneralThreadClosed: nil, replyMessage: nil, accountPeerColor: nil, businessIntro: nil) + self.presentationInterfaceState = ChatPresentationInterfaceState(chatWallpaper: self.presentationData.chatWallpaper, theme: self.presentationData.theme, preferredGlassType: .default, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, limitsConfiguration: context.currentLimitsConfiguration.with { $0 }, fontSize: self.presentationData.chatFontSize, bubbleCorners: self.presentationData.chatBubbleCorners, accountPeerId: context.account.peerId, mode: mode, chatLocation: chatLocation, subject: subject, peerNearbyData: peerNearbyData, greetingData: context.prefetchManager?.preloadedGreetingSticker, pendingUnpinnedAllMessages: false, activeGroupCallInfo: nil, hasActiveGroupCall: false, threadData: nil, isGeneralThreadClosed: nil, replyMessage: nil, accountPeerColor: nil, businessIntro: nil) if case let .customChatContents(customChatContents) = subject { switch customChatContents.kind { @@ -714,7 +758,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G case .inline, .standard(.embedded): navigationBarPresentationData = nil default: - navigationBarPresentationData = NavigationBarPresentationData(presentationData: self.presentationData, hideBackground: false, hideBadge: false, style: .glass) + navigationBarPresentationData = NavigationBarPresentationData(theme: chatNavigationBarTheme(presentationTheme: self.presentationData.theme, hideBadge: false), strings: NavigationBarStrings(presentationStrings: self.presentationData.strings)) } self.moreBarButton = MoreHeaderButton(color: self.presentationData.theme.chat.inputPanel.panelControlColor) @@ -732,11 +776,22 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G self.ready.set(.never()) - self.chatBackgroundNode.isDarkUpdated = { [weak self] in + self.chatBackgroundNode.contentStatsUpdated = { [weak self] in guard let self else { return } self.updateStatusBarPresentation(animated: false) + + var preferredGlassType: ChatPresentationInterfaceState.GlassType = self.chatBackgroundNode.contentStats?.isSaturated == true ? .clear : .default + if !self.presentationData.theme.overallDarkAppearance { + preferredGlassType = .default + } + if self.presentationInterfaceState.preferredGlassType != preferredGlassType { + self.updateChatPresentationInterfaceState(transition: .immediate, interactive: false, { state in + return state.updatedPreferredGlassType(preferredGlassType) + }) + self.updateNavigationBarPresentation() + } } self.scrollToTop = { [weak self] in @@ -829,745 +884,29 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G return true } - let openMessage: (Message, OpenMessageParams) -> Bool = { [weak self] message, params in - guard let self, self.isNodeLoaded, let message = self.chatDisplayNode.historyNode.messageInCurrentHistoryView(message.id) else { + let openMessageImpl = { [weak self] (message: Message, params: OpenMessageParams) -> Bool in + guard let self else { return false } - - if let contextController = self.currentContextController { - self.present(contextController, in: .window(.root)) - Queue.mainQueue().after(0.15) { - contextController.dismiss(result: .dismissWithoutContent, completion: nil) - } - } - - let mode = params.mode - - let displayVoiceMessageDiscardAlert: () -> Bool = { [weak self] in - guard let self else { - return true - } - if self.presentVoiceMessageDiscardAlert(action: { [weak self] in - Queue.mainQueue().after(0.1, { - guard let self else { - return - } - let _ = self.controllerInteraction?.openMessage(message, params) - }) - }, performAction: false) { - return false - } - return true - } - - self.commitPurposefulAction() - self.dismissAllTooltips() - - self.chatDisplayNode.messageTransitionNode.dismissMessageReactionContexts() - - var openMessageByAction = false - var isLocation = false - - for media in message.media { - if media is TelegramMediaMap { - if !displayVoiceMessageDiscardAlert() { - return false - } - isLocation = true - } - if let file = media as? TelegramMediaFile { - if file.isInstantVideo { - if self.chatDisplayNode.isInputViewFocused { - self.returnInputViewFocus = true - self.chatDisplayNode.dismissInput() - } - } - if file.isMusic || file.isVoice || file.isInstantVideo { - if !displayVoiceMessageDiscardAlert() { - return false - } - - if (file.isVoice || file.isInstantVideo) && message.minAutoremoveOrClearTimeout == viewOnceTimeout { - self.openViewOnceMediaMessage(message) - return false - } - } else if file.isVideo { - if !displayVoiceMessageDiscardAlert() { - return false - } - } - } - if let paidContent = media as? TelegramMediaPaidContent, let extendedMedia = paidContent.extendedMedia.first { - switch extendedMedia { - case .preview: - if displayVoiceMessageDiscardAlert() { - self.controllerInteraction?.openCheckoutOrReceipt(message.id, params) - return true - } else { - return false - } - case .full: - break - } - } else if let invoice = media as? TelegramMediaInvoice, let extendedMedia = invoice.extendedMedia { - switch extendedMedia { - case .preview: - if displayVoiceMessageDiscardAlert() { - self.controllerInteraction?.openCheckoutOrReceipt(message.id, nil) - return true - } else { - return false - } - case .full: - break - } - } else if media is TelegramMediaGiveaway || media is TelegramMediaGiveawayResults { - let progress = params.progress - let presentationData = self.presentationData - - var signal = self.context.engine.payments.premiumGiveawayInfo(peerId: message.id.peerId, messageId: message.id) - let disposable: MetaDisposable - if let current = self.giveawayStatusDisposable { - disposable = current - } else { - disposable = MetaDisposable() - self.giveawayStatusDisposable = disposable - } - - let progressSignal = Signal { [weak self] subscriber in - if let progress { - progress.set(.single(true)) - return ActionDisposable { - Queue.mainQueue().async() { - progress.set(.single(false)) - } - } - } else { - let controller = OverlayStatusController(theme: presentationData.theme, type: .loading(cancelled: nil)) - self?.present(controller, in: .window(.root)) - return ActionDisposable { [weak controller] in - Queue.mainQueue().async() { - controller?.dismiss() - } - } - } - } - |> runOn(Queue.mainQueue()) - |> delay(0.25, queue: Queue.mainQueue()) - let progressDisposable = progressSignal.startStrict() - - signal = signal - |> afterDisposed { - Queue.mainQueue().async { - progressDisposable.dispose() - } - } - disposable.set((signal - |> deliverOnMainQueue).startStrict(next: { [weak self] info in - if let self, let info { - self.displayGiveawayStatusInfo(messageId: message.id, giveawayInfo: info) - } - })) - - return true - } else if let action = media as? TelegramMediaAction { - if !displayVoiceMessageDiscardAlert() { - return false - } - switch action.action { - case .pinnedMessageUpdated, .gameScore, .setSameChatWallpaper, .giveawayResults, .customText, .todoCompletions, .todoAppendTasks, .suggestedPostRefund, .suggestedPostSuccess, .suggestedPostApprovalStatus: - for attribute in message.attributes { - if let attribute = attribute as? ReplyMessageAttribute { - var todoTaskId: Int32? - if case let .todoCompletions(completed, incompleted) = action.action { - if let completedTaskId = completed.first { - todoTaskId = completedTaskId - } else if let incompletedTaskId = incompleted.first { - todoTaskId = incompletedTaskId - } - } else if case let .todoAppendTasks(tasks) = action.action { - if let task = tasks.first { - todoTaskId = task.id - } - } - self.navigateToMessage(from: message.id, to: .id(attribute.messageId, NavigateToMessageParams(timestamp: nil, quote: attribute.isQuote ? attribute.quote.flatMap { quote in NavigateToMessageParams.Quote(string: quote.text, offset: quote.offset) } : nil, todoTaskId: todoTaskId))) - break - } - } - case let .photoUpdated(image): - openMessageByAction = image != nil - case .groupPhoneCall, .inviteToGroupPhoneCall: - if let activeCall = self.presentationInterfaceState.activeGroupCallInfo?.activeCall { - self.joinGroupCall(peerId: message.id.peerId, invite: nil, activeCall: EngineGroupCallDescription(id: activeCall.id, accessHash: activeCall.accessHash, title: activeCall.title, scheduleTimestamp: activeCall.scheduleTimestamp, subscribedToScheduled: activeCall.subscribedToScheduled, isStream: activeCall.isStream)) - } else { - var canManageGroupCalls = false - if let channel = self.presentationInterfaceState.renderedPeer?.chatMainPeer as? TelegramChannel { - if channel.flags.contains(.isCreator) || channel.hasPermission(.manageCalls) { - canManageGroupCalls = true - } - } else if let group = self.presentationInterfaceState.renderedPeer?.chatMainPeer as? TelegramGroup { - if case .creator = group.role { - canManageGroupCalls = true - } else if case let .admin(rights, _) = group.role { - if rights.rights.contains(.canManageCalls) { - canManageGroupCalls = true - } - } - } - - if canManageGroupCalls { - let text: String - if let channel = self.presentationInterfaceState.renderedPeer?.chatMainPeer as? TelegramChannel, case .broadcast = channel.info { - text = self.presentationData.strings.LiveStream_CreateNewVoiceChatText - } else { - text = self.presentationData.strings.VoiceChat_CreateNewVoiceChatText - } - self.present(textAlertController(context: self.context, updatedPresentationData: self.updatedPresentationData, title: nil, text: text, actions: [TextAlertAction(type: .defaultAction, title: self.presentationData.strings.VoiceChat_CreateNewVoiceChatStartNow, action: { [weak self] in - if let self { - var dismissStatus: (() -> Void)? - let statusController = OverlayStatusController(theme: self.presentationData.theme, type: .loading(cancelled: { - dismissStatus?() - })) - dismissStatus = { [weak self, weak statusController] in - self?.createVoiceChatDisposable.set(nil) - statusController?.dismiss() - } - self.present(statusController, in: .window(.root)) - self.createVoiceChatDisposable.set((self.context.engine.calls.createGroupCall(peerId: message.id.peerId, title: nil, scheduleDate: nil, isExternalStream: false) - |> deliverOnMainQueue).startStrict(next: { [weak self] info in - guard let self else { - return - } - self.joinGroupCall(peerId: message.id.peerId, invite: nil, activeCall: EngineGroupCallDescription(id: info.id, accessHash: info.accessHash, title: info.title, scheduleTimestamp: info.scheduleTimestamp, subscribedToScheduled: info.subscribedToScheduled, isStream: info.isStream)) - }, error: { [weak self] error in - dismissStatus?() - - guard let self else { - return - } - - let text: String - switch error { - case .generic, .scheduledTooLate: - text = self.presentationData.strings.Login_UnknownError - case .anonymousNotAllowed: - if let channel = message.peers[message.id.peerId] as? TelegramChannel, case .broadcast = channel.info { - text = self.presentationData.strings.LiveStream_AnonymousDisabledAlertText - } else { - text = self.presentationData.strings.VoiceChat_AnonymousDisabledAlertText - } - } - self.present(textAlertController(context: self.context, updatedPresentationData: self.updatedPresentationData, title: nil, text: text, actions: [TextAlertAction(type: .defaultAction, title: self.presentationData.strings.Common_OK, action: {})]), in: .window(.root)) - }, completed: { - dismissStatus?() - })) - } - }), TextAlertAction(type: .genericAction, title: self.presentationData.strings.VoiceChat_CreateNewVoiceChatSchedule, action: { [weak self] in - if let self { - self.context.scheduleGroupCall(peerId: message.id.peerId, parentController: self) - } - }), TextAlertAction(type: .genericAction, title: self.presentationData.strings.Common_Cancel, action: {})], actionLayout: .vertical), in: .window(.root)) - } - } - return true - case .messageAutoremoveTimeoutUpdated: - var canSetupAutoremoveTimeout = false - - if let _ = self.presentationInterfaceState.renderedPeer?.peer as? TelegramSecretChat { - canSetupAutoremoveTimeout = false - } else if let group = self.presentationInterfaceState.renderedPeer?.peer as? TelegramGroup { - if !group.hasBannedPermission(.banChangeInfo) { - canSetupAutoremoveTimeout = true - } - } else if let user = self.presentationInterfaceState.renderedPeer?.peer as? TelegramUser { - if user.id != self.context.account.peerId && user.botInfo == nil { - canSetupAutoremoveTimeout = true - } - } else if let channel = self.presentationInterfaceState.renderedPeer?.peer as? TelegramChannel { - if channel.hasPermission(.changeInfo) { - canSetupAutoremoveTimeout = true - } - } - - if canSetupAutoremoveTimeout { - self.presentAutoremoveSetup() - } - case let .paymentSent(currency, _, _, _, _): - if currency == "XTR" { - let _ = (context.engine.payments.requestBotPaymentReceipt(messageId: message.id) - |> deliverOnMainQueue).start(next: { [weak self] receipt in - guard let self else { - return - } - self.push(self.context.sharedContext.makeStarsReceiptScreen(context: self.context, receipt: receipt)) - }) - } else { - self.present(BotReceiptController(context: self.context, messageId: message.id), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) - } - return true - case let .setChatTheme(chatTheme): - switch chatTheme { - case .emoticon: - self.presentThemeSelection() - case let .gift(gift, _): - if case let .unique(uniqueGift) = gift { - let controller = self.context.sharedContext.makeGiftViewScreen(context: self.context, gift: uniqueGift, shareStory: { [weak self] uniqueGift in - Queue.mainQueue().after(0.15) { - if let self { - let controller = self.context.sharedContext.makeStorySharingScreen(context: self.context, subject: .gift(uniqueGift), parentController: self) - self.push(controller) - } - } - }, openChatTheme: { [weak self] in - if let self { - Queue.mainQueue().after(0.15) { - self.presentThemeSelection() - } - } - }, dismissed: nil) - self.push(controller) - } - } - return true - case let .setChatWallpaper(wallpaper, _): - guard let peer = self.presentationInterfaceState.renderedPeer?.peer else { - return true - } - if let peer = peer as? TelegramChannel { - if peer.flags.contains(.isCreator) || peer.adminRights?.rights.contains(.canChangeInfo) == true { - let _ = (context.engine.peers.getChannelBoostStatus(peerId: peer.id) - |> deliverOnMainQueue).start(next: { [weak self] boostStatus in - guard let self else { - return - } - self.push(ChannelAppearanceScreen(context: self.context, updatedPresentationData: self.updatedPresentationData, peerId: peer.id, boostStatus: boostStatus)) - }) - } - return true - } - guard message.effectivelyIncoming(self.context.account.peerId), let peer = self.presentationInterfaceState.renderedPeer?.peer else { - self.presentThemeSelection() - return true - } - self.chatDisplayNode.dismissInput() - var options = WallpaperPresentationOptions() - var intensity: Int32? - if let settings = wallpaper.settings { - if settings.blur { - options.insert(.blur) - } - if settings.motion { - options.insert(.motion) - } - if case let .file(file) = wallpaper, !file.isPattern { - intensity = settings.intensity - } - } - let wallpaperPreviewController = WallpaperGalleryController(context: self.context, source: .wallpaper(wallpaper, options, [], intensity, nil, nil), mode: .peer(EnginePeer(peer), true)) - wallpaperPreviewController.apply = { [weak wallpaperPreviewController] entry, options, _, _, brightness, forBoth in - var settings: WallpaperSettings? - if case let .wallpaper(wallpaper, _) = entry { - let baseSettings = wallpaper.settings - var intensity: Int32? = baseSettings?.intensity - if case let .file(file) = wallpaper, !file.isPattern { - if let brightness { - intensity = max(0, min(100, Int32(brightness * 100.0))) - } - } - settings = WallpaperSettings(blur: options.contains(.blur), motion: options.contains(.motion), colors: baseSettings?.colors ?? [], intensity: intensity, rotation: baseSettings?.rotation) - } - let _ = (self.context.engine.themes.setExistingChatWallpaper(messageId: message.id, settings: settings, forBoth: forBoth) - |> deliverOnMainQueue).startStandalone() - Queue.mainQueue().after(0.1) { - wallpaperPreviewController?.dismiss() - } - } - self.push(wallpaperPreviewController) - return true - case let .giftPremium(_, _, duration, _, _, _, _): - self.chatDisplayNode.dismissInput() - let fromPeerId: PeerId = message.author?.id == self.context.account.peerId ? self.context.account.peerId : message.id.peerId - let toPeerId: PeerId = message.author?.id == self.context.account.peerId ? message.id.peerId : self.context.account.peerId - let controller = PremiumIntroScreen(context: self.context, source: .gift(from: fromPeerId, to: toPeerId, duration: duration, giftCode: nil)) - self.push(controller) - return true - case .starGift, .starGiftUnique: - let controller = self.context.sharedContext.makeGiftViewScreen(context: self.context, message: EngineMessage(message), shareStory: { [weak self] uniqueGift in - Queue.mainQueue().after(0.15) { - if let self { - let controller = self.context.sharedContext.makeStorySharingScreen(context: self.context, subject: .gift(uniqueGift), parentController: self) - self.push(controller) - } - } - }) - self.push(controller) - return true - case .giftStars: - let controller = self.context.sharedContext.makeStarsGiftScreen(context: self.context, message: EngineMessage(message)) - self.push(controller) - return true - case let .giftTon(_, _, _, _, transactionId): - Task { @MainActor [weak self] in - guard let self, let transactionId, let peerId = self.chatLocation.peerId else { - return - } - let transactionData = await self.context.engine.payments.getStarsTransaction(reference: StarsTransactionReference(peerId: self.context.account.peerId, ton: true, id: transactionId, isRefund: false)).get() - let peer = await self.context.engine.data.get( - TelegramEngine.EngineData.Item.Peer.Peer(id: peerId) - ).get() - if let transactionData, let peer { - self.push(self.context.sharedContext.makeStarsTransactionScreen(context: self.context, transaction: transactionData, peer: peer)) - } - } - case let .giftCode(slug, _, _, _, _, _, _, _, _, _, _): - self.openResolved(result: .premiumGiftCode(slug: slug), sourceMessageId: message.id, progress: params.progress) - return true - case .prizeStars: - let controller = self.context.sharedContext.makeStarsGiftScreen(context: self.context, message: EngineMessage(message)) - self.push(controller) - return true - case let .suggestedBirthday(birthday): - self.chatDisplayNode.dismissInput() - guard message.author?.id != self.context.account.peerId else { - return true - } - let settingsPromise: Promise - if let rootController = self.context.sharedContext.mainWindow?.viewController as? TelegramRootControllerInterface, let current = rootController.getPrivacySettings() { - settingsPromise = current - } else { - settingsPromise = Promise() - settingsPromise.set(.single(nil) |> then(self.context.engine.privacy.requestAccountPrivacySettings() |> map(Optional.init))) - } - - let controller = self.context.sharedContext.makeBirthdayAcceptSuggestionScreen(context: self.context, birthday: birthday, settings: settingsPromise, openSettings: { [weak self] in - guard let self else { - return - } - self.context.sharedContext.makeBirthdayPrivacyController(context: self.context, settings: settingsPromise, openedFromBirthdayScreen: true, present: { [weak self] c in - self?.push(c) - }) - }, completion: { [weak self] value in - guard let self else { - return - } - let _ = self.context.engine.accountData.updateBirthday(birthday: value).startStandalone() - - self.present(UndoOverlayController(presentationData: self.presentationData, content: .universal(animation: "anim_gift", scale: 0.058, colors: ["__allcolors__": UIColor.white], title: nil, text: self.presentationData.strings.SuggestBirthdate_Accept_Added, customUndoText: nil, timeout: 5.0), elevatedLayout: false, action: { _ in - return true - }), in: .current) - }) - self.push(controller) - return true - case let .suggestedProfilePhoto(image): - self.chatDisplayNode.dismissInput() - if let image = image { - if message.effectivelyIncoming(self.context.account.peerId) { - if let emojiMarkup = image.emojiMarkup { - let controller = AvatarEditorScreen(context: self.context, inputData: AvatarEditorScreen.inputData(context: self.context, isGroup: false), peerType: .user, markup: emojiMarkup) - controller.imageCompletion = { [weak self] image, commit in - if let self { - if let rootController = self.effectiveNavigationController as? TelegramRootController, let settingsController = rootController.accountSettingsController as? PeerInfoScreenImpl { - settingsController.updateProfilePhoto(image, mode: .accept, uploadStatus: nil) - commit() - } - } - } - controller.videoCompletion = { [weak self] image, url, values, markup, commit in - if let self { - if let rootController = self.effectiveNavigationController as? TelegramRootController, let settingsController = rootController.accountSettingsController as? PeerInfoScreenImpl { - settingsController.updateProfileVideo(image, video: nil, values: nil, markup: markup, mode: .accept, uploadStatus: nil) - commit() - } - } - } - self.push(controller) - } else { - var selectedNode: (ASDisplayNode, CGRect, () -> (UIView?, UIView?))? - self.chatDisplayNode.historyNode.forEachItemNode { itemNode in - if let itemNode = itemNode as? ChatMessageItemView { - if let result = itemNode.transitionNode(id: message.id, media: image, adjustRect: false) { - selectedNode = result - } - } - } - let transitionView = selectedNode?.0.view - - let senderName: String? - if let peer = message.peers[message.id.peerId] { - senderName = EnginePeer(peer).compactDisplayTitle - } else { - senderName = nil - } - - legacyAvatarEditor(context: self.context, media: .message(message: MessageReference(message), media: image), transitionView: transitionView, senderName: senderName, present: { [weak self] c, a in - self?.present(c, in: .window(.root), with: a) - }, imageCompletion: { [weak self] image in - if let self { - if let rootController = self.effectiveNavigationController as? TelegramRootController, let settingsController = rootController.accountSettingsController as? PeerInfoScreenImpl { - settingsController.updateProfilePhoto(image, mode: .accept, uploadStatus: nil) - } - } - }, videoCompletion: { [weak self] image, url, adjustments in - if let self { - if let rootController = self.effectiveNavigationController as? TelegramRootController, let settingsController = rootController.accountSettingsController as? PeerInfoScreenImpl { - settingsController.oldUpdateProfileVideo(image, asset: AVURLAsset(url: url), adjustments: adjustments, mode: .accept) - } - } - }) - } - } else { - openMessageByAction = true - } - } - case .boostsApplied: - self.controllerInteraction?.openGroupBoostInfo(nil, 0) - return true - case .paidMessagesPriceEdited: - self.interfaceInteraction?.openMonoforum() - return true - case .starGiftPurchaseOffer: - let controller = self.context.sharedContext.makeGiftViewScreen(context: self.context, message: EngineMessage(message), shareStory: { [weak self] uniqueGift in - Queue.mainQueue().after(0.15) { - if let self { - let controller = self.context.sharedContext.makeStorySharingScreen(context: self.context, subject: .gift(uniqueGift), parentController: self) - self.push(controller) - } - } - }) - self.push(controller) - return true - default: - break - } - if !openMessageByAction { - return true - } - } - } - - let openChatLocation = self.chatLocation - var chatFilterTag: MemoryBuffer? - if case let .customTag(value, _) = self.chatDisplayNode.historyNode.tag { - chatFilterTag = value - } - - var standalone = false - if case .customChatContents = self.chatLocation { - standalone = true - } - - if let adAttribute = message.attributes.first(where: { $0 is AdMessageAttribute }) as? AdMessageAttribute { - if let file = message.media.first(where: { $0 is TelegramMediaFile}) as? TelegramMediaFile, file.isVideo && !file.isAnimated { - self.chatDisplayNode.adMessagesContext?.markAction(opaqueId: adAttribute.opaqueId, media: true, fullscreen: false) - } else { - self.controllerInteraction?.activateAdAction(message.id, nil, true, false) - return true - } - } - - let openChatMessageParams = OpenChatMessageParams(context: context, updatedPresentationData: self.updatedPresentationData, chatLocation: openChatLocation, chatFilterTag: chatFilterTag, chatLocationContextHolder: self.chatLocationContextHolder, message: message, mediaIndex: params.mediaIndex, standalone: standalone, reverseMessageGalleryOrder: false, mode: mode, navigationController: self.effectiveNavigationController, dismissInput: { [weak self] in - self?.chatDisplayNode.dismissInput() - }, present: { [weak self] c, a, i in - guard let self else { - return - } - - if case .current = i { - c.presentationArguments = a - c.statusBar.alphaUpdated = { [weak self] transition in - guard let self else { - return - } - self.updateStatusBarPresentation(animated: transition.isAnimated) - } - self.galleryPresentationContext.present(c, on: PresentationSurfaceLevel(rawValue: 0), blockInteraction: true, completion: {}) - } else { - self.present(c, in: .window(.root), with: a, blockInteraction: true) - } - }, transitionNode: { [weak self] messageId, media, adjustRect in - var selectedNode: (ASDisplayNode, CGRect, () -> (UIView?, UIView?))? - if let self { - self.chatDisplayNode.historyNode.forEachItemNode { itemNode in - if let itemNode = itemNode as? ChatMessageItemView { - if let result = itemNode.transitionNode(id: messageId, media: media, adjustRect: adjustRect) { - selectedNode = result - } - } - } - } - return selectedNode - }, addToTransitionSurface: { [weak self] view in - guard let self else { - return - } - if let contextController = self.currentContextController { - contextController.view.addSubview(view) - } else { - self.chatDisplayNode.historyNode.view.superview?.insertSubview(view, aboveSubview: self.chatDisplayNode.historyNode.view) - } - }, openUrl: { [weak self] url in - self?.openUrl(url, concealed: false, skipConcealedAlert: isLocation, message: nil) - }, openPeer: { [weak self] peer, navigation in - self?.openPeer(peer: EnginePeer(peer), navigation: navigation, fromMessage: nil) - }, callPeer: { [weak self] peerId, isVideo in - self?.controllerInteraction?.callPeer(peerId, isVideo) - }, openConferenceCall: { [weak self] message in - self?.controllerInteraction?.openConferenceCall(message) - }, enqueueMessage: { [weak self] message in - self?.sendMessages([message]) - }, sendSticker: canSendMessagesToChat(self.presentationInterfaceState) ? { [weak self] fileReference, sourceNode, sourceRect in - return self?.controllerInteraction?.sendSticker(fileReference, false, false, nil, false, sourceNode, sourceRect, nil, []) ?? false - } : nil, sendEmoji: canSendMessagesToChat(self.presentationInterfaceState) ? { [weak self] text, attribute in - self?.controllerInteraction?.sendEmoji(text, attribute, false) - } : nil, setupTemporaryHiddenMedia: { [weak self] signal, centralIndex, galleryMedia in - if let self { - self.temporaryHiddenGalleryMediaDisposable.set((signal |> deliverOnMainQueue).startStrict(next: { [weak self] entry in - if let self, let controllerInteraction = self.controllerInteraction { - var messageIdAndMedia: [MessageId: [Media]] = [:] - - if let entry = entry as? InstantPageGalleryEntry, entry.index == centralIndex { - messageIdAndMedia[message.id] = [galleryMedia] - } - - controllerInteraction.hiddenMedia = messageIdAndMedia - - self.chatDisplayNode.historyNode.forEachItemNode { itemNode in - if let itemNode = itemNode as? ChatMessageItemView { - itemNode.updateHiddenMedia() - } - } - } - })) - } - }, chatAvatarHiddenMedia: { [weak self] signal, media in - if let self { - self.temporaryHiddenGalleryMediaDisposable.set((signal |> deliverOnMainQueue).startStrict(next: { [weak self] messageId in - if let self, let controllerInteraction = self.controllerInteraction { - var messageIdAndMedia: [MessageId: [Media]] = [:] - - if let messageId = messageId { - messageIdAndMedia[messageId] = [media] - } - - controllerInteraction.hiddenMedia = messageIdAndMedia - - self.chatDisplayNode.historyNode.forEachItemNode { itemNode in - if let itemNode = itemNode as? ChatMessageItemView { - itemNode.updateHiddenMedia() - } - } - } - })) - } - }, actionInteraction: GalleryControllerActionInteraction( - openUrl: { [weak self] url, concealed, forceExternal in - if let self { - self.openUrl(url, concealed: concealed, forceExternal: forceExternal, message: nil) - } - }, openUrlIn: { [weak self] url in - if let self { - self.openUrlIn(url) - } - }, openPeerMention: { [weak self] mention in - if let self { - self.controllerInteraction?.openPeerMention(mention, nil) - } - }, openPeer: { [weak self] peer in - if let self { - self.controllerInteraction?.openPeer(peer, .default, nil, .default) - } - }, openHashtag: { [weak self] peerName, hashtag in - if let self { - self.controllerInteraction?.openHashtag(peerName, hashtag) - } - }, openBotCommand: { [weak self] command in - if let self { - self.controllerInteraction?.sendBotCommand(nil, command) - } - }, openAd: { [weak self] messageId in - if let self { - self.controllerInteraction?.activateAdAction(messageId, nil, true, true) - } - }, addContact: { [weak self] phoneNumber in - if let self { - self.controllerInteraction?.addContact(phoneNumber) - } - }, storeMediaPlaybackState: { [weak self] messageId, timestamp, playbackRate in - guard let self else { - return - } - var storedState: MediaPlaybackStoredState? - if let timestamp = timestamp { - storedState = MediaPlaybackStoredState(timestamp: timestamp, playbackRate: AudioPlaybackRate(playbackRate)) - } - let _ = updateMediaPlaybackStoredStateInteractively(engine: self.context.engine, messageId: messageId, state: storedState).startStandalone() - }, editMedia: { [weak self] messageId, snapshots, transitionCompletion in - guard let self else { - return - } - - let _ = (self.context.engine.data.get(TelegramEngine.EngineData.Item.Messages.Message(id: messageId)) - |> deliverOnMainQueue).startStandalone(next: { [weak self] message in - guard let self, let message = message else { - return - } - - var mediaReference: AnyMediaReference? - for media in message.media { - if let image = media as? TelegramMediaImage { - mediaReference = AnyMediaReference.standalone(media: image) - } else if let file = media as? TelegramMediaFile { - mediaReference = AnyMediaReference.standalone(media: file) - } else if let webpage = media as? TelegramMediaWebpage, case let .Loaded(content) = webpage.content { - if let image = content.image { - mediaReference = AnyMediaReference.standalone(media: image) - } else if let file = content.file { - mediaReference = AnyMediaReference.standalone(media: file) - } - } - } - - if let mediaReference = mediaReference, let peer = message.peers[message.id.peerId] { - legacyMediaEditor(context: self.context, peer: peer, threadTitle: self.contentData?.state.threadInfo?.title, media: mediaReference, mode: .draw, initialCaption: NSAttributedString(), snapshots: snapshots, transitionCompletion: { - transitionCompletion() - }, getCaptionPanelView: { [weak self] in - return self?.getCaptionPanelView(isFile: false) - }, sendMessagesWithSignals: { [weak self] signals, _, _, isCaptionAbove in - if let self { - var parameters: ChatSendMessageActionSheetController.SendParameters? - if isCaptionAbove { - parameters = ChatSendMessageActionSheetController.SendParameters(effect: nil, textIsAboveMedia: true) - } - self.enqueueMediaMessages(signals: signals, silentPosting: false, parameters: parameters) - } - }, present: { [weak self] c, a in - self?.present(c, in: .window(.root), with: a) - }) - } - }) - }, updateCanReadHistory: { [weak self] canReadHistory in - self?.canReadHistory.set(canReadHistory) - }), - getSourceRect: { [weak self] in - guard let self else { - return nil - } - var rect: CGRect? - self.chatDisplayNode.historyNode.forEachVisibleMessageItemNode({ itemNode in - if itemNode.item?.message.id == message.id { - rect = itemNode.view.convert(itemNode.contentFrame(), to: nil) - } - }) - return rect - } - ) - - self.controllerInteraction?.isOpeningMediaSignal = openChatMessageParams.blockInteraction.get() - - return context.sharedContext.openChatMessage(openChatMessageParams) + return self.openMessageFromControllerInteraction(message, params: params) } - let openPeer: (EnginePeer, ChatControllerInteractionNavigateToPeer, MessageReference?, ChatControllerInteraction.OpenPeerSource) -> Void = { [weak self] peer, navigation, fromMessage, source in + let sgGetChatPredictedLangImpl: () -> String? = { [weak self] in + if let strongSelf = self { + var result: String? + if let chatPeerId = strongSelf.chatLocation.peerId { + result = SGSimpleSettings.shared.outgoingLanguageTranslation[SGSimpleSettings.makeOutgoingLanguageTranslationKey(accountId: strongSelf.context.account.peerId.id._internalGetInt64Value(), peerId: chatPeerId.id._internalGetInt64Value())] + } + return result ?? strongSelf.contentData?.state.predictedChatLanguage + } + return nil + } + let sgStartMessageEditImpl: (Message) -> Void = { [weak self] message in + if let strongSelf = self { + strongSelf.interfaceInteraction?.setupEditMessage(message.id, { _ in }) + } + } + let openPeerImpl = { [weak self] (peer: EnginePeer, navigation: ChatControllerInteractionNavigateToPeer, fromMessage: MessageReference?, source: ChatControllerInteraction.OpenPeerSource) -> Void in var expandAvatar = false if case let .groupParticipant(storyStats, avatarHeaderNode) = source { if let storyStats, storyStats.totalCount != 0, let avatarHeaderNode = avatarHeaderNode as? ChatMessageAvatarHeaderNodeImpl { @@ -1583,19 +922,16 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G } self?.openPeer(peer: peer, navigation: navigation, fromMessage: fromMessage, fromReactionMessageId: fromReactionMessageId, expandAvatar: expandAvatar) } - - let openPeerMention: (String, Promise?) -> Void = { [weak self] name, progress in + let openPeerMentionImpl: (String, Promise?) -> Void = { [weak self] name, progress in self?.openPeerMention(name, progress: progress) } - - let openMessageContextMenu: (Message, Bool, ASDisplayNode, CGRect, UIGestureRecognizer?, CGPoint?) -> Void = { [weak self] message, selectAll, node, frame, anyRecognizer, location in + let openMessageContextMenuImpl: (Message, Bool, ASDisplayNode, CGRect, UIGestureRecognizer?, CGPoint?) -> Void = { [weak self] message, selectAll, node, frame, anyRecognizer, location in guard let self, self.isNodeLoaded else { return } self.openMessageContextMenu(message: message, selectAll: selectAll, node: node, frame: frame, anyRecognizer: anyRecognizer, location: location) } - - let openMessageReactionContextMenu: (Message, ContextExtractedContentContainingView, ContextGesture?, MessageReaction.Reaction) -> Void = { [weak self] message, sourceView, gesture, value in + let openMessageReactionContextMenuImpl: (Message, ContextExtractedContentContainingView, ContextGesture?, MessageReaction.Reaction) -> Void = { [weak self] message, sourceView, gesture, value in guard let self else { return } @@ -1603,7 +939,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G self.openMessageReactionContextMenu(message: message, sourceView: sourceView, gesture: gesture, value: value) } - let updateMessageReaction: (Message, ChatControllerInteractionReaction, Bool, ContextExtractedContentContainingView?) -> Void = { [weak self] initialMessage, reaction, force, sourceView in + let updateMessageReactionImpl: (Message, ChatControllerInteractionReaction, Bool, ContextExtractedContentContainingView?) -> Void = { [weak self] initialMessage, reaction, force, sourceView in guard let strongSelf = self else { return } @@ -2073,14 +1409,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G }) } - let controllerInteraction = ChatControllerInteraction( - openMessage: openMessage, - openPeer: openPeer, - openPeerMention: openPeerMention, - openMessageContextMenu: openMessageContextMenu, - openMessageReactionContextMenu: openMessageReactionContextMenu, - updateMessageReaction: updateMessageReaction, - activateMessagePinch: { [weak self] sourceNode in + let controllerInteraction = ChatControllerInteraction(openMessage: openMessageImpl, sgGetChatPredictedLang: sgGetChatPredictedLangImpl, sgStartMessageEdit: sgStartMessageEditImpl, openPeer: openPeerImpl, openPeerMention: openPeerMentionImpl, openMessageContextMenu: openMessageContextMenuImpl, openMessageReactionContextMenu: openMessageReactionContextMenuImpl, updateMessageReaction: updateMessageReactionImpl, activateMessagePinch: { [weak self] sourceNode in guard let strongSelf = self else { return } @@ -2096,7 +1425,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G } let isSecret = strongSelf.presentationInterfaceState.copyProtectionEnabled || strongSelf.chatLocation.peerId?.namespace == Namespaces.Peer.SecretChat - let pinchController = PinchController(sourceNode: sourceNode, disableScreenshots: isSecret, getContentAreaInScreenSpace: { + let pinchController = makePinchController(sourceNode: sourceNode, disableScreenshots: isSecret, getContentAreaInScreenSpace: { guard let strongSelf = self else { return CGRect() } @@ -2119,7 +1448,8 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G if let context = self?.context, let navigationController = self?.effectiveNavigationController { let _ = context.sharedContext.navigateToForumThread(context: context, peerId: peerId, threadId: threadId, messageId: messageId, navigationController: navigationController, activateInput: nil, scrollToEndIfExists: false, keepStack: .always, animated: true).startStandalone() } - }, tapMessage: nil, clickThroughMessage: { [weak self] view, location in + }, tapMessage: nil, + clickThroughMessage: { [weak self] view, location in self?.chatDisplayNode.dismissInput(view: view, location: location) }, toggleMessagesSelection: { [weak self] ids, value in guard let strongSelf = self, strongSelf.isNodeLoaded else { @@ -2865,18 +2195,18 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G switch result { case .default: strongSelf.openUrl(defaultUrl, concealed: false, skipUrlAuth: true) - case let .request(domain, bot, requestWriteAccess): - let controller = chatMessageActionUrlAuthController(context: strongSelf.context, defaultUrl: defaultUrl, domain: domain, bot: bot, requestWriteAccess: requestWriteAccess, displayName: EnginePeer(peer).displayTitle(strings: strongSelf.presentationData.strings, displayOrder: strongSelf.presentationData.nameDisplayOrder), open: { [weak self] authorize, allowWriteAccess in + case let .request(domain, bot, _, flags): + let controller = chatMessageActionUrlAuthController(context: strongSelf.context, defaultUrl: defaultUrl, domain: domain, bot: bot, requestWriteAccess: flags.contains(.requestWriteAccess), displayName: EnginePeer(peer).displayTitle(strings: strongSelf.presentationData.strings, displayOrder: strongSelf.presentationData.nameDisplayOrder), open: { [weak self] authorize, allowWriteAccess in if let strongSelf = self { if authorize { strongSelf.updateChatPresentationInterfaceState(animated: true, interactive: true, { return $0.updatedTitlePanelContext { if !$0.contains(where: { switch $0 { - case .requestInProgress: - return true - default: - return false + case .requestInProgress: + return true + default: + return false } }) { var updatedContexts = $0 @@ -2887,17 +2217,17 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G } }) - strongSelf.messageActionUrlAuthDisposable.set(((strongSelf.context.engine.messages.acceptMessageActionUrlAuth(subject: subject, allowWriteAccess: allowWriteAccess) |> afterDisposed { + strongSelf.messageActionUrlAuthDisposable.set(((strongSelf.context.engine.messages.acceptMessageActionUrlAuth(subject: subject, allowWriteAccess: allowWriteAccess, sharePhoneNumber: false) |> afterDisposed { Queue.mainQueue().async { if let strongSelf = self { strongSelf.updateChatPresentationInterfaceState(animated: true, interactive: true, { return $0.updatedTitlePanelContext { if let index = $0.firstIndex(where: { switch $0 { - case .requestInProgress: - return true - default: - return false + case .requestInProgress: + return true + default: + return false } }) { var updatedContexts = $0 @@ -2912,10 +2242,12 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G }) |> deliverOnMainQueue).startStrict(next: { [weak self] result in if let strongSelf = self { switch result { - case let .accepted(url): + case let .accepted(url): + if let url { strongSelf.openUrl(url, concealed: false, skipUrlAuth: true) - default: - strongSelf.openUrl(defaultUrl, concealed: false, skipUrlAuth: true) + } + default: + strongSelf.openUrl(defaultUrl, concealed: false, skipUrlAuth: true) } } })) @@ -2927,7 +2259,9 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G strongSelf.chatDisplayNode.dismissInput() strongSelf.present(controller, in: .window(.root)) case let .accepted(url): - strongSelf.openUrl(url, concealed: false, forceExternal: true, skipUrlAuth: true) + if let url { + strongSelf.openUrl(url, concealed: false, forceExternal: true, skipUrlAuth: true) + } } } })) @@ -3411,7 +2745,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G strongSelf.chatDisplayNode.messageTransitionNode.dismissMessageReactionContexts() - let controller = ContextController(presentationData: strongSelf.presentationData, source: .extracted(ChatMessageContextExtractedContentSource(chatController: strongSelf, chatNode: strongSelf.chatDisplayNode, engine: strongSelf.context.engine, message: message._asMessage(), selectAll: true)), items: .single(ContextController.Items(content: .list(actions))), recognizer: nil) + let controller = makeContextController(presentationData: strongSelf.presentationData, source: .extracted(ChatMessageContextExtractedContentSource(chatController: strongSelf, chatNode: strongSelf.chatDisplayNode, engine: strongSelf.context.engine, message: message._asMessage(), selectAll: true)), items: .single(ContextController.Items(content: .list(actions))), recognizer: nil) strongSelf.currentContextController = controller strongSelf.forEachController({ controller in if let controller = controller as? TooltipScreen { @@ -3499,7 +2833,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G strongSelf.chatDisplayNode.messageTransitionNode.dismissMessageReactionContexts() - let controller = ContextController(presentationData: strongSelf.presentationData, source: .extracted(ChatMessageContextExtractedContentSource(chatController: strongSelf, chatNode: strongSelf.chatDisplayNode, engine: strongSelf.context.engine, message: topMessage, selectAll: true)), items: .single(ContextController.Items(content: .list(actions))), recognizer: nil) + let controller = makeContextController(presentationData: strongSelf.presentationData, source: .extracted(ChatMessageContextExtractedContentSource(chatController: strongSelf, chatNode: strongSelf.chatDisplayNode, engine: strongSelf.context.engine, message: topMessage, selectAll: true)), items: .single(ContextController.Items(content: .list(actions))), recognizer: nil) strongSelf.currentContextController = controller strongSelf.forEachController({ controller in if let controller = controller as? TooltipScreen { @@ -3898,7 +3232,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G self.currentContextController = nil if let transition { - currentContextController.dismissWithCustomTransition(transition: transition) + currentContextController.dismissWithCustomTransition(transition: transition, completion: nil) } else { currentContextController.dismiss(completion: {}) } @@ -4114,7 +3448,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G source = .reference(ChatControllerContextReferenceContentSource(controller: strongSelf, sourceView: node.view, insets: .zero)) } - let contextController = ContextController(presentationData: strongSelf.presentationData, source: source, items: .single(ContextController.Items(content: .list(items))), gesture: gesture) + let contextController = makeContextController(presentationData: strongSelf.presentationData, source: source, items: .single(ContextController.Items(content: .list(items))), gesture: gesture) contextController.dismissed = { [weak self] in self?.canReadHistory.set(true) } @@ -4790,7 +4124,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G self.canReadHistory.set(false) - let contextController = ContextController(presentationData: self.presentationData, source: .controller(ChatContextControllerContentSourceImpl(controller: chatController, sourceView: sourceView, passthroughTouches: true)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) + let contextController = makeContextController(presentationData: self.presentationData, source: .controller(ChatContextControllerContentSourceImpl(controller: chatController, sourceView: sourceView, passthroughTouches: true)), items: .single(ContextController.Items(content: .list(items))), gesture: gesture) contextController.dismissed = { [weak self] in self?.canReadHistory.set(true) } @@ -4830,7 +4164,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G reveal() }) } else { - let controller = chatAgeRestrictionAlertController(context: self.context, updatedPresentationData: self.updatedPresentationData, parentController: self, completion: { alwaysShow in + let controller = ChatAgeRestrictionAlertController.chatAgeRestrictionAlertController(context: self.context, updatedPresentationData: self.updatedPresentationData, parentController: self, completion: { alwaysShow in if alwaysShow { let _ = updateRemoteContentSettingsConfiguration(postbox: context.account.postbox, network: context.account.network, sensitiveContentEnabled: true).start() } @@ -5546,7 +4880,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G source = .reference(ChatControllerContextReferenceContentSource(controller: strongSelf, sourceView: node.view, insets: .zero)) } - let contextController = ContextController(presentationData: strongSelf.presentationData, source: source, items: items |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) + let contextController = makeContextController(presentationData: strongSelf.presentationData, source: source, items: items |> map { ContextController.Items(content: .list($0)) }, gesture: gesture) contextController.dismissed = { [weak self] in self?.canReadHistory.set(true) } @@ -6158,6 +5492,33 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G return state.updatedInterfaceState({ $0.withUpdatedSelectedMessages(messageIds) }) }) } + + // MARK: Swiftgram + self.sgShowHiddenPinnedMessagesObserver = NotificationCenter.default.addObserver( + forName: NSNotification.Name("SGShowHiddenPinnedMessages"), + object: nil, + queue: nil, + using: { [weak self] notification in + guard + let self = self, + let peerId = self.chatLocation.peerId, + let notificationPeerId = notification.object as? PeerId, + peerId == notificationPeerId + else { + return + } + + self.updateChatPresentationInterfaceState(animated: true, interactive: true, { + $0.updatedInterfaceState { + $0.withUpdatedMessageActionsState { value in + var value = value + value.closedPinnedMessageId = nil + return value + } + } + }) + } + ) } required public init(coder aDecoder: NSCoder) { @@ -6165,6 +5526,8 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G } deinit { + // MARK: Swiftgram + if let observer = sgShowHiddenPinnedMessagesObserver { NotificationCenter.default.removeObserver(observer) } let _ = ChatControllerCount.modify { value in return value - 1 } @@ -6338,8 +5701,8 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G case .embedded: self.statusBar.statusBarStyle = .Ignore default: - if let isDark = self.chatDisplayNode.backgroundNode.isDark { - if isDark { + if let contentStats = self.chatDisplayNode.backgroundNode.contentStats { + if contentStats.isDark { self.statusBar.statusBarStyle = .White } else { self.statusBar.statusBarStyle = .Black @@ -6382,10 +5745,10 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G let presentationTheme: PresentationTheme if let forcedNavigationBarTheme = self.forcedNavigationBarTheme { presentationTheme = forcedNavigationBarTheme - navigationBarTheme = NavigationBarTheme(rootControllerTheme: forcedNavigationBarTheme, hideBackground: false, hideBadge: true, edgeEffectColor: .clear, style: .glass) + navigationBarTheme = chatNavigationBarTheme(presentationTheme: forcedNavigationBarTheme, hideBadge: true) } else { presentationTheme = self.presentationData.theme - navigationBarTheme = NavigationBarTheme(rootControllerTheme: self.presentationData.theme, hideBackground: false, hideBadge: false, edgeEffectColor: .clear, style: .glass) + navigationBarTheme = chatNavigationBarTheme(presentationTheme: self.presentationData.theme, hideBadge: false) } self.navigationBar?.updatePresentationData(NavigationBarPresentationData(theme: navigationBarTheme, strings: NavigationBarStrings(presentationStrings: self.presentationData.strings)), transition: .immediate) @@ -8112,7 +7475,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G var defaultReplyMessageSubject: EngineMessageReplySubject? switch self.chatLocation { case .peer: - if let user = self.presentationInterfaceState.renderedPeer?.peer as? TelegramUser, user.isForum { + if let user = self.presentationInterfaceState.renderedPeer?.peer as? TelegramUser, let botInfo = user.botInfo, botInfo.flags.contains(.hasForum), botInfo.flags.contains(.forumManagedByUser) { defaultThreadId = EngineMessage.newTopicThreadId } case let .replyThread(replyThreadMessage): @@ -8324,6 +7687,8 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G guard let strongSelf = self else { return } + + let isSendDelayActive = SendDelayManager.shared.isEnabled && scheduleTime == nil var completionImpl: (() -> Void)? = completion @@ -8336,7 +7701,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G var skipAddingTransitions = false - if shouldDivert { + if shouldDivert || isSendDelayActive { skipAddingTransitions = true } @@ -8453,16 +7818,24 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G let messages = strongSelf.transformEnqueueMessages(mappedMessages, silentPosting: silentPosting, scheduleTime: scheduleTime, postpone: postpone) let replyMessageSubject = strongSelf.presentationInterfaceState.interfaceState.replyMessageSubject - strongSelf.chatDisplayNode.setupSendActionOnViewUpdate({ - if let strongSelf = self { - strongSelf.chatDisplayNode.collapseInput() - - strongSelf.updateChatPresentationInterfaceState(animated: true, interactive: false, { - $0.updatedInterfaceState { $0.withUpdatedReplyMessageSubject(nil).withUpdatedSendMessageEffect(nil).withUpdatedPostSuggestionState(nil) } - }) - } + if isSendDelayActive { + strongSelf.chatDisplayNode.collapseInput() + strongSelf.updateChatPresentationInterfaceState(animated: true, interactive: false, { + $0.updatedInterfaceState { $0.withUpdatedReplyMessageSubject(nil).withUpdatedSendMessageEffect(nil).withUpdatedPostSuggestionState(nil) } + }) completionImpl?() - }, usedCorrelationId) + } else { + strongSelf.chatDisplayNode.setupSendActionOnViewUpdate({ + if let strongSelf = self { + strongSelf.chatDisplayNode.collapseInput() + + strongSelf.updateChatPresentationInterfaceState(animated: true, interactive: false, { + $0.updatedInterfaceState { $0.withUpdatedReplyMessageSubject(nil).withUpdatedSendMessageEffect(nil).withUpdatedPostSuggestionState(nil) } + }) + } + completionImpl?() + }, usedCorrelationId) + } strongSelf.sendMessages(messages.map { $0.withUpdatedReplyToMessageId(replyMessageSubject?.subjectModel) }, media: true) @@ -9124,6 +8497,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G } func displayMediaRecordingTooltip() { + if ({ return true })() { return } // MARK: Swiftgram guard let peer = self.presentationInterfaceState.renderedPeer?.peer else { return } @@ -10356,6 +9730,782 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G } } + private func openMessageFromControllerInteraction(_ message: Message, params: OpenMessageParams) -> Bool { + guard self.isNodeLoaded, let message = self.chatDisplayNode.historyNode.messageInCurrentHistoryView(message.id) else { + return false + } + + if let contextController = self.currentContextController { + self.present(contextController, in: .window(.root)) + Queue.mainQueue().after(0.15) { + contextController.dismiss(result: .dismissWithoutContent, completion: nil) + } + } + + let mode = params.mode + + let displayVoiceMessageDiscardAlert: () -> Bool = { [weak self] in + guard let self else { + return true + } + if self.presentVoiceMessageDiscardAlert(action: { [weak self] in + Queue.mainQueue().after(0.1, { + guard let self else { + return + } + let _ = self.controllerInteraction?.openMessage(message, params) + }) + }, performAction: false) { + return false + } + return true + } + + self.commitPurposefulAction() + self.dismissAllTooltips() + + self.chatDisplayNode.messageTransitionNode.dismissMessageReactionContexts() + + var openMessageByAction = false + var isLocation = false + + for media in message.media { + if media is TelegramMediaMap { + if !displayVoiceMessageDiscardAlert() { + return false + } + isLocation = true + } + if let file = media as? TelegramMediaFile { + if file.isInstantVideo { + if self.chatDisplayNode.isInputViewFocused { + self.returnInputViewFocus = true + self.chatDisplayNode.dismissInput() + } + } + if file.isMusic || file.isVoice || file.isInstantVideo { + if !displayVoiceMessageDiscardAlert() { + return false + } + + if (file.isVoice || file.isInstantVideo) && message.minAutoremoveOrClearTimeout == viewOnceTimeout { + self.openViewOnceMediaMessage(message) + return false + } + } else if file.isVideo { + if !displayVoiceMessageDiscardAlert() { + return false + } + } + } + if let paidContent = media as? TelegramMediaPaidContent, let extendedMedia = paidContent.extendedMedia.first { + switch extendedMedia { + case .preview: + if displayVoiceMessageDiscardAlert() { + self.controllerInteraction?.openCheckoutOrReceipt(message.id, params) + return true + } else { + return false + } + case .full: + break + } + } else if let invoice = media as? TelegramMediaInvoice, let extendedMedia = invoice.extendedMedia { + switch extendedMedia { + case .preview: + if displayVoiceMessageDiscardAlert() { + self.controllerInteraction?.openCheckoutOrReceipt(message.id, nil) + return true + } else { + return false + } + case .full: + break + } + } else if media is TelegramMediaGiveaway || media is TelegramMediaGiveawayResults { + let progress = params.progress + let presentationData = self.presentationData + + var signal = self.context.engine.payments.premiumGiveawayInfo(peerId: message.id.peerId, messageId: message.id) + let disposable: MetaDisposable + if let current = self.giveawayStatusDisposable { + disposable = current + } else { + disposable = MetaDisposable() + self.giveawayStatusDisposable = disposable + } + + let progressSignal = Signal { [weak self] subscriber in + if let progress { + progress.set(.single(true)) + return ActionDisposable { + Queue.mainQueue().async() { + progress.set(.single(false)) + } + } + } else { + let controller = OverlayStatusController(theme: presentationData.theme, type: .loading(cancelled: nil)) + self?.present(controller, in: .window(.root)) + return ActionDisposable { [weak controller] in + Queue.mainQueue().async() { + controller?.dismiss() + } + } + } + } + |> runOn(Queue.mainQueue()) + |> delay(0.25, queue: Queue.mainQueue()) + let progressDisposable = progressSignal.startStrict() + + signal = signal + |> afterDisposed { + Queue.mainQueue().async { + progressDisposable.dispose() + } + } + disposable.set((signal + |> deliverOnMainQueue).startStrict(next: { [weak self] info in + if let self, let info { + self.displayGiveawayStatusInfo(messageId: message.id, giveawayInfo: info) + } + })) + + return true + } else if let action = media as? TelegramMediaAction { + if !displayVoiceMessageDiscardAlert() { + return false + } + switch action.action { + case .pinnedMessageUpdated, .gameScore, .setSameChatWallpaper, .giveawayResults, .customText, .todoCompletions, .todoAppendTasks, .suggestedPostRefund, .suggestedPostSuccess, .suggestedPostApprovalStatus: + for attribute in message.attributes { + if let attribute = attribute as? ReplyMessageAttribute { + var todoTaskId: Int32? + if case let .todoCompletions(completed, incompleted) = action.action { + if let completedTaskId = completed.first { + todoTaskId = completedTaskId + } else if let incompletedTaskId = incompleted.first { + todoTaskId = incompletedTaskId + } + } else if case let .todoAppendTasks(tasks) = action.action { + if let task = tasks.first { + todoTaskId = task.id + } + } + self.navigateToMessage(from: message.id, to: .id(attribute.messageId, NavigateToMessageParams(timestamp: nil, quote: attribute.isQuote ? attribute.quote.flatMap { quote in NavigateToMessageParams.Quote(string: quote.text, offset: quote.offset) } : nil, todoTaskId: todoTaskId))) + break + } + } + case let .photoUpdated(image): + openMessageByAction = image != nil + case .groupPhoneCall, .inviteToGroupPhoneCall: + if let activeCall = self.presentationInterfaceState.activeGroupCallInfo?.activeCall { + self.joinGroupCall(peerId: message.id.peerId, invite: nil, activeCall: EngineGroupCallDescription(id: activeCall.id, accessHash: activeCall.accessHash, title: activeCall.title, scheduleTimestamp: activeCall.scheduleTimestamp, subscribedToScheduled: activeCall.subscribedToScheduled, isStream: activeCall.isStream)) + } else { + var canManageGroupCalls = false + if let channel = self.presentationInterfaceState.renderedPeer?.chatMainPeer as? TelegramChannel { + if channel.flags.contains(.isCreator) || channel.hasPermission(.manageCalls) { + canManageGroupCalls = true + } + } else if let group = self.presentationInterfaceState.renderedPeer?.chatMainPeer as? TelegramGroup { + if case .creator = group.role { + canManageGroupCalls = true + } else if case let .admin(rights, _) = group.role { + if rights.rights.contains(.canManageCalls) { + canManageGroupCalls = true + } + } + } + + if canManageGroupCalls { + let text: String + if let channel = self.presentationInterfaceState.renderedPeer?.chatMainPeer as? TelegramChannel, case .broadcast = channel.info { + text = self.presentationData.strings.LiveStream_CreateNewVoiceChatText + } else { + text = self.presentationData.strings.VoiceChat_CreateNewVoiceChatText + } + self.present(textAlertController(context: self.context, updatedPresentationData: self.updatedPresentationData, title: nil, text: text, actions: [TextAlertAction(type: .defaultAction, title: self.presentationData.strings.VoiceChat_CreateNewVoiceChatStartNow, action: { [weak self] in + if let self { + var dismissStatus: (() -> Void)? + let statusController = OverlayStatusController(theme: self.presentationData.theme, type: .loading(cancelled: { + dismissStatus?() + })) + dismissStatus = { [weak self, weak statusController] in + self?.createVoiceChatDisposable.set(nil) + statusController?.dismiss() + } + self.present(statusController, in: .window(.root)) + self.createVoiceChatDisposable.set((self.context.engine.calls.createGroupCall(peerId: message.id.peerId, title: nil, scheduleDate: nil, isExternalStream: false) + |> deliverOnMainQueue).startStrict(next: { [weak self] info in + guard let self else { + return + } + self.joinGroupCall(peerId: message.id.peerId, invite: nil, activeCall: EngineGroupCallDescription(id: info.id, accessHash: info.accessHash, title: info.title, scheduleTimestamp: info.scheduleTimestamp, subscribedToScheduled: info.subscribedToScheduled, isStream: info.isStream)) + }, error: { [weak self] error in + dismissStatus?() + + guard let self else { + return + } + + let text: String + switch error { + case .generic, .scheduledTooLate: + text = self.presentationData.strings.Login_UnknownError + case .anonymousNotAllowed: + if let channel = message.peers[message.id.peerId] as? TelegramChannel, case .broadcast = channel.info { + text = self.presentationData.strings.LiveStream_AnonymousDisabledAlertText + } else { + text = self.presentationData.strings.VoiceChat_AnonymousDisabledAlertText + } + } + self.present(textAlertController(context: self.context, updatedPresentationData: self.updatedPresentationData, title: nil, text: text, actions: [TextAlertAction(type: .defaultAction, title: self.presentationData.strings.Common_OK, action: {})]), in: .window(.root)) + }, completed: { + dismissStatus?() + })) + } + }), TextAlertAction(type: .genericAction, title: self.presentationData.strings.VoiceChat_CreateNewVoiceChatSchedule, action: { [weak self] in + if let self { + self.context.scheduleGroupCall(peerId: message.id.peerId, parentController: self) + } + }), TextAlertAction(type: .genericAction, title: self.presentationData.strings.Common_Cancel, action: {})], actionLayout: .vertical), in: .window(.root)) + } + } + return true + case .messageAutoremoveTimeoutUpdated: + var canSetupAutoremoveTimeout = false + + if let _ = self.presentationInterfaceState.renderedPeer?.peer as? TelegramSecretChat { + canSetupAutoremoveTimeout = false + } else if let group = self.presentationInterfaceState.renderedPeer?.peer as? TelegramGroup { + if !group.hasBannedPermission(.banChangeInfo) { + canSetupAutoremoveTimeout = true + } + } else if let user = self.presentationInterfaceState.renderedPeer?.peer as? TelegramUser { + if user.id != self.context.account.peerId && user.botInfo == nil { + canSetupAutoremoveTimeout = true + } + } else if let channel = self.presentationInterfaceState.renderedPeer?.peer as? TelegramChannel { + if channel.hasPermission(.changeInfo) { + canSetupAutoremoveTimeout = true + } + } + + if canSetupAutoremoveTimeout { + self.presentAutoremoveSetup() + } + case let .paymentSent(currency, _, _, _, _): + if currency == "XTR" { + let _ = (context.engine.payments.requestBotPaymentReceipt(messageId: message.id) + |> deliverOnMainQueue).start(next: { [weak self] receipt in + guard let self else { + return + } + self.push(self.context.sharedContext.makeStarsReceiptScreen(context: self.context, receipt: receipt)) + }) + } else { + self.present(BotReceiptController(context: self.context, messageId: message.id), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + } + return true + case let .setChatTheme(chatTheme): + switch chatTheme { + case .emoticon: + self.presentThemeSelection() + case let .gift(gift, _): + if case let .unique(uniqueGift) = gift { + let controller = self.context.sharedContext.makeGiftViewScreen(context: self.context, gift: uniqueGift, shareStory: { [weak self] uniqueGift in + Queue.mainQueue().after(0.15) { + if let self { + let controller = self.context.sharedContext.makeStorySharingScreen(context: self.context, subject: .gift(uniqueGift), parentController: self) + self.push(controller) + } + } + }, openChatTheme: { [weak self] in + if let self { + Queue.mainQueue().after(0.15) { + self.presentThemeSelection() + } + } + }, dismissed: nil) + self.push(controller) + } + } + return true + case let .setChatWallpaper(wallpaper, _): + guard let peer = self.presentationInterfaceState.renderedPeer?.peer else { + return true + } + if let peer = peer as? TelegramChannel { + if peer.flags.contains(.isCreator) || peer.adminRights?.rights.contains(.canChangeInfo) == true { + let _ = (context.engine.peers.getChannelBoostStatus(peerId: peer.id) + |> deliverOnMainQueue).start(next: { [weak self] boostStatus in + guard let self else { + return + } + self.push(ChannelAppearanceScreen(context: self.context, updatedPresentationData: self.updatedPresentationData, peerId: peer.id, boostStatus: boostStatus)) + }) + } + return true + } + guard message.effectivelyIncoming(self.context.account.peerId), let peer = self.presentationInterfaceState.renderedPeer?.peer else { + self.presentThemeSelection() + return true + } + self.chatDisplayNode.dismissInput() + var options = WallpaperPresentationOptions() + var intensity: Int32? + if let settings = wallpaper.settings { + if settings.blur { + options.insert(.blur) + } + if settings.motion { + options.insert(.motion) + } + if case let .file(file) = wallpaper, !file.isPattern { + intensity = settings.intensity + } + } + let wallpaperPreviewController = WallpaperGalleryController(context: self.context, source: .wallpaper(wallpaper, options, [], intensity, nil, nil), mode: .peer(EnginePeer(peer), true)) + wallpaperPreviewController.apply = { [weak wallpaperPreviewController] entry, options, _, _, brightness, forBoth in + var settings: WallpaperSettings? + if case let .wallpaper(wallpaper, _) = entry { + let baseSettings = wallpaper.settings + var intensity: Int32? = baseSettings?.intensity + if case let .file(file) = wallpaper, !file.isPattern { + if let brightness { + intensity = max(0, min(100, Int32(brightness * 100.0))) + } + } + settings = WallpaperSettings(blur: options.contains(.blur), motion: options.contains(.motion), colors: baseSettings?.colors ?? [], intensity: intensity, rotation: baseSettings?.rotation) + } + let _ = (self.context.engine.themes.setExistingChatWallpaper(messageId: message.id, settings: settings, forBoth: forBoth) + |> deliverOnMainQueue).startStandalone() + Queue.mainQueue().after(0.1) { + wallpaperPreviewController?.dismiss() + } + } + self.push(wallpaperPreviewController) + return true + case let .giftPremium(_, _, duration, _, _, _, _): + self.chatDisplayNode.dismissInput() + let fromPeerId: PeerId = message.author?.id == self.context.account.peerId ? self.context.account.peerId : message.id.peerId + let toPeerId: PeerId = message.author?.id == self.context.account.peerId ? message.id.peerId : self.context.account.peerId + let controller = PremiumIntroScreen(context: self.context, source: .gift(from: fromPeerId, to: toPeerId, duration: duration, giftCode: nil)) + self.push(controller) + return true + case .starGift, .starGiftUnique: + if case let .starGiftUnique(gift, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _) = action.action, case let .unique(uniqueGift) = gift, uniqueGift.flags.contains(.isBurned) { + self.present(textAlertController(context: context, updatedPresentationData: updatedPresentationData, title: nil, text: "This gift was already burned.", actions: [TextAlertAction(type: .defaultAction, title: self.presentationData.strings.Common_OK, action: {})]), in: .window(.root)) + } else { + let controller = self.context.sharedContext.makeGiftViewScreen(context: self.context, message: EngineMessage(message), shareStory: { [weak self] uniqueGift in + Queue.mainQueue().after(0.15) { + if let self { + let controller = self.context.sharedContext.makeStorySharingScreen(context: self.context, subject: .gift(uniqueGift), parentController: self) + self.push(controller) + } + } + }) + self.push(controller) + } + return true + case .giftStars: + let controller = self.context.sharedContext.makeStarsGiftScreen(context: self.context, message: EngineMessage(message)) + self.push(controller) + return true + case let .giftTon(_, _, _, _, transactionId): + Task { @MainActor [weak self] in + guard let self, let transactionId, let peerId = self.chatLocation.peerId else { + return + } + let transactionData = await self.context.engine.payments.getStarsTransaction(reference: StarsTransactionReference(peerId: self.context.account.peerId, ton: true, id: transactionId, isRefund: false)).get() + let peer = await self.context.engine.data.get( + TelegramEngine.EngineData.Item.Peer.Peer(id: peerId) + ).get() + if let transactionData, let peer { + self.push(self.context.sharedContext.makeStarsTransactionScreen(context: self.context, transaction: transactionData, peer: peer)) + } + } + case let .giftCode(slug, _, _, _, _, _, _, _, _, _, _): + self.openResolved(result: .premiumGiftCode(slug: slug), sourceMessageId: message.id, progress: params.progress) + return true + case .prizeStars: + let controller = self.context.sharedContext.makeStarsGiftScreen(context: self.context, message: EngineMessage(message)) + self.push(controller) + return true + case let .suggestedBirthday(birthday): + self.chatDisplayNode.dismissInput() + guard message.author?.id != self.context.account.peerId else { + return true + } + let settingsPromise: Promise + if let rootController = self.context.sharedContext.mainWindow?.viewController as? TelegramRootControllerInterface, let current = rootController.getPrivacySettings() { + settingsPromise = current + } else { + settingsPromise = Promise() + settingsPromise.set(.single(nil) |> then(self.context.engine.privacy.requestAccountPrivacySettings() |> map(Optional.init))) + } + + let controller = self.context.sharedContext.makeBirthdayAcceptSuggestionScreen(context: self.context, birthday: birthday, settings: settingsPromise, openSettings: { [weak self] in + guard let self else { + return + } + self.context.sharedContext.makeBirthdayPrivacyController(context: self.context, settings: settingsPromise, openedFromBirthdayScreen: true, present: { [weak self] c in + self?.push(c) + }) + }, completion: { [weak self] value in + guard let self else { + return + } + let _ = self.context.engine.accountData.updateBirthday(birthday: value).startStandalone() + + self.present(UndoOverlayController(presentationData: self.presentationData, content: .universal(animation: "anim_gift", scale: 0.058, colors: ["__allcolors__": UIColor.white], title: nil, text: self.presentationData.strings.SuggestBirthdate_Accept_Added, customUndoText: nil, timeout: 5.0), elevatedLayout: false, action: { _ in + return true + }), in: .current) + }) + self.push(controller) + return true + case let .suggestedProfilePhoto(image): + self.chatDisplayNode.dismissInput() + if let image = image { + if message.effectivelyIncoming(self.context.account.peerId) { + if let emojiMarkup = image.emojiMarkup { + let controller = AvatarEditorScreen(context: self.context, inputData: AvatarEditorScreen.inputData(context: self.context, isGroup: false), peerType: .user, markup: emojiMarkup) + controller.imageCompletion = { [weak self] image, commit in + if let self { + if let rootController = self.effectiveNavigationController as? TelegramRootController, let settingsController = rootController.accountSettingsController as? PeerInfoScreenImpl { + settingsController.updateProfilePhoto(image, mode: .accept, uploadStatus: nil) + commit() + } + } + } + controller.videoCompletion = { [weak self] image, url, values, markup, commit in + if let self { + if let rootController = self.effectiveNavigationController as? TelegramRootController, let settingsController = rootController.accountSettingsController as? PeerInfoScreenImpl { + settingsController.updateProfileVideo(image, video: nil, values: nil, markup: markup, mode: .accept, uploadStatus: nil) + commit() + } + } + } + self.push(controller) + } else { + var selectedNode: (ASDisplayNode, CGRect, () -> (UIView?, UIView?))? + self.chatDisplayNode.historyNode.forEachItemNode { itemNode in + if let itemNode = itemNode as? ChatMessageItemView { + if let result = itemNode.transitionNode(id: message.id, media: image, adjustRect: false) { + selectedNode = result + } + } + } + let transitionView = selectedNode?.0.view + + let senderName: String? + if let peer = message.peers[message.id.peerId] { + senderName = EnginePeer(peer).compactDisplayTitle + } else { + senderName = nil + } + + legacyAvatarEditor(context: self.context, media: .message(message: MessageReference(message), media: image), transitionView: transitionView, senderName: senderName, present: { [weak self] c, a in + self?.present(c, in: .window(.root), with: a) + }, imageCompletion: { [weak self] image in + if let self { + if let rootController = self.effectiveNavigationController as? TelegramRootController, let settingsController = rootController.accountSettingsController as? PeerInfoScreenImpl { + settingsController.updateProfilePhoto(image, mode: .accept, uploadStatus: nil) + } + } + }, videoCompletion: { [weak self] image, url, adjustments in + if let self { + if let rootController = self.effectiveNavigationController as? TelegramRootController, let settingsController = rootController.accountSettingsController as? PeerInfoScreenImpl { + settingsController.oldUpdateProfileVideo(image, asset: AVURLAsset(url: url), adjustments: adjustments, mode: .accept) + } + } + }) + } + } else { + openMessageByAction = true + } + } + case .boostsApplied: + self.controllerInteraction?.openGroupBoostInfo(nil, 0) + return true + case .paidMessagesPriceEdited: + self.interfaceInteraction?.openMonoforum() + return true + case .starGiftPurchaseOffer: + let controller = self.context.sharedContext.makeGiftViewScreen(context: self.context, message: EngineMessage(message), shareStory: { [weak self] uniqueGift in + Queue.mainQueue().after(0.15) { + if let self { + let controller = self.context.sharedContext.makeStorySharingScreen(context: self.context, subject: .gift(uniqueGift), parentController: self) + self.push(controller) + } + } + }) + self.push(controller) + return true + default: + break + } + if !openMessageByAction { + return true + } + } + } + + let openChatLocation = self.chatLocation + var chatFilterTag: MemoryBuffer? + if case let .customTag(value, _) = self.chatDisplayNode.historyNode.tag { + chatFilterTag = value + } + + var standalone = false + if case .customChatContents = self.chatLocation { + standalone = true + } + + if let adAttribute = message.attributes.first(where: { $0 is AdMessageAttribute }) as? AdMessageAttribute { + if let file = message.media.first(where: { $0 is TelegramMediaFile}) as? TelegramMediaFile, file.isVideo && !file.isAnimated { + self.chatDisplayNode.adMessagesContext?.markAction(opaqueId: adAttribute.opaqueId, media: true, fullscreen: false) + } else { + self.controllerInteraction?.activateAdAction(message.id, nil, true, false) + return true + } + } + + let openChatMessageParams = OpenChatMessageParams( + context: context, + updatedPresentationData: self.updatedPresentationData, + chatLocation: openChatLocation, + chatFilterTag: chatFilterTag, + chatLocationContextHolder: self.chatLocationContextHolder, + message: message, + mediaIndex: params.mediaIndex, + standalone: standalone, + reverseMessageGalleryOrder: false, + mode: mode, + navigationController: self.effectiveNavigationController, dismissInput: { [weak self] in + self?.chatDisplayNode.dismissInput() + }, + present: { [weak self] c, a, i in + guard let self else { + return + } + + if case .current = i { + c.presentationArguments = a + c.statusBar.alphaUpdated = { [weak self] transition in + guard let self else { + return + } + self.updateStatusBarPresentation(animated: transition.isAnimated) + } + self.galleryPresentationContext.present(c, on: PresentationSurfaceLevel(rawValue: 0), blockInteraction: true, completion: {}) + } else { + self.present(c, in: .window(.root), with: a, blockInteraction: true) + } + }, + transitionNode: { [weak self] messageId, media, adjustRect in + var selectedNode: (ASDisplayNode, CGRect, () -> (UIView?, UIView?))? + if let self { + self.chatDisplayNode.historyNode.forEachItemNode { itemNode in + if let itemNode = itemNode as? ChatMessageItemView { + if let result = itemNode.transitionNode(id: messageId, media: media, adjustRect: adjustRect) { + selectedNode = result + } + } + } + } + return selectedNode + }, + addToTransitionSurface: { [weak self] view in + guard let self else { + return + } + if let contextController = self.currentContextController { + contextController.view.addSubview(view) + } else { + self.chatDisplayNode.historyNode.view.superview?.insertSubview(view, aboveSubview: self.chatDisplayNode.historyNode.view) + } + }, + openUrl: { [weak self] url in + self?.openUrl(url, concealed: false, skipConcealedAlert: isLocation, message: nil) + }, + openPeer: { [weak self] peer, navigation in + self?.openPeer(peer: EnginePeer(peer), navigation: navigation, fromMessage: nil) + }, + callPeer: { [weak self] peerId, isVideo in + self?.controllerInteraction?.callPeer(peerId, isVideo) + }, + openConferenceCall: { [weak self] message in + self?.controllerInteraction?.openConferenceCall(message) + }, + enqueueMessage: { [weak self] message in + self?.sendMessages([message]) + }, + sendSticker: canSendMessagesToChat(self.presentationInterfaceState) ? { [weak self] fileReference, sourceNode, sourceRect in + return self?.controllerInteraction?.sendSticker(fileReference, false, false, nil, false, sourceNode, sourceRect, nil, []) ?? false + } : nil, + sendEmoji: canSendMessagesToChat(self.presentationInterfaceState) ? { [weak self] text, attribute in + self?.controllerInteraction?.sendEmoji(text, attribute, false) + } : nil, + setupTemporaryHiddenMedia: { [weak self] signal, centralIndex, galleryMedia in + if let self { + self.temporaryHiddenGalleryMediaDisposable.set((signal |> deliverOnMainQueue).startStrict(next: { [weak self] entry in + if let self, let controllerInteraction = self.controllerInteraction { + var messageIdAndMedia: [MessageId: [Media]] = [:] + + if let entry = entry as? InstantPageGalleryEntry, entry.index == centralIndex { + messageIdAndMedia[message.id] = [galleryMedia] + } + + controllerInteraction.hiddenMedia = messageIdAndMedia + + self.chatDisplayNode.historyNode.forEachItemNode { itemNode in + if let itemNode = itemNode as? ChatMessageItemView { + itemNode.updateHiddenMedia() + } + } + } + })) + } + }, + chatAvatarHiddenMedia: { [weak self] signal, media in + if let self { + self.temporaryHiddenGalleryMediaDisposable.set((signal |> deliverOnMainQueue).startStrict(next: { [weak self] messageId in + if let self, let controllerInteraction = self.controllerInteraction { + var messageIdAndMedia: [MessageId: [Media]] = [:] + + if let messageId = messageId { + messageIdAndMedia[messageId] = [media] + } + + controllerInteraction.hiddenMedia = messageIdAndMedia + + self.chatDisplayNode.historyNode.forEachItemNode { itemNode in + if let itemNode = itemNode as? ChatMessageItemView { + itemNode.updateHiddenMedia() + } + } + } + })) + } + }, + actionInteraction: GalleryControllerActionInteraction( + openUrl: { [weak self] url, concealed, forceExternal in + if let self { + self.openUrl(url, concealed: concealed, forceExternal: forceExternal, message: nil) + } + }, + openUrlIn: { [weak self] url in + if let self { + self.openUrlIn(url) + } + }, + openPeerMention: { [weak self] mention in + if let self { + self.controllerInteraction?.openPeerMention(mention, nil) + } + }, + openPeer: { [weak self] peer in + if let self { + self.controllerInteraction?.openPeer(peer, .default, nil, .default) + } + }, + openHashtag: { [weak self] peerName, hashtag in + if let self { + self.controllerInteraction?.openHashtag(peerName, hashtag) + } + }, + openBotCommand: { [weak self] command in + if let self { + self.controllerInteraction?.sendBotCommand(nil, command) + } + }, + openAd: { [weak self] messageId in + if let self { + self.controllerInteraction?.activateAdAction(messageId, nil, true, true) + } + }, + addContact: { [weak self] phoneNumber in + if let self { + self.controllerInteraction?.addContact(phoneNumber) + } + }, + storeMediaPlaybackState: { [weak self] messageId, timestamp, playbackRate in + guard let self else { + return + } + var storedState: MediaPlaybackStoredState? + if let timestamp = timestamp { + storedState = MediaPlaybackStoredState(timestamp: timestamp, playbackRate: AudioPlaybackRate(playbackRate)) + } + let _ = updateMediaPlaybackStoredStateInteractively(engine: self.context.engine, messageId: messageId, state: storedState).startStandalone() + }, + editMedia: { [weak self] messageId, snapshots, transitionCompletion in + guard let self else { + return + } + + let _ = (self.context.engine.data.get(TelegramEngine.EngineData.Item.Messages.Message(id: messageId)) + |> deliverOnMainQueue).startStandalone(next: { [weak self] message in + guard let self, let message = message else { + return + } + + var mediaReference: AnyMediaReference? + for media in message.media { + if let image = media as? TelegramMediaImage { + mediaReference = AnyMediaReference.standalone(media: image) + } else if let file = media as? TelegramMediaFile { + mediaReference = AnyMediaReference.standalone(media: file) + } else if let webpage = media as? TelegramMediaWebpage, case let .Loaded(content) = webpage.content { + if let image = content.image { + mediaReference = AnyMediaReference.standalone(media: image) + } else if let file = content.file { + mediaReference = AnyMediaReference.standalone(media: file) + } + } + } + + if let mediaReference = mediaReference, let peer = message.peers[message.id.peerId] { + legacyMediaEditor(context: self.context, peer: peer, threadTitle: self.contentData?.state.threadInfo?.title, media: mediaReference, mode: .draw, initialCaption: NSAttributedString(), snapshots: snapshots, transitionCompletion: { + transitionCompletion() + }, getCaptionPanelView: { [weak self] in + return self?.getCaptionPanelView(isFile: false) + }, sendMessagesWithSignals: { [weak self] signals, _, _, isCaptionAbove in + if let self { + var parameters: ChatSendMessageActionSheetController.SendParameters? + if isCaptionAbove { + parameters = ChatSendMessageActionSheetController.SendParameters(effect: nil, textIsAboveMedia: true) + } + self.enqueueMediaMessages(signals: signals, silentPosting: false, parameters: parameters) + } + }, present: { [weak self] c, a in + self?.present(c, in: .window(.root), with: a) + }) + } + }) + }, + updateCanReadHistory: { [weak self] canReadHistory in + self?.canReadHistory.set(canReadHistory) + } + ), + getSourceRect: { [weak self] in + guard let self else { + return nil + } + var rect: CGRect? + self.chatDisplayNode.historyNode.forEachVisibleMessageItemNode({ itemNode in + if itemNode.item?.message.id == message.id { + rect = itemNode.view.convert(itemNode.contentFrame(), to: nil) + } + }) + return rect + } + ) + + self.controllerInteraction?.isOpeningMediaSignal = openChatMessageParams.blockInteraction.get() + + return context.sharedContext.openChatMessage(openChatMessageParams) + } public var contentContainerNode: ASDisplayNode { return self.chatDisplayNode.contentContainerNode } diff --git a/submodules/TelegramUI/Sources/ChatControllerContentData.swift b/submodules/TelegramUI/Sources/ChatControllerContentData.swift index 9d815c5b..c1c0ac49 100644 --- a/submodules/TelegramUI/Sources/ChatControllerContentData.swift +++ b/submodules/TelegramUI/Sources/ChatControllerContentData.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import TelegramPresentationData import AccountContext @@ -136,6 +137,10 @@ extension ChatControllerImpl { var voiceMessagesAvailable: Bool = true var requestsState: PeerInvitationImportersState? var dismissedInvitationRequests: [Int64]? + + // MARK: Swiftgram + var predictedChatLanguage: String? + var customEmojiAvailable: Bool = false var threadData: ChatPresentationInterfaceState.ThreadData? var forumTopicData: ChatPresentationInterfaceState.ThreadData? @@ -163,6 +168,9 @@ extension ChatControllerImpl { private var premiumGiftSuggestionDisposable: Disposable? private var translationStateDisposable: Disposable? + // MARK: Swiftgram + private var chatLanguagePredictionDisposable: Disposable? + private let isPeerInfoReady = ValuePromise(false, ignoreRepeated: true) private let isChatLocationInfoReady = ValuePromise(false, ignoreRepeated: true) private let isCachedDataReady = ValuePromise(false, ignoreRepeated: true) @@ -893,8 +901,7 @@ extension ChatControllerImpl { peerVerification = cachedChannelData.verification } } - // GHOSTGRAM: Bypass copy protection if enabled in Misc settings - copyProtectionEnabled = MiscSettingsManager.shared.shouldBypassCopyProtection ? false : peer.isCopyProtectionEnabled + copyProtectionEnabled = peer.isCopyProtectionEnabled if let cachedGroupData = peerView.cachedData as? CachedGroupData { if !cachedGroupData.botInfos.isEmpty { hasBots = true @@ -983,7 +990,9 @@ extension ChatControllerImpl { } var adMessage = adMessage - if let peer = peerView.peers[peerView.peerId] as? TelegramUser, peer.botInfo != nil { + if MiscSettingsManager.shared.shouldBlockAds { + adMessage = nil + } else if let peer = peerView.peers[peerView.peerId] as? TelegramUser, peer.botInfo != nil { } else { adMessage = nil } @@ -1028,7 +1037,7 @@ extension ChatControllerImpl { } else { isRegularChat = true } - if strongSelf.nextChannelToReadDisposable == nil, let peerId = chatLocation.peerId, let customChatNavigationStack { + if strongSelf.nextChannelToReadDisposable == nil, let peerId = chatLocation.peerId, let customChatNavigationStack, !SGSimpleSettings.shared.disableScrollToNextChannel { if let index = customChatNavigationStack.firstIndex(of: peerId), index != customChatNavigationStack.count - 1 { let nextPeerId = customChatNavigationStack[index + 1] strongSelf.nextChannelToReadDisposable = (combineLatest(queue: .mainQueue(), @@ -1072,7 +1081,7 @@ extension ChatControllerImpl { } }) } - } else if isRegularChat, strongSelf.nextChannelToReadDisposable == nil { + } else if isRegularChat, strongSelf.nextChannelToReadDisposable == nil, !SGSimpleSettings.shared.disableScrollToNextChannel { //TODO:loc optimize let accountPeerId = context.account.peerId strongSelf.nextChannelToReadDisposable = (combineLatest(queue: .mainQueue(), @@ -1372,8 +1381,7 @@ extension ChatControllerImpl { var alwaysShowGiftButton = false var disallowedGifts: TelegramDisallowedGifts? if let peer = peerView.peers[peerView.peerId] { - // GHOSTGRAM: Bypass copy protection if enabled in Misc settings - copyProtectionEnabled = MiscSettingsManager.shared.shouldBypassCopyProtection ? false : peer.isCopyProtectionEnabled + copyProtectionEnabled = peer.isCopyProtectionEnabled if let cachedData = peerView.cachedData as? CachedUserData { contactStatus = ChatContactStatus(canAddContact: !peerView.peerIsContact, peerStatusSettings: cachedData.peerStatusSettings, invitedBy: nil, managingBot: managingBot) if case let .known(value) = cachedData.businessIntro { @@ -1701,7 +1709,7 @@ extension ChatControllerImpl { strongSelf.state.alwaysShowGiftButton = alwaysShowGiftButton strongSelf.state.disallowedGifts = disallowedGifts - if let replyThreadId, let channel = renderedPeer?.peer as? TelegramChannel, channel.isForumOrMonoForum, strongSelf.nextChannelToReadDisposable == nil { + if let replyThreadId, let channel = renderedPeer?.peer as? TelegramChannel, channel.isForumOrMonoForum, strongSelf.nextChannelToReadDisposable == nil, !SGSimpleSettings.shared.disableScrollToNextTopic { strongSelf.nextChannelToReadDisposable = (combineLatest(queue: .mainQueue(), context.engine.peers.getNextUnreadForumTopic(peerId: channel.id, topicId: Int32(clamping: replyThreadId)), ApplicationSpecificNotice.getNextChatSuggestionTip(accountManager: context.sharedContext.accountManager) @@ -2112,7 +2120,8 @@ extension ChatControllerImpl { if counterAndTimestamp.0 >= 3 { maybeSuggestPremium = true } - if (isPremium || maybeSuggestPremium || hasAutoTranslate) && !isHidden { + let sgTranslationAvailable = SGSimpleSettings.shared.translationBackendEnum != .default + if (isPremium || maybeSuggestPremium || hasAutoTranslate || sgTranslationAvailable) && !isHidden { return chatTranslationState(context: context, peerId: peerId, threadId: chatLocation.threadId) |> map { translationState -> ChatPresentationTranslationState? in if let translationState, !translationState.fromLang.isEmpty && (translationState.fromLang != baseLanguageCode || translationState.isEnabled) { @@ -2137,6 +2146,27 @@ extension ChatControllerImpl { strongSelf.onUpdated?(previousState) }) + + // MARK: Swiftgram + self.chatLanguagePredictionDisposable = ( + chatTranslationState(context: context, peerId: peerId, threadId: chatLocation.threadId) + |> map { translationState -> ChatPresentationTranslationState? in + if let translationState, !translationState.fromLang.isEmpty { + return ChatPresentationTranslationState(isEnabled: translationState.isEnabled, fromLang: translationState.fromLang, toLang: translationState.toLang ?? baseLanguageCode) + } else { + return nil + } + } + |> distinctUntilChanged + |> deliverOnMainQueue).startStrict(next: { [weak self] translationState in + if let strongSelf = self, let translationState = translationState, strongSelf.state.predictedChatLanguage == nil { + let previousState = strongSelf.state + + strongSelf.state.predictedChatLanguage = translationState.fromLang + + strongSelf.onUpdated?(previousState) + } + }) } let premiumGiftOptions: Signal<[CachedPremiumGiftOption], NoError> = .single([]) @@ -2400,6 +2430,8 @@ extension ChatControllerImpl { self.cachedDataDisposable?.dispose() self.premiumGiftSuggestionDisposable?.dispose() self.translationStateDisposable?.dispose() + // MARK: Swiftgram + self.chatLanguagePredictionDisposable?.dispose() self.inviteRequestsDisposable?.dispose() } } diff --git a/submodules/TelegramUI/Sources/ChatControllerForwardMessages.swift b/submodules/TelegramUI/Sources/ChatControllerForwardMessages.swift index 6913d4cb..bf1b7e96 100644 --- a/submodules/TelegramUI/Sources/ChatControllerForwardMessages.swift +++ b/submodules/TelegramUI/Sources/ChatControllerForwardMessages.swift @@ -15,7 +15,165 @@ import ReactionSelectionNode import TopMessageReactions import ChatMessagePaymentAlertController +enum ForwardEnqueueMessagesResult { + case messages([EnqueueMessage]) + case unsupported +} + extension ChatControllerImpl { + private func forwardOptionsAttributes(_ options: ChatInterfaceForwardOptionsState?) -> [MessageAttribute] { + return [ + ForwardOptionsMessageAttribute( + hideNames: options?.hideNames == true, + hideCaptions: options?.hideCaptions == true + ) + ] + } + + private func shouldUsePlainCopyForward(for message: Message) -> Bool { + return MiscSettingsManager.shared.shouldBypassCopyProtection && message.isCopyProtectedIgnoringBypass() + } + + private func forwardMessagesNeedPlainCopy(_ messages: [Message]) -> Bool { + return messages.contains(where: self.shouldUsePlainCopyForward(for:)) + } + + private func plainCopyForwardMediaReference(for message: Message) -> AnyMediaReference? { + var supportedMedia: Media? + + for media in message.media { + switch media { + case is TelegramMediaAction, is TelegramMediaPoll, is TelegramMediaTodo, is TelegramMediaDice, is TelegramMediaPaidContent, is TelegramMediaExpiredContent, is TelegramMediaStory, is TelegramMediaInvoice: + return nil + case is TelegramMediaWebpage: + continue + case is TelegramMediaImage, is TelegramMediaFile: + if supportedMedia != nil { + return nil + } + supportedMedia = media + case is TelegramMediaMap, is TelegramMediaContact: + if supportedMedia != nil { + return nil + } + supportedMedia = media + default: + return nil + } + } + + guard let supportedMedia else { + return nil + } + if supportedMedia is TelegramMediaImage || supportedMedia is TelegramMediaFile { + return .message(message: MessageReference(message), media: supportedMedia) + } else { + return .standalone(media: supportedMedia) + } + } + + private func plainCopyForwardMessage( + _ message: Message, + options: ChatInterfaceForwardOptionsState?, + threadId: Int64?, + localGroupingKey: Int64? + ) -> EnqueueMessage? { + if message.id.peerId.namespace == Namespaces.Peer.SecretChat || message.containsSecretMedia || message.minAutoremoveOrClearTimeout == viewOnceTimeout { + return nil + } + + let mediaReference = self.plainCopyForwardMediaReference(for: message) + if !message.media.isEmpty && mediaReference == nil { + return nil + } + + var text = message.text + var entities = message.textEntitiesAttribute?.entities ?? [] + if options?.hideCaptions == true, mediaReference != nil { + text = "" + entities = [] + } + + if mediaReference == nil && text.isEmpty { + return nil + } + + var attributes: [MessageAttribute] = [] + if !entities.isEmpty { + attributes.append(TextEntitiesMessageAttribute(entities: entities)) + } + for attribute in message.attributes { + if attribute is MediaSpoilerMessageAttribute || attribute is InvertMediaMessageAttribute { + attributes.append(attribute) + } + } + + return .message( + text: text, + attributes: attributes, + inlineStickers: [:], + mediaReference: mediaReference, + threadId: threadId, + replyToMessageId: nil, + replyToStoryId: nil, + localGroupingKey: localGroupingKey, + correlationId: nil, + bubbleUpEmojiOrStickersets: [] + ) + } + + func buildForwardEnqueueMessages( + from messages: [Message], + options: ChatInterfaceForwardOptionsState?, + threadId: Int64? + ) -> ForwardEnqueueMessagesResult { + let forwardAttributes = self.forwardOptionsAttributes(options) + var groupingKeyMap: [Int64: Int64] = [:] + var result: [EnqueueMessage] = [] + + for message in messages { + if self.shouldUsePlainCopyForward(for: message) { + let localGroupingKey: Int64? + if let groupingKey = message.groupingKey { + if let existingKey = groupingKeyMap[groupingKey] { + localGroupingKey = existingKey + } else { + let newKey = Int64.random(in: Int64.min ... Int64.max) + groupingKeyMap[groupingKey] = newKey + localGroupingKey = newKey + } + } else { + localGroupingKey = nil + } + + guard let plainCopyMessage = self.plainCopyForwardMessage(message, options: options, threadId: threadId, localGroupingKey: localGroupingKey) else { + return .unsupported + } + result.append(plainCopyMessage) + } else { + result.append(.forward(source: message.id, threadId: threadId, grouping: .auto, attributes: forwardAttributes, correlationId: nil)) + } + } + + return .messages(result) + } + + func presentUnsupportedProtectedForwardAlert(in controller: ViewController?) { + let presentationData = self.context.sharedContext.currentPresentationData.with { $0 } + let text = "This protected message type can't be copied yet." + let alert = textAlertController( + context: self.context, + title: nil, + text: text, + actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})] + ) + if let controller { + controller.present(alert, in: .window(.root)) + } else { + self.present(alert, in: .window(.root)) + } + } + func forwardMessages(messageIds: [MessageId], options: ChatInterfaceForwardOptionsState? = nil, resetCurrent: Bool = false) { let _ = (self.context.engine.data.get(EngineDataMap( messageIds.map(TelegramEngine.EngineData.Item.Messages.Message.init) @@ -53,7 +211,7 @@ extension ChatControllerImpl { var attemptSelectionImpl: ((EnginePeer, ChatListDisabledPeerReason) -> Void)? let controller = self.context.sharedContext.makePeerSelectionController(PeerSelectionControllerParams(context: self.context, updatedPresentationData: self.updatedPresentationData, filter: filter, hasFilters: true, attemptSelection: { peer, _, reason in attemptSelectionImpl?(peer, reason) - }, multipleSelection: true, forwardedMessageIds: messages.map { $0.id }, selectForumThreads: true)) + }, multipleSelection: true, forwardedMessageIds: messages.map { $0.id }, initialForwardOptionsState: options, selectForumThreads: true)) let context = self.context attemptSelectionImpl = { [weak self, weak controller] peer, reason in guard let strongSelf = self, let controller = controller else { @@ -153,12 +311,13 @@ extension ChatControllerImpl { } } - var attributes: [MessageAttribute] = [] - attributes.append(ForwardOptionsMessageAttribute(hideNames: forwardOptions?.hideNames == true, hideCaptions: forwardOptions?.hideCaptions == true)) - - result.append(contentsOf: messages.map { message -> EnqueueMessage in - return .forward(source: message.id, threadId: nil, grouping: .auto, attributes: attributes, correlationId: nil) - }) + switch strongSelf.buildForwardEnqueueMessages(from: messages, options: forwardOptions, threadId: nil) { + case let .messages(forwardMessages): + result.append(contentsOf: forwardMessages) + case .unsupported: + strongSelf.presentUnsupportedProtectedForwardAlert(in: strongController) + return + } let commit: ([EnqueueMessage]) -> Void = { result in guard let strongSelf = self else { @@ -392,10 +551,17 @@ extension ChatControllerImpl { } var correlationIds: [Int64] = [] - let mappedMessages = messages.map { message -> EnqueueMessage in - let correlationId = Int64.random(in: Int64.min ... Int64.max) - correlationIds.append(correlationId) - return .forward(source: message.id, threadId: nil, grouping: .auto, attributes: [], correlationId: correlationId) + let mappedMessages: [EnqueueMessage] + switch strongSelf.buildForwardEnqueueMessages(from: messages, options: options, threadId: nil) { + case let .messages(builtMessages): + mappedMessages = builtMessages.map { message in + let correlationId = Int64.random(in: Int64.min ... Int64.max) + correlationIds.append(correlationId) + return message.withUpdatedCorrelationId(correlationId) + } + case .unsupported: + strongSelf.presentUnsupportedProtectedForwardAlert(in: strongController) + return } let _ = (reactionItems @@ -448,6 +614,33 @@ extension ChatControllerImpl { strongSelf.updateChatPresentationInterfaceState(animated: false, interactive: true, { $0.updatedInterfaceState({ $0.withoutSelectionState() }) }) strongController.dismiss() } else { + if strongSelf.forwardMessagesNeedPlainCopy(messages) { + let forwardOptions = options ?? ChatInterfaceForwardOptionsState(hideNames: !hasNotOwnMessages, hideCaptions: false, unhideNamesOnCaptionChange: false) + let mappedMessages: [EnqueueMessage] + switch strongSelf.buildForwardEnqueueMessages(from: messages, options: forwardOptions, threadId: threadId) { + case let .messages(builtMessages): + mappedMessages = builtMessages + case .unsupported: + strongSelf.presentUnsupportedProtectedForwardAlert(in: strongController) + return + } + + let _ = (enqueueMessages(account: strongSelf.context.account, peerId: peerId, messages: mappedMessages) + |> deliverOnMainQueue).startStandalone() + + let presentationData = strongSelf.context.sharedContext.currentPresentationData.with { $0 } + var peerName = peer.displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder) + peerName = peerName.replacingOccurrences(of: "**", with: "") + let text = messages.count == 1 ? presentationData.strings.Conversation_ForwardTooltip_Chat_One(peerName).string : presentationData.strings.Conversation_ForwardTooltip_Chat_Many(peerName).string + strongSelf.present(UndoOverlayController(presentationData: presentationData, content: .forward(savedMessages: false, text: text), elevatedLayout: false, position: .bottom, animateInAsReplacement: true, action: { _ in + return false + }), in: .current) + + strongSelf.updateChatPresentationInterfaceState(animated: false, interactive: true, { $0.updatedInterfaceState({ $0.withoutSelectionState() }) }) + strongController.dismiss() + return + } + if let navigationController = strongSelf.navigationController as? NavigationController { for controller in navigationController.viewControllers { if let maybeChat = controller as? ChatControllerImpl { diff --git a/submodules/TelegramUI/Sources/ChatControllerNode.swift b/submodules/TelegramUI/Sources/ChatControllerNode.swift index b50efb0b..afac8af1 100644 --- a/submodules/TelegramUI/Sources/ChatControllerNode.swift +++ b/submodules/TelegramUI/Sources/ChatControllerNode.swift @@ -1,4 +1,5 @@ import Foundation +import SGSimpleSettings import UIKit import AsyncDisplayKit import Postbox @@ -129,7 +130,6 @@ class HistoryNodeContainer: ASDisplayNode { var isSecret: Bool { didSet { if self.isSecret != oldValue { - // MISC: Bypass screenshot protection if enabled let shouldDisable = self.isSecret && !MiscSettingsManager.shared.shouldBypassScreenshotProtection setLayerDisableScreenshots(self.layer, shouldDisable) } @@ -146,7 +146,6 @@ class HistoryNodeContainer: ASDisplayNode { super.init() if self.isSecret { - // MISC: Bypass screenshot protection if enabled let shouldDisable = self.isSecret && !MiscSettingsManager.shared.shouldBypassScreenshotProtection setLayerDisableScreenshots(self.layer, shouldDisable) } @@ -1109,8 +1108,8 @@ class ChatControllerNode: ASDisplayNode, ASScrollViewDelegate { statusBar.updateStatusBarStyle(.White, animated: true) } else { let statusBarStyle: StatusBarStyle - if let isDark = self.backgroundNode.isDark { - if isDark { + if let contentStats = self.backgroundNode.contentStats { + if contentStats.isDark { statusBarStyle = .White } else { statusBarStyle = .Black @@ -1129,7 +1128,6 @@ class ChatControllerNode: ASDisplayNode, ASScrollViewDelegate { } } - // GHOSTGRAM: Bypass screenshot protection if enabled in Misc settings let effectiveCopyProtection = MiscSettingsManager.shared.shouldBypassScreenshotProtection ? false : self.chatPresentationInterfaceState.copyProtectionEnabled let isSecret = effectiveCopyProtection || self.chatLocation.peerId?.namespace == Namespaces.Peer.SecretChat || self.chatLocation.peerId?.isVerificationCodes == true if self.historyNodeContainer.isSecret != isSecret { @@ -1644,6 +1642,10 @@ class ChatControllerNode: ASDisplayNode, ASScrollViewDelegate { dismissedFloatingTopicsPanel = floatingTopicsPanel } + if floatingTopicsPanelInsets.top != 0.0 { + floatingTopicsPanelInsets.top += 8.0 + } + var isSidebarOpen = false if let floatingTopicsPanel = self.floatingTopicsPanel { isSidebarOpen = floatingTopicsPanel.component.location == .side @@ -1704,8 +1706,21 @@ class ChatControllerNode: ASDisplayNode, ASScrollViewDelegate { var dismissedAccessoryPanelNode: AccessoryPanelNode? var dismissedInputContextPanelNode: ChatInputContextPanelNode? var dismissedOverlayContextPanelNode: ChatInputContextPanelNode? - - let inputPanelNodes = inputPanelForChatPresentationIntefaceState(self.chatPresentationInterfaceState, context: self.context, currentPanel: self.inputPanelNode, currentSecondaryPanel: self.secondaryInputPanelNode, textInputPanelNode: self.textInputPanelNode, chatControllerInteraction: self.controllerInteraction, interfaceInteraction: self.interfaceInteraction) + // MARK: Swiftgram + var inputPanelNodes = inputPanelForChatPresentationIntefaceState(self.chatPresentationInterfaceState, context: self.context, currentPanel: self.inputPanelNode, currentSecondaryPanel: self.secondaryInputPanelNode, textInputPanelNode: self.textInputPanelNode, chatControllerInteraction: self.controllerInteraction, interfaceInteraction: self.interfaceInteraction) + if SGSimpleSettings.shared.hideChannelBottomButton { + // We still need the panel for messages multi-select or search. Likely can break in future. + if self.chatPresentationInterfaceState.interfaceState.selectionState != nil || self.chatPresentationInterfaceState.search != nil { + self.inputPanelBackgroundNode.isHidden = false + } else if (inputPanelNodes.primary != nil || inputPanelNodes.secondary != nil) { + // So there should be some panel, but user don't want it. Let's check if our logic will hide it + inputPanelNodes = inputPanelForChatPresentationIntefaceState(self.chatPresentationInterfaceState, context: self.context, currentPanel: self.inputPanelNode, currentSecondaryPanel: self.secondaryInputPanelNode, textInputPanelNode: self.textInputPanelNode, chatControllerInteraction: self.controllerInteraction, interfaceInteraction: self.interfaceInteraction) + if inputPanelNodes.primary == nil && inputPanelNodes.secondary == nil { + // Looks like we're eligible to hide the panel, let's remove safe area fill as well + self.inputPanelBackgroundNode.isHidden = true + } + } + } let inputPanelBottomInset = max(insets.bottom, inputPanelBottomInsetTerm) @@ -1931,7 +1946,7 @@ class ChatControllerNode: ASDisplayNode, ASScrollViewDelegate { updateExtraNavigationBarBackgroundHeight(0.0, 0.0, nil, transition) - var sidePanelTopInset: CGFloat = insets.top + 4.0 + var sidePanelTopInset: CGFloat = insets.top - 4.0 let contentBounds = CGRect(x: 0.0, y: 0.0, width: layout.size.width - wrappingInsets.left - wrappingInsets.right, height: layout.size.height - wrappingInsets.top - wrappingInsets.bottom) @@ -2241,24 +2256,38 @@ class ChatControllerNode: ASDisplayNode, ASScrollViewDelegate { } } - var bottomBackgroundEdgeEffectNode: WallpaperEdgeEffectNode? - if let current = self.bottomBackgroundEdgeEffectNode { - bottomBackgroundEdgeEffectNode = current + let edgeEffectAlpha: CGFloat + if case .image = self.chatPresentationInterfaceState.chatWallpaper { + edgeEffectAlpha = 0.7 + } else if case .color = self.chatPresentationInterfaceState.chatWallpaper { + edgeEffectAlpha = 0.85 } else { - if let value = self.backgroundNode.makeEdgeEffectNode() { - bottomBackgroundEdgeEffectNode = value - self.bottomBackgroundEdgeEffectNode = value - self.historyNodeContainer.view.superview?.insertSubview(value.view, aboveSubview: self.historyNodeContainer.view) + edgeEffectAlpha = 0.75 + } + + + var bottomBackgroundEdgeEffectNode: WallpaperEdgeEffectNode? + if self.historyNode.rotated { + if let current = self.bottomBackgroundEdgeEffectNode { + bottomBackgroundEdgeEffectNode = current + } else { + if let value = self.backgroundNode.makeEdgeEffectNode() { + bottomBackgroundEdgeEffectNode = value + self.bottomBackgroundEdgeEffectNode = value + value.isUserInteractionEnabled = false + self.historyNodeContainer.view.superview?.insertSubview(value.view, aboveSubview: self.historyNodeContainer.view) + } } } if let bottomBackgroundEdgeEffectNode { var blurFrame = inputBackgroundFrame - blurFrame.origin.y -= 18.0 + blurFrame.origin.y -= 20.0 blurFrame.size.height = max(100.0, layout.size.height - blurFrame.origin.y) transition.updateFrame(node: bottomBackgroundEdgeEffectNode, frame: blurFrame) bottomBackgroundEdgeEffectNode.update( rect: blurFrame, - edge: WallpaperEdgeEffectEdge(edge: .bottom, size: 100.0), + edge: WallpaperEdgeEffectEdge(edge: .bottom, size: min(60.0, blurFrame.height)), + alpha: edgeEffectAlpha, blur: false, containerSize: wallpaperBounds.size, transition: transition @@ -2275,7 +2304,11 @@ class ChatControllerNode: ASDisplayNode, ASScrollViewDelegate { } } - var contentBottomInset: CGFloat = inputPanelsHeight + 11.0 + inputPanelsInset + var contentBottomInset: CGFloat = inputPanelsHeight + inputPanelsInset + if previewing { + } else { + contentBottomInset += 11.0 + } if let scrollContainerNode = self.scrollContainerNode { transition.updateFrame(node: scrollContainerNode, frame: CGRect(origin: CGPoint(), size: layout.size)) @@ -2307,7 +2340,6 @@ class ChatControllerNode: ASDisplayNode, ASScrollViewDelegate { } if let containerNode = self.containerNode { - contentBottomInset += 8.0 let containerNodeFrame = CGRect(origin: CGPoint(x: wrappingInsets.left, y: wrappingInsets.top), size: CGSize(width: contentBounds.size.width, height: contentBounds.size.height - containerInsets.bottom - inputPanelsHeight - 8.0)) transition.updateFrame(node: containerNode, frame: containerNodeFrame) @@ -2322,7 +2354,7 @@ class ChatControllerNode: ASDisplayNode, ASScrollViewDelegate { overlayNavigationBar.updateLayout(size: barFrame.size, transition: transition) } - var listInsets = UIEdgeInsets(top: containerInsets.bottom + contentBottomInset, left: containerInsets.right, bottom: containerInsets.top + 6.0, right: containerInsets.left) + var listInsets = UIEdgeInsets(top: containerInsets.bottom + contentBottomInset, left: containerInsets.right, bottom: containerInsets.top, right: containerInsets.left) let listScrollIndicatorInsets = UIEdgeInsets(top: containerInsets.bottom + inputPanelsHeight, left: containerInsets.right, bottom: containerInsets.top, right: containerInsets.left) var childContentInsets: UIEdgeInsets = containerInsets @@ -2446,23 +2478,28 @@ class ChatControllerNode: ASDisplayNode, ASScrollViewDelegate { }) var topBackgroundEdgeEffectNode: WallpaperEdgeEffectNode? - if let current = self.topBackgroundEdgeEffectNode { - topBackgroundEdgeEffectNode = current - } else { - if let value = self.backgroundNode.makeEdgeEffectNode() { - topBackgroundEdgeEffectNode = value - self.topBackgroundEdgeEffectNode = value - self.historyNodeContainer.view.superview?.insertSubview(value.view, aboveSubview: self.historyNodeContainer.view) + if self.historyNode.rotated { + if let current = self.topBackgroundEdgeEffectNode { + topBackgroundEdgeEffectNode = current + } else { + if let value = self.backgroundNode.makeEdgeEffectNode() { + topBackgroundEdgeEffectNode = value + self.topBackgroundEdgeEffectNode = value + value.isUserInteractionEnabled = false + self.historyNodeContainer.view.superview?.insertSubview(value.view, aboveSubview: self.historyNodeContainer.view) + } } } if let topBackgroundEdgeEffectNode { - var blurFrame = CGRect(origin: CGPoint(), size: CGSize(width: layout.size.width, height: max(100.0, listInsets.bottom + 10.0))) - blurFrame.origin.y = listInsets.bottom + 10.0 - blurFrame.height + let topExtent: CGFloat = 34.0 + var blurFrame = CGRect(origin: CGPoint(), size: CGSize(width: layout.size.width, height: max(100.0, listInsets.bottom + topExtent))) + blurFrame.origin.y = listInsets.bottom + topExtent - blurFrame.height transition.updateFrame(node: topBackgroundEdgeEffectNode, frame: blurFrame) topBackgroundEdgeEffectNode.update( rect: blurFrame, - edge: WallpaperEdgeEffectEdge(edge: .top, size: 100.0), - blur: false, + edge: WallpaperEdgeEffectEdge(edge: .top, size: 80.0), + alpha: edgeEffectAlpha, + blur: true, containerSize: wallpaperBounds.size, transition: transition ) @@ -2524,6 +2561,7 @@ class ChatControllerNode: ASDisplayNode, ASScrollViewDelegate { transition.updateFrame(node: self.inputPanelBackgroundNode, frame: apparentInputBackgroundFrame, beginWithCurrentState: true) if let headerPanelsComponentView = self.headerPanelsView?.view, let headerPanelsSize { + sidePanelTopInset += 8.0 let headerPanelsFrame = CGRect(origin: CGPoint(x: layout.safeInsets.left, y: sidePanelTopInset), size: headerPanelsSize) var headerPanelsTransition = ComponentTransition(transition) if headerPanelsComponentView.superview == nil { @@ -4602,12 +4640,13 @@ class ChatControllerNode: ASDisplayNode, ASScrollViewDelegate { } } - // GHOSTGRAM: When send delay is active, scheduled messages - // don't trigger history view update, so clear input immediately. if SendDelayManager.shared.isEnabled { self.collapseInput() + self.ignoreUpdateHeight = true - textInputPanelNode.text = "" + if let textInputPanelNode = self.inputPanelNode as? ChatTextInputPanelNode { + textInputPanelNode.text = "" + } self.requestUpdateChatInterfaceState(.immediate, overrideThreadId == nil, { state in var state = state state = state.withUpdatedReplyMessageSubject(nil) @@ -4657,7 +4696,7 @@ class ChatControllerNode: ASDisplayNode, ASScrollViewDelegate { } var targetThreadId: Int64? - if self.chatLocation.threadId == nil, let user = self.chatPresentationInterfaceState.renderedPeer?.peer as? TelegramUser, user.isForum { + if self.chatLocation.threadId == nil, let user = self.chatPresentationInterfaceState.renderedPeer?.peer as? TelegramUser, let botInfo = user.botInfo, botInfo.flags.contains(.hasForum), botInfo.flags.contains(.forumManagedByUser) { if let message = messages.first { switch message { case let .message(_, _, _, _, _, replyToMessageId, _, _, _, _): diff --git a/submodules/TelegramUI/Sources/ChatHistoryEntriesForView.swift b/submodules/TelegramUI/Sources/ChatHistoryEntriesForView.swift index 44097d73..7dc3c820 100644 --- a/submodules/TelegramUI/Sources/ChatHistoryEntriesForView.swift +++ b/submodules/TelegramUI/Sources/ChatHistoryEntriesForView.swift @@ -647,7 +647,7 @@ func chatHistoryEntriesForView( } } - if !dynamicAdMessages.isEmpty { + if !MiscSettingsManager.shared.shouldBlockAds && !dynamicAdMessages.isEmpty { assert(entries.sorted() == entries) for message in dynamicAdMessages { entries.append(.MessageEntry(message, presentationData, false, nil, .none, ChatMessageEntryAttributes(rank: nil, isContact: false, contentTypeHint: .generic, updatingMedia: nil, isPlaying: false, isCentered: false, authorStoryStats: nil, displayContinueThreadFooter: false))) @@ -655,7 +655,7 @@ func chatHistoryEntriesForView( entries.sort() } - if view.laterId == nil && !view.isLoading { + if !MiscSettingsManager.shared.shouldBlockAds && view.laterId == nil && !view.isLoading { if !entries.isEmpty, case let .MessageEntry(lastMessage, _, _, _, _, _) = entries[entries.count - 1], let message = adMessage { var nextAdMessageId: Int32 = 10000 let updatedMessage = Message( diff --git a/submodules/TelegramUI/Sources/ChatHistoryListNode.swift b/submodules/TelegramUI/Sources/ChatHistoryListNode.swift index 95b575d2..a5bfa6dc 100644 --- a/submodules/TelegramUI/Sources/ChatHistoryListNode.swift +++ b/submodules/TelegramUI/Sources/ChatHistoryListNode.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import Postbox @@ -339,6 +340,7 @@ final class ChatHistoryTransactionOpaqueState { } private func extractAssociatedData( + translationSettings: TranslationSettings, chatLocation: ChatLocation, view: MessageHistoryView, automaticDownloadNetworkType: MediaAutoDownloadNetworkType, @@ -421,7 +423,43 @@ private func extractAssociatedData( automaticDownloadPeerId = message.peerId } - return ChatMessageItemAssociatedData(automaticDownloadPeerType: automaticMediaDownloadPeerType, automaticDownloadPeerId: automaticDownloadPeerId, automaticDownloadNetworkType: automaticDownloadNetworkType, preferredStoryHighQuality: preferredStoryHighQuality, isRecentActions: false, subject: subject, contactsPeerIds: contactsPeerIds, channelDiscussionGroup: channelDiscussionGroup, animatedEmojiStickers: animatedEmojiStickers, additionalAnimatedEmojiStickers: additionalAnimatedEmojiStickers, currentlyPlayingMessageId: currentlyPlayingMessageId, isCopyProtectionEnabled: isCopyProtectionEnabled, availableReactions: availableReactions, availableMessageEffects: availableMessageEffects, savedMessageTags: savedMessageTags, defaultReaction: defaultReaction, areStarReactionsEnabled: areStarReactionsEnabled, isPremium: isPremium, accountPeer: accountPeer, alwaysDisplayTranscribeButton: alwaysDisplayTranscribeButton, topicAuthorId: topicAuthorId, hasBots: hasBots, translateToLanguage: translateToLanguage, maxReadStoryId: maxReadStoryId, recommendedChannels: recommendedChannels, audioTranscriptionTrial: audioTranscriptionTrial, chatThemes: chatThemes, deviceContactsNumbers: deviceContactsNumbers, isInline: isInline, showSensitiveContent: showSensitiveContent, isSuspiciousPeer: isSuspiciousPeer) + return ChatMessageItemAssociatedData( + automaticDownloadPeerType: automaticMediaDownloadPeerType, + automaticDownloadPeerId: automaticDownloadPeerId, + automaticDownloadNetworkType: automaticDownloadNetworkType, + preferredStoryHighQuality: preferredStoryHighQuality, + isRecentActions: false, + subject: subject, + contactsPeerIds: contactsPeerIds, + channelDiscussionGroup: channelDiscussionGroup, + animatedEmojiStickers: animatedEmojiStickers, + additionalAnimatedEmojiStickers: additionalAnimatedEmojiStickers, + forcedResourceStatus: nil, + currentlyPlayingMessageId: currentlyPlayingMessageId, + isCopyProtectionEnabled: isCopyProtectionEnabled, + availableReactions: availableReactions, + availableMessageEffects: availableMessageEffects, + savedMessageTags: savedMessageTags, + defaultReaction: defaultReaction, + areStarReactionsEnabled: areStarReactionsEnabled, + isPremium: isPremium, + accountPeer: accountPeer, + forceInlineReactions: false, + alwaysDisplayTranscribeButton: alwaysDisplayTranscribeButton, + topicAuthorId: topicAuthorId, + hasBots: hasBots, + translationSettings: translationSettings, + translateToLanguage: translateToLanguage, + maxReadStoryId: maxReadStoryId, + recommendedChannels: recommendedChannels, + audioTranscriptionTrial: audioTranscriptionTrial, + chatThemes: chatThemes, + deviceContactsNumbers: deviceContactsNumbers, + isStandalone: false, + isInline: isInline, + showSensitiveContent: showSensitiveContent, + isSuspiciousPeer: isSuspiciousPeer + ) } private extension ChatHistoryLocationInput { @@ -791,6 +829,7 @@ public final class ChatHistoryListNodeImpl: ListView, ChatHistoryNode, ChatHisto self.messageTransitionNode = messageTransitionNode self.mode = mode + if SGSimpleSettings.shared.disableSnapDeletionEffect { self.allowDustEffect = false } if let data = context.currentAppConfiguration.with({ $0 }).data { if let _ = data["ios_killswitch_disable_unread_alignment"] { self.enableUnreadAlignment = false @@ -1816,6 +1855,7 @@ public final class ChatHistoryListNodeImpl: ListView, ChatHistoryNode, ChatHisto var measure_isFirstTime = true let messageViewQueue = Queue.mainQueue() let historyViewTransitionDisposable = (combineLatest(queue: messageViewQueue, + self.context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.translationSettings]) |> take(1), historyViewUpdate |> debug_measureTimeToFirstEvent(label: "chatHistoryNode_historyViewUpdate"), self.chatPresentationDataPromise.get() |> debug_measureTimeToFirstEvent(label: "chatHistoryNode_chatPresentationData"), selectedMessages |> debug_measureTimeToFirstEvent(label: "chatHistoryNode_selectedMessages"), @@ -1841,7 +1881,7 @@ public final class ChatHistoryListNodeImpl: ListView, ChatHistoryNode, ChatHisto chatThemes |> debug_measureTimeToFirstEvent(label: "chatHistoryNode_chatThemes"), deviceContactsNumbers |> debug_measureTimeToFirstEvent(label: "chatHistoryNode_deviceContactsNumbers"), contentSettings |> debug_measureTimeToFirstEvent(label: "chatHistoryNode_contentSettings") - ) |> debug_measureTimeToFirstEvent(label: "chatHistoryNode_firstChatHistoryTransition")).startStrict(next: { [weak self] update, chatPresentationData, selectedMessages, updatingMedia, networkType, preferredStoryHighQuality, animatedEmojiStickers, additionalAnimatedEmojiStickers, customChannelDiscussionReadState, customThreadOutgoingReadState, availableReactions, availableMessageEffects, savedMessageTags, defaultReaction, accountPeer, suggestAudioTranscription, promises, topicAuthorId, translationState, maxReadStoryId, recommendedChannels, audioTranscriptionTrial, chatThemes, deviceContactsNumbers, contentSettings in + ) |> debug_measureTimeToFirstEvent(label: "chatHistoryNode_firstChatHistoryTransition")).startStrict(next: { [weak self] sharedData, /* MARK: Swiftgram */ update, chatPresentationData, selectedMessages, updatingMedia, networkType, preferredStoryHighQuality, animatedEmojiStickers, additionalAnimatedEmojiStickers, customChannelDiscussionReadState, customThreadOutgoingReadState, availableReactions, availableMessageEffects, savedMessageTags, defaultReaction, accountPeer, suggestAudioTranscription, promises, topicAuthorId, translationState, maxReadStoryId, recommendedChannels, audioTranscriptionTrial, chatThemes, deviceContactsNumbers, contentSettings in let (historyAppearsCleared, pendingUnpinnedAllMessages, pendingRemovedMessages, currentlyPlayingMessageIdAndType, scrollToMessageId, chatHasBots, allAdMessages) = promises if measure_isFirstTime { @@ -1852,6 +1892,13 @@ public final class ChatHistoryListNodeImpl: ListView, ChatHistoryNode, ChatHisto #endif } + let translationSettings: TranslationSettings + if let current = sharedData.entries[ApplicationSpecificSharedDataKeys.translationSettings]?.get(TranslationSettings.self) { + translationSettings = current + } else { + translationSettings = TranslationSettings.defaultSettings + } + func applyHole() { Queue.mainQueue().async { if let strongSelf = self { @@ -2056,23 +2103,24 @@ public final class ChatHistoryListNodeImpl: ListView, ChatHistoryNode, ChatHisto } } } - // GHOSTGRAM: Bypass copy protection if enabled in Misc settings - if MiscSettingsManager.shared.shouldBypassCopyProtection { - isCopyProtectionEnabled = false - } let alwaysDisplayTranscribeButton = ChatMessageItemAssociatedData.DisplayTranscribeButton( canBeDisplayed: suggestAudioTranscription.0 < 2, displayForNotConsumed: suggestAudioTranscription.1, providedByGroupBoost: audioTranscriptionProvidedByBoost ) - - var translateToLanguage: (fromLang: String, toLang: String)? - if let translationState, (isPremium || autoTranslate) && translationState.isEnabled { - var languageCode = translationState.toLang ?? chatPresentationData.strings.baseLanguageCode + + // MARK: Swiftgram + // var translateToLanguage: (fromLang: String, toLang: String)? + // if let translationState, (isPremium || autoTranslate) && translationState.isEnabled { + var languageCode = translationState?.toLang ?? chatPresentationData.strings.baseLanguageCode let rawSuffix = "-raw" if languageCode.hasSuffix(rawSuffix) { languageCode = String(languageCode.dropLast(rawSuffix.count)) } + languageCode = normalizeTranslationLanguage(languageCode) + var translateToLanguage: (fromLang: String, toLang: String)? + let sgTranslationAvailable = SGSimpleSettings.shared.translationBackendEnum != .default + if let translationState, (isPremium || autoTranslate || sgTranslationAvailable) && translationState.isEnabled { translateToLanguage = (normalizeTranslationLanguage(translationState.fromLang), normalizeTranslationLanguage(languageCode)) } @@ -2081,7 +2129,7 @@ public final class ChatHistoryListNodeImpl: ListView, ChatHistoryNode, ChatHisto isSuspiciousPeer = true } - let associatedData = extractAssociatedData(chatLocation: chatLocation, view: view, automaticDownloadNetworkType: networkType, preferredStoryHighQuality: preferredStoryHighQuality, animatedEmojiStickers: animatedEmojiStickers, additionalAnimatedEmojiStickers: additionalAnimatedEmojiStickers, subject: subject, currentlyPlayingMessageId: currentlyPlayingMessageIdAndType?.0, isCopyProtectionEnabled: isCopyProtectionEnabled, availableReactions: availableReactions, availableMessageEffects: availableMessageEffects, savedMessageTags: savedMessageTags, defaultReaction: defaultReaction.0, areStarReactionsEnabled: defaultReaction.1, isPremium: isPremium, alwaysDisplayTranscribeButton: alwaysDisplayTranscribeButton, accountPeer: accountPeer, topicAuthorId: topicAuthorId, hasBots: chatHasBots, translateToLanguage: translateToLanguage?.toLang, maxReadStoryId: maxReadStoryId, recommendedChannels: recommendedChannels, audioTranscriptionTrial: audioTranscriptionTrial, chatThemes: chatThemes, deviceContactsNumbers: deviceContactsNumbers, isInline: !rotated, showSensitiveContent: contentSettings.ignoreContentRestrictionReasons.contains("sensitive"), isSuspiciousPeer: isSuspiciousPeer) + let associatedData = extractAssociatedData(translationSettings: translationSettings, /* MARK: Swiftgram */ chatLocation: chatLocation, view: view, automaticDownloadNetworkType: networkType, preferredStoryHighQuality: preferredStoryHighQuality, animatedEmojiStickers: animatedEmojiStickers, additionalAnimatedEmojiStickers: additionalAnimatedEmojiStickers, subject: subject, currentlyPlayingMessageId: currentlyPlayingMessageIdAndType?.0, isCopyProtectionEnabled: isCopyProtectionEnabled, availableReactions: availableReactions, availableMessageEffects: availableMessageEffects, savedMessageTags: savedMessageTags, defaultReaction: defaultReaction.0, areStarReactionsEnabled: defaultReaction.1, isPremium: isPremium, alwaysDisplayTranscribeButton: alwaysDisplayTranscribeButton, accountPeer: accountPeer, topicAuthorId: topicAuthorId, hasBots: chatHasBots, translateToLanguage: translateToLanguage?.toLang, maxReadStoryId: maxReadStoryId, recommendedChannels: recommendedChannels, audioTranscriptionTrial: audioTranscriptionTrial, chatThemes: chatThemes, deviceContactsNumbers: deviceContactsNumbers, isInline: !rotated, showSensitiveContent: contentSettings.ignoreContentRestrictionReasons.contains("sensitive"), isSuspiciousPeer: isSuspiciousPeer) var includeEmbeddedSavedChatInfo = false if case let .replyThread(message) = chatLocation, message.peerId == context.account.peerId, !rotated { @@ -2106,8 +2154,7 @@ public final class ChatHistoryListNodeImpl: ListView, ChatHistoryNode, ChatHisto selectedMessages: selectedMessages, presentationData: chatPresentationData, historyAppearsCleared: historyAppearsCleared, - // GHOSTGRAM: Keep view-once media visible if bypass is enabled - skipViewOnceMedia: MiscSettingsManager.shared.shouldDisableViewOnceAutoDelete ? false : (mode != .bubbles), + skipViewOnceMedia: mode != .bubbles, pendingUnpinnedAllMessages: pendingUnpinnedAllMessages, pendingRemovedMessages: pendingRemovedMessages, associatedData: associatedData, @@ -2115,9 +2162,8 @@ public final class ChatHistoryListNodeImpl: ListView, ChatHistoryNode, ChatHisto customChannelDiscussionReadState: customChannelDiscussionReadState, customThreadOutgoingReadState: customThreadOutgoingReadState, cachedData: data.cachedData, - // GHOSTGRAM: Block ads if enabled in Misc settings - adMessage: MiscSettingsManager.shared.shouldBlockAds ? nil : allAdMessages.fixed, - dynamicAdMessages: MiscSettingsManager.shared.shouldBlockAds ? [] : allAdMessages.opportunistic + adMessage: allAdMessages.fixed, + dynamicAdMessages: allAdMessages.opportunistic ) let lastHeaderId = filteredEntries.last.flatMap { listMessageDateHeaderId(timestamp: $0.index.timestamp) } ?? 0 let processedView = ChatHistoryView(originalView: view, filteredEntries: filteredEntries, associatedData: associatedData, lastHeaderId: lastHeaderId, id: id, locationInput: update.2, ignoreMessagesInTimestampRange: update.3, ignoreMessageIds: update.4) diff --git a/submodules/TelegramUI/Sources/ChatInterfaceInputContexts.swift b/submodules/TelegramUI/Sources/ChatInterfaceInputContexts.swift index 997524d0..4101cb0e 100644 --- a/submodules/TelegramUI/Sources/ChatInterfaceInputContexts.swift +++ b/submodules/TelegramUI/Sources/ChatInterfaceInputContexts.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import TelegramCore @@ -261,7 +262,7 @@ func inputTextPanelStateForChatPresentationInterfaceState(_ chatPresentationInte } } else { stickersAreEmoji = stickersAreEmoji || hasForward - if stickersEnabled { + if stickersEnabled, !SGSimpleSettings.shared.forceEmojiTab { accessoryItems.append(.input(isEnabled: true, inputMode: stickersAreEmoji ? .emoji : .stickers)) } else { accessoryItems.append(.input(isEnabled: true, inputMode: .emoji)) diff --git a/submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift b/submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift index 0d05ccc3..8a374877 100644 --- a/submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift +++ b/submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift @@ -1,3 +1,6 @@ +import SGStrings +import SGSimpleSettings +import PeerInfoUI import Foundation import UIKit import Postbox @@ -496,6 +499,16 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState if case .standard(.embedded) = chatPresentationInterfaceState.mode { isEmbeddedMode = true } + // MARK: Swiftgram + var canReveal = false + if !chatPresentationInterfaceState.copyProtectionEnabled { + outer: for message in messages { + if message.canRevealContent(contentSettings: context.currentContentSettings.with { $0 }) { + canReveal = true + break outer + } + } + } if case let .customChatContents(customChatContents) = chatPresentationInterfaceState.subject, case .hashTagSearch = customChatContents.kind { isEmbeddedMode = true @@ -644,7 +657,7 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState messageEntities = attribute.entities } if let attribute = attribute as? RestrictedContentMessageAttribute { - restrictedText = attribute.platformText(platform: "ios", contentSettings: context.currentContentSettings.with { $0 }) ?? "" + restrictedText = attribute.platformText(platform: "ios", contentSettings: context.currentContentSettings.with { $0 }, chatId: message.author?.id.id._internalGetInt64Value()) ?? "" } } @@ -939,10 +952,12 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState return dataSignal |> deliverOnMainQueue - |> map { data, updatingMessageMedia, infoSummaryData, appConfig, isMessageRead, messageViewsPrivacyTips, availableReactions, translationSettings, loggingSettings, notificationSoundList, accountPeer -> ContextController.Items in + |> map { value -> ContextController.Items in + let (data, updatingMessageMedia, infoSummaryData, appConfig, isMessageRead, _, availableReactions, translationSettings, loggingSettings, notificationSoundList, accountPeer) = value let isPremium = accountPeer?.isPremium ?? false var actions: [ContextMenuItem] = [] + var sgActions: [ContextMenuItem] = [] var isPinnedMessages = false if case .pinnedMessages = chatPresentationInterfaceState.subject { @@ -1140,7 +1155,7 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState let sendGiftTitle: String var isIncoming = message.effectivelyIncoming(context.account.peerId) for media in message.media { - if let action = media as? TelegramMediaAction, case let .starGiftUnique(_, isUpgrade, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _) = action.action { + if let action = media as? TelegramMediaAction, case let .starGiftUnique(_, isUpgrade, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _) = action.action { if isUpgrade && message.author?.id == context.account.peerId { isIncoming = true } @@ -1177,6 +1192,7 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState }) }) }))) + if !SGSimpleSettings.shared.contextShowReply { sgActions.append(actions.removeLast()) } } if data.messageActions.options.contains(.sendScheduledNow) { @@ -1284,7 +1300,7 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState messageEntities = attribute.entities } if let attribute = attribute as? RestrictedContentMessageAttribute { - restrictedText = attribute.platformText(platform: "ios", contentSettings: context.currentContentSettings.with { $0 }) ?? "" + restrictedText = attribute.platformText(platform: "ios", contentSettings: context.currentContentSettings.with { $0 }, chatId: message.author?.id.id._internalGetInt64Value()) ?? "" } } @@ -1413,13 +1429,13 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState }) f(.default) }))) - - // MARK: - Ghostgram: Send as Circle (Video Message) + if !SGSimpleSettings.shared.contextShowSaveMedia { sgActions.append(actions.removeLast()) } + if isVideo, let file = message.media.first(where: { $0 is TelegramMediaFile }) as? TelegramMediaFile { actions.append(.action(ContextMenuActionItem(text: "Отправить как кружок", icon: { theme in return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/VideoMessage"), color: theme.actionSheet.primaryTextColor) - }, action: { (controller: ContextControllerProtocol?, dismiss: @escaping (ContextMenuActionResult) -> Void) in - dismiss(.default) + }, action: { _, f in + f(.default) convertVideoToCircleAndSend(context: context, message: message, file: file, controllerInteraction: controllerInteraction) }))) } @@ -1457,8 +1473,28 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState } } - // REMOVED: Send Logs button + if (loggingSettings.logToFile || loggingSettings.logToConsole) && !downloadableMediaResourceInfos.isEmpty { + actions.append(.action(ContextMenuActionItem(text: "Send Logs", icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Message"), color: theme.actionSheet.primaryTextColor) + }, action: { _, f in + triggerDebugSendLogsUI(context: context, additionalInfo: "User has requested download logs for \(downloadableMediaResourceInfos)", pushController: { c in + controllerInteraction.navigationController()?.pushViewController(c) + }) + f(.default) + }))) + } + let showJsonAction: ContextMenuItem = .action(ContextMenuActionItem(text: "JSON", icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Settings"), color: theme.actionSheet.primaryTextColor) + }, action: { _, f in + showMessageJson(controllerInteraction: controllerInteraction, chatPresentationInterfaceState: chatPresentationInterfaceState, message: message, context: context) + f(.default) + })) + if SGSimpleSettings.shared.contextShowJson { + actions.append(showJsonAction) + } else { + sgActions.append(showJsonAction) + } var threadId: Int64? var threadMessageCount: Int = 0 @@ -1498,6 +1534,7 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState controllerInteraction.openMessageReplies(messages[0].id, true, true) }) }))) + if !SGSimpleSettings.shared.contextShowMessageReplies { sgActions.append(actions.removeLast()) } } let isMigrated: Bool @@ -1533,57 +1570,55 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState } }))) } - - // MARK: - Ghostgram: Local Edit (Client-Side Only) - // Allows editing any message text locally without sending to server + if !message.text.isEmpty { actions.append(.action(ContextMenuActionItem(text: "Изменить локально", icon: { theme in return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Edit"), color: theme.actionSheet.primaryTextColor) }, action: { [weak controllerInteraction] _, f in f(.dismissWithoutContent) - - guard let controllerInteraction = controllerInteraction else { return } - + + guard let controllerInteraction = controllerInteraction else { + return + } + let peerId = message.id.peerId.toInt64() let messageId = message.id.id let currentText = LocalEditManager.shared.getLocalEdit(peerId: peerId, messageId: messageId) ?? message.text - + let alertController = UIAlertController( title: "Изменить локально", message: "Это изменение видно только вам и сбросится после перезапуска приложения", preferredStyle: .alert ) - + alertController.addTextField { textField in textField.text = currentText textField.placeholder = "Введите новый текст" } - + alertController.addAction(UIAlertAction(title: "Отмена", style: .cancel, handler: nil)) - alertController.addAction(UIAlertAction(title: "Сохранить", style: .default) { [weak alertController] _ in + alertController.addAction(UIAlertAction(title: "Сохранить", style: .default, handler: { [weak alertController] _ in guard let textField = alertController?.textFields?.first, - let newText = textField.text, !newText.isEmpty else { + let newText = textField.text, + !newText.isEmpty else { return } - + LocalEditManager.shared.setLocalEdit(peerId: peerId, messageId: messageId, newText: newText) - - // Request UI update controllerInteraction.requestMessageUpdate(message.id, true) - }) - - if let chatControllerNode = controllerInteraction.chatControllerNode() { - if let viewController = chatControllerNode.view.window?.rootViewController { - var topController = viewController - while let presented = topController.presentedViewController { - topController = presented - } - topController.present(alertController, animated: true, completion: nil) + })) + + if let chatControllerNode = controllerInteraction.chatControllerNode(), + let viewController = chatControllerNode.view.window?.rootViewController { + var topController = viewController + while let presented = topController.presentedViewController { + topController = presented } + topController.present(alertController, animated: true, completion: nil) } }))) } - + if let message = messages.first, message.id.namespace == Namespaces.Message.Cloud, let channel = message.peers[message.id.peerId] as? TelegramChannel, channel.isMonoForum { var canSuggestPost = true for media in message.media { @@ -1698,6 +1733,7 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState interfaceInteraction.pinMessage(messages[0].id, c) }))) } + if !SGSimpleSettings.shared.contextShowPin { sgActions.append(actions.removeLast()) } } if let activePoll = activePoll, messages[0].forwardInfo == nil { @@ -1870,18 +1906,52 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_ContextMenuForward, icon: { theme in return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Forward"), color: theme.actionSheet.primaryTextColor) }, action: { _, f in - interfaceInteraction.forwardMessages(selectAll || isImage ? messages : [message]) + interfaceInteraction.forwardMessages(selectAll || isImage ? messages : [message], nil) f(.dismissWithoutContent) }))) + if message.id.peerId != context.account.peerId { + let action: ContextMenuItem = .action(ContextMenuActionItem(text: i18n("ContextMenu.SaveToCloud", chatPresentationInterfaceState.strings.baseLanguageCode), icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Fave"), color: theme.actionSheet.primaryTextColor) + }, action: { _, f in + interfaceInteraction.forwardMessages(selectAll || isImage ? messages : [message], "forwardMessagesToCloud") + f(.dismissWithoutContent) + })) + if SGSimpleSettings.shared.contextShowSaveToCloud { + actions.append(action) + } else { + sgActions.append(action) + } + } + let action: ContextMenuItem = .action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.NotificationSettings_Stories_CompactHideName, icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Forward"), color: theme.actionSheet.primaryTextColor) + }, action: { _, f in + interfaceInteraction.forwardMessages(selectAll || isImage ? messages : [message], "forwardMessagesWithNoNames") + f(.dismissWithoutContent) + })) + if SGSimpleSettings.shared.contextShowHideForwardName { + actions.append(action) + } else { + sgActions.append(action) + } } } - if data.messageActions.options.contains(.report) { + if canReveal { + actions.insert(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Username_ActivateAlertShow, icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Premium/Stories/Views" /*"Chat/Context Menu/Eye"*/ ), color: theme.actionSheet.primaryTextColor) + }, action: { _, f in + interfaceInteraction.forwardMessages(selectAll || isImage ? messages : [message], "forwardMessagesToCloudWithNoNamesAndOpen") + f(.dismissWithoutContent) + })), at: 0) + } + + if data.messageActions.options.contains(.report) || context.account.testingEnvironment { actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_ContextMenuReport, icon: { theme in return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Report"), color: theme.actionSheet.primaryTextColor) }, action: { controller, f in interfaceInteraction.reportMessages(messages, controller) }))) + if !SGSimpleSettings.shared.contextShowReport { sgActions.append(actions.removeLast()) } } else if message.id.peerId.isReplies { actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_ContextMenuBlock, textColor: .destructive, icon: { theme in return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Restrict"), color: theme.actionSheet.destructiveActionTextColor) @@ -1890,6 +1960,54 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState }))) } + if let peer = chatPresentationInterfaceState.renderedPeer?.peer ?? message.peers[message.id.peerId] { + let hasRestrictPermission: Bool + if let channel = peer as? TelegramChannel { + hasRestrictPermission = channel.hasPermission(.banMembers) + } else if let group = peer as? TelegramGroup { + switch group.role { + case .creator: + hasRestrictPermission = true + case let .admin(adminRights, _): + hasRestrictPermission = adminRights.rights.contains(.canBanUsers) + case .member: + hasRestrictPermission = false + } + } else { + hasRestrictPermission = false + } + + if let user = message.author as? TelegramUser { + if (user.id != context.account.peerId) && hasRestrictPermission { + let banDisposables = DisposableDict() + // TODO(swiftgram): Check is user an admin? + let action: ContextMenuItem = .action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_ContextMenuBan, icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Restrict"), color: theme.actionSheet.primaryTextColor) + }, action: { _, f in + let participantSignal: Signal + if peer is TelegramChannel { + participantSignal = context.engine.peers.fetchChannelParticipant(peerId: peer.id, participantId: user.id) + } else if peer is TelegramGroup { + participantSignal = .single(.member(id: user.id, invitedAt: 0, adminInfo: nil, banInfo: nil, rank: nil, subscriptionUntilDate: nil)) + } else { + participantSignal = .single(nil) + } + banDisposables.set((participantSignal + |> deliverOnMainQueue).start(next: { participant in + controllerInteraction.presentController(channelBannedMemberController(context: context, peerId: peer.id, memberId: message.author!.id, initialParticipant: participant, updated: { _ in }, upgradedToSupergroup: { _, f in f() }), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + }), forKey: user.id) + f(.dismissWithoutContent) + })) + if SGSimpleSettings.shared.contextShowRestrict { + actions.append(action) + } else { + sgActions.append(action) + } + } + } + } + + var clearCacheAsDelete = false if let channel = message.peers[message.id.peerId] as? TelegramChannel, case .broadcast = channel.info, !isMigrated { var views: Int = 0 @@ -2013,9 +2131,86 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState }))) } } - + var sgActionsIndex: Int? = nil if !isPinnedMessages, !isReplyThreadHead, data.canSelect { + sgActionsIndex = actions.count var didAddSeparator = false + // MARK: Swiftgram + if let authorId = message.author?.id { + let action: ContextMenuItem = .action(ContextMenuActionItem(text: i18n("ContextMenu.SelectFromUser", chatPresentationInterfaceState.strings.baseLanguageCode), icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/SelectAll"), color: theme.actionSheet.primaryTextColor) + }, action: { _, f in + let progressSignal = Signal { subscriber in + let overlayController = OverlayStatusController(theme: chatPresentationInterfaceState.theme, type: .loading(cancelled: nil)) + controllerInteraction.presentGlobalOverlayController(overlayController, nil) + return ActionDisposable { [weak overlayController] in + Queue.mainQueue().async() { + overlayController?.dismiss() + } + } + } + |> runOn(Queue.mainQueue()) + |> delay(0.2, queue: Queue.mainQueue()) + let progressDisposable = progressSignal.start() + let _ = (context.account.postbox.transaction { transaction -> [MessageId] in + let limit = 500 + var result: [MessageId] = [] + + let needThreadIdFilter: Bool + let searchThreadId: Int64? + switch chatPresentationInterfaceState.chatLocation { + case let .replyThread(replyThreadMessage): + needThreadIdFilter = true + searchThreadId = replyThreadMessage.threadId + default: + needThreadIdFilter = false + searchThreadId = nil + } + transaction.withAllMessages(peerId: message.id.peerId, { searchMessage in + if result.count >= limit { + return false + } + if searchMessage.author?.id == authorId { + // Only messages from current opened thread + // print("searchMessage.threadId:\(String(describing: searchMessage.threadId)) threadId:\(String(describing: threadId)) message.threadId:\(String(describing:message.threadId)) needThreadIdFilter:\(needThreadIdFilter) searchThreadId:\(String(describing:searchThreadId))") + if needThreadIdFilter && searchMessage.threadId != searchThreadId { + return true + } + // No service messages + if searchMessage.media.contains(where: { $0 is TelegramMediaAction }) { + return true + } + result.append(searchMessage.id) + } + return true + }) + return result + } + |> deliverOnMainQueue) + .start(next: { ids in + interfaceInteraction.beginMessageSelection(ids, { transition in + f(.custom(transition)) + }) + Queue.mainQueue().async { + progressDisposable.dispose() + } + }, completed: { + Queue.mainQueue().async { + progressDisposable.dispose() + } + }) + })) + if SGSimpleSettings.shared.contextShowSelectFromUser { + if !actions.isEmpty && !didAddSeparator { + didAddSeparator = true + actions.append(.separator) + } + actions.append(action) + } else { + sgActions.append(action) + } + } + if !selectAll || messages.count == 1 { if !actions.isEmpty && !didAddSeparator { didAddSeparator = true @@ -2061,6 +2256,40 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState } else if let messageReadStatsAreHidden = infoSummaryData.messageReadStatsAreHidden, !messageReadStatsAreHidden { canViewStats = canViewReadStats(message: message, participantCount: infoSummaryData.participantCount, isMessageRead: isMessageRead, isPremium: isPremium, appConfig: appConfig) } + + // MARK: Swiftgram + if !sgActions.isEmpty { + if !actions.isEmpty { + if let sgActionsIndex = sgActionsIndex { + actions.insert(.separator, at: sgActionsIndex) + } else { + actions.append(.separator) + } + } + + var popSGItems: (() -> Void)? = nil + sgActions.insert(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Common_Back, icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Back"), color: theme.actionSheet.primaryTextColor) + }, iconPosition: .left, action: { _, _ in + popSGItems?() + })), at: 0) + sgActions.insert(.separator, at: 1) + + let swiftgramSubMenu: ContextMenuItem = .action(ContextMenuActionItem(text: "Swiftgram", icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "SwiftgramContextMenu"), color: theme.actionSheet.primaryTextColor) + }, action: { c, f in + popSGItems = { [weak c] in + c?.popItems() + } + c?.pushItems(items: .single(ContextController.Items(content: .list(sgActions)))) + })) + + if let sgActionsIndex = sgActionsIndex { + actions.insert(swiftgramSubMenu, at: sgActionsIndex + 1) + } else { + actions.append(swiftgramSubMenu) + } + } var reactionCount = 0 for reaction in mergedMessageReactionsAndPeers(accountPeerId: context.account.peerId, accountPeer: nil, message: message).reactions { @@ -2078,40 +2307,6 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState } return false }) - - if isEdited { - if !actions.isEmpty { - actions.insert(.separator, at: 0) - } - actions.insert(.custom(ChatReadReportContextItem(context: context, message: message, hasReadReports: false, isEdit: true, stats: MessageReadStats(reactionCount: 0, peers: [], readTimestamps: [:]), action: nil), false), at: 0) - } - - // GHOSTGRAM: Show edit history button if message was edited and has saved history - if isEdited && EditHistoryManager.shared.hasEditHistory(peerId: message.id.peerId.toInt64(), messageId: message.id.id) { - actions.append(.action(ContextMenuActionItem(text: "История", icon: { theme in - return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Edit"), color: theme.actionSheet.primaryTextColor) - }, action: { c, f in - let editHistory = EditHistoryManager.shared.getEditHistory(peerId: message.id.peerId.toInt64(), messageId: message.id.id) - var historyText = "Оригинальные версии:\n\n" - for (index, record) in editHistory.enumerated() { - let date = Date(timeIntervalSince1970: TimeInterval(record.editDate)) - let formatter = DateFormatter() - formatter.dateStyle = .short - formatter.timeStyle = .short - historyText += "\(index + 1). [\(formatter.string(from: date))]\n\(record.text)\n\n" - } - - c?.dismiss(completion: { - let alertController = textAlertController( - context: context, - title: "История правок", - text: historyText, - actions: [TextAlertAction(type: .defaultAction, title: "OK", action: {})] - ) - controllerInteraction.presentController(alertController, nil) - }) - }))) - } if canViewAuthor { actions.insert(.custom(ChatMessageAuthorContextItem(context: context, message: message, action: { c, f, peer in @@ -2120,6 +2315,7 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState }) }), false), at: 0) } + if let peer = message.peers[message.id.peerId], (canViewStats || reactionCount != 0) { var hasReadReports = false if let channel = peer as? TelegramChannel { @@ -2234,6 +2430,36 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState } } + if isEdited { + if !actions.isEmpty { + actions.insert(.separator, at: 0) + } + actions.insert(.custom(ChatReadReportContextItem(context: context, message: message, hasReadReports: false, isEdit: true, stats: MessageReadStats(reactionCount: 0, peers: [], readTimestamps: [:]), action: nil), false), at: 0) + } + + if isEdited && EditHistoryManager.shared.hasEditHistory(peerId: message.id.peerId.toInt64(), messageId: message.id.id) { + actions.append(.action(ContextMenuActionItem(text: "История", icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Edit"), color: theme.actionSheet.primaryTextColor) + }, action: { c, _ in + let editHistory = EditHistoryManager.shared.getEditHistory(peerId: message.id.peerId.toInt64(), messageId: message.id.id) + var historyText = "Оригинальные версии:\n\n" + for (index, record) in editHistory.enumerated() { + let dateString = stringForFullDate(timestamp: record.editDate, strings: context.sharedContext.currentPresentationData.with { $0 }.strings, dateTimeFormat: context.sharedContext.currentPresentationData.with { $0 }.dateTimeFormat) + historyText += "\(index + 1). \(dateString)\n\(record.text)\n\n" + } + + c?.dismiss(completion: { + let alertController = textAlertController( + context: context, + title: "История правок", + text: historyText, + actions: [TextAlertAction(type: .defaultAction, title: "OK", action: {})] + ) + controllerInteraction.presentController(alertController, nil) + }) + }))) + } + if !actions.isEmpty, case .separator = actions[0] { actions.removeFirst() } @@ -2255,7 +2481,7 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState messageEntities = attribute.entities } if let attribute = attribute as? RestrictedContentMessageAttribute { - restrictedText = attribute.platformText(platform: "ios", contentSettings: context.currentContentSettings.with { $0 }) ?? "" + restrictedText = attribute.platformText(platform: "ios", contentSettings: context.currentContentSettings.with { $0 }, chatId: message.author?.id.id._internalGetInt64Value()) ?? "" } } @@ -2692,7 +2918,6 @@ private final class ChatDeleteMessageContextItemNode: ASDisplayNode, ContextMenu private let actionSelected: (ContextMenuActionResult) -> Void private let backgroundNode: ASDisplayNode - private let highlightedBackgroundNode: ASDisplayNode private let textNode: ImmediateTextNode private let statusNode: ImmediateTextNode private let iconNode: ASImageNode @@ -2719,10 +2944,6 @@ private final class ChatDeleteMessageContextItemNode: ASDisplayNode, ContextMenu self.backgroundNode = ASDisplayNode() self.backgroundNode.isAccessibilityElement = false self.backgroundNode.backgroundColor = presentationData.theme.contextMenu.itemBackgroundColor - self.highlightedBackgroundNode = ASDisplayNode() - self.highlightedBackgroundNode.isAccessibilityElement = false - self.highlightedBackgroundNode.backgroundColor = presentationData.theme.contextMenu.itemHighlightedBackgroundColor - self.highlightedBackgroundNode.alpha = 0.0 self.textNode = ImmediateTextNode() self.textNode.isAccessibilityElement = false @@ -2752,24 +2973,12 @@ private final class ChatDeleteMessageContextItemNode: ASDisplayNode, ContextMenu super.init() self.addSubnode(self.backgroundNode) - self.addSubnode(self.highlightedBackgroundNode) self.addSubnode(self.textNode) self.addSubnode(self.statusNode) self.addSubnode(self.iconNode) self.addSubnode(self.textIconNode) self.addSubnode(self.buttonNode) - self.buttonNode.highligthedChanged = { [weak self] highligted in - guard let strongSelf = self else { - return - } - if highligted { - strongSelf.highlightedBackgroundNode.alpha = 1.0 - } else { - strongSelf.highlightedBackgroundNode.alpha = 0.0 - strongSelf.highlightedBackgroundNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.3) - } - } self.buttonNode.addTarget(self, action: #selector(self.buttonPressed), forControlEvents: .touchUpInside) } @@ -2780,14 +2989,8 @@ private final class ChatDeleteMessageContextItemNode: ASDisplayNode, ContextMenu override func didLoad() { super.didLoad() - self.pointerInteraction = PointerInteraction(node: self.buttonNode, style: .hover, willEnter: { [weak self] in - if let strongSelf = self { - strongSelf.highlightedBackgroundNode.alpha = 0.75 - } - }, willExit: { [weak self] in - if let strongSelf = self { - strongSelf.highlightedBackgroundNode.alpha = 0.0 - } + self.pointerInteraction = PointerInteraction(node: self.buttonNode, style: .hover, willEnter: { + }, willExit: { }) let timer = SwiftSignalKit.Timer(timeout: 0.5, repeat: true, completion: { [weak self] in @@ -2806,13 +3009,13 @@ private final class ChatDeleteMessageContextItemNode: ASDisplayNode, ContextMenu let subtextFont = Font.regular(self.presentationData.listsFontSize.baseDisplaySize * 13.0 / 17.0) self.statusNode.attributedText = NSAttributedString(string: stringForRemainingTime(Int32(max(0.0, self.item.timestamp - Date().timeIntervalSince1970)), strings: presentationData.strings), font: subtextFont, textColor: presentationData.theme.contextMenu.destructiveColor) - let sideInset: CGFloat = 16.0 + let sideInset: CGFloat = 18.0 let statusSize = self.statusNode.updateLayout(CGSize(width: size.width - sideInset - 32.0 + 4.0, height: .greatestFiniteMagnitude)) transition.updateFrameAdditive(node: self.statusNode, frame: CGRect(origin: CGPoint(x: self.statusNode.frame.minX, y: self.statusNode.frame.minY), size: statusSize)) } func updateLayout(constrainedWidth: CGFloat, constrainedHeight: CGFloat) -> (CGSize, (CGSize, ContainedViewLayoutTransition) -> Void) { - let sideInset: CGFloat = 16.0 + let sideInset: CGFloat = 18.0 let iconSideInset: CGFloat = 12.0 let verticalInset: CGFloat = 12.0 @@ -2833,25 +3036,23 @@ private final class ChatDeleteMessageContextItemNode: ASDisplayNode, ContextMenu return (CGSize(width: max(textSize.width, statusSize.width) + sideInset + rightTextInset, height: verticalInset * 2.0 + combinedTextHeight), { size, transition in self.validLayout = size let verticalOrigin = floor((size.height - combinedTextHeight) / 2.0) - let textFrame = CGRect(origin: CGPoint(x: sideInset, y: verticalOrigin), size: textSize) + let textFrame = CGRect(origin: CGPoint(x: sideInset + 42.0, y: verticalOrigin), size: textSize) transition.updateFrameAdditive(node: self.textNode, frame: textFrame) - transition.updateFrame(node: self.textIconNode, frame: CGRect(origin: CGPoint(x: sideInset, y: verticalOrigin + verticalSpacing + textSize.height + floorToScreenPixels((statusSize.height - textIconSize.height) / 2.0) + 1.0), size: textIconSize)) - transition.updateFrameAdditive(node: self.statusNode, frame: CGRect(origin: CGPoint(x: sideInset + textIconSize.width + 2.0, y: verticalOrigin + verticalSpacing + textSize.height), size: statusSize)) + transition.updateFrame(node: self.textIconNode, frame: CGRect(origin: CGPoint(x: sideInset + 42.0, y: verticalOrigin + verticalSpacing + textSize.height + floorToScreenPixels((statusSize.height - textIconSize.height) / 2.0) + 1.0), size: textIconSize)) + transition.updateFrameAdditive(node: self.statusNode, frame: CGRect(origin: CGPoint(x: sideInset + 42.0 + textIconSize.width + 2.0, y: verticalOrigin + verticalSpacing + textSize.height), size: statusSize)) if !iconSize.width.isZero { - transition.updateFrameAdditive(node: self.iconNode, frame: CGRect(origin: CGPoint(x: size.width - standardIconWidth - iconSideInset + floor((standardIconWidth - iconSize.width) / 2.0), y: floor((size.height - iconSize.height) / 2.0)), size: iconSize)) + transition.updateFrameAdditive(node: self.iconNode, frame: CGRect(origin: CGPoint(x: iconSideInset + 12.0, y: floor((size.height - iconSize.height) / 2.0)), size: iconSize)) } transition.updateFrame(node: self.backgroundNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) - transition.updateFrame(node: self.highlightedBackgroundNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) transition.updateFrame(node: self.buttonNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) }) } func updateTheme(presentationData: PresentationData) { self.backgroundNode.backgroundColor = presentationData.theme.contextMenu.itemBackgroundColor - self.highlightedBackgroundNode.backgroundColor = presentationData.theme.contextMenu.itemHighlightedBackgroundColor let textFont = Font.regular(presentationData.listsFontSize.baseDisplaySize) let subtextFont = Font.regular(presentationData.listsFontSize.baseDisplaySize * 13.0 / 17.0) @@ -2874,11 +3075,6 @@ private final class ChatDeleteMessageContextItemNode: ASDisplayNode, ContextMenu } func setIsHighlighted(_ value: Bool) { - if value { - self.highlightedBackgroundNode.alpha = 1.0 - } else { - self.highlightedBackgroundNode.alpha = 0.0 - } } func canBeHighlighted() -> Bool { @@ -2917,17 +3113,10 @@ private final class ChatMessageAuthorContextItemNode: ASDisplayNode, ContextMenu private let actionSelected: (ContextMenuActionResult) -> Void private let backgroundNode: ASDisplayNode - private let highlightedBackgroundNode: ASDisplayNode private let placeholderCalculationTextNode: ImmediateTextNode private let textNode: ImmediateTextNode private let shimmerNode: ShimmerEffectNode - /*private let avatarsNode: AnimatedAvatarSetNode - private let avatarsContext: AnimatedAvatarSetContext - - private let placeholderAvatarsNode: AnimatedAvatarSetNode - private let placeholderAvatarsContext: AnimatedAvatarSetContext*/ - private let buttonNode: HighlightTrackingButtonNode private var pointerInteraction: PointerInteraction? @@ -2946,10 +3135,6 @@ private final class ChatMessageAuthorContextItemNode: ASDisplayNode, ContextMenu self.backgroundNode = ASDisplayNode() self.backgroundNode.isAccessibilityElement = false self.backgroundNode.backgroundColor = presentationData.theme.contextMenu.itemBackgroundColor - self.highlightedBackgroundNode = ASDisplayNode() - self.highlightedBackgroundNode.isAccessibilityElement = false - self.highlightedBackgroundNode.backgroundColor = presentationData.theme.contextMenu.itemHighlightedBackgroundColor - self.highlightedBackgroundNode.alpha = 0.0 self.placeholderCalculationTextNode = ImmediateTextNode() self.placeholderCalculationTextNode.attributedText = NSAttributedString(string: presentationData.strings.Conversation_ContextMenuSeen(11), font: textFont, textColor: presentationData.theme.contextMenu.primaryColor) @@ -2970,33 +3155,13 @@ private final class ChatMessageAuthorContextItemNode: ASDisplayNode, ContextMenu self.buttonNode.isAccessibilityElement = true self.buttonNode.accessibilityLabel = presentationData.strings.VoiceChat_StopRecording - /*self.avatarsNode = AnimatedAvatarSetNode() - self.avatarsContext = AnimatedAvatarSetContext() - - self.placeholderAvatarsNode = AnimatedAvatarSetNode() - self.placeholderAvatarsContext = AnimatedAvatarSetContext()*/ - super.init() self.addSubnode(self.backgroundNode) - self.addSubnode(self.highlightedBackgroundNode) self.addSubnode(self.shimmerNode) self.addSubnode(self.textNode) - /*self.addSubnode(self.avatarsNode) - self.addSubnode(self.placeholderAvatarsNode)*/ self.addSubnode(self.buttonNode) - self.buttonNode.highligthedChanged = { [weak self] highligted in - guard let strongSelf = self else { - return - } - if highligted { - strongSelf.highlightedBackgroundNode.alpha = 1.0 - } else { - strongSelf.highlightedBackgroundNode.alpha = 0.0 - strongSelf.highlightedBackgroundNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.3) - } - } self.buttonNode.addTarget(self, action: #selector(self.buttonPressed), forControlEvents: .touchUpInside) self.buttonNode.isUserInteractionEnabled = false @@ -3019,14 +3184,8 @@ private final class ChatMessageAuthorContextItemNode: ASDisplayNode, ContextMenu override func didLoad() { super.didLoad() - self.pointerInteraction = PointerInteraction(node: self.buttonNode, style: .hover, willEnter: { [weak self] in - if let strongSelf = self { - strongSelf.highlightedBackgroundNode.alpha = 0.75 - } - }, willExit: { [weak self] in - if let strongSelf = self { - strongSelf.highlightedBackgroundNode.alpha = 0.0 - } + self.pointerInteraction = PointerInteraction(node: self.buttonNode, style: .hover, willEnter: { + }, willExit: { }) } @@ -3046,7 +3205,7 @@ private final class ChatMessageAuthorContextItemNode: ASDisplayNode, ContextMenu } func updateLayout(constrainedWidth: CGFloat, constrainedHeight: CGFloat) -> (CGSize, (CGSize, ContainedViewLayoutTransition) -> Void) { - let sideInset: CGFloat = 14.0 + let sideInset: CGFloat = 18.0 let verticalInset: CGFloat let rightTextInset: CGFloat //let avatarsWidth: CGFloat = 32.0 @@ -3112,27 +3271,7 @@ private final class ChatMessageAuthorContextItemNode: ASDisplayNode, ContextMenu self.shimmerNode.updateAbsoluteRect(self.shimmerNode.frame, within: size) transition.updateAlpha(node: self.shimmerNode, alpha: self.peer == nil ? 1.0 : 0.0) - /*let avatarsContent: AnimatedAvatarSetContext.Content - let placeholderAvatarsContent: AnimatedAvatarSetContext.Content - - var avatarsPeers: [EnginePeer] = [] - if let peer = self.peer { - avatarsPeers = [peer] - } - avatarsContent = self.avatarsContext.update(peers: avatarsPeers, animated: false) - - placeholderAvatarsContent = self.avatarsContext.updatePlaceholder(color: shimmeringForegroundColor, count: 1, animated: false) - - let avatarsSize = self.avatarsNode.update(context: self.item.context, content: avatarsContent, itemSize: CGSize(width: 24.0, height: 24.0), customSpacing: 10.0, animated: false, synchronousLoad: true) - self.avatarsNode.frame = CGRect(origin: CGPoint(x: sideInset, y: floor((size.height - avatarsSize.height) / 2.0)), size: avatarsSize) - transition.updateAlpha(node: self.avatarsNode, alpha: self.peer == nil ? 0.0 : 1.0) - - let placeholderAvatarsSize = self.placeholderAvatarsNode.update(context: self.item.context, content: placeholderAvatarsContent, itemSize: CGSize(width: 24.0, height: 24.0), customSpacing: 10.0, animated: false, synchronousLoad: true) - self.placeholderAvatarsNode.frame = CGRect(origin: CGPoint(x: self.avatarsNode.frame.minX, y: floor((size.height - placeholderAvatarsSize.height) / 2.0)), size: placeholderAvatarsSize) - transition.updateAlpha(node: self.placeholderAvatarsNode, alpha: self.peer == nil ? 1.0 : 0.0)*/ - transition.updateFrame(node: self.backgroundNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) - transition.updateFrame(node: self.highlightedBackgroundNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) transition.updateFrame(node: self.buttonNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) }) } @@ -3141,7 +3280,6 @@ private final class ChatMessageAuthorContextItemNode: ASDisplayNode, ContextMenu self.presentationData = presentationData self.backgroundNode.backgroundColor = presentationData.theme.contextMenu.itemBackgroundColor - self.highlightedBackgroundNode.backgroundColor = presentationData.theme.contextMenu.itemHighlightedBackgroundColor let textFont = Font.regular(presentationData.listsFontSize.baseDisplaySize) @@ -3189,11 +3327,6 @@ private final class ChatMessageAuthorContextItemNode: ASDisplayNode, ContextMenu } func setIsHighlighted(_ value: Bool) { - if value { - self.highlightedBackgroundNode.alpha = 1.0 - } else { - self.highlightedBackgroundNode.alpha = 0.0 - } } func actionNode(at point: CGPoint) -> ContextActionNodeProtocol { @@ -3230,7 +3363,6 @@ private final class ChatReadReportContextItemNode: ASDisplayNode, ContextMenuCus private let actionSelected: (ContextMenuActionResult) -> Void private let backgroundNode: ASDisplayNode - private let highlightedBackgroundNode: ASDisplayNode private let placeholderCalculationTextNode: ImmediateTextNode private let textNode: ImmediateTextNode private var badgeBackground: UIImageView? @@ -3267,10 +3399,6 @@ private final class ChatReadReportContextItemNode: ASDisplayNode, ContextMenuCus self.backgroundNode = ASDisplayNode() self.backgroundNode.isAccessibilityElement = false self.backgroundNode.backgroundColor = presentationData.theme.contextMenu.itemBackgroundColor - self.highlightedBackgroundNode = ASDisplayNode() - self.highlightedBackgroundNode.isAccessibilityElement = false - self.highlightedBackgroundNode.backgroundColor = presentationData.theme.contextMenu.itemHighlightedBackgroundColor - self.highlightedBackgroundNode.alpha = 0.0 self.placeholderCalculationTextNode = ImmediateTextNode() self.placeholderCalculationTextNode.attributedText = NSAttributedString(string: presentationData.strings.Conversation_ContextMenuSeen(11), font: textFont, textColor: presentationData.theme.contextMenu.primaryColor) @@ -3311,7 +3439,6 @@ private final class ChatReadReportContextItemNode: ASDisplayNode, ContextMenuCus super.init() self.addSubnode(self.backgroundNode) - self.addSubnode(self.highlightedBackgroundNode) self.addSubnode(self.shimmerNode) self.addSubnode(self.textNode) self.addSubnode(self.iconNode) @@ -3319,17 +3446,6 @@ private final class ChatReadReportContextItemNode: ASDisplayNode, ContextMenuCus self.addSubnode(self.placeholderAvatarsNode) self.addSubnode(self.buttonNode) - self.buttonNode.highligthedChanged = { [weak self] highligted in - guard let strongSelf = self else { - return - } - if highligted { - strongSelf.highlightedBackgroundNode.alpha = 1.0 - } else { - strongSelf.highlightedBackgroundNode.alpha = 0.0 - strongSelf.highlightedBackgroundNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.3) - } - } self.buttonNode.addTarget(self, action: #selector(self.buttonPressed), forControlEvents: .touchUpInside) var reactionCount = 0 @@ -3424,14 +3540,8 @@ private final class ChatReadReportContextItemNode: ASDisplayNode, ContextMenuCus override func didLoad() { super.didLoad() - self.pointerInteraction = PointerInteraction(node: self.buttonNode, style: .hover, willEnter: { [weak self] in - if let strongSelf = self { - strongSelf.highlightedBackgroundNode.alpha = 0.75 - } - }, willExit: { [weak self] in - if let strongSelf = self { - strongSelf.highlightedBackgroundNode.alpha = 0.0 - } + self.pointerInteraction = PointerInteraction(node: self.buttonNode, style: .hover, willEnter: { + }, willExit: { }) } @@ -3455,7 +3565,7 @@ private final class ChatReadReportContextItemNode: ASDisplayNode, ContextMenuCus } func updateLayout(constrainedWidth: CGFloat, constrainedHeight: CGFloat) -> (CGSize, (CGSize, ContainedViewLayoutTransition) -> Void) { - let sideInset: CGFloat = 14.0 + let sideInset: CGFloat = 18.0 let verticalInset: CGFloat let rightTextInset: CGFloat @@ -3463,7 +3573,7 @@ private final class ChatReadReportContextItemNode: ASDisplayNode, ContextMenuCus verticalInset = 7.0 rightTextInset = 8.0 } else { - verticalInset = 12.0 + verticalInset = 11.0 rightTextInset = sideInset + 36.0 } @@ -3570,7 +3680,11 @@ private final class ChatReadReportContextItemNode: ASDisplayNode, ContextMenuCus } } } else { - self.textNode.attributedText = NSAttributedString(string: " ", font: textFont, textColor: self.presentationData.theme.contextMenu.primaryColor) + var actualFont = textFont + if self.item.message.id.peerId.namespace == Namespaces.Peer.CloudUser { + actualFont = Font.regular(floor(self.presentationData.listsFontSize.baseDisplaySize * 0.8)) + } + self.textNode.attributedText = NSAttributedString(string: " ", font: actualFont, textColor: self.presentationData.theme.contextMenu.primaryColor) } let textSize = self.textNode.updateLayout(CGSize(width: calculatedWidth - sideInset - rightTextInset - iconSize.width - 4.0, height: .greatestFiniteMagnitude)) @@ -3620,11 +3734,7 @@ private final class ChatReadReportContextItemNode: ASDisplayNode, ContextMenuCus let positionTransition: ContainedViewLayoutTransition = animatePositions ? transition : .immediate let verticalOrigin = floor((size.height - combinedTextHeight) / 2.0) - var textFrame = CGRect(origin: CGPoint(x: sideInset + iconSize.width + 4.0, y: verticalOrigin), size: textSize) - - if self.item.isEdit { - textFrame.origin.x -= 2.0 - } + let textFrame = CGRect(origin: CGPoint(x: sideInset + 42.0, y: verticalOrigin), size: textSize) positionTransition.updateFrameAdditive(node: self.textNode, frame: textFrame) transition.updateAlpha(node: self.textNode, alpha: self.currentStats == nil ? 0.0 : 1.0) @@ -3669,9 +3779,9 @@ private final class ChatReadReportContextItemNode: ASDisplayNode, ContextMenuCus transition.updateAlpha(node: self.shimmerNode, alpha: self.currentStats == nil ? 1.0 : 0.0) if !iconSize.width.isZero { - var iconFrame = CGRect(origin: CGPoint(x: sideInset + 1.0, y: floor((size.height - iconSize.height) / 2.0)), size: iconSize) + var iconFrame = CGRect(origin: CGPoint(x: sideInset + 6.0, y: floor((size.height - iconSize.height) / 2.0)), size: iconSize) if self.item.isEdit { - iconFrame.origin.x -= 2.0 + iconFrame.origin.x += 1.0 } transition.updateFrameAdditive(node: self.iconNode, frame: iconFrame) } @@ -3708,15 +3818,14 @@ private final class ChatReadReportContextItemNode: ASDisplayNode, ContextMenuCus } let avatarsSize = self.avatarsNode.update(context: self.item.context, content: avatarsContent, itemSize: CGSize(width: 24.0, height: 24.0), customSpacing: 10.0, animated: false, synchronousLoad: true) - self.avatarsNode.frame = CGRect(origin: CGPoint(x: floorToScreenPixels(size.width - sideInset - 2.0 - avatarsSize.width), y: floor((size.height - avatarsSize.height) / 2.0)), size: avatarsSize) + self.avatarsNode.frame = CGRect(origin: CGPoint(x: floorToScreenPixels(size.width - sideInset - 4.0 - avatarsSize.width), y: floor((size.height - avatarsSize.height) / 2.0)), size: avatarsSize) transition.updateAlpha(node: self.avatarsNode, alpha: self.currentStats == nil ? 0.0 : 1.0) let placeholderAvatarsSize = self.placeholderAvatarsNode.update(context: self.item.context, content: placeholderAvatarsContent, itemSize: CGSize(width: 24.0, height: 24.0), customSpacing: 10.0, animated: false, synchronousLoad: true) - self.placeholderAvatarsNode.frame = CGRect(origin: CGPoint(x: size.width - sideInset - 2.0 - placeholderAvatarsSize.width, y: floor((size.height - placeholderAvatarsSize.height) / 2.0)), size: placeholderAvatarsSize) + self.placeholderAvatarsNode.frame = CGRect(origin: CGPoint(x: size.width - sideInset - 4.0 - placeholderAvatarsSize.width, y: floor((size.height - placeholderAvatarsSize.height) / 2.0)), size: placeholderAvatarsSize) transition.updateAlpha(node: self.placeholderAvatarsNode, alpha: self.currentStats == nil ? 1.0 : 0.0) transition.updateFrame(node: self.backgroundNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) - transition.updateFrame(node: self.highlightedBackgroundNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) transition.updateFrame(node: self.buttonNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height))) }) } @@ -3725,7 +3834,6 @@ private final class ChatReadReportContextItemNode: ASDisplayNode, ContextMenuCus self.presentationData = presentationData self.backgroundNode.backgroundColor = presentationData.theme.contextMenu.itemBackgroundColor - self.highlightedBackgroundNode.backgroundColor = presentationData.theme.contextMenu.itemHighlightedBackgroundColor let textFont = Font.regular(presentationData.listsFontSize.baseDisplaySize) @@ -3767,6 +3875,15 @@ private final class ChatReadReportContextItemNode: ASDisplayNode, ContextMenuCus if self.item.action == nil { return false } + if self.item.isEdit { + return false + } + if self.item.message.id.peerId.namespace == Namespaces.Peer.CloudUser { + if let stats = self.currentStats, stats.peers.isEmpty { + } else { + return false + } + } var reactionCount = 0 for reaction in mergedMessageReactionsAndPeers(accountPeerId: self.item.context.account.peerId, accountPeer: nil, message: self.item.message).reactions { reactionCount += Int(reaction.count) @@ -3781,11 +3898,6 @@ private final class ChatReadReportContextItemNode: ASDisplayNode, ContextMenuCus } func setIsHighlighted(_ value: Bool) { - if value { - self.highlightedBackgroundNode.alpha = 1.0 - } else { - self.highlightedBackgroundNode.alpha = 0.0 - } } func actionNode(at point: CGPoint) -> ContextActionNodeProtocol { @@ -3905,7 +4017,7 @@ private final class ChatRateTranscriptionContextItemNode: ASDisplayNode, Context } func updateLayout(constrainedWidth: CGFloat, constrainedHeight: CGFloat) -> (CGSize, (CGSize, ContainedViewLayoutTransition) -> Void) { - let sideInset: CGFloat = 14.0 + let sideInset: CGFloat = 18.0 let verticalInset: CGFloat = 9.0 let calculatedWidth = min(constrainedWidth, 250.0) @@ -3969,42 +4081,36 @@ private final class ChatRateTranscriptionContextItemNode: ASDisplayNode, Context } } -// MARK: - Ghostgram: Video to Circle Conversion Helper private func convertVideoToCircleAndSend( context: AccountContext, message: Message, file: TelegramMediaFile, controllerInteraction: ChatControllerInteraction ) { - // Show progress controllerInteraction.displayUndo(.info(title: nil, text: "Конвертация в кружок...", timeout: 5.0, customUndoText: nil)) - - // Get video file path + let resourcePath = context.account.postbox.mediaBox.completedResourcePath(file.resource) - guard let videoPath = resourcePath, FileManager.default.fileExists(atPath: videoPath) else { controllerInteraction.displayUndo(.info(title: "Ошибка", text: "Видео ещё не загружено. Откройте его для загрузки.", timeout: nil, customUndoText: nil)) return } - - // Get video dimensions - var videoDimensions = CGSize(width: 240, height: 240) + + var videoDimensions = CGSize(width: 240.0, height: 240.0) for attr in file.attributes { - switch attr { - case let .Video(_, size, _, _, _, _): + if case let .Video(_, size, _, _, _, _) = attr { videoDimensions = size.cgSize - default: break } } - - // Create square crop (center crop to 1:1 aspect ratio) + let minDim = min(videoDimensions.width, videoDimensions.height) - let cropX = (videoDimensions.width - minDim) / 2 - let cropY = (videoDimensions.height - minDim) / 2 - let cropRect = CGRect(x: cropX, y: cropY, width: minDim, height: minDim) - - // Create adjustments for video message format + let cropRect = CGRect( + x: (videoDimensions.width - minDim) / 2.0, + y: (videoDimensions.height - minDim) / 2.0, + width: minDim, + height: minDim + ) + let adjustments = TGVideoEditAdjustments( originalSize: videoDimensions, cropRect: cropRect, @@ -4019,37 +4125,23 @@ private func convertVideoToCircleAndSend( sendAsGif: false, preset: TGMediaVideoConversionPresetVideoMessage ) - - // Generate output path - let outputPath = NSTemporaryDirectory() + "circle_\(Int64.random(in: Int64.min...Int64.max)).mp4" - - print("[Ghostgram Circle] Starting conversion from: \(videoPath)") - print("[Ghostgram Circle] Output path: \(outputPath)") - print("[Ghostgram Circle] Video dimensions: \(videoDimensions)") - - // Start conversion in background + + let outputPath = NSTemporaryDirectory() + "circle_\(Int64.random(in: Int64.min ... Int64.max)).mp4" + DispatchQueue.global(qos: .userInitiated).async { - // AVFoundation needs file extension to detect format - // Postbox stores files without extension, so copy to temp with .mp4 - let tempSourcePath = NSTemporaryDirectory() + "source_\(Int64.random(in: Int64.min...Int64.max)).mp4" - + let tempSourcePath = NSTemporaryDirectory() + "source_\(Int64.random(in: Int64.min ... Int64.max)).mp4" do { try FileManager.default.copyItem(atPath: videoPath, toPath: tempSourcePath) - print("[Ghostgram Circle] Copied to temp with extension: \(tempSourcePath)") } catch { - print("[Ghostgram Circle] ERROR: Failed to copy file: \(error)") DispatchQueue.main.async { controllerInteraction.displayUndo(.info(title: "Ошибка", text: "Не удалось подготовить видео", timeout: nil, customUndoText: nil)) } return } - + let videoUrl = URL(fileURLWithPath: tempSourcePath) let avAsset = AVURLAsset(url: videoUrl) - - print("[Ghostgram Circle] Created AVAsset, starting conversion...") - - // Use TGMediaVideoConverter with correct signature + guard let signal = TGMediaVideoConverter.convert( avAsset, adjustments: adjustments, @@ -4057,39 +4149,28 @@ private func convertVideoToCircleAndSend( watcher: nil, entityRenderer: nil ) else { - print("[Ghostgram Circle] ERROR: Failed to create conversion signal!") DispatchQueue.main.async { controllerInteraction.displayUndo(.info(title: "Ошибка", text: "Не удалось запустить конвертацию", timeout: nil, customUndoText: nil)) } return } - - print("[Ghostgram Circle] Conversion signal created, starting...") - - // Use SBlockDisposable instead to keep signal alive + let disposable = signal.start(next: { result in - print("[Ghostgram Circle] Got result: \(String(describing: result))") - - guard let result = result as? TGMediaVideoConversionResult, - let resultUrl = result.fileURL else { - print("[Ghostgram Circle] ERROR: Result is not TGMediaVideoConversionResult or no fileURL") + guard let result = result as? TGMediaVideoConversionResult, let resultUrl = result.fileURL else { DispatchQueue.main.async { controllerInteraction.displayUndo(.info(title: "Ошибка", text: "Не удалось конвертировать видео", timeout: nil, customUndoText: nil)) } return } - - print("[Ghostgram Circle] Conversion SUCCESS! File: \(resultUrl.path)") - + let finalDuration = result.duration let finalDimensions = result.dimensions - + DispatchQueue.main.async { - // Create preview image var previewRepresentations: [TelegramMediaImageRepresentation] = [] if let previewImage = result.coverImage { - let resource = LocalFileMediaResource(fileId: Int64.random(in: Int64.min...Int64.max)) - let thumbnailSize = CGSize(width: 240, height: 240) + let resource = LocalFileMediaResource(fileId: Int64.random(in: Int64.min ... Int64.max)) + let thumbnailSize = CGSize(width: 240.0, height: 240.0) if let thumbnailImage = TGScaleImageToPixelSize(previewImage, thumbnailSize), let thumbnailData = thumbnailImage.jpegData(compressionQuality: 0.4) { context.account.postbox.mediaBox.storeResourceData(resource.id, data: thumbnailData) @@ -4103,17 +4184,15 @@ private func convertVideoToCircleAndSend( )) } } - - // Create local resource for converted video + let videoResource = LocalFileVideoMediaResource( - randomId: Int64.random(in: Int64.min...Int64.max), + randomId: Int64.random(in: Int64.min ... Int64.max), path: resultUrl.path, adjustments: nil ) - - // Create TelegramMediaFile with instantRoundVideo flag + let media = TelegramMediaFile( - fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: Int64.random(in: Int64.min...Int64.max)), + fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: Int64.random(in: Int64.min ... Int64.max)), partialReference: nil, resource: videoResource, previewRepresentations: previewRepresentations, @@ -4127,8 +4206,7 @@ private func convertVideoToCircleAndSend( ], alternativeRepresentations: [] ) - - // Create message + let outMessage: EnqueueMessage = .message( text: "", attributes: [], @@ -4141,49 +4219,42 @@ private func convertVideoToCircleAndSend( correlationId: nil, bubbleUpEmojiOrStickersets: [] ) - - print("[Ghostgram Circle] Sending message...") - - // Send message + let _ = enqueueMessages(account: context.account, peerId: message.id.peerId, messages: [outMessage]).start() - - // Show success controllerInteraction.displayUndo(.succeed(text: "Кружок отправлен!", timeout: nil, customUndoText: nil)) } - }, error: { error in - print("[Ghostgram Circle] ERROR in conversion: \(String(describing: error))") + }, error: { _ in DispatchQueue.main.async { controllerInteraction.displayUndo(.info(title: "Ошибка", text: "Не удалось конвертировать видео", timeout: nil, customUndoText: nil)) } - }, completed: { - print("[Ghostgram Circle] Conversion completed callback!") }) - - // Keep disposable alive - hold reference until task completes - // This is a workaround for ObjC signal disposal + DispatchQueue.main.async { CircleConversionHolder.shared.add(disposable) } } } -// Helper class to hold conversion disposables private final class CircleConversionHolder { static let shared = CircleConversionHolder() private var disposables: [AnyObject] = [] private let lock = NSLock() - + func add(_ disposable: AnyObject?) { - guard let disposable = disposable else { return } + guard let disposable else { + return + } lock.lock() disposables.append(disposable) lock.unlock() - - // Auto-cleanup after 2 minutes - DispatchQueue.main.asyncAfter(deadline: .now() + 120) { [weak self] in - self?.lock.lock() - self?.disposables.removeAll { $0 === disposable } - self?.lock.unlock() + + DispatchQueue.main.asyncAfter(deadline: .now() + 120.0) { [weak self] in + guard let self else { + return + } + self.lock.lock() + self.disposables.removeAll { $0 === disposable } + self.lock.unlock() } } } diff --git a/submodules/TelegramUI/Sources/ChatPinnedMessageTitlePanelNode.swift b/submodules/TelegramUI/Sources/ChatPinnedMessageTitlePanelNode.swift index 5f5f9f17..d0be4aa6 100644 --- a/submodules/TelegramUI/Sources/ChatPinnedMessageTitlePanelNode.swift +++ b/submodules/TelegramUI/Sources/ChatPinnedMessageTitlePanelNode.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import Display @@ -494,8 +495,8 @@ final class ChatPinnedMessageTitlePanelNode: ChatTitleAccessoryPanelNode { } if currentTranslateToLanguageUpdated || messageUpdated, let message = interfaceState.pinnedMessage?.message { - if let translation = message.attributes.first(where: { $0 is TranslationMessageAttribute }) as? TranslationMessageAttribute, translation.toLang == translateToLanguage?.toLang { - } else if let translateToLanguage { + if let translation = message.attributes.first(where: { $0 is TranslationMessageAttribute }) as? TranslationMessageAttribute, translation.toLang == translateToLanguage?.toLang || translation.toLang.hasPrefix("\(translateToLanguage?.toLang ?? "")-") /* MARK: Swiftgram */ { + } else if let translateToLanguage { self.translationDisposable.set(translateMessageIds(context: self.context, messageIds: [message.id], fromLang: translateToLanguage.fromLang, toLang: translateToLanguage.toLang).startStrict()) } } diff --git a/submodules/TelegramUI/Sources/ChatTranslationPanelNode.swift b/submodules/TelegramUI/Sources/ChatTranslationPanelNode.swift index 1f4ea934..9b361fbf 100644 --- a/submodules/TelegramUI/Sources/ChatTranslationPanelNode.swift +++ b/submodules/TelegramUI/Sources/ChatTranslationPanelNode.swift @@ -18,6 +18,17 @@ import TranslateUI import TelegramUIPreferences import TelegramNotices import PremiumUI +import SGSimpleSettings + +private func sgChatTranslationAvailable(isPremium: Bool, peer: Peer?) -> Bool { + if isPremium || SGSimpleSettings.shared.translationBackendEnum != .default { + return true + } + if let channel = peer as? TelegramChannel, channel.flags.contains(.autoTranslateEnabled) { + return true + } + return false +} final class ChatTranslationPanelNode: ASDisplayNode { private let context: AccountContext @@ -183,11 +194,7 @@ final class ChatTranslationPanelNode: ASDisplayNode { @objc private func closePressed() { let isPremium = self.chatInterfaceState?.isPremium ?? false - - var translationAvailable = isPremium - if let channel = self.chatInterfaceState?.renderedPeer?.chatMainPeer as? TelegramChannel, channel.flags.contains(.autoTranslateEnabled) { - translationAvailable = true - } + let translationAvailable = sgChatTranslationAvailable(isPremium: isPremium, peer: self.chatInterfaceState?.renderedPeer?.chatMainPeer) if translationAvailable { self.interfaceInteraction?.hideTranslationPanel() @@ -202,11 +209,7 @@ final class ChatTranslationPanelNode: ASDisplayNode { } let isPremium = self.chatInterfaceState?.isPremium ?? false - - var translationAvailable = isPremium - if let channel = self.chatInterfaceState?.renderedPeer?.chatMainPeer as? TelegramChannel, channel.flags.contains(.autoTranslateEnabled) { - translationAvailable = true - } + let translationAvailable = sgChatTranslationAvailable(isPremium: isPremium, peer: self.chatInterfaceState?.renderedPeer?.chatMainPeer) if translationAvailable { self.interfaceInteraction?.toggleTranslation(translationState.isEnabled ? .original : .translated) diff --git a/submodules/TelegramUI/Sources/OpenChatMessage.swift b/submodules/TelegramUI/Sources/OpenChatMessage.swift index de807438..29323b0f 100644 --- a/submodules/TelegramUI/Sources/OpenChatMessage.swift +++ b/submodules/TelegramUI/Sources/OpenChatMessage.swift @@ -1,4 +1,5 @@ import Foundation +import SGSimpleSettings import Display import AsyncDisplayKit import Postbox diff --git a/submodules/TelegramUI/Sources/OpenResolvedUrl.swift b/submodules/TelegramUI/Sources/OpenResolvedUrl.swift index 0a99f2c9..ddbb649b 100644 --- a/submodules/TelegramUI/Sources/OpenResolvedUrl.swift +++ b/submodules/TelegramUI/Sources/OpenResolvedUrl.swift @@ -757,7 +757,7 @@ func openResolvedUrlImpl( case let .settings(section): dismissInput() switch section { - case .theme: + case .legacy(.theme): if let navigationController = navigationController { let controller = themeSettingsController(context: context) controller.navigationPresentation = .modal @@ -768,7 +768,7 @@ func openResolvedUrlImpl( navigationController.setViewControllers(controllers, animated: true) } - case .devices: + case .legacy(.devices): if let navigationController = navigationController { let activeSessions = deferred { () -> Signal<(ActiveSessionsContext, Int, WebSessionsContext), NoError> in let activeSessionsContext = context.engine.privacy.activeSessions() @@ -798,15 +798,13 @@ func openResolvedUrlImpl( navigationController.setViewControllers(controllers, animated: true) }) } - case .autoremoveMessages: + case .legacy(.autoremoveMessages): let _ = (context.engine.privacy.requestAccountPrivacySettings() |> take(1) |> deliverOnMainQueue).start(next: { settings in navigationController?.pushViewController(globalAutoremoveScreen(context: context, initialValue: settings.messageAutoremoveTimeout ?? 0, updated: { _ in }), animated: true) }) - case .twoStepAuth: - break - case .enableLog: + case .legacy(.enableLog): if let navigationController = navigationController { let _ = updateLoggingSettings(accountManager: context.sharedContext.accountManager, { $0.withUpdatedLogToFile(true) @@ -819,7 +817,7 @@ func openResolvedUrlImpl( navigationController.setViewControllers(controllers, animated: true) } } - case .phonePrivacy: + case .legacy(.phonePrivacy): let privacySignal = context.engine.privacy.requestAccountPrivacySettings() let _ = (privacySignal |> deliverOnMainQueue).start(next: { info in @@ -831,11 +829,13 @@ func openResolvedUrlImpl( navigationController.pushViewController(controller) } }) - case .loginEmail: + case .legacy(.loginEmail): if let navigationController { let controller = loginEmailSetupController(context: context, blocking: false, emailPattern: nil, navigationController: navigationController, completion: {}, dismiss: {}) navigationController.pushViewController(controller) } + case .path(_): + break } case let .premiumOffer(reference): dismissInput() @@ -851,7 +851,7 @@ func openResolvedUrlImpl( } case let .starsTopup(amount, purpose): dismissInput() - if let starsContext = context.starsContext { + if let starsContext = context.starsContext, let amount { let proceed = { let controller = context.sharedContext.makeStarsPurchaseScreen(context: context, starsContext: starsContext, options: [], purpose: .topUp(requiredStars: amount, purpose: purpose), targetPeerId: nil, customTheme: nil, completion: { _ in }) if let navigationController = navigationController { @@ -1480,8 +1480,8 @@ func openResolvedUrlImpl( present(textAlertController(context: context, updatedPresentationData: updatedPresentationData, title: nil, text: presentationData.strings.Login_UnknownError, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), nil) } }) - case let .collectible(gift): - if let gift { + case let .collectible(collectible): + if case let .gift(gift) = collectible { var dismissedImpl: (() -> Void)? if let storyProgressPauseContext = contentContext as? StoryProgressPauseContext { let updateExternalController = storyProgressPauseContext.update @@ -1628,5 +1628,17 @@ func openResolvedUrlImpl( navigationController?.pushViewController(controller) } } + case let .unknownDeepLink(path): + present(textAlertController(context: context, updatedPresentationData: updatedPresentationData, title: nil, text: path, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), nil) + case let .oauth(url): + context.sharedContext.openExternalUrl(context: context, urlContext: urlContext, url: url, forceExternal: true, presentationData: presentationData, navigationController: navigationController, dismissInput: dismissInput) + case .chats(_): + dismissInput() + case .compose(_): + dismissInput() + case .postStory(_): + dismissInput() + case .contacts(_): + dismissInput() } } diff --git a/submodules/TelegramUI/Sources/OpenUrl.swift b/submodules/TelegramUI/Sources/OpenUrl.swift index bc32dcc7..17dec9a3 100644 --- a/submodules/TelegramUI/Sources/OpenUrl.swift +++ b/submodules/TelegramUI/Sources/OpenUrl.swift @@ -1,3 +1,12 @@ +import SGLogging +import SGAPIWebSettings +import SGConfig +import SGSettingsUI +import SGDebugUI +import SFSafariViewControllerPlus +import UndoUI +// +import ContactListUI import Foundation import Display import SafariServices @@ -36,71 +45,71 @@ public func parseProxyUrl(sharedContext: SharedAccountContext, url: URL) -> Prox } } +public func isOAuthUrl(_ url: URL) -> Bool { + guard let query = url.query, let params = QueryParameters(query), ["oauth", "resolve"].contains(url.host) else { + return false + } + + let domain = params["domain"] + let startApp = params["startapp"] + let token = params["token"] + + var valid = false + if url.host == "resolve" { + if domain == "oauth", let _ = startApp { + valid = true + } + } else { + if let _ = token { + valid = true + } + } + + return valid +} + public func parseSecureIdUrl(_ url: URL) -> ParsedSecureIdUrl? { - guard let query = url.query else { + guard let query = url.query, let params = QueryParameters(query), ["passport", "resolve"].contains(url.host) else { return nil } - if url.host == "passport" || url.host == "resolve" { - if let components = URLComponents(string: "/?" + query) { - var domain: String? - var botId: Int64? - var scope: String? - var publicKey: String? - var callbackUrl: String? - var opaquePayload = Data() - var opaqueNonce = Data() - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "domain" { - domain = value - } else if queryItem.name == "bot_id" { - botId = Int64(value) - } else if queryItem.name == "scope" { - scope = value - } else if queryItem.name == "public_key" { - publicKey = value - } else if queryItem.name == "callback_url" { - callbackUrl = value - } else if queryItem.name == "payload" { - if let data = value.data(using: .utf8) { - opaquePayload = data - } - } else if queryItem.name == "nonce" { - if let data = value.data(using: .utf8) { - opaqueNonce = data - } - } - } + let domain = params["domain"] + let botId = params["bot_id"].flatMap(Int64.init) + let scope = params["scope"] + let publicKey = params["public_key"] + let callbackUrl = params["callback_url"] + var opaquePayload = Data() + var opaqueNonce = Data() + if let payloadValue = params["payload"], let data = payloadValue.data(using: .utf8) { + opaquePayload = data + } + if let nonceValue = params["nonce"], let data = nonceValue.data(using: .utf8) { + opaqueNonce = data + } + + let valid: Bool + if url.host == "resolve" { + if domain == "telegrampassport" { + valid = true + } else { + valid = false + } + } else { + valid = true + } + + if valid { + if let botId = botId, let scope = scope, let publicKey = publicKey, let callbackUrl = callbackUrl { + if scope.hasPrefix("{") && scope.hasSuffix("}") { + opaquePayload = Data() + if opaqueNonce.isEmpty { + return nil } + } else if opaquePayload.isEmpty { + return nil } - let valid: Bool - if url.host == "resolve" { - if domain == "telegrampassport" { - valid = true - } else { - valid = false - } - } else { - valid = true - } - - if valid { - if let botId = botId, let scope = scope, let publicKey = publicKey, let callbackUrl = callbackUrl { - if scope.hasPrefix("{") && scope.hasSuffix("}") { - opaquePayload = Data() - if opaqueNonce.isEmpty { - return nil - } - } else if opaquePayload.isEmpty { - return nil - } - - return ParsedSecureIdUrl(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(botId)), scope: scope, publicKey: publicKey, callbackUrl: callbackUrl, opaquePayload: opaquePayload, opaqueNonce: opaqueNonce) - } - } + return ParsedSecureIdUrl(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(botId)), scope: scope, publicKey: publicKey, callbackUrl: callbackUrl, opaquePayload: opaquePayload, opaqueNonce: opaqueNonce) } } @@ -116,10 +125,10 @@ public func parseConfirmationCodeUrl(sharedContext: SharedAccountContext, url: U if url.scheme == "tg" { if let host = url.host, let query = url.query, let parsedUrl = parseInternalUrl(sharedContext: sharedContext, context: nil, query: host + "?" + query) { switch parsedUrl { - case let .confirmationCode(code): - return code - default: - break + case let .confirmationCode(code): + return code + default: + break } } } @@ -139,6 +148,241 @@ func formattedConfirmationCode(_ code: Int) -> String { return result } +private func canonicalExternalUrl(from url: String) -> URL? { + var urlWithScheme = url + if !url.contains("://") && !url.hasPrefix("mailto:") { + urlWithScheme = "http://" + url + } + if let parsed = URL(string: urlWithScheme) { + return parsed + } else if let encoded = (urlWithScheme as NSString).addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) { + return URL(string: encoded) + } + return nil +} + +private func makeResolvedUrlHandler( + context: AccountContext, + presentationData: PresentationData, + navigationController: NavigationController?, + dismissInput: @escaping () -> Void +) -> (ResolvedUrl) -> Void { + return { resolved in + if case let .externalUrl(value) = resolved { + context.sharedContext.applicationBindings.openUrl(value) + } else { + context.sharedContext.openResolvedUrl( + resolved, + context: context, + urlContext: .generic, + navigationController: navigationController, + forceExternal: false, + forceUpdate: false, + openPeer: { peer, navigation in + switch navigation { + case .info: + if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { + context.sharedContext.applicationBindings.dismissNativeController() + navigationController?.pushViewController(infoController) + } + case let .chat(textInputState, subject, peekData): + context.sharedContext.applicationBindings.dismissNativeController() + if let navigationController { + context.sharedContext.navigateToChatController(NavigateToChatControllerParams(navigationController: navigationController, context: context, chatLocation: .peer(peer), subject: subject, updateTextInputState: !peer.id.isGroupOrChannel ? textInputState : nil, peekData: peekData)) + } + case let .withBotStartPayload(payload): + context.sharedContext.applicationBindings.dismissNativeController() + if let navigationController { + context.sharedContext.navigateToChatController(NavigateToChatControllerParams(navigationController: navigationController, context: context, chatLocation: .peer(peer), botStart: payload)) + } + case let .withAttachBot(attachBotStart): + context.sharedContext.applicationBindings.dismissNativeController() + if let navigationController { + context.sharedContext.navigateToChatController(NavigateToChatControllerParams(navigationController: navigationController, context: context, chatLocation: .peer(peer), attachBotStart: attachBotStart)) + } + case let .withBotApp(botAppStart): + context.sharedContext.applicationBindings.dismissNativeController() + if let navigationController { + context.sharedContext.navigateToChatController(NavigateToChatControllerParams(navigationController: navigationController, context: context, chatLocation: .peer(peer), botAppStart: botAppStart)) + } + default: + break + } + }, + sendFile: nil, + sendSticker: nil, + sendEmoji: nil, + requestMessageActionUrlAuth: nil, + joinVoiceChat: { _, _, _ in }, + present: { c, a in + context.sharedContext.applicationBindings.dismissNativeController() + c.presentationArguments = a + context.sharedContext.applicationBindings.getWindowHost()?.present(c, on: .root, blockInteraction: false, completion: {}) + }, + dismissInput: { + dismissInput() + }, + contentContext: nil, + progress: nil, + completion: nil + ) + } + } +} + +private func makeInternalUrlHandler( + context: AccountContext, + resolvedHandler: @escaping (ResolvedUrl) -> Void +) -> (String) -> Void { + return { url in + let _ = (context.sharedContext.resolveUrl(context: context, peerId: nil, url: url, skipUrlAuth: true) + |> deliverOnMainQueue).startStandalone(next: resolvedHandler) + } +} + +private let internetSchemes: [String] = ["http", "https"] +private let telegramMeHosts: [String] = ["t.me", "telegram.me", "telegram.dog"] + +private func handleInternetUrl( + parsedUrl: URL, + originalUrl: String, + context: AccountContext, + presentationData: PresentationData, + navigationController: NavigationController?, + handleInternalUrl: @escaping (String) -> Void +) { + let urlScheme = (parsedUrl.scheme ?? "").lowercased() + var isInternetUrl = false + if internetSchemes.contains(urlScheme) { + isInternetUrl = true + } + if urlScheme == "tonsite" { + isInternetUrl = true + } + + if isInternetUrl { + if let host = parsedUrl.host, telegramMeHosts.contains(host) { + handleInternalUrl(parsedUrl.absoluteString) + } else { + let settings = combineLatest(context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.webBrowserSettings, ApplicationSpecificSharedDataKeys.presentationPasscodeSettings]), context.sharedContext.accountManager.accessChallengeData()) + |> take(1) + |> map { sharedData, accessChallengeData -> WebBrowserSettings in + let passcodeSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationPasscodeSettings]?.get(PresentationPasscodeSettings.self) ?? PresentationPasscodeSettings.defaultSettings + + var settings: WebBrowserSettings + if let current = sharedData.entries[ApplicationSpecificSharedDataKeys.webBrowserSettings]?.get(WebBrowserSettings.self) { + settings = current + } else { + settings = .defaultSettings + } + if accessChallengeData.data.isLockable { + if passcodeSettings.autolockTimeout != nil && settings.defaultWebBrowser == "inApp" { + settings = WebBrowserSettings(defaultWebBrowser: "safari", exceptions: []) + } + } + return settings + } + + let _ = (settings + |> deliverOnMainQueue).startStandalone(next: { settings in + var isTonSite = false + if let host = parsedUrl.host, host.lowercased().hasSuffix(".ton") { + isTonSite = true + } else if let scheme = parsedUrl.scheme, scheme.lowercased().hasPrefix("tonsite") { + isTonSite = true + } + + if let defaultWebBrowser = settings.defaultWebBrowser, defaultWebBrowser != "inApp" && !isTonSite { + let openInOptions = availableOpenInOptions(context: context, item: .url(url: originalUrl)) + if let option = openInOptions.first(where: { $0.identifier == settings.defaultWebBrowser }) { + if case let .openUrl(openInUrl) = option.action() { + context.sharedContext.applicationBindings.openUrl(openInUrl) + } else { + context.sharedContext.applicationBindings.openUrl(originalUrl) + } + } else { + context.sharedContext.applicationBindings.openUrl(originalUrl) + } + } else { + var isExceptedDomain = false + let host = ".\((parsedUrl.host ?? "").lowercased())" + for exception in settings.exceptions { + if host.hasSuffix(".\(exception.domain)") { + isExceptedDomain = true + break + } + } + if settings.defaultWebBrowser == "inApp" { isExceptedDomain = false } // MARK: Swiftgram + + if (settings.defaultWebBrowser == nil && !isExceptedDomain) || isTonSite { + let controller = BrowserScreen(context: context, subject: .webPage(url: parsedUrl.absoluteString)) + navigationController?.pushViewController(controller) + } else { + if let window = navigationController?.view.window, !isExceptedDomain { + let controller = SFSafariViewControllerPlusDidFinish(url: parsedUrl) // MARK: Swiftgram + controller.preferredBarTintColor = presentationData.theme.rootController.navigationBar.opaqueBackgroundColor + controller.preferredControlTintColor = presentationData.theme.rootController.navigationBar.accentTextColor + // MARK: Swiftgram + if parsedUrl.host?.lowercased() == SG_API_WEBAPP_URL_PARSED.host?.lowercased() { + controller.onDidFinish = { + SGLogger.shared.log("SafariController", "Closed webapp") + updateSGWebSettingsInteractivelly(context: context) + } + } + // + window.rootViewController?.present(controller, animated: true) + } else { + context.sharedContext.applicationBindings.openUrl(parsedUrl.absoluteString) + } + } + } + }) + } + } else { + context.sharedContext.applicationBindings.openUrl(originalUrl) + } +} + +private struct QueryParameters { + private let map: [String: [String?]] + let items: [URLQueryItem] + + init?(_ query: String) { + guard let components = URLComponents(string: "/?" + query) else { + return nil + } + let queryItems = components.queryItems ?? [] + self.items = queryItems + + var map: [String: [String?]] = [:] + for item in queryItems { + map[item.name, default: []].append(item.value) + } + self.map = map + } + + subscript(_ name: String) -> String? { + return self.map[name]?.first ?? nil + } +} + +private func appendQueryItems(to base: String, items: [URLQueryItem]) -> String { + guard !items.isEmpty else { + return base + } + var components = URLComponents() + components.queryItems = items + guard let query = components.percentEncodedQuery, !query.isEmpty else { + return base + } + let separator = base.contains("?") ? "&" : "?" + return base + separator + query +} + +private func makeTelegramUrl(_ path: String, queryItems: [URLQueryItem] = []) -> String { + return appendQueryItems(to: "https://t.me\(path)", items: queryItems) +} + func openExternalUrlImpl(context: AccountContext, urlContext: OpenURLContext, url: String, forceExternal: Bool, presentationData: PresentationData, navigationController: NavigationController?, dismissInput: @escaping () -> Void) { if forceExternal || url.lowercased().hasPrefix("tel:") || url.lowercased().hasPrefix("calshow:") { if url.lowercased().hasPrefix("tel:+888") { @@ -152,25 +396,16 @@ func openExternalUrlImpl(context: AccountContext, urlContext: OpenURLContext, ur return } - var parsedUrlValue: URL? - var urlWithScheme = url - if !url.contains("://") && !url.hasPrefix("mailto:") { - urlWithScheme = "http://" + url - } - if let parsed = URL(string: urlWithScheme) { - parsedUrlValue = parsed - } else if let encoded = (urlWithScheme as NSString).addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed), let parsed = URL(string: encoded) { - parsedUrlValue = parsed + guard let canonicalUrl = canonicalExternalUrl(from: url) else { + return } - if let parsedUrlValue = parsedUrlValue, parsedUrlValue.scheme == "mailto" { + if canonicalUrl.scheme == "mailto" { context.sharedContext.applicationBindings.openUrl(url) return } - guard var parsedUrl = parsedUrlValue else { - return - } + var parsedUrl = canonicalUrl if let host = parsedUrl.host?.lowercased() { if host == "itunes.apple.com" { @@ -192,65 +427,18 @@ func openExternalUrlImpl(context: AccountContext, urlContext: OpenURLContext, ur } } + let handleResolvedUrl = makeResolvedUrlHandler( + context: context, + presentationData: presentationData, + navigationController: navigationController, + dismissInput: dismissInput + ) + let handleInternalUrl = makeInternalUrlHandler( + context: context, + resolvedHandler: handleResolvedUrl + ) + let continueHandling: () -> Void = { - let handleResolvedUrl: (ResolvedUrl) -> Void = { resolved in - if case let .externalUrl(value) = resolved { - context.sharedContext.applicationBindings.openUrl(value) - } else { - context.sharedContext.openResolvedUrl(resolved, context: context, urlContext: .generic, navigationController: navigationController, forceExternal: false, forceUpdate: false, openPeer: { peer, navigation in - switch navigation { - case .info: - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - context.sharedContext.applicationBindings.dismissNativeController() - navigationController?.pushViewController(infoController) - } - case let .chat(textInputState, subject, peekData): - context.sharedContext.applicationBindings.dismissNativeController() - if let navigationController = navigationController { - context.sharedContext.navigateToChatController(NavigateToChatControllerParams(navigationController: navigationController, context: context, chatLocation: .peer(peer), subject: subject, updateTextInputState: !peer.id.isGroupOrChannel ? textInputState : nil, peekData: peekData)) - } - case let .withBotStartPayload(payload): - context.sharedContext.applicationBindings.dismissNativeController() - if let navigationController = navigationController { - context.sharedContext.navigateToChatController(NavigateToChatControllerParams(navigationController: navigationController, context: context, chatLocation: .peer(peer), botStart: payload)) - } - case let .withAttachBot(attachBotStart): - context.sharedContext.applicationBindings.dismissNativeController() - if let navigationController = navigationController { - context.sharedContext.navigateToChatController(NavigateToChatControllerParams(navigationController: navigationController, context: context, chatLocation: .peer(peer), attachBotStart: attachBotStart)) - } - case let .withBotApp(botAppStart): - context.sharedContext.applicationBindings.dismissNativeController() - if let navigationController = navigationController { - context.sharedContext.navigateToChatController(NavigateToChatControllerParams(navigationController: navigationController, context: context, chatLocation: .peer(peer), botAppStart: botAppStart)) - } - default: - break - } - }, - sendFile: nil, - sendSticker: nil, - sendEmoji: nil, - requestMessageActionUrlAuth: nil, - joinVoiceChat: { peerId, invite, call in - - }, present: { c, a in - context.sharedContext.applicationBindings.dismissNativeController() - - c.presentationArguments = a - - context.sharedContext.applicationBindings.getWindowHost()?.present(c, on: .root, blockInteraction: false, completion: {}) - }, dismissInput: { - dismissInput() - }, contentContext: nil, progress: nil, completion: nil) - } - } - - let handleInternalUrl: (String) -> Void = { url in - let _ = (context.sharedContext.resolveUrl(context: context, peerId: nil, url: url, skipUrlAuth: true) - |> deliverOnMainQueue).startStandalone(next: handleResolvedUrl) - } - if let scheme = parsedUrl.scheme, (scheme == "tg" || scheme == context.sharedContext.applicationBindings.appSpecificScheme) { if parsedUrl.host == "tonsite" { if let value = URL(string: "tonsite:/" + parsedUrl.path) { @@ -261,821 +449,239 @@ func openExternalUrlImpl(context: AccountContext, urlContext: OpenURLContext, ur if let scheme = parsedUrl.scheme, (scheme == "tg" || scheme == context.sharedContext.applicationBindings.appSpecificScheme) { var convertedUrl: String? - if let query = parsedUrl.query { - if parsedUrl.host == "localpeer" { - if let components = URLComponents(string: "/?" + query) { - var peerId: PeerId? - var accountId: Int64? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "id", let intValue = Int64(value) { - peerId = PeerId(intValue) - } else if queryItem.name == "accountId", let intValue = Int64(value) { - accountId = intValue - } - } + let host = parsedUrl.host?.lowercased() ?? "" + if let query = parsedUrl.query, let params = QueryParameters(query) { + switch host { + case "localpeer": + if let peerIdValue = params["id"].flatMap(Int64.init), let accountId = params["accountId"].flatMap(Int64.init) { + let peerId = PeerId(peerIdValue) + context.sharedContext.applicationBindings.dismissNativeController() + context.sharedContext.navigateToChat(accountId: AccountRecordId(rawValue: accountId), peerId: peerId, messageId: nil) + } + case "join": + if let invite = params["invite"] { + convertedUrl = makeTelegramUrl("/joinchat/\(invite)") + } + case "addstickers": + if let set = params["set"] { + convertedUrl = makeTelegramUrl("/addstickers/\(set)") + } + case "addemoji": + if let set = params["set"] { + convertedUrl = makeTelegramUrl("/addemoji/\(set)") + } + case "invoice": + if let slug = params["slug"] { + convertedUrl = makeTelegramUrl("/invoice/\(slug)") + } + case "setlanguage": + if let lang = params["lang"] { + convertedUrl = makeTelegramUrl("/setlanguage/\(lang)") + } + case "msg": + let sharePhoneNumber = params["to"] + let shareText = params["text"] + if sharePhoneNumber != nil || shareText != nil { + handleResolvedUrl(.share(url: nil, text: shareText, to: sharePhoneNumber)) + return + } + case "msg_url": + if let shareUrl = params["url"] { + var queryItems: [URLQueryItem] = [URLQueryItem(name: "url", value: shareUrl)] + if let shareText = params["text"] { + queryItems.append(URLQueryItem(name: "text", value: shareText)) + } + convertedUrl = makeTelegramUrl("/share/url", queryItems: queryItems) + } + case "socks", "proxy": + let server = params["server"] ?? params["proxy"] + let port = params["port"] + let user = params["user"] + let pass = params["pass"] + let secret = params["secret"] + let secretHost = params["host"] + + if let server, !server.isEmpty, let port, let _ = Int32(port) { + var queryItems: [URLQueryItem] = [ + URLQueryItem(name: "proxy", value: server), + URLQueryItem(name: "port", value: port) + ] + if let user { + queryItems.append(URLQueryItem(name: "user", value: user)) + if let pass { + queryItems.append(URLQueryItem(name: "pass", value: pass)) } } - if let peerId = peerId, let accountId = accountId { + if let secret { + queryItems.append(URLQueryItem(name: "secret", value: secret)) + } + if let secretHost { + queryItems.append(URLQueryItem(name: "host", value: secretHost)) + } + convertedUrl = makeTelegramUrl("/proxy", queryItems: queryItems) + } + case "passport", "oauth", "resolve": + if isOAuthUrl(parsedUrl) { + handleResolvedUrl(.oauth(url: url)) + return + } else if let secureId = parseSecureIdUrl(parsedUrl) { + if case .chat = urlContext { + return + } + let controller = SecureIdAuthController(context: context, mode: .form(peerId: secureId.peerId, scope: secureId.scope, publicKey: secureId.publicKey, callbackUrl: secureId.callbackUrl, opaquePayload: secureId.opaquePayload, opaqueNonce: secureId.opaqueNonce)) + + if let navigationController = navigationController { context.sharedContext.applicationBindings.dismissNativeController() - context.sharedContext.navigateToChat(accountId: AccountRecordId(rawValue: accountId), peerId: peerId, messageId: nil) + + navigationController.view.window?.endEditing(true) + context.sharedContext.applicationBindings.getWindowHost()?.present(controller, on: .root, blockInteraction: false, completion: {}) + } + return + } + case "user": + if let idValue = params["id"].flatMap(Int64.init), idValue > 0 { + let _ = (context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(idValue)))) + |> deliverOnMainQueue).startStandalone(next: { peer in + if let peer = peer, let controller = context.sharedContext.makePeerInfoController( + context: context, + updatedPresentationData: nil, + peer: peer._asPeer(), + mode: .generic, + avatarInitiallyExpanded: false, + fromChat: false, + requestsContext: nil + ) { + navigationController?.pushViewController(controller) + } + }) + return + } + case "login": + if let _ = params["token"] { + let alertController = textAlertController( + context: context, + title: nil, + text: presentationData.strings.AuthSessions_AddDevice_UrlLoginHint, + actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Common_OK, action: {})], + parseMarkdown: true + ) + context.sharedContext.presentGlobalController(alertController, nil) + return + } + if let code = params["code"] { + convertedUrl = makeTelegramUrl("/login/\(code)") + } + case "contact": + if let token = params["token"] { + convertedUrl = makeTelegramUrl("/contact/\(token)") + } + case "confirmphone": + if let phone = params["phone"], let hash = params["hash"] { + let queryItems = [ + URLQueryItem(name: "phone", value: phone), + URLQueryItem(name: "hash", value: hash) + ] + convertedUrl = makeTelegramUrl("/confirmphone", queryItems: queryItems) + } + case "bg": + var parameter: String? + var queryItems: [URLQueryItem] = [] + for item in params.items { + guard let value = item.value else { + continue + } + switch item.name { + case "slug", "color", "gradient": + parameter = value + case "mode", "bg_color", "intensity", "rotation": + queryItems.append(URLQueryItem(name: item.name, value: value)) + default: + break } } - } else if parsedUrl.host == "join" { - if let components = URLComponents(string: "/?" + query) { - var invite: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "invite" { - invite = value - } - } - } - } - if let invite = invite { - convertedUrl = "https://t.me/joinchat/\(invite)" - } + if let parameter = parameter { + convertedUrl = makeTelegramUrl("/bg/\(parameter)", queryItems: queryItems) } - } else if parsedUrl.host == "addstickers" { - if let components = URLComponents(string: "/?" + query) { - var set: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "set" { - set = value - } - } - } - } - if let set = set { - convertedUrl = "https://t.me/addstickers/\(set)" - } + case "addtheme": + if let parameter = params["slug"] { + convertedUrl = makeTelegramUrl("/addtheme/\(parameter)") } - } else if parsedUrl.host == "addemoji" { - if let components = URLComponents(string: "/?" + query) { - var set: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "set" { - set = value - } - } - } - } - if let set = set { - convertedUrl = "https://t.me/addemoji/\(set)" - } + case "nft": + if let slug = params["slug"] { + convertedUrl = makeTelegramUrl("/nft/\(slug)") } - } else if parsedUrl.host == "invoice" { - if let components = URLComponents(string: "/?" + query) { - var slug: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "slug" { - slug = value - } - } - } - } - if let slug = slug { - convertedUrl = "https://t.me/invoice/\(slug)" - } + case "stargift_auction": + if let slug = params["slug"] { + convertedUrl = makeTelegramUrl("/auction/\(slug)") } - } else if parsedUrl.host == "setlanguage" { - if let components = URLComponents(string: "/?" + query) { - var lang: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "lang" { - lang = value - } - } - } - } - if let lang = lang { - convertedUrl = "https://t.me/setlanguage/\(lang)" - } - } - } else if parsedUrl.host == "msg" { - if let components = URLComponents(string: "/?" + query) { - var sharePhoneNumber: String? - var shareText: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "to" { - sharePhoneNumber = value - } else if queryItem.name == "text" { - shareText = value - } - } - } - } - if sharePhoneNumber != nil || shareText != nil { - handleResolvedUrl(.share(url: nil, text: shareText, to: sharePhoneNumber)) - return - } - } - } else if parsedUrl.host == "msg_url" { - if let components = URLComponents(string: "/?" + query) { - var shareUrl: String? - var shareText: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "url" { - shareUrl = value - } else if queryItem.name == "text" { - shareText = value - } - } - } - } - if let shareUrl = shareUrl { - var resultUrl = "https://t.me/share/url?url=\(urlEncodedStringFromString(shareUrl))" - if let shareText = shareText { - resultUrl += "&text=\(urlEncodedStringFromString(shareText))" - } - convertedUrl = resultUrl - } - } - } else if parsedUrl.host == "socks" || parsedUrl.host == "proxy" { - if let components = URLComponents(string: "/?" + query) { - var server: String? - var port: String? - var user: String? - var pass: String? - var secret: String? - var secretHost: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "server" || queryItem.name == "proxy" { - server = value - } else if queryItem.name == "port" { - port = value - } else if queryItem.name == "user" { - user = value - } else if queryItem.name == "pass" { - pass = value - } else if queryItem.name == "secret" { - secret = value - } else if queryItem.name == "host" { - secretHost = value - } - } - } - } - - if let server = server, !server.isEmpty, let port = port, let _ = Int32(port) { - var result = "https://t.me/proxy?proxy=\(server)&port=\(port)" - if let user = user { - result += "&user=\((user as NSString).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryValueAllowed) ?? "")" - if let pass = pass { - result += "&pass=\((pass as NSString).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryValueAllowed) ?? "")" - } - } - if let secret = secret { - result += "&secret=\((secret as NSString).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryValueAllowed) ?? "")" - } - if let secretHost = secretHost?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryValueAllowed) { - result += "&host=\(secretHost)" - } - convertedUrl = result - } - } - } else if parsedUrl.host == "passport" || parsedUrl.host == "resolve" { - if let components = URLComponents(string: "/?" + query) { - var domain: String? - var botId: Int64? - var scope: String? - var publicKey: String? - var callbackUrl: String? - var opaquePayload = Data() - var opaqueNonce = Data() - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "domain" { - domain = value - } else if queryItem.name == "bot_id" { - botId = Int64(value) - } else if queryItem.name == "scope" { - scope = value - } else if queryItem.name == "public_key" { - publicKey = value - } else if queryItem.name == "callback_url" { - callbackUrl = value - } else if queryItem.name == "payload" { - if let data = value.data(using: .utf8) { - opaquePayload = data - } - } else if queryItem.name == "nonce" { - if let data = value.data(using: .utf8) { - opaqueNonce = data - } - } - } - } - } - - let valid: Bool - if parsedUrl.host == "resolve" { - if domain == "telegrampassport" { - valid = true - } else { - valid = false - } - } else { - valid = true - } - - if valid { - if let botId = botId, let scope = scope, let publicKey = publicKey { - if scope.hasPrefix("{") && scope.hasSuffix("}") { - opaquePayload = Data() - if opaqueNonce.isEmpty { - return - } - } else if opaquePayload.isEmpty { - return - } - if case .chat = urlContext { - return - } - let controller = SecureIdAuthController(context: context, mode: .form(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(botId)), scope: scope, publicKey: publicKey, callbackUrl: callbackUrl, opaquePayload: opaquePayload, opaqueNonce: opaqueNonce)) - - if let navigationController = navigationController { - context.sharedContext.applicationBindings.dismissNativeController() - - navigationController.view.window?.endEditing(true) - context.sharedContext.applicationBindings.getWindowHost()?.present(controller, on: .root, blockInteraction: false, completion: {}) - } - } - return - } - } - } else if parsedUrl.host == "user" { - if let components = URLComponents(string: "/?" + query) { - var id: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "id" { - id = value - } - } - } - } - - if let id = id, !id.isEmpty, let idValue = Int64(id), idValue > 0 { - let _ = (context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(idValue)))) - |> deliverOnMainQueue).startStandalone(next: { peer in - if let peer = peer, let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - navigationController?.pushViewController(controller) - } - }) - return - } - } - } else if parsedUrl.host == "login" { - if let components = URLComponents(string: "/?" + query) { - var code: String? - var isToken: Bool = false - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "code" { - code = value - } - } - if queryItem.name == "token" { - isToken = true - } - } - } - if isToken { - context.sharedContext.presentGlobalController(textAlertController(context: context, title: nil, text: presentationData.strings.AuthSessions_AddDevice_UrlLoginHint, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Common_OK, action: {}), - ], parseMarkdown: true), nil) - return - } - if let code = code { - convertedUrl = "https://t.me/login/\(code)" - } - } - } else if parsedUrl.host == "contact" { - if let components = URLComponents(string: "/?" + query) { - var token: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "token" { - token = value - } - } - } - } - if let token = token { - convertedUrl = "https://t.me/contact/\(token)" - } - } - } else if parsedUrl.host == "confirmphone" { - if let components = URLComponents(string: "/?" + query) { - var phone: String? - var hash: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "phone" { - phone = value - } else if queryItem.name == "hash" { - hash = value - } - } - } - } - if let phone = phone, let hash = hash { - convertedUrl = "https://t.me/confirmphone?phone=\(phone)&hash=\(hash)" - } - } - } else if parsedUrl.host == "bg" { - if let components = URLComponents(string: "/?" + query) { - var parameter: String? - var query: [String] = [] - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "slug" { - parameter = value - } else if queryItem.name == "color" { - parameter = value - } else if queryItem.name == "gradient" { - parameter = value - } else if queryItem.name == "mode" { - query.append("mode=\(value)") - } else if queryItem.name == "bg_color" { - query.append("bg_color=\(value)") - } else if queryItem.name == "intensity" { - query.append("intensity=\(value)") - } else if queryItem.name == "rotation" { - query.append("rotation=\(value)") - } - } - } - } - var queryString = "" - if !query.isEmpty { - queryString = "?\(query.joined(separator: "&"))" - } - if let parameter = parameter { - convertedUrl = "https://t.me/bg/\(parameter)\(queryString)" - } - } - } else if parsedUrl.host == "addtheme" { - if let components = URLComponents(string: "/?" + query) { - var parameter: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "slug" { - parameter = value - } - } - } - } - if let parameter = parameter { - convertedUrl = "https://t.me/addtheme/\(parameter)" - } - } - } else if parsedUrl.host == "nft" { - if let components = URLComponents(string: "/?" + query) { - var slug: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "slug" { - slug = value - } - } - } - } - if let slug { - convertedUrl = "https://t.me/nft/\(slug)" - } - } - } else if parsedUrl.host == "stargift_auction" { - if let components = URLComponents(string: "/?" + query) { - var slug: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "slug" { - slug = value - } - } - } - } - if let slug { - convertedUrl = "https://t.me/auction/\(slug)" - } - } - } else if parsedUrl.host == "privatepost" { - if let components = URLComponents(string: "/?" + query) { - var channelId: Int64? - var postId: Int32? - var threadId: Int64? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "channel" { - channelId = Int64(value) - } else if queryItem.name == "post" { - postId = Int32(value) - } else if queryItem.name == "thread" { - threadId = Int64(value) - } - } - } - } - if let channelId = channelId { - if let postId = postId { - if let threadId = threadId { - convertedUrl = "https://t.me/c/\(channelId)/\(threadId)/\(postId)" - } else { - convertedUrl = "https://t.me/c/\(channelId)/\(postId)" - } - } else if let threadId = threadId { - convertedUrl = "https://t.me/c/\(channelId)/\(threadId)" - } - } - } - } else if parsedUrl.host == "giftcode" { - if let components = URLComponents(string: "/?" + query) { - var slug: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "slug" { - slug = value - } - } - } - } - if let slug { - convertedUrl = "https://t.me/giftcode/\(slug)" - } - } - } else if parsedUrl.host == "message" { - if let components = URLComponents(string: "/?" + query) { - var parameter: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "slug" { - parameter = value - } - } - } - } - if let parameter { - convertedUrl = "https://t.me/m/\(parameter)" - } - } - } - - if parsedUrl.host == "resolve" { - if let components = URLComponents(string: "/?" + query) { - var phone: String? - var domain: String? - var start: String? - var startGroup: String? - var startChannel: String? - var admin: String? - var game: String? - var post: String? - var voiceChat: String? - var attach: String? - var startAttach: String? - var choose: String? - var threadId: Int64? - var appName: String? - var startApp: String? - var text: String? - var profile: Bool = false - var direct: Bool = false - var referrer: String? - var albumId: Int64? - var collectionId: Int64? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "phone" { - phone = value - } else if queryItem.name == "domain" { - domain = value - } else if queryItem.name == "start" { - start = value - } else if queryItem.name == "startgroup" { - startGroup = value - } else if queryItem.name == "admin" { - admin = value - } else if queryItem.name == "game" { - game = value - } else if queryItem.name == "post" { - post = value - } else if ["voicechat", "videochat", "livestream"].contains(queryItem.name) { - voiceChat = value - } else if queryItem.name == "attach" { - attach = value - } else if queryItem.name == "startattach" { - startAttach = value - } else if queryItem.name == "choose" { - choose = value - } else if queryItem.name == "thread" { - threadId = Int64(value) - } else if queryItem.name == "appname" { - appName = value - } else if queryItem.name == "startapp" { - startApp = value - } else if queryItem.name == "text" { - text = value - } else if queryItem.name == "ref" { - referrer = value - } else if queryItem.name == "album" { - albumId = Int64(value) - } else if queryItem.name == "collection" { - collectionId = Int64(value) - } - } else if ["voicechat", "videochat", "livestream"].contains(queryItem.name) { - voiceChat = "" - } else if queryItem.name == "startattach" { - startAttach = "" - } else if queryItem.name == "startgroup" { - startGroup = "" - } else if queryItem.name == "startchannel" { - startChannel = "" - } else if queryItem.name == "profile" { - profile = true - } else if queryItem.name == "direct" { - direct = true - } else if queryItem.name == "startapp" { - startApp = "" - } - } - } - - if let phone = phone { - var result = "https://t.me/+\(phone)" - if let text = text { - result += "?text=\(text)" - } - convertedUrl = result - } else if let domain = domain { - var result = "https://t.me/\(domain)" - if let appName { - result += "/\(appName)" - } - if let startApp { - result += "?startapp=\(startApp)" - } + case "privatepost": + let channelId = params["channel"].flatMap(Int64.init) + let postId = params["post"].flatMap(Int32.init) + let threadId = params["thread"].flatMap(Int64.init) + + if let channelId { + if let postId { if let threadId { - result += "/\(threadId)" - if let post, let postValue = Int(post) { - result += "/\(postValue)" - } + convertedUrl = makeTelegramUrl("/c/\(channelId)/\(threadId)/\(postId)") } else { - if let post, let postValue = Int(post) { - result += "/\(postValue)" - } - } - if let start = start { - result += "?start=\(start)" - } else if let startGroup = startGroup { - if !startGroup.isEmpty { - result += "?startgroup=\(startGroup)" - } else { - result += "?startgroup" - } - if let admin = admin { - result += "&admin=\(admin)" - } - } else if let startChannel = startChannel { - if !startChannel.isEmpty { - result += "?startchannel=\(startChannel)" - } else { - result += "?startchannel" - } - if let admin = admin { - result += "&admin=\(admin)" - } - } else if let game = game { - result += "?game=\(game)" - } else if let voiceChat = voiceChat { - if !voiceChat.isEmpty { - result += "?voicechat=\(voiceChat)" - } else { - result += "?voicechat=" - } - } else if let attach = attach { - result += "?attach=\(attach)" - } else if let albumId { - result += "/a/\(albumId)" - } else if let collectionId { - result += "/c/\(collectionId)" - } - if let startAttach = startAttach { - if attach == nil { - result += "?" - } else { - result += "&" - } - if !startAttach.isEmpty { - result += "startattach=\(startAttach)" - } else { - result += "startattach" - } - if let choose = choose { - result += "&choose=\(choose)" - } - } - if let text = text { - result += "?text=\(text)" - } - if let referrer { - result += "?ref=\(referrer)" - } - convertedUrl = result - } - if profile, let current = convertedUrl { - if current.contains("?") { - convertedUrl = current + "&profile" - } else { - convertedUrl = current + "?profile" - } - } - if direct, let current = convertedUrl { - if current.contains("?") { - convertedUrl = current + "&direct" - } else { - convertedUrl = current + "?direct" + convertedUrl = makeTelegramUrl("/c/\(channelId)/\(postId)") } + } else if let threadId { + convertedUrl = makeTelegramUrl("/c/\(channelId)/\(threadId)") } } - } else if parsedUrl.host == "hostOverride" { - if let components = URLComponents(string: "/?" + query) { - var host: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "host" { - host = value - } - } - } - } - if let host = host { - let _ = updateNetworkSettingsInteractively(postbox: context.account.postbox, network: context.account.network, { settings in - var settings = settings - settings.backupHostOverride = host - return settings - }).startStandalone() - return - } + case "giftcode": + if let slug = params["slug"] { + convertedUrl = makeTelegramUrl("/giftcode/\(slug)") } - } else if parsedUrl.host == "premium_offer" { - var reference: String? - if let components = URLComponents(string: "/?" + query) { - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "ref" { - reference = value - } - } - } - } + case "message": + if let parameter = params["slug"] { + convertedUrl = makeTelegramUrl("/m/\(parameter)") } + case "hostoverride": + if let override = params["host"] { + let _ = updateNetworkSettingsInteractively(postbox: context.account.postbox, network: context.account.network, { settings in + var settings = settings + settings.backupHostOverride = override + return settings + }).startStandalone() + return + } + case "premium_offer": + let reference = params["ref"] handleResolvedUrl(.premiumOffer(reference: reference)) - } else if parsedUrl.host == "premium_multigift" { - var reference: String? - if let components = URLComponents(string: "/?" + query) { - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "ref" { - reference = value - } - } - } - } - } + case "premium_multigift": + let reference = params["ref"] handleResolvedUrl(.premiumMultiGift(reference: reference)) - } else if parsedUrl.host == "stars_topup" { - var amount: Int64? - var purpose: String? - if let components = URLComponents(string: "/?" + query) { - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "balance", let amountValue = Int64(value), amountValue > 0 && amountValue < Int32.max { - amount = amountValue - } else if queryItem.name == "purpose" { - purpose = value - } - } - } - } - } - if let amount { + case "stars_topup": + let amount = params["balance"].flatMap(Int64.init) + let purpose = params["purpose"] + if let amount, amount > 0 && amount < Int64(Int32.max) { handleResolvedUrl(.starsTopup(amount: amount, purpose: purpose)) + } else { + handleResolvedUrl(.starsTopup(amount: nil, purpose: purpose)) } - } else if parsedUrl.host == "addlist" { - if let components = URLComponents(string: "/?" + query) { - var slug: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "slug" { - slug = value - } - } - } - } - if let slug = slug { - convertedUrl = "https://t.me/addlist/\(slug)" - } + case "addlist": + if let slug = params["slug"] { + convertedUrl = makeTelegramUrl("/addlist/\(slug)") } - } else if parsedUrl.host == "boost" { - if let components = URLComponents(string: "/?" + query) { - var domain: String? - var channel: Int64? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "domain" { - domain = value - } else if queryItem.name == "channel" { - channel = Int64(value) - } - } - } - } - if let domain { - convertedUrl = "https://t.me/\(domain)?boost" - } else if let channel { - convertedUrl = "https://t.me/c/\(channel)?boost" - } + case "boost": + if let domain = params["domain"] { + convertedUrl = makeTelegramUrl("/\(domain)", queryItems: [URLQueryItem(name: "boost", value: nil)]) + } else if let channel = params["channel"].flatMap(Int64.init) { + convertedUrl = makeTelegramUrl("/c/\(channel)", queryItems: [URLQueryItem(name: "boost", value: nil)]) } - } else if parsedUrl.host == "call" { - if let components = URLComponents(string: "/?" + query) { - var slug: String? - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "slug" { - slug = value - } - } - } - } - if let slug = slug { - convertedUrl = "https://t.me/call/\(slug)" - } + case "call": + if let slug = params["slug"] { + convertedUrl = makeTelegramUrl("/call/\(slug)") } - } else if parsedUrl.host == "shareStory" { - if let components = URLComponents(string: "/?" + query) { - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "session", let sessionId = Int64(value) { - handleResolvedUrl(.shareStory(sessionId)) - break - } - } - } - } + case "sharestory": + if let session = params["session"].flatMap(Int64.init) { + handleResolvedUrl(.shareStory(session)) + return } - } else if parsedUrl.host == "send_gift" { - var recipient: String? - if let components = URLComponents(string: "/?" + query) { - if let queryItems = components.queryItems { - for queryItem in queryItems { - if let value = queryItem.value { - if queryItem.name == "to" { - recipient = value - break - } - } - } - } - } - if let recipient { + case "send_gift": + if let recipient = params["to"] { if let id = Int64(recipient) { handleResolvedUrl(.sendGift(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(id)))) } else { @@ -1090,40 +696,253 @@ func openExternalUrlImpl(context: AccountContext, urlContext: OpenURLContext, ur } else { handleResolvedUrl(.sendGift(peerId: nil)) } + default: + break } - } else { - if parsedUrl.host == "stars" { - handleResolvedUrl(.stars) - } else if parsedUrl.host == "ton" { - handleResolvedUrl(.ton) - } else if parsedUrl.host == "importStickers" { - handleResolvedUrl(.importStickers) - } else if parsedUrl.host == "settings" { - if let path = parsedUrl.pathComponents.last { - var section: ResolvedUrlSettingsSection? - switch path { - case "themes": - section = .theme - case "devices": - section = .devices - case "password": - section = .twoStepAuth - case "enable_log": - section = .enableLog - case "phone_privacy": - section = .phonePrivacy - case "login_email": - section = .loginEmail - default: - break - } - if let section = section { - handleResolvedUrl(.settings(section)) + + if host == "resolve" { + var phone: String? + var domain: String? + var start: String? + var startGroup: String? + var startChannel: String? + var admin: String? + var game: String? + var post: String? + var voiceChat: String? + var attach: String? + var startAttach: String? + var choose: String? + var threadId: Int64? + var appName: String? + var startApp: String? + var text: String? + var profile = false + var direct = false + var referrer: String? + var albumId: Int64? + var collectionId: Int64? + + for queryItem in params.items { + if let value = queryItem.value { + switch queryItem.name { + case "phone": + phone = value + case "domain": + domain = value + case "start": + start = value + case "startgroup": + startGroup = value + case "admin": + admin = value + case "game": + game = value + case "post": + post = value + case "voicechat", "videochat", "livestream": + voiceChat = value + case "attach": + attach = value + case "startattach": + startAttach = value + case "choose": + choose = value + case "thread": + threadId = Int64(value) + case "appname": + appName = value + case "startapp": + startApp = value + case "text": + text = value + case "ref": + referrer = value + case "album": + albumId = Int64(value) + case "collection": + collectionId = Int64(value) + default: + break + } + } else { + switch queryItem.name { + case "voicechat", "videochat", "livestream": + voiceChat = "" + case "startattach": + startAttach = "" + case "startgroup": + startGroup = "" + case "startchannel": + startChannel = "" + case "profile": + profile = true + case "direct": + direct = true + case "startapp": + startApp = "" + default: + break + } } } - } else if parsedUrl.host == "premium_offer" { + + if let phone = phone { + var queryItems: [URLQueryItem] = [] + if let text { + queryItems.append(URLQueryItem(name: "text", value: text)) + } + if let referrer { + queryItems.append(URLQueryItem(name: "ref", value: referrer)) + } + if profile { + queryItems.append(URLQueryItem(name: "profile", value: nil)) + } + if direct { + queryItems.append(URLQueryItem(name: "direct", value: nil)) + } + convertedUrl = makeTelegramUrl("/+\(phone)", queryItems: queryItems) + } else if let domain = domain { + var path = "/\(domain)" + if let appName { + path += "/\(appName)" + } + if let threadId { + path += "/\(threadId)" + if let post, let postValue = Int(post) { + path += "/\(postValue)" + } + } else if let post, let postValue = Int(post) { + path += "/\(postValue)" + } + if let albumId { + path += "/a/\(albumId)" + } else if let collectionId { + path += "/c/\(collectionId)" + } + + var queryItems: [URLQueryItem] = [] + if let startApp { + queryItems.append(URLQueryItem(name: "startapp", value: startApp.isEmpty ? "" : startApp)) + } + if let start { + queryItems.append(URLQueryItem(name: "start", value: start)) + } else if let startGroup { + queryItems.append(URLQueryItem(name: "startgroup", value: startGroup.isEmpty ? nil : startGroup)) + if let admin { + queryItems.append(URLQueryItem(name: "admin", value: admin)) + } + } else if let startChannel { + queryItems.append(URLQueryItem(name: "startchannel", value: startChannel.isEmpty ? nil : startChannel)) + if let admin = admin { + queryItems.append(URLQueryItem(name: "admin", value: admin)) + } + } else if let game { + queryItems.append(URLQueryItem(name: "game", value: game)) + } else if let voiceChat { + queryItems.append(URLQueryItem(name: "voicechat", value: voiceChat.isEmpty ? "" : voiceChat)) + } else if let attach { + queryItems.append(URLQueryItem(name: "attach", value: attach)) + } + + if let startAttach { + queryItems.append(URLQueryItem(name: "startattach", value: startAttach.isEmpty ? nil : startAttach)) + if let choose { + queryItems.append(URLQueryItem(name: "choose", value: choose)) + } + } + if let text { + queryItems.append(URLQueryItem(name: "text", value: text)) + } + if let referrer { + queryItems.append(URLQueryItem(name: "ref", value: referrer)) + } + if profile { + queryItems.append(URLQueryItem(name: "profile", value: nil)) + } + if direct { + queryItems.append(URLQueryItem(name: "direct", value: nil)) + } + + convertedUrl = makeTelegramUrl(path, queryItems: queryItems) + } + } + } else { + switch host { + case "stars": + handleResolvedUrl(.stars) + case "sg": + if let path = parsedUrl.pathComponents.last { + switch path { + case "debug": + if let debugController = context.sharedContext.makeDebugSettingsController(context: context) { + navigationController?.pushViewController(debugController) + return + } + case "sgdebug", "sg_debug": + navigationController?.pushViewController(sgDebugController(context: context)) + return + case "settings": + navigationController?.pushViewController(sgSettingsController(context: context)) + return + case "ios_settings": + context.sharedContext.applicationBindings.openSettings() + return + case "contacts": + if let lastViewController = navigationController?.viewControllers.last as? ViewController { + lastViewController.present(ContactsController(context: context), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + } + return + case "pro", "premium", "buy": + if context.sharedContext.immediateSGStatus.status > 1 { + navigationController?.pushViewController(context.sharedContext.makeSGProController(context: context)) + } else { + if let lastViewController = navigationController?.viewControllers.last as? ViewController { + if let payWallController = context.sharedContext.makeSGPayWallController(context: context) { + lastViewController.present(payWallController, in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + } else { + lastViewController.present(context.sharedContext.makeSGUpdateIOSController(), animated: true) + } + } + } + case "restart": + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + let lang = presentationData.strings.baseLanguageCode + context.sharedContext.presentGlobalController( + UndoOverlayController( + presentationData: presentationData, + content: .info(title: nil, + text: "Common.RestartRequired".i18n(lang), + timeout: nil, + customUndoText: "Common.RestartNow".i18n(lang) + ), + elevatedLayout: false, + action: { action in if action == .undo { exit(0) }; return true } + ), + nil + ) + case "restore_purchases", "pro_restore", "validate", "restore": + let presentationData = context.sharedContext.currentPresentationData.with { $0 } + let lang = presentationData.strings.baseLanguageCode + context.sharedContext.presentGlobalController(UndoOverlayController( + presentationData: presentationData, + content: .info(title: nil, text: "PayWall.Button.Restoring".i18n(lang), timeout: nil, customUndoText: nil), + elevatedLayout: false, + action: { _ in return false } + ), + nil) + context.sharedContext.SGIAP?.restorePurchases {} + default: + break + } + } + case "ton": + handleResolvedUrl(.ton) + case "importstickers": + handleResolvedUrl(.importStickers) + case "premium_offer": handleResolvedUrl(.premiumOffer(reference: nil)) - } else if parsedUrl.host == "restore_purchases" { + case "restore_purchases": let statusController = OverlayStatusController(theme: presentationData.theme, type: .loading(cancelled: nil)) context.sharedContext.presentGlobalController(statusController, nil) @@ -1132,120 +951,142 @@ func openExternalUrlImpl(context: AccountContext, urlContext: OpenURLContext, ur let text: String? switch result { - case let .succeed(serverProvided): - text = serverProvided ? nil : presentationData.strings.Premium_Restore_Success - case .failed: - text = presentationData.strings.Premium_Restore_ErrorUnknown + case let .succeed(serverProvided): + text = serverProvided ? nil : presentationData.strings.Premium_Restore_Success + case .failed: + text = presentationData.strings.Premium_Restore_ErrorUnknown } - if let text = text { + if let text { let alertController = textAlertController(context: context, title: nil, text: text, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]) context.sharedContext.presentGlobalController(alertController, nil) } }) - } else if parsedUrl.host == "send_gift" { + case "send_gift": handleResolvedUrl(.sendGift(peerId: nil)) + case "contacts": + var section: ResolvedUrl.ContactsSection? + if let path = parsedUrl.pathComponents.last { + switch path { + case "search": + section = .search + case "sort": + section = .sort + case "new": + section = .new + case "invite": + section = .invite + case "manage": + section = .manage + default: + break + } + } + handleResolvedUrl(.contacts(section)) + case "chats": + var section: ResolvedUrl.ChatsSection? + if let path = parsedUrl.pathComponents.last { + switch path { + case "search": + section = .search + case "edit": + section = .edit + case "emoji-status": + section = .emojiStatus + default: + break + } + } + handleResolvedUrl(.chats(section)) + case "new": + var section: ResolvedUrl.ComposeSection? + if let path = parsedUrl.pathComponents.last { + switch path { + case "group": + section = .group + case "channel": + section = .channel + case "contact": + section = .contact + default: + break + } + } + handleResolvedUrl(.compose(section)) + case "post": + var section: ResolvedUrl.PostStorySection? + if let path = parsedUrl.pathComponents.last { + switch path { + case "photo": + section = .photo + case "video": + section = .video + case "live": + section = .live + default: + break + } + } + handleResolvedUrl(.postStory(section)) + case "settings": + if let lastComponent = parsedUrl.pathComponents.last { + var section: ResolvedUrl.SettingsSection? + switch lastComponent { + case "themes": + section = .legacy(.theme) + case "devices": + section = .legacy(.devices) + case "enable_log": + section = .legacy(.enableLog) + case "phone_privacy": + section = .legacy(.phonePrivacy) + case "login_email": + section = .legacy(.loginEmail) + default: + let fullPath = parsedUrl.pathComponents.joined(separator: "/").replacingOccurrences(of: "//", with: "") + section = .path(fullPath) + } + if let section { + handleResolvedUrl(.settings(section)) + } + } else { + handleResolvedUrl(.settings(.path(""))) + } + default: + break } } - if let convertedUrl = convertedUrl { + if let convertedUrl { handleInternalUrl(convertedUrl) + } else if let path = parsedUrl.host { + handleResolvedUrl(.unknownDeepLink(path: path)) } return } - let urlScheme = (parsedUrl.scheme ?? "").lowercased() - var isInternetUrl = false - if ["http", "https"].contains(urlScheme) { - isInternetUrl = true - } - if urlScheme == "tonsite" { - isInternetUrl = true - } - - if isInternetUrl { - if parsedUrl.host == "t.me" || parsedUrl.host == "telegram.me" || parsedUrl.host == "telegram.dog" { - handleInternalUrl(parsedUrl.absoluteString) - } else { - let settings = combineLatest(context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.webBrowserSettings, ApplicationSpecificSharedDataKeys.presentationPasscodeSettings]), context.sharedContext.accountManager.accessChallengeData()) - |> take(1) - |> map { sharedData, accessChallengeData -> WebBrowserSettings in - let passcodeSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationPasscodeSettings]?.get(PresentationPasscodeSettings.self) ?? PresentationPasscodeSettings.defaultSettings - - var settings: WebBrowserSettings - if let current = sharedData.entries[ApplicationSpecificSharedDataKeys.webBrowserSettings]?.get(WebBrowserSettings.self) { - settings = current - } else { - settings = .defaultSettings - } - if accessChallengeData.data.isLockable { - if passcodeSettings.autolockTimeout != nil && settings.defaultWebBrowser == "inApp" { - settings = WebBrowserSettings(defaultWebBrowser: "safari", exceptions: []) - } - } - return settings - } - - let _ = (settings - |> deliverOnMainQueue).startStandalone(next: { settings in - var isTonSite = false - if let host = parsedUrl.host, host.lowercased().hasSuffix(".ton") { - isTonSite = true - } else if let scheme = parsedUrl.scheme, scheme.lowercased().hasPrefix("tonsite") { - isTonSite = true - } - - if let defaultWebBrowser = settings.defaultWebBrowser, defaultWebBrowser != "inApp" && !isTonSite { - let openInOptions = availableOpenInOptions(context: context, item: .url(url: url)) - if let option = openInOptions.first(where: { $0.identifier == settings.defaultWebBrowser }) { - if case let .openUrl(openInUrl) = option.action() { - context.sharedContext.applicationBindings.openUrl(openInUrl) - } else { - context.sharedContext.applicationBindings.openUrl(url) - } - } else { - context.sharedContext.applicationBindings.openUrl(url) - } - } else { - var isExceptedDomain = false - let host = ".\((parsedUrl.host ?? "").lowercased())" - for exception in settings.exceptions { - if host.hasSuffix(".\(exception.domain)") { - isExceptedDomain = true - break - } - } - - if (settings.defaultWebBrowser == nil && !isExceptedDomain) || isTonSite { - let controller = BrowserScreen(context: context, subject: .webPage(url: parsedUrl.absoluteString)) - navigationController?.pushViewController(controller) - } else { - if let window = navigationController?.view.window, !isExceptedDomain { - let controller = SFSafariViewController(url: parsedUrl) - controller.preferredBarTintColor = presentationData.theme.rootController.navigationBar.opaqueBackgroundColor - controller.preferredControlTintColor = presentationData.theme.rootController.navigationBar.accentTextColor - window.rootViewController?.present(controller, animated: true) - } else { - context.sharedContext.applicationBindings.openUrl(parsedUrl.absoluteString) - } - } - } - }) - } - } else { - context.sharedContext.applicationBindings.openUrl(url) - } + handleInternetUrl( + parsedUrl: parsedUrl, + originalUrl: url, + context: context, + presentationData: presentationData, + navigationController: navigationController, + handleInternalUrl: handleInternalUrl + ) } - if parsedUrl.scheme == "http" || parsedUrl.scheme == "https" { - let nativeHosts = ["t.me", "telegram.me", "telegram.dog"] - if let host = parsedUrl.host, nativeHosts.contains(host) { + if let scheme = parsedUrl.scheme, internetSchemes.contains(scheme) { + if let host = parsedUrl.host, telegramMeHosts.contains(host) { continueHandling() } else { - context.sharedContext.applicationBindings.openUniversalUrl(url, TelegramApplicationOpenUrlCompletion(completion: { success in - if !success { - continueHandling() - } - })) + if isTelegraPhLink(parsedUrl.absoluteString) { + continueHandling() + } else { + context.sharedContext.applicationBindings.openUniversalUrl(url, TelegramApplicationOpenUrlCompletion(completion: { success in + if !success { + continueHandling() + } + })) + } } } else { continueHandling() diff --git a/submodules/TelegramUI/Sources/SharedAccountContext.swift b/submodules/TelegramUI/Sources/SharedAccountContext.swift index 3d727ce1..47680770 100644 --- a/submodules/TelegramUI/Sources/SharedAccountContext.swift +++ b/submodules/TelegramUI/Sources/SharedAccountContext.swift @@ -1,3 +1,10 @@ +// MARK: Swiftgram +import SGIAP +import SGPayWall +import SGProUI +import SGSimpleSettings +import SGStatus +// import Foundation import UIKit import AsyncDisplayKit @@ -95,6 +102,7 @@ import PasskeysScreen import GiftDemoScreen import ChatTextLinkEditUI import CocoonInfoScreen +import GiftCraftScreen private final class AccountUserInterfaceInUseContext { let subscribers = Bag<(Bool) -> Void>() @@ -254,6 +262,9 @@ public final class SharedAccountContextImpl: SharedAccountContext { public let currentMediaDisplaySettings: Atomic private var mediaDisplaySettingsDisposable: Disposable? + public let currentChatSettings: Atomic + private var chatSettingsDisposable: Disposable? + public let currentStickerSettings: Atomic private var stickerSettingsDisposable: Disposable? @@ -264,6 +275,14 @@ public final class SharedAccountContextImpl: SharedAccountContext { return self.immediateExperimentalUISettingsValue.with { $0 } } private var experimentalUISettingsDisposable: Disposable? + + // MARK: Swiftgram + private var immediateSGStatusValue = Atomic(value: SGStatus.default) + public var immediateSGStatus: SGStatus { + return self.immediateSGStatusValue.with { $0 } + } + private var sgStatusDisposable: Disposable? + public var SGIAP: SGIAPManager? public var presentGlobalController: (ViewController, Any?) -> Void = { _, _ in } public var presentCrossfadeController: () -> Void = {} @@ -338,6 +357,7 @@ public final class SharedAccountContextImpl: SharedAccountContext { self.currentMediaDisplaySettings = Atomic(value: initialPresentationDataAndSettings.mediaDisplaySettings) self.currentStickerSettings = Atomic(value: initialPresentationDataAndSettings.stickerSettings) self.currentInAppNotificationSettings = Atomic(value: initialPresentationDataAndSettings.inAppNotificationSettings) + self.currentChatSettings = Atomic(value: ChatSettings.defaultSettings) if automaticEnergyUsageShouldBeOnNow(settings: self.currentAutomaticMediaDownloadSettings) { self.energyUsageSettings = EnergyUsageSettings.powerSavingDefault @@ -484,6 +504,15 @@ public final class SharedAccountContextImpl: SharedAccountContext { } }) + self.chatSettingsDisposable = (self.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.chatSettings]) + |> deliverOnMainQueue).start(next: { [weak self] sharedData in + if let strongSelf = self { + if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.chatSettings]?.get(ChatSettings.self) { + let _ = strongSelf.currentChatSettings.swap(settings) + } + } + }) + let immediateExperimentalUISettingsValue = self.immediateExperimentalUISettingsValue let _ = immediateExperimentalUISettingsValue.swap(initialPresentationDataAndSettings.experimentalUISettings) @@ -498,6 +527,18 @@ public final class SharedAccountContextImpl: SharedAccountContext { GlassBackgroundView.useCustomGlassImpl = settings.fakeGlass } }) + // MARK: Swiftgram + let immediateSGStatusValue = self.immediateSGStatusValue + self.sgStatusDisposable = (self.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.sgStatus]) + |> deliverOnMainQueue).start(next: { sharedData in + if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.sgStatus]?.get(SGStatus.self) { + let _ = immediateSGStatusValue.swap(settings) + SGSimpleSettings.shared.ephemeralStatus = settings.status + SGSimpleSettings.shared.status = settings.status + } + }) + self.initSGIAP(isMainApp: applicationBindings.isMainApp) + // let _ = self.contactDataManager?.personNameDisplayOrder().start(next: { order in let _ = updateContactSettingsInteractively(accountManager: accountManager, { settings in @@ -1077,6 +1118,8 @@ public final class SharedAccountContextImpl: SharedAccountContext { self.inAppNotificationSettingsDisposable?.dispose() self.mediaInputSettingsDisposable?.dispose() self.mediaDisplaySettingsDisposable?.dispose() + self.chatSettingsDisposable?.dispose() + self.stickerSettingsDisposable?.dispose() self.callDisposable?.dispose() self.groupCallDisposable?.dispose() self.callStateDisposable?.dispose() @@ -1084,8 +1127,20 @@ public final class SharedAccountContextImpl: SharedAccountContext { self.callPeerDisposable?.dispose() } + // MARK: Swiftgram + var didPerformSGUISettingsMigration = false + // + // MARK: Swiftgram + func sgPrimaryAccountContextForMigration() -> AccountContext? { + return self.activeAccountsValue?.primary + } + // private var didPerformAccountSettingsImport = false + private func performAccountSettingsImportIfNecessary() { + // MARK: Swiftgram + self.performSGUISettingsMigrationIfNecessary() + // if self.didPerformAccountSettingsImport { return } @@ -3767,7 +3822,24 @@ public final class SharedAccountContextImpl: SharedAccountContext { } public func makeStarsTransferScreen(context: AccountContext, starsContext: StarsContext, invoice: TelegramMediaInvoice, source: BotPaymentInvoiceSource, extendedMedia: [TelegramExtendedMedia], inputData: Signal<(StarsContext.State, BotPaymentForm, EnginePeer?, EnginePeer?)?, NoError>, completion: @escaping (Bool) -> Void) -> ViewController { - return StarsTransferScreen(context: context, starsContext: starsContext, invoice: invoice, source: source, extendedMedia: extendedMedia, inputData: inputData, completion: completion) + return StarsTransferScreen(context: context, starsContext: starsContext, invoice: invoice, source: source, extendedMedia: extendedMedia, inputData: inputData, navigateToPeer: { [weak self] peer in + guard let self else { + return + } + if let infoController = self.makePeerInfoController( + context: context, + updatedPresentationData: nil, + peer: peer._asPeer(), + mode: .generic, + avatarInitiallyExpanded: peer.smallProfileImage != nil, + fromChat: false, + requestsContext: nil + ) { + if let navigationController = self.mainWindow?.viewController as? NavigationController { + navigationController.pushViewController(infoController) + } + } + }, completion: completion) } public func makeStarsSubscriptionTransferScreen(context: AccountContext, starsContext: StarsContext, invoice: TelegramMediaInvoice, link: String, inputData: Signal<(StarsContext.State, BotPaymentForm, EnginePeer?, EnginePeer?)?, NoError>, navigateToPeer: @escaping (EnginePeer) -> Void) -> ViewController { @@ -3851,7 +3923,7 @@ public final class SharedAccountContextImpl: SharedAccountContext { return GiftViewScreen(context: context, subject: .wearPreview(gift, attributes)) } - public func makeGiftUpgradePreviewScreen(context: AccountContext, attributes: [StarGift.UniqueGift.Attribute], peerName: String) -> ViewController { + public func makeGiftUpgradePreviewScreen(context: AccountContext, gift: StarGift.Gift, attributes: [StarGift.UniqueGift.Attribute], peerName: String) -> ViewController { return GiftViewScreen(context: context, subject: .upgradePreview(attributes, peerName)) } @@ -3875,7 +3947,7 @@ public final class SharedAccountContextImpl: SharedAccountContext { return giftOfferAlertController(context: context, updatedPresentationData: updatedPresentationData, gift: gift, peer: peer, amount: amount, commit: commit) } - public func makeGiftUpgradeVariantsScreen(context: AccountContext, gift: StarGift, attributes: [StarGift.UniqueGift.Attribute], selectedAttributes: [StarGift.UniqueGift.Attribute]?, focusedAttribute: StarGift.UniqueGift.Attribute?) -> ViewController { + public func makeGiftUpgradeVariantsScreen(context: AccountContext, gift: StarGift, crafted: Bool, attributes: [StarGift.UniqueGift.Attribute], selectedAttributes: [StarGift.UniqueGift.Attribute]?, focusedAttribute: StarGift.UniqueGift.Attribute?) -> ViewController { return GiftUpgradeVariantsScreen(context: context, gift: gift, attributes: attributes, selectedAttributes: selectedAttributes, focusedAttribute: focusedAttribute) } @@ -3883,6 +3955,10 @@ public final class SharedAccountContextImpl: SharedAccountContext { return GiftAuctionWearPreviewScreen(context: context, auctionContext: auctionContext, attributes: attributes, completion: completion) } + public func makeGiftCraftScreen(context: AccountContext, gift: StarGift.UniqueGift, profileGiftsContext: ProfileGiftsContext?) -> ViewController { + return GiftCraftScreen(context: context, gift: gift, profileGiftsContext: profileGiftsContext) + } + public func makeGiftDemoScreen(context: AccountContext) -> ViewController { return GiftDemoScreen(context: context) } @@ -4094,8 +4170,23 @@ public final class SharedAccountContextImpl: SharedAccountContext { } private func peerInfoControllerImpl(context: AccountContext, updatedPresentationData: (PresentationData, Signal)?, peer: Peer, mode: PeerInfoControllerMode, avatarInitiallyExpanded: Bool, isOpenedFromChat: Bool, requestsContext: PeerInvitationImportersContext? = nil) -> ViewController? { + var switchToMediaTarget: PeerInfoSwitchToMediaTarget? + switch mode { + case let .media(kind, index): + let mappedKind: PeerInfoSwitchToMediaTarget.Kind + switch kind { + case .photoVideo: + mappedKind = .photoVideo + case .file: + mappedKind = .file + } + switchToMediaTarget = PeerInfoSwitchToMediaTarget(kind: mappedKind, messageIndex: index) + default: + break + } + if let _ = peer as? TelegramGroup { - return PeerInfoScreenImpl(context: context, updatedPresentationData: updatedPresentationData, peerId: peer.id, avatarInitiallyExpanded: avatarInitiallyExpanded, isOpenedFromChat: isOpenedFromChat, nearbyPeerDistance: nil, reactionSourceMessageId: nil, callMessages: []) + return PeerInfoScreenImpl(context: context, updatedPresentationData: updatedPresentationData, peerId: peer.id, avatarInitiallyExpanded: avatarInitiallyExpanded, isOpenedFromChat: isOpenedFromChat, nearbyPeerDistance: nil, reactionSourceMessageId: nil, callMessages: [], switchToMediaTarget: switchToMediaTarget) } else if let _ = peer as? TelegramChannel { var forumTopicThread: ChatReplyThreadMessage? var switchToRecommendedChannels = false @@ -4118,7 +4209,7 @@ private func peerInfoControllerImpl(context: AccountContext, updatedPresentation default: break } - return PeerInfoScreenImpl(context: context, updatedPresentationData: updatedPresentationData, peerId: peer.id, avatarInitiallyExpanded: avatarInitiallyExpanded, isOpenedFromChat: isOpenedFromChat, nearbyPeerDistance: nil, reactionSourceMessageId: nil, callMessages: [], forumTopicThread: forumTopicThread, switchToRecommendedChannels: switchToRecommendedChannels, switchToGiftsTarget: switchToGiftsTarget, switchToGroupsInCommon: switchToGroupsInCommon, switchToStoryFolder: switchToStoryFolder) + return PeerInfoScreenImpl(context: context, updatedPresentationData: updatedPresentationData, peerId: peer.id, avatarInitiallyExpanded: avatarInitiallyExpanded, isOpenedFromChat: isOpenedFromChat, nearbyPeerDistance: nil, reactionSourceMessageId: nil, callMessages: [], forumTopicThread: forumTopicThread, switchToRecommendedChannels: switchToRecommendedChannels, switchToGiftsTarget: switchToGiftsTarget, switchToGroupsInCommon: switchToGroupsInCommon, switchToStoryFolder: switchToStoryFolder, switchToMediaTarget: switchToMediaTarget) } else if peer is TelegramUser { var nearbyPeerDistance: Int32? var reactionSourceMessageId: MessageId? @@ -4171,9 +4262,9 @@ private func peerInfoControllerImpl(context: AccountContext, updatedPresentation default: break } - return PeerInfoScreenImpl(context: context, updatedPresentationData: updatedPresentationData, peerId: peer.id, avatarInitiallyExpanded: avatarInitiallyExpanded, isOpenedFromChat: isOpenedFromChat, nearbyPeerDistance: nearbyPeerDistance, reactionSourceMessageId: reactionSourceMessageId, callMessages: callMessages, isMyProfile: isMyProfile, hintGroupInCommon: hintGroupInCommon, forumTopicThread: forumTopicThread, sharedMediaFromForumTopic: sharedMediaFromForumTopic, switchToGiftsTarget: switchToGiftsTarget, switchToGroupsInCommon: switchToGroupsInCommon, switchToStoryFolder: switchToStoryFolder) + return PeerInfoScreenImpl(context: context, updatedPresentationData: updatedPresentationData, peerId: peer.id, avatarInitiallyExpanded: avatarInitiallyExpanded, isOpenedFromChat: isOpenedFromChat, nearbyPeerDistance: nearbyPeerDistance, reactionSourceMessageId: reactionSourceMessageId, callMessages: callMessages, isMyProfile: isMyProfile, hintGroupInCommon: hintGroupInCommon, forumTopicThread: forumTopicThread, sharedMediaFromForumTopic: sharedMediaFromForumTopic, switchToGiftsTarget: switchToGiftsTarget, switchToGroupsInCommon: switchToGroupsInCommon, switchToStoryFolder: switchToStoryFolder, switchToMediaTarget: switchToMediaTarget) } else if peer is TelegramSecretChat { - return PeerInfoScreenImpl(context: context, updatedPresentationData: updatedPresentationData, peerId: peer.id, avatarInitiallyExpanded: avatarInitiallyExpanded, isOpenedFromChat: isOpenedFromChat, nearbyPeerDistance: nil, reactionSourceMessageId: nil, callMessages: []) + return PeerInfoScreenImpl(context: context, updatedPresentationData: updatedPresentationData, peerId: peer.id, avatarInitiallyExpanded: avatarInitiallyExpanded, isOpenedFromChat: isOpenedFromChat, nearbyPeerDistance: nil, reactionSourceMessageId: nil, callMessages: [], switchToMediaTarget: switchToMediaTarget) } return nil } @@ -4184,3 +4275,64 @@ private func useFlatModalCallsPresentation(context: AccountContext) -> Bool { } return true } + + + +// MARK: Swiftgram +extension SharedAccountContextImpl { + func initSGIAP(isMainApp: Bool) { + if isMainApp { + self.SGIAP = SGIAPManager() + } else { + self.SGIAP = nil + } + } + + public func makeSGProController(context: AccountContext) -> ViewController { + let controller = sgProController(context: context) + return controller + } + + public func makeSGPayWallController(context: AccountContext) -> ViewController? { + guard #available(iOS 13.0, *) else { + return nil + } + guard let sgIAP = self.SGIAP else { + return nil + } + + let statusSignal = self.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.sgStatus]) + |> map { sharedData -> Int64 in + let sgStatus = sharedData.entries[ApplicationSpecificSharedDataKeys.sgStatus]?.get(SGStatus.self) ?? SGStatus.default + return sgStatus.status + } + + let proController = self.makeSGProController(context: context) + let sgWebSettings = context.currentAppConfiguration.with { $0 }.sgWebSettings + let presentationData = self.currentPresentationData.with { $0 } + var payWallController: ViewController? = nil + let openUrl: ((String, Bool) -> Void) = { [weak self, weak context] url, forceExternal in + guard let strongSelf = self, let strongContext = context, let strongPayWallController = payWallController else { + return + } + let navigationController = strongPayWallController.navigationController as? NavigationController + Queue.mainQueue().async { + strongSelf.openExternalUrl(context: strongContext, urlContext: .generic, url: url, forceExternal: forceExternal, presentationData: presentationData, navigationController: navigationController, dismissInput: {}) + } + } + + var supportUrl: String? = nil + if let supportUrlString = sgWebSettings.global.proSupportUrl, !supportUrlString.isEmpty, let data = Data(base64Encoded: supportUrlString), let decodedString = String(data: data, encoding: .utf8) { + supportUrl = decodedString + } + payWallController = sgPayWallController(statusSignal: statusSignal, replacementController: proController, presentationData: presentationData, SGIAPManager: sgIAP, openUrl: openUrl, paymentsEnabled: sgWebSettings.global.paymentsEnabled, canBuyInBeta: sgWebSettings.user.canBuyInBeta, openAppStorePage: self.applicationBindings.openAppStorePage, proSupportUrl: supportUrl) + return payWallController + } + + public func makeSGUpdateIOSController() -> ViewController { + let presentationData = self.currentPresentationData.with { $0 } + let controller = textAlertController(sharedContext: self, title: nil, text: "Common.UpdateOS".i18n(presentationData.strings.baseLanguageCode), actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: { + })]) + return controller + } +} diff --git a/submodules/TelegramUI/Sources/TelegramRootController.swift b/submodules/TelegramUI/Sources/TelegramRootController.swift index 8b4fee9e..5defcd09 100644 --- a/submodules/TelegramUI/Sources/TelegramRootController.swift +++ b/submodules/TelegramUI/Sources/TelegramRootController.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import Display @@ -41,7 +42,7 @@ private class DetailsChatPlaceholderNode: ASDisplayNode, NavigationDetailsPlaceh init(context: AccountContext) { self.presentationData = context.sharedContext.currentPresentationData.with { $0 } - self.presentationInterfaceState = ChatPresentationInterfaceState(chatWallpaper: self.presentationData.chatWallpaper, theme: self.presentationData.theme, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, limitsConfiguration: context.currentLimitsConfiguration.with { $0 }, fontSize: self.presentationData.chatFontSize, bubbleCorners: self.presentationData.chatBubbleCorners, accountPeerId: context.account.peerId, mode: .standard(.default), chatLocation: .peer(id: context.account.peerId), subject: nil, peerNearbyData: nil, greetingData: nil, pendingUnpinnedAllMessages: false, activeGroupCallInfo: nil, hasActiveGroupCall: false, threadData: nil, isGeneralThreadClosed: nil, replyMessage: nil, accountPeerColor: nil, businessIntro: nil) + self.presentationInterfaceState = ChatPresentationInterfaceState(chatWallpaper: self.presentationData.chatWallpaper, theme: self.presentationData.theme, preferredGlassType: .default, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, limitsConfiguration: context.currentLimitsConfiguration.with { $0 }, fontSize: self.presentationData.chatFontSize, bubbleCorners: self.presentationData.chatBubbleCorners, accountPeerId: context.account.peerId, mode: .standard(.default), chatLocation: .peer(id: context.account.peerId), subject: nil, peerNearbyData: nil, greetingData: nil, pendingUnpinnedAllMessages: false, activeGroupCallInfo: nil, hasActiveGroupCall: false, threadData: nil, isGeneralThreadClosed: nil, replyMessage: nil, accountPeerColor: nil, businessIntro: nil) self.wallpaperBackgroundNode = createWallpaperBackgroundNode(context: context, forChatDisplay: true, useSharedAnimationPhase: true) self.emptyNode = ChatEmptyNode(context: context, interaction: nil) @@ -54,7 +55,8 @@ private class DetailsChatPlaceholderNode: ASDisplayNode, NavigationDetailsPlaceh func updatePresentationData(_ presentationData: PresentationData) { self.presentationData = presentationData - self.presentationInterfaceState = ChatPresentationInterfaceState(chatWallpaper: self.presentationData.chatWallpaper, theme: self.presentationData.theme, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, limitsConfiguration: self.presentationInterfaceState.limitsConfiguration, fontSize: self.presentationData.chatFontSize, bubbleCorners: self.presentationData.chatBubbleCorners, accountPeerId: self.presentationInterfaceState.accountPeerId, mode: .standard(.default), chatLocation: self.presentationInterfaceState.chatLocation, subject: nil, peerNearbyData: nil, greetingData: nil, pendingUnpinnedAllMessages: false, activeGroupCallInfo: nil, hasActiveGroupCall: false, threadData: nil, isGeneralThreadClosed: nil, replyMessage: nil, accountPeerColor: nil, businessIntro: nil) + let preferredGlassType = self.presentationInterfaceState.preferredGlassType + self.presentationInterfaceState = ChatPresentationInterfaceState(chatWallpaper: self.presentationData.chatWallpaper, theme: self.presentationData.theme, preferredGlassType: preferredGlassType, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, limitsConfiguration: self.presentationInterfaceState.limitsConfiguration, fontSize: self.presentationData.chatFontSize, bubbleCorners: self.presentationData.chatBubbleCorners, accountPeerId: self.presentationInterfaceState.accountPeerId, mode: .standard(.default), chatLocation: self.presentationInterfaceState.chatLocation, subject: nil, peerNearbyData: nil, greetingData: nil, pendingUnpinnedAllMessages: false, activeGroupCallInfo: nil, hasActiveGroupCall: false, threadData: nil, isGeneralThreadClosed: nil, replyMessage: nil, accountPeerColor: nil, businessIntro: nil) self.wallpaperBackgroundNode.update(wallpaper: presentationData.chatWallpaper, animated: false) } @@ -156,10 +158,18 @@ public final class TelegramRootController: NavigationController, TelegramRootCon return self.chatListController } + public func getSettingsController() -> ViewController? { + return self.accountSettingsController + } + public func getPrivacySettings() -> Promise? { return self.accountSettingsController?.privacySettings } + public func getTwoStepAuthData() -> Promise? { + return self.accountSettingsController?.twoStepAuthData + } + override public func containerLayoutUpdated(_ layout: ContainerViewLayout, transition: ContainedViewLayoutTransition) { let needsRootWallpaperBackgroundNode: Bool if case .regular = layout.metrics.widthClass { @@ -186,7 +196,7 @@ public final class TelegramRootController: NavigationController, TelegramRootCon super.containerLayoutUpdated(layout, transition: transition) } - public func addRootControllers(showCallsTab: Bool) { + public func addRootControllers(hidePhoneInSettings: Bool, showContactsTab: Bool, showCallsTab: Bool) { let tabBarController = TabBarControllerImpl(theme: self.presentationData.theme, strings: self.presentationData.strings) tabBarController.navigationPresentation = .master let chatListController = self.context.sharedContext.makeChatListController(context: self.context, location: .chatList(groupId: .root), controlsHistoryPreload: true, hideNetworkActivityStatus: false, previewing: false, enableDebugActions: !GlobalExperimentalSettings.isAppStoreBuild) @@ -201,7 +211,10 @@ public final class TelegramRootController: NavigationController, TelegramRootCon contactsController.switchToChatsController = { [weak self] in self?.openChatsController(activateSearch: false) } - controllers.append(contactsController) + // MARK: Swiftgram + if showContactsTab { + controllers.append(contactsController) + } if showCallsTab { controllers.append(callListController) @@ -217,7 +230,7 @@ public final class TelegramRootController: NavigationController, TelegramRootCon sharedContext.switchingData = (nil, nil, nil) } - let accountSettingsController = PeerInfoScreenImpl(context: self.context, updatedPresentationData: nil, peerId: self.context.account.peerId, avatarInitiallyExpanded: false, isOpenedFromChat: false, nearbyPeerDistance: nil, reactionSourceMessageId: nil, callMessages: [], isSettings: true) + let accountSettingsController = PeerInfoScreenImpl(hidePhoneInSettings: hidePhoneInSettings, context: self.context, updatedPresentationData: nil, peerId: self.context.account.peerId, avatarInitiallyExpanded: false, isOpenedFromChat: false, nearbyPeerDistance: nil, reactionSourceMessageId: nil, callMessages: [], isSettings: true) accountSettingsController.tabBarItemDebugTapAction = { [weak self] in guard let strongSelf = self else { return @@ -237,12 +250,14 @@ public final class TelegramRootController: NavigationController, TelegramRootCon self.pushViewController(tabBarController, animated: false) } - public func updateRootControllers(showCallsTab: Bool) { + public func updateRootControllers(showContactsTab: Bool, showCallsTab: Bool) { guard let rootTabController = self.rootTabController as? TabBarControllerImpl else { return } var controllers: [ViewController] = [] - controllers.append(self.contactsController!) + if showContactsTab { + controllers.append(self.contactsController!) + } if showCallsTab { controllers.append(self.callListController!) } @@ -300,7 +315,7 @@ public final class TelegramRootController: NavigationController, TelegramRootCon } @discardableResult - public func openStoryCamera(customTarget: Stories.PendingTarget?, resumeLiveStream: Bool, transitionIn: StoryCameraTransitionIn?, transitionedIn: @escaping () -> Void, transitionOut: @escaping (Stories.PendingTarget?, Bool) -> StoryCameraTransitionOut?) -> StoryCameraTransitionInCoordinator? { + public func openStoryCamera(mode: StoryCameraMode, customTarget: Stories.PendingTarget?, resumeLiveStream: Bool, transitionIn: StoryCameraTransitionIn?, transitionedIn: @escaping () -> Void, transitionOut: @escaping (Stories.PendingTarget?, Bool) -> StoryCameraTransitionOut?) -> StoryCameraTransitionInCoordinator? { guard let controller = self.viewControllers.last as? ViewController else { return nil } @@ -675,7 +690,7 @@ public final class TelegramRootController: NavigationController, TelegramRootCon defer { TempBox.shared.dispose(tempFile) } - if let imageData = compressImageToJPEG(image, quality: 0.7, tempFilePath: tempFile.path) { + if let imageData = compressImageToJPEG(image, quality: Float(SGSimpleSettings.shared.outgoingPhotoQuality) / 100.0, tempFilePath: tempFile.path) { media = .image(dimensions: dimensions, data: imageData, stickers: result.stickers) } case let .video(content, firstFrameImage, values, duration, dimensions): @@ -698,7 +713,7 @@ public final class TelegramRootController: NavigationController, TelegramRootCon defer { TempBox.shared.dispose(tempFile) } - let imageData = firstFrameImage.flatMap { compressImageToJPEG($0, quality: 0.6, tempFilePath: tempFile.path) } + let imageData = firstFrameImage.flatMap { compressImageToJPEG($0, quality: Float(SGSimpleSettings.shared.outgoingPhotoQuality) / 100.0, tempFilePath: tempFile.path) } let firstFrameFile = imageData.flatMap { data -> TempBoxFile? in let file = TempBox.shared.tempFile(fileName: "image.jpg") if let _ = try? data.write(to: URL(fileURLWithPath: file.path)) { @@ -758,7 +773,31 @@ public final class TelegramRootController: NavigationController, TelegramRootCon } } - public func openSettings() { + public func openChats() { + guard let rootTabController = self.rootTabController else { + return + } + + self.popToRoot(animated: false) + + if let index = rootTabController.controllers.firstIndex(where: { $0 is ChatListController }) { + rootTabController.selectedIndex = index + } + } + + public func openContacts() { + guard let rootTabController = self.rootTabController else { + return + } + + self.popToRoot(animated: false) + + if let index = rootTabController.controllers.firstIndex(where: { $0 is ContactsController }) { + rootTabController.selectedIndex = index + } + } + + public func openSettings(edit: Bool) { guard let rootTabController = self.rootTabController else { return } @@ -768,6 +807,10 @@ public final class TelegramRootController: NavigationController, TelegramRootCon if let index = rootTabController.controllers.firstIndex(where: { $0 is PeerInfoScreenImpl }) { rootTabController.selectedIndex = index } + + if edit { + self.accountSettingsController?.activateEdit() + } } public func openBirthdaySetup() { @@ -784,6 +827,10 @@ public final class TelegramRootController: NavigationController, TelegramRootCon accountSettingsController.openAvatars() } } + + public func startNewCall() { + self.callListController?.tabBarActivateSearch() + } } #if SWIFT_PACKAGE diff --git a/submodules/TelegramUI/Sources/TransformOutgoingMessageMedia.swift b/submodules/TelegramUI/Sources/TransformOutgoingMessageMedia.swift index 51b7b85a..aa94c8b5 100644 --- a/submodules/TelegramUI/Sources/TransformOutgoingMessageMedia.swift +++ b/submodules/TelegramUI/Sources/TransformOutgoingMessageMedia.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import TelegramCore @@ -169,7 +170,8 @@ public func transformOutgoingMessageMedia(postbox: Postbox, network: Network, me defer { TempBox.shared.dispose(tempFile) } - if let fullImage = UIImage(contentsOfFile: data.path), let smallestImage = generateScaledImage(image: fullImage, size: smallestSize, scale: 1.0), let smallestData = compressImageToJPEG(smallestImage, quality: 0.7, tempFilePath: tempFile.path) { + // MARK: Swiftgram + if let fullImage = UIImage(contentsOfFile: data.path), let smallestImage = generateScaledImage(image: fullImage, size: smallestSize, scale: 1.0), let smallestData = compressImageToJPEG(smallestImage, quality: Float(SGSimpleSettings.shared.outgoingPhotoQuality) / 100.0, tempFilePath: tempFile.path) { var representations = image.representations let thumbnailResource = LocalFileMediaResource(fileId: Int64.random(in: Int64.min ... Int64.max)) diff --git a/submodules/TelegramUI/Sources/WatchManager.swift b/submodules/TelegramUI/Sources/WatchManager.swift new file mode 100644 index 00000000..daebf130 --- /dev/null +++ b/submodules/TelegramUI/Sources/WatchManager.swift @@ -0,0 +1,25 @@ +import Foundation +import SwiftSignalKit +import TelegramCore +import AccountContext +import WatchBridge + +public final class WatchManagerImpl: WatchManager { + private let arguments: WatchManagerArguments? + + public init(arguments: WatchManagerArguments?) { + self.arguments = arguments + } + + public var watchAppInstalled: Signal { + return self.arguments?.appInstalled ?? .single(false) + } + + public var navigateToMessageRequested: Signal { + return self.arguments?.navigateToMessageRequested ?? .never() + } + + public var runningTasks: Signal { + return self.arguments?.runningTasks ?? .single(nil) + } +} diff --git a/submodules/TelegramUIPreferences/Sources/CallListSettings.swift b/submodules/TelegramUIPreferences/Sources/CallListSettings.swift index 850f6c62..eb667147 100644 --- a/submodules/TelegramUIPreferences/Sources/CallListSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/CallListSettings.swift @@ -3,10 +3,24 @@ import TelegramCore import SwiftSignalKit public struct CallListSettings: Codable, Equatable { + public var _showContactsTab: Bool? public var _showTab: Bool? + + public var showContactsTab: Bool { + get { + if let value = self._showContactsTab { + return value + } else { + return true + } + } + set { + self._showContactsTab = newValue + } + } public static var defaultSettings: CallListSettings { - return CallListSettings(showTab: nil) + return CallListSettings(showContactsTab: nil, showTab: nil) } public var showTab: Bool { @@ -21,13 +35,17 @@ public struct CallListSettings: Codable, Equatable { } } - public init(showTab: Bool?) { + public init(showContactsTab: Bool?, showTab: Bool?) { + self._showContactsTab = showContactsTab self._showTab = showTab } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) + if let value = try container.decodeIfPresent(Int32.self, forKey: "showContactsTab") { + self._showContactsTab = value != 0 + } if let value = try container.decodeIfPresent(Int32.self, forKey: "showTab") { self._showTab = value != 0 } @@ -36,6 +54,11 @@ public struct CallListSettings: Codable, Equatable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) + if let showContactsTab = self._showContactsTab { + try container.encode((showContactsTab ? 1 : 0) as Int32, forKey: "showContactsTab") + } else { + try container.encodeNil(forKey: "showContactsTab") + } if let showTab = self._showTab { try container.encode((showTab ? 1 : 0) as Int32, forKey: "showTab") } else { @@ -44,11 +67,15 @@ public struct CallListSettings: Codable, Equatable { } public static func ==(lhs: CallListSettings, rhs: CallListSettings) -> Bool { - return lhs._showTab == rhs._showTab + return lhs._showContactsTab == rhs._showContactsTab && lhs._showTab == rhs._showTab + } + + public func withUpdatedShowContactsTab(_ showContactsTab: Bool) -> CallListSettings { + return CallListSettings(showContactsTab: showContactsTab, showTab: self._showTab) } public func withUpdatedShowTab(_ showTab: Bool) -> CallListSettings { - return CallListSettings(showTab: showTab) + return CallListSettings(showContactsTab: self._showContactsTab, showTab: showTab) } } diff --git a/submodules/TelegramUIPreferences/Sources/ChatSettings.swift b/submodules/TelegramUIPreferences/Sources/ChatSettings.swift new file mode 100644 index 00000000..a6cfee2e --- /dev/null +++ b/submodules/TelegramUIPreferences/Sources/ChatSettings.swift @@ -0,0 +1,49 @@ +import Foundation +import TelegramCore +import SwiftSignalKit + +public struct ChatSettings: Codable, Equatable { + public let sendWithCmdEnter: Bool + + public static var defaultSettings: ChatSettings { + return ChatSettings(sendWithCmdEnter: false) + } + + public init(sendWithCmdEnter: Bool) { + self.sendWithCmdEnter = sendWithCmdEnter + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.sendWithCmdEnter = (try container.decode(Int32.self, forKey: "sendWithCmdEnter")) != 0 + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode((self.sendWithCmdEnter ? 1 : 0) as Int32, forKey: "sendWithCmdEnter") + } + + public static func ==(lhs: ChatSettings, rhs: ChatSettings) -> Bool { + return lhs.sendWithCmdEnter == rhs.sendWithCmdEnter + } + + public func withUpdatedSendWithCmdEnter(_ sendWithCmdEnter: Bool) -> ChatSettings { + return ChatSettings(sendWithCmdEnter: sendWithCmdEnter) + } +} + +public func updateChatSettingsInteractively(accountManager: AccountManager, _ f: @escaping (ChatSettings) -> ChatSettings) -> Signal { + return accountManager.transaction { transaction -> Void in + transaction.updateSharedData(ApplicationSpecificSharedDataKeys.chatSettings, { entry in + let currentSettings: ChatSettings + if let entry = entry?.get(ChatSettings.self) { + currentSettings = entry + } else { + currentSettings = ChatSettings.defaultSettings + } + return SharedPreferencesEntry(f(currentSettings)) + }) + } +} diff --git a/submodules/TelegramUIPreferences/Sources/PostboxKeys.swift b/submodules/TelegramUIPreferences/Sources/PostboxKeys.swift index 51296e37..e7503119 100644 --- a/submodules/TelegramUIPreferences/Sources/PostboxKeys.swift +++ b/submodules/TelegramUIPreferences/Sources/PostboxKeys.swift @@ -3,6 +3,7 @@ import TelegramCore import Postbox private enum ApplicationSpecificPreferencesKeyValues: Int32 { + case SGUISettings = 900 case voipDerivedState = 16 case chatArchiveSettings = 17 case chatListFilterSettings = 18 @@ -12,6 +13,7 @@ private enum ApplicationSpecificPreferencesKeyValues: Int32 { } public struct ApplicationSpecificPreferencesKeys { + public static let SGUISettings = applicationSpecificPreferencesKey(ApplicationSpecificPreferencesKeyValues.SGUISettings.rawValue) public static let voipDerivedState = applicationSpecificPreferencesKey(ApplicationSpecificPreferencesKeyValues.voipDerivedState.rawValue) public static let chatArchiveSettings = applicationSpecificPreferencesKey(ApplicationSpecificPreferencesKeyValues.chatArchiveSettings.rawValue) public static let chatListFilterSettings = applicationSpecificPreferencesKey(ApplicationSpecificPreferencesKeyValues.chatListFilterSettings.rawValue) @@ -21,6 +23,8 @@ public struct ApplicationSpecificPreferencesKeys { } private enum ApplicationSpecificSharedDataKeyValues: Int32 { + // MARK: Swiftgram + case sgStatus = 999 case inAppNotificationSettings = 0 case presentationPasscodeSettings = 1 case automaticMediaDownloadSettings = 2 @@ -43,9 +47,12 @@ private enum ApplicationSpecificSharedDataKeyValues: Int32 { case drawingSettings = 19 case mediaDisplaySettings = 20 case updateSettings = 21 + case chatSettings = 22 } public struct ApplicationSpecificSharedDataKeys { + // MARK: Swiftgram + public static let sgStatus = applicationSpecificSharedDataKey(ApplicationSpecificSharedDataKeyValues.sgStatus.rawValue) public static let inAppNotificationSettings = applicationSpecificSharedDataKey(ApplicationSpecificSharedDataKeyValues.inAppNotificationSettings.rawValue) public static let presentationPasscodeSettings = applicationSpecificSharedDataKey(ApplicationSpecificSharedDataKeyValues.presentationPasscodeSettings.rawValue) public static let automaticMediaDownloadSettings = applicationSpecificSharedDataKey(ApplicationSpecificSharedDataKeyValues.automaticMediaDownloadSettings.rawValue) @@ -68,6 +75,7 @@ public struct ApplicationSpecificSharedDataKeys { public static let drawingSettings = applicationSpecificPreferencesKey(ApplicationSpecificSharedDataKeyValues.drawingSettings.rawValue) public static let mediaDisplaySettings = applicationSpecificPreferencesKey(ApplicationSpecificSharedDataKeyValues.mediaDisplaySettings.rawValue) public static let updateSettings = applicationSpecificPreferencesKey(ApplicationSpecificSharedDataKeyValues.updateSettings.rawValue) + public static let chatSettings = applicationSpecificPreferencesKey(ApplicationSpecificSharedDataKeyValues.chatSettings.rawValue) } private enum ApplicationSpecificItemCacheCollectionIdValues: Int8 { @@ -104,12 +112,12 @@ public struct ApplicationSpecificItemCacheCollectionId { private enum ApplicationSpecificOrderedItemListCollectionIdValues: Int32 { case webSearchRecentQueries = 0 case wallpaperSearchRecentQueries = 1 - case settingsSearchRecentItems = 2 case localThemes = 3 case storyDrafts = 4 case storySources = 5 case hashtagSearchRecentQueries = 6 case browserRecentlyVisited = 7 + case settingsSearchRecentItems = 8 } public struct ApplicationSpecificOrderedItemListCollectionId { diff --git a/submodules/TranslateUI/BUILD b/submodules/TranslateUI/BUILD index 376c7130..59caa9bd 100644 --- a/submodules/TranslateUI/BUILD +++ b/submodules/TranslateUI/BUILD @@ -1,5 +1,10 @@ load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", + "//submodules/TextFormat:TextFormat" +] + swift_library( name = "TranslateUI", module_name = "TranslateUI", @@ -9,7 +14,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ + deps = sgdeps + [ "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", "//submodules/AsyncDisplayKit:AsyncDisplayKit", "//submodules/Display:Display", @@ -32,6 +37,8 @@ swift_library( "//submodules/UndoUI:UndoUI", "//submodules/ActivityIndicator:ActivityIndicator", "//submodules/ShimmerEffect:ShimmerEffect", + "//submodules/Components/ResizableSheetComponent", + "//submodules/TelegramUI/Components/GlassBarButtonComponent", ], visibility = [ "//visibility:public", diff --git a/submodules/TranslateUI/Sources/TranslateScreen.swift b/submodules/TranslateUI/Sources/TranslateScreen.swift index d246a19a..6e096afa 100644 --- a/submodules/TranslateUI/Sources/TranslateScreen.swift +++ b/submodules/TranslateUI/Sources/TranslateScreen.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import Display @@ -15,6 +16,8 @@ import MultilineTextWithEntitiesComponent import BundleIconComponent import UndoUI import SwiftUI +import ResizableSheetComponent +import GlassBarButtonComponent private func generateExpandBackground(size: CGSize, color: UIColor) -> UIImage { return generateImage(size, rotatedContext: { size, context in @@ -32,7 +35,7 @@ private func generateExpandBackground(size: CGSize, color: UIColor) -> UIImage { })! } -private final class TranslateScreenComponent: CombinedComponent { +private final class SheetContent: CombinedComponent { typealias EnvironmentType = ViewControllerComponentContainer.Environment let context: AccountContext @@ -55,7 +58,7 @@ private final class TranslateScreenComponent: CombinedComponent { self.expand = expand } - static func ==(lhs: TranslateScreenComponent, rhs: TranslateScreenComponent) -> Bool { + static func ==(lhs: SheetContent, rhs: SheetContent) -> Bool { if lhs.context !== rhs.context { return false } @@ -134,7 +137,7 @@ private final class TranslateScreenComponent: CombinedComponent { } func translate(text: String, fromLang: String?, toLang: String) -> Signal<(String, [MessageTextEntity])?, TranslationError> { - if self.useAlternativeTranslation { + if self.useAlternativeTranslation && SGSimpleSettings.shared.translationBackendEnum == .default { return alternativeTranslateText(text: text, fromLang: fromLang, toLang: toLang) } else { return self.context.engine.messages.translate(text: text, toLang: toLang) @@ -249,16 +252,16 @@ private final class TranslateScreenComponent: CombinedComponent { return { context in let environment = context.environment[ViewControllerComponentContainer.Environment.self].value let state = context.state - let theme = environment.theme + let theme = environment.theme.withModalBlocksBackground() let strings = environment.strings - let topInset: CGFloat = environment.navigationHeight + 22.0 - let sideInset: CGFloat = 16.0 + environment.safeInsets.left + let topInset: CGFloat = environment.navigationHeight - 35.0 + let sideInset: CGFloat = 20.0 + environment.safeInsets.left let textTopInset: CGFloat = 16.0 - let textSideInset: CGFloat = 16.0 + let textSideInset: CGFloat = 20.0 let textSpacing: CGFloat = 5.0 - let itemSpacing: CGFloat = 16.0 - let itemHeight: CGFloat = 44.0 + let itemSpacing: CGFloat = 20.0 + let itemHeight: CGFloat = 52.0 var languageCode = environment.strings.baseLanguageCode let rawSuffix = "-raw" @@ -284,7 +287,7 @@ private final class TranslateScreenComponent: CombinedComponent { let originalText = originalText.update( component: MultilineTextComponent( - text: .plain(NSAttributedString(string: state.text, font: Font.medium(17.0), textColor: theme.list.itemPrimaryTextColor, paragraphAlignment: .natural)), + text: .plain(NSAttributedString(string: state.text, font: Font.medium(20.0), textColor: theme.list.itemPrimaryTextColor, paragraphAlignment: .natural)), horizontalAlignment: .natural, maximumNumberOfLines: state.textExpanded ? 0 : 1, lineSpacing: 0.1 @@ -311,7 +314,7 @@ private final class TranslateScreenComponent: CombinedComponent { if let translatedText = state.translatedText { maybeTranslationText = translationText.update( component: MultilineTextComponent( - text: .plain(NSAttributedString(string: translatedText, font: Font.medium(17.0), textColor: theme.list.itemAccentColor, paragraphAlignment: .natural)), + text: .plain(NSAttributedString(string: translatedText, font: Font.medium(20.0), textColor: theme.list.itemAccentColor, paragraphAlignment: .natural)), horizontalAlignment: .natural, maximumNumberOfLines: 0, lineSpacing: 0.1 @@ -340,7 +343,7 @@ private final class TranslateScreenComponent: CombinedComponent { let textBackgroundSize = CGSize(width: context.availableSize.width - sideInset * 2.0, height: textTopInset + originalTitle.size.height + textSpacing + originalText.size.height + itemSpacing + textTopInset + translationTitle.size.height + textSpacing + translationTextHeight + itemSpacing) let textBackground = textBackground.update( - component: RoundedRectangle(color: theme.list.itemBlocksBackgroundColor, cornerRadius: 10.0), + component: RoundedRectangle(color: theme.list.itemBlocksBackgroundColor, cornerRadius: 26.0), availableSize: textBackgroundSize, transition: context.transition ) @@ -372,12 +375,12 @@ private final class TranslateScreenComponent: CombinedComponent { content: AnyComponent(ZStack([ AnyComponentWithIdentity(id: "b", component: AnyComponent(Circle( fillColor: theme.list.itemPrimaryTextColor, - size: CGSize(width: 22.0, height: 22.0) + size: CGSize(width: 26.0, height: 26.0) ))), AnyComponentWithIdentity(id: "a", component: AnyComponent(PlayPauseIconComponent( state: state.isSpeakingOriginalText ? .pause : .play, tintColor: checkColor, - size: CGSize(width: 18.0, height: 18.0) + size: CGSize(width: 20.0, height: 20.0) ))), ])), action: { [weak state] in @@ -387,12 +390,12 @@ private final class TranslateScreenComponent: CombinedComponent { state.speakOriginalText() } ).minSize(CGSize(width: 44.0, height: 44.0)), - availableSize: CGSize(width: 22.0, height: 22.0), + availableSize: CGSize(width: 26.0, height: 26.0), transition: .immediate ) context.add(originalSpeakButton - .position(CGPoint(x: context.availableSize.width - sideInset - textSideInset - originalSpeakButton.size.width / 2.0 - 3.0, y: textBackgroundOrigin.y + textTopInset + originalTitle.size.height + textSpacing + originalText.size.height - originalSpeakButton.size.height / 2.0 - 2.0)) + .position(CGPoint(x: context.availableSize.width - sideInset - textSideInset - originalSpeakButton.size.width / 2.0 + 9.0, y: textBackgroundOrigin.y + textTopInset + originalTitle.size.height + textSpacing + originalText.size.height - originalSpeakButton.size.height / 2.0 - 2.0 + 12.0)) ) } } else { @@ -442,44 +445,46 @@ private final class TranslateScreenComponent: CombinedComponent { context.add(translationText .position(CGPoint(x: textBackgroundOrigin.x + textSideInset + translationText.size.width / 2.0, y: textBackgroundOrigin.y + textTopInset + originalTitle.size.height + textSpacing + originalText.size.height + itemSpacing + textTopInset + translationTitle.size.height + textSpacing + translationText.size.height / 2.0)) ) + + if state.availableSpeakLanguages.contains(state.toLanguage) { + let translationSpeakButton = translationSpeakButton.update( + component: Button( + content: AnyComponent(ZStack([ + AnyComponentWithIdentity(id: "b", component: AnyComponent(Circle( + fillColor: theme.list.itemAccentColor, + size: CGSize(width: 26.0, height: 26.0) + ))), + AnyComponentWithIdentity(id: "a", component: AnyComponent(PlayPauseIconComponent( + state: state.isSpeakingTranslatedText ? .pause : .play, + tintColor: theme.list.itemCheckColors.foregroundColor, + size: CGSize(width: 20.0, height: 20.0) + ))), + ])), + action: { [weak state] in + guard let state = state else { + return + } + state.speakTranslatedText() + } + ).minSize(CGSize(width: 44.0, height: 44.0)), + availableSize: CGSize(width: 26.0, height: 26.0), + transition: .immediate + ) + + context.add(translationSpeakButton + .position(CGPoint(x: context.availableSize.width - sideInset - textSideInset - translationSpeakButton.size.width / 2.0 + 9.0, y: textBackgroundOrigin.y + textTopInset + originalTitle.size.height + textSpacing + originalText.size.height + itemSpacing + textTopInset + translationTitle.size.height + textSpacing + translationTextHeight - translationSpeakButton.size.height / 2.0 - 2.0 + 12.0)) + .appear(.default()) + .disappear(.default()) + ) + } } else if let translationPlaceholder = maybeTranslationPlaceholder { context.add(translationPlaceholder .position(CGPoint(x: textBackgroundOrigin.x + textSideInset + translationPlaceholder.size.width / 2.0, y: textBackgroundOrigin.y + textTopInset + originalTitle.size.height + textSpacing + originalText.size.height + itemSpacing + textTopInset + translationTitle.size.height + textSpacing + translationPlaceholder.size.height / 2.0 + 4.0)) ) } - if state.availableSpeakLanguages.contains(state.toLanguage) { - let translationSpeakButton = translationSpeakButton.update( - component: Button( - content: AnyComponent(ZStack([ - AnyComponentWithIdentity(id: "b", component: AnyComponent(Circle( - fillColor: theme.list.itemAccentColor, - size: CGSize(width: 22.0, height: 22.0) - ))), - AnyComponentWithIdentity(id: "a", component: AnyComponent(PlayPauseIconComponent( - state: state.isSpeakingTranslatedText ? .pause : .play, - tintColor: theme.list.itemCheckColors.foregroundColor, - size: CGSize(width: 18.0, height: 18.0) - ))), - ])), - action: { [weak state] in - guard let state = state else { - return - } - state.speakTranslatedText() - } - ).minSize(CGSize(width: 44.0, height: 44.0)), - availableSize: CGSize(width: 22.0, height: 22.0), - transition: .immediate - ) - - context.add(translationSpeakButton - .position(CGPoint(x: context.availableSize.width - sideInset - textSideInset - translationSpeakButton.size.width / 2.0 - 3.0, y: textBackgroundOrigin.y + textTopInset + originalTitle.size.height + textSpacing + originalText.size.height + itemSpacing + textTopInset + translationTitle.size.height + textSpacing + translationTextHeight - translationSpeakButton.size.height / 2.0 - 2.0)) - ) - } - - let buttonsSpacing: CGFloat = 24.0 - let smallSectionSpacing: CGFloat = 8.0 + let buttonsSpacing: CGFloat = 20.0 + let smallSectionSpacing: CGFloat = 20.0 var buttonsHeight: CGFloat = 0.0 @@ -532,500 +537,156 @@ private final class TranslateScreenComponent: CombinedComponent { } } -public class TranslateScreen: ViewController { - final class Node: ViewControllerTracingNode, ASScrollViewDelegate, ASGestureRecognizerDelegate { - private var presentationData: PresentationData - private weak var controller: TranslateScreen? - - private let component: AnyComponent - private let theme: PresentationTheme? - - let dim: ASDisplayNode - let wrappingView: UIView - let containerView: UIView - let scrollView: UIScrollView - let hostView: ComponentHostView - - private(set) var isExpanded = false - private var panGestureRecognizer: UIPanGestureRecognizer? - private var panGestureArguments: (topInset: CGFloat, offset: CGFloat, scrollView: UIScrollView?, listNode: ListView?)? - - private var currentIsVisible: Bool = false - private var currentLayout: (layout: ContainerViewLayout, navigationHeight: CGFloat)? - - fileprivate var temporaryDismiss = false - - init(context: AccountContext, controller: TranslateScreen, component: AnyComponent, theme: PresentationTheme?) { - self.presentationData = context.sharedContext.currentPresentationData.with { $0 } - - self.controller = controller - - self.component = component - self.theme = theme - - let effectiveTheme = theme ?? self.presentationData.theme - - self.dim = ASDisplayNode() - self.dim.alpha = 0.0 - self.dim.backgroundColor = UIColor(white: 0.0, alpha: 0.25) - - self.wrappingView = UIView() - self.containerView = UIView() - self.scrollView = UIScrollView() - self.hostView = ComponentHostView() - - super.init() - - self.scrollView.delegate = self.wrappedScrollViewDelegate - self.scrollView.showsVerticalScrollIndicator = false - - self.containerView.clipsToBounds = true - self.containerView.backgroundColor = effectiveTheme.list.blocksBackgroundColor - - self.addSubnode(self.dim) - - self.view.addSubview(self.wrappingView) - self.wrappingView.addSubview(self.containerView) - self.containerView.addSubview(self.scrollView) - self.scrollView.addSubview(self.hostView) - } - - override func didLoad() { - super.didLoad() - - let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.panGesture(_:))) - panRecognizer.delegate = self.wrappedGestureRecognizerDelegate - panRecognizer.delaysTouchesBegan = false - panRecognizer.cancelsTouchesInView = true - self.panGestureRecognizer = panRecognizer - self.wrappingView.addGestureRecognizer(panRecognizer) - - self.dim.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dimTapGesture(_:)))) - - self.controller?.navigationBar?.updateBackgroundAlpha(0.0, transition: .immediate) - } - - @objc func dimTapGesture(_ recognizer: UITapGestureRecognizer) { - if case .ended = recognizer.state { - self.controller?.dismiss(animated: true) - } - } - - override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { - if let (layout, _) = self.currentLayout { - if case .regular = layout.metrics.widthClass { - return false - } - } - return true - } - - func scrollViewDidScroll(_ scrollView: UIScrollView) { - let contentOffset = self.scrollView.contentOffset.y - self.controller?.navigationBar?.updateBackgroundAlpha(min(30.0, contentOffset) / 30.0, transition: .immediate) - } - - func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { - if gestureRecognizer is UIPanGestureRecognizer && otherGestureRecognizer is UIPanGestureRecognizer { - return true - } - return false - } - - private var isDismissing = false - func animateIn() { - ContainedViewLayoutTransition.animated(duration: 0.3, curve: .linear).updateAlpha(node: self.dim, alpha: 1.0) - - let targetPosition = self.containerView.center - let startPosition = targetPosition.offsetBy(dx: 0.0, dy: self.bounds.height) - - self.containerView.center = startPosition - let transition = ContainedViewLayoutTransition.animated(duration: 0.4, curve: .spring) - transition.animateView(allowUserInteraction: true, { - self.containerView.center = targetPosition - }, completion: { _ in - }) - } - - func animateOut(completion: @escaping () -> Void = {}) { - self.isDismissing = true - - let positionTransition: ContainedViewLayoutTransition = .animated(duration: 0.25, curve: .easeInOut) - positionTransition.updatePosition(layer: self.containerView.layer, position: CGPoint(x: self.containerView.center.x, y: self.bounds.height + self.containerView.bounds.height / 2.0), completion: { [weak self] _ in - self?.controller?.dismiss(animated: false, completion: completion) - }) - let alphaTransition: ContainedViewLayoutTransition = .animated(duration: 0.25, curve: .easeInOut) - alphaTransition.updateAlpha(node: self.dim, alpha: 0.0) - - if !self.temporaryDismiss { - self.controller?.updateModalStyleOverlayTransitionFactor(0.0, transition: positionTransition) - } - } - - func containerLayoutUpdated(layout: ContainerViewLayout, navigationHeight: CGFloat, transition: ComponentTransition) { - self.currentLayout = (layout, navigationHeight) - - if let controller = self.controller, let navigationBar = controller.navigationBar, navigationBar.view.superview !== self.wrappingView { - self.containerView.addSubview(navigationBar.view) - } - - self.dim.frame = CGRect(origin: CGPoint(x: 0.0, y: -layout.size.height), size: CGSize(width: layout.size.width, height: layout.size.height * 3.0)) - - var effectiveExpanded = self.isExpanded - if case .regular = layout.metrics.widthClass { - effectiveExpanded = true - } - - let isLandscape = layout.orientation == .landscape - let edgeTopInset = isLandscape ? 0.0 : self.defaultTopInset - let topInset: CGFloat - if let (panInitialTopInset, panOffset, _, _) = self.panGestureArguments { - if effectiveExpanded { - topInset = min(edgeTopInset, panInitialTopInset + max(0.0, panOffset)) - } else { - topInset = max(0.0, panInitialTopInset + min(0.0, panOffset)) - } - } else { - topInset = effectiveExpanded ? 0.0 : edgeTopInset - } - transition.setFrame(view: self.wrappingView, frame: CGRect(origin: CGPoint(x: 0.0, y: topInset), size: layout.size), completion: nil) - - let modalProgress = isLandscape ? 0.0 : (1.0 - topInset / self.defaultTopInset) - self.controller?.updateModalStyleOverlayTransitionFactor(modalProgress, transition: transition.containedViewLayoutTransition) - - let clipFrame: CGRect - if layout.metrics.widthClass == .compact { - self.dim.backgroundColor = UIColor(rgb: 0x000000, alpha: 0.25) - if isLandscape { - self.containerView.layer.cornerRadius = 0.0 - } else { - self.containerView.layer.cornerRadius = 10.0 - } - - if #available(iOS 11.0, *) { - if layout.safeInsets.bottom.isZero { - self.containerView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] - } else { - self.containerView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner] - } - } - - if isLandscape { - clipFrame = CGRect(origin: CGPoint(), size: layout.size) - } else { - let coveredByModalTransition: CGFloat = 0.0 - var containerTopInset: CGFloat = 10.0 - if let statusBarHeight = layout.statusBarHeight { - containerTopInset += statusBarHeight - } - - let unscaledFrame = CGRect(origin: CGPoint(x: 0.0, y: containerTopInset - coveredByModalTransition * 10.0), size: CGSize(width: layout.size.width, height: layout.size.height - containerTopInset)) - let maxScale: CGFloat = (layout.size.width - 16.0 * 2.0) / layout.size.width - let containerScale = 1.0 * (1.0 - coveredByModalTransition) + maxScale * coveredByModalTransition - let maxScaledTopInset: CGFloat = containerTopInset - 10.0 - let scaledTopInset: CGFloat = containerTopInset * (1.0 - coveredByModalTransition) + maxScaledTopInset * coveredByModalTransition - let containerFrame = unscaledFrame.offsetBy(dx: 0.0, dy: scaledTopInset - (unscaledFrame.midY - containerScale * unscaledFrame.height / 2.0)) - - clipFrame = CGRect(x: containerFrame.minX, y: containerFrame.minY, width: containerFrame.width, height: containerFrame.height) - } - } else { - self.dim.backgroundColor = UIColor(rgb: 0x000000, alpha: 0.4) - self.containerView.layer.cornerRadius = 10.0 - - let verticalInset: CGFloat = 44.0 - - let maxSide = max(layout.size.width, layout.size.height) - let minSide = min(layout.size.width, layout.size.height) - let containerSize = CGSize(width: min(layout.size.width - 20.0, floor(maxSide / 2.0)), height: min(layout.size.height, minSide) - verticalInset * 2.0) - clipFrame = CGRect(origin: CGPoint(x: floor((layout.size.width - containerSize.width) / 2.0), y: floor((layout.size.height - containerSize.height) / 2.0)), size: containerSize) - } - - transition.setFrame(view: self.containerView, frame: clipFrame) - transition.setFrame(view: self.scrollView, frame: CGRect(origin: CGPoint(), size: clipFrame.size), completion: nil) - - let environment = ViewControllerComponentContainer.Environment( - statusBarHeight: 0.0, - navigationHeight: navigationHeight, - safeInsets: UIEdgeInsets(top: layout.intrinsicInsets.top + layout.safeInsets.top, left: layout.safeInsets.left, bottom: layout.intrinsicInsets.bottom + layout.safeInsets.bottom, right: layout.safeInsets.right), - additionalInsets: layout.additionalInsets, - inputHeight: layout.inputHeight ?? 0.0, - metrics: layout.metrics, - deviceMetrics: layout.deviceMetrics, - orientation: layout.metrics.orientation, - isVisible: self.currentIsVisible, - theme: self.theme ?? self.presentationData.theme, - strings: self.presentationData.strings, - dateTimeFormat: self.presentationData.dateTimeFormat, - controller: { [weak self] in - return self?.controller - } - ) - var contentSize = self.hostView.update( - transition: transition, - component: self.component, - environment: { - environment - }, - forceUpdate: true, - containerSize: CGSize(width: clipFrame.size.width, height: 10000.0) - ) - contentSize.height = max(layout.size.height - navigationHeight, contentSize.height) - transition.setFrame(view: self.hostView, frame: CGRect(origin: CGPoint(), size: contentSize), completion: nil) - - self.scrollView.contentSize = contentSize - } - - private var didPlayAppearAnimation = false - func updateIsVisible(isVisible: Bool) { - if self.currentIsVisible == isVisible { - return - } - self.currentIsVisible = isVisible - - guard let currentLayout = self.currentLayout else { - return - } - self.containerLayoutUpdated(layout: currentLayout.layout, navigationHeight: currentLayout.navigationHeight, transition: .immediate) - - if !self.didPlayAppearAnimation { - self.didPlayAppearAnimation = true - self.animateIn() - } - } - - private var defaultTopInset: CGFloat { - guard let (layout, _) = self.currentLayout else{ - return 210.0 - } - if case .compact = layout.metrics.widthClass { - var factor: CGFloat = 0.2488 - if layout.size.width <= 320.0 { - factor = 0.15 - } - return floor(max(layout.size.width, layout.size.height) * factor) - } else { - return 210.0 - } - } - - private func findScrollView(view: UIView?) -> (UIScrollView, ListView?)? { - if let view = view { - if let view = view as? UIScrollView { - return (view, nil) - } - if let node = view.asyncdisplaykit_node as? ListView { - return (node.scroller, node) - } - return findScrollView(view: view.superview) - } else { - return nil - } - } - - @objc func panGesture(_ recognizer: UIPanGestureRecognizer) { - guard let (layout, navigationHeight) = self.currentLayout else { - return - } - - let isLandscape = layout.orientation == .landscape - let edgeTopInset = isLandscape ? 0.0 : defaultTopInset - - switch recognizer.state { - case .began: - let point = recognizer.location(in: self.view) - let currentHitView = self.hitTest(point, with: nil) - - var scrollViewAndListNode = self.findScrollView(view: currentHitView) - if scrollViewAndListNode?.0.frame.height == self.frame.width { - scrollViewAndListNode = nil - } - let scrollView = scrollViewAndListNode?.0 - let listNode = scrollViewAndListNode?.1 - - let topInset: CGFloat - if self.isExpanded { - topInset = 0.0 - } else { - topInset = edgeTopInset - } - - self.panGestureArguments = (topInset, 0.0, scrollView, listNode) - case .changed: - guard let (topInset, panOffset, scrollView, listNode) = self.panGestureArguments else { - return - } - let visibleContentOffset = listNode?.visibleContentOffset() - let contentOffset = scrollView?.contentOffset.y ?? 0.0 - - var translation = recognizer.translation(in: self.view).y - - var currentOffset = topInset + translation - - let epsilon = 1.0 - if case let .known(value) = visibleContentOffset, value <= epsilon { - if let scrollView = scrollView { - scrollView.bounces = false - scrollView.setContentOffset(CGPoint(x: 0.0, y: 0.0), animated: false) - } - } else if let scrollView = scrollView, contentOffset <= -scrollView.contentInset.top + epsilon { - scrollView.bounces = false - scrollView.setContentOffset(CGPoint(x: 0.0, y: -scrollView.contentInset.top), animated: false) - } else if let scrollView = scrollView { - translation = panOffset - currentOffset = topInset + translation - if self.isExpanded { - recognizer.setTranslation(CGPoint(), in: self.view) - } else if currentOffset > 0.0 { - scrollView.setContentOffset(CGPoint(x: 0.0, y: -scrollView.contentInset.top), animated: false) - } - } - - self.panGestureArguments = (topInset, translation, scrollView, listNode) - - if !self.isExpanded { - if currentOffset > 0.0, let scrollView = scrollView { - scrollView.panGestureRecognizer.setTranslation(CGPoint(), in: scrollView) - } - } - - var bounds = self.bounds - if self.isExpanded { - bounds.origin.y = -max(0.0, translation - edgeTopInset) - } else { - bounds.origin.y = -translation - } - bounds.origin.y = min(0.0, bounds.origin.y) - self.bounds = bounds - - self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: .immediate) - case .ended: - guard let (currentTopInset, panOffset, scrollView, listNode) = self.panGestureArguments else { - return - } - self.panGestureArguments = nil - - let visibleContentOffset = listNode?.visibleContentOffset() - let contentOffset = scrollView?.contentOffset.y ?? 0.0 - - let translation = recognizer.translation(in: self.view).y - var velocity = recognizer.velocity(in: self.view) - - if self.isExpanded { - if case let .known(value) = visibleContentOffset, value > 0.1 { - velocity = CGPoint() - } else if case .unknown = visibleContentOffset { - velocity = CGPoint() - } else if contentOffset > 0.1 { - velocity = CGPoint() - } - } - - var bounds = self.bounds - if self.isExpanded { - bounds.origin.y = -max(0.0, translation - edgeTopInset) - } else { - bounds.origin.y = -translation - } - bounds.origin.y = min(0.0, bounds.origin.y) - - scrollView?.bounces = true - - let offset = currentTopInset + panOffset - let topInset: CGFloat = edgeTopInset - - var dismissing = false - if bounds.minY < -60 || (bounds.minY < 0.0 && velocity.y > 300.0) || (self.isExpanded && bounds.minY.isZero && velocity.y > 1800.0) { - self.controller?.dismiss(animated: true, completion: nil) - dismissing = true - } else if self.isExpanded { - if velocity.y > 300.0 || offset > topInset / 2.0 { - self.isExpanded = false - if let listNode = listNode { - listNode.scroller.setContentOffset(CGPoint(), animated: false) - } else if let scrollView = scrollView { - scrollView.setContentOffset(CGPoint(x: 0.0, y: -scrollView.contentInset.top), animated: false) - } - - let distance = topInset - offset - let initialVelocity: CGFloat = distance.isZero ? 0.0 : abs(velocity.y / distance) - let transition = ContainedViewLayoutTransition.animated(duration: 0.45, curve: .customSpring(damping: 124.0, initialVelocity: initialVelocity)) - - self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: ComponentTransition(transition)) - } else { - self.isExpanded = true - - self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: ComponentTransition(.animated(duration: 0.3, curve: .easeInOut))) - } - } else if (velocity.y < -300.0 || offset < topInset / 2.0) { - if velocity.y > -2200.0 && velocity.y < -300.0, let listNode = listNode { - DispatchQueue.main.async { - listNode.transaction(deleteIndices: [], insertIndicesAndItems: [], updateIndicesAndItems: [], options: [.Synchronous, .LowLatency], scrollToItem: ListViewScrollToItem(index: 0, position: .top(0.0), animated: true, curve: .Default(duration: nil), directionHint: .Up), updateSizeAndInsets: nil, stationaryItemRange: nil, updateOpaqueState: nil, completion: { _ in }) - } - } - - let initialVelocity: CGFloat = offset.isZero ? 0.0 : abs(velocity.y / offset) - let transition = ContainedViewLayoutTransition.animated(duration: 0.45, curve: .customSpring(damping: 124.0, initialVelocity: initialVelocity)) - self.isExpanded = true - - self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: ComponentTransition(transition)) - } else { - if let listNode = listNode { - listNode.scroller.setContentOffset(CGPoint(), animated: false) - } else if let scrollView = scrollView { - scrollView.setContentOffset(CGPoint(x: 0.0, y: -scrollView.contentInset.top), animated: false) - } - - self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: ComponentTransition(.animated(duration: 0.3, curve: .easeInOut))) - } - - if !dismissing { - var bounds = self.bounds - let previousBounds = bounds - bounds.origin.y = 0.0 - self.bounds = bounds - self.layer.animateBounds(from: previousBounds, to: self.bounds, duration: 0.3, timingFunction: CAMediaTimingFunctionName.easeInEaseOut.rawValue) - } - case .cancelled: - self.panGestureArguments = nil - - self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: ComponentTransition(.animated(duration: 0.3, curve: .easeInOut))) - default: - break - } - } - - func update(isExpanded: Bool, transition: ContainedViewLayoutTransition) { - guard isExpanded != self.isExpanded else { - return - } - self.isExpanded = isExpanded - - guard let (layout, navigationHeight) = self.currentLayout else { - return - } - self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: ComponentTransition(transition)) - } - } - - var node: Node { - return self.displayNode as! Node - } +private final class TranslateSheetComponent: CombinedComponent { + typealias EnvironmentType = ViewControllerComponentContainer.Environment private let context: AccountContext - private let theme: PresentationTheme? - private let component: AnyComponent - private var isInitiallyExpanded = false + private let text: String + private let entities: [MessageTextEntity] + private let fromLanguage: String? + private let toLanguage: String + private let copyTranslation: ((String) -> Void)? + private let changeLanguage: (String, String, @escaping (String, String) -> Void) -> Void - private var currentLayout: ContainerViewLayout? + init( + context: AccountContext, + text: String, + entities: [MessageTextEntity], + fromLanguage: String?, + toLanguage: String, + copyTranslation: ((String) -> Void)?, + changeLanguage: @escaping (String, String, @escaping (String, String) -> Void) -> Void + ) { + self.context = context + self.text = text + self.entities = entities + self.fromLanguage = fromLanguage + self.toLanguage = toLanguage + self.copyTranslation = copyTranslation + self.changeLanguage = changeLanguage + } + + static func ==(lhs: TranslateSheetComponent, rhs: TranslateSheetComponent) -> Bool { + return true + } + + static var body: Body { + let sheet = Child(ResizableSheetComponent<(EnvironmentType)>.self) + let animateOut = StoredActionSlot(Action.self) + + return { context in + let environment = context.environment[EnvironmentType.self] + + let controller = environment.controller + + let dismiss: (Bool) -> Void = { animated in + if animated { + animateOut.invoke(Action { _ in + if let controller = controller() { + controller.dismiss(completion: nil) + } + }) + } else { + if let controller = controller() { + controller.dismiss(completion: nil) + } + } + } + + let theme = environment.theme.withModalBlocksBackground() + + let sheet = sheet.update( + component: ResizableSheetComponent( + content: AnyComponent(SheetContent( + context: context.component.context, + text: context.component.text, + entities: context.component.entities, + fromLanguage: context.component.fromLanguage, + toLanguage: context.component.toLanguage, + copyTranslation: context.component.copyTranslation, + changeLanguage: context.component.changeLanguage, + expand: {} + )), + titleItem: AnyComponent( + MultilineTextComponent(text: .plain(NSAttributedString(string: environment.strings.Translate_Title, font: Font.semibold(17.0), textColor: theme.list.itemPrimaryTextColor))) + ), + leftItem: AnyComponent( + GlassBarButtonComponent( + size: CGSize(width: 44.0, height: 44.0), + backgroundColor: nil, + isDark: theme.overallDarkAppearance, + state: .glass, + component: AnyComponentWithIdentity(id: "close", component: AnyComponent( + BundleIconComponent( + name: "Navigation/Close", + tintColor: theme.chat.inputPanel.panelControlColor + ) + )), + action: { _ in + dismiss(true) + } + ) + ), + bottomItem: nil, + backgroundColor: .color(theme.list.modalBlocksBackgroundColor), + animateOut: animateOut + ), + environment: { + environment + ResizableSheetComponentEnvironment( + theme: theme, + statusBarHeight: environment.statusBarHeight, + safeInsets: environment.safeInsets, + metrics: environment.metrics, + deviceMetrics: environment.deviceMetrics, + isDisplaying: environment.value.isVisible, + isCentered: environment.metrics.widthClass == .regular, + screenSize: context.availableSize, + regularMetricsSize: CGSize(width: 430.0, height: 900.0), + dismiss: { animated in + dismiss(animated) + } + ) + }, + availableSize: context.availableSize, + transition: context.transition + ) + + context.add(sheet + .position(CGPoint(x: context.availableSize.width / 2.0, y: context.availableSize.height / 2.0)) + ) + + return context.availableSize + } + } +} + +public final class TranslateScreen: ViewControllerComponentContainer { + private let context: AccountContext public var pushController: (ViewController) -> Void = { _ in } public var presentController: (ViewController) -> Void = { _ in } - - public var wasDismissed: (() -> Void)? - - public convenience init(context: AccountContext, forceTheme: PresentationTheme? = nil, text: String, entities: [MessageTextEntity] = [], canCopy: Bool, fromLanguage: String?, toLanguage: String? = nil, isExpanded: Bool = false, ignoredLanguages: [String]? = nil) { - let presentationData = context.sharedContext.currentPresentationData.with { $0 } + public init( + context: AccountContext, + forceTheme: PresentationTheme? = nil, + text: String, + entities: [MessageTextEntity] = [], + canCopy: Bool, + fromLanguage: String?, + toLanguage: String? = nil, + ignoredLanguages: [String]? = nil + ) { + self.context = context + + let theme: ViewControllerComponentContainer.Theme + if let forceTheme { + theme = .custom(forceTheme) + } else { + theme = .default + } + + let presentationData = self.context.sharedContext.currentPresentationData.with { $0 } var baseLanguageCode = presentationData.strings.baseLanguageCode let rawSuffix = "-raw" if baseLanguageCode.hasSuffix(rawSuffix) { @@ -1047,21 +708,30 @@ public class TranslateScreen: ViewController { var copyTranslationImpl: ((String) -> Void)? var changeLanguageImpl: ((String, String, @escaping (String, String) -> Void) -> Void)? - var expandImpl: (() -> Void)? - self.init(context: context, component: TranslateScreenComponent(context: context, text: text, entities: entities, fromLanguage: fromLanguage, toLanguage: toLanguage, copyTranslation: !canCopy ? nil : { text in - copyTranslationImpl?(text) - }, changeLanguage: { fromLang, toLang, completion in - changeLanguageImpl?(fromLang, toLang, completion) - }, expand: { - expandImpl?() - }), theme: forceTheme) - self.isInitiallyExpanded = isExpanded - - self.title = presentationData.strings.Translate_Title - - self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: presentationData.strings.Common_Close, style: .plain, target: self, action: #selector(self.cancelPressed)) + super.init( + context: context, + component: TranslateSheetComponent( + context: context, + text: text, + entities: entities, + fromLanguage: fromLanguage, + toLanguage: toLanguage, + copyTranslation: !canCopy ? nil : { text in + copyTranslationImpl?(text) + }, + changeLanguage: { fromLang, toLang, completion in + changeLanguageImpl?(fromLang, toLang, completion) + } + ), + navigationBarAppearance: .none, + statusBarStyle: .ignore, + theme: theme + ) + self.statusBar.statusBarStyle = .Ignore + self.navigationPresentation = .flatModal + self.blocksBackgroundWhenInOverlay = true self.supportedOrientations = ViewControllerSupportedOrientations(regularSize: .all, compactSize: .portrait) copyTranslationImpl = { [weak self] text in @@ -1075,116 +745,682 @@ public class TranslateScreen: ViewController { let pushController = self?.pushController let presentController = self?.presentController let controller = languageSelectionController(context: context, forceTheme: forceTheme, fromLanguage: fromLang, toLanguage: toLang, completion: { fromLang, toLang in - let controller = TranslateScreen(context: context, forceTheme: forceTheme, text: text, canCopy: canCopy, fromLanguage: fromLang, toLanguage: toLang, isExpanded: true, ignoredLanguages: ignoredLanguages) + let controller = TranslateScreen(context: context, forceTheme: forceTheme, text: text, canCopy: canCopy, fromLanguage: fromLang, toLanguage: toLang, ignoredLanguages: ignoredLanguages) controller.pushController = pushController ?? { _ in } controller.presentController = presentController ?? { _ in } presentController?(controller) }) - self?.node.temporaryDismiss = true - self?.dismiss(animated: true, completion: nil) + self?.dismissAnimated() pushController?(controller) } - - expandImpl = { [weak self] in - self?.node.update(isExpanded: true, transition: .animated(duration: 0.4, curve: .spring)) - if let currentLayout = self?.currentLayout { - self?.containerLayoutUpdated(currentLayout, transition: .animated(duration: 0.4, curve: .spring)) - } - } } - - private init(context: AccountContext, component: C, theme: PresentationTheme? = nil) where C.EnvironmentType == ViewControllerComponentContainer.Environment { - self.context = context - self.component = AnyComponent(component) - self.theme = theme - var presentationData = context.sharedContext.currentPresentationData.with { $0 } - if let theme { - presentationData = presentationData.withUpdated(theme: theme) - } - super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: presentationData)) - } - required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } - - @objc private func cancelPressed() { - self.dismiss(animated: true, completion: nil) - } - - override open func loadDisplayNode() { - self.displayNode = Node(context: self.context, controller: self, component: self.component, theme: self.theme) - if self.isInitiallyExpanded { - (self.displayNode as! Node).update(isExpanded: true, transition: .immediate) + + public func dismissAnimated() { + if let view = self.node.hostView.findTaggedView(tag: ResizableSheetComponent.View.Tag()) as? ResizableSheetComponent.View { + view.dismissAnimated() } - self.displayNodeDidLoad() - } - - public override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { - self.view.endEditing(true) - let wasDismissed = self.wasDismissed - if flag { - self.node.animateOut(completion: { - super.dismiss(animated: false, completion: {}) - wasDismissed?() - completion?() - }) - } else { - super.dismiss(animated: false, completion: {}) - wasDismissed?() - completion?() - } - } - - override open func viewDidAppear(_ animated: Bool) { - super.viewDidAppear(animated) - - self.node.updateIsVisible(isVisible: true) - } - - override open func viewDidDisappear(_ animated: Bool) { - super.viewDidDisappear(animated) - - self.node.updateIsVisible(isVisible: false) - } - - override public func updateNavigationBarLayout(_ layout: ContainerViewLayout, transition: ContainedViewLayoutTransition) { - var navigationLayout = self.navigationLayout(layout: layout) - var navigationFrame = navigationLayout.navigationFrame - - var layout = layout - if case .regular = layout.metrics.widthClass { - let verticalInset: CGFloat = 44.0 - let maxSide = max(layout.size.width, layout.size.height) - let minSide = min(layout.size.width, layout.size.height) - let containerSize = CGSize(width: min(layout.size.width - 20.0, floor(maxSide / 2.0)), height: min(layout.size.height, minSide) - verticalInset * 2.0) - let clipFrame = CGRect(origin: CGPoint(x: floor((layout.size.width - containerSize.width) / 2.0), y: floor((layout.size.height - containerSize.height) / 2.0)), size: containerSize) - navigationFrame.size.width = clipFrame.width - layout.size = clipFrame.size - } - - navigationFrame.size.height = 56.0 - navigationLayout.navigationFrame = navigationFrame - navigationLayout.defaultContentHeight = 56.0 - - layout.statusBarHeight = nil - - self.applyNavigationBarLayout(layout, navigationLayout: navigationLayout, additionalBackgroundHeight: 0.0, additionalCutout: nil, transition: transition) - } - - override open func containerLayoutUpdated(_ layout: ContainerViewLayout, transition: ContainedViewLayoutTransition) { - self.currentLayout = layout - super.containerLayoutUpdated(layout, transition: transition) - - let navigationHeight: CGFloat = 56.0 - - self.node.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: ComponentTransition(transition)) } } +//public class TranslateScreen: ViewController { +// final class Node: ViewControllerTracingNode, ASScrollViewDelegate, ASGestureRecognizerDelegate { +// private var presentationData: PresentationData +// private weak var controller: TranslateScreen? +// +// private let component: AnyComponent +// private let theme: PresentationTheme? +// +// let dim: ASDisplayNode +// let wrappingView: UIView +// let containerView: UIView +// let scrollView: UIScrollView +// let hostView: ComponentHostView +// +// private(set) var isExpanded = false +// private var panGestureRecognizer: UIPanGestureRecognizer? +// private var panGestureArguments: (topInset: CGFloat, offset: CGFloat, scrollView: UIScrollView?, listNode: ListView?)? +// +// private var currentIsVisible: Bool = false +// private var currentLayout: (layout: ContainerViewLayout, navigationHeight: CGFloat)? +// +// fileprivate var temporaryDismiss = false +// +// init(context: AccountContext, controller: TranslateScreen, component: AnyComponent, theme: PresentationTheme?) { +// self.presentationData = context.sharedContext.currentPresentationData.with { $0 } +// +// self.controller = controller +// +// self.component = component +// self.theme = theme +// +// let effectiveTheme = theme ?? self.presentationData.theme +// +// self.dim = ASDisplayNode() +// self.dim.alpha = 0.0 +// self.dim.backgroundColor = UIColor(white: 0.0, alpha: 0.25) +// +// self.wrappingView = UIView() +// self.containerView = UIView() +// self.scrollView = UIScrollView() +// self.hostView = ComponentHostView() +// +// super.init() +// +// self.scrollView.delegate = self.wrappedScrollViewDelegate +// self.scrollView.showsVerticalScrollIndicator = false +// +// self.containerView.clipsToBounds = true +// self.containerView.backgroundColor = effectiveTheme.list.blocksBackgroundColor +// +// self.addSubnode(self.dim) +// +// self.view.addSubview(self.wrappingView) +// self.wrappingView.addSubview(self.containerView) +// self.containerView.addSubview(self.scrollView) +// self.scrollView.addSubview(self.hostView) +// } +// +// override func didLoad() { +// super.didLoad() +// +// let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.panGesture(_:))) +// panRecognizer.delegate = self.wrappedGestureRecognizerDelegate +// panRecognizer.delaysTouchesBegan = false +// panRecognizer.cancelsTouchesInView = true +// self.panGestureRecognizer = panRecognizer +// self.wrappingView.addGestureRecognizer(panRecognizer) +// +// self.dim.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dimTapGesture(_:)))) +// +// self.controller?.navigationBar?.updateBackgroundAlpha(0.0, transition: .immediate) +// } +// +// @objc func dimTapGesture(_ recognizer: UITapGestureRecognizer) { +// if case .ended = recognizer.state { +// self.controller?.dismiss(animated: true) +// } +// } +// +// override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { +// if let (layout, _) = self.currentLayout { +// if case .regular = layout.metrics.widthClass { +// return false +// } +// } +// return true +// } +// +// func scrollViewDidScroll(_ scrollView: UIScrollView) { +// let contentOffset = self.scrollView.contentOffset.y +// self.controller?.navigationBar?.updateBackgroundAlpha(min(30.0, contentOffset) / 30.0, transition: .immediate) +// } +// +// func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { +// if gestureRecognizer is UIPanGestureRecognizer && otherGestureRecognizer is UIPanGestureRecognizer { +// return true +// } +// return false +// } +// +// private var isDismissing = false +// func animateIn() { +// ContainedViewLayoutTransition.animated(duration: 0.3, curve: .linear).updateAlpha(node: self.dim, alpha: 1.0) +// +// let targetPosition = self.containerView.center +// let startPosition = targetPosition.offsetBy(dx: 0.0, dy: self.bounds.height) +// +// self.containerView.center = startPosition +// let transition = ContainedViewLayoutTransition.animated(duration: 0.4, curve: .spring) +// transition.animateView(allowUserInteraction: true, { +// self.containerView.center = targetPosition +// }, completion: { _ in +// }) +// } +// +// func animateOut(completion: @escaping () -> Void = {}) { +// self.isDismissing = true +// +// let positionTransition: ContainedViewLayoutTransition = .animated(duration: 0.25, curve: .easeInOut) +// positionTransition.updatePosition(layer: self.containerView.layer, position: CGPoint(x: self.containerView.center.x, y: self.bounds.height + self.containerView.bounds.height / 2.0), completion: { [weak self] _ in +// self?.controller?.dismiss(animated: false, completion: completion) +// }) +// let alphaTransition: ContainedViewLayoutTransition = .animated(duration: 0.25, curve: .easeInOut) +// alphaTransition.updateAlpha(node: self.dim, alpha: 0.0) +// +// if !self.temporaryDismiss { +// self.controller?.updateModalStyleOverlayTransitionFactor(0.0, transition: positionTransition) +// } +// } +// +// func containerLayoutUpdated(layout: ContainerViewLayout, navigationHeight: CGFloat, transition: ComponentTransition) { +// self.currentLayout = (layout, navigationHeight) +// +// if let controller = self.controller, let navigationBar = controller.navigationBar, navigationBar.view.superview !== self.wrappingView { +// self.containerView.addSubview(navigationBar.view) +// } +// +// self.dim.frame = CGRect(origin: CGPoint(x: 0.0, y: -layout.size.height), size: CGSize(width: layout.size.width, height: layout.size.height * 3.0)) +// +// var effectiveExpanded = self.isExpanded +// if case .regular = layout.metrics.widthClass { +// effectiveExpanded = true +// } +// +// let isLandscape = layout.orientation == .landscape +// let edgeTopInset = isLandscape ? 0.0 : self.defaultTopInset +// let topInset: CGFloat +// if let (panInitialTopInset, panOffset, _, _) = self.panGestureArguments { +// if effectiveExpanded { +// topInset = min(edgeTopInset, panInitialTopInset + max(0.0, panOffset)) +// } else { +// topInset = max(0.0, panInitialTopInset + min(0.0, panOffset)) +// } +// } else { +// topInset = effectiveExpanded ? 0.0 : edgeTopInset +// } +// transition.setFrame(view: self.wrappingView, frame: CGRect(origin: CGPoint(x: 0.0, y: topInset), size: layout.size), completion: nil) +// +// let modalProgress = isLandscape ? 0.0 : (1.0 - topInset / self.defaultTopInset) +// self.controller?.updateModalStyleOverlayTransitionFactor(modalProgress, transition: transition.containedViewLayoutTransition) +// +// let clipFrame: CGRect +// if layout.metrics.widthClass == .compact { +// self.dim.backgroundColor = UIColor(rgb: 0x000000, alpha: 0.25) +// if isLandscape { +// self.containerView.layer.cornerRadius = 0.0 +// } else { +// self.containerView.layer.cornerRadius = 10.0 +// } +// +// if #available(iOS 11.0, *) { +// if layout.safeInsets.bottom.isZero { +// self.containerView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] +// } else { +// self.containerView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner] +// } +// } +// +// if isLandscape { +// clipFrame = CGRect(origin: CGPoint(), size: layout.size) +// } else { +// let coveredByModalTransition: CGFloat = 0.0 +// var containerTopInset: CGFloat = 10.0 +// if let statusBarHeight = layout.statusBarHeight { +// containerTopInset += statusBarHeight +// } +// +// let unscaledFrame = CGRect(origin: CGPoint(x: 0.0, y: containerTopInset - coveredByModalTransition * 10.0), size: CGSize(width: layout.size.width, height: layout.size.height - containerTopInset)) +// let maxScale: CGFloat = (layout.size.width - 16.0 * 2.0) / layout.size.width +// let containerScale = 1.0 * (1.0 - coveredByModalTransition) + maxScale * coveredByModalTransition +// let maxScaledTopInset: CGFloat = containerTopInset - 10.0 +// let scaledTopInset: CGFloat = containerTopInset * (1.0 - coveredByModalTransition) + maxScaledTopInset * coveredByModalTransition +// let containerFrame = unscaledFrame.offsetBy(dx: 0.0, dy: scaledTopInset - (unscaledFrame.midY - containerScale * unscaledFrame.height / 2.0)) +// +// clipFrame = CGRect(x: containerFrame.minX, y: containerFrame.minY, width: containerFrame.width, height: containerFrame.height) +// } +// } else { +// self.dim.backgroundColor = UIColor(rgb: 0x000000, alpha: 0.4) +// self.containerView.layer.cornerRadius = 10.0 +// +// let verticalInset: CGFloat = 44.0 +// +// let maxSide = max(layout.size.width, layout.size.height) +// let minSide = min(layout.size.width, layout.size.height) +// let containerSize = CGSize(width: min(layout.size.width - 20.0, floor(maxSide / 2.0)), height: min(layout.size.height, minSide) - verticalInset * 2.0) +// clipFrame = CGRect(origin: CGPoint(x: floor((layout.size.width - containerSize.width) / 2.0), y: floor((layout.size.height - containerSize.height) / 2.0)), size: containerSize) +// } +// +// transition.setFrame(view: self.containerView, frame: clipFrame) +// transition.setFrame(view: self.scrollView, frame: CGRect(origin: CGPoint(), size: clipFrame.size), completion: nil) +// +// let environment = ViewControllerComponentContainer.Environment( +// statusBarHeight: 0.0, +// navigationHeight: navigationHeight, +// safeInsets: UIEdgeInsets(top: layout.intrinsicInsets.top + layout.safeInsets.top, left: layout.safeInsets.left, bottom: layout.intrinsicInsets.bottom + layout.safeInsets.bottom, right: layout.safeInsets.right), +// additionalInsets: layout.additionalInsets, +// inputHeight: layout.inputHeight ?? 0.0, +// metrics: layout.metrics, +// deviceMetrics: layout.deviceMetrics, +// orientation: layout.metrics.orientation, +// isVisible: self.currentIsVisible, +// theme: self.theme ?? self.presentationData.theme, +// strings: self.presentationData.strings, +// dateTimeFormat: self.presentationData.dateTimeFormat, +// controller: { [weak self] in +// return self?.controller +// } +// ) +// var contentSize = self.hostView.update( +// transition: transition, +// component: self.component, +// environment: { +// environment +// }, +// forceUpdate: true, +// containerSize: CGSize(width: clipFrame.size.width, height: 10000.0) +// ) +// contentSize.height = max(layout.size.height - navigationHeight, contentSize.height) +// transition.setFrame(view: self.hostView, frame: CGRect(origin: CGPoint(), size: contentSize), completion: nil) +// +// self.scrollView.contentSize = contentSize +// } +// +// private var didPlayAppearAnimation = false +// func updateIsVisible(isVisible: Bool) { +// if self.currentIsVisible == isVisible { +// return +// } +// self.currentIsVisible = isVisible +// +// guard let currentLayout = self.currentLayout else { +// return +// } +// self.containerLayoutUpdated(layout: currentLayout.layout, navigationHeight: currentLayout.navigationHeight, transition: .immediate) +// +// if !self.didPlayAppearAnimation { +// self.didPlayAppearAnimation = true +// self.animateIn() +// } +// } +// +// private var defaultTopInset: CGFloat { +// guard let (layout, _) = self.currentLayout else{ +// return 210.0 +// } +// if case .compact = layout.metrics.widthClass { +// var factor: CGFloat = 0.2488 +// if layout.size.width <= 320.0 { +// factor = 0.15 +// } +// return floor(max(layout.size.width, layout.size.height) * factor) +// } else { +// return 210.0 +// } +// } +// +// private func findScrollView(view: UIView?) -> (UIScrollView, ListView?)? { +// if let view = view { +// if let view = view as? UIScrollView { +// return (view, nil) +// } +// if let node = view.asyncdisplaykit_node as? ListView { +// return (node.scroller, node) +// } +// return findScrollView(view: view.superview) +// } else { +// return nil +// } +// } +// +// @objc func panGesture(_ recognizer: UIPanGestureRecognizer) { +// guard let (layout, navigationHeight) = self.currentLayout else { +// return +// } +// +// let isLandscape = layout.orientation == .landscape +// let edgeTopInset = isLandscape ? 0.0 : defaultTopInset +// +// switch recognizer.state { +// case .began: +// let point = recognizer.location(in: self.view) +// let currentHitView = self.hitTest(point, with: nil) +// +// var scrollViewAndListNode = self.findScrollView(view: currentHitView) +// if scrollViewAndListNode?.0.frame.height == self.frame.width { +// scrollViewAndListNode = nil +// } +// let scrollView = scrollViewAndListNode?.0 +// let listNode = scrollViewAndListNode?.1 +// +// let topInset: CGFloat +// if self.isExpanded { +// topInset = 0.0 +// } else { +// topInset = edgeTopInset +// } +// +// self.panGestureArguments = (topInset, 0.0, scrollView, listNode) +// case .changed: +// guard let (topInset, panOffset, scrollView, listNode) = self.panGestureArguments else { +// return +// } +// let visibleContentOffset = listNode?.visibleContentOffset() +// let contentOffset = scrollView?.contentOffset.y ?? 0.0 +// +// var translation = recognizer.translation(in: self.view).y +// +// var currentOffset = topInset + translation +// +// let epsilon = 1.0 +// if case let .known(value) = visibleContentOffset, value <= epsilon { +// if let scrollView = scrollView { +// scrollView.bounces = false +// scrollView.setContentOffset(CGPoint(x: 0.0, y: 0.0), animated: false) +// } +// } else if let scrollView = scrollView, contentOffset <= -scrollView.contentInset.top + epsilon { +// scrollView.bounces = false +// scrollView.setContentOffset(CGPoint(x: 0.0, y: -scrollView.contentInset.top), animated: false) +// } else if let scrollView = scrollView { +// translation = panOffset +// currentOffset = topInset + translation +// if self.isExpanded { +// recognizer.setTranslation(CGPoint(), in: self.view) +// } else if currentOffset > 0.0 { +// scrollView.setContentOffset(CGPoint(x: 0.0, y: -scrollView.contentInset.top), animated: false) +// } +// } +// +// self.panGestureArguments = (topInset, translation, scrollView, listNode) +// +// if !self.isExpanded { +// if currentOffset > 0.0, let scrollView = scrollView { +// scrollView.panGestureRecognizer.setTranslation(CGPoint(), in: scrollView) +// } +// } +// +// var bounds = self.bounds +// if self.isExpanded { +// bounds.origin.y = -max(0.0, translation - edgeTopInset) +// } else { +// bounds.origin.y = -translation +// } +// bounds.origin.y = min(0.0, bounds.origin.y) +// self.bounds = bounds +// +// self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: .immediate) +// case .ended: +// guard let (currentTopInset, panOffset, scrollView, listNode) = self.panGestureArguments else { +// return +// } +// self.panGestureArguments = nil +// +// let visibleContentOffset = listNode?.visibleContentOffset() +// let contentOffset = scrollView?.contentOffset.y ?? 0.0 +// +// let translation = recognizer.translation(in: self.view).y +// var velocity = recognizer.velocity(in: self.view) +// +// if self.isExpanded { +// if case let .known(value) = visibleContentOffset, value > 0.1 { +// velocity = CGPoint() +// } else if case .unknown = visibleContentOffset { +// velocity = CGPoint() +// } else if contentOffset > 0.1 { +// velocity = CGPoint() +// } +// } +// +// var bounds = self.bounds +// if self.isExpanded { +// bounds.origin.y = -max(0.0, translation - edgeTopInset) +// } else { +// bounds.origin.y = -translation +// } +// bounds.origin.y = min(0.0, bounds.origin.y) +// +// scrollView?.bounces = true +// +// let offset = currentTopInset + panOffset +// let topInset: CGFloat = edgeTopInset +// +// var dismissing = false +// if bounds.minY < -60 || (bounds.minY < 0.0 && velocity.y > 300.0) || (self.isExpanded && bounds.minY.isZero && velocity.y > 1800.0) { +// self.controller?.dismiss(animated: true, completion: nil) +// dismissing = true +// } else if self.isExpanded { +// if velocity.y > 300.0 || offset > topInset / 2.0 { +// self.isExpanded = false +// if let listNode = listNode { +// listNode.scroller.setContentOffset(CGPoint(), animated: false) +// } else if let scrollView = scrollView { +// scrollView.setContentOffset(CGPoint(x: 0.0, y: -scrollView.contentInset.top), animated: false) +// } +// +// let distance = topInset - offset +// let initialVelocity: CGFloat = distance.isZero ? 0.0 : abs(velocity.y / distance) +// let transition = ContainedViewLayoutTransition.animated(duration: 0.45, curve: .customSpring(damping: 124.0, initialVelocity: initialVelocity)) +// +// self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: ComponentTransition(transition)) +// } else { +// self.isExpanded = true +// +// self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: ComponentTransition(.animated(duration: 0.3, curve: .easeInOut))) +// } +// } else if (velocity.y < -300.0 || offset < topInset / 2.0) { +// if velocity.y > -2200.0 && velocity.y < -300.0, let listNode = listNode { +// DispatchQueue.main.async { +// listNode.transaction(deleteIndices: [], insertIndicesAndItems: [], updateIndicesAndItems: [], options: [.Synchronous, .LowLatency], scrollToItem: ListViewScrollToItem(index: 0, position: .top(0.0), animated: true, curve: .Default(duration: nil), directionHint: .Up), updateSizeAndInsets: nil, stationaryItemRange: nil, updateOpaqueState: nil, completion: { _ in }) +// } +// } +// +// let initialVelocity: CGFloat = offset.isZero ? 0.0 : abs(velocity.y / offset) +// let transition = ContainedViewLayoutTransition.animated(duration: 0.45, curve: .customSpring(damping: 124.0, initialVelocity: initialVelocity)) +// self.isExpanded = true +// +// self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: ComponentTransition(transition)) +// } else { +// if let listNode = listNode { +// listNode.scroller.setContentOffset(CGPoint(), animated: false) +// } else if let scrollView = scrollView { +// scrollView.setContentOffset(CGPoint(x: 0.0, y: -scrollView.contentInset.top), animated: false) +// } +// +// self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: ComponentTransition(.animated(duration: 0.3, curve: .easeInOut))) +// } +// +// if !dismissing { +// var bounds = self.bounds +// let previousBounds = bounds +// bounds.origin.y = 0.0 +// self.bounds = bounds +// self.layer.animateBounds(from: previousBounds, to: self.bounds, duration: 0.3, timingFunction: CAMediaTimingFunctionName.easeInEaseOut.rawValue) +// } +// case .cancelled: +// self.panGestureArguments = nil +// +// self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: ComponentTransition(.animated(duration: 0.3, curve: .easeInOut))) +// default: +// break +// } +// } +// +// func update(isExpanded: Bool, transition: ContainedViewLayoutTransition) { +// guard isExpanded != self.isExpanded else { +// return +// } +// self.isExpanded = isExpanded +// +// guard let (layout, navigationHeight) = self.currentLayout else { +// return +// } +// self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: ComponentTransition(transition)) +// } +// } +// +// var node: Node { +// return self.displayNode as! Node +// } +// +// private let context: AccountContext +// private let theme: PresentationTheme? +// private let component: AnyComponent +// private var isInitiallyExpanded = false +// +// private var currentLayout: ContainerViewLayout? +// +// public var pushController: (ViewController) -> Void = { _ in } +// public var presentController: (ViewController) -> Void = { _ in } +// +// public var wasDismissed: (() -> Void)? +// +// public convenience init(context: AccountContext, forceTheme: PresentationTheme? = nil, text: String, entities: [MessageTextEntity] = [], canCopy: Bool, fromLanguage: String?, toLanguage: String? = nil, isExpanded: Bool = false, ignoredLanguages: [String]? = nil) { +// let presentationData = context.sharedContext.currentPresentationData.with { $0 } +// +// var baseLanguageCode = presentationData.strings.baseLanguageCode +// let rawSuffix = "-raw" +// if baseLanguageCode.hasSuffix(rawSuffix) { +// baseLanguageCode = String(baseLanguageCode.dropLast(rawSuffix.count)) +// } +// +// let dontTranslateLanguages = effectiveIgnoredTranslationLanguages(context: context, ignoredLanguages: ignoredLanguages) +// +// var toLanguage = toLanguage ?? baseLanguageCode +// if toLanguage == fromLanguage { +// if fromLanguage == "en" { +// toLanguage = dontTranslateLanguages.first(where: { $0 != "en" }) ?? "en" +// } else { +// toLanguage = "en" +// } +// } +// +// toLanguage = normalizeTranslationLanguage(toLanguage) +// +// var copyTranslationImpl: ((String) -> Void)? +// var changeLanguageImpl: ((String, String, @escaping (String, String) -> Void) -> Void)? +// var expandImpl: (() -> Void)? +// self.init(context: context, component: TranslateScreenComponent(context: context, text: text, entities: entities, fromLanguage: fromLanguage, toLanguage: toLanguage, copyTranslation: !canCopy ? nil : { text in +// copyTranslationImpl?(text) +// }, changeLanguage: { fromLang, toLang, completion in +// changeLanguageImpl?(fromLang, toLang, completion) +// }, expand: { +// expandImpl?() +// }), theme: forceTheme) +// +// self.isInitiallyExpanded = isExpanded +// +// self.title = presentationData.strings.Translate_Title +// +// self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: presentationData.strings.Common_Close, style: .plain, target: self, action: #selector(self.cancelPressed)) +// +// self.supportedOrientations = ViewControllerSupportedOrientations(regularSize: .all, compactSize: .portrait) +// +// copyTranslationImpl = { [weak self] text in +// UIPasteboard.general.string = text +// let content = UndoOverlayContent.copy(text: presentationData.strings.Conversation_TextCopied) +// self?.present(UndoOverlayController(presentationData: presentationData, content: content, elevatedLayout: true, animateInAsReplacement: false, action: { _ in return false }), in: .window(.root)) +// self?.dismiss(animated: true, completion: nil) +// } +// +// changeLanguageImpl = { [weak self] fromLang, toLang, completion in +// let pushController = self?.pushController +// let presentController = self?.presentController +// let controller = languageSelectionController(context: context, forceTheme: forceTheme, fromLanguage: fromLang, toLanguage: toLang, completion: { fromLang, toLang in +// let controller = TranslateScreen(context: context, forceTheme: forceTheme, text: text, canCopy: canCopy, fromLanguage: fromLang, toLanguage: toLang, isExpanded: true, ignoredLanguages: ignoredLanguages) +// controller.pushController = pushController ?? { _ in } +// controller.presentController = presentController ?? { _ in } +// presentController?(controller) +// }) +// +// self?.node.temporaryDismiss = true +// self?.dismiss(animated: true, completion: nil) +// +// pushController?(controller) +// } +// +// expandImpl = { [weak self] in +// self?.node.update(isExpanded: true, transition: .animated(duration: 0.4, curve: .spring)) +// if let currentLayout = self?.currentLayout { +// self?.containerLayoutUpdated(currentLayout, transition: .animated(duration: 0.4, curve: .spring)) +// } +// } +// } +// +// private init(context: AccountContext, component: C, theme: PresentationTheme? = nil) where C.EnvironmentType == ViewControllerComponentContainer.Environment { +// self.context = context +// self.component = AnyComponent(component) +// self.theme = theme +// +// var presentationData = context.sharedContext.currentPresentationData.with { $0 } +// if let theme { +// presentationData = presentationData.withUpdated(theme: theme) +// } +// super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: presentationData)) +// } +// +// required public init(coder aDecoder: NSCoder) { +// fatalError("init(coder:) has not been implemented") +// } +// +// @objc private func cancelPressed() { +// self.dismiss(animated: true, completion: nil) +// } +// +// override open func loadDisplayNode() { +// self.displayNode = Node(context: self.context, controller: self, component: self.component, theme: self.theme) +// if self.isInitiallyExpanded { +// (self.displayNode as! Node).update(isExpanded: true, transition: .immediate) +// } +// self.displayNodeDidLoad() +// } +// +// public override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { +// self.view.endEditing(true) +// let wasDismissed = self.wasDismissed +// if flag { +// self.node.animateOut(completion: { +// super.dismiss(animated: false, completion: {}) +// wasDismissed?() +// completion?() +// }) +// } else { +// super.dismiss(animated: false, completion: {}) +// wasDismissed?() +// completion?() +// } +// } +// +// override open func viewDidAppear(_ animated: Bool) { +// super.viewDidAppear(animated) +// +// self.node.updateIsVisible(isVisible: true) +// } +// +// override open func viewDidDisappear(_ animated: Bool) { +// super.viewDidDisappear(animated) +// +// self.node.updateIsVisible(isVisible: false) +// } +// +// override public func updateNavigationBarLayout(_ layout: ContainerViewLayout, transition: ContainedViewLayoutTransition) { +// var navigationLayout = self.navigationLayout(layout: layout) +// var navigationFrame = navigationLayout.navigationFrame +// +// var layout = layout +// if case .regular = layout.metrics.widthClass { +// let verticalInset: CGFloat = 44.0 +// let maxSide = max(layout.size.width, layout.size.height) +// let minSide = min(layout.size.width, layout.size.height) +// let containerSize = CGSize(width: min(layout.size.width - 20.0, floor(maxSide / 2.0)), height: min(layout.size.height, minSide) - verticalInset * 2.0) +// let clipFrame = CGRect(origin: CGPoint(x: floor((layout.size.width - containerSize.width) / 2.0), y: floor((layout.size.height - containerSize.height) / 2.0)), size: containerSize) +// navigationFrame.size.width = clipFrame.width +// layout.size = clipFrame.size +// } +// +// navigationFrame.size.height = 56.0 +// navigationLayout.navigationFrame = navigationFrame +// navigationLayout.defaultContentHeight = 56.0 +// +// layout.statusBarHeight = nil +// +// self.applyNavigationBarLayout(layout, navigationLayout: navigationLayout, additionalBackgroundHeight: 0.0, additionalCutout: nil, transition: transition) +// } +// +// override open func containerLayoutUpdated(_ layout: ContainerViewLayout, transition: ContainedViewLayoutTransition) { +// self.currentLayout = layout +// super.containerLayoutUpdated(layout, transition: transition) +// +// let navigationHeight: CGFloat = 56.0 +// +// self.node.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: ComponentTransition(transition)) +// } +//} + public func presentTranslateScreen( context: AccountContext, text: String, @@ -1200,7 +1436,7 @@ public func presentTranslateScreen( display: (ViewController) -> Void ) { let translationConfiguration = TranslationConfiguration.with(appConfiguration: context.currentAppConfiguration.with { $0 }) - var useSystemTranslation = false + var useSystemTranslation = SGSimpleSettings.shared.translationBackendEnum == .system switch translationConfiguration.manual { case .system: if #available(iOS 18.0, *) { @@ -1213,7 +1449,7 @@ public func presentTranslateScreen( if useSystemTranslation { presentSystemTranslateScreen(context: context, text: text) } else { - let controller = TranslateScreen(context: context, text: text, canCopy: canCopy, fromLanguage: fromLanguage, toLanguage: toLanguage, isExpanded: isExpanded, ignoredLanguages: ignoredLanguages) + let controller = TranslateScreen(context: context, text: text, canCopy: canCopy, fromLanguage: fromLanguage, toLanguage: toLanguage, ignoredLanguages: ignoredLanguages) controller.pushController = pushController controller.presentController = presentController controller.wasDismissed = wasDismissed diff --git a/submodules/UrlHandling/Sources/UrlHandling.swift b/submodules/UrlHandling/Sources/UrlHandling.swift index 82ace727..0ef1262e 100644 --- a/submodules/UrlHandling/Sources/UrlHandling.swift +++ b/submodules/UrlHandling/Sources/UrlHandling.swift @@ -1209,8 +1209,16 @@ private func resolveInternalUrl(context: AccountContext, url: ParsedInternalUrl) case let .collectible(slug): return .single(.progress) |> then(context.engine.payments.getUniqueStarGift(slug: slug) |> map { gift -> ResolveInternalUrlResult in - return .result(.collectible(gift: gift)) + return .result(.collectible(.gift(gift))) }) + |> `catch` { error -> Signal in + switch error { + case .alreadyBurned: + return .single(.result(.collectible(.alreadyBurned))) + default: + return .single(.result(.collectible(.invalidSlug))) + } + } case let .auction(slug): if let giftAuctionsManager = context.giftAuctionsManager { return .single(.progress) |> then(giftAuctionsManager.auctionContext(for: .slug(slug)) diff --git a/submodules/Utils/DeviceModel/BUILD b/submodules/Utils/DeviceModel/BUILD index 16d3d3f3..4152adec 100644 --- a/submodules/Utils/DeviceModel/BUILD +++ b/submodules/Utils/DeviceModel/BUILD @@ -9,11 +9,7 @@ swift_library( copts = [ "-warnings-as-errors", ], - deps = [ - "//submodules/SSignalKit/SwiftSignalKit", - "//submodules/LegacyComponents", - "//submodules/AccountContext", - ], + deps = [], visibility = [ "//visibility:public", ], diff --git a/submodules/WallpaperBackgroundNode/BUILD b/submodules/WallpaperBackgroundNode/BUILD index ccba786f..c9ab85d0 100644 --- a/submodules/WallpaperBackgroundNode/BUILD +++ b/submodules/WallpaperBackgroundNode/BUILD @@ -40,19 +40,27 @@ apple_resource_bundle( ], ) +sgdeps = [ + "//Swiftgram/SGSimpleSettings:SGSimpleSettings", +] + +sgsrcs = [ + "//Swiftgram/SGNY:SGNY" +] + swift_library( name = "WallpaperBackgroundNode", module_name = "WallpaperBackgroundNode", srcs = glob([ "Sources/**/*.swift", - ]), + ]) + sgsrcs, copts = [ "-warnings-as-errors", ], data = [ ":WallpaperBackgroundNodeBundle", ], - deps = [ + deps = sgdeps + [ "//submodules/AsyncDisplayKit:AsyncDisplayKit", "//submodules/Display:Display", "//submodules/GradientBackground:GradientBackground", diff --git a/submodules/WallpaperBackgroundNode/Sources/WallpaperBackgroundNode.swift b/submodules/WallpaperBackgroundNode/Sources/WallpaperBackgroundNode.swift index 80b974c6..94f19efb 100644 --- a/submodules/WallpaperBackgroundNode/Sources/WallpaperBackgroundNode.swift +++ b/submodules/WallpaperBackgroundNode/Sources/WallpaperBackgroundNode.swift @@ -1,3 +1,4 @@ +import SGSimpleSettings import Foundation import UIKit import AsyncDisplayKit @@ -51,6 +52,44 @@ private func calculateWallpaperBrightness(from colors: [UInt32]) -> CGFloat { return UIColor.average(of: colors.map(UIColor.init(rgb:))).hsb.b } +private func calculateWallpaperSaturation(from colors: [UInt32]) -> CGFloat { + guard !colors.isEmpty else { + return 0.0 + } + + var hsbValues: [(h: CGFloat, s: CGFloat, b: CGFloat)] = [] + for color in colors { + hsbValues.append(UIColor(rgb: color).hsb) + } + + // Check if any two colors have different hues (>60° apart) + var colorsAreDiverse = false + outer: for i in 0 ..< hsbValues.count { + for j in (i + 1) ..< hsbValues.count { + let hueDiff = abs(hsbValues[i].h - hsbValues[j].h) + let angularDiff = min(hueDiff, 1.0 - hueDiff) + if angularDiff > 0.167 { + colorsAreDiverse = true + break outer + } + } + } + + var maxSaturation: CGFloat = 0.0 + for hsb in hsbValues { + let saturation: CGFloat + if colorsAreDiverse { + // Diverse colors: only penalize darkness, not brightness + saturation = hsb.s * min(hsb.b * 2.0, 1.0) + } else { + // Similar colors: original formula + saturation = hsb.s * min(hsb.b, 1.0 - hsb.b) * 2.0 + } + maxSaturation = max(maxSaturation, saturation) + } + return maxSaturation +} + private func calculateWallpaperBrightness(from image: UIImage) -> CGFloat { guard let cgImage = image.cgImage else { return 1.0 @@ -102,6 +141,51 @@ private func calculateWallpaperBrightness(from image: UIImage) -> CGFloat { return totalLuminance / CGFloat(pixelCount) } +private func calculateWallpaperSaturation(from image: UIImage) -> CGFloat { + guard let cgImage = image.cgImage else { + return 0.0 + } + + let targetSize = CGSize(width: 10.0, height: 10.0) + let width = Int(targetSize.width) + let height = Int(targetSize.height) + let bytesPerPixel = 4 + let bytesPerRow = bytesPerPixel * width + let bitsPerComponent = 8 + + var pixelData = [UInt8](repeating: 0, count: width * height * bytesPerPixel) + + guard let context = CGContext( + data: &pixelData, + width: width, + height: height, + bitsPerComponent: bitsPerComponent, + bytesPerRow: bytesPerRow, + space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue + ) else { + return 0.0 + } + + context.draw(cgImage, in: CGRect(origin: .zero, size: targetSize)) + + var totalWeightedSaturation: CGFloat = 0.0 + let pixelCount = width * height + + for i in 0 ..< pixelCount { + let offset = i * bytesPerPixel + let r = CGFloat(pixelData[offset]) / 255.0 + let g = CGFloat(pixelData[offset + 1]) / 255.0 + let b = CGFloat(pixelData[offset + 2]) / 255.0 + + let hsb = UIColor(red: r, green: g, blue: b, alpha: 1.0).hsb + let weightedSaturation = hsb.s * min(hsb.b, 1.0 - hsb.b) * 2.0 + totalWeightedSaturation += weightedSaturation + } + + return totalWeightedSaturation / CGFloat(pixelCount) +} + public enum WallpaperBubbleType { case incoming case outgoing @@ -156,14 +240,24 @@ public struct WallpaperEdgeEffectEdge: Equatable { } public protocol WallpaperEdgeEffectNode: ASDisplayNode { - func update(rect: CGRect, edge: WallpaperEdgeEffectEdge, blur: Bool, containerSize: CGSize, transition: ContainedViewLayoutTransition) + func update(rect: CGRect, edge: WallpaperEdgeEffectEdge, alpha: CGFloat, blur: Bool, containerSize: CGSize, transition: ContainedViewLayoutTransition) +} + +public struct WallpaperContentStats: Equatable { + public let isDark: Bool + public let isSaturated: Bool + + public init(isDark: Bool, isSaturated: Bool) { + self.isDark = isDark + self.isSaturated = isSaturated + } } public protocol WallpaperBackgroundNode: ASDisplayNode { var isReady: Signal { get } var rotation: CGFloat { get set } - var isDark: Bool? { get } - var isDarkUpdated: (() -> Void)? { get set } + var contentStats: WallpaperContentStats? { get } + var contentStatsUpdated: (() -> Void)? { get set } func update(wallpaper: TelegramWallpaper, animated: Bool) func update(wallpaper: TelegramWallpaper, starGift: StarGift?, animated: Bool) @@ -1020,6 +1114,10 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou } } + // MARK: Swiftgram + private var NYNode: WallpaperNYNode? + // + private var imageContentMode: UIView.ContentMode { didSet { self.contentNode.contentMode = self.imageContentMode @@ -1041,13 +1139,13 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou } private static var cachedSharedPattern: (PatternKey, UIImage)? - public private(set) var isDark: Bool? - public var isDarkUpdated: (() -> Void)? + public private(set) var contentStats: WallpaperContentStats? + public var contentStatsUpdated: (() -> Void)? - private func updateIsDark(_ isDark: Bool?) { - if self.isDark != isDark { - self.isDark = isDark - self.isDarkUpdated?() + private func updateContentStats(_ contentStats: WallpaperContentStats?) { + if self.contentStats != contentStats { + self.contentStats = contentStats + self.contentStatsUpdated?() } } @@ -1205,9 +1303,9 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou self.wallpaperDisposable.set(nil) if case let .file(file) = wallpaper, file.isPattern { - self.updateIsDark(nil) + self.updateContentStats(nil) } else { - self.updateIsDark(calculateWallpaperBrightness(from: gradientColors) <= 0.3) + self.updateContentStats(WallpaperContentStats(isDark: calculateWallpaperBrightness(from: gradientColors) <= 0.34, isSaturated: calculateWallpaperSaturation(from: gradientColors) > 0.35)) } } else { if let gradientBackgroundNode = self.gradientBackgroundNode { @@ -1237,20 +1335,20 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou self.contentNode.contents = image?.cgImage self.blurredBackgroundContents = image self.wallpaperDisposable.set(nil) - self.updateIsDark(calculateWallpaperBrightness(from: gradientColors) <= 0.3) + updateContentStats(WallpaperContentStats(isDark: calculateWallpaperBrightness(from: gradientColors) <= 0.3, isSaturated: calculateWallpaperSaturation(from: gradientColors) > 0.35)) } else if gradientColors.count >= 1 { self.contentNode.backgroundColor = UIColor(rgb: gradientColors[0]) self.contentNode.contents = nil self.blurredBackgroundContents = nil self.wallpaperDisposable.set(nil) - self.updateIsDark(calculateWallpaperBrightness(from: gradientColors) <= 0.3) + updateContentStats(WallpaperContentStats(isDark: calculateWallpaperBrightness(from: gradientColors) <= 0.3, isSaturated: calculateWallpaperSaturation(from: gradientColors) > 0.35)) } else { self.contentNode.backgroundColor = .white if let image = chatControllerBackgroundImage(theme: nil, wallpaper: wallpaper, mediaBox: self.context.sharedContext.accountManager.mediaBox, knockoutMode: false) { self.contentNode.contents = image.cgImage self.blurredBackgroundContents = generateBlurredContents(image: image, dimColor: wallpaperDimColor) self.wallpaperDisposable.set(nil) - self.updateIsDark(calculateWallpaperBrightness(from: image) <= 0.55) + updateContentStats(WallpaperContentStats(isDark: calculateWallpaperBrightness(from: image) <= 0.55, isSaturated: calculateWallpaperSaturation(from: image) > 0.35)) Queue.mainQueue().justDispatch { self._isReady.set(true) } @@ -1258,7 +1356,7 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou self.contentNode.contents = image.cgImage self.blurredBackgroundContents = generateBlurredContents(image: image, dimColor: wallpaperDimColor) self.wallpaperDisposable.set(nil) - self.updateIsDark(calculateWallpaperBrightness(from: image) <= 0.55) + self.updateContentStats(WallpaperContentStats(isDark: calculateWallpaperBrightness(from: image) <= 0.55, isSaturated: calculateWallpaperSaturation(from: image) > 0.35)) Queue.mainQueue().justDispatch { self._isReady.set(true) } @@ -1271,7 +1369,7 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou strongSelf.contentNode.contents = image?.0?.cgImage if let image = image?.0 { strongSelf.blurredBackgroundContents = generateBlurredContents(image: image, dimColor: wallpaperDimColor) - strongSelf.updateIsDark(calculateWallpaperBrightness(from: image) <= 0.55) + strongSelf.updateContentStats(WallpaperContentStats(isDark: calculateWallpaperBrightness(from: image) <= 0.55, isSaturated: calculateWallpaperSaturation(from: image) > 0.35)) } else { strongSelf.blurredBackgroundContents = nil } @@ -1507,7 +1605,6 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou if self.validPatternGeneratedImage != updatedGeneratedImage { self.validPatternGeneratedImage = updatedGeneratedImage - if let cachedValidPatternImage = WallpaperBackgroundNodeImpl.cachedValidPatternImage, cachedValidPatternImage.generated == updatedGeneratedImage { self.patternImageLayer.suspendCompositionUpdates = true self.updatePatternPresentation() @@ -1570,7 +1667,7 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou if let validPatternImage = self.validPatternImage, !validPatternImage.rects.isEmpty, let starGift = validPatternImage.starGift { if case let .unique(uniqueGift) = starGift { for attribute in uniqueGift.attributes { - if case let .model(_, file, _) = attribute { + if case let .model(_, file, _, _) = attribute { modelFile = file } } @@ -1689,7 +1786,9 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou if isFirstLayout && !self.frame.isEmpty { self.updateScale() + /* MARK: Swiftgram */ if SGSimpleSettings.shared.isNYEnabled && self.NYNode == nil { let nYNode = WallpaperNYNode(); self.addSubnode(nYNode); self.NYNode = nYNode } } + /* MARK: Swiftgram */ self.NYNode?.frame = CGRect(origin: CGPoint(), size: size); self.NYNode?.updateLayout(size: size) } private var isAnimating = false diff --git a/submodules/WallpaperBackgroundNode/Sources/WallpaperEdgeEffectNodeImpl.swift b/submodules/WallpaperBackgroundNode/Sources/WallpaperEdgeEffectNodeImpl.swift index 8898e7f8..bec63c7a 100644 --- a/submodules/WallpaperBackgroundNode/Sources/WallpaperEdgeEffectNodeImpl.swift +++ b/submodules/WallpaperBackgroundNode/Sources/WallpaperEdgeEffectNodeImpl.swift @@ -12,12 +12,14 @@ final class WallpaperEdgeEffectNodeImpl: ASDisplayNode, WallpaperEdgeEffectNode private struct Params: Equatable { let rect: CGRect let edge: WallpaperEdgeEffectEdge + let alpha: CGFloat let blur: Bool let containerSize: CGSize - init(rect: CGRect, edge: WallpaperEdgeEffectEdge, blur: Bool, containerSize: CGSize) { + init(rect: CGRect, edge: WallpaperEdgeEffectEdge, alpha: CGFloat, blur: Bool, containerSize: CGSize) { self.rect = rect self.edge = edge + self.alpha = alpha self.blur = blur self.containerSize = containerSize } @@ -94,7 +96,7 @@ final class WallpaperEdgeEffectNodeImpl: ASDisplayNode, WallpaperEdgeEffectNode self.containerNode.insertSubnode(gradientNode, at: 0) if let params = self.params { - self.updateImpl(rect: params.rect, edge: params.edge, blur: params.blur, containerSize: params.containerSize, transition: .immediate) + self.updateImpl(rect: params.rect, edge: params.edge, alpha: params.alpha, blur: params.blur, containerSize: params.containerSize, transition: .immediate) } } } else { @@ -123,15 +125,16 @@ final class WallpaperEdgeEffectNodeImpl: ASDisplayNode, WallpaperEdgeEffectNode self.contentNode.isHidden = parentNode.contentNode.isHidden } - func update(rect: CGRect, edge: WallpaperEdgeEffectEdge, blur: Bool, containerSize: CGSize, transition: ContainedViewLayoutTransition) { - let params = Params(rect: rect, edge: edge, blur: blur, containerSize: containerSize) + func update(rect: CGRect, edge: WallpaperEdgeEffectEdge, alpha: CGFloat, blur: Bool, containerSize: CGSize, transition: ContainedViewLayoutTransition) { + let params = Params(rect: rect, edge: edge, alpha: alpha, blur: blur, containerSize: containerSize) if self.params != params { self.params = params - self.updateImpl(rect: params.rect, edge: params.edge, blur: params.blur, containerSize: params.containerSize, transition: transition) + self.updateImpl(rect: params.rect, edge: params.edge, alpha: params.alpha, blur: params.blur, containerSize: params.containerSize, transition: transition) } } - private func updateImpl(rect: CGRect, edge: WallpaperEdgeEffectEdge, blur: Bool, containerSize: CGSize, transition: ContainedViewLayoutTransition) { + private func updateImpl(rect: CGRect, edge: WallpaperEdgeEffectEdge, alpha: CGFloat, blur: Bool, containerSize: CGSize, transition: ContainedViewLayoutTransition) { + transition.updateAlpha(node: self, alpha: alpha) transition.updateFrame(node: self.containerMaskingNode, frame: CGRect(origin: CGPoint(), size: rect.size)) transition.updateBounds(node: self.containerNode, bounds: CGRect(origin: CGPoint(x: rect.minX, y: rect.minY), size: rect.size)) diff --git a/submodules/WatchBridge/BUILD b/submodules/WatchBridge/BUILD new file mode 100644 index 00000000..5766afcb --- /dev/null +++ b/submodules/WatchBridge/BUILD @@ -0,0 +1,33 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "WatchBridge", + module_name = "WatchBridge", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + "//submodules/SSignalKit/SSignalKit:SSignalKit", + "//submodules/Postbox:Postbox", + "//submodules/TelegramCore:TelegramCore", + "//submodules/WatchCommon/Host:WatchCommon", + "//submodules/WatchBridgeAudio:WatchBridgeAudio", + "//submodules/TelegramPresentationData:TelegramPresentationData", + "//submodules/TelegramUIPreferences:TelegramUIPreferences", + "//submodules/AccountContext:AccountContext", + "//submodules/AvatarNode:AvatarNode", + "//submodules/StickerResources:StickerResources", + "//submodules/PhotoResources:PhotoResources", + "//submodules/LegacyComponents:LegacyComponents", + "//submodules/LegacyUI:LegacyUI", + "//submodules/PhoneNumberFormat:PhoneNumberFormat", + "//submodules/WatchBridge/Impl:WatchBridgeImpl", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/submodules/WatchBridge/Impl/BUILD b/submodules/WatchBridge/Impl/BUILD new file mode 100644 index 00000000..764f2687 --- /dev/null +++ b/submodules/WatchBridge/Impl/BUILD @@ -0,0 +1,27 @@ + +objc_library( + name = "WatchBridgeImpl", + enable_modules = True, + module_name = "WatchBridgeImpl", + srcs = glob([ + "Sources/**/*.m", + "Sources/**/*.h", + ], allow_empty=True), + hdrs = glob([ + "PublicHeaders/**/*.h", + ]), + includes = [ + "PublicHeaders", + ], + deps = [ + "//submodules/LegacyComponents:LegacyComponents", + "//submodules/WatchCommon/Host:WatchCommon", + ], + sdk_frameworks = [ + "Foundation", + "WatchConnectivity", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/submodules/WatchBridge/Impl/PublicHeaders/WatchBridgeImpl/TGBridgeServer.h b/submodules/WatchBridge/Impl/PublicHeaders/WatchBridgeImpl/TGBridgeServer.h new file mode 100644 index 00000000..d28a8b03 --- /dev/null +++ b/submodules/WatchBridge/Impl/PublicHeaders/WatchBridgeImpl/TGBridgeServer.h @@ -0,0 +1,29 @@ +#import +#import + +@class TGBridgeSubscription; + +@interface TGBridgeServer : NSObject + +@property (nonatomic, readonly) NSURL * _Nullable temporaryFilesURL; + +@property (nonatomic, readonly) bool isRunning; + +- (instancetype _Nonnull)initWithHandler:(SSignal * _Nullable (^ _Nonnull)(TGBridgeSubscription * _Nullable))handler fileHandler:(void (^ _Nonnull)(NSString * _Nullable, NSDictionary * _Nullable))fileHandler dispatchOnQueue:(void (^ _Nonnull)(void (^ _Nonnull)(void)))dispatchOnQueue logFunction:(void (^ _Nonnull)(NSString * _Nullable))logFunction allowBackgroundTimeExtension:(void (^ _Nonnull)())allowBackgroundTimeExtension; +- (void)startRunning; + +- (SSignal * _Nonnull)watchAppInstalledSignal; +- (SSignal * _Nonnull)runningRequestsSignal; + +- (void)setAuthorized:(bool)authorized userId:(int64_t)userId; +- (void)setMicAccessAllowed:(bool)allowed; +- (void)setStartupData:(NSDictionary * _Nullable)data; +- (void)pushContext; + +- (void)sendFileWithURL:(NSURL * _Nonnull)url metadata:(NSDictionary * _Nullable)metadata asMessageData:(bool)asMessageData; +- (void)sendFileWithData:(NSData * _Nonnull)data metadata:(NSDictionary * _Nullable)metadata errorHandler:(void (^ _Nullable)(void))errorHandler; + +- (NSInteger)wakeupNetwork; +- (void)suspendNetworkIfReady:(NSInteger)token; + +@end diff --git a/submodules/WatchBridge/Impl/PublicHeaders/WatchBridgeImpl/WatchBridgeImpl.h b/submodules/WatchBridge/Impl/PublicHeaders/WatchBridgeImpl/WatchBridgeImpl.h new file mode 100644 index 00000000..8ed2f162 --- /dev/null +++ b/submodules/WatchBridge/Impl/PublicHeaders/WatchBridgeImpl/WatchBridgeImpl.h @@ -0,0 +1,3 @@ +#import + +#import diff --git a/submodules/WatchBridge/Impl/Sources/TGBridgeServer.m b/submodules/WatchBridge/Impl/Sources/TGBridgeServer.m new file mode 100644 index 00000000..5664ac12 --- /dev/null +++ b/submodules/WatchBridge/Impl/Sources/TGBridgeServer.m @@ -0,0 +1,770 @@ +#import + +#import +#import +#import +#import + +@interface TGBridgeSignalManager : NSObject + +- (bool)startSignalForKey:(NSString *)key producer:(SSignal *(^)())producer; +- (void)haltSignalForKey:(NSString *)key; +- (void)haltAllSignals; + +@end + +@interface TGBridgeServer () +{ + SSignal *(^_handler)(TGBridgeSubscription *); + void (^_fileHandler)(NSString *, NSDictionary *); + void (^_logFunction)(NSString *); + void (^_dispatch)(void (^)(void)); + + bool _pendingStart; + + bool _processingNotification; + + int32_t _sessionId; + volatile int32_t _tasksVersion; + + TGBridgeContext *_activeContext; + + TGBridgeSignalManager *_signalManager; + + os_unfair_lock _incomingQueueLock; + NSMutableArray *_incomingMessageQueue; + + bool _requestSubscriptionList; + NSArray *_initialSubscriptionList; + + os_unfair_lock _outgoingQueueLock; + NSMutableArray *_outgoingMessageQueue; + + os_unfair_lock _replyHandlerMapLock; + NSMutableDictionary *_replyHandlerMap; + + SPipe *_appInstalled; + + NSMutableDictionary *_runningTasks; + SVariable *_hasRunningTasks; + + void (^_allowBackgroundTimeExtension)(); +} + +@property (nonatomic, readonly) WCSession *session; + +@end + +@implementation TGBridgeServer + +- (instancetype)initWithHandler:(SSignal *(^)(TGBridgeSubscription *))handler fileHandler:(void (^)(NSString *, NSDictionary *))fileHandler dispatchOnQueue:(void (^)(void (^)(void)))dispatchOnQueue logFunction:(void (^)(NSString *))logFunction allowBackgroundTimeExtension:(void (^)())allowBackgroundTimeExtension +{ + self = [super init]; + if (self != nil) + { + _handler = [handler copy]; + _fileHandler = [fileHandler copy]; + _dispatch = [dispatchOnQueue copy]; + _logFunction = [logFunction copy]; + _allowBackgroundTimeExtension = [allowBackgroundTimeExtension copy]; + + _runningTasks = [[NSMutableDictionary alloc] init]; + _hasRunningTasks = [[SVariable alloc] init]; + [_hasRunningTasks set:[SSignal single:@false]]; + + _signalManager = [[TGBridgeSignalManager alloc] init]; + _incomingMessageQueue = [[NSMutableArray alloc] init]; + + self.session.delegate = self; + [self.session activateSession]; + + _replyHandlerMap = [[NSMutableDictionary alloc] init]; + + _appInstalled = [[SPipe alloc] init]; + + _activeContext = [[TGBridgeContext alloc] initWithDictionary:[self.session applicationContext]]; + } + return self; +} + +- (void)log:(NSString *)message +{ + _logFunction(message); +} + +- (void)dispatch:(void (^)(void))action +{ + _dispatch(action); +} + +- (void)startRunning +{ + if (self.isRunning) + return; + + os_unfair_lock_lock(&_incomingQueueLock); + _isRunning = true; + + for (id message in _incomingMessageQueue) + [self handleMessage:message replyHandler:nil finishTask:nil completion:nil]; + + [_incomingMessageQueue removeAllObjects]; + os_unfair_lock_unlock(&_incomingQueueLock); + + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [self dispatch:^{ + _appInstalled.sink(@(self.session.isWatchAppInstalled)); + }]; + }); +} + +- (NSURL *)temporaryFilesURL +{ + return self.session.watchDirectoryURL; +} + +- (SSignal *)watchAppInstalledSignal +{ + return [[SSignal single:@(self.session.watchAppInstalled)] then:_appInstalled.signalProducer()]; +} + +- (SSignal *)runningRequestsSignal +{ + return _hasRunningTasks.signal; +} + +#pragma mark - + +- (void)setAuthorized:(bool)authorized userId:(int64_t)userId +{ + _activeContext = [_activeContext updatedWithAuthorized:authorized peerId:userId]; +} + +- (void)setMicAccessAllowed:(bool)allowed +{ + _activeContext = [_activeContext updatedWithMicAccessAllowed:allowed]; +} + +- (void)setStartupData:(NSDictionary *)data +{ + _activeContext = [_activeContext updatedWithPreheatData:data]; +} + +- (void)pushContext +{ + NSError *error; + [self.session updateApplicationContext:[_activeContext dictionary] error:&error]; + + //if (error != nil) + //TGLog(@"[BridgeServer][ERROR] Failed to push active application context: %@", error.localizedDescription); +} + +#pragma mark - + +- (void)handleMessageData:(NSData *)messageData task:(id)task replyHandler:(void (^)(NSData *))replyHandler completion:(void (^)(void))completion +{ + if (_allowBackgroundTimeExtension) { + _allowBackgroundTimeExtension(); + } + + __block id runningTask = task; + void (^finishTask)(NSTimeInterval) = ^(NSTimeInterval delay) + { + if (runningTask == nil) + return; + + void (^block)(void) = ^ + { + [self dispatch:^{ + [runningTask dispose]; + //TGLog(@"[BridgeServer]: ended taskid: %d", runningTask); + runningTask = nil; + }]; + }; + + if (delay > DBL_EPSILON) + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((delay) * NSEC_PER_SEC)), dispatch_get_main_queue(), block); + else + block(); + }; + + id message = [NSKeyedUnarchiver unarchiveObjectWithData:messageData]; + os_unfair_lock_lock(&_incomingQueueLock); + if (!self.isRunning) + { + [_incomingMessageQueue addObject:message]; + + if (replyHandler != nil) + replyHandler([NSData data]); + + finishTask(4.0); + + os_unfair_lock_unlock(&_incomingQueueLock); + return; + } + os_unfair_lock_unlock(&_incomingQueueLock); + + [self handleMessage:message replyHandler:replyHandler finishTask:finishTask completion:completion]; +} + +- (void)handleMessage:(id)message replyHandler:(void (^)(NSData *))replyHandler finishTask:(void (^)(NSTimeInterval))finishTask completion:(void (^)(void))completion +{ + if ([message isKindOfClass:[TGBridgeSubscription class]]) + { + TGBridgeSubscription *subcription = (TGBridgeSubscription *)message; + [self _createSubscription:subcription replyHandler:replyHandler finishTask:finishTask completion:completion]; + + //TGLog(@"[BridgeServer] Create subscription: %@", subcription); + } + else if ([message isKindOfClass:[TGBridgeDisposal class]]) + { + TGBridgeDisposal *disposal = (TGBridgeDisposal *)message; + [_signalManager haltSignalForKey:[NSString stringWithFormat:@"%lld", disposal.identifier]]; + + if (replyHandler != nil) + replyHandler([NSData data]); + + if (completion != nil) + completion(); + + //TGLog(@"[BridgeServer] Dispose subscription %lld", disposal.identifier); + + if (finishTask != nil) + finishTask(0); + } + else if ([message isKindOfClass:[TGBridgeSubscriptionList class]]) + { + TGBridgeSubscriptionList *list = (TGBridgeSubscriptionList *)message; + for (TGBridgeSubscription *subscription in list.subscriptions) + [self _createSubscription:subscription replyHandler:nil finishTask:nil completion:nil]; + + //TGLog(@"[BridgeServer] Received subscription list, applying"); + + if (replyHandler != nil) + replyHandler([NSData data]); + + if (finishTask != nil) + finishTask(4.0); + + if (completion != nil) + completion(); + } + else if ([message isKindOfClass:[TGBridgePing class]]) + { + TGBridgePing *ping = (TGBridgePing *)message; + if (_sessionId != ping.sessionId) + { + //TGLog(@"[BridgeServer] Session id mismatch"); + + if (_sessionId != 0) + { + //TGLog(@"[BridgeServer] Halt all active subscriptions"); + [_signalManager haltAllSignals]; + + os_unfair_lock_lock(&_outgoingQueueLock); + [_outgoingMessageQueue removeAllObjects]; + os_unfair_lock_unlock(&_outgoingQueueLock); + } + + _sessionId = ping.sessionId; + + if (self.session.isReachable) + [self _requestSubscriptionList]; + else + _requestSubscriptionList = true; + } + else + { + if (_requestSubscriptionList) + { + _requestSubscriptionList = false; + [self _requestSubscriptionList]; + } + + [self _sendQueuedResponses]; + + if (replyHandler != nil) + replyHandler([NSData data]); + } + + if (completion != nil) + completion(); + + if (finishTask != nil) + finishTask(4.0); + } + else + { + if (completion != nil) + completion(); + if (finishTask != nil) + finishTask(1.0); + } +} + +- (void)_createSubscription:(TGBridgeSubscription *)subscription replyHandler:(void (^)(NSData *))replyHandler finishTask:(void (^)(NSTimeInterval))finishTask completion:(void (^)(void))completion +{ + SSignal *subscriptionHandler = _handler(subscription); + if (replyHandler != nil) + { + os_unfair_lock_lock(&_replyHandlerMapLock); + _replyHandlerMap[@(subscription.identifier)] = replyHandler; + os_unfair_lock_unlock(&_replyHandlerMapLock); + } + + if (subscriptionHandler != nil) + { + [_signalManager startSignalForKey:[NSString stringWithFormat:@"%lld", subscription.identifier] producer:^SSignal * + { + STimer *timer = [[STimer alloc] initWithTimeout:2.0 repeat:false completion:^(__unused STimer *timer) + { + os_unfair_lock_lock(&_replyHandlerMapLock); + void (^reply)(NSData *) = _replyHandlerMap[@(subscription.identifier)]; + if (reply == nil) + { + os_unfair_lock_unlock(&_replyHandlerMapLock); + + if (finishTask != nil) + finishTask(2.0); + return; + } + + reply([NSData data]); + [_replyHandlerMap removeObjectForKey:@(subscription.identifier)]; + os_unfair_lock_unlock(&_replyHandlerMapLock); + + if (finishTask != nil) + finishTask(4.0); + + //TGLog(@"[BridgeServer]: subscription 0x%x hit 2.0s timeout, releasing reply handler", subscription.identifier); + } queue:[SQueue mainQueue]]; + [timer start]; + + return [[SSignal alloc] initWithGenerator:^id(__unused SSubscriber *subscriber) + { + return [subscriptionHandler startWithNext:^(id next) + { + [timer invalidate]; + [self _responseToSubscription:subscription message:next type:TGBridgeResponseTypeNext completion:completion]; + + if (finishTask != nil) + finishTask(4.0); + } error:^(id error) + { + [timer invalidate]; + [self _responseToSubscription:subscription message:error type:TGBridgeResponseTypeFailed completion:completion]; + + if (finishTask != nil) + finishTask(4.0); + } completed:^ + { + [timer invalidate]; + [self _responseToSubscription:subscription message:nil type:TGBridgeResponseTypeCompleted completion:completion]; + + if (finishTask != nil) + finishTask(4.0); + }]; + }]; + }]; + } + else + { + os_unfair_lock_lock(&_replyHandlerMapLock); + void (^reply)(NSData *) = _replyHandlerMap[@(subscription.identifier)]; + if (reply == nil) + { + os_unfair_lock_unlock(&_replyHandlerMapLock); + + if (finishTask != nil) + finishTask(2.0); + return; + } + + reply([NSData data]); + [_replyHandlerMap removeObjectForKey:@(subscription.identifier)]; + os_unfair_lock_unlock(&_replyHandlerMapLock); + + if (finishTask != nil) + finishTask(2.0); + } +} + +- (void)_responseToSubscription:(TGBridgeSubscription *)subscription message:(id)message type:(TGBridgeResponseType)type completion:(void (^)(void))completion +{ + TGBridgeResponse *response = nil; + switch (type) + { + case TGBridgeResponseTypeNext: + response = [TGBridgeResponse single:message forSubscription:subscription]; + break; + + case TGBridgeResponseTypeFailed: + response = [TGBridgeResponse fail:message forSubscription:subscription]; + break; + + case TGBridgeResponseTypeCompleted: + response = [TGBridgeResponse completeForSubscription:subscription]; + break; + + default: + break; + } + + os_unfair_lock_lock(&_replyHandlerMapLock); + void (^reply)(NSData *) = _replyHandlerMap[@(subscription.identifier)]; + if (reply != nil) + [_replyHandlerMap removeObjectForKey:@(subscription.identifier)]; + os_unfair_lock_unlock(&_replyHandlerMapLock); + + if (_processingNotification) + { + [self _enqueueResponse:response forSubscription:subscription]; + + if (completion != nil) + completion(); + + return; + } + + NSData *messageData = [NSKeyedArchiver archivedDataWithRootObject:response]; + if (reply != nil && messageData.length < 64000) + { + reply(messageData); + + if (completion != nil) + completion(); + } + else + { + if (reply != nil) + reply([NSData data]); + + if (self.session.isReachable) + { + [self.session sendMessageData:messageData replyHandler:nil errorHandler:^(NSError *error) + { + //if (error != nil) + // TGLog(@"[BridgeServer]: send response for subscription %lld failed with error %@", subscription.identifier, error); + }]; + } + else + { + //TGLog(@"[BridgeServer]: client out of reach, queueing response for subscription %lld", subscription.identifier); + [self _enqueueResponse:response forSubscription:subscription]; + } + + if (completion != nil) + completion(); + } +} + +- (void)_enqueueResponse:(TGBridgeResponse *)response forSubscription:(TGBridgeSubscription *)subscription +{ + os_unfair_lock_lock(&_outgoingQueueLock); + NSMutableArray *updatedResponses = (_outgoingMessageQueue != nil) ? [_outgoingMessageQueue mutableCopy] : [[NSMutableArray alloc] init]; + + if (subscription.dropPreviouslyQueued) + { + NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init]; + + [updatedResponses enumerateObjectsUsingBlock:^(TGBridgeResponse *queuedResponse, NSUInteger index, __unused BOOL *stop) + { + if (queuedResponse.subscriptionIdentifier == subscription.identifier) + [indexSet addIndex:index]; + }]; + + [updatedResponses removeObjectsAtIndexes:indexSet]; + } + + [updatedResponses addObject:response]; + + _outgoingMessageQueue = updatedResponses; + os_unfair_lock_unlock(&_outgoingQueueLock); +} + +- (void)_sendQueuedResponses +{ + if (_processingNotification) + return; + + os_unfair_lock_lock(&_outgoingQueueLock); + + if (_outgoingMessageQueue.count > 0) + { + //TGLog(@"[BridgeServer] Sending queued responses"); + + for (TGBridgeResponse *response in _outgoingMessageQueue) + { + NSData *messageData = [NSKeyedArchiver archivedDataWithRootObject:response]; + [self.session sendMessageData:messageData replyHandler:nil errorHandler:nil]; + } + + [_outgoingMessageQueue removeAllObjects]; + } + os_unfair_lock_unlock(&_outgoingQueueLock); +} + +- (void)_requestSubscriptionList +{ + TGBridgeSubscriptionListRequest *request = [[TGBridgeSubscriptionListRequest alloc] initWithSessionId:_sessionId]; + NSData *messageData = [NSKeyedArchiver archivedDataWithRootObject:request]; + [self.session sendMessageData:messageData replyHandler:nil errorHandler:nil]; +} + +- (void)sendFileWithURL:(NSURL *)url metadata:(NSDictionary *)metadata asMessageData:(bool)asMessageData +{ + //TGLog(@"[BridgeServer] Sent file with metadata %@", metadata); + if (asMessageData && self.session.isReachable) { + NSData *data = [NSData dataWithContentsOfURL:url]; + [self sendFileWithData:data metadata:metadata errorHandler:^{ + [self.session transferFile:url metadata:metadata]; + }]; + } else { + [self.session transferFile:url metadata:metadata]; + } +} + +- (void)sendFileWithData:(NSData *)data metadata:(NSDictionary *)metadata errorHandler:(void (^)(void))errorHandler +{ + TGBridgeFile *file = [[TGBridgeFile alloc] initWithData:data metadata:metadata]; + NSData *messageData = [NSKeyedArchiver archivedDataWithRootObject:file]; + [self.session sendMessageData:messageData replyHandler:nil errorHandler:^(NSError *error) { + if (errorHandler != nil) + errorHandler(); + }]; +} + +#pragma mark - Tasks + +- (id)beginTask +{ + int64_t randomId = 0; + arc4random_buf(&randomId, 8); + NSNumber *taskId = @(randomId); + + _runningTasks[taskId] = @true; + [_hasRunningTasks set:[SSignal single:@{@"version": @(_tasksVersion++), @"running": @true}]]; + + SBlockDisposable *taskDisposable = [[SBlockDisposable alloc] initWithBlock:^{ + [_runningTasks removeObjectForKey:taskId]; + [_hasRunningTasks set:[SSignal single:@{@"version": @(_tasksVersion++), @"running": @(_runningTasks.count > 0)}]]; + }]; + + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((4.0) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [self dispatch:^{ + [taskDisposable dispose]; + }]; + }); + + return taskDisposable; +} + +#pragma mark - Session Delegate + +- (void)handleReceivedData:(NSData *)messageData replyHandler:(void (^)(NSData *))replyHandler +{ + if (messageData.length == 0) + { + if (replyHandler != nil) + replyHandler([NSData data]); + return; + } + +// __block UIBackgroundTaskIdentifier backgroundTask; +// backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^ +// { +// if (replyHandler != nil) +// replyHandler([NSData data]); +// [[UIApplication sharedApplication] endBackgroundTask:backgroundTask]; +// }]; +// + + [self handleMessageData:messageData task:[self beginTask] replyHandler:replyHandler completion:^{}]; +} + +- (void)session:(WCSession *)__unused session didReceiveMessageData:(NSData *)messageData +{ + [self dispatch:^{ + [self handleReceivedData:messageData replyHandler:nil]; + }]; +} + +- (void)session:(WCSession *)__unused session didReceiveMessageData:(NSData *)messageData replyHandler:(void (^)(NSData *))replyHandler +{ + [self dispatch:^{ + [self handleReceivedData:messageData replyHandler:replyHandler]; + }]; +} + +- (void)session:(WCSession *)__unused session didReceiveFile:(WCSessionFile *)file +{ + NSDictionary *metadata = file.metadata; + if (metadata == nil || ![metadata[TGBridgeIncomingFileTypeKey] isEqualToString:TGBridgeIncomingFileTypeAudio]) + return; + + NSError *error; + NSURL *tempURL = [NSURL URLWithString:file.fileURL.lastPathComponent relativeToURL:self.temporaryFilesURL]; + [[NSFileManager defaultManager] createDirectoryAtPath:self.temporaryFilesURL.path withIntermediateDirectories:true attributes:nil error:&error]; + [[NSFileManager defaultManager] moveItemAtURL:file.fileURL toURL:tempURL error:&error]; + + [self dispatch:^{ + _fileHandler(tempURL.path, file.metadata); + }]; +} + +- (void)session:(WCSession *)__unused session didFinishFileTransfer:(WCSessionFileTransfer *)__unused fileTransfer error:(NSError *)__unused error +{ + +} + +- (void)session:(nonnull WCSession *)session activationDidCompleteWithState:(WCSessionActivationState)activationState error:(nullable NSError *)error { + +} + + +- (void)sessionDidBecomeInactive:(nonnull WCSession *)session { + +} + + +- (void)sessionDidDeactivate:(nonnull WCSession *)session { + +} + +- (void)sessionWatchStateDidChange:(WCSession *)session +{ + [self dispatch:^{ + if (session.isWatchAppInstalled) + [self pushContext]; + + _appInstalled.sink(@(session.isWatchAppInstalled)); + }]; +} + +- (void)sessionReachabilityDidChange:(WCSession *)session +{ + NSLog(@"[TGBridgeServer] Reachability changed: %d", session.isReachable); +} + +#pragma mark - + +- (NSInteger)wakeupNetwork +{ + return 0; +} + +- (void)suspendNetworkIfReady:(NSInteger)token +{ +} + +#pragma mark - + +- (WCSession *)session +{ + return [WCSession defaultSession]; +} + +@end + + +@interface TGBridgeSignalManager() +{ + os_unfair_lock _lock; + NSMutableDictionary *_disposables; +} +@end + +@implementation TGBridgeSignalManager + +- (instancetype)init +{ + self = [super init]; + if (self != nil) + { + _disposables = [[NSMutableDictionary alloc] init]; + } + return self; +} + +- (void)dealloc +{ + NSArray *disposables = nil; + os_unfair_lock_lock(&_lock); + disposables = [_disposables allValues]; + os_unfair_lock_unlock(&_lock); + + for (id disposable in disposables) + { + [disposable dispose]; + } +} + +- (bool)startSignalForKey:(NSString *)key producer:(SSignal *(^)())producer +{ + if (key == nil) + return false; + + bool produce = false; + os_unfair_lock_lock(&_lock); + if (_disposables[key] == nil) + { + _disposables[key] = [[SMetaDisposable alloc] init]; + produce = true; + } + os_unfair_lock_unlock(&_lock); + + if (produce) + { + __weak TGBridgeSignalManager *weakSelf = self; + id disposable = [producer() startWithNext:nil error:^(__unused id error) + { + __strong TGBridgeSignalManager *strongSelf = weakSelf; + if (strongSelf != nil) + { + os_unfair_lock_lock(&strongSelf->_lock); + [strongSelf->_disposables removeObjectForKey:key]; + os_unfair_lock_unlock(&strongSelf->_lock); + } + } completed:^ + { + __strong TGBridgeSignalManager *strongSelf = weakSelf; + if (strongSelf != nil) + { + os_unfair_lock_lock(&strongSelf->_lock); + [strongSelf->_disposables removeObjectForKey:key]; + os_unfair_lock_unlock(&strongSelf->_lock); + } + }]; + + os_unfair_lock_lock(&_lock); + [(SMetaDisposable *)_disposables[key] setDisposable:disposable]; + os_unfair_lock_unlock(&_lock); + } + + return produce; +} + +- (void)haltSignalForKey:(NSString *)key +{ + if (key == nil) + return; + + os_unfair_lock_lock(&_lock); + if (_disposables[key] != nil) + { + [_disposables[key] dispose]; + [_disposables removeObjectForKey:key]; + } + os_unfair_lock_unlock(&_lock); +} + +- (void)haltAllSignals +{ + os_unfair_lock_lock(&_lock); + for (NSObject *disposable in _disposables.allValues) + [disposable dispose]; + [_disposables removeAllObjects]; + os_unfair_lock_unlock(&_lock); +} + +@end diff --git a/submodules/WatchBridge/Sources/WatchBridge.swift b/submodules/WatchBridge/Sources/WatchBridge.swift new file mode 100644 index 00000000..e7098263 --- /dev/null +++ b/submodules/WatchBridge/Sources/WatchBridge.swift @@ -0,0 +1,553 @@ +import Foundation +import Postbox +import TelegramCore +import WatchCommon +import TelegramPresentationData +import LegacyUI +import PhoneNumberFormat + +private func legacyImageLocationUri(resource: MediaResource) -> String? { + if let resource = resource as? CloudPeerPhotoSizeMediaResource { + return resource.id.stringRepresentation + } + return nil +} + +func makePeerIdFromBridgeIdentifier(_ identifier: Int64) -> PeerId? { + if identifier < 0 && identifier > Int32.min { + return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(-identifier)) + } else if identifier < Int64(Int32.min) * 2 && identifier > Int64(Int32.min) * 3 { + return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(Int64(Int32.min) &* 2 &- identifier)) + // MARK: Swiftgram + // supports 52 bits + } else if identifier > 0 && identifier < (1 << 52) { + return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(identifier)) + } else { + return nil + } +} + +func makeBridgeIdentifier(_ peerId: PeerId) -> Int64 { + switch peerId.namespace { + case Namespaces.Peer.CloudGroup: + return -Int64(peerId.id._internalGetInt64Value()) + case Namespaces.Peer.CloudChannel: + return Int64(Int32.min) * 2 - Int64(peerId.id._internalGetInt64Value()) + default: + return Int64(peerId.id._internalGetInt64Value()) + } +} + +func makeBridgeDeliveryState(_ message: Message?) -> TGBridgeMessageDeliveryState { + if let message = message { + if message.flags.contains(.Failed) { + return .failed + } + else if message.flags.contains(.Sending) { + return .pending + } + } + return .delivered +} + +private func makeBridgeImage(_ image: TelegramMediaImage?) -> TGBridgeImageMediaAttachment? { + if let image = image, let representation = largestImageRepresentation(image.representations) { + let bridgeImage = TGBridgeImageMediaAttachment() + bridgeImage.imageId = image.imageId.id + bridgeImage.dimensions = representation.dimensions.cgSize + return bridgeImage + } else { + return nil + } +} + +func makeBridgeDocument(_ file: TelegramMediaFile?) -> TGBridgeDocumentMediaAttachment? { + if let file = file { + let bridgeDocument = TGBridgeDocumentMediaAttachment() + bridgeDocument.documentId = file.fileId.id + bridgeDocument.fileSize = Int32(file.size ?? 0) + for attribute in file.attributes { + switch attribute { + case let .FileName(fileName): + bridgeDocument.fileName = fileName + case .Animated: + bridgeDocument.isAnimated = true + case let .ImageSize(size): + bridgeDocument.imageSize = NSValue(cgSize: size.cgSize) + case let .Sticker(displayText, packReference, _): + bridgeDocument.isSticker = true + bridgeDocument.stickerAlt = displayText + if let packReference = packReference, case let .id(id, accessHash) = packReference { + bridgeDocument.stickerPackId = id + bridgeDocument.stickerPackAccessHash = accessHash + } + case let .Audio(_, duration, title, performer, _): + bridgeDocument.duration = Int32(clamping: duration) + bridgeDocument.title = title + bridgeDocument.performer = performer + default: + break + } + } + return bridgeDocument + } + return nil +} + +func makeBridgeMedia(message: Message, strings: PresentationStrings, chatPeer: Peer? = nil, filterUnsupportedActions: Bool = true) -> [TGBridgeMediaAttachment] { + var bridgeMedia: [TGBridgeMediaAttachment] = [] + + if let forward = message.forwardInfo { + let bridgeForward = TGBridgeForwardedMessageMediaAttachment() + bridgeForward.peerId = forward.author.flatMap({ makeBridgeIdentifier($0.id) }) ?? 0 + if let sourceMessageId = forward.sourceMessageId { + bridgeForward.mid = sourceMessageId.id + } + bridgeForward.date = forward.date + bridgeMedia.append(bridgeForward) + } + + for attribute in message.attributes { + if let reply = attribute as? ReplyMessageAttribute, let replyMessage = message.associatedMessages[reply.messageId] { + let bridgeReply = TGBridgeReplyMessageMediaAttachment() + bridgeReply.mid = reply.messageId.id + bridgeReply.message = makeBridgeMessage(replyMessage, strings: strings) + bridgeMedia.append(bridgeReply) + } else if let entities = attribute as? TextEntitiesMessageAttribute { + var bridgeEntities: [Any] = [] + for entity in entities.entities { + var bridgeEntity: TGBridgeMessageEntity? = nil + switch entity.type { + case .Url: + bridgeEntity = TGBridgeMessageEntityUrl() + bridgeEntity?.range = NSRange(entity.range) + case .TextUrl: + bridgeEntity = TGBridgeMessageEntityTextUrl() + bridgeEntity?.range = NSRange(entity.range) + case .Email: + bridgeEntity = TGBridgeMessageEntityEmail() + bridgeEntity?.range = NSRange(entity.range) + case .Mention: + bridgeEntity = TGBridgeMessageEntityMention() + bridgeEntity?.range = NSRange(entity.range) + case .Hashtag: + bridgeEntity = TGBridgeMessageEntityHashtag() + bridgeEntity?.range = NSRange(entity.range) + case .BotCommand: + bridgeEntity = TGBridgeMessageEntityBotCommand() + bridgeEntity?.range = NSRange(entity.range) + case .Bold: + bridgeEntity = TGBridgeMessageEntityBold() + bridgeEntity?.range = NSRange(entity.range) + case .Italic: + bridgeEntity = TGBridgeMessageEntityItalic() + bridgeEntity?.range = NSRange(entity.range) + case .Code: + bridgeEntity = TGBridgeMessageEntityCode() + bridgeEntity?.range = NSRange(entity.range) + case .Pre: + bridgeEntity = TGBridgeMessageEntityPre() + bridgeEntity?.range = NSRange(entity.range) + default: + break + } + if let bridgeEntity = bridgeEntity { + bridgeEntities.append(bridgeEntity) + } + } + if !bridgeEntities.isEmpty { + let attachment = TGBridgeMessageEntitiesAttachment() + attachment.entities = bridgeEntities + bridgeMedia.append(attachment) + } + } + } + + for m in message.media { + if let image = m as? TelegramMediaImage, let bridgeImage = makeBridgeImage(image) { + bridgeMedia.append(bridgeImage) + } + else if let file = m as? TelegramMediaFile { + if file.isVideo { + let bridgeVideo = TGBridgeVideoMediaAttachment() + bridgeVideo.videoId = file.fileId.id + + for attribute in file.attributes { + switch attribute { + case let .Video(duration, size, flags, _, _, _): + bridgeVideo.duration = Int32(duration) + bridgeVideo.dimensions = size.cgSize + bridgeVideo.round = flags.contains(.instantRoundVideo) + default: + break + } + } + + bridgeMedia.append(bridgeVideo) + } else if file.isVoice { + let bridgeAudio = TGBridgeAudioMediaAttachment() + bridgeAudio.audioId = file.fileId.id + bridgeAudio.fileSize = Int32(clamping: file.size ?? 0) + + for attribute in file.attributes { + switch attribute { + case let .Audio(_, duration, _, _, _): + bridgeAudio.duration = Int32(clamping: duration) + default: + break + } + } + + bridgeMedia.append(bridgeAudio) + } else if let bridgeDocument = makeBridgeDocument(file) { + bridgeMedia.append(bridgeDocument) + } + } else if let action = m as? TelegramMediaAction { + var bridgeAction: TGBridgeActionMediaAttachment? = nil + var consumed = false + switch action.action { + case let .groupCreated(title): + bridgeAction = TGBridgeActionMediaAttachment() + if chatPeer is TelegramGroup { + bridgeAction?.actionType = .createChat + bridgeAction?.actionData = ["title": title] + } else if let channel = chatPeer as? TelegramChannel { + if case .group = channel.info { + bridgeAction?.actionType = .createChat + bridgeAction?.actionData = ["title": title] + } else { + bridgeAction?.actionType = .channelCreated + } + } + case let .phoneCall(_, discardReason, _, _): + let bridgeAttachment = TGBridgeUnsupportedMediaAttachment() + let incoming = message.flags.contains(.Incoming) + var compactTitle: String = "" + var subTitle: String = "" + if let discardReason = discardReason { + switch discardReason { + case .busy, .disconnect: + compactTitle = strings.Notification_CallCanceled + subTitle = strings.Notification_CallCanceledShort + case .missed: + compactTitle = incoming ? strings.Notification_CallMissed : strings.Notification_CallCanceled + subTitle = incoming ? strings.Notification_CallMissedShort : strings.Notification_CallCanceledShort + case .hangup: + break + } + } + if compactTitle.isEmpty { + compactTitle = incoming ? strings.Notification_CallIncoming : strings.Notification_CallOutgoing + subTitle = incoming ? strings.Notification_CallIncomingShort : strings.Notification_CallOutgoingShort + } + bridgeAttachment.compactTitle = compactTitle + bridgeAttachment.title = strings.Watch_Message_Call + bridgeAttachment.subtitle = subTitle + bridgeMedia.append(bridgeAttachment) + consumed = true + default: + break + } + if let bridgeAction = bridgeAction { + bridgeMedia.append(bridgeAction) + } else if !consumed && !filterUnsupportedActions { + let bridgeAttachment = TGBridgeUnsupportedMediaAttachment() + bridgeAttachment.compactTitle = "" + bridgeAttachment.title = "" + bridgeMedia.append(bridgeAttachment) + } + } else if let poll = m as? TelegramMediaPoll { + let bridgeAttachment = TGBridgeUnsupportedMediaAttachment() + bridgeAttachment.compactTitle = strings.Watch_Message_Poll + bridgeAttachment.title = strings.Watch_Message_Poll + bridgeAttachment.subtitle = poll.text + bridgeMedia.append(bridgeAttachment) + } else if let contact = m as? TelegramMediaContact { + let bridgeContact = TGBridgeContactMediaAttachment() + if let peerId = contact.peerId { + bridgeContact.uid = Int32(clamping: makeBridgeIdentifier(peerId)) + } + bridgeContact.firstName = contact.firstName + bridgeContact.lastName = contact.lastName + bridgeContact.phoneNumber = contact.phoneNumber + bridgeContact.prettyPhoneNumber = formatPhoneNumber(contact.phoneNumber) + bridgeMedia.append(bridgeContact) + } else if let map = m as? TelegramMediaMap { + let bridgeLocation = TGBridgeLocationMediaAttachment() + bridgeLocation.latitude = map.latitude + bridgeLocation.longitude = map.longitude + if let venue = map.venue { + let bridgeVenue = TGBridgeVenueAttachment() + bridgeVenue.title = venue.title + bridgeVenue.address = venue.address + bridgeVenue.provider = venue.provider + bridgeVenue.venueId = venue.id + bridgeLocation.venue = bridgeVenue + } + bridgeMedia.append(bridgeLocation) + } else if let webpage = m as? TelegramMediaWebpage { + if case let .Loaded(content) = webpage.content { + let bridgeWebpage = TGBridgeWebPageMediaAttachment() + bridgeWebpage.webPageId = webpage.id?.id ?? 0 + bridgeWebpage.url = content.url + bridgeWebpage.displayUrl = content.displayUrl + bridgeWebpage.pageType = content.type + bridgeWebpage.siteName = content.websiteName + bridgeWebpage.title = content.title + bridgeWebpage.pageDescription = content.text + bridgeWebpage.photo = makeBridgeImage(content.image) + bridgeWebpage.embedUrl = content.embedUrl + bridgeWebpage.embedType = content.embedType + bridgeWebpage.embedSize = content.embedSize?.cgSize ?? CGSize() + bridgeWebpage.duration = NSNumber(integerLiteral: content.duration ?? 0) + bridgeWebpage.author = content.author + bridgeMedia.append(bridgeWebpage) + } + } else if let game = m as? TelegramMediaGame { + let bridgeAttachment = TGBridgeUnsupportedMediaAttachment() + bridgeAttachment.compactTitle = game.title + bridgeAttachment.title = strings.Watch_Message_Game + bridgeAttachment.subtitle = game.title + bridgeMedia.append(bridgeAttachment) + } else if let invoice = m as? TelegramMediaInvoice { + let bridgeAttachment = TGBridgeUnsupportedMediaAttachment() + bridgeAttachment.compactTitle = invoice.title + bridgeAttachment.title = strings.Watch_Message_Invoice + bridgeAttachment.subtitle = invoice.title + bridgeMedia.append(bridgeAttachment) + } else if let _ = m as? TelegramMediaUnsupported { + let bridgeAttachment = TGBridgeUnsupportedMediaAttachment() + bridgeAttachment.compactTitle = strings.Watch_Message_Unsupported + bridgeAttachment.title = strings.Watch_Message_Unsupported + bridgeAttachment.subtitle = "" + bridgeMedia.append(bridgeAttachment) + } + } + return bridgeMedia +} + +func makeBridgeChat(_ entry: ChatListEntry, strings: PresentationStrings) -> (TGBridgeChat, [Int64 : TGBridgeUser])? { + if case let .MessageEntry(entryData) = entry { + let index = entryData.index + let messages = entryData.messages + let readState = entryData.readState + let renderedPeer = entryData.renderedPeer + let hasFailed = entryData.hasFailed + + guard index.messageIndex.id.peerId.namespace != Namespaces.Peer.SecretChat else { + return nil + } + let message = messages.last + let (bridgeChat, participants) = makeBridgeChat(renderedPeer.peer) + bridgeChat.date = TimeInterval(index.messageIndex.timestamp) + if let message = message { + if let author = message.author { + bridgeChat.fromUid = Int32(clamping: makeBridgeIdentifier(author.id)) + } + bridgeChat.text = message.text + bridgeChat.outgoing = !message.flags.contains(.Incoming) + bridgeChat.deliveryState = makeBridgeDeliveryState(message) + bridgeChat.deliveryError = hasFailed + bridgeChat.media = makeBridgeMedia(message: message, strings: strings, filterUnsupportedActions: false) + } + bridgeChat.unread = readState?.state.isUnread ?? false + bridgeChat.unreadCount = readState?.state.count ?? 0 + + var bridgeUsers: [Int64 : TGBridgeUser] = participants + if let bridgeUser = makeBridgeUser(message?.author, presence: nil) { + bridgeUsers[bridgeUser.identifier] = bridgeUser + } + if let user = renderedPeer.peer as? TelegramUser, user.id != message?.author?.id, let bridgeUser = makeBridgeUser(user, presence: nil) { + bridgeUsers[bridgeUser.identifier] = bridgeUser + } + + return (bridgeChat, bridgeUsers) + } + return nil +} + +func makeBridgeChat(_ peer: Peer?, view: PeerView? = nil) -> (TGBridgeChat, [Int64 : TGBridgeUser]) { + let bridgeChat = TGBridgeChat() + var bridgeUsers: [Int64 : TGBridgeUser] = [:] + if let peer = peer { + bridgeChat.identifier = makeBridgeIdentifier(peer.id) + bridgeChat.userName = peer.addressName + } + if let group = peer as? TelegramGroup { + bridgeChat.isGroup = true + bridgeChat.groupTitle = group.title + bridgeChat.participantsCount = Int32(clamping: group.participantCount) + + if let representation = smallestImageRepresentation(group.photo) { + bridgeChat.groupPhotoSmall = legacyImageLocationUri(resource: representation.resource) + } + if let representation = largestImageRepresentation(group.photo) { + bridgeChat.groupPhotoBig = legacyImageLocationUri(resource: representation.resource) + } + if let view = view, let cachedData = view.cachedData as? CachedGroupData, let participants = cachedData.participants { + bridgeChat.participantsCount = Int32(clamping: participants.participants.count) + var bridgeParticipants: [Int64] = [] + for participant in participants.participants { + if let user = view.peers[participant.peerId], let bridgeUser = makeBridgeUser(user, presence: view.peerPresences[user.id]) { + bridgeParticipants.append(bridgeUser.identifier) + bridgeUsers[bridgeUser.identifier] = bridgeUser + } + } + bridgeChat.participants = bridgeParticipants + } + } else if let channel = peer as? TelegramChannel { + bridgeChat.isChannel = true + bridgeChat.groupTitle = channel.title + if case .group = channel.info { + bridgeChat.isChannelGroup = true + } + bridgeChat.verified = channel.flags.contains(.isVerified) + + if let representation = smallestImageRepresentation(channel.photo) { + bridgeChat.groupPhotoSmall = legacyImageLocationUri(resource: representation.resource) + } + if let representation = largestImageRepresentation(channel.photo) { + bridgeChat.groupPhotoBig = legacyImageLocationUri(resource: representation.resource) + } + if let view = view, let cachedData = view.cachedData as? CachedChannelData { + bridgeChat.about = cachedData.about + } + } + + // _hasLeftGroup = [aDecoder decodeBoolForKey:TGBridgeChatHasLeftGroupKey]; + // _isKickedFromGroup = [aDecoder decodeBoolForKey:TGBridgeChatIsKickedFromGroupKey]; + return (bridgeChat, bridgeUsers) +} + +func makeBridgeUser(_ peer: Peer?, presence: PeerPresence? = nil, cachedData: CachedPeerData? = nil) -> TGBridgeUser? { + if let user = peer as? TelegramUser { + let bridgeUser = TGBridgeUser() + bridgeUser.identifier = makeBridgeIdentifier(user.id) + bridgeUser.firstName = user.firstName + bridgeUser.lastName = user.lastName + bridgeUser.userName = user.addressName + bridgeUser.phoneNumber = user.phone + if let phone = user.phone { + bridgeUser.prettyPhoneNumber = formatPhoneNumber(phone) + } + if let presence = presence as? TelegramUserPresence { + let timestamp = 0 + switch presence.status { + case .recently: + bridgeUser.lastSeen = -2 + case .lastWeek: + bridgeUser.lastSeen = -3 + case .lastMonth: + bridgeUser.lastSeen = -4 + case .none: + bridgeUser.lastSeen = -5 + case let .present(statusTimestamp): + if statusTimestamp > timestamp { + bridgeUser.online = true + } + bridgeUser.lastSeen = TimeInterval(statusTimestamp) + } + } + if let cachedData = cachedData as? CachedUserData { + bridgeUser.about = cachedData.about + } + if let representation = smallestImageRepresentation(user.photo) { + bridgeUser.photoSmall = legacyImageLocationUri(resource: representation.resource) + } + if let representation = largestImageRepresentation(user.photo) { + bridgeUser.photoBig = legacyImageLocationUri(resource: representation.resource) + } + if user.botInfo != nil { + bridgeUser.kind = .bot + bridgeUser.botKind = .generic + } + bridgeUser.verified = user.flags.contains(.isVerified) + return bridgeUser + } else { + return nil + } +} + +func makeBridgePeers(_ message: Message) -> [Int64 : Any] { + var bridgeUsers: [Int64 : Any] = [:] + for (_, peer) in message.peers { + if peer is TelegramUser, let bridgeUser = makeBridgeUser(peer, presence: nil) { + bridgeUsers[bridgeUser.identifier] = bridgeUser + } else if peer is TelegramGroup || peer is TelegramChannel { + let bridgeChat = makeBridgeChat(peer) + bridgeUsers[bridgeChat.0.identifier] = bridgeChat.0 + } + } + if let author = message.author, let bridgeUser = makeBridgeUser(author) { + bridgeUsers[bridgeUser.identifier] = bridgeUser + } + return bridgeUsers +} + +func makeBridgeMessage(_ entry: MessageHistoryEntry, strings: PresentationStrings) -> (TGBridgeMessage, [Int64 : TGBridgeUser])? { + guard let bridgeMessage = makeBridgeMessage(entry.message, strings: strings) else { + return nil + } + if entry.message.id.namespace == Namespaces.Message.Local && !entry.message.flags.contains(.Failed) { + return nil + } + + bridgeMessage.unread = !entry.isRead + + var bridgeUsers: [Int64 : TGBridgeUser] = [:] + if let bridgeUser = makeBridgeUser(entry.message.author, presence: nil) { + bridgeUsers[bridgeUser.identifier] = bridgeUser + } + for (_, peer) in entry.message.peers { + if let bridgeUser = makeBridgeUser(peer, presence: nil) { + bridgeUsers[bridgeUser.identifier] = bridgeUser + } + } + + return (bridgeMessage, bridgeUsers) +} + +func makeBridgeMessage(_ message: Message, strings: PresentationStrings, chatPeer: Peer? = nil) -> TGBridgeMessage? { + var chatPeer = chatPeer + if chatPeer == nil { + chatPeer = message.peers[message.id.peerId] + } + + let bridgeMessage = TGBridgeMessage() + bridgeMessage.identifier = message.id.id + bridgeMessage.date = TimeInterval(message.timestamp) + bridgeMessage.randomId = message.globallyUniqueId ?? 0 +// bridgeMessage.unread = false + bridgeMessage.outgoing = !message.flags.contains(.Incoming) + if let author = message.author { + bridgeMessage.fromUid = makeBridgeIdentifier(author.id) + } + bridgeMessage.toUid = makeBridgeIdentifier(message.id.peerId) + bridgeMessage.cid = makeBridgeIdentifier(message.id.peerId) + bridgeMessage.text = message.text + bridgeMessage.deliveryState = makeBridgeDeliveryState(message) + bridgeMessage.media = makeBridgeMedia(message: message, strings: strings, chatPeer: chatPeer) + return bridgeMessage +} + +func makeVenue(from bridgeVenue: TGBridgeVenueAttachment?) -> MapVenue? { + if let bridgeVenue = bridgeVenue { + return MapVenue(title: bridgeVenue.title, address: bridgeVenue.address, provider: bridgeVenue.provider, id: bridgeVenue.venueId, type: "") + } + return nil +} + +func makeBridgeLocationVenue(_ contextResult: ChatContextResultMessage) -> TGBridgeLocationVenue? { + if case let .mapLocation(mapMedia, _) = contextResult { + let bridgeVenue = TGBridgeLocationVenue() + bridgeVenue.coordinate = CLLocationCoordinate2D(latitude: mapMedia.latitude, longitude: mapMedia.longitude) + if let venue = mapMedia.venue { + bridgeVenue.name = venue.title + bridgeVenue.address = venue.address + bridgeVenue.provider = venue.provider + bridgeVenue.identifier = venue.id + } + return bridgeVenue + } + return nil +} diff --git a/submodules/WatchBridge/Sources/WatchCommunicationManager.swift b/submodules/WatchBridge/Sources/WatchCommunicationManager.swift new file mode 100644 index 00000000..1c69d158 --- /dev/null +++ b/submodules/WatchBridge/Sources/WatchCommunicationManager.swift @@ -0,0 +1,219 @@ +import Foundation +import SwiftSignalKit +import Postbox +import TelegramCore +import WatchCommon +import SSignalKit +import TelegramUIPreferences +import AccountContext +import WatchBridgeImpl + +public final class WatchCommunicationManagerContext { + public let context: AccountContext + + public init(context: AccountContext) { + self.context = context + } +} + +public final class WatchManagerArguments { + public let appInstalled: Signal + public let navigateToMessageRequested: Signal + public let runningTasks: Signal + + public init(appInstalled: Signal, navigateToMessageRequested: Signal, runningTasks: Signal) { + self.appInstalled = appInstalled + self.navigateToMessageRequested = navigateToMessageRequested + self.runningTasks = runningTasks + } +} + +public final class WatchCommunicationManager { + private let queue: Queue + private let allowBackgroundTimeExtension: (Double) -> Void + + private var server: TGBridgeServer! + + private let contextDisposable = MetaDisposable() + private let presetsDisposable = MetaDisposable() + + let accountContext = Promise(nil) + private let presets = Promise(nil) + private let navigateToMessagePipe = ValuePipe() + + public init(queue: Queue, context: Signal, allowBackgroundTimeExtension: @escaping (Double) -> Void) { + self.queue = queue + self.allowBackgroundTimeExtension = allowBackgroundTimeExtension + + let handlers = allWatchRequestHandlers.reduce([String : AnyClass]()) { (map, handler) -> [String : AnyClass] in + var map = map + if let handler = handler as? WatchRequestHandler.Type { + for case let subscription as TGBridgeSubscription.Type in handler.handledSubscriptions { + if let name = subscription.subscriptionName() { + map[name] = handler + } + } + } + return map + } + + self.server = TGBridgeServer(handler: { [weak self] subscription -> SSignal? in + guard let strongSelf = self, let subscription = subscription, let handler = handlers[subscription.name] as? WatchRequestHandler.Type else { + return nil + } + return handler.handle(subscription: subscription, manager: strongSelf) + }, fileHandler: { [weak self] path, metadata in + guard let strongSelf = self, let path = path, let metadata = metadata as? [String : Any] else { + return + } + if metadata[TGBridgeIncomingFileTypeKey] as? String == TGBridgeIncomingFileTypeAudio { + let _ = WatchAudioHandler.handleFile(path: path, metadata: metadata, manager: strongSelf).start() + } + }, dispatchOnQueue: { [weak self] block in + if let strongSelf = self { + strongSelf.queue.justDispatch(block) + } + }, logFunction: { value in + if let value = value { + Logger.shared.log("WatchBridge", value) + } + }, allowBackgroundTimeExtension: { + allowBackgroundTimeExtension(4.0) + }) + self.server.startRunning() + + self.contextDisposable.set((combineLatest(self.watchAppInstalled, context |> deliverOn(self.queue))).start(next: { [weak self] appInstalled, appContext in + guard let strongSelf = self, appInstalled else { + return + } + if let context = appContext { + strongSelf.accountContext.set(.single(context.context)) + strongSelf.server.setAuthorized(true, userId: context.context.account.peerId.id._internalGetInt64Value()) + strongSelf.server.setMicAccessAllowed(false) + strongSelf.server.pushContext() + strongSelf.server.setMicAccessAllowed(true) + strongSelf.server.pushContext() + + strongSelf.presets.set(context.context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.watchPresetSettings]) + |> map({ sharedData -> WatchPresetSettings in + return sharedData.entries[ApplicationSpecificSharedDataKeys.watchPresetSettings]?.get(WatchPresetSettings.self) ?? WatchPresetSettings.defaultSettings + })) + } else { + strongSelf.accountContext.set(.single(nil)) + strongSelf.server.setAuthorized(false, userId: 0) + strongSelf.server.pushContext() + + strongSelf.presets.set(.single(nil)) + } + })) + + self.presetsDisposable.set((combineLatest(self.watchAppInstalled, self.presets.get() |> distinctUntilChanged |> deliverOn(self.queue), context |> deliverOn(self.queue))).start(next: { [weak self] appInstalled, presets, appContext in + guard let strongSelf = self, let presets = presets, let context = appContext, appInstalled, let tempPath = strongSelf.watchTemporaryStorePath else { + return + } + let presentationData = context.context.sharedContext.currentPresentationData.with { $0 } + let defaultSuggestions: [String : String] = [ + "OK": presentationData.strings.Watch_Suggestion_OK, + "Thanks": presentationData.strings.Watch_Suggestion_Thanks, + "WhatsUp": presentationData.strings.Watch_Suggestion_WhatsUp, + "TalkLater": presentationData.strings.Watch_Suggestion_TalkLater, + "CantTalk": presentationData.strings.Watch_Suggestion_CantTalk, + "HoldOn": presentationData.strings.Watch_Suggestion_HoldOn, + "BRB": presentationData.strings.Watch_Suggestion_BRB, + "OnMyWay": presentationData.strings.Watch_Suggestion_OnMyWay + ] + + var suggestions: [String : String] = [:] + for (key, defaultValue) in defaultSuggestions { + suggestions[key] = presets.customPresets[key] ?? defaultValue + } + + let fileManager = FileManager.default + let presetsFileUrl = URL(fileURLWithPath: tempPath + "/presets.dat") + + if fileManager.fileExists(atPath: presetsFileUrl.path) { + try? fileManager.removeItem(atPath: presetsFileUrl.path) + } + let data = try? NSKeyedArchiver.archivedData(withRootObject: suggestions, requiringSecureCoding: false) + try? data?.write(to: presetsFileUrl) + + let _ = strongSelf.sendFile(url: presetsFileUrl, metadata: [TGBridgeIncomingFileIdentifierKey: "presets"]).start() + })) + } + + deinit { + self.contextDisposable.dispose() + self.presetsDisposable.dispose() + } + + public var arguments: WatchManagerArguments { + return WatchManagerArguments(appInstalled: self.watchAppInstalled, navigateToMessageRequested: self.navigateToMessagePipe.signal(), runningTasks: self.runningTasks) + } + + public func requestNavigateToMessage(messageId: MessageId) { + self.navigateToMessagePipe.putNext(messageId) + } + + private var watchAppInstalled: Signal { + return Signal { subscriber in + let disposable = self.server.watchAppInstalledSignal().start(next: { value in + if let value = value as? NSNumber { + subscriber.putNext(value.boolValue) + } + }) + return ActionDisposable { + disposable?.dispose() + } + } |> deliverOn(self.queue) + } + + private var runningTasks: Signal { + return Signal { subscriber in + let disposable = self.server.runningRequestsSignal().start(next: { value in + if let value = value as? Dictionary { + if let running = value["running"] as? Bool, let version = value["version"] as? Int32 { + subscriber.putNext(WatchRunningTasks(running: running, version: version)) + } + } + }) + return ActionDisposable { + disposable?.dispose() + } + } |> deliverOn(self.queue) + } + + public var watchTemporaryStorePath: String? { + return self.server.temporaryFilesURL?.path + } + + public func sendFile(url: URL, metadata: Dictionary, asMessageData: Bool = false) -> Signal { + return Signal { subscriber in + self.server.sendFile(with: url, metadata: metadata, asMessageData: asMessageData) + subscriber.putCompletion() + return EmptyDisposable + } |> runOn(self.queue) + } + + public func sendFile(data: Data, metadata: Dictionary) -> Signal { + return Signal { subscriber in + self.server.sendFile(with: data, metadata: metadata, errorHandler: {}) + subscriber.putCompletion() + return EmptyDisposable + } |> runOn(self.queue) + } +} + +public func watchCommunicationManager(context: Signal, allowBackgroundTimeExtension: @escaping (Double) -> Void) -> Signal { + return Signal { subscriber in + let queue = Queue() + queue.async { + if #available(iOSApplicationExtension 9.0, *) { + subscriber.putNext(WatchCommunicationManager(queue: queue, context: context, allowBackgroundTimeExtension: allowBackgroundTimeExtension)) + } else { + subscriber.putNext(nil) + } + subscriber.putCompletion() + } + return EmptyDisposable + } +} diff --git a/submodules/WatchBridge/Sources/WatchRequestHandlers.swift b/submodules/WatchBridge/Sources/WatchRequestHandlers.swift new file mode 100644 index 00000000..315ebd6e --- /dev/null +++ b/submodules/WatchBridge/Sources/WatchRequestHandlers.swift @@ -0,0 +1,884 @@ +import Foundation +import SwiftSignalKit +import Postbox +import Display +import TelegramCore +import LegacyComponents +import WatchCommon +import TelegramPresentationData +import AvatarNode +import StickerResources +import PhotoResources +import AccountContext +import WatchBridgeAudio + +let allWatchRequestHandlers: [AnyClass] = [ + WatchChatListHandler.self, + WatchChatMessagesHandler.self, + WatchSendMessageHandler.self, + WatchPeerInfoHandler.self, + WatchMediaHandler.self, + WatchStickersHandler.self, + WatchAudioHandler.self, + WatchLocationHandler.self, + WatchPeerSettingsHandler.self, + WatchContinuationHandler.self, +] + +protocol WatchRequestHandler: AnyObject { + static var handledSubscriptions: [Any] { get } + static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal +} + +final class WatchChatListHandler: WatchRequestHandler { + static var handledSubscriptions: [Any] { + return [TGBridgeChatListSubscription.self] + } + + static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal { + if let args = subscription as? TGBridgeChatListSubscription { + let limit = Int(args.limit) + return SSignal { subscriber in + let signal = manager.accountContext.get() + |> take(1) + |> mapToSignal({ context -> Signal<(ChatListView, PresentationData), NoError> in + if let context = context { + return context.account.viewTracker.tailChatListView(groupId: .root, count: limit) + |> map { chatListView, _ -> (ChatListView, PresentationData) in + return (chatListView, context.sharedContext.currentPresentationData.with { $0 }) + } + } else { + return .complete() + } + }) + let disposable = signal.start(next: { chatListView, presentationData in + var chats: [TGBridgeChat] = [] + var users: [Int64 : TGBridgeUser] = [:] + for entry in chatListView.entries.reversed() { + if let (chat, chatUsers) = makeBridgeChat(entry, strings: presentationData.strings) { + chats.append(chat) + users = users.merging(chatUsers, uniquingKeysWith: { (_, last) in last }) + } + } + subscriber.putNext([ TGBridgeChatsArrayKey: chats, TGBridgeUsersDictionaryKey: users ] as [String: Any]) + }) + + return SBlockDisposable { + disposable.dispose() + } + } + } else { + return SSignal.fail(nil) + } + } +} + + +final class WatchChatMessagesHandler: WatchRequestHandler { + static var handledSubscriptions: [Any] { + return [ + TGBridgeChatMessageListSubscription.self, + TGBridgeChatMessageSubscription.self, + TGBridgeReadChatMessageListSubscription.self + ] + } + + static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal { + if let args = subscription as? TGBridgeChatMessageListSubscription, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) { + return SSignal { subscriber in + let limit = Int(args.rangeMessageCount) + let signal = manager.accountContext.get() + |> take(1) + |> mapToSignal({ context -> Signal<(MessageHistoryView, Bool, PresentationData), NoError> in + if let context = context { + return context.account.viewTracker.aroundMessageHistoryViewForLocation(.peer(peerId: peerId, threadId: nil), index: .upperBound, anchorIndex: .upperBound, count: limit, fixedCombinedReadStates: nil) + |> map { messageHistoryView, _, _ -> (MessageHistoryView, Bool, PresentationData) in + return (messageHistoryView, peerId == context.account.peerId, context.sharedContext.currentPresentationData.with { $0 }) + } + } else { + return .complete() + } + }) + let disposable = signal.start(next: { messageHistoryView, savedMessages, presentationData in + var messages: [TGBridgeMessage] = [] + var users: [Int64 : TGBridgeUser] = [:] + for entry in messageHistoryView.entries.reversed() { + if let (message, messageUsers) = makeBridgeMessage(entry, strings: presentationData.strings) { + messages.append(message) + users = users.merging(messageUsers, uniquingKeysWith: { (_, last) in last }) + } + } + subscriber.putNext([ TGBridgeMessagesArrayKey: messages, TGBridgeUsersDictionaryKey: users ] as [String: Any]) + }) + + return SBlockDisposable { + disposable.dispose() + } + } + } else if let args = subscription as? TGBridgeReadChatMessageListSubscription, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) { + return SSignal { subscriber in + let signal = manager.accountContext.get() + |> take(1) + |> mapToSignal({ context -> Signal in + if let context = context { + let messageId = MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: args.messageId) + return context.engine.messages.applyMaxReadIndexInteractively(index: MessageIndex(id: messageId, timestamp: 0)) + } else { + return .complete() + } + }) + let disposable = signal.start(next: { _ in + subscriber.putNext(true) + }, completed: { + subscriber.putCompletion() + }) + + return SBlockDisposable { + disposable.dispose() + } + } + } else if let args = subscription as? TGBridgeChatMessageSubscription, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) { + return SSignal { subscriber in + let signal = manager.accountContext.get() + |> take(1) + |> mapToSignal({ context -> Signal<(Message, PresentationData)?, NoError> in + if let context = context { + let messageSignal = context.engine.messages.downloadMessage(messageId: MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: args.messageId)) + |> map { message -> (Message, PresentationData)? in + if let message = message { + return (message, context.sharedContext.currentPresentationData.with { $0 }) + } else { + return nil + } + } + return messageSignal |> timeout(3.5, queue: Queue.concurrentDefaultQueue(), alternate: .single(nil)) + } else { + return .single(nil) + } + }) + let disposable = signal.start(next: { messageAndPresentationData in + if let (message, presentationData) = messageAndPresentationData, let bridgeMessage = makeBridgeMessage(message, strings: presentationData.strings) { + let peers = makeBridgePeers(message) + var response: [String : Any] = [TGBridgeMessageKey: bridgeMessage, TGBridgeUsersDictionaryKey: peers] + if peerId.namespace != Namespaces.Peer.CloudUser { + response[TGBridgeChatKey] = peers[makeBridgeIdentifier(peerId)] + } + subscriber.putNext(response) + } + subscriber.putCompletion() + }) + return SBlockDisposable { + disposable.dispose() + } + } + } + return SSignal.fail(nil) + } +} + +final class WatchSendMessageHandler: WatchRequestHandler { + static var handledSubscriptions: [Any] { + return [ + TGBridgeSendTextMessageSubscription.self, + TGBridgeSendLocationMessageSubscription.self, + TGBridgeSendStickerMessageSubscription.self, + TGBridgeSendForwardedMessageSubscription.self + ] + } + + static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal { + return SSignal { subscriber in + let signal = manager.accountContext.get() + |> take(1) + |> mapToSignal({ context -> Signal in + if let context = context { + var messageSignal: Signal<(EnqueueMessage?, PeerId?), NoError>? + if let args = subscription as? TGBridgeSendTextMessageSubscription { + let peerId = makePeerIdFromBridgeIdentifier(args.peerId) + var replyMessageId: MessageId? + if args.replyToMid != 0, let peerId = peerId { + replyMessageId = MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: args.replyToMid) + } + messageSignal = .single((.message(text: args.text, attributes: [], inlineStickers: [:], mediaReference: nil, threadId: nil, replyToMessageId: replyMessageId.flatMap { EngineMessageReplySubject(messageId: $0, quote: nil, todoItemId: nil) }, replyToStoryId: nil, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: []), peerId)) + } else if let args = subscription as? TGBridgeSendLocationMessageSubscription, let location = args.location { + let peerId = makePeerIdFromBridgeIdentifier(args.peerId) + let map = TelegramMediaMap(latitude: location.latitude, longitude: location.longitude, heading: nil, accuracyRadius: nil, venue: makeVenue(from: location.venue), liveBroadcastingTimeout: nil, liveProximityNotificationRadius: nil) + messageSignal = .single((.message(text: "", attributes: [], inlineStickers: [:], mediaReference: .standalone(media: map), threadId: nil, replyToMessageId: nil, replyToStoryId: nil, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: []), peerId)) + } else if let args = subscription as? TGBridgeSendStickerMessageSubscription { + let peerId = makePeerIdFromBridgeIdentifier(args.peerId) + messageSignal = mediaForSticker(documentId: args.document.documentId, account: context.account) + |> map({ media -> (EnqueueMessage?, PeerId?) in + if let media = media { + return (.message(text: "", attributes: [], inlineStickers: [:], mediaReference: .standalone(media: media), threadId: nil, replyToMessageId: nil, replyToStoryId: nil, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: []), peerId) + } else { + return (nil, nil) + } + }) + } else if let args = subscription as? TGBridgeSendForwardedMessageSubscription { + let peerId = makePeerIdFromBridgeIdentifier(args.targetPeerId) + if let forwardPeerId = makePeerIdFromBridgeIdentifier(args.peerId) { + messageSignal = .single((.forward(source: MessageId(peerId: forwardPeerId, namespace: Namespaces.Message.Cloud, id: args.messageId), threadId: nil, grouping: .none, attributes: [], correlationId: nil), peerId)) + } + } + + if let messageSignal = messageSignal { + return messageSignal |> mapToSignal({ message, peerId -> Signal in + if let message = message, let peerId = peerId { + return enqueueMessages(account: context.account, peerId: peerId, messages: [message]) |> mapToSignal({ _ in + return .single(true) + }) + } else { + return .complete() + } + }) + } + } + return .complete() + }) + + let disposable = signal.start(next: { _ in + subscriber.putNext(true) + }, completed: { + subscriber.putCompletion() + }) + + return SBlockDisposable { + disposable.dispose() + } + } + } +} + +final class WatchPeerInfoHandler: WatchRequestHandler { + static var handledSubscriptions: [Any] { + return [ + TGBridgeUserInfoSubscription.self, + TGBridgeUserBotInfoSubscription.self, + TGBridgeConversationSubscription.self + ] + } + + static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal { + if let args = subscription as? TGBridgeUserInfoSubscription { + return SSignal { subscriber in + let signal = manager.accountContext.get() + |> take(1) + |> mapToSignal({ context -> Signal in + if let context = context, let userId = args.userIds.first as? Int64, let peerId = makePeerIdFromBridgeIdentifier(userId) { + return context.account.viewTracker.peerView(peerId) + } else { + return .complete() + } + }) + let disposable = signal.start(next: { view in + if let user = makeBridgeUser(peerViewMainPeer(view), presence: view.peerPresences[view.peerId], cachedData: view.cachedData) { + subscriber.putNext([user.identifier: user]) + } else { + subscriber.putCompletion() + } + }) + + return SBlockDisposable { + disposable.dispose() + } + } + } else if let _ = subscription as? TGBridgeUserBotInfoSubscription { + return SSignal.complete() + } else if let args = subscription as? TGBridgeConversationSubscription { + return SSignal { subscriber in + let signal = manager.accountContext.get() |> take(1) |> mapToSignal({ context -> Signal in + if let context = context, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) { + return context.account.viewTracker.peerView(peerId) + } else { + return .complete() + } + }) + let disposable = signal.start(next: { view in + let (chat, users) = makeBridgeChat(peerViewMainPeer(view), view: view) + subscriber.putNext([ TGBridgeChatKey: chat, TGBridgeUsersDictionaryKey: users ] as [String: Any]) + }) + + return SBlockDisposable { + disposable.dispose() + } + } + } + return SSignal.fail(nil) + } +} + +private func mediaForSticker(documentId: Int64, account: Account) -> Signal { + return account.postbox.itemCollectionsView(orderedItemListCollectionIds: [Namespaces.OrderedItemList.CloudSavedStickers, Namespaces.OrderedItemList.CloudRecentStickers], namespaces: [Namespaces.ItemCollection.CloudStickerPacks], aroundIndex: nil, count: 50) + |> take(1) + |> map { view -> TelegramMediaFile? in + for view in view.orderedItemListsViews { + for entry in view.items { + if let file = entry.contents.get(SavedStickerItem.self)?.file { + if file.id.id == documentId { + return file._parse() + } + } else if let file = entry.contents.get(RecentMediaItem.self)?.media { + if file.id.id == documentId { + return file._parse() + } + } + } + } + return nil + } +} + +private let roundCorners = { () -> UIImage in + let diameter: CGFloat = 44.0 + UIGraphicsBeginImageContextWithOptions(CGSize(width: diameter, height: diameter), false, 0.0) + let context = UIGraphicsGetCurrentContext()! + context.setBlendMode(.copy) + context.setFillColor(UIColor.black.cgColor) + context.fill(CGRect(origin: CGPoint(), size: CGSize(width: diameter, height: diameter))) + context.setBlendMode(.clear) + context.setFillColor(UIColor.clear.cgColor) + context.fillEllipse(in: CGRect(origin: CGPoint(), size: CGSize(width: diameter, height: diameter))) + let image = UIGraphicsGetImageFromCurrentImageContext()!.stretchableImage(withLeftCapWidth: Int(diameter / 2.0), topCapHeight: Int(diameter / 2.0)) + UIGraphicsEndImageContext() + return image +}() + +private func sendData(manager: WatchCommunicationManager, data: Data, key: String, ext: String, type: String, forceAsData: Bool = false) { + if let tempPath = manager.watchTemporaryStorePath, !forceAsData { + let tempFileUrl = URL(fileURLWithPath: tempPath + "/\(key)\(ext)") + let _ = try? data.write(to: tempFileUrl) + let _ = manager.sendFile(url: tempFileUrl, metadata: [TGBridgeIncomingFileTypeKey: type, TGBridgeIncomingFileIdentifierKey: key]).start() + } else { + let _ = manager.sendFile(data: data, metadata: [TGBridgeIncomingFileTypeKey: type, TGBridgeIncomingFileIdentifierKey: key]).start() + } +} + +final class WatchMediaHandler: WatchRequestHandler { + static var handledSubscriptions: [Any] { + return [ + TGBridgeMediaThumbnailSubscription.self, + TGBridgeMediaAvatarSubscription.self, + TGBridgeMediaStickerSubscription.self + ] + } + + static private let disposable = DisposableSet() + + static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal { + if let args = subscription as? TGBridgeMediaAvatarSubscription, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) { + let key = "\(args.url!)_\(args.type.rawValue)" + let targetSize: CGSize + var compressionRate: CGFloat = 0.5 + var round = false + switch args.type { + case .small: + targetSize = CGSize(width: 19, height: 19); + compressionRate = 0.5 + case .profile: + targetSize = CGSize(width: 44, height: 44); + round = true + case .large: + targetSize = CGSize(width: 150, height: 150); + @unknown default: + fatalError() + } + + return SSignal { subscriber in + let signal = manager.accountContext.get() + |> take(1) + |> mapToSignal({ context -> Signal in + if let context = context { + return context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: peerId)) + |> mapToSignal { peer -> Signal in + if let peer = peer, case let .secretChat(secretChat) = peer { + return context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: secretChat.regularPeerId)) + } else { + return .single(peer) + } + } + |> mapToSignal({ peer -> Signal in + if let peer = peer, let representation = peer.smallProfileImage { + let imageData = peerAvatarImageData(account: context.account, peerReference: PeerReference(peer._asPeer()), authorOfMessage: nil, representation: representation, synchronousLoad: false) + if let imageData = imageData { + return imageData + |> map { data -> UIImage? in + if let (data, _) = data, let image = generateImage(targetSize, contextGenerator: { size, context -> Void in + if let imageSource = CGImageSourceCreateWithData(data as CFData, nil), let dataImage = CGImageSourceCreateImageAtIndex(imageSource, 0, nil) { + context.setBlendMode(.copy) + context.draw(dataImage, in: CGRect(origin: CGPoint(), size: targetSize)) + if round { + context.setBlendMode(.normal) + context.draw(roundCorners.cgImage!, in: CGRect(origin: CGPoint(), size: targetSize)) + } + } + }, scale: 2.0) { + return image + } + return nil + } + } + } + return .single(nil) + }) + } else { + return .complete() + } + }) + + let disposable = signal.start(next: { image in + if let image = image, let imageData = image.jpegData(compressionQuality: compressionRate) { + sendData(manager: manager, data: imageData, key: key, ext: ".jpg", type: TGBridgeIncomingFileTypeImage, forceAsData: true) + } + subscriber.putNext(key) + }, completed: { + subscriber.putCompletion() + }) + + return SBlockDisposable { + disposable.dispose() + } + } + } else if let args = subscription as? TGBridgeMediaStickerSubscription { + let key = "sticker_\(args.documentId)_\(Int(args.size.width))x\(Int(args.size.height))_\(args.notification ? 1 : 0)" + return SSignal { subscriber in + let signal = manager.accountContext.get() + |> take(1) + |> mapToSignal({ context -> Signal in + if let context = context { + var mediaSignal: Signal<(TelegramMediaFile, FileMediaReference)?, NoError>? = nil + if args.stickerPackId != 0 { + mediaSignal = mediaForSticker(documentId: args.documentId, account: context.account) + |> map { media -> (TelegramMediaFile, FileMediaReference)? in + if let media = media { + return (media, .standalone(media: media)) + } else { + return nil + } + } + } else if args.stickerPeerId != 0, let peerId = makePeerIdFromBridgeIdentifier(args.stickerPeerId) { + mediaSignal = context.engine.data.get(TelegramEngine.EngineData.Item.Messages.Message(id: MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: args.stickerMessageId))) + |> map { message -> (TelegramMediaFile, FileMediaReference)? in + if let message = message { + for media in message.media { + if let media = media as? TelegramMediaFile { + return (media, .message(message: MessageReference(message._asMessage()), media: media)) + } + } + } + return nil + } + } + var size: CGSize = args.size + if let mediaSignal = mediaSignal { + return mediaSignal + |> mapToSignal { mediaAndFileReference -> Signal<(TransformImageArguments) -> DrawingContext?, NoError> in + if let (media, fileReference) = mediaAndFileReference { + if let dimensions = media.dimensions { + size = dimensions.cgSize + } + self.disposable.add(freeMediaFileInteractiveFetched(account: context.account, userLocation: .other, fileReference: fileReference).start()) + return chatMessageSticker(account: context.account, userLocation: .other, file: media, small: false, fetched: true, onlyFullSize: true) + } + return .complete() + } + |> map{ f -> UIImage? in + let context = f(TransformImageArguments(corners: ImageCorners(), imageSize: size.fitted(args.size), boundingSize: args.size, intrinsicInsets: UIEdgeInsets(), emptyColor: args.notification ? UIColor(rgb: 0xe5e5ea) : .black, scale: 2.0)) + return context?.generateImage() + } + } + } + return .complete() + }) + + let disposable = signal.start(next: { image in + if let image = image, let imageData = image.jpegData(compressionQuality: 0.2) { + sendData(manager: manager, data: imageData, key: key, ext: ".jpg", type: TGBridgeIncomingFileTypeImage, forceAsData: args.notification) + } + subscriber.putNext(key) + }, completed: { + subscriber.putCompletion() + }) + + return SBlockDisposable { + disposable.dispose() + } + } + } else if let args = subscription as? TGBridgeMediaThumbnailSubscription { + let key = "\(args.peerId)_\(args.messageId)" + return SSignal { subscriber in + let signal = manager.accountContext.get() + |> take(1) + |> mapToSignal({ context -> Signal in + if let context = context, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) { + var roundVideo = false + return context.engine.data.get(TelegramEngine.EngineData.Item.Messages.Message(id: MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: args.messageId))) + |> mapToSignal { message -> Signal<(TransformImageArguments) -> DrawingContext?, NoError> in + if let message = message, !message._asMessage().containsSecretMedia { + var imageSignal: Signal<(TransformImageArguments) -> DrawingContext?, NoError>? + var updatedMediaReference: AnyMediaReference? + var candidateMediaReference: AnyMediaReference? + var imageDimensions: CGSize? + for media in message.media { + if let image = media as? TelegramMediaImage, let resource = largestImageRepresentation(image.representations)?.resource { + self.disposable.add(messageMediaImageInteractiveFetched(context: context, message: message._asMessage(), image: image, resource: resource, storeToDownloadsPeerId: nil).start()) + candidateMediaReference = .message(message: MessageReference(message._asMessage()), media: media) + break + } else if let _ = media as? TelegramMediaFile { + candidateMediaReference = .message(message: MessageReference(message._asMessage()), media: media) + break + } else if let webPage = media as? TelegramMediaWebpage, case let .Loaded(content) = webPage.content, let image = content.image, let resource = largestImageRepresentation(image.representations)?.resource { + self.disposable.add(messageMediaImageInteractiveFetched(context: context, message: message._asMessage(), image: image, resource: resource, storeToDownloadsPeerId: nil).start()) + candidateMediaReference = .webPage(webPage: WebpageReference(webPage), media: image) + break + } + } + if let imageReference = candidateMediaReference?.concrete(TelegramMediaImage.self) { + updatedMediaReference = imageReference.abstract + if let representation = largestRepresentationForPhoto(imageReference.media) { + imageDimensions = representation.dimensions.cgSize + } + } else if let fileReference = candidateMediaReference?.concrete(TelegramMediaFile.self) { + updatedMediaReference = fileReference.abstract + if let representation = largestImageRepresentation(fileReference.media.previewRepresentations), !fileReference.media.isSticker { + imageDimensions = representation.dimensions.cgSize + } + } + if let updatedMediaReference = updatedMediaReference, imageDimensions != nil { + if let imageReference = updatedMediaReference.concrete(TelegramMediaImage.self) { + imageSignal = chatMessagePhotoThumbnail(account: context.account, userLocation: .other, photoReference: imageReference, onlyFullSize: true) + } else if let fileReference = updatedMediaReference.concrete(TelegramMediaFile.self) { + if fileReference.media.isVideo { + imageSignal = chatMessageVideoThumbnail(account: context.account, userLocation: .other, fileReference: fileReference) + roundVideo = fileReference.media.isInstantVideo + } else if let iconImageRepresentation = smallestImageRepresentation(fileReference.media.previewRepresentations) { + imageSignal = chatWebpageSnippetFile(account: context.account, userLocation: .other, mediaReference: fileReference.abstract, representation: iconImageRepresentation) + } + } + } + if let signal = imageSignal { + return signal + } + } + return .complete() + } |> map{ f -> UIImage? in + var insets = UIEdgeInsets() + if roundVideo { + insets = UIEdgeInsets(top: -2, left: -2, bottom: -2, right: -2) + } + let context = f(TransformImageArguments(corners: ImageCorners(), imageSize: args.size, boundingSize: args.size, intrinsicInsets: insets, scale: 2.0)) + return context?.generateImage() + } + } else { + return .complete() + } + }) + + let disposable = signal.start(next: { image in + if let image = image, let imageData = image.jpegData(compressionQuality: 0.5) { + sendData(manager: manager, data: imageData, key: key, ext: ".jpg", type: TGBridgeIncomingFileTypeImage, forceAsData: args.notification) + } + subscriber.putNext(key) + }, completed: { + subscriber.putCompletion() + }) + + return SBlockDisposable { + disposable.dispose() + } + } + } + return SSignal.fail(nil) + } +} + +final class WatchStickersHandler: WatchRequestHandler { + static var handledSubscriptions: [Any] { + return [TGBridgeRecentStickersSubscription.self] + } + + static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal { + if let args = subscription as? TGBridgeRecentStickersSubscription { + return SSignal { subscriber in + let signal = manager.accountContext.get() + |> take(1) + |> mapToSignal({ context -> Signal in + if let context = context { + return context.account.postbox.itemCollectionsView(orderedItemListCollectionIds: [Namespaces.OrderedItemList.CloudSavedStickers, Namespaces.OrderedItemList.CloudRecentStickers], namespaces: [Namespaces.ItemCollection.CloudStickerPacks], aroundIndex: nil, count: 50) |> take(1) + } else { + return .complete() + } + }) + let disposable = signal.start(next: { view in + var stickers: [TGBridgeDocumentMediaAttachment] = [] + var added: Set = [] + outer: for view in view.orderedItemListsViews { + for entry in view.items { + if let file = entry.contents.get(SavedStickerItem.self)?.file { + if let sticker = makeBridgeDocument(file._parse()), !added.contains(sticker.documentId) { + stickers.append(sticker) + added.insert(sticker.documentId) + } + } else if let file = entry.contents.get(RecentMediaItem.self)?.media { + if let sticker = makeBridgeDocument(file._parse()), !added.contains(sticker.documentId) { + stickers.append(sticker) + added.insert(sticker.documentId) + } + } + if stickers.count == args.limit { + break outer + } + } + } + subscriber.putNext(stickers) + }) + + return SBlockDisposable { + disposable.dispose() + } + } + } + return SSignal.fail(nil) + } +} + +final class WatchAudioHandler: WatchRequestHandler { + static var handledSubscriptions: [Any] { + return [ + TGBridgeAudioSubscription.self, + TGBridgeAudioSentSubscription.self + ] + } + + static private let disposable = DisposableSet() + + static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal { + if let args = subscription as? TGBridgeAudioSubscription { + let key = "audio_\(args.peerId)_\(args.messageId)" + return SSignal { subscriber in + let signal = manager.accountContext.get() + |> take(1) + |> mapToSignal({ context -> Signal in + if let context = context, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) { + return context.engine.data.get(TelegramEngine.EngineData.Item.Messages.Message(id: MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: args.messageId))) + |> mapToSignal { message -> Signal in + if let message = message { + for media in message.media { + if let file = media as? TelegramMediaFile { + self.disposable.add(messageMediaFileInteractiveFetched(context: context, message: message._asMessage(), file: file, userInitiated: true).start()) + return context.account.postbox.mediaBox.resourceData(file.resource) + |> mapToSignal({ data -> Signal in + if let tempPath = manager.watchTemporaryStorePath, data.complete { + let outputPath = tempPath + "/\(key).m4a" + return legacyDecodeOpusAudio(path: data.path, outputPath: outputPath) + } else { + return .complete() + } + }) + } + } + } + return .complete() + } + } else { + return .complete() + } + }) + + let disposable = signal.start(next: { path in + let _ = manager.sendFile(url: URL(fileURLWithPath: path), metadata: [TGBridgeIncomingFileTypeKey: TGBridgeIncomingFileTypeAudio, TGBridgeIncomingFileIdentifierKey: key]).start() + subscriber.putNext(key) + }, completed: { + subscriber.putCompletion() + }) + + return SBlockDisposable { + disposable.dispose() + } + } + //let outputPath = manager.watchTemporaryStorePath + "/\(key).opus" + } else if let _ = subscription as? TGBridgeAudioSentSubscription { + + } + return SSignal.fail(nil) + } + + static func handleFile(path: String, metadata: Dictionary, manager: WatchCommunicationManager) -> Signal { + let randomId = metadata[TGBridgeIncomingFileRandomIdKey] as? Int64 + let peerId = metadata[TGBridgeIncomingFilePeerIdKey] as? Int64 + let replyToMid = metadata[TGBridgeIncomingFileReplyToMidKey] as? Int32 + + if let randomId = randomId, let id = peerId, let peerId = makePeerIdFromBridgeIdentifier(id) { + return combineLatest(manager.accountContext.get() |> take(1), legacyEncodeOpusAudio(path: path)) + |> map({ context, pathAndDuration -> Void in + let (path, duration) = pathAndDuration + if let context = context, let path = path, let data = try? Data(contentsOf: URL(fileURLWithPath: path)) { + let resource = LocalFileMediaResource(fileId: randomId) + context.account.postbox.mediaBox.storeResourceData(resource.id, data: data) + + var replyMessageId: MessageId? = nil + if let replyToMid = replyToMid, replyToMid != 0 { + replyMessageId = MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: replyToMid) + } + + let _ = enqueueMessages(account: context.account, peerId: peerId, messages: [.message(text: "", attributes: [], inlineStickers: [:], mediaReference: .standalone(media: TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: randomId), partialReference: nil, resource: resource, previewRepresentations: [], videoThumbnails: [], immediateThumbnailData: nil, mimeType: "audio/ogg", size: Int64(data.count), attributes: [.Audio(isVoice: true, duration: Int(duration), title: nil, performer: nil, waveform: nil)], alternativeRepresentations: [])), threadId: nil, replyToMessageId: replyMessageId.flatMap { EngineMessageReplySubject(messageId: $0, quote: nil, todoItemId: nil) }, replyToStoryId: nil, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: [])]).start() + } + }) + } else { + return .complete() + } + } +} + +final class WatchLocationHandler: WatchRequestHandler { + static var handledSubscriptions: [Any] { + return [TGBridgeNearbyVenuesSubscription.self] + } + + static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal { + if let args = subscription as? TGBridgeNearbyVenuesSubscription { + return SSignal { subscriber in + let signal = manager.accountContext.get() + |> take(1) + |> mapToSignal({ context -> Signal<[ChatContextResultMessage], NoError> in + if let context = context { + return context.engine.peers.resolvePeerByName(name: "foursquare", referrer: nil) + |> mapToSignal { result -> Signal in + guard case let .result(result) = result else { + return .complete() + } + return .single(result) + } + |> take(1) + |> mapToSignal { peer -> Signal in + guard let peer = peer?._asPeer() else { + return .single(nil) + } + return context.engine.messages.requestChatContextResults(botId: peer.id, peerId: context.account.peerId, query: "", location: .single((args.coordinate.latitude, args.coordinate.longitude)), offset: "") + |> map { results -> ChatContextResultCollection? in + return results?.results + } + |> `catch` { error -> Signal in + return .single(nil) + } + } + |> mapToSignal { contextResult -> Signal<[ChatContextResultMessage], NoError> in + guard let contextResult = contextResult else { + return .single([]) + } + return .single(contextResult.results.map { $0.message }) + } + } else { + return .complete() + } + }) + + let disposable = signal.start(next: { results in + var venues: [TGBridgeLocationVenue] = [] + for result in results { + if let venue = makeBridgeLocationVenue(result) { + venues.append(venue) + } + } + subscriber.putNext(venues) + }) + + return SBlockDisposable { + disposable.dispose() + } + } + } + return SSignal.fail(nil) + } +} + +final class WatchPeerSettingsHandler: WatchRequestHandler { + static var handledSubscriptions: [Any] { + return [ + TGBridgePeerSettingsSubscription.self, + TGBridgePeerUpdateNotificationSettingsSubscription.self, + TGBridgePeerUpdateBlockStatusSubscription.self + ] + } + + static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal { + if let args = subscription as? TGBridgePeerSettingsSubscription { + return SSignal { subscriber in + let signal = manager.accountContext.get() + |> take(1) + |> mapToSignal({ context -> Signal in + if let context = context, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) { + return context.account.viewTracker.peerView(peerId) + } else { + return .complete() + } + }) + let disposable = signal.start(next: { view in + var muted = false + var blocked = false + + if let notificationSettings = view.notificationSettings as? TelegramPeerNotificationSettings, case let .muted(until) = notificationSettings.muteState, until >= Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970) { + muted = true + } + if let cachedData = view.cachedData as? CachedUserData { + blocked = cachedData.isBlocked + } + + subscriber.putNext([ "muted": muted, "blocked": blocked ]) + }) + + return SBlockDisposable { + disposable.dispose() + } + } + } else { + return SSignal { subscriber in + let signal = manager.accountContext.get() + |> take(1) + |> mapToSignal({ context -> Signal in + if let context = context { + var signal: Signal? + + if let args = subscription as? TGBridgePeerUpdateNotificationSettingsSubscription, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) { + signal = context.engine.peers.togglePeerMuted(peerId: peerId, threadId: nil) + } else if let args = subscription as? TGBridgePeerUpdateBlockStatusSubscription, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) { + signal = context.engine.privacy.requestUpdatePeerIsBlocked(peerId: peerId, isBlocked: args.blocked) + } + + if let signal = signal { + return signal |> mapToSignal({ _ in + return .single(true) + }) + } else { + return .complete() + } + } else { + return .complete() + } + }) + + let disposable = signal.start(next: { _ in + subscriber.putNext(true) + }, completed: { + subscriber.putCompletion() + }) + + return SBlockDisposable { + disposable.dispose() + } + } + } + } +} + +final class WatchContinuationHandler: WatchRequestHandler { + static var handledSubscriptions: [Any] { + return [TGBridgeRemoteSubscription.self] + } + + static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal { + if let args = subscription as? TGBridgeRemoteSubscription, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) { + manager.requestNavigateToMessage(messageId: MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: args.messageId)) + } + return SSignal.fail(nil) + } +} diff --git a/submodules/WatchBridgeAudio/BUILD b/submodules/WatchBridgeAudio/BUILD new file mode 100644 index 00000000..e3994dc6 --- /dev/null +++ b/submodules/WatchBridgeAudio/BUILD @@ -0,0 +1,19 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "WatchBridgeAudio", + module_name = "WatchBridgeAudio", + srcs = glob([ + "Sources/**/*.swift", + ]), + copts = [ + "-warnings-as-errors", + ], + deps = [ + "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", + "//submodules/WatchBridgeAudio/Impl:WatchBridgeAudioImpl", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/submodules/WatchBridgeAudio/Impl/BUILD b/submodules/WatchBridgeAudio/Impl/BUILD new file mode 100644 index 00000000..b1290aca --- /dev/null +++ b/submodules/WatchBridgeAudio/Impl/BUILD @@ -0,0 +1,27 @@ + +objc_library( + name = "WatchBridgeAudioImpl", + enable_modules = True, + module_name = "WatchBridgeAudioImpl", + srcs = glob([ + "Sources/**/*.m", + "Sources/**/*.mm", + "Sources/**/*.h", + ], allow_empty=True), + hdrs = glob([ + "PublicHeaders/**/*.h", + ]), + includes = [ + "PublicHeaders", + ], + deps = [ + "//submodules/SSignalKit/SSignalKit:SSignalKit", + "//submodules/OpusBinding:OpusBinding", + ], + sdk_frameworks = [ + "Foundation", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/submodules/WatchBridgeAudio/Impl/PublicHeaders/WatchBridgeAudioImpl/TGBridgeAudioDecoder.h b/submodules/WatchBridgeAudio/Impl/PublicHeaders/WatchBridgeAudioImpl/TGBridgeAudioDecoder.h new file mode 100644 index 00000000..9332bf61 --- /dev/null +++ b/submodules/WatchBridgeAudio/Impl/PublicHeaders/WatchBridgeAudioImpl/TGBridgeAudioDecoder.h @@ -0,0 +1,8 @@ +#import + +@interface TGBridgeAudioDecoder : NSObject + +- (instancetype)initWithURL:(NSURL *)url outputUrl:(NSURL *)outputURL; +- (void)startWithCompletion:(void (^)(void))completion; + +@end diff --git a/submodules/WatchBridgeAudio/Impl/PublicHeaders/WatchBridgeAudioImpl/TGBridgeAudioEncoder.h b/submodules/WatchBridgeAudio/Impl/PublicHeaders/WatchBridgeAudioImpl/TGBridgeAudioEncoder.h new file mode 100644 index 00000000..7c186daf --- /dev/null +++ b/submodules/WatchBridgeAudio/Impl/PublicHeaders/WatchBridgeAudioImpl/TGBridgeAudioEncoder.h @@ -0,0 +1,8 @@ +#import + +@interface TGBridgeAudioEncoder : NSObject + +- (instancetype)initWithURL:(NSURL *)url; +- (void)startWithCompletion:(void (^)(NSString *, int32_t))completion; + +@end diff --git a/submodules/WatchBridgeAudio/Impl/PublicHeaders/WatchBridgeAudioImpl/WatchBridgeAudioImpl.h b/submodules/WatchBridgeAudio/Impl/PublicHeaders/WatchBridgeAudioImpl/WatchBridgeAudioImpl.h new file mode 100644 index 00000000..03950d97 --- /dev/null +++ b/submodules/WatchBridgeAudio/Impl/PublicHeaders/WatchBridgeAudioImpl/WatchBridgeAudioImpl.h @@ -0,0 +1,6 @@ +#import + +#import +#import + + diff --git a/submodules/WatchBridgeAudio/Impl/Sources/TGBridgeAudioDecoder.mm b/submodules/WatchBridgeAudio/Impl/Sources/TGBridgeAudioDecoder.mm new file mode 100644 index 00000000..c1d30b80 --- /dev/null +++ b/submodules/WatchBridgeAudio/Impl/Sources/TGBridgeAudioDecoder.mm @@ -0,0 +1,197 @@ +#import + +#import +#import + +#import + +#import + +const NSInteger TGBridgeAudioDecoderInputSampleRate = 48000; +const NSInteger TGBridgeAudioDecoderResultSampleRate = 24000; +const NSUInteger TGBridgeAudioDecoderBufferSize = 32768; + +#define checkResult(result,operation) (_checkResultLite((result),(operation),__FILE__,__LINE__)) + +struct TGAudioBuffer +{ + NSUInteger capacity; + uint8_t *data; + NSUInteger size; + int64_t pcmOffset; +}; + +inline TGAudioBuffer *TGAudioBufferWithCapacity(NSUInteger capacity) +{ + TGAudioBuffer *audioBuffer = (TGAudioBuffer *)malloc(sizeof(TGAudioBuffer)); + audioBuffer->capacity = capacity; + audioBuffer->data = (uint8_t *)malloc(capacity); + audioBuffer->size = 0; + audioBuffer->pcmOffset = 0; + return audioBuffer; +} + +inline void TGAudioBufferDispose(TGAudioBuffer *audioBuffer) +{ + if (audioBuffer != NULL) + { + free(audioBuffer->data); + free(audioBuffer); + } +} + +static inline bool _checkResultLite(OSStatus result, const char *operation, const char* file, int line) +{ + if ( result != noErr ) + { + NSLog(@"%s:%d: %s result %d %08X %4.4s\n", file, line, operation, (int)result, (int)result, (char*)&result); + return NO; + } + return YES; +} + +@interface TGBridgeAudioDecoder () +{ + NSURL *_url; + NSURL *_resultURL; + + OggOpusReader *_opusReader; + + bool _finished; + bool _cancelled; +} +@end + +@implementation TGBridgeAudioDecoder + +- (instancetype)initWithURL:(NSURL *)url outputUrl:(NSURL *)outputUrl +{ + self = [super init]; + if (self != nil) + { + _url = url; + + int64_t randomId = 0; + arc4random_buf(&randomId, 8); + _resultURL = outputUrl; + } + return self; +} + +- (void)startWithCompletion:(void (^)(void))completion +{ + [[TGBridgeAudioDecoder processingQueue] dispatch:^ + { + _opusReader = [[OggOpusReader alloc] initWithPath:_url.path]; + if (_opusReader == NULL) { + return; + } + + AudioStreamBasicDescription sourceFormat; + sourceFormat.mSampleRate = TGBridgeAudioDecoderInputSampleRate; + sourceFormat.mFormatID = kAudioFormatLinearPCM; + sourceFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; + sourceFormat.mFramesPerPacket = 1; + sourceFormat.mChannelsPerFrame = 1; + sourceFormat.mBitsPerChannel = 16; + sourceFormat.mBytesPerPacket = 2; + sourceFormat.mBytesPerFrame = 2; + + AudioStreamBasicDescription destFormat; + memset(&destFormat, 0, sizeof(destFormat)); + destFormat.mChannelsPerFrame = sourceFormat.mChannelsPerFrame; + destFormat.mFormatID = kAudioFormatMPEG4AAC; + destFormat.mSampleRate = TGBridgeAudioDecoderResultSampleRate; + UInt32 size = sizeof(destFormat); + if (!checkResult(AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, 0, NULL, &size, &destFormat), + "AudioFormatGetProperty(kAudioFormatProperty_FormatInfo)")) + { + return; + } + + ExtAudioFileRef destinationFile; + if (!checkResult(ExtAudioFileCreateWithURL((__bridge CFURLRef)_resultURL, kAudioFileM4AType, &destFormat, NULL, kAudioFileFlags_EraseFile, &destinationFile), "ExtAudioFileCreateWithURL")) + { + return; + } + + if (!checkResult(ExtAudioFileSetProperty(destinationFile, kExtAudioFileProperty_ClientDataFormat, size, &sourceFormat), + "ExtAudioFileSetProperty(destinationFile, kExtAudioFileProperty_ClientDataFormat")) + { + return; + } + + bool canResumeAfterInterruption = false; + AudioConverterRef converter; + size = sizeof(converter); + if (checkResult(ExtAudioFileGetProperty(destinationFile, kExtAudioFileProperty_AudioConverter, &size, &converter), + "ExtAudioFileGetProperty(kExtAudioFileProperty_AudioConverter;)")) + { + UInt32 canResume = 0; + size = sizeof(canResume); + if (AudioConverterGetProperty(converter, kAudioConverterPropertyCanResumeFromInterruption, &size, &canResume) == noErr) + canResumeAfterInterruption = canResume; + } + + uint8_t srcBuffer[TGBridgeAudioDecoderBufferSize]; + while (!_cancelled) + { + AudioBufferList bufferList; + bufferList.mNumberBuffers = 1; + bufferList.mBuffers[0].mNumberChannels = sourceFormat.mChannelsPerFrame; + bufferList.mBuffers[0].mDataByteSize = TGBridgeAudioDecoderBufferSize; + bufferList.mBuffers[0].mData = srcBuffer; + + uint32_t writtenOutputBytes = 0; + while (writtenOutputBytes < TGBridgeAudioDecoderBufferSize) + { + int32_t readSamples = [_opusReader read:(uint16_t *)(srcBuffer + writtenOutputBytes) bufSize:(TGBridgeAudioDecoderBufferSize - writtenOutputBytes) / sourceFormat.mBytesPerFrame]; + + if (readSamples > 0) + writtenOutputBytes += readSamples * sourceFormat.mBytesPerFrame; + else + break; + } + bufferList.mBuffers[0].mDataByteSize = writtenOutputBytes; + int32_t nFrames = writtenOutputBytes / sourceFormat.mBytesPerFrame; + + if (nFrames == 0) + break; + + OSStatus status = ExtAudioFileWrite(destinationFile, nFrames, &bufferList); + if (status == kExtAudioFileError_CodecUnavailableInputConsumed) + { + //TGLog(@"1"); + } + else if (status == kExtAudioFileError_CodecUnavailableInputNotConsumed) + { + //TGLog(@"2"); + } + else if (!checkResult(status, "ExtAudioFileWrite")) + { + //TGLog(@"3"); + } + } + + ExtAudioFileDispose(destinationFile); + + if (completion != nil) + completion(); + }]; +} + ++ (SQueue *)processingQueue +{ + static SQueue *queue = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^ + { + static const char *queueSpecific = "org.telegram.opusAudioDecoderQueue"; + dispatch_queue_t dispatchQueue = dispatch_queue_create("org.telegram.opusAudioDecoderQueue", DISPATCH_QUEUE_SERIAL); + dispatch_queue_set_specific(dispatchQueue, queueSpecific, (void *)queueSpecific, NULL); + queue = [SQueue wrapConcurrentNativeQueue:dispatchQueue]; + }); + return queue; +} + +@end diff --git a/submodules/WatchBridgeAudio/Impl/Sources/TGBridgeAudioEncoder.m b/submodules/WatchBridgeAudio/Impl/Sources/TGBridgeAudioEncoder.m new file mode 100644 index 00000000..2bf80914 --- /dev/null +++ b/submodules/WatchBridgeAudio/Impl/Sources/TGBridgeAudioEncoder.m @@ -0,0 +1,564 @@ +#import +#import + +#import + +static const char *AMQueueSpecific = "AMQueueSpecific"; + +const NSInteger TGBridgeAudioEncoderSampleRate = 48000; + +typedef enum { + ATQueuePriorityLow, + ATQueuePriorityDefault, + ATQueuePriorityHigh +} ATQueuePriority; + +@interface ATQueue : NSObject + ++ (ATQueue *)mainQueue; ++ (ATQueue *)concurrentDefaultQueue; ++ (ATQueue *)concurrentBackgroundQueue; + +- (instancetype)init; +- (instancetype)initWithName:(NSString *)name; +- (instancetype)initWithPriority:(ATQueuePriority)priority; + +- (void)dispatch:(dispatch_block_t)block; +- (void)dispatch:(dispatch_block_t)block synchronous:(bool)synchronous; +- (void)dispatchAfter:(NSTimeInterval)seconds block:(dispatch_block_t)block; + +- (dispatch_queue_t)nativeQueue; + +@end + +@interface TGFileDataItem : TGDataItem + +- (instancetype)initWithTempFile; + +- (void)appendData:(NSData *)data; +- (NSData *)readDataAtOffset:(NSUInteger)offset length:(NSUInteger)length; +- (NSUInteger)length; + +- (NSString *)path; + +@end + +@interface TGBridgeAudioEncoder () +{ + AVAssetReader *_assetReader; + AVAssetReaderOutput *_readerOutput; + + NSMutableData *_audioBuffer; + TGFileDataItem *_tempFileItem; + TGOggOpusWriter *_oggWriter; + + int _tailLength; +} +@end + +@implementation TGBridgeAudioEncoder + +- (instancetype)initWithURL:(NSURL *)url +{ + self = [super init]; + if (self != nil) + { + AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil]; + if (asset == nil || asset.tracks.count == 0) + { + return nil; + } + + NSError *error; + _assetReader = [[AVAssetReader alloc] initWithAsset:asset error:&error]; + + NSDictionary *outputSettings = @ + { + AVFormatIDKey: @(kAudioFormatLinearPCM), + AVSampleRateKey: @(TGBridgeAudioEncoderSampleRate), + AVNumberOfChannelsKey: @1, + AVLinearPCMBitDepthKey: @16, + AVLinearPCMIsFloatKey: @false, + AVLinearPCMIsBigEndianKey: @false, + AVLinearPCMIsNonInterleaved: @false + }; + + _readerOutput = [AVAssetReaderAudioMixOutput assetReaderAudioMixOutputWithAudioTracks:asset.tracks audioSettings:outputSettings]; + + [_assetReader addOutput:_readerOutput]; + + _tempFileItem = [[TGFileDataItem alloc] initWithTempFile]; + } + return self; +} + +- (void)dealloc +{ + [self cleanup]; +} + +- (void)cleanup +{ + _oggWriter = nil; +} + ++ (ATQueue *)processingQueue +{ + static ATQueue *queue = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^ + { + queue = [[ATQueue alloc] initWithName:@"org.telegram.opusAudioEncoderQueue"]; + }); + + return queue; +} + +static const int encoderPacketSizeInBytes = 16000 / 1000 * 60 * 2; + +- (void)startWithCompletion:(void (^)(NSString *, int32_t))completion +{ + [[TGBridgeAudioEncoder processingQueue] dispatch:^ + { + _oggWriter = [[TGOggOpusWriter alloc] init]; + if (![_oggWriter beginWithDataItem:_tempFileItem]) + { + [self cleanup]; + return; + } + + [_assetReader startReading]; + + while (_assetReader.status != AVAssetReaderStatusCompleted) + { + if (_assetReader.status == AVAssetReaderStatusReading) + { + CMSampleBufferRef nextBuffer = [_readerOutput copyNextSampleBuffer]; + if (nextBuffer) + { + AudioBufferList abl; + CMBlockBufferRef blockBuffer; + CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(nextBuffer, NULL, &abl, sizeof(abl), NULL, NULL, kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, &blockBuffer); + + [[TGBridgeAudioEncoder processingQueue] dispatch:^ + { + [self _processBuffer:&abl.mBuffers[0]]; + + CFRelease(nextBuffer); + CFRelease(blockBuffer); + }]; + } + else + { + [[TGBridgeAudioEncoder processingQueue] dispatch:^ + { + if (_tailLength > 0) { + [_oggWriter writeFrame:(uint8_t *)_audioBuffer.bytes frameByteCount:(NSUInteger)_tailLength]; + } + }]; + break; + } + } + } + + [[TGBridgeAudioEncoder processingQueue] dispatch:^ + { + TGFileDataItem *dataItemResult = nil; + NSTimeInterval durationResult = 0.0; + + NSUInteger totalBytes = 0; + + if (_assetReader.status == AVAssetReaderStatusCompleted) + { + NSLog(@"finished"); + if (_oggWriter != nil && [_oggWriter writeFrame:NULL frameByteCount:0]) + { + dataItemResult = _tempFileItem; + durationResult = [_oggWriter encodedDuration]; + totalBytes = [_oggWriter encodedBytes]; + } + + [self cleanup]; + } + + //TGLog(@"[TGBridgeAudioEncoder#%x convert time: %f ms]", self, (CFAbsoluteTimeGetCurrent() - startTime) * 1000.0); + + if (completion != nil) + completion(dataItemResult.path, (int32_t)durationResult); + }]; + }]; +} + +- (void)_processBuffer:(AudioBuffer const *)buffer +{ + @autoreleasepool + { + if (_oggWriter == nil) + return; + + unsigned char currentEncoderPacket[encoderPacketSizeInBytes]; + + int bufferOffset = 0; + + while (true) + { + int currentEncoderPacketSize = 0; + + while (currentEncoderPacketSize < encoderPacketSizeInBytes) + { + if (_audioBuffer.length != 0) + { + int takenBytes = MIN((int)_audioBuffer.length, encoderPacketSizeInBytes - currentEncoderPacketSize); + if (takenBytes != 0) + { + memcpy(currentEncoderPacket + currentEncoderPacketSize, _audioBuffer.bytes, takenBytes); + [_audioBuffer replaceBytesInRange:NSMakeRange(0, takenBytes) withBytes:NULL length:0]; + currentEncoderPacketSize += takenBytes; + } + } + else if (bufferOffset < (int)buffer->mDataByteSize) + { + int takenBytes = MIN((int)buffer->mDataByteSize - bufferOffset, encoderPacketSizeInBytes - currentEncoderPacketSize); + if (takenBytes != 0) + { + memcpy(currentEncoderPacket + currentEncoderPacketSize, ((const char *)buffer->mData) + bufferOffset, takenBytes); + bufferOffset += takenBytes; + currentEncoderPacketSize += takenBytes; + } + } + else { + break; + } + } + _tailLength = currentEncoderPacketSize; + if (currentEncoderPacketSize < encoderPacketSizeInBytes) + { + if (_audioBuffer == nil) + _audioBuffer = [[NSMutableData alloc] initWithCapacity:encoderPacketSizeInBytes]; + [_audioBuffer appendBytes:currentEncoderPacket length:currentEncoderPacketSize]; + break; + } + else + { + [_oggWriter writeFrame:currentEncoderPacket frameByteCount:(NSUInteger)currentEncoderPacketSize]; + _tailLength = 0; + } + } + } +} + +@end + +@interface TGFileDataItem () +{ + NSUInteger _length; + + NSString *_fileName; + bool _fileExists; + + NSMutableData *_data; +} + +@end + +@implementation TGFileDataItem +{ + ATQueue *_queue; +} + +- (void)_commonInit +{ + _queue = [[ATQueue alloc] initWithPriority:ATQueuePriorityLow]; + _data = [[NSMutableData alloc] init]; +} + +- (instancetype)initWithTempFile +{ + self = [super init]; + if (self != nil) + { + [self _commonInit]; + + [_queue dispatch:^ + { + int64_t randomId = 0; + arc4random_buf(&randomId, 8); + _fileName = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSString alloc] initWithFormat:@"%" PRIx64 "", randomId]]; + _fileExists = false; + }]; + } + return self; +} + +- (instancetype)initWithFilePath:(NSString *)filePath +{ + self = [super init]; + if (self != nil) + { + [self _commonInit]; + + + [_queue dispatch:^ + { + _fileName = filePath; + _length = [[[NSFileManager defaultManager] attributesOfItemAtPath:_fileName error:nil][NSFileSize] unsignedIntegerValue]; + _fileExists = [[NSFileManager defaultManager] fileExistsAtPath:_fileName]; + }]; + } + return self; +} + +- (void)noop +{ +} + +- (void)moveToPath:(NSString *)path +{ + [_queue dispatch:^ + { + [[NSFileManager defaultManager] moveItemAtPath:_fileName toPath:path error:nil]; + _fileName = path; + }]; +} + +- (void)remove +{ + [_queue dispatch:^ + { + [[NSFileManager defaultManager] removeItemAtPath:_fileName error:nil]; + }]; +} + +- (void)appendData:(NSData *)data +{ + [_queue dispatch:^ + { + if (!_fileExists) + { + [[NSFileManager defaultManager] createFileAtPath:_fileName contents:nil attributes:nil]; + _fileExists = true; + } + NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath:_fileName]; + [file seekToEndOfFile]; + [file writeData:data]; + [file synchronizeFile]; + [file closeFile]; + _length += data.length; + + [_data appendData:data]; + }]; +} + +- (NSData *)readDataAtOffset:(NSUInteger)offset length:(NSUInteger)length +{ + __block NSData *data = nil; + + [_queue dispatch:^ + { + NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath:_fileName]; + [file seekToFileOffset:(unsigned long long)offset]; + data = [file readDataOfLength:length]; + if (data.length != length) + //TGLog(@"Read data length mismatch"); + [file closeFile]; + } synchronous:true]; + + return data; +} + +- (NSUInteger)length +{ + __block NSUInteger result = 0; + [_queue dispatch:^ + { + result = _length; + } synchronous:true]; + + return result; +} + +- (NSString *)path { + return _fileName; +} + +@end + + +@interface ATQueue () +{ + dispatch_queue_t _nativeQueue; + bool _isMainQueue; + + int32_t _noop; +} + +@end + +@implementation ATQueue + ++ (NSString *)applicationPrefix +{ + static NSString *prefix = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^ + { + prefix = [[NSBundle mainBundle] bundleIdentifier]; + }); + + return prefix; +} + ++ (ATQueue *)mainQueue +{ + static ATQueue *queue = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^ + { + queue = [[ATQueue alloc] init]; + queue->_nativeQueue = dispatch_get_main_queue(); + queue->_isMainQueue = true; + }); + + return queue; +} + ++ (ATQueue *)concurrentDefaultQueue +{ + static ATQueue *queue = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^ + { + queue = [[ATQueue alloc] initWithNativeQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)]; + }); + + return queue; +} + ++ (ATQueue *)concurrentBackgroundQueue +{ + static ATQueue *queue = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^ + { + queue = [[ATQueue alloc] initWithNativeQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)]; + }); + + return queue; +} + +- (instancetype)init +{ + return [self initWithName:[[ATQueue applicationPrefix] stringByAppendingFormat:@".%ld", lrand48()]]; +} + +- (instancetype)initWithName:(NSString *)name +{ + self = [super init]; + if (self != nil) + { + _nativeQueue = dispatch_queue_create([name UTF8String], DISPATCH_QUEUE_SERIAL); + dispatch_queue_set_specific(_nativeQueue, AMQueueSpecific, (__bridge void *)self, NULL); + } + return self; +} + +- (instancetype)initWithPriority:(ATQueuePriority)priority +{ + self = [super init]; + if (self != nil) + { + _nativeQueue = dispatch_queue_create([[[ATQueue applicationPrefix] stringByAppendingFormat:@".%ld", lrand48()] UTF8String], DISPATCH_QUEUE_SERIAL); + long targetQueueIdentifier = DISPATCH_QUEUE_PRIORITY_DEFAULT; + switch (priority) + { + case ATQueuePriorityLow: + targetQueueIdentifier = DISPATCH_QUEUE_PRIORITY_LOW; + break; + case ATQueuePriorityDefault: + targetQueueIdentifier = DISPATCH_QUEUE_PRIORITY_DEFAULT; + break; + case ATQueuePriorityHigh: + targetQueueIdentifier = DISPATCH_QUEUE_PRIORITY_HIGH; + break; + } + dispatch_set_target_queue(_nativeQueue, dispatch_get_global_queue(targetQueueIdentifier, 0)); + dispatch_queue_set_specific(_nativeQueue, AMQueueSpecific, (__bridge void *)self, NULL); + } + return self; +} + +- (instancetype)initWithNativeQueue:(dispatch_queue_t)queue +{ + self = [super init]; + if (self != nil) + { +#if !OS_OBJECT_USE_OBJC + _nativeQueue = dispatch_retain(queue); +#else + _nativeQueue = queue; +#endif + } + return self; +} + +- (void)dealloc +{ + if (_nativeQueue != nil) + { +#if !OS_OBJECT_USE_OBJC + dispatch_release(_nativeQueue); +#endif + _nativeQueue = nil; + } +} + +- (void)dispatch:(dispatch_block_t)block +{ + [self dispatch:block synchronous:false]; +} + +- (void)dispatch:(dispatch_block_t)block synchronous:(bool)synchronous +{ + __block ATQueue *strongSelf = self; + dispatch_block_t blockWithSelf = ^ + { + block(); + [strongSelf noop]; + strongSelf = nil; + }; + + if (_isMainQueue) + { + if ([NSThread isMainThread]) + blockWithSelf(); + else if (synchronous) + dispatch_sync(_nativeQueue, blockWithSelf); + else + dispatch_async(_nativeQueue, blockWithSelf); + } + else + { + if (dispatch_get_specific(AMQueueSpecific) == (__bridge void *)self) + block(); + else if (synchronous) + dispatch_sync(_nativeQueue, blockWithSelf); + else + dispatch_async(_nativeQueue, blockWithSelf); + } +} + +- (void)dispatchAfter:(NSTimeInterval)seconds block:(dispatch_block_t)block +{ + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), _nativeQueue, block); +} + +- (dispatch_queue_t)nativeQueue +{ + return _nativeQueue; +} + +- (void)noop +{ +} + +@end diff --git a/submodules/WatchBridgeAudio/Sources/LegacyBridgeAudio.swift b/submodules/WatchBridgeAudio/Sources/LegacyBridgeAudio.swift new file mode 100644 index 00000000..ab80d4f2 --- /dev/null +++ b/submodules/WatchBridgeAudio/Sources/LegacyBridgeAudio.swift @@ -0,0 +1,25 @@ +import Foundation +import SwiftSignalKit +import WatchBridgeAudioImpl + +public func legacyDecodeOpusAudio(path: String, outputPath: String) -> Signal { + return Signal { subscriber in + let decoder = TGBridgeAudioDecoder(url: URL(fileURLWithPath: path), outputUrl: URL(fileURLWithPath: outputPath)) + decoder?.start(completion: { + subscriber.putNext(outputPath) + subscriber.putCompletion() + }) + return EmptyDisposable + } +} + +public func legacyEncodeOpusAudio(path: String) -> Signal<(String?, Int32), NoError> { + return Signal { subscriber in + let encoder = TGBridgeAudioEncoder(url: URL(fileURLWithPath: path)) + encoder?.start(completion: { (path, duration) in + subscriber.putNext((path, duration)) + subscriber.putCompletion() + }) + return EmptyDisposable + } +} diff --git a/submodules/WatchCommon/Host/BUILD b/submodules/WatchCommon/Host/BUILD new file mode 100644 index 00000000..043309a9 --- /dev/null +++ b/submodules/WatchCommon/Host/BUILD @@ -0,0 +1,25 @@ + +objc_library( + name = "WatchCommon", + enable_modules = True, + module_name = "WatchCommon", + srcs = glob([ + "Sources/**/*.m", + "Sources/**/*.h", + ], allow_empty=True), + hdrs = glob([ + "PublicHeaders/**/*.h", + ]), + copts = [ + "-I{}/PublicHeaders/WatchCommon".format(package_name()), + ], + includes = [ + "PublicHeaders", + ], + sdk_frameworks = [ + "Foundation", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeActionMediaAttachment.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeActionMediaAttachment.h new file mode 100644 index 00000000..bb18757f --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeActionMediaAttachment.h @@ -0,0 +1,36 @@ +#import + +typedef NS_ENUM(NSUInteger, TGBridgeMessageAction) { + TGBridgeMessageActionNone = 0, + TGBridgeMessageActionChatEditTitle = 1, + TGBridgeMessageActionChatAddMember = 2, + TGBridgeMessageActionChatDeleteMember = 3, + TGBridgeMessageActionCreateChat = 4, + TGBridgeMessageActionChatEditPhoto = 5, + TGBridgeMessageActionContactRequest = 6, + TGBridgeMessageActionAcceptContactRequest = 7, + TGBridgeMessageActionContactRegistered = 8, + TGBridgeMessageActionUserChangedPhoto = 9, + TGBridgeMessageActionEncryptedChatRequest = 10, + TGBridgeMessageActionEncryptedChatAccept = 11, + TGBridgeMessageActionEncryptedChatDecline = 12, + TGBridgeMessageActionEncryptedChatMessageLifetime = 13, + TGBridgeMessageActionEncryptedChatScreenshot = 14, + TGBridgeMessageActionEncryptedChatMessageScreenshot = 15, + TGBridgeMessageActionCreateBroadcastList = 16, + TGBridgeMessageActionJoinedByLink = 17, + TGBridgeMessageActionChannelCreated = 18, + TGBridgeMessageActionChannelCommentsStatusChanged = 19, + TGBridgeMessageActionChannelInviter = 20, + TGBridgeMessageActionGroupMigratedTo = 21, + TGBridgeMessageActionGroupDeactivated = 22, + TGBridgeMessageActionGroupActivated = 23, + TGBridgeMessageActionChannelMigratedFrom = 24 +}; + +@interface TGBridgeActionMediaAttachment : TGBridgeMediaAttachment + +@property (nonatomic, assign) TGBridgeMessageAction actionType; +@property (nonatomic, strong) NSDictionary *actionData; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeAudioMediaAttachment.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeAudioMediaAttachment.h new file mode 100644 index 00000000..ffdb8645 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeAudioMediaAttachment.h @@ -0,0 +1,16 @@ +#import + +@interface TGBridgeAudioMediaAttachment : TGBridgeMediaAttachment + +@property (nonatomic, assign) int64_t audioId; +@property (nonatomic, assign) int64_t accessHash; +@property (nonatomic, assign) int32_t datacenterId; + +@property (nonatomic, assign) int64_t localAudioId; + +@property (nonatomic, assign) int32_t duration; +@property (nonatomic, assign) int32_t fileSize; + +- (int64_t)identifier; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeBotCommandInfo.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeBotCommandInfo.h new file mode 100644 index 00000000..fe6f72e1 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeBotCommandInfo.h @@ -0,0 +1,12 @@ +#import + +@interface TGBridgeBotCommandInfo : NSObject +{ + NSString *_command; + NSString *_commandDescription; +} + +@property (nonatomic, readonly) NSString *command; +@property (nonatomic, readonly) NSString *commandDescription; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeBotInfo.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeBotInfo.h new file mode 100644 index 00000000..0dafae5c --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeBotInfo.h @@ -0,0 +1,12 @@ +#import + +@interface TGBridgeBotInfo : NSObject +{ + NSString *_shortDescription; + NSArray *_commandList; +} + +@property (nonatomic, readonly) NSString *shortDescription; +@property (nonatomic, readonly) NSArray *commandList; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeChat.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeChat.h new file mode 100644 index 00000000..fa56be05 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeChat.h @@ -0,0 +1,46 @@ +#import +#import + +@interface TGBridgeChat : NSObject + +@property (nonatomic) int64_t identifier; +@property (nonatomic) NSTimeInterval date; +@property (nonatomic) int32_t fromUid; +@property (nonatomic, strong) NSString *text; + +@property (nonatomic, strong) NSArray *media; + +@property (nonatomic) bool outgoing; +@property (nonatomic) bool unread; +@property (nonatomic) bool deliveryError; +@property (nonatomic) TGBridgeMessageDeliveryState deliveryState; + +@property (nonatomic) int32_t unreadCount; + +@property (nonatomic) bool isBroadcast; + +@property (nonatomic, strong) NSString *groupTitle; +@property (nonatomic, strong) NSString *groupPhotoSmall; +@property (nonatomic, strong) NSString *groupPhotoBig; + +@property (nonatomic) bool isGroup; +@property (nonatomic) bool hasLeftGroup; +@property (nonatomic) bool isKickedFromGroup; + +@property (nonatomic) bool isChannel; +@property (nonatomic) bool isChannelGroup; + +@property (nonatomic, strong) NSString *userName; +@property (nonatomic, strong) NSString *about; +@property (nonatomic) bool verified; + +@property (nonatomic) int32_t participantsCount; +@property (nonatomic, strong) NSArray *participants; + +- (NSArray *)involvedUserIds; +- (NSArray *)participantsUserIds; + +@end + +extern NSString *const TGBridgeChatKey; +extern NSString *const TGBridgeChatsArrayKey; diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeChatMessages.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeChatMessages.h new file mode 100644 index 00000000..9c539758 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeChatMessages.h @@ -0,0 +1,14 @@ +#import + +@class SSignal; + +@interface TGBridgeChatMessages : NSObject +{ + NSArray *_messages; +} + +@property (nonatomic, readonly) NSArray *messages; + +@end + +extern NSString *const TGBridgeChatMessageListViewKey; diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeCommon.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeCommon.h new file mode 100644 index 00000000..fe0510c0 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeCommon.h @@ -0,0 +1,95 @@ +#import + +extern NSString *const TGBridgeIncomingFileTypeKey; +extern NSString *const TGBridgeIncomingFileIdentifierKey; +extern NSString *const TGBridgeIncomingFileRandomIdKey; +extern NSString *const TGBridgeIncomingFilePeerIdKey; +extern NSString *const TGBridgeIncomingFileReplyToMidKey; + +extern NSString *const TGBridgeIncomingFileTypeAudio; +extern NSString *const TGBridgeIncomingFileTypeImage; + +@interface TGBridgeSubscription : NSObject + +@property (nonatomic, readonly) int64_t identifier; +@property (nonatomic, readonly, strong) NSString *name; + +@property (nonatomic, readonly) bool isOneTime; +@property (nonatomic, readonly) bool renewable; +@property (nonatomic, readonly) bool dropPreviouslyQueued; +@property (nonatomic, readonly) bool synchronous; + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder; +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder; + ++ (NSString *)subscriptionName; + +@end + + +@interface TGBridgeDisposal : NSObject + +@property (nonatomic, readonly) int64_t identifier; + +- (instancetype)initWithIdentifier:(int64_t)identifier; + +@end + + +@interface TGBridgeFile : NSObject + +@property (nonatomic, readonly, strong) NSData *data; +@property (nonatomic, readonly, strong) NSDictionary *metadata; + +- (instancetype)initWithData:(NSData *)data metadata:(NSDictionary *)metadata; + +@end + + +@interface TGBridgePing : NSObject + +@property (nonatomic, readonly) int32_t sessionId; + +- (instancetype)initWithSessionId:(int32_t)sessionId; + +@end + + +@interface TGBridgeSubscriptionListRequest : NSObject + +@property (nonatomic, readonly) int32_t sessionId; + +- (instancetype)initWithSessionId:(int32_t)sessionId; + +@end + + +@interface TGBridgeSubscriptionList : NSObject + +@property (nonatomic, readonly, strong) NSArray *subscriptions; + +- (instancetype)initWithArray:(NSArray *)array; + +@end + + +typedef NS_ENUM(int32_t, TGBridgeResponseType) { + TGBridgeResponseTypeUndefined, + TGBridgeResponseTypeNext, + TGBridgeResponseTypeFailed, + TGBridgeResponseTypeCompleted +}; + +@interface TGBridgeResponse : NSObject + +@property (nonatomic, readonly) int64_t subscriptionIdentifier; + +@property (nonatomic, readonly) TGBridgeResponseType type; +@property (nonatomic, readonly, strong) id next; +@property (nonatomic, readonly, strong) NSString *error; + ++ (TGBridgeResponse *)single:(id)next forSubscription:(TGBridgeSubscription *)subscription; ++ (TGBridgeResponse *)fail:(id)error forSubscription:(TGBridgeSubscription *)subscription; ++ (TGBridgeResponse *)completeForSubscription:(TGBridgeSubscription *)subscription; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeContactMediaAttachment.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeContactMediaAttachment.h new file mode 100644 index 00000000..05229313 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeContactMediaAttachment.h @@ -0,0 +1,13 @@ +#import + +@interface TGBridgeContactMediaAttachment : TGBridgeMediaAttachment + +@property (nonatomic, assign) int32_t uid; +@property (nonatomic, strong) NSString *firstName; +@property (nonatomic, strong) NSString *lastName; +@property (nonatomic, strong) NSString *phoneNumber; +@property (nonatomic, strong) NSString *prettyPhoneNumber; + +- (NSString *)displayName; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeContext.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeContext.h new file mode 100644 index 00000000..45225a04 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeContext.h @@ -0,0 +1,18 @@ +#import + +@interface TGBridgeContext : NSObject + +@property (nonatomic, readonly) bool authorized; +@property (nonatomic, readonly) int32_t userId; +@property (nonatomic, readonly) bool micAccessAllowed; +@property (nonatomic, readonly) NSDictionary *preheatData; +@property (nonatomic, readonly) NSInteger preheatVersion; + +- (instancetype)initWithDictionary:(NSDictionary *)dictionary; +- (NSDictionary *)dictionary; + +- (TGBridgeContext *)updatedWithAuthorized:(bool)authorized peerId:(int32_t)peerId; +- (TGBridgeContext *)updatedWithPreheatData:(NSDictionary *)data; +- (TGBridgeContext *)updatedWithMicAccessAllowed:(bool)allowed; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeDocumentMediaAttachment.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeDocumentMediaAttachment.h new file mode 100644 index 00000000..020a50fa --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeDocumentMediaAttachment.h @@ -0,0 +1,23 @@ +#import + +@interface TGBridgeDocumentMediaAttachment : TGBridgeMediaAttachment + +@property (nonatomic, assign) int64_t documentId; +@property (nonatomic, assign) int64_t localDocumentId; +@property (nonatomic, assign) int32_t fileSize; + +@property (nonatomic, strong) NSString *fileName; +@property (nonatomic, strong) NSValue *imageSize; +@property (nonatomic, assign) bool isAnimated; +@property (nonatomic, assign) bool isSticker; +@property (nonatomic, strong) NSString *stickerAlt; +@property (nonatomic, assign) int64_t stickerPackId; +@property (nonatomic, assign) int64_t stickerPackAccessHash; + +@property (nonatomic, assign) bool isVoice; +@property (nonatomic, assign) bool isAudio; +@property (nonatomic, strong) NSString *title; +@property (nonatomic, strong) NSString *performer; +@property (nonatomic, assign) int32_t duration; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeForwardedMessageMediaAttachment.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeForwardedMessageMediaAttachment.h new file mode 100644 index 00000000..f57651e4 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeForwardedMessageMediaAttachment.h @@ -0,0 +1,9 @@ +#import + +@interface TGBridgeForwardedMessageMediaAttachment : TGBridgeMediaAttachment + +@property (nonatomic, assign) int64_t peerId; +@property (nonatomic, assign) int32_t mid; +@property (nonatomic, assign) int32_t date; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeImageMediaAttachment.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeImageMediaAttachment.h new file mode 100644 index 00000000..f35b6623 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeImageMediaAttachment.h @@ -0,0 +1,10 @@ +#import + +#import + +@interface TGBridgeImageMediaAttachment : TGBridgeMediaAttachment + +@property (nonatomic, assign) int64_t imageId; +@property (nonatomic, assign) CGSize dimensions; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeLocationMediaAttachment.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeLocationMediaAttachment.h new file mode 100644 index 00000000..01081546 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeLocationMediaAttachment.h @@ -0,0 +1,19 @@ +#import + +@interface TGBridgeVenueAttachment : NSObject + +@property (nonatomic, strong) NSString *title; +@property (nonatomic, strong) NSString *address; +@property (nonatomic, strong) NSString *provider; +@property (nonatomic, strong) NSString *venueId; + +@end + +@interface TGBridgeLocationMediaAttachment : TGBridgeMediaAttachment + +@property (nonatomic, assign) double latitude; +@property (nonatomic, assign) double longitude; + +@property (nonatomic, strong) TGBridgeVenueAttachment *venue; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeLocationVenue.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeLocationVenue.h new file mode 100644 index 00000000..c626f76f --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeLocationVenue.h @@ -0,0 +1,15 @@ +#import + +@class TGBridgeLocationMediaAttachment; + +@interface TGBridgeLocationVenue : NSObject + +@property (nonatomic) CLLocationCoordinate2D coordinate; +@property (nonatomic, strong) NSString *identifier; +@property (nonatomic, strong) NSString *provider; +@property (nonatomic, strong) NSString *name; +@property (nonatomic, strong) NSString *address; + +- (TGBridgeLocationMediaAttachment *)locationAttachment; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeMediaAttachment.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeMediaAttachment.h new file mode 100644 index 00000000..a814ea50 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeMediaAttachment.h @@ -0,0 +1,11 @@ +#import + +@interface TGBridgeMediaAttachment : NSObject + +@property (nonatomic, readonly) NSInteger mediaType; + ++ (NSInteger)mediaType; + +@end + +extern NSString *const TGBridgeMediaAttachmentTypeKey; diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeMessage.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeMessage.h new file mode 100644 index 00000000..a55e1491 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeMessage.h @@ -0,0 +1,65 @@ +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import + +typedef enum { + TGBridgeTextCheckingResultTypeUndefined, + TGBridgeTextCheckingResultTypeBold, + TGBridgeTextCheckingResultTypeItalic, + TGBridgeTextCheckingResultTypeCode, + TGBridgeTextCheckingResultTypePre +} TGBridgeTextCheckingResultType; + +@interface TGBridgeTextCheckingResult : NSObject + +@property (nonatomic, assign) TGBridgeTextCheckingResultType type; +@property (nonatomic, assign) NSRange range; + +@end + + +typedef NS_ENUM(NSUInteger, TGBridgeMessageDeliveryState) { + TGBridgeMessageDeliveryStateDelivered = 0, + TGBridgeMessageDeliveryStatePending = 1, + TGBridgeMessageDeliveryStateFailed = 2 +}; + +@interface TGBridgeMessage : NSObject + +@property (nonatomic) int32_t identifier; +@property (nonatomic) NSTimeInterval date; +@property (nonatomic) int64_t randomId; +@property (nonatomic) bool unread; +@property (nonatomic) bool deliveryError; +@property (nonatomic) TGBridgeMessageDeliveryState deliveryState; +@property (nonatomic) bool outgoing; +@property (nonatomic) int64_t fromUid; +@property (nonatomic) int64_t toUid; +@property (nonatomic) int64_t cid; +@property (nonatomic, strong) NSString *text; +@property (nonatomic, strong) NSArray *media; +@property (nonatomic) bool forceReply; + +- (NSArray *)involvedUserIds; +- (NSArray *)textCheckingResults; + ++ (instancetype)temporaryNewMessageForText:(NSString *)text userId:(int32_t)userId; ++ (instancetype)temporaryNewMessageForText:(NSString *)text userId:(int32_t)userId replyToMessage:(TGBridgeMessage *)replyToMessage; ++ (instancetype)temporaryNewMessageForSticker:(TGBridgeDocumentMediaAttachment *)sticker userId:(int32_t)userId; ++ (instancetype)temporaryNewMessageForLocation:(TGBridgeLocationMediaAttachment *)location userId:(int32_t)userId; ++ (instancetype)temporaryNewMessageForAudioWithDuration:(int32_t)duration userId:(int32_t)userId localAudioId:(int64_t)localAudioId; + +@end + +extern NSString *const TGBridgeMessageKey; +extern NSString *const TGBridgeMessagesArrayKey; diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeMessageEntities.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeMessageEntities.h new file mode 100644 index 00000000..669ff3b2 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeMessageEntities.h @@ -0,0 +1,59 @@ +#import + +@interface TGBridgeMessageEntity : NSObject + +@property (nonatomic, assign) NSRange range; + ++ (instancetype)entitityWithRange:(NSRange)range; + +@end + + +@interface TGBridgeMessageEntityUrl : TGBridgeMessageEntity + +@end + + +@interface TGBridgeMessageEntityEmail : TGBridgeMessageEntity + +@end + + +@interface TGBridgeMessageEntityTextUrl : TGBridgeMessageEntity + +@end + + +@interface TGBridgeMessageEntityMention : TGBridgeMessageEntity + +@end + + +@interface TGBridgeMessageEntityHashtag : TGBridgeMessageEntity + +@end + + +@interface TGBridgeMessageEntityBotCommand : TGBridgeMessageEntity + +@end + + +@interface TGBridgeMessageEntityBold : TGBridgeMessageEntity + +@end + + +@interface TGBridgeMessageEntityItalic : TGBridgeMessageEntity + +@end + + +@interface TGBridgeMessageEntityCode : TGBridgeMessageEntity + +@end + + +@interface TGBridgeMessageEntityPre : TGBridgeMessageEntity + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeMessageEntitiesAttachment.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeMessageEntitiesAttachment.h new file mode 100644 index 00000000..8f32fd03 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeMessageEntitiesAttachment.h @@ -0,0 +1,8 @@ +#import +#import + +@interface TGBridgeMessageEntitiesAttachment : TGBridgeMediaAttachment + +@property (nonatomic, strong) NSArray *entities; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgePeerIdAdapter.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgePeerIdAdapter.h new file mode 100644 index 00000000..5c646d56 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgePeerIdAdapter.h @@ -0,0 +1,120 @@ +#ifndef Telegraph_TGPeerIdAdapter_h +#define Telegraph_TGPeerIdAdapter_h + +// Namespace constants based on Swift implementation +#define TG_NAMESPACE_MASK 0x7 +#define TG_NAMESPACE_EMPTY 0x0 +#define TG_NAMESPACE_CLOUD 0x1 +#define TG_NAMESPACE_GROUP 0x2 +#define TG_NAMESPACE_CHANNEL 0x3 +#define TG_NAMESPACE_SECRET_CHAT 0x4 +#define TG_NAMESPACE_ADMIN_LOG 0x5 +#define TG_NAMESPACE_AD 0x6 +#define TG_NAMESPACE_MAX 0x7 + +// Helper functions for bit manipulation +static inline uint32_t TGPeerIdGetNamespace(int64_t peerId) { + uint64_t data = (uint64_t)peerId; + return (uint32_t)((data >> 32) & TG_NAMESPACE_MASK); +} + +static inline int64_t TGPeerIdGetId(int64_t peerId) { + uint64_t data = (uint64_t)peerId; + uint64_t idHighBits = (data >> (32 + 3)) << 32; + uint64_t idLowBits = data & 0xffffffff; + return (int64_t)(idHighBits | idLowBits); +} + +static inline int64_t TGPeerIdMake(uint32_t namespaceId, int64_t id) { + uint64_t data = 0; + uint64_t idBits = (uint64_t)id; + uint64_t idLowBits = idBits & 0xffffffff; + uint64_t idHighBits = (idBits >> 32) & 0xffffffff; + + data |= ((uint64_t)(namespaceId & TG_NAMESPACE_MASK)) << 32; + data |= (idHighBits << (32 + 3)); + data |= idLowBits; + + return (int64_t)data; +} + +// Updated peer type checks +static inline bool TGPeerIdIsEmpty(int64_t peerId) { + return TGPeerIdGetNamespace(peerId) == TG_NAMESPACE_EMPTY; +} + +static inline bool TGPeerIdIsUser(int64_t peerId) { + return TGPeerIdGetNamespace(peerId) == TG_NAMESPACE_CLOUD; +} + +static inline bool TGPeerIdIsGroup(int64_t peerId) { + return TGPeerIdGetNamespace(peerId) == TG_NAMESPACE_GROUP; +} + +static inline bool TGPeerIdIsChannel(int64_t peerId) { + return TGPeerIdGetNamespace(peerId) == TG_NAMESPACE_CHANNEL; +} + +static inline bool TGPeerIdIsSecretChat(int64_t peerId) { + return TGPeerIdGetNamespace(peerId) == TG_NAMESPACE_SECRET_CHAT; +} + +static inline bool TGPeerIdIsAdminLog(int64_t peerId) { + return TGPeerIdGetNamespace(peerId) == TG_NAMESPACE_ADMIN_LOG; +} + +static inline bool TGPeerIdIsAd(int64_t peerId) { + return TGPeerIdGetNamespace(peerId) == TG_NAMESPACE_AD; +} + +// Conversion functions +static inline int64_t TGPeerIdFromUserId(int64_t userId) { + return TGPeerIdMake(TG_NAMESPACE_CLOUD, userId); +} + +static inline int64_t TGPeerIdFromGroupId(int64_t groupId) { + return TGPeerIdMake(TG_NAMESPACE_GROUP, groupId); +} + +static inline int64_t TGPeerIdFromChannelId(int64_t channelId) { + return TGPeerIdMake(TG_NAMESPACE_CHANNEL, channelId); +} + +static inline int64_t TGPeerIdFromSecretChatId(int64_t secretChatId) { + return TGPeerIdMake(TG_NAMESPACE_SECRET_CHAT, secretChatId); +} + +static inline int64_t TGPeerIdFromAdminLogId(int64_t adminLogId) { + return TGPeerIdMake(TG_NAMESPACE_ADMIN_LOG, adminLogId); +} + +static inline int64_t TGPeerIdFromAdId(int64_t adId) { + return TGPeerIdMake(TG_NAMESPACE_AD, adId); +} + +// Extract IDs +static inline int64_t TGUserIdFromPeerId(int64_t peerId) { + return TGPeerIdIsUser(peerId) ? TGPeerIdGetId(peerId) : 0; +} + +static inline int64_t TGGroupIdFromPeerId(int64_t peerId) { + return TGPeerIdIsGroup(peerId) ? TGPeerIdGetId(peerId) : 0; +} + +static inline int64_t TGChannelIdFromPeerId(int64_t peerId) { + return TGPeerIdIsChannel(peerId) ? TGPeerIdGetId(peerId) : 0; +} + +static inline int64_t TGSecretChatIdFromPeerId(int64_t peerId) { + return TGPeerIdIsSecretChat(peerId) ? TGPeerIdGetId(peerId) : 0; +} + +static inline int64_t TGAdminLogIdFromPeerId(int64_t peerId) { + return TGPeerIdIsAdminLog(peerId) ? TGPeerIdGetId(peerId) : 0; +} + +static inline int64_t TGAdIdFromPeerId(int64_t peerId) { + return TGPeerIdIsAd(peerId) ? TGPeerIdGetId(peerId) : 0; +} + +#endif diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgePeerNotificationSettings.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgePeerNotificationSettings.h new file mode 100644 index 00000000..fce723ce --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgePeerNotificationSettings.h @@ -0,0 +1,7 @@ +#import + +@interface TGBridgePeerNotificationSettings : NSObject + +@property (nonatomic, assign) int32_t muteFor; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeReplyMarkupMediaAttachment.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeReplyMarkupMediaAttachment.h new file mode 100644 index 00000000..ef8a600a --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeReplyMarkupMediaAttachment.h @@ -0,0 +1,9 @@ +#import + +@class TGBridgeBotReplyMarkup; + +@interface TGBridgeReplyMarkupMediaAttachment : TGBridgeMediaAttachment + +@property (nonatomic, strong) TGBridgeBotReplyMarkup *replyMarkup; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeReplyMessageMediaAttachment.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeReplyMessageMediaAttachment.h new file mode 100644 index 00000000..50353e21 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeReplyMessageMediaAttachment.h @@ -0,0 +1,10 @@ +#import + +@class TGBridgeMessage; + +@interface TGBridgeReplyMessageMediaAttachment : TGBridgeMediaAttachment + +@property (nonatomic, assign) int32_t mid; +@property (nonatomic, strong) TGBridgeMessage *message; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeSubscriptions.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeSubscriptions.h new file mode 100644 index 00000000..609c2d01 --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeSubscriptions.h @@ -0,0 +1,268 @@ +#import + +#import +#import + +@class TGBridgeMediaAttachment; +@class TGBridgeImageMediaAttachment; +@class TGBridgeVideoMediaAttachment; +@class TGBridgeDocumentMediaAttachment; +@class TGBridgeLocationMediaAttachment; +@class TGBridgePeerNotificationSettings; + +@interface TGBridgeAudioSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) TGBridgeMediaAttachment *attachment; +@property (nonatomic, readonly) int64_t peerId; +@property (nonatomic, readonly) int32_t messageId; + +- (instancetype)initWithAttachment:(TGBridgeMediaAttachment *)attachment peerId:(int64_t)peerId messageId:(int32_t)messageId; + +@end + + +@interface TGBridgeAudioSentSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t conversationId; + +- (instancetype)initWithConversationId:(int64_t)conversationId; + +@end + + +@interface TGBridgeChatListSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int32_t limit; + +- (instancetype)initWithLimit:(int32_t)limit; + +@end + + +@interface TGBridgeChatMessageListSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t peerId; +@property (nonatomic, readonly) int32_t atMessageId; +@property (nonatomic, readonly) NSUInteger rangeMessageCount; + +- (instancetype)initWithPeerId:(int64_t)peerId atMessageId:(int32_t)messageId rangeMessageCount:(NSUInteger)rangeMessageCount; + +@end + + +@interface TGBridgeChatMessageSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t peerId; +@property (nonatomic, readonly) int32_t messageId; + +- (instancetype)initWithPeerId:(int64_t)peerId messageId:(int32_t)messageId; + +@end + + +@interface TGBridgeReadChatMessageListSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t peerId; +@property (nonatomic, readonly) int32_t messageId; + +- (instancetype)initWithPeerId:(int64_t)peerId messageId:(int32_t)messageId; + +@end + + +@interface TGBridgeContactsSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) NSString *query; + +- (instancetype)initWithQuery:(NSString *)query; + +@end + + +@interface TGBridgeConversationSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t peerId; + +- (instancetype)initWithPeerId:(int64_t)peerId; + +@end + + +@interface TGBridgeNearbyVenuesSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) CLLocationCoordinate2D coordinate; +@property (nonatomic, readonly) int32_t limit; + +- (instancetype)initWithCoordinate:(CLLocationCoordinate2D)coordinate limit:(int32_t)limit; + +@end + + +@interface TGBridgeMediaThumbnailSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t peerId; +@property (nonatomic, readonly) int32_t messageId; +@property (nonatomic, readonly) CGSize size; +@property (nonatomic, readonly) bool notification; + +- (instancetype)initWithPeerId:(int64_t)peerId messageId:(int32_t)messageId size:(CGSize)size notification:(bool)notification; + +@end + + +typedef NS_ENUM(NSUInteger, TGBridgeMediaAvatarType) { + TGBridgeMediaAvatarTypeSmall, + TGBridgeMediaAvatarTypeProfile, + TGBridgeMediaAvatarTypeLarge +}; + +@interface TGBridgeMediaAvatarSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t peerId; +@property (nonatomic, readonly) NSString *url; +@property (nonatomic, readonly) TGBridgeMediaAvatarType type; + +- (instancetype)initWithPeerId:(int64_t)peerId url:(NSString *)url type:(TGBridgeMediaAvatarType)type; + +@end + +@interface TGBridgeMediaStickerSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t documentId; +@property (nonatomic, readonly) int64_t stickerPackId; +@property (nonatomic, readonly) int64_t stickerPackAccessHash; +@property (nonatomic, readonly) int64_t stickerPeerId; +@property (nonatomic, readonly) int32_t stickerMessageId; +@property (nonatomic, readonly) bool notification; +@property (nonatomic, readonly) CGSize size; + +- (instancetype)initWithDocumentId:(int64_t)documentId stickerPackId:(int64_t)stickerPackId stickerPackAccessHash:(int64_t)stickerPackAccessHash stickerPeerId:(int64_t)stickerPeerId stickerMessageId:(int32_t)stickerMessageId notification:(bool)notification size:(CGSize)size; + +@end + + +@interface TGBridgePeerSettingsSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t peerId; + +- (instancetype)initWithPeerId:(int64_t)peerId; + +@end + +@interface TGBridgePeerUpdateNotificationSettingsSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t peerId; + +- (instancetype)initWithPeerId:(int64_t)peerId; + +@end + +@interface TGBridgePeerUpdateBlockStatusSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t peerId; +@property (nonatomic, readonly) bool blocked; + +- (instancetype)initWithPeerId:(int64_t)peerId blocked:(bool)blocked; + +@end + + +@interface TGBridgeRemoteSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t peerId; +@property (nonatomic, readonly) int32_t messageId; +@property (nonatomic, readonly) int32_t type; +@property (nonatomic, readonly) bool autoPlay; + +- (instancetype)initWithPeerId:(int64_t)peerId messageId:(int32_t)messageId type:(int32_t)type autoPlay:(bool)autoPlay; + +@end + + +@interface TGBridgeSendTextMessageSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t peerId; +@property (nonatomic, readonly) NSString *text; +@property (nonatomic, readonly) int32_t replyToMid; + +- (instancetype)initWithPeerId:(int64_t)peerId text:(NSString *)text replyToMid:(int32_t)replyToMid; + +@end + + +@interface TGBridgeSendStickerMessageSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t peerId; +@property (nonatomic, readonly) TGBridgeDocumentMediaAttachment *document; +@property (nonatomic, readonly) int32_t replyToMid; + +- (instancetype)initWithPeerId:(int64_t)peerId document:(TGBridgeDocumentMediaAttachment *)document replyToMid:(int32_t)replyToMid; + +@end + + +@interface TGBridgeSendLocationMessageSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t peerId; +@property (nonatomic, readonly) TGBridgeLocationMediaAttachment *location; +@property (nonatomic, readonly) int32_t replyToMid; + +- (instancetype)initWithPeerId:(int64_t)peerId location:(TGBridgeLocationMediaAttachment *)location replyToMid:(int32_t)replyToMid; + +@end + + +@interface TGBridgeSendForwardedMessageSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t peerId; +@property (nonatomic, readonly) int32_t messageId; +@property (nonatomic, readonly) int64_t targetPeerId; + +- (instancetype)initWithPeerId:(int64_t)peerId messageId:(int32_t)messageId targetPeerId:(int64_t)targetPeerId; + +@end + + +@interface TGBridgeStateSubscription : TGBridgeSubscription + +@end + + +@interface TGBridgeStickerPacksSubscription : TGBridgeSubscription + +@end + + +@interface TGBridgeRecentStickersSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int32_t limit; + +- (instancetype)initWithLimit:(int32_t)limit; + +@end + + +@interface TGBridgeUserInfoSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) NSArray *userIds; + +- (instancetype)initWithUserIds:(NSArray *)userIds; + +@end + + +@interface TGBridgeUserBotInfoSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) NSArray *userIds; + +- (instancetype)initWithUserIds:(NSArray *)userIds; + +@end + +@interface TGBridgeBotReplyMarkupSubscription : TGBridgeSubscription + +@property (nonatomic, readonly) int64_t peerId; + +- (instancetype)initWithPeerId:(int64_t)peerId; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeUnsupportedMediaAttachment.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeUnsupportedMediaAttachment.h new file mode 100644 index 00000000..5b81ed1f --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeUnsupportedMediaAttachment.h @@ -0,0 +1,9 @@ +#import + +@interface TGBridgeUnsupportedMediaAttachment : TGBridgeMediaAttachment + +@property (nonatomic, strong) NSString *compactTitle; +@property (nonatomic, strong) NSString *title; +@property (nonatomic, strong) NSString *subtitle; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeUser.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeUser.h new file mode 100644 index 00000000..632d934d --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeUser.h @@ -0,0 +1,59 @@ +#import + +@class TGBridgeBotInfo; +@class TGBridgeUserChange; + +typedef NS_ENUM(NSUInteger, TGBridgeUserKind) { + TGBridgeUserKindGeneric, + TGBridgeUserKindBot, + TGBridgeUserKindSmartBot +}; + +typedef NS_ENUM(NSUInteger, TGBridgeBotKind) { + TGBridgeBotKindGeneric, + TGBridgeBotKindPrivate +}; + +@interface TGBridgeUser : NSObject + +@property (nonatomic) int64_t identifier; +@property (nonatomic, strong) NSString *firstName; +@property (nonatomic, strong) NSString *lastName; +@property (nonatomic, strong) NSString *userName; +@property (nonatomic, strong) NSString *phoneNumber; +@property (nonatomic, strong) NSString *prettyPhoneNumber; +@property (nonatomic, strong) NSString *about; + +@property (nonatomic) bool online; +@property (nonatomic) NSTimeInterval lastSeen; + +@property (nonatomic, strong) NSString *photoSmall; +@property (nonatomic, strong) NSString *photoBig; + +@property (nonatomic) TGBridgeUserKind kind; +@property (nonatomic) TGBridgeBotKind botKind; +@property (nonatomic) int32_t botVersion; + +@property (nonatomic) bool verified; + +@property (nonatomic) int32_t userVersion; + +- (NSString *)displayName; +- (TGBridgeUserChange *)changeFromUser:(TGBridgeUser *)user; +- (TGBridgeUser *)userByApplyingChange:(TGBridgeUserChange *)change; + +- (bool)isBot; + +@end + + +@interface TGBridgeUserChange : NSObject + +@property (nonatomic, readonly) int32_t userIdentifier; +@property (nonatomic, readonly) NSDictionary *fields; + +- (instancetype)initWithUserIdentifier:(int32_t)userIdentifier fields:(NSDictionary *)fields; + +@end + +extern NSString *const TGBridgeUsersDictionaryKey; diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeVideoMediaAttachment.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeVideoMediaAttachment.h new file mode 100644 index 00000000..8d54027c --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeVideoMediaAttachment.h @@ -0,0 +1,12 @@ +#import + +#import + +@interface TGBridgeVideoMediaAttachment : TGBridgeMediaAttachment + +@property (nonatomic, assign) int64_t videoId; +@property (nonatomic, assign) int32_t duration; +@property (nonatomic, assign) CGSize dimensions; +@property (nonatomic, assign) bool round; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeWebPageMediaAttachment.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeWebPageMediaAttachment.h new file mode 100644 index 00000000..6e20ee3f --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/TGBridgeWebPageMediaAttachment.h @@ -0,0 +1,23 @@ +#import + +#import + +@class TGBridgeImageMediaAttachment; + +@interface TGBridgeWebPageMediaAttachment : TGBridgeMediaAttachment + +@property (nonatomic, assign) int64_t webPageId; +@property (nonatomic, strong) NSString *url; +@property (nonatomic, strong) NSString *displayUrl; +@property (nonatomic, strong) NSString *pageType; +@property (nonatomic, strong) NSString *siteName; +@property (nonatomic, strong) NSString *title; +@property (nonatomic, strong) NSString *pageDescription; +@property (nonatomic, strong) TGBridgeImageMediaAttachment *photo; +@property (nonatomic, strong) NSString *embedUrl; +@property (nonatomic, strong) NSString *embedType; +@property (nonatomic, assign) CGSize embedSize; +@property (nonatomic, strong) NSNumber *duration; +@property (nonatomic, strong) NSString *author; + +@end diff --git a/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/WatchCommon.h b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/WatchCommon.h new file mode 100644 index 00000000..27b37d2d --- /dev/null +++ b/submodules/WatchCommon/Host/PublicHeaders/WatchCommon/WatchCommon.h @@ -0,0 +1,29 @@ +#import + +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeActionMediaAttachment.m b/submodules/WatchCommon/Host/Sources/TGBridgeActionMediaAttachment.m new file mode 100644 index 00000000..763cf8a1 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeActionMediaAttachment.m @@ -0,0 +1,33 @@ +#import "TGBridgeActionMediaAttachment.h" +#import "TGBridgeImageMediaAttachment.h" + +const NSInteger TGBridgeActionMediaAttachmentType = 0x1167E28B; + +NSString *const TGBridgeActionMediaTypeKey = @"actionType"; +NSString *const TGBridgeActionMediaDataKey = @"actionData"; + +@implementation TGBridgeActionMediaAttachment + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _actionType = (TGBridgeMessageAction)[aDecoder decodeInt32ForKey:TGBridgeActionMediaTypeKey]; + _actionData = [aDecoder decodeObjectForKey:TGBridgeActionMediaDataKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt32:self.actionType forKey:TGBridgeActionMediaTypeKey]; + [aCoder encodeObject:self.actionData forKey:TGBridgeActionMediaDataKey]; +} + ++ (NSInteger)mediaType +{ + return TGBridgeActionMediaAttachmentType; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeAudioMediaAttachment.m b/submodules/WatchCommon/Host/Sources/TGBridgeAudioMediaAttachment.m new file mode 100644 index 00000000..3f4096a8 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeAudioMediaAttachment.m @@ -0,0 +1,65 @@ +#import "TGBridgeAudioMediaAttachment.h" + +const NSInteger TGBridgeAudioMediaAttachmentType = 0x3A0E7A32; + +NSString *const TGBridgeAudioMediaAudioIdKey = @"audioId"; +NSString *const TGBridgeAudioMediaAccessHashKey = @"accessHash"; +NSString *const TGBridgeAudioMediaLocalIdKey = @"localId"; +NSString *const TGBridgeAudioMediaDatacenterIdKey = @"datacenterId"; +NSString *const TGBridgeAudioMediaDurationKey = @"duration"; +NSString *const TGBridgeAudioMediaFileSizeKey = @"fileSize"; + +@implementation TGBridgeAudioMediaAttachment + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _audioId = [aDecoder decodeInt64ForKey:TGBridgeAudioMediaAudioIdKey]; + _accessHash = [aDecoder decodeInt64ForKey:TGBridgeAudioMediaAccessHashKey]; + _localAudioId = [aDecoder decodeInt64ForKey:TGBridgeAudioMediaLocalIdKey]; + _datacenterId = [aDecoder decodeInt32ForKey:TGBridgeAudioMediaDatacenterIdKey]; + _duration = [aDecoder decodeInt32ForKey:TGBridgeAudioMediaDurationKey]; + _fileSize = [aDecoder decodeInt32ForKey:TGBridgeAudioMediaFileSizeKey]; + } + return self; +} + +- (void)encodeWithCoder:(nonnull NSCoder *)aCoder +{ + [aCoder encodeInt64:self.audioId forKey:TGBridgeAudioMediaAudioIdKey]; + [aCoder encodeInt64:self.accessHash forKey:TGBridgeAudioMediaAccessHashKey]; + [aCoder encodeInt64:self.localAudioId forKey:TGBridgeAudioMediaLocalIdKey]; + [aCoder encodeInt32:self.datacenterId forKey:TGBridgeAudioMediaDatacenterIdKey]; + [aCoder encodeInt32:self.duration forKey:TGBridgeAudioMediaDurationKey]; + [aCoder encodeInt32:self.fileSize forKey:TGBridgeAudioMediaFileSizeKey]; +} + +- (int64_t)identifier +{ + if (self.localAudioId != 0) + return self.localAudioId; + + return self.audioId; +} + +- (BOOL)isEqual:(id)object +{ + if (object == self) + return YES; + + if (!object || ![object isKindOfClass:[self class]]) + return NO; + + TGBridgeAudioMediaAttachment *audio = (TGBridgeAudioMediaAttachment *)object; + + return (self.audioId == audio.audioId || self.localAudioId == audio.localAudioId); +} + ++ (NSInteger)mediaType +{ + return TGBridgeAudioMediaAttachmentType; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeBotCommandInfo.m b/submodules/WatchCommon/Host/Sources/TGBridgeBotCommandInfo.m new file mode 100644 index 00000000..0f1e0058 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeBotCommandInfo.m @@ -0,0 +1,25 @@ +#import "TGBridgeBotCommandInfo.h" + +NSString *const TGBridgeBotCommandInfoCommandKey = @"command"; +NSString *const TGBridgeBotCommandDescriptionKey = @"commandDescription"; + +@implementation TGBridgeBotCommandInfo + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _command = [aDecoder decodeObjectForKey:TGBridgeBotCommandInfoCommandKey]; + _commandDescription = [aDecoder decodeObjectForKey:TGBridgeBotCommandDescriptionKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeObject:self.command forKey:TGBridgeBotCommandInfoCommandKey]; + [aCoder encodeObject:self.commandDescription forKey:TGBridgeBotCommandDescriptionKey]; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeBotInfo.m b/submodules/WatchCommon/Host/Sources/TGBridgeBotInfo.m new file mode 100644 index 00000000..996abb3a --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeBotInfo.m @@ -0,0 +1,25 @@ +#import "TGBridgeBotInfo.h" + +NSString *const TGBridgeBotInfoShortDescriptionKey = @"shortDescription"; +NSString *const TGBridgeBotInfoCommandListKey = @"commandList"; + +@implementation TGBridgeBotInfo + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _shortDescription = [aDecoder decodeObjectForKey:TGBridgeBotInfoShortDescriptionKey]; + _commandList = [aDecoder decodeObjectForKey:TGBridgeBotInfoCommandListKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeObject:self.shortDescription forKey:TGBridgeBotInfoShortDescriptionKey]; + [aCoder encodeObject:self.commandList forKey:TGBridgeBotInfoCommandListKey]; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeChat.m b/submodules/WatchCommon/Host/Sources/TGBridgeChat.m new file mode 100644 index 00000000..973522fa --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeChat.m @@ -0,0 +1,148 @@ +#import "TGBridgeChat.h" +#import "TGBridgePeerIdAdapter.h" + +NSString *const TGBridgeChatIdentifierKey = @"identifier"; +NSString *const TGBridgeChatDateKey = @"date"; +NSString *const TGBridgeChatFromUidKey = @"fromUid"; +NSString *const TGBridgeChatTextKey = @"text"; +NSString *const TGBridgeChatOutgoingKey = @"outgoing"; +NSString *const TGBridgeChatUnreadKey = @"unread"; +NSString *const TGBridgeChatMediaKey = @"media"; +NSString *const TGBridgeChatUnreadCountKey = @"unreadCount"; +NSString *const TGBridgeChatGroupTitleKey = @"groupTitle"; +NSString *const TGBridgeChatGroupPhotoSmallKey = @"groupPhotoSmall"; +NSString *const TGBridgeChatGroupPhotoBigKey = @"groupPhotoBig"; +NSString *const TGBridgeChatIsGroupKey = @"isGroup"; +NSString *const TGBridgeChatHasLeftGroupKey = @"hasLeftGroup"; +NSString *const TGBridgeChatIsKickedFromGroupKey = @"isKickedFromGroup"; +NSString *const TGBridgeChatIsChannelKey = @"isChannel"; +NSString *const TGBridgeChatIsChannelGroupKey = @"isChannelGroup"; +NSString *const TGBridgeChatUserNameKey = @"userName"; +NSString *const TGBridgeChatAboutKey = @"about"; +NSString *const TGBridgeChatVerifiedKey = @"verified"; +NSString *const TGBridgeChatGroupParticipantsCountKey = @"participantsCount"; +NSString *const TGBridgeChatGroupParticipantsKey = @"participants"; +NSString *const TGBridgeChatDeliveryStateKey = @"deliveryState"; +NSString *const TGBridgeChatDeliveryErrorKey = @"deliveryError"; + +NSString *const TGBridgeChatKey = @"chat"; +NSString *const TGBridgeChatsArrayKey = @"chats"; + +@implementation TGBridgeChat + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _identifier = [aDecoder decodeInt64ForKey:TGBridgeChatIdentifierKey]; + _date = [aDecoder decodeDoubleForKey:TGBridgeChatDateKey]; + _fromUid = [aDecoder decodeInt32ForKey:TGBridgeChatFromUidKey]; + _text = [aDecoder decodeObjectForKey:TGBridgeChatTextKey]; + _outgoing = [aDecoder decodeBoolForKey:TGBridgeChatOutgoingKey]; + _unread = [aDecoder decodeBoolForKey:TGBridgeChatUnreadKey]; + _unreadCount = [aDecoder decodeInt32ForKey:TGBridgeChatUnreadCountKey]; + _deliveryState = [aDecoder decodeInt32ForKey:TGBridgeChatDeliveryStateKey]; + _deliveryError = [aDecoder decodeBoolForKey:TGBridgeChatDeliveryErrorKey]; + _media = [aDecoder decodeObjectForKey:TGBridgeChatMediaKey]; + + _groupTitle = [aDecoder decodeObjectForKey:TGBridgeChatGroupTitleKey]; + _groupPhotoSmall = [aDecoder decodeObjectForKey:TGBridgeChatGroupPhotoSmallKey]; + _groupPhotoBig = [aDecoder decodeObjectForKey:TGBridgeChatGroupPhotoBigKey]; + _isGroup = [aDecoder decodeBoolForKey:TGBridgeChatIsGroupKey]; + _hasLeftGroup = [aDecoder decodeBoolForKey:TGBridgeChatHasLeftGroupKey]; + _isKickedFromGroup = [aDecoder decodeBoolForKey:TGBridgeChatIsKickedFromGroupKey]; + _isChannel = [aDecoder decodeBoolForKey:TGBridgeChatIsChannelKey]; + _isChannelGroup = [aDecoder decodeBoolForKey:TGBridgeChatIsChannelGroupKey]; + _userName = [aDecoder decodeObjectForKey:TGBridgeChatUserNameKey]; + _about = [aDecoder decodeObjectForKey:TGBridgeChatAboutKey]; + _verified = [aDecoder decodeBoolForKey:TGBridgeChatVerifiedKey]; + _participantsCount = [aDecoder decodeInt32ForKey:TGBridgeChatGroupParticipantsCountKey]; + _participants = [aDecoder decodeObjectForKey:TGBridgeChatGroupParticipantsKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.identifier forKey:TGBridgeChatIdentifierKey]; + [aCoder encodeDouble:self.date forKey:TGBridgeChatDateKey]; + [aCoder encodeInt32:self.fromUid forKey:TGBridgeChatFromUidKey]; + [aCoder encodeObject:self.text forKey:TGBridgeChatTextKey]; + [aCoder encodeBool:self.outgoing forKey:TGBridgeChatOutgoingKey]; + [aCoder encodeBool:self.unread forKey:TGBridgeChatUnreadKey]; + [aCoder encodeInt32:self.unreadCount forKey:TGBridgeChatUnreadCountKey]; + [aCoder encodeInt32:self.deliveryState forKey:TGBridgeChatDeliveryStateKey]; + [aCoder encodeBool:self.deliveryError forKey:TGBridgeChatDeliveryErrorKey]; + [aCoder encodeObject:self.media forKey:TGBridgeChatMediaKey]; + + [aCoder encodeObject:self.groupTitle forKey:TGBridgeChatGroupTitleKey]; + [aCoder encodeObject:self.groupPhotoSmall forKey:TGBridgeChatGroupPhotoSmallKey]; + [aCoder encodeObject:self.groupPhotoBig forKey:TGBridgeChatGroupPhotoBigKey]; + + [aCoder encodeBool:self.isGroup forKey:TGBridgeChatIsGroupKey]; + [aCoder encodeBool:self.hasLeftGroup forKey:TGBridgeChatHasLeftGroupKey]; + [aCoder encodeBool:self.isKickedFromGroup forKey:TGBridgeChatIsKickedFromGroupKey]; + + [aCoder encodeBool:self.isChannel forKey:TGBridgeChatIsChannelKey]; + [aCoder encodeBool:self.isChannelGroup forKey:TGBridgeChatIsChannelGroupKey]; + [aCoder encodeObject:self.userName forKey:TGBridgeChatUserNameKey]; + [aCoder encodeObject:self.about forKey:TGBridgeChatAboutKey]; + [aCoder encodeBool:self.verified forKey:TGBridgeChatVerifiedKey]; + + [aCoder encodeInt32:self.participantsCount forKey:TGBridgeChatGroupParticipantsCountKey]; + [aCoder encodeObject:self.participants forKey:TGBridgeChatGroupParticipantsKey]; +} + +- (NSArray *)involvedUserIds +{ + NSMutableSet *userIds = [[NSMutableSet alloc] init]; + if (!self.isGroup && !self.isChannel && self.identifier != 0) + [userIds addObject:[NSNumber numberWithLongLong:self.identifier]]; + if ((!self.isChannel || self.isChannelGroup) && self.fromUid != self.identifier && self.fromUid != 0 && !TGPeerIdIsChannel(self.fromUid) && self.fromUid > 0) + [userIds addObject:[NSNumber numberWithLongLong:self.fromUid]]; + + for (TGBridgeMediaAttachment *attachment in self.media) + { + if ([attachment isKindOfClass:[TGBridgeActionMediaAttachment class]]) + { + TGBridgeActionMediaAttachment *actionAttachment = (TGBridgeActionMediaAttachment *)attachment; + if (actionAttachment.actionData[@"uid"] != nil) + [userIds addObject:[NSNumber numberWithLongLong:[actionAttachment.actionData[@"uid"] longLongValue]]]; + } + } + + NSMutableArray *result = [[NSMutableArray alloc] init]; + for (NSNumber *object in userIds) { + [result addObject:object]; + } + return result; +} + +- (NSArray *)participantsUserIds +{ + NSMutableSet *userIds = [[NSMutableSet alloc] init]; + + for (NSNumber *uid in self.participants) { + [userIds addObject:[NSNumber numberWithLongLong:uid.longLongValue]]; + } + + NSMutableArray *result = [[NSMutableArray alloc] init]; + for (NSNumber *object in userIds) { + [result addObject:object]; + } + return result; +} + +- (BOOL)isEqual:(id)object +{ + if (object == self) + return YES; + + if (!object || ![object isKindOfClass:[self class]]) + return NO; + + return self.identifier == ((TGBridgeChat *)object).identifier; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeChatMessages.m b/submodules/WatchCommon/Host/Sources/TGBridgeChatMessages.m new file mode 100644 index 00000000..c7b64e2c --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeChatMessages.m @@ -0,0 +1,27 @@ +#import "TGBridgeChatMessages.h" +#import "TGBridgeMessage.h" + +NSString *const TGBridgeChatMessageListViewMessagesKey = @"messages"; +NSString *const TGBridgeChatMessageListViewEarlierMessageIdKey = @"earlier"; +NSString *const TGBridgeChatMessageListViewLaterMessageIdKey = @"later"; + +NSString *const TGBridgeChatMessageListViewKey = @"messageListView"; + +@implementation TGBridgeChatMessages + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _messages = [aDecoder decodeObjectForKey:TGBridgeChatMessageListViewMessagesKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeObject:self.messages forKey:TGBridgeChatMessageListViewMessagesKey]; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeCommon.m b/submodules/WatchCommon/Host/Sources/TGBridgeCommon.m new file mode 100644 index 00000000..ae0cf530 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeCommon.m @@ -0,0 +1,295 @@ +#import "TGBridgeCommon.h" + +NSString *const TGBridgeIncomingFileTypeKey = @"type"; +NSString *const TGBridgeIncomingFileIdentifierKey = @"identifier"; +NSString *const TGBridgeIncomingFileRandomIdKey = @"randomId"; +NSString *const TGBridgeIncomingFilePeerIdKey = @"peerId"; +NSString *const TGBridgeIncomingFileReplyToMidKey = @"replyToMid"; +NSString *const TGBridgeIncomingFileTypeAudio = @"audio"; +NSString *const TGBridgeIncomingFileTypeImage = @"image"; + +NSString *const TGBridgeResponseSubscriptionIdentifier = @"identifier"; +NSString *const TGBridgeResponseTypeKey = @"type"; +NSString *const TGBridgeResponseNextKey = @"next"; +NSString *const TGBridgeResponseErrorKey = @"error"; + +@implementation TGBridgeResponse + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _subscriptionIdentifier = [aDecoder decodeInt64ForKey:TGBridgeResponseSubscriptionIdentifier]; + _type = [aDecoder decodeInt32ForKey:TGBridgeResponseTypeKey]; + _next = [aDecoder decodeObjectForKey:TGBridgeResponseNextKey]; + _error = [aDecoder decodeObjectForKey:TGBridgeResponseErrorKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.subscriptionIdentifier forKey:TGBridgeResponseSubscriptionIdentifier]; + [aCoder encodeInt32:self.type forKey:TGBridgeResponseTypeKey]; + [aCoder encodeObject:self.next forKey:TGBridgeResponseNextKey]; + [aCoder encodeObject:self.error forKey:TGBridgeResponseErrorKey]; +} + ++ (TGBridgeResponse *)single:(id)next forSubscription:(TGBridgeSubscription *)subscription +{ + TGBridgeResponse *response = [[TGBridgeResponse alloc] init]; + response->_subscriptionIdentifier = subscription.identifier; + response->_type = TGBridgeResponseTypeNext; + response->_next = next; + return response; +} + ++ (TGBridgeResponse *)fail:(id)error forSubscription:(TGBridgeSubscription *)subscription +{ + TGBridgeResponse *response = [[TGBridgeResponse alloc] init]; + response->_subscriptionIdentifier = subscription.identifier; + response->_type = TGBridgeResponseTypeFailed; + response->_error = error; + return response; +} + ++ (TGBridgeResponse *)completeForSubscription:(TGBridgeSubscription *)subscription +{ + TGBridgeResponse *response = [[TGBridgeResponse alloc] init]; + response->_subscriptionIdentifier = subscription.identifier; + response->_type = TGBridgeResponseTypeCompleted; + return response; +} + +@end + + +NSString *const TGBridgeSubscriptionIdentifierKey = @"identifier"; +NSString *const TGBridgeSubscriptionNameKey = @"name"; +NSString *const TGBridgeSubscriptionParametersKey = @"parameters"; + +@implementation TGBridgeSubscription + +- (instancetype)init +{ + self = [super init]; + if (self != nil) + { + int64_t randomId = 0; + arc4random_buf(&randomId, sizeof(int64_t)); + _identifier = randomId; + _name = [[self class] subscriptionName]; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _identifier = [aDecoder decodeInt64ForKey:TGBridgeSubscriptionIdentifierKey]; + _name = [aDecoder decodeObjectForKey:TGBridgeSubscriptionNameKey]; + [self _unserializeParametersWithCoder:aDecoder]; + } + return self; +} + +- (bool)synchronous +{ + return false; +} + +- (bool)renewable +{ + return true; +} + +- (bool)dropPreviouslyQueued +{ + return false; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)__unused aCoder +{ + +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)__unused aDecoder +{ + +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.identifier forKey:TGBridgeSubscriptionIdentifierKey]; + [aCoder encodeObject:self.name forKey:TGBridgeSubscriptionNameKey]; + [self _serializeParametersWithCoder:aCoder]; +} + ++ (NSString *)subscriptionName +{ + return nil; +} + +@end + + +@implementation TGBridgeDisposal + +- (instancetype)initWithIdentifier:(int64_t)identifier +{ + self = [super init]; + if (self != nil) + { + _identifier = identifier; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _identifier = [aDecoder decodeInt64ForKey:TGBridgeSubscriptionIdentifierKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.identifier forKey:TGBridgeSubscriptionIdentifierKey]; +} + +@end + +NSString *const TGBridgeFileDataKey = @"data"; +NSString *const TGBridgeFileMetadataKey = @"metadata"; + +@implementation TGBridgeFile + +- (instancetype)initWithData:(NSData *)data metadata:(NSDictionary *)metadata +{ + self = [super init]; + if (self != nil) + { + _data = data; + _metadata = metadata; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _data = [aDecoder decodeObjectForKey:TGBridgeFileDataKey]; + _metadata = [aDecoder decodeObjectForKey:TGBridgeFileMetadataKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeObject:self.data forKey:TGBridgeFileDataKey]; + [aCoder encodeObject:self.metadata forKey:TGBridgeFileMetadataKey]; +} + +@end + + +NSString *const TGBridgeSessionIdKey = @"sessionId"; + +@implementation TGBridgePing + +- (instancetype)initWithSessionId:(int32_t)sessionId +{ + self = [super init]; + if (self != nil) + { + _sessionId = sessionId; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _sessionId = [aDecoder decodeInt32ForKey:TGBridgeSessionIdKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt32:self.sessionId forKey:TGBridgeSessionIdKey]; +} + +@end + + +@implementation TGBridgeSubscriptionListRequest + +- (instancetype)initWithSessionId:(int32_t)sessionId +{ + self = [super init]; + if (self != nil) + { + _sessionId = sessionId; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _sessionId = [aDecoder decodeInt32ForKey:TGBridgeSessionIdKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt32:self.sessionId forKey:TGBridgeSessionIdKey]; +} + +@end + + +NSString *const TGBridgeSubscriptionListSubscriptionsKey = @"subscriptions"; + +@implementation TGBridgeSubscriptionList + +- (instancetype)initWithArray:(NSArray *)array +{ + self = [super init]; + if (self != nil) + { + _subscriptions = array; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _subscriptions = [aDecoder decodeObjectForKey:TGBridgeSubscriptionListSubscriptionsKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeObject:self.subscriptions forKey:TGBridgeSubscriptionListSubscriptionsKey]; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeContactMediaAttachment.m b/submodules/WatchCommon/Host/Sources/TGBridgeContactMediaAttachment.m new file mode 100644 index 00000000..4b2f482e --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeContactMediaAttachment.m @@ -0,0 +1,60 @@ +#import "TGBridgeContactMediaAttachment.h" + +//#import "../Extension/TGStringUtils.h" + +const NSInteger TGBridgeContactMediaAttachmentType = 0xB90A5663; + +NSString *const TGBridgeContactMediaUidKey = @"uid"; +NSString *const TGBridgeContactMediaFirstNameKey = @"firstName"; +NSString *const TGBridgeContactMediaLastNameKey = @"lastName"; +NSString *const TGBridgeContactMediaPhoneNumberKey = @"phoneNumber"; +NSString *const TGBridgeContactMediaPrettyPhoneNumberKey = @"prettyPhoneNumber"; + +@implementation TGBridgeContactMediaAttachment + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _uid = [aDecoder decodeInt32ForKey:TGBridgeContactMediaUidKey]; + _firstName = [aDecoder decodeObjectForKey:TGBridgeContactMediaFirstNameKey]; + _lastName = [aDecoder decodeObjectForKey:TGBridgeContactMediaLastNameKey]; + _phoneNumber = [aDecoder decodeObjectForKey:TGBridgeContactMediaPhoneNumberKey]; + _prettyPhoneNumber = [aDecoder decodeObjectForKey:TGBridgeContactMediaPrettyPhoneNumberKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt32:self.uid forKey:TGBridgeContactMediaUidKey]; + [aCoder encodeObject:self.firstName forKey:TGBridgeContactMediaFirstNameKey]; + [aCoder encodeObject:self.lastName forKey:TGBridgeContactMediaLastNameKey]; + [aCoder encodeObject:self.phoneNumber forKey:TGBridgeContactMediaPhoneNumberKey]; + [aCoder encodeObject:self.prettyPhoneNumber forKey:TGBridgeContactMediaPrettyPhoneNumberKey]; +} + +- (NSString *)displayName +{ + NSString *firstName = self.firstName; + NSString *lastName = self.lastName; + + if (firstName != nil && firstName.length != 0 && lastName != nil && lastName.length != 0) + { + return [[NSString alloc] initWithFormat:@"%@ %@", firstName, lastName]; + } + else if (firstName != nil && firstName.length != 0) + return firstName; + else if (lastName != nil && lastName.length != 0) + return lastName; + + return @""; +} + ++ (NSInteger)mediaType +{ + return TGBridgeContactMediaAttachmentType; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeContext.m b/submodules/WatchCommon/Host/Sources/TGBridgeContext.m new file mode 100644 index 00000000..4b0600e2 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeContext.m @@ -0,0 +1,101 @@ +#import "TGBridgeContext.h" +#import "TGBridgeCommon.h" +//#import "TGWatchCommon.h" + +NSString *const TGBridgeContextAuthorized = @"authorized"; +NSString *const TGBridgeContextUserId = @"userId"; +NSString *const TGBridgeContextMicAccessAllowed = @"micAccessAllowed"; +NSString *const TGBridgeContextStartupData = @"startupData"; +NSString *const TGBridgeContextStartupDataVersion = @"version"; + +@implementation TGBridgeContext + +- (instancetype)initWithDictionary:(NSDictionary *)dictionary +{ + self = [super init]; + if (self != nil) + { + _authorized = [dictionary[TGBridgeContextAuthorized] boolValue]; + _userId = (int32_t)[dictionary[TGBridgeContextUserId] intValue]; + _micAccessAllowed = [dictionary[TGBridgeContextMicAccessAllowed] boolValue]; + + if (dictionary[TGBridgeContextStartupData] != nil) { + _preheatData = [NSKeyedUnarchiver unarchiveObjectWithData:dictionary[TGBridgeContextStartupData]]; + _preheatVersion = [dictionary[TGBridgeContextStartupDataVersion] integerValue]; + } + } + return self; +} + +- (NSDictionary *)dictionary +{ + NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; + dictionary[TGBridgeContextAuthorized] = @(self.authorized); + dictionary[TGBridgeContextUserId] = @(self.userId); + dictionary[TGBridgeContextMicAccessAllowed] = @(self.micAccessAllowed); + if (self.preheatData != nil) { + dictionary[TGBridgeContextStartupData] = [NSKeyedArchiver archivedDataWithRootObject:self.preheatData]; + dictionary[TGBridgeContextStartupDataVersion] = @(self.preheatVersion); + } + return dictionary; +} + +- (TGBridgeContext *)updatedWithAuthorized:(bool)authorized peerId:(int32_t)peerId +{ + TGBridgeContext *context = [[TGBridgeContext alloc] init]; + context->_authorized = authorized; + context->_userId = peerId; + context->_micAccessAllowed = self.micAccessAllowed; + if (authorized) { + context->_preheatData = self.preheatData; + context->_preheatVersion = self.preheatVersion; + } + return context; +} + +- (TGBridgeContext *)updatedWithPreheatData:(NSDictionary *)data +{ + TGBridgeContext *context = [[TGBridgeContext alloc] init]; + context->_authorized = self.authorized; + context->_userId = self.userId; + context->_micAccessAllowed = self.micAccessAllowed; + if (data != nil) { + context->_preheatData = data; + context->_preheatVersion = (int32_t)[NSDate date].timeIntervalSinceReferenceDate; + } + return context; +} + +- (TGBridgeContext *)updatedWithMicAccessAllowed:(bool)allowed +{ + TGBridgeContext *context = [[TGBridgeContext alloc] init]; + context->_authorized = self.authorized; + context->_userId = self.userId; + context->_micAccessAllowed = allowed; + context->_preheatData = self.preheatData; + context->_preheatVersion = self.preheatVersion; + return context; +} + +- (BOOL)isEqual:(id)object +{ + if (object == self) + return true; + + if (!object || ![object isKindOfClass:[self class]]) + return false; + + TGBridgeContext *context = (TGBridgeContext *)object; + if (context.authorized != self.authorized) + return false; + if (context.userId != self.userId) + return false; + if (context.micAccessAllowed != self.micAccessAllowed) + return false; + if (context.preheatVersion != self.preheatVersion) + return false; + + return true; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeDocumentMediaAttachment.m b/submodules/WatchCommon/Host/Sources/TGBridgeDocumentMediaAttachment.m new file mode 100644 index 00000000..8d492ae7 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeDocumentMediaAttachment.m @@ -0,0 +1,84 @@ +#import "TGBridgeDocumentMediaAttachment.h" + +const NSInteger TGBridgeDocumentMediaAttachmentType = 0xE6C64318; + +NSString *const TGBridgeDocumentMediaDocumentIdKey = @"documentId"; +NSString *const TGBridgeDocumentMediaLocalDocumentIdKey = @"localDocumentId"; +NSString *const TGBridgeDocumentMediaFileSizeKey = @"fileSize"; +NSString *const TGBridgeDocumentMediaFileNameKey = @"fileName"; +NSString *const TGBridgeDocumentMediaImageSizeKey = @"imageSize"; +NSString *const TGBridgeDocumentMediaAnimatedKey = @"animated"; +NSString *const TGBridgeDocumentMediaStickerKey = @"sticker"; +NSString *const TGBridgeDocumentMediaStickerAltKey = @"stickerAlt"; +NSString *const TGBridgeDocumentMediaStickerPackIdKey = @"stickerPackId"; +NSString *const TGBridgeDocumentMediaStickerPackAccessHashKey = @"stickerPackAccessHash"; +NSString *const TGBridgeDocumentMediaAudioKey = @"audio"; +NSString *const TGBridgeDocumentMediaAudioTitleKey = @"title"; +NSString *const TGBridgeDocumentMediaAudioPerformerKey = @"performer"; +NSString *const TGBridgeDocumentMediaAudioVoice = @"voice"; +NSString *const TGBridgeDocumentMediaAudioDuration = @"duration"; + +@implementation TGBridgeDocumentMediaAttachment + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _documentId = [aDecoder decodeInt64ForKey:TGBridgeDocumentMediaDocumentIdKey]; + _localDocumentId = [aDecoder decodeInt64ForKey:TGBridgeDocumentMediaLocalDocumentIdKey]; + _fileSize = [aDecoder decodeInt32ForKey:TGBridgeDocumentMediaFileSizeKey]; + _fileName = [aDecoder decodeObjectForKey:TGBridgeDocumentMediaFileNameKey]; + _imageSize = [aDecoder decodeObjectForKey:TGBridgeDocumentMediaImageSizeKey]; + _isAnimated = [aDecoder decodeBoolForKey:TGBridgeDocumentMediaAnimatedKey]; + _isSticker = [aDecoder decodeBoolForKey:TGBridgeDocumentMediaStickerKey]; + _stickerAlt = [aDecoder decodeObjectForKey:TGBridgeDocumentMediaStickerAltKey]; + _stickerPackId = [aDecoder decodeInt64ForKey:TGBridgeDocumentMediaStickerPackIdKey]; + _stickerPackAccessHash = [aDecoder decodeInt64ForKey:TGBridgeDocumentMediaStickerPackAccessHashKey]; + _isAudio = [aDecoder decodeBoolForKey:TGBridgeDocumentMediaAudioKey]; + _title = [aDecoder decodeObjectForKey:TGBridgeDocumentMediaAudioTitleKey]; + _performer = [aDecoder decodeObjectForKey:TGBridgeDocumentMediaAudioPerformerKey]; + _isVoice = [aDecoder decodeBoolForKey:TGBridgeDocumentMediaAudioVoice]; + _duration = [aDecoder decodeInt32ForKey:TGBridgeDocumentMediaAudioDuration]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.documentId forKey:TGBridgeDocumentMediaDocumentIdKey]; + [aCoder encodeInt64:self.localDocumentId forKey:TGBridgeDocumentMediaLocalDocumentIdKey]; + [aCoder encodeInt32:self.fileSize forKey:TGBridgeDocumentMediaFileSizeKey]; + [aCoder encodeObject:self.fileName forKey:TGBridgeDocumentMediaFileNameKey]; + [aCoder encodeObject:self.imageSize forKey:TGBridgeDocumentMediaImageSizeKey]; + [aCoder encodeBool:self.isAnimated forKey:TGBridgeDocumentMediaAnimatedKey]; + [aCoder encodeBool:self.isSticker forKey:TGBridgeDocumentMediaStickerKey]; + [aCoder encodeObject:self.stickerAlt forKey:TGBridgeDocumentMediaStickerAltKey]; + [aCoder encodeInt64:self.stickerPackId forKey:TGBridgeDocumentMediaStickerPackIdKey]; + [aCoder encodeInt64:self.stickerPackAccessHash forKey:TGBridgeDocumentMediaStickerPackAccessHashKey]; + [aCoder encodeBool:self.isAudio forKey:TGBridgeDocumentMediaAudioKey]; + [aCoder encodeObject:self.title forKey:TGBridgeDocumentMediaAudioTitleKey]; + [aCoder encodeObject:self.performer forKey:TGBridgeDocumentMediaAudioPerformerKey]; + [aCoder encodeBool:self.isVoice forKey:TGBridgeDocumentMediaAudioVoice]; + [aCoder encodeInt32:self.duration forKey:TGBridgeDocumentMediaAudioDuration]; +} + +- (BOOL)isEqual:(id)object +{ + if (object == self) + return YES; + + if (!object || ![object isKindOfClass:[self class]]) + return NO; + + TGBridgeDocumentMediaAttachment *document = (TGBridgeDocumentMediaAttachment *)object; + + return (self.localDocumentId == 0 && self.documentId == document.documentId) || (self.localDocumentId != 0 && self.localDocumentId == document.localDocumentId); +} + ++ (NSInteger)mediaType +{ + return TGBridgeDocumentMediaAttachmentType; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeForwardedMessageMediaAttachment.m b/submodules/WatchCommon/Host/Sources/TGBridgeForwardedMessageMediaAttachment.m new file mode 100644 index 00000000..169e261c --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeForwardedMessageMediaAttachment.m @@ -0,0 +1,35 @@ +#import "TGBridgeForwardedMessageMediaAttachment.h" + +const NSInteger TGBridgeForwardedMessageMediaAttachmentType = 0xAA1050C1; + +NSString *const TGBridgeForwardedMessageMediaPeerIdKey = @"peerId"; +NSString *const TGBridgeForwardedMessageMediaMidKey = @"mid"; +NSString *const TGBridgeForwardedMessageMediaDateKey = @"date"; + +@implementation TGBridgeForwardedMessageMediaAttachment + +- (nullable instancetype)initWithCoder:(nonnull NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _peerId = [aDecoder decodeInt64ForKey:TGBridgeForwardedMessageMediaPeerIdKey]; + _mid = [aDecoder decodeInt32ForKey:TGBridgeForwardedMessageMediaMidKey]; + _date = [aDecoder decodeInt32ForKey:TGBridgeForwardedMessageMediaDateKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgeForwardedMessageMediaPeerIdKey]; + [aCoder encodeInt32:self.mid forKey:TGBridgeForwardedMessageMediaMidKey]; + [aCoder encodeInt32:self.date forKey:TGBridgeForwardedMessageMediaDateKey]; +} + ++ (NSInteger)mediaType +{ + return TGBridgeForwardedMessageMediaAttachmentType; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeImageMediaAttachment.m b/submodules/WatchCommon/Host/Sources/TGBridgeImageMediaAttachment.m new file mode 100644 index 00000000..8ab5ec70 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeImageMediaAttachment.m @@ -0,0 +1,33 @@ +#import "TGBridgeImageMediaAttachment.h" +#import + +const NSInteger TGBridgeImageMediaAttachmentType = 0x269BD8A8; + +NSString *const TGBridgeImageMediaImageIdKey = @"imageId"; +NSString *const TGBridgeImageMediaDimensionsKey = @"dimensions"; + +@implementation TGBridgeImageMediaAttachment + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _imageId = [aDecoder decodeInt64ForKey:TGBridgeImageMediaImageIdKey]; + _dimensions = [aDecoder decodeCGSizeForKey:TGBridgeImageMediaDimensionsKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.imageId forKey:TGBridgeImageMediaImageIdKey]; + [aCoder encodeCGSize:self.dimensions forKey:TGBridgeImageMediaDimensionsKey]; +} + ++ (NSInteger)mediaType +{ + return TGBridgeImageMediaAttachmentType; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeLocationMediaAttachment.m b/submodules/WatchCommon/Host/Sources/TGBridgeLocationMediaAttachment.m new file mode 100644 index 00000000..f6762eb5 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeLocationMediaAttachment.m @@ -0,0 +1,95 @@ +#import "TGBridgeLocationMediaAttachment.h" + +const NSInteger TGBridgeLocationMediaAttachmentType = 0x0C9ED06E; + +NSString *const TGBridgeLocationMediaLatitudeKey = @"lat"; +NSString *const TGBridgeLocationMediaLongitudeKey = @"lon"; +NSString *const TGBridgeLocationMediaVenueKey = @"venue"; + +NSString *const TGBridgeVenueTitleKey = @"title"; +NSString *const TGBridgeVenueAddressKey = @"address"; +NSString *const TGBridgeVenueProviderKey = @"provider"; +NSString *const TGBridgeVenueIdKey = @"venueId"; + +@implementation TGBridgeVenueAttachment + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _title = [aDecoder decodeObjectForKey:TGBridgeVenueTitleKey]; + _address = [aDecoder decodeObjectForKey:TGBridgeVenueAddressKey]; + _provider = [aDecoder decodeObjectForKey:TGBridgeVenueProviderKey]; + _venueId = [aDecoder decodeObjectForKey:TGBridgeVenueIdKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeObject:self.title forKey:TGBridgeVenueTitleKey]; + [aCoder encodeObject:self.address forKey:TGBridgeVenueAddressKey]; + [aCoder encodeObject:self.provider forKey:TGBridgeVenueProviderKey]; + [aCoder encodeObject:self.venueId forKey:TGBridgeVenueIdKey]; +} + +- (BOOL)isEqual:(id)object +{ + if (object == self) + return YES; + + if (!object || ![object isKindOfClass:[self class]]) + return NO; + + TGBridgeVenueAttachment *venue = (TGBridgeVenueAttachment *)object; + + return [self.title isEqualToString:venue.title] && [self.address isEqualToString:venue.address] && [self.provider isEqualToString:venue.provider] && [self.venueId isEqualToString:venue.venueId]; +} + +@end + + +@implementation TGBridgeLocationMediaAttachment + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _latitude = [aDecoder decodeDoubleForKey:TGBridgeLocationMediaLatitudeKey]; + _longitude = [aDecoder decodeDoubleForKey:TGBridgeLocationMediaLongitudeKey]; + _venue = [aDecoder decodeObjectForKey:TGBridgeLocationMediaVenueKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeDouble:self.latitude forKey:TGBridgeLocationMediaLatitudeKey]; + [aCoder encodeDouble:self.longitude forKey:TGBridgeLocationMediaLongitudeKey]; + [aCoder encodeObject:self.venue forKey:TGBridgeLocationMediaVenueKey]; +} + +- (BOOL)isEqual:(id)object +{ + if (object == self) + return YES; + + if (!object || ![object isKindOfClass:[self class]]) + return NO; + + TGBridgeLocationMediaAttachment *location = (TGBridgeLocationMediaAttachment *)object; + + bool equalCoord = (fabs(self.latitude - location.latitude) < DBL_EPSILON && fabs(self.longitude - location.longitude) < DBL_EPSILON); + bool equalVenue = (self.venue == nil && location.venue == nil) || ([self.venue isEqual:location.venue]); + + return equalCoord || equalVenue; +} + ++ (NSInteger)mediaType +{ + return TGBridgeLocationMediaAttachmentType; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeLocationVenue.m b/submodules/WatchCommon/Host/Sources/TGBridgeLocationVenue.m new file mode 100644 index 00000000..01c8fc8c --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeLocationVenue.m @@ -0,0 +1,66 @@ +#import "TGBridgeLocationVenue.h" + +#import "TGBridgeLocationMediaAttachment.h" + +NSString *const TGBridgeLocationVenueLatitudeKey = @"lat"; +NSString *const TGBridgeLocationVenueLongitudeKey = @"lon"; +NSString *const TGBridgeLocationVenueIdentifierKey = @"identifier"; +NSString *const TGBridgeLocationVenueProviderKey = @"provider"; +NSString *const TGBridgeLocationVenueNameKey = @"name"; +NSString *const TGBridgeLocationVenueAddressKey = @"address"; + +@implementation TGBridgeLocationVenue + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _coordinate = CLLocationCoordinate2DMake([aDecoder decodeDoubleForKey:TGBridgeLocationVenueLatitudeKey], [aDecoder decodeDoubleForKey:TGBridgeLocationVenueLongitudeKey]); + _identifier = [aDecoder decodeObjectForKey:TGBridgeLocationVenueIdentifierKey]; + _provider = [aDecoder decodeObjectForKey:TGBridgeLocationVenueProviderKey]; + _name = [aDecoder decodeObjectForKey:TGBridgeLocationVenueNameKey]; + _address = [aDecoder decodeObjectForKey:TGBridgeLocationVenueAddressKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeDouble:self.coordinate.latitude forKey:TGBridgeLocationVenueLatitudeKey]; + [aCoder encodeDouble:self.coordinate.longitude forKey:TGBridgeLocationVenueLongitudeKey]; + [aCoder encodeObject:self.identifier forKey:TGBridgeLocationVenueIdentifierKey]; + [aCoder encodeObject:self.provider forKey:TGBridgeLocationVenueProviderKey]; + [aCoder encodeObject:self.name forKey:TGBridgeLocationVenueNameKey]; + [aCoder encodeObject:self.address forKey:TGBridgeLocationVenueAddressKey]; +} + +- (TGBridgeLocationMediaAttachment *)locationAttachment +{ + TGBridgeLocationMediaAttachment *attachment = [[TGBridgeLocationMediaAttachment alloc] init]; + attachment.latitude = self.coordinate.latitude; + attachment.longitude = self.coordinate.longitude; + + TGBridgeVenueAttachment *venueAttachment = [[TGBridgeVenueAttachment alloc] init]; + venueAttachment.title = self.name; + venueAttachment.address = self.address; + venueAttachment.provider = self.provider; + venueAttachment.venueId = self.identifier; + + attachment.venue = venueAttachment; + + return attachment; +} + +- (BOOL)isEqual:(id)object +{ + if (object == self) + return YES; + + if (!object || ![object isKindOfClass:[self class]]) + return NO; + + return [self.identifier isEqualToString:((TGBridgeLocationVenue *)object).identifier]; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeMediaAttachment.m b/submodules/WatchCommon/Host/Sources/TGBridgeMediaAttachment.m new file mode 100644 index 00000000..971a23b6 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeMediaAttachment.m @@ -0,0 +1,32 @@ +#import "TGBridgeMediaAttachment.h" + +NSString *const TGBridgeMediaAttachmentTypeKey = @"type"; + +@implementation TGBridgeMediaAttachment + +- (instancetype)initWithCoder:(NSCoder *)__unused aDecoder +{ + self = [super init]; + if (self != nil) + { + + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)__unused aCoder +{ + +} + +- (NSInteger)mediaType +{ + return 0; +} + ++ (NSInteger)mediaType +{ + return 0; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeMessage.m b/submodules/WatchCommon/Host/Sources/TGBridgeMessage.m new file mode 100644 index 00000000..e66e3313 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeMessage.m @@ -0,0 +1,242 @@ +#import "TGBridgeMessage.h" +//#import "TGWatchCommon.h" +#import "TGBridgePeerIdAdapter.h" + +NSString *const TGBridgeMessageIdentifierKey = @"identifier"; +NSString *const TGBridgeMessageDateKey = @"date"; +NSString *const TGBridgeMessageRandomIdKey = @"randomId"; +NSString *const TGBridgeMessageFromUidKey = @"fromUid"; +NSString *const TGBridgeMessageCidKey = @"cid"; +NSString *const TGBridgeMessageTextKey = @"text"; +NSString *const TGBridgeMessageUnreadKey = @"unread"; +NSString *const TGBridgeMessageOutgoingKey = @"outgoing"; +NSString *const TGBridgeMessageMediaKey = @"media"; +NSString *const TGBridgeMessageDeliveryStateKey = @"deliveryState"; +NSString *const TGBridgeMessageForceReplyKey = @"forceReply"; + +NSString *const TGBridgeMessageKey = @"message"; +NSString *const TGBridgeMessagesArrayKey = @"messages"; + +@interface TGBridgeMessage () +{ + NSArray *_textCheckingResults; +} +@end + +@implementation TGBridgeMessage + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _identifier = [aDecoder decodeInt32ForKey:TGBridgeMessageIdentifierKey]; + _date = [aDecoder decodeDoubleForKey:TGBridgeMessageDateKey]; + _randomId = [aDecoder decodeInt64ForKey:TGBridgeMessageRandomIdKey]; + _fromUid = [aDecoder decodeInt64ForKey:TGBridgeMessageFromUidKey]; + _cid = [aDecoder decodeInt64ForKey:TGBridgeMessageCidKey]; + _text = [aDecoder decodeObjectForKey:TGBridgeMessageTextKey]; + _outgoing = [aDecoder decodeBoolForKey:TGBridgeMessageOutgoingKey]; + _unread = [aDecoder decodeBoolForKey:TGBridgeMessageUnreadKey]; + _deliveryState = [aDecoder decodeInt32ForKey:TGBridgeMessageDeliveryStateKey]; + _media = [aDecoder decodeObjectForKey:TGBridgeMessageMediaKey]; + _forceReply = [aDecoder decodeBoolForKey:TGBridgeMessageForceReplyKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt32:self.identifier forKey:TGBridgeMessageIdentifierKey]; + [aCoder encodeDouble:self.date forKey:TGBridgeMessageDateKey]; + [aCoder encodeInt64:self.randomId forKey:TGBridgeMessageRandomIdKey]; + [aCoder encodeInt64:self.fromUid forKey:TGBridgeMessageFromUidKey]; + [aCoder encodeInt64:self.cid forKey:TGBridgeMessageCidKey]; + [aCoder encodeObject:self.text forKey:TGBridgeMessageTextKey]; + [aCoder encodeBool:self.outgoing forKey:TGBridgeMessageOutgoingKey]; + [aCoder encodeBool:self.unread forKey:TGBridgeMessageUnreadKey]; + [aCoder encodeInt32:self.deliveryState forKey:TGBridgeMessageDeliveryStateKey]; + [aCoder encodeObject:self.media forKey:TGBridgeMessageMediaKey]; + [aCoder encodeBool:self.forceReply forKey:TGBridgeMessageForceReplyKey]; +} + +- (NSArray *)involvedUserIds +{ + NSMutableSet *userIds = [[NSMutableSet alloc] init]; + if (!TGPeerIdIsChannel(self.fromUid)) + [userIds addObject:[NSNumber numberWithLongLong:self.fromUid]]; + + for (TGBridgeMediaAttachment *attachment in self.media) + { + if ([attachment isKindOfClass:[TGBridgeContactMediaAttachment class]]) + { + TGBridgeContactMediaAttachment *contactAttachment = (TGBridgeContactMediaAttachment *)attachment; + if (contactAttachment.uid != 0) + [userIds addObject:[NSNumber numberWithLongLong:contactAttachment.uid]]; + } + else if ([attachment isKindOfClass:[TGBridgeForwardedMessageMediaAttachment class]]) + { + TGBridgeForwardedMessageMediaAttachment *forwardAttachment = (TGBridgeForwardedMessageMediaAttachment *)attachment; + if (forwardAttachment.peerId != 0 && !TGPeerIdIsChannel(forwardAttachment.peerId)) + [userIds addObject:[NSNumber numberWithLongLong:forwardAttachment.peerId]]; + } + else if ([attachment isKindOfClass:[TGBridgeReplyMessageMediaAttachment class]]) + { + TGBridgeReplyMessageMediaAttachment *replyAttachment = (TGBridgeReplyMessageMediaAttachment *)attachment; + if (replyAttachment.message != nil && !TGPeerIdIsChannel(replyAttachment.message.fromUid)) + [userIds addObject:[NSNumber numberWithLongLong:replyAttachment.message.fromUid]]; + } + else if ([attachment isKindOfClass:[TGBridgeActionMediaAttachment class]]) + { + TGBridgeActionMediaAttachment *actionAttachment = (TGBridgeActionMediaAttachment *)attachment; + if (actionAttachment.actionData[@"uid"] != nil) + [userIds addObject:[NSNumber numberWithLongLong:[actionAttachment.actionData[@"uid"] intValue]]]; + } + } + + NSMutableArray *result = [[NSMutableArray alloc] init]; + for (NSNumber *object in userIds) { + [result addObject:object]; + } + return result; +} + +- (NSArray *)textCheckingResults +{ + if (_textCheckingResults == nil) + { + NSMutableArray *results = [[NSMutableArray alloc] init]; + + NSArray *entities = nil; + for (TGBridgeMediaAttachment *attachment in self.media) + { + if ([attachment isKindOfClass:[TGBridgeMessageEntitiesAttachment class]]) + { + entities = ((TGBridgeMessageEntitiesAttachment *)attachment).entities; + break; + } + } + + for (TGBridgeMessageEntity *entity in entities) + { + TGBridgeTextCheckingResult *result = [[TGBridgeTextCheckingResult alloc] init]; + result.range = entity.range; + + if ([entity isKindOfClass:[TGBridgeMessageEntityBold class]]) + result.type = TGBridgeTextCheckingResultTypeBold; + else if ([entity isKindOfClass:[TGBridgeMessageEntityItalic class]]) + result.type = TGBridgeTextCheckingResultTypeItalic; + else if ([entity isKindOfClass:[TGBridgeMessageEntityCode class]]) + result.type = TGBridgeTextCheckingResultTypeCode; + else if ([entity isKindOfClass:[TGBridgeMessageEntityPre class]]) + result.type = TGBridgeTextCheckingResultTypePre; + + if (result.type != TGBridgeTextCheckingResultTypeUndefined) + [results addObject:result]; + } + + _textCheckingResults = results; + } + + return _textCheckingResults; +} + +- (BOOL)isEqual:(id)object +{ + if (object == self) + return YES; + + if (!object || ![object isKindOfClass:[self class]]) + return NO; + + TGBridgeMessage *message = (TGBridgeMessage *)object; + + if (self.randomId != 0) + return self.randomId == message.randomId; + else + return self.identifier == message.identifier; +} + ++ (instancetype)temporaryNewMessageForText:(NSString *)text userId:(int32_t)userId +{ + return [self temporaryNewMessageForText:text userId:userId replyToMessage:nil]; +} + ++ (instancetype)temporaryNewMessageForText:(NSString *)text userId:(int32_t)userId replyToMessage:(TGBridgeMessage *)replyToMessage +{ + int64_t randomId = 0; + arc4random_buf(&randomId, 8); + + int32_t messageId = 0; + arc4random_buf(&messageId, 4); + + TGBridgeMessage *message = [[TGBridgeMessage alloc] init]; + message->_identifier = -abs(messageId); + message->_fromUid = userId; + message->_randomId = randomId; + message->_unread = true; + message->_outgoing = true; + message->_deliveryState = TGBridgeMessageDeliveryStatePending; + message->_text = text; + message->_date = [[NSDate date] timeIntervalSince1970]; + + if (replyToMessage != nil) + { + TGBridgeReplyMessageMediaAttachment *replyAttachment = [[TGBridgeReplyMessageMediaAttachment alloc] init]; + replyAttachment.mid = replyToMessage.identifier; + replyAttachment.message = replyToMessage; + + message->_media = @[ replyToMessage ]; + } + + return message; +} + ++ (instancetype)temporaryNewMessageForSticker:(TGBridgeDocumentMediaAttachment *)sticker userId:(int32_t)userId +{ + return [self _temporaryNewMessageForMediaAttachment:sticker userId:userId]; +} + ++ (instancetype)temporaryNewMessageForLocation:(TGBridgeLocationMediaAttachment *)location userId:(int32_t)userId +{ + return [self _temporaryNewMessageForMediaAttachment:location userId:userId]; +} + ++ (instancetype)temporaryNewMessageForAudioWithDuration:(int32_t)duration userId:(int32_t)userId localAudioId:(int64_t)localAudioId +{ + TGBridgeDocumentMediaAttachment *document = [[TGBridgeDocumentMediaAttachment alloc] init]; + document.isAudio = true; + document.isVoice = true; + document.localDocumentId = localAudioId; + document.duration = duration; + + return [self _temporaryNewMessageForMediaAttachment:document userId:userId]; +} + ++ (instancetype)_temporaryNewMessageForMediaAttachment:(TGBridgeMediaAttachment *)attachment userId:(int32_t)userId +{ + int64_t randomId = 0; + arc4random_buf(&randomId, 8); + + int32_t messageId = 0; + arc4random_buf(&messageId, 4); + + TGBridgeMessage *message = [[TGBridgeMessage alloc] init]; + message->_identifier = -abs(messageId); + message->_fromUid = userId; + message->_unread = true; + message->_outgoing = true; + message->_deliveryState = TGBridgeMessageDeliveryStatePending; + message->_date = [[NSDate date] timeIntervalSince1970]; + + message->_media = @[ attachment ]; + + return message; +} + +@end + + +@implementation TGBridgeTextCheckingResult + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeMessageEntities.m b/submodules/WatchCommon/Host/Sources/TGBridgeMessageEntities.m new file mode 100644 index 00000000..8d639a94 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeMessageEntities.m @@ -0,0 +1,83 @@ +#import "TGBridgeMessageEntities.h" + +NSString *const TGBridgeMessageEntityLocationKey = @"loc"; +NSString *const TGBridgeMessageEntityLengthKey = @"len"; + +@implementation TGBridgeMessageEntity + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + NSUInteger loc = [aDecoder decodeIntegerForKey:TGBridgeMessageEntityLocationKey]; + NSUInteger len = [aDecoder decodeIntegerForKey:TGBridgeMessageEntityLengthKey]; + _range = NSMakeRange(loc, len); + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInteger:self.range.location forKey:TGBridgeMessageEntityLocationKey]; + [aCoder encodeInteger:self.range.length forKey:TGBridgeMessageEntityLengthKey]; +} + ++ (instancetype)entitityWithRange:(NSRange)range +{ + TGBridgeMessageEntity *entity = [[self alloc] init]; + entity.range = range; + return entity; +} + +@end + + +@implementation TGBridgeMessageEntityUrl + +@end + + +@implementation TGBridgeMessageEntityEmail + +@end + + +@implementation TGBridgeMessageEntityTextUrl + +@end + + +@implementation TGBridgeMessageEntityMention + +@end + + +@implementation TGBridgeMessageEntityHashtag + +@end + + +@implementation TGBridgeMessageEntityBotCommand + +@end + + +@implementation TGBridgeMessageEntityBold + +@end + + +@implementation TGBridgeMessageEntityItalic + +@end + + +@implementation TGBridgeMessageEntityCode + +@end + + +@implementation TGBridgeMessageEntityPre + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeMessageEntitiesAttachment.m b/submodules/WatchCommon/Host/Sources/TGBridgeMessageEntitiesAttachment.m new file mode 100644 index 00000000..fb5cb3b7 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeMessageEntitiesAttachment.m @@ -0,0 +1,30 @@ +#import "TGBridgeMessageEntitiesAttachment.h" + +const NSInteger TGBridgeMessageEntitiesAttachmentType = 0x8c2e3cce; + +NSString *const TGBridgeMessageEntitiesKey = @"entities"; + +@implementation TGBridgeMessageEntitiesAttachment + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _entities = [aDecoder decodeObjectForKey:TGBridgeMessageEntitiesKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeObject:self.entities forKey:TGBridgeMessageEntitiesKey]; +} + ++ (NSInteger)mediaType +{ + return TGBridgeMessageEntitiesAttachmentType; +} + + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgePeerNotificationSettings.m b/submodules/WatchCommon/Host/Sources/TGBridgePeerNotificationSettings.m new file mode 100644 index 00000000..662c2f4c --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgePeerNotificationSettings.m @@ -0,0 +1,22 @@ +#import "TGBridgePeerNotificationSettings.h" + +NSString *const TGBridgePeerNotificationSettingsMuteForKey = @"muteFor"; + +@implementation TGBridgePeerNotificationSettings + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _muteFor = [aDecoder decodeInt32ForKey:TGBridgePeerNotificationSettingsMuteForKey]; + } + return self; +} + +- (void)encodeWithCoder:(nonnull NSCoder *)aCoder +{ + [aCoder encodeInt32:self.muteFor forKey:TGBridgePeerNotificationSettingsMuteForKey]; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeReplyMarkupMediaAttachment.m b/submodules/WatchCommon/Host/Sources/TGBridgeReplyMarkupMediaAttachment.m new file mode 100644 index 00000000..1299c900 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeReplyMarkupMediaAttachment.m @@ -0,0 +1,29 @@ +#import "TGBridgeReplyMarkupMediaAttachment.h" + +const NSInteger TGBridgeReplyMarkupMediaAttachmentType = 0x5678acc1; + +NSString *const TGBridgeReplyMarkupMediaMessageKey = @"replyMarkup"; + +@implementation TGBridgeReplyMarkupMediaAttachment + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _replyMarkup = [aDecoder decodeObjectForKey:TGBridgeReplyMarkupMediaMessageKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeObject:self.replyMarkup forKey:TGBridgeReplyMarkupMediaMessageKey]; +} + ++ (NSInteger)mediaType +{ + return TGBridgeReplyMarkupMediaAttachmentType; +} + +@end \ No newline at end of file diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeReplyMessageMediaAttachment.m b/submodules/WatchCommon/Host/Sources/TGBridgeReplyMessageMediaAttachment.m new file mode 100644 index 00000000..fbc24569 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeReplyMessageMediaAttachment.m @@ -0,0 +1,33 @@ +#import "TGBridgeReplyMessageMediaAttachment.h" +#import "TGBridgeMessage.h" + +const NSInteger TGBridgeReplyMessageMediaAttachmentType = 414002169; + +NSString *const TGBridgeReplyMessageMediaMidKey = @"mid"; +NSString *const TGBridgeReplyMessageMediaMessageKey = @"message"; + +@implementation TGBridgeReplyMessageMediaAttachment + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _mid = [aDecoder decodeInt32ForKey:TGBridgeReplyMessageMediaMidKey]; + _message = [aDecoder decodeObjectForKey:TGBridgeReplyMessageMediaMessageKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt32:self.mid forKey:TGBridgeReplyMessageMediaMidKey]; + [aCoder encodeObject:self.message forKey:TGBridgeReplyMessageMediaMessageKey]; +} + ++ (NSInteger)mediaType +{ + return TGBridgeReplyMessageMediaAttachmentType; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeSubscriptions.m b/submodules/WatchCommon/Host/Sources/TGBridgeSubscriptions.m new file mode 100644 index 00000000..8c4b50d2 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeSubscriptions.m @@ -0,0 +1,1048 @@ +#import "TGBridgeSubscriptions.h" + +#import + +#import "TGBridgeImageMediaAttachment.h" +#import "TGBridgeVideoMediaAttachment.h" +#import "TGBridgeDocumentMediaAttachment.h" +#import "TGBridgeLocationMediaAttachment.h" +#import "TGBridgePeerNotificationSettings.h" + +NSString *const TGBridgeAudioSubscriptionName = @"media.audio"; +NSString *const TGBridgeAudioSubscriptionAttachmentKey = @"attachment"; +NSString *const TGBridgeAudioSubscriptionPeerIdKey = @"peerId"; +NSString *const TGBridgeAudioSubscriptionMessageIdKey = @"messageId"; + +@implementation TGBridgeAudioSubscription + +- (instancetype)initWithAttachment:(TGBridgeMediaAttachment *)attachment peerId:(int64_t)peerId messageId:(int32_t)messageId +{ + self = [super init]; + if (self != nil) + { + _attachment = attachment; + _peerId = peerId; + _messageId = messageId; + } + return self; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeObject:self.attachment forKey:TGBridgeAudioSubscriptionAttachmentKey]; + [aCoder encodeInt64:self.peerId forKey:TGBridgeAudioSubscriptionPeerIdKey]; + [aCoder encodeInt32:self.messageId forKey:TGBridgeAudioSubscriptionMessageIdKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _attachment = [aDecoder decodeObjectForKey:TGBridgeAudioSubscriptionAttachmentKey]; + _peerId = [aDecoder decodeInt64ForKey:TGBridgeAudioSubscriptionPeerIdKey]; + _messageId = [aDecoder decodeInt32ForKey:TGBridgeAudioSubscriptionMessageIdKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeAudioSubscriptionName; +} + +@end + + +NSString *const TGBridgeAudioSentSubscriptionName = @"media.audioSent"; +NSString *const TGBridgeAudioSentSubscriptionConversationIdKey = @"conversationId"; + +@implementation TGBridgeAudioSentSubscription + +- (instancetype)initWithConversationId:(int64_t)conversationId +{ + self = [super init]; + if (self != nil) + { + _conversationId = conversationId; + } + return self; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.conversationId forKey:TGBridgeAudioSentSubscriptionConversationIdKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _conversationId = [aDecoder decodeInt64ForKey:TGBridgeAudioSentSubscriptionConversationIdKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeAudioSentSubscriptionName; +} + +@end + + +NSString *const TGBridgeChatListSubscriptionName = @"chats.chatList"; +NSString *const TGBridgeChatListSubscriptionLimitKey = @"limit"; + +@implementation TGBridgeChatListSubscription + +- (instancetype)initWithLimit:(int32_t)limit +{ + self = [super init]; + if (self != nil) + { + _limit = limit; + } + return self; +} + +- (bool)dropPreviouslyQueued +{ + return true; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt32:self.limit forKey:TGBridgeChatListSubscriptionLimitKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _limit = [aDecoder decodeInt32ForKey:TGBridgeChatListSubscriptionLimitKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeChatListSubscriptionName; +} + +@end + + +NSString *const TGBridgeChatMessageListSubscriptionName = @"chats.chatMessageList"; +NSString *const TGBridgeChatMessageListSubscriptionPeerIdKey = @"peerId"; +NSString *const TGBridgeChatMessageListSubscriptionAtMessageIdKey = @"atMessageId"; +NSString *const TGBridgeChatMessageListSubscriptionRangeMessageCountKey = @"rangeMessageCount"; + +@implementation TGBridgeChatMessageListSubscription + +- (instancetype)initWithPeerId:(int64_t)peerId atMessageId:(int32_t)messageId rangeMessageCount:(NSUInteger)rangeMessageCount +{ + self = [super init]; + if (self != nil) + { + _peerId = peerId; + _atMessageId = messageId; + _rangeMessageCount = rangeMessageCount; + } + return self; +} + +- (bool)dropPreviouslyQueued +{ + return true; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgeChatMessageListSubscriptionPeerIdKey]; + [aCoder encodeInt32:self.atMessageId forKey:TGBridgeChatMessageListSubscriptionAtMessageIdKey]; + [aCoder encodeInt32:(int32_t)self.rangeMessageCount forKey:TGBridgeChatMessageListSubscriptionRangeMessageCountKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _peerId = [aDecoder decodeInt64ForKey:TGBridgeChatMessageListSubscriptionPeerIdKey]; + _atMessageId = [aDecoder decodeInt32ForKey:TGBridgeChatMessageListSubscriptionAtMessageIdKey]; + _rangeMessageCount = [aDecoder decodeInt32ForKey:TGBridgeChatMessageListSubscriptionRangeMessageCountKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeChatMessageListSubscriptionName; +} + +@end + + +NSString *const TGBridgeChatMessageSubscriptionName = @"chats.message"; +NSString *const TGBridgeChatMessageSubscriptionPeerIdKey = @"peerId"; +NSString *const TGBridgeChatMessageSubscriptionMessageIdKey = @"mid"; + +@implementation TGBridgeChatMessageSubscription + +- (instancetype)initWithPeerId:(int64_t)peerId messageId:(int32_t)messageId +{ + self = [super init]; + if (self != nil) + { + _peerId = peerId; + _messageId = messageId; + } + return self; +} + +- (bool)synchronous +{ + return true; +} + +- (bool)renewable +{ + return false; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgeChatMessageSubscriptionPeerIdKey]; + [aCoder encodeInt32:self.messageId forKey:TGBridgeChatMessageSubscriptionMessageIdKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _peerId = [aDecoder decodeInt64ForKey:TGBridgeChatMessageSubscriptionPeerIdKey]; + _messageId = [aDecoder decodeInt32ForKey:TGBridgeChatMessageSubscriptionMessageIdKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeChatMessageSubscriptionName; +} + +@end + + +NSString *const TGBridgeReadChatMessageListSubscriptionName = @"chats.readChatMessageList"; +NSString *const TGBridgeReadChatMessageListSubscriptionPeerIdKey = @"peerId"; +NSString *const TGBridgeReadChatMessageListSubscriptionMessageIdKey = @"mid"; + +@implementation TGBridgeReadChatMessageListSubscription + +- (instancetype)initWithPeerId:(int64_t)peerId messageId:(int32_t)messageId +{ + self = [super init]; + if (self != nil) + { + _peerId = peerId; + _messageId = messageId; + } + return self; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgeReadChatMessageListSubscriptionPeerIdKey]; + [aCoder encodeInt32:self.messageId forKey:TGBridgeReadChatMessageListSubscriptionMessageIdKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _peerId = [aDecoder decodeInt64ForKey:TGBridgeReadChatMessageListSubscriptionPeerIdKey]; + _messageId = [aDecoder decodeInt32ForKey:TGBridgeReadChatMessageListSubscriptionMessageIdKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeReadChatMessageListSubscriptionName; +} + +@end + + +NSString *const TGBridgeContactsSubscriptionName = @"contacts.search"; +NSString *const TGBridgeContactsSubscriptionQueryKey = @"query"; + +@implementation TGBridgeContactsSubscription + +- (instancetype)initWithQuery:(NSString *)query +{ + self = [super init]; + if (self != nil) + { + _query = query; + } + return self; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeObject:self.query forKey:TGBridgeContactsSubscriptionQueryKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _query = [aDecoder decodeObjectForKey:TGBridgeContactsSubscriptionQueryKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeContactsSubscriptionName; +} + +@end + + +NSString *const TGBridgeConversationSubscriptionName = @"chats.conversation"; +NSString *const TGBridgeConversationSubscriptionPeerIdKey = @"peerId"; + +@implementation TGBridgeConversationSubscription + +- (instancetype)initWithPeerId:(int64_t)peerId +{ + self = [super init]; + if (self != nil) + { + _peerId = peerId; + } + return self; +} + +- (bool)dropPreviouslyQueued +{ + return true; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgeConversationSubscriptionPeerIdKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _peerId = [aDecoder decodeInt64ForKey:TGBridgeConversationSubscriptionPeerIdKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeConversationSubscriptionName; +} + +@end + + +NSString *const TGBridgeNearbyVenuesSubscriptionName = @"location.nearbyVenues"; +NSString *const TGBridgeNearbyVenuesSubscriptionLatitudeKey = @"lat"; +NSString *const TGBridgeNearbyVenuesSubscriptionLongitudeKey = @"lon"; +NSString *const TGBridgeNearbyVenuesSubscriptionLimitKey = @"limit"; + +@implementation TGBridgeNearbyVenuesSubscription + +- (instancetype)initWithCoordinate:(CLLocationCoordinate2D)coordinate limit:(int32_t)limit +{ + self = [super init]; + if (self != nil) + { + _coordinate = coordinate; + _limit = limit; + } + return self; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeDouble:self.coordinate.latitude forKey:TGBridgeNearbyVenuesSubscriptionLatitudeKey]; + [aCoder encodeDouble:self.coordinate.longitude forKey:TGBridgeNearbyVenuesSubscriptionLongitudeKey]; + [aCoder encodeInt32:self.limit forKey:TGBridgeNearbyVenuesSubscriptionLimitKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _coordinate = CLLocationCoordinate2DMake([aDecoder decodeDoubleForKey:TGBridgeNearbyVenuesSubscriptionLatitudeKey], + [aDecoder decodeDoubleForKey:TGBridgeNearbyVenuesSubscriptionLongitudeKey]); + _limit = [aDecoder decodeInt32ForKey:TGBridgeNearbyVenuesSubscriptionLimitKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeNearbyVenuesSubscriptionName; +} + +@end + + +NSString *const TGBridgeMediaThumbnailSubscriptionName = @"media.thumbnail"; +NSString *const TGBridgeMediaThumbnailPeerIdKey = @"peerId"; +NSString *const TGBridgeMediaThumbnailMessageIdKey = @"mid"; +NSString *const TGBridgeMediaThumbnailSizeKey = @"size"; +NSString *const TGBridgeMediaThumbnailNotificationKey = @"notification"; + +@implementation TGBridgeMediaThumbnailSubscription + +- (instancetype)initWithPeerId:(int64_t)peerId messageId:(int32_t)messageId size:(CGSize)size notification:(bool)notification +{ + self = [super init]; + if (self != nil) + { + _peerId = peerId; + _messageId = messageId; + _size = size; + _notification = notification; + } + return self; +} + +- (bool)renewable +{ + return false; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgeMediaThumbnailPeerIdKey]; + [aCoder encodeInt32:self.messageId forKey:TGBridgeMediaThumbnailMessageIdKey]; + [aCoder encodeCGSize:self.size forKey:TGBridgeMediaThumbnailSizeKey]; + [aCoder encodeBool:self.notification forKey:TGBridgeMediaThumbnailNotificationKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _peerId = [aDecoder decodeInt64ForKey:TGBridgeMediaThumbnailPeerIdKey]; + _messageId = [aDecoder decodeInt32ForKey:TGBridgeMediaThumbnailMessageIdKey]; + _size = [aDecoder decodeCGSizeForKey:TGBridgeMediaThumbnailSizeKey]; + _notification = [aDecoder decodeBoolForKey:TGBridgeMediaThumbnailNotificationKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeMediaThumbnailSubscriptionName; +} + +@end + + +NSString *const TGBridgeMediaAvatarSubscriptionName = @"media.avatar"; +NSString *const TGBridgeMediaAvatarPeerIdKey = @"peerId"; +NSString *const TGBridgeMediaAvatarUrlKey = @"url"; +NSString *const TGBridgeMediaAvatarTypeKey = @"type"; + +@implementation TGBridgeMediaAvatarSubscription + +- (instancetype)initWithPeerId:(int64_t)peerId url:(NSString *)url type:(TGBridgeMediaAvatarType)type +{ + self = [super init]; + if (self != nil) + { + _peerId = peerId; + _url = url; + _type = type; + } + return self; +} + +- (bool)renewable +{ + return false; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgeMediaAvatarPeerIdKey]; + [aCoder encodeObject:self.url forKey:TGBridgeMediaAvatarUrlKey]; + [aCoder encodeInt32:self.type forKey:TGBridgeMediaAvatarTypeKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _peerId = [aDecoder decodeInt64ForKey:TGBridgeMediaAvatarPeerIdKey]; + _url = [aDecoder decodeObjectForKey:TGBridgeMediaAvatarUrlKey]; + _type = [aDecoder decodeInt32ForKey:TGBridgeMediaAvatarTypeKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeMediaAvatarSubscriptionName; +} + +@end + + +NSString *const TGBridgeMediaStickerSubscriptionName = @"media.sticker"; +NSString *const TGBridgeMediaStickerDocumentIdKey = @"documentId"; +NSString *const TGBridgeMediaStickerPackIdKey = @"packId"; +NSString *const TGBridgeMediaStickerPackAccessHashKey = @"accessHash"; +NSString *const TGBridgeMediaStickerPeerIdKey = @"peerId"; +NSString *const TGBridgeMediaStickerMessageIdKey = @"mid"; +NSString *const TGBridgeMediaStickerNotificationKey = @"notification"; +NSString *const TGBridgeMediaStickerSizeKey = @"size"; + +@implementation TGBridgeMediaStickerSubscription + +- (instancetype)initWithDocumentId:(int64_t)documentId stickerPackId:(int64_t)stickerPackId stickerPackAccessHash:(int64_t)stickerPackAccessHash stickerPeerId:(int64_t)stickerPeerId stickerMessageId:(int32_t)stickerMessageId notification:(bool)notification size:(CGSize)size +{ + self = [super init]; + if (self != nil) + { + _documentId = documentId; + _stickerPackId = stickerPackId; + _stickerPackAccessHash = stickerPackAccessHash; + _stickerPeerId = stickerPeerId; + _stickerMessageId = stickerMessageId; + _notification = notification; + _size = size; + } + return self; +} + +- (bool)renewable +{ + return false; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.documentId forKey:TGBridgeMediaStickerDocumentIdKey]; + [aCoder encodeInt64:self.stickerPackId forKey:TGBridgeMediaStickerPackIdKey]; + [aCoder encodeInt64:self.stickerPackAccessHash forKey:TGBridgeMediaStickerPackAccessHashKey]; + [aCoder encodeInt64:self.stickerPeerId forKey:TGBridgeMediaStickerPeerIdKey]; + [aCoder encodeInt32:self.stickerMessageId forKey:TGBridgeMediaStickerMessageIdKey]; + [aCoder encodeBool:self.notification forKey:TGBridgeMediaStickerNotificationKey]; + [aCoder encodeCGSize:self.size forKey:TGBridgeMediaStickerSizeKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _documentId = [aDecoder decodeInt64ForKey:TGBridgeMediaStickerDocumentIdKey]; + _stickerPackId = [aDecoder decodeInt64ForKey:TGBridgeMediaStickerPackIdKey]; + _stickerPackAccessHash = [aDecoder decodeInt64ForKey:TGBridgeMediaStickerPackAccessHashKey]; + _stickerPeerId = [aDecoder decodeInt64ForKey:TGBridgeMediaStickerPeerIdKey]; + _stickerMessageId = [aDecoder decodeInt32ForKey:TGBridgeMediaStickerMessageIdKey]; + _notification = [aDecoder decodeBoolForKey:TGBridgeMediaStickerNotificationKey]; + _size = [aDecoder decodeCGSizeForKey:TGBridgeMediaStickerSizeKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeMediaStickerSubscriptionName; +} + +@end + + +NSString *const TGBridgePeerSettingsSubscriptionName = @"peer.settings"; +NSString *const TGBridgePeerSettingsSubscriptionPeerIdKey = @"peerId"; + +@implementation TGBridgePeerSettingsSubscription + +- (instancetype)initWithPeerId:(int64_t)peerId +{ + self = [super init]; + if (self != nil) + { + _peerId = peerId; + } + return self; +} + +- (bool)dropPreviouslyQueued +{ + return true; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgePeerSettingsSubscriptionPeerIdKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _peerId = [aDecoder decodeInt64ForKey:TGBridgePeerSettingsSubscriptionPeerIdKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgePeerSettingsSubscriptionName; +} + +@end + + +NSString *const TGBridgePeerUpdateNotificationSettingsSubscriptionName = @"peer.notificationSettings"; +NSString *const TGBridgePeerUpdateNotificationSettingsSubscriptionPeerIdKey = @"peerId"; + +@implementation TGBridgePeerUpdateNotificationSettingsSubscription + +- (instancetype)initWithPeerId:(int64_t)peerId +{ + self = [super init]; + if (self != nil) + { + _peerId = peerId; + } + return self; +} + +- (bool)renewable +{ + return false; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgePeerUpdateNotificationSettingsSubscriptionPeerIdKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _peerId = [aDecoder decodeInt64ForKey:TGBridgePeerUpdateNotificationSettingsSubscriptionPeerIdKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgePeerUpdateNotificationSettingsSubscriptionName; +} + +@end + + +NSString *const TGBridgePeerUpdateBlockStatusSubscriptionName = @"peer.updateBlocked"; +NSString *const TGBridgePeerUpdateBlockStatusSubscriptionPeerIdKey = @"peerId"; +NSString *const TGBridgePeerUpdateBlockStatusSubscriptionBlockedKey = @"blocked"; + +@implementation TGBridgePeerUpdateBlockStatusSubscription + +- (instancetype)initWithPeerId:(int64_t)peerId blocked:(bool)blocked +{ + self = [super init]; + if (self != nil) + { + _peerId = peerId; + _blocked = blocked; + } + return self; +} + +- (bool)renewable +{ + return false; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgePeerUpdateBlockStatusSubscriptionPeerIdKey]; + [aCoder encodeBool:self.blocked forKey:TGBridgePeerUpdateBlockStatusSubscriptionBlockedKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _peerId = [aDecoder decodeInt64ForKey:TGBridgePeerUpdateBlockStatusSubscriptionPeerIdKey]; + _blocked = [aDecoder decodeBoolForKey:TGBridgePeerUpdateBlockStatusSubscriptionBlockedKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgePeerUpdateBlockStatusSubscriptionName; +} + +@end + + +NSString *const TGBridgeRemoteSubscriptionName = @"remote.request"; +NSString *const TGBridgeRemotePeerIdKey = @"peerId"; +NSString *const TGBridgeRemoteMessageIdKey = @"mid"; +NSString *const TGBridgeRemoteTypeKey = @"mediaType"; +NSString *const TGBridgeRemoteAutoPlayKey = @"autoPlay"; + +@implementation TGBridgeRemoteSubscription + +- (instancetype)initWithPeerId:(int64_t)peerId messageId:(int32_t)messageId type:(int32_t)type autoPlay:(bool)autoPlay +{ + self = [super init]; + if (self != nil) + { + _peerId = peerId; + _messageId = messageId; + _type = type; + _autoPlay = autoPlay; + } + return self; +} + +- (bool)renewable +{ + return false; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgeRemotePeerIdKey]; + [aCoder encodeInt32:self.messageId forKey:TGBridgeRemoteMessageIdKey]; + [aCoder encodeInt32:self.type forKey:TGBridgeRemoteTypeKey]; + [aCoder encodeBool:self.autoPlay forKey:TGBridgeRemoteAutoPlayKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _peerId = [aDecoder decodeInt64ForKey:TGBridgeRemotePeerIdKey]; + _messageId = [aDecoder decodeInt32ForKey:TGBridgeRemoteMessageIdKey]; + _type = [aDecoder decodeInt32ForKey:TGBridgeRemoteTypeKey]; + _autoPlay = [aDecoder decodeBoolForKey:TGBridgeRemoteAutoPlayKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeRemoteSubscriptionName; +} + +@end + + +NSString *const TGBridgeSendTextMessageSubscriptionName = @"sendMessage.text"; +NSString *const TGBridgeSendTextMessageSubscriptionPeerIdKey = @"peerId"; +NSString *const TGBridgeSendTextMessageSubscriptionTextKey = @"text"; +NSString *const TGBridgeSendTextMessageSubscriptionReplyToMidKey = @"replyToMid"; + +@implementation TGBridgeSendTextMessageSubscription + +- (instancetype)initWithPeerId:(int64_t)peerId text:(NSString *)text replyToMid:(int32_t)replyToMid +{ + self = [super init]; + if (self != nil) + { + _peerId = peerId; + _text = text; + _replyToMid = replyToMid; + } + return self; +} + +- (bool)renewable +{ + return false; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgeSendTextMessageSubscriptionPeerIdKey]; + [aCoder encodeObject:self.text forKey:TGBridgeSendTextMessageSubscriptionTextKey]; + [aCoder encodeInt32:self.replyToMid forKey:TGBridgeSendTextMessageSubscriptionReplyToMidKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _peerId = [aDecoder decodeInt64ForKey:TGBridgeSendTextMessageSubscriptionPeerIdKey]; + _text = [aDecoder decodeObjectForKey:TGBridgeSendTextMessageSubscriptionTextKey]; + _replyToMid = [aDecoder decodeInt32ForKey:TGBridgeSendTextMessageSubscriptionReplyToMidKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeSendTextMessageSubscriptionName; +} + +@end + + +NSString *const TGBridgeSendStickerMessageSubscriptionName = @"sendMessage.sticker"; +NSString *const TGBridgeSendStickerMessageSubscriptionPeerIdKey = @"peerId"; +NSString *const TGBridgeSendStickerMessageSubscriptionDocumentKey = @"document"; +NSString *const TGBridgeSendStickerMessageSubscriptionReplyToMidKey = @"replyToMid"; + +@implementation TGBridgeSendStickerMessageSubscription + +- (instancetype)initWithPeerId:(int64_t)peerId document:(TGBridgeDocumentMediaAttachment *)document replyToMid:(int32_t)replyToMid +{ + self = [super init]; + if (self != nil) + { + _peerId = peerId; + _document = document; + _replyToMid = replyToMid; + } + return self; +} + +- (bool)renewable +{ + return false; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgeSendStickerMessageSubscriptionPeerIdKey]; + [aCoder encodeObject:self.document forKey:TGBridgeSendStickerMessageSubscriptionDocumentKey]; + [aCoder encodeInt32:self.replyToMid forKey:TGBridgeSendStickerMessageSubscriptionReplyToMidKey]; +} + + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _peerId = [aDecoder decodeInt64ForKey:TGBridgeSendStickerMessageSubscriptionPeerIdKey]; + _document = [aDecoder decodeObjectForKey:TGBridgeSendStickerMessageSubscriptionDocumentKey]; + _replyToMid = [aDecoder decodeInt32ForKey:TGBridgeSendStickerMessageSubscriptionReplyToMidKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeSendStickerMessageSubscriptionName; +} + +@end + + +NSString *const TGBridgeSendLocationMessageSubscriptionName = @"sendMessage.location"; +NSString *const TGBridgeSendLocationMessageSubscriptionPeerIdKey = @"peerId"; +NSString *const TGBridgeSendLocationMessageSubscriptionLocationKey = @"location"; +NSString *const TGBridgeSendLocationMessageSubscriptionReplyToMidKey = @"replyToMid"; + +@implementation TGBridgeSendLocationMessageSubscription + +- (instancetype)initWithPeerId:(int64_t)peerId location:(TGBridgeLocationMediaAttachment *)location replyToMid:(int32_t)replyToMid +{ + self = [super init]; + if (self != nil) + { + _peerId = peerId; + _location = location; + _replyToMid = replyToMid; + } + return self; +} + +- (bool)renewable +{ + return false; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgeSendLocationMessageSubscriptionPeerIdKey]; + [aCoder encodeObject:self.location forKey:TGBridgeSendLocationMessageSubscriptionLocationKey]; + [aCoder encodeInt32:self.replyToMid forKey:TGBridgeSendLocationMessageSubscriptionReplyToMidKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _peerId = [aDecoder decodeInt64ForKey:TGBridgeSendLocationMessageSubscriptionPeerIdKey]; + _location = [aDecoder decodeObjectForKey:TGBridgeSendLocationMessageSubscriptionLocationKey]; + _replyToMid = [aDecoder decodeInt32ForKey:TGBridgeSendLocationMessageSubscriptionReplyToMidKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeSendLocationMessageSubscriptionName; +} + +@end + + +NSString *const TGBridgeSendForwardedMessageSubscriptionName = @"sendMessage.forward"; +NSString *const TGBridgeSendForwardedMessageSubscriptionPeerIdKey = @"peerId"; +NSString *const TGBridgeSendForwardedMessageSubscriptionMidKey = @"mid"; +NSString *const TGBridgeSendForwardedMessageSubscriptionTargetPeerIdKey = @"targetPeerId"; + +@implementation TGBridgeSendForwardedMessageSubscription + +- (instancetype)initWithPeerId:(int64_t)peerId messageId:(int32_t)messageId targetPeerId:(int64_t)targetPeerId +{ + self = [super init]; + if (self != nil) + { + _peerId = peerId; + _messageId = messageId; + _targetPeerId = targetPeerId; + } + return self; +} + +- (bool)renewable +{ + return false; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgeSendForwardedMessageSubscriptionPeerIdKey]; + [aCoder encodeInt32:self.messageId forKey:TGBridgeSendForwardedMessageSubscriptionMidKey]; + [aCoder encodeInt64:self.targetPeerId forKey:TGBridgeSendForwardedMessageSubscriptionTargetPeerIdKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _peerId = [aDecoder decodeInt64ForKey:TGBridgeSendForwardedMessageSubscriptionPeerIdKey]; + _messageId = [aDecoder decodeInt32ForKey:TGBridgeSendForwardedMessageSubscriptionMidKey]; + _targetPeerId = [aDecoder decodeInt64ForKey:TGBridgeSendForwardedMessageSubscriptionTargetPeerIdKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeSendForwardedMessageSubscriptionName; +} + +@end + + +NSString *const TGBridgeStateSubscriptionName = @"state.syncState"; + +@implementation TGBridgeStateSubscription + +- (bool)dropPreviouslyQueued +{ + return true; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeStateSubscriptionName; +} + +@end + + +NSString *const TGBridgeStickerPacksSubscriptionName = @"stickers.packs"; + +@implementation TGBridgeStickerPacksSubscription + ++ (NSString *)subscriptionName +{ + return TGBridgeStickerPacksSubscriptionName; +} + +@end + + +NSString *const TGBridgeRecentStickersSubscriptionName = @"stickers.recent"; +NSString *const TGBridgeRecentStickersSubscriptionLimitKey = @"limit"; + +@implementation TGBridgeRecentStickersSubscription + +- (instancetype)initWithLimit:(int32_t)limit +{ + self = [super init]; + if (self != nil) + { + _limit = limit; + } + return self; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt32:self.limit forKey:TGBridgeRecentStickersSubscriptionLimitKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _limit = [aDecoder decodeInt32ForKey:TGBridgeRecentStickersSubscriptionLimitKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeRecentStickersSubscriptionName; +} + +@end + + +NSString *const TGBridgeUserInfoSubscriptionName = @"user.userInfo"; +NSString *const TGBridgeUserInfoSubscriptionUserIdsKey = @"uids"; + +@implementation TGBridgeUserInfoSubscription + +- (instancetype)initWithUserIds:(NSArray *)userIds +{ + self = [super init]; + if (self != nil) + { + _userIds = userIds; + } + return self; +} + +- (bool)dropPreviouslyQueued +{ + return true; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeObject:self.userIds forKey:TGBridgeUserInfoSubscriptionUserIdsKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _userIds = [aDecoder decodeObjectForKey:TGBridgeUserInfoSubscriptionUserIdsKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeUserInfoSubscriptionName; +} + +@end + + +NSString *const TGBridgeUserBotInfoSubscriptionName = @"user.botInfo"; +NSString *const TGBridgeUserBotInfoSubscriptionUserIdsKey = @"uids"; + +@implementation TGBridgeUserBotInfoSubscription + +- (instancetype)initWithUserIds:(NSArray *)userIds +{ + self = [super init]; + if (self != nil) + { + _userIds = userIds; + } + return self; +} + +- (bool)dropPreviouslyQueued +{ + return true; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeObject:self.userIds forKey:TGBridgeUserBotInfoSubscriptionUserIdsKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _userIds = [aDecoder decodeObjectForKey:TGBridgeUserBotInfoSubscriptionUserIdsKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeUserBotInfoSubscriptionName; +} + +@end + + +NSString *const TGBridgeBotReplyMarkupSubscriptionName = @"user.botReplyMarkup"; +NSString *const TGBridgeBotReplyMarkupPeerIdKey = @"peerId"; + +@implementation TGBridgeBotReplyMarkupSubscription + +- (instancetype)initWithPeerId:(int64_t)peerId +{ + self = [super init]; + if (self != nil) + { + _peerId = peerId; + } + return self; +} + +- (bool)dropPreviouslyQueued +{ + return true; +} + +- (void)_serializeParametersWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.peerId forKey:TGBridgeBotReplyMarkupPeerIdKey]; +} + +- (void)_unserializeParametersWithCoder:(NSCoder *)aDecoder +{ + _peerId = [aDecoder decodeInt64ForKey:TGBridgeBotReplyMarkupPeerIdKey]; +} + ++ (NSString *)subscriptionName +{ + return TGBridgeBotReplyMarkupSubscriptionName; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeUnsupportedMediaAttachment.m b/submodules/WatchCommon/Host/Sources/TGBridgeUnsupportedMediaAttachment.m new file mode 100644 index 00000000..b51e422f --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeUnsupportedMediaAttachment.m @@ -0,0 +1,35 @@ +#import "TGBridgeUnsupportedMediaAttachment.h" + +const NSInteger TGBridgeUnsupportedMediaAttachmentType = 0x3837BEF7; + +NSString *const TGBridgeUnsupportedMediaCompactTitleKey = @"compactTitle"; +NSString *const TGBridgeUnsupportedMediaTitleKey = @"title"; +NSString *const TGBridgeUnsupportedMediaSubtitleKey = @"subtitle"; + +@implementation TGBridgeUnsupportedMediaAttachment + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _compactTitle = [aDecoder decodeObjectForKey:TGBridgeUnsupportedMediaCompactTitleKey]; + _title = [aDecoder decodeObjectForKey:TGBridgeUnsupportedMediaTitleKey]; + _subtitle = [aDecoder decodeObjectForKey:TGBridgeUnsupportedMediaSubtitleKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeObject:self.compactTitle forKey:TGBridgeUnsupportedMediaCompactTitleKey]; + [aCoder encodeObject:self.title forKey:TGBridgeUnsupportedMediaTitleKey]; + [aCoder encodeObject:self.subtitle forKey:TGBridgeUnsupportedMediaSubtitleKey]; +} + ++ (NSInteger)mediaType +{ + return TGBridgeUnsupportedMediaAttachmentType; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeUser.m b/submodules/WatchCommon/Host/Sources/TGBridgeUser.m new file mode 100644 index 00000000..4c0fed8d --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeUser.m @@ -0,0 +1,286 @@ +#import "TGBridgeUser.h" +//#import "TGWatchCommon.h" +#import "TGBridgeBotInfo.h" + +//#import "../Extension/TGStringUtils.h" + +NSString *const TGBridgeUserIdentifierKey = @"identifier"; +NSString *const TGBridgeUserFirstNameKey = @"firstName"; +NSString *const TGBridgeUserLastNameKey = @"lastName"; +NSString *const TGBridgeUserUserNameKey = @"userName"; +NSString *const TGBridgeUserPhoneNumberKey = @"phoneNumber"; +NSString *const TGBridgeUserPrettyPhoneNumberKey = @"prettyPhoneNumber"; +NSString *const TGBridgeUserOnlineKey = @"online"; +NSString *const TGBridgeUserLastSeenKey = @"lastSeen"; +NSString *const TGBridgeUserPhotoSmallKey = @"photoSmall"; +NSString *const TGBridgeUserPhotoBigKey = @"photoBig"; +NSString *const TGBridgeUserKindKey = @"kind"; +NSString *const TGBridgeUserBotKindKey = @"botKind"; +NSString *const TGBridgeUserBotVersionKey = @"botVersion"; +NSString *const TGBridgeUserVerifiedKey = @"verified"; +NSString *const TGBridgeUserAboutKey = @"about"; +NSString *const TGBridgeUserVersionKey = @"version"; + +NSString *const TGBridgeUsersDictionaryKey = @"users"; + +@implementation TGBridgeUser + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _identifier = [aDecoder decodeInt64ForKey:TGBridgeUserIdentifierKey]; + _firstName = [aDecoder decodeObjectForKey:TGBridgeUserFirstNameKey]; + _lastName = [aDecoder decodeObjectForKey:TGBridgeUserLastNameKey]; + _userName = [aDecoder decodeObjectForKey:TGBridgeUserUserNameKey]; + _phoneNumber = [aDecoder decodeObjectForKey:TGBridgeUserPhoneNumberKey]; + _prettyPhoneNumber = [aDecoder decodeObjectForKey:TGBridgeUserPrettyPhoneNumberKey]; + _online = [aDecoder decodeBoolForKey:TGBridgeUserOnlineKey]; + _lastSeen = [aDecoder decodeDoubleForKey:TGBridgeUserLastSeenKey]; + _photoSmall = [aDecoder decodeObjectForKey:TGBridgeUserPhotoSmallKey]; + _photoBig = [aDecoder decodeObjectForKey:TGBridgeUserPhotoBigKey]; + _kind = [aDecoder decodeInt32ForKey:TGBridgeUserKindKey]; + _botKind = [aDecoder decodeInt32ForKey:TGBridgeUserBotKindKey]; + _botVersion = [aDecoder decodeInt32ForKey:TGBridgeUserBotVersionKey]; + _verified = [aDecoder decodeBoolForKey:TGBridgeUserVerifiedKey]; + _about = [aDecoder decodeObjectForKey:TGBridgeUserAboutKey]; + _userVersion = [aDecoder decodeInt32ForKey:TGBridgeUserVersionKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.identifier forKey:TGBridgeUserIdentifierKey]; + [aCoder encodeObject:self.firstName forKey:TGBridgeUserFirstNameKey]; + [aCoder encodeObject:self.lastName forKey:TGBridgeUserLastNameKey]; + [aCoder encodeObject:self.userName forKey:TGBridgeUserUserNameKey]; + [aCoder encodeObject:self.phoneNumber forKey:TGBridgeUserPhoneNumberKey]; + [aCoder encodeObject:self.prettyPhoneNumber forKey:TGBridgeUserPrettyPhoneNumberKey]; + [aCoder encodeBool:self.online forKey:TGBridgeUserOnlineKey]; + [aCoder encodeDouble:self.lastSeen forKey:TGBridgeUserLastSeenKey]; + [aCoder encodeObject:self.photoSmall forKey:TGBridgeUserPhotoSmallKey]; + [aCoder encodeObject:self.photoBig forKey:TGBridgeUserPhotoBigKey]; + [aCoder encodeInt32:self.kind forKey:TGBridgeUserKindKey]; + [aCoder encodeInt32:self.botKind forKey:TGBridgeUserBotKindKey]; + [aCoder encodeInt32:self.botVersion forKey:TGBridgeUserBotVersionKey]; + [aCoder encodeBool:self.verified forKey:TGBridgeUserVerifiedKey]; + [aCoder encodeObject:self.about forKey:TGBridgeUserAboutKey]; + [aCoder encodeInt32:self.userVersion forKey:TGBridgeUserVersionKey]; +} + +- (instancetype)copyWithZone:(NSZone *)__unused zone +{ + TGBridgeUser *user = [[TGBridgeUser alloc] init]; + user->_identifier = self.identifier; + user->_firstName = self.firstName; + user->_lastName = self.lastName; + user->_userName = self.userName; + user->_phoneNumber = self.phoneNumber; + user->_prettyPhoneNumber = self.prettyPhoneNumber; + user->_online = self.online; + user->_lastSeen = self.lastSeen; + user->_photoSmall = self.photoSmall; + user->_photoBig = self.photoBig; + user->_kind = self.kind; + user->_botKind = self.botKind; + user->_botVersion = self.botVersion; + user->_verified = self.verified; + user->_about = self.about; + user->_userVersion = self.userVersion; + + return user; +} + +- (NSString *)displayName +{ + NSString *firstName = self.firstName; + NSString *lastName = self.lastName; + + if (firstName != nil && firstName.length != 0 && lastName != nil && lastName.length != 0) + { + return [[NSString alloc] initWithFormat:@"%@ %@", firstName, lastName]; + } + else if (firstName != nil && firstName.length != 0) + return firstName; + else if (lastName != nil && lastName.length != 0) + return lastName; + + return @""; +} + +- (bool)isBot +{ + return (self.kind == TGBridgeUserKindBot || self.kind ==TGBridgeUserKindSmartBot); +} + +- (TGBridgeUserChange *)changeFromUser:(TGBridgeUser *)user +{ + NSMutableDictionary *fields = [[NSMutableDictionary alloc] init]; + + [self _compareString:self.firstName oldString:user.firstName dict:fields key:TGBridgeUserFirstNameKey]; + [self _compareString:self.lastName oldString:user.lastName dict:fields key:TGBridgeUserLastNameKey]; + [self _compareString:self.userName oldString:user.userName dict:fields key:TGBridgeUserUserNameKey]; + [self _compareString:self.phoneNumber oldString:user.phoneNumber dict:fields key:TGBridgeUserPhoneNumberKey]; + [self _compareString:self.prettyPhoneNumber oldString:user.prettyPhoneNumber dict:fields key:TGBridgeUserPrettyPhoneNumberKey]; + + if (self.online != user.online) + fields[TGBridgeUserOnlineKey] = @(self.online); + + if (fabs(self.lastSeen - user.lastSeen) > DBL_EPSILON) + fields[TGBridgeUserLastSeenKey] = @(self.lastSeen); + + [self _compareString:self.photoSmall oldString:user.photoSmall dict:fields key:TGBridgeUserPhotoSmallKey]; + [self _compareString:self.photoBig oldString:user.photoBig dict:fields key:TGBridgeUserPhotoBigKey]; + + if (self.kind != user.kind) + fields[TGBridgeUserKindKey] = @(self.kind); + + if (self.botKind != user.botKind) + fields[TGBridgeUserBotKindKey] = @(self.botKind); + + if (self.botVersion != user.botVersion) + fields[TGBridgeUserBotVersionKey] = @(self.botVersion); + + if (self.verified != user.verified) + fields[TGBridgeUserVerifiedKey] = @(self.verified); + + if (fields.count == 0) + return nil; + + return [[TGBridgeUserChange alloc] initWithUserIdentifier:user.identifier fields:fields]; +} + +- (void)_compareString:(NSString *)newString oldString:(NSString *)oldString dict:(NSMutableDictionary *)dict key:(NSString *)key +{ + if (newString == nil && oldString == nil) + return; + + if (![newString isEqualToString:oldString]) + { + if (newString == nil) + dict[key] = [NSNull null]; + else + dict[key] = newString; + } +} + +- (TGBridgeUser *)userByApplyingChange:(TGBridgeUserChange *)change +{ + if (change.userIdentifier != self.identifier) + return nil; + + TGBridgeUser *user = [self copy]; + + NSString *firstNameChange = change.fields[TGBridgeUserFirstNameKey]; + if (firstNameChange != nil) + user->_firstName = [self _stringForFieldChange:firstNameChange]; + + NSString *lastNameChange = change.fields[TGBridgeUserLastNameKey]; + if (lastNameChange != nil) + user->_lastName = [self _stringForFieldChange:lastNameChange]; + + NSString *userNameChange = change.fields[TGBridgeUserUserNameKey]; + if (userNameChange != nil) + user->_userName = [self _stringForFieldChange:userNameChange]; + + NSString *phoneNumberChange = change.fields[TGBridgeUserPhoneNumberKey]; + if (phoneNumberChange != nil) + user->_phoneNumber = [self _stringForFieldChange:phoneNumberChange]; + + NSString *prettyPhoneNumberChange = change.fields[TGBridgeUserPrettyPhoneNumberKey]; + if (prettyPhoneNumberChange != nil) + user->_prettyPhoneNumber = [self _stringForFieldChange:prettyPhoneNumberChange]; + + NSNumber *onlineChange = change.fields[TGBridgeUserOnlineKey]; + if (onlineChange != nil) + user->_online = [onlineChange boolValue]; + + NSNumber *lastSeenChange = change.fields[TGBridgeUserLastSeenKey]; + if (lastSeenChange != nil) + user->_lastSeen = [lastSeenChange doubleValue]; + + NSString *photoSmallChange = change.fields[TGBridgeUserPhotoSmallKey]; + if (photoSmallChange != nil) + user->_photoSmall = [self _stringForFieldChange:photoSmallChange]; + + NSString *photoBigChange = change.fields[TGBridgeUserPhotoBigKey]; + if (photoBigChange != nil) + user->_photoBig = [self _stringForFieldChange:photoBigChange]; + + NSNumber *kindChange = change.fields[TGBridgeUserKindKey]; + if (kindChange != nil) + user->_kind = (int32_t)[kindChange intValue]; + + NSNumber *botKindChange = change.fields[TGBridgeUserBotKindKey]; + if (botKindChange != nil) + user->_botKind = (int32_t)[botKindChange intValue]; + + NSNumber *botVersionChange = change.fields[TGBridgeUserBotVersionKey]; + if (botVersionChange != nil) + user->_botVersion = (int32_t)[botVersionChange intValue]; + + NSNumber *verifiedChange = change.fields[TGBridgeUserVerifiedKey]; + if (verifiedChange != nil) + user->_verified = [verifiedChange boolValue]; + + return user; +} + +- (NSString *)_stringForFieldChange:(NSString *)fieldChange +{ + if ([fieldChange isKindOfClass:[NSNull class]]) + return nil; + + return fieldChange; +} + +- (BOOL)isEqual:(id)object +{ + if (object == self) + return YES; + + if (!object || ![object isKindOfClass:[self class]]) + return NO; + + return self.identifier == ((TGBridgeUser *)object).identifier; +} + +@end + + +NSString *const TGBridgeUserChangeIdentifierKey = @"userIdentifier"; +NSString *const TGBridgeUserChangeFieldsKey = @"fields"; + +@implementation TGBridgeUserChange + +- (instancetype)initWithUserIdentifier:(int32_t)userIdentifier fields:(NSDictionary *)fields +{ + self = [super init]; + if (self != nil) + { + _userIdentifier = userIdentifier; + _fields = fields; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _userIdentifier = [aDecoder decodeInt32ForKey:TGBridgeUserChangeIdentifierKey]; + _fields = [aDecoder decodeObjectForKey:TGBridgeUserChangeFieldsKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt32:self.userIdentifier forKey:TGBridgeUserChangeIdentifierKey]; + [aCoder encodeObject:self.fields forKey:TGBridgeUserChangeFieldsKey]; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeVideoMediaAttachment.m b/submodules/WatchCommon/Host/Sources/TGBridgeVideoMediaAttachment.m new file mode 100644 index 00000000..66fe8679 --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeVideoMediaAttachment.m @@ -0,0 +1,39 @@ +#import "TGBridgeVideoMediaAttachment.h" +#import + +const NSInteger TGBridgeVideoMediaAttachmentType = 0x338EAA20; + +NSString *const TGBridgeVideoMediaVideoIdKey = @"videoId"; +NSString *const TGBridgeVideoMediaDimensionsKey = @"dimensions"; +NSString *const TGBridgeVideoMediaDurationKey = @"duration"; +NSString *const TGBridgeVideoMediaRoundKey = @"round"; + +@implementation TGBridgeVideoMediaAttachment + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _videoId = [aDecoder decodeInt64ForKey:TGBridgeVideoMediaVideoIdKey]; + _dimensions = [aDecoder decodeCGSizeForKey:TGBridgeVideoMediaDimensionsKey]; + _duration = [aDecoder decodeInt32ForKey:TGBridgeVideoMediaDurationKey]; + _round = [aDecoder decodeBoolForKey:TGBridgeVideoMediaRoundKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.videoId forKey:TGBridgeVideoMediaVideoIdKey]; + [aCoder encodeCGSize:self.dimensions forKey:TGBridgeVideoMediaDimensionsKey]; + [aCoder encodeInt32:self.duration forKey:TGBridgeVideoMediaDurationKey]; + [aCoder encodeBool:self.round forKey:TGBridgeVideoMediaRoundKey]; +} + ++ (NSInteger)mediaType +{ + return TGBridgeVideoMediaAttachmentType; +} + +@end diff --git a/submodules/WatchCommon/Host/Sources/TGBridgeWebPageMediaAttachment.m b/submodules/WatchCommon/Host/Sources/TGBridgeWebPageMediaAttachment.m new file mode 100644 index 00000000..3983075d --- /dev/null +++ b/submodules/WatchCommon/Host/Sources/TGBridgeWebPageMediaAttachment.m @@ -0,0 +1,65 @@ +#import "TGBridgeWebPageMediaAttachment.h" +#import "TGBridgeImageMediaAttachment.h" +#import + +const NSInteger TGBridgeWebPageMediaAttachmentType = 0x584197af; + +NSString *const TGBridgeWebPageMediaWebPageIdKey = @"webPageId"; +NSString *const TGBridgeWebPageMediaUrlKey = @"url"; +NSString *const TGBridgeWebPageMediaDisplayUrlKey = @"displayUrl"; +NSString *const TGBridgeWebPageMediaPageTypeKey = @"pageType"; +NSString *const TGBridgeWebPageMediaSiteNameKey = @"siteName"; +NSString *const TGBridgeWebPageMediaTitleKey = @"title"; +NSString *const TGBridgeWebPageMediaPageDescriptionKey = @"pageDescription"; +NSString *const TGBridgeWebPageMediaPhotoKey = @"photo"; +NSString *const TGBridgeWebPageMediaEmbedUrlKey = @"embedUrl"; +NSString *const TGBridgeWebPageMediaEmbedTypeKey = @"embedType"; +NSString *const TGBridgeWebPageMediaEmbedSizeKey = @"embedSize"; +NSString *const TGBridgeWebPageMediaDurationKey = @"duration"; +NSString *const TGBridgeWebPageMediaAuthorKey = @"author"; + +@implementation TGBridgeWebPageMediaAttachment + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super init]; + if (self != nil) + { + _webPageId = [aDecoder decodeInt64ForKey:TGBridgeWebPageMediaWebPageIdKey]; + _url = [aDecoder decodeObjectForKey:TGBridgeWebPageMediaUrlKey]; + _displayUrl = [aDecoder decodeObjectForKey:TGBridgeWebPageMediaDisplayUrlKey]; + _pageType = [aDecoder decodeObjectForKey:TGBridgeWebPageMediaPageTypeKey]; + _siteName = [aDecoder decodeObjectForKey:TGBridgeWebPageMediaSiteNameKey]; + _title = [aDecoder decodeObjectForKey:TGBridgeWebPageMediaTitleKey]; + _pageDescription = [aDecoder decodeObjectForKey:TGBridgeWebPageMediaPageDescriptionKey]; + _photo = [aDecoder decodeObjectForKey:TGBridgeWebPageMediaPhotoKey]; + _embedUrl = [aDecoder decodeObjectForKey:TGBridgeWebPageMediaEmbedUrlKey]; + _embedSize = [aDecoder decodeCGSizeForKey:TGBridgeWebPageMediaEmbedSizeKey]; + _duration = [aDecoder decodeObjectForKey:TGBridgeWebPageMediaDurationKey]; + _author = [aDecoder decodeObjectForKey:TGBridgeWebPageMediaAuthorKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInt64:self.webPageId forKey:TGBridgeWebPageMediaWebPageIdKey]; + [aCoder encodeObject:self.url forKey:TGBridgeWebPageMediaUrlKey]; + [aCoder encodeObject:self.displayUrl forKey:TGBridgeWebPageMediaDisplayUrlKey]; + [aCoder encodeObject:self.pageType forKey:TGBridgeWebPageMediaPageTypeKey]; + [aCoder encodeObject:self.siteName forKey:TGBridgeWebPageMediaSiteNameKey]; + [aCoder encodeObject:self.title forKey:TGBridgeWebPageMediaTitleKey]; + [aCoder encodeObject:self.pageDescription forKey:TGBridgeWebPageMediaPageDescriptionKey]; + [aCoder encodeObject:self.photo forKey:TGBridgeWebPageMediaPhotoKey]; + [aCoder encodeObject:self.embedUrl forKey:TGBridgeWebPageMediaEmbedUrlKey]; + [aCoder encodeCGSize:self.embedSize forKey:TGBridgeWebPageMediaEmbedSizeKey]; + [aCoder encodeObject:self.duration forKey:TGBridgeWebPageMediaDurationKey]; + [aCoder encodeObject:self.author forKey:TGBridgeWebPageMediaAuthorKey]; +} + ++ (NSInteger)mediaType +{ + return TGBridgeWebPageMediaAttachmentType; +} + +@end diff --git a/submodules/WebSearchUI/Sources/LegacyWebSearchGallery.swift b/submodules/WebSearchUI/Sources/LegacyWebSearchGallery.swift index 29f65144..5d4d4488 100644 --- a/submodules/WebSearchUI/Sources/LegacyWebSearchGallery.swift +++ b/submodules/WebSearchUI/Sources/LegacyWebSearchGallery.swift @@ -346,7 +346,10 @@ func presentLegacyWebSearchGallery(context: AccountContext, peer: EnginePeer?, t model.storeOriginalImageForItem = { item, image in editingContext.setOriginalImage(image, for: item, synchronous: false) } - model.willFinishEditingItem = { item, adjustments, representation, hasChanges in + model.willFinishEditingItem = { (item: TGMediaEditableItem?, adjustments: TGMediaEditAdjustments?, representation: Any?, hasChanges: Bool) in + guard let item else { + return + } if hasChanges { editingContext.setAdjustments(adjustments, for: item) } @@ -355,10 +358,16 @@ func presentLegacyWebSearchGallery(context: AccountContext, peer: EnginePeer?, t selectionContext.setItem(item, selected: true) } } - model.didFinishEditingItem = { item, adjustments, result, thumbnail in + model.didFinishEditingItem = { (item: TGMediaEditableItem?, adjustments: TGMediaEditAdjustments?, result: UIImage?, thumbnail: UIImage?) in + guard let item, let result, let thumbnail else { + return + } editingContext.setImage(result, thumbnailImage: thumbnail, for: item, synchronous: true) } - model.saveItemCaption = { item, caption in + model.saveItemCaption = { (item: TGMediaEditableItem?, caption: NSAttributedString?) in + guard let item else { + return + } editingContext.setCaption(caption, for: item) if let selectionContext = selectionContext, let caption = caption, caption.length > 0, let item = item as? TGMediaSelectableItem { selectionContext.setItem(item, selected: true) @@ -367,7 +376,7 @@ func presentLegacyWebSearchGallery(context: AccountContext, peer: EnginePeer?, t if let selectionContext = selectionContext { model.interfaceView.updateSelectionInterface(selectionContext.count(), counterVisible: selectionContext.count() > 0, animated: false) } - model.interfaceView.donePressed = { item in + model.interfaceView.donePressed = { (item: TGModernGalleryItem?) in if let item = item as? LegacyWebSearchGalleryItem { controller.dismissWhenReady(animated: true) completed(item.item.result) diff --git a/submodules/WebUI/Sources/WebAppController.swift b/submodules/WebUI/Sources/WebAppController.swift index bc04472f..e74c8197 100644 --- a/submodules/WebUI/Sources/WebAppController.swift +++ b/submodules/WebUI/Sources/WebAppController.swift @@ -1,3 +1,6 @@ +import SGConfig +import SGAPIWebSettings +import SGLogging import Foundation import UIKit @preconcurrency import WebKit @@ -250,7 +253,7 @@ public final class WebAppController: ViewController, AttachmentContainable { private var validLayout: (ContainerViewLayout, CGFloat)? - init(context: AccountContext, controller: WebAppController) { + init(userScripts: [WKUserScript] = [], context: AccountContext, controller: WebAppController) { #if DEBUG let _ = registeredProtocols #endif @@ -271,12 +274,24 @@ public final class WebAppController: ViewController, AttachmentContainable { self.backgroundColor = self.presentationData.theme.list.plainBackgroundColor } + // MARK: Swiftgram + var userScripts: [WKUserScript] = [] + let globalSGConfig = context.currentAppConfiguration.with({ $0 }).sgWebSettings.global + let botIdInt = controller.botId.id._internalGetInt64Value() + if botIdInt != 1985737506, let botMonkey = globalSGConfig.botMonkeys.first(where: { $0.botId == botIdInt}) { + if !botMonkey.src.isEmpty { + userScripts.append(WKUserScript(source: botMonkey.src, injectionTime: .atDocumentStart, forMainFrameOnly: false)) + } + } let webView = WebAppWebView(account: context.account) + for userScript in userScripts { + webView.configuration.userContentController.addUserScript(userScript) + } webView.alpha = 0.0 webView.navigationDelegate = self webView.uiDelegate = self webView.scrollView.delegate = self.wrappedScrollViewDelegate - webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: [], context: nil) + webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: [], context: nil as UnsafeMutableRawPointer?) webView.tintColor = self.presentationData.theme.rootController.tabBar.iconColor webView.handleScriptMessage = { [weak self] message in self?.handleScriptMessage(message) @@ -290,13 +305,13 @@ public final class WebAppController: ViewController, AttachmentContainable { } } } - if #available(iOS 13.0, *) { - if self.presentationData.theme.overallDarkAppearance { - webView.overrideUserInterfaceStyle = .dark - } else { - webView.overrideUserInterfaceStyle = .unspecified - } + + if self.presentationData.theme.overallDarkAppearance { + webView.overrideUserInterfaceStyle = UIUserInterfaceStyle.dark + } else { + webView.overrideUserInterfaceStyle = UIUserInterfaceStyle.unspecified } + self.webView = webView self.addSubnode(self.backgroundNode) @@ -1093,6 +1108,9 @@ public final class WebAppController: ViewController, AttachmentContainable { guard let controller = self.controller else { return } + guard message.frameInfo.isMainFrame else { + return + } guard let body = message.body as? [String: Any] else { return } @@ -2028,12 +2046,10 @@ public final class WebAppController: ViewController, AttachmentContainable { self.updateHeaderBackgroundColor(transition: .immediate) self.sendThemeChangedEvent() - if #available(iOS 13.0, *) { - if self.presentationData.theme.overallDarkAppearance { - self.webView?.overrideUserInterfaceStyle = .dark - } else { - self.webView?.overrideUserInterfaceStyle = .unspecified - } + if self.presentationData.theme.overallDarkAppearance { + self.webView?.overrideUserInterfaceStyle = UIUserInterfaceStyle.dark + } else { + self.webView?.overrideUserInterfaceStyle = UIUserInterfaceStyle.unspecified } } @@ -3441,6 +3457,7 @@ public final class WebAppController: ViewController, AttachmentContainable { fileprivate let updatedPresentationData: (initial: PresentationData, signal: Signal)? private var presentationDataDisposable: Disposable? + private var viewWillDisappearCalled = false private var hasSettings = false public var openUrl: (String, Bool, Bool, @escaping () -> Void) -> Void = { _, _, _, _ in } @@ -3724,193 +3741,68 @@ public final class WebAppController: ViewController, AttachmentContainable { } } - let peerId = self.peerId - let botId = self.botId - let source = self.source let hasSettings = self.hasSettings - let activeDownload = WebAppController.activeDownloads.first - let activeDownloadProgress: Signal - if let activeDownload { - activeDownloadProgress = activeDownload.progressSignal - |> map(Optional.init) - |> mapToThrottled { next -> Signal in - return .single(next) |> then(.complete() |> delay(0.2, queue: Queue.mainQueue())) - } - } else { - activeDownloadProgress = .single(nil) + var items: [ContextMenuItem] = [] + + if hasSettings { + items.append(.action(ContextMenuActionItem(text: presentationData.strings.WebApp_Settings, icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Settings"), color: theme.contextMenu.primaryColor) + }, action: { [weak self] c, _ in + c?.dismiss(completion: nil) + self?.controllerNode.sendSettingsButtonEvent() + }))) } - let items = combineLatest(queue: Queue.mainQueue(), - context.engine.messages.attachMenuBots() |> take(1), - context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: self.botId)), - context.engine.data.get(TelegramEngine.EngineData.Item.Peer.BotCommands(id: self.botId)), - context.engine.data.get(TelegramEngine.EngineData.Item.Peer.BotPrivacyPolicyUrl(id: self.botId)), - activeDownloadProgress - ) - |> map { [weak self] attachMenuBots, botPeer, botCommands, privacyPolicyUrl, activeDownloadProgress -> ContextController.Items in - var items: [ContextMenuItem] = [] - - if let activeDownload, let progress = activeDownloadProgress { - let isActive = progress < 1.0 - .ulpOfOne - let progressString: String - if isActive { - if let fileSize = activeDownload.fileSize { - let downloadedSize = Int64(Double(fileSize) * progress) - progressString = "\(dataSizeString(downloadedSize, formatting: DataSizeStringFormatting(presentationData: presentationData))) / \(dataSizeString(fileSize, formatting: DataSizeStringFormatting(presentationData: presentationData)))" - } else { - progressString = "\(Int32(progress))%" - } - } else { - progressString = activeDownload.isMedia ? presentationData.strings.WebApp_Download_SavedToPhotos : presentationData.strings.WebApp_Download_SavedToFiles - } - items.append(.action(ContextMenuActionItem(text: activeDownload.fileName, textLayout: .secondLineWithValue(progressString), icon: { theme in return isActive ? generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Clear"), color: theme.contextMenu.primaryColor) : nil }, iconPosition: .right, action: isActive ? { [weak self, weak activeDownload] _, f in - f(.default) - - WebAppController.activeDownloads.removeAll(where: { $0 === activeDownload }) - activeDownload?.cancel() - - if let fileDownloadTooltip = self?.controllerNode.fileDownloadTooltip { - fileDownloadTooltip.dismissWithCommitAction() - } - } : nil))) - items.append(.separator) - } - - let attachMenuBot = attachMenuBots.first(where: { $0.peer.id == botId && !$0.flags.contains(.notActivated) }) - if hasSettings { - items.append(.action(ContextMenuActionItem(text: presentationData.strings.WebApp_Settings, icon: { theme in - return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Settings"), color: theme.contextMenu.primaryColor) - }, action: { [weak self] c, _ in - c?.dismiss(completion: nil) - - if let strongSelf = self { - strongSelf.controllerNode.sendSettingsButtonEvent() - } - }))) - } - - if peerId != botId { - items.append(.action(ContextMenuActionItem(text: presentationData.strings.WebApp_OpenBot, icon: { theme in - return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Bots"), color: theme.contextMenu.primaryColor) - }, action: { [weak self] c, _ in - c?.dismiss(completion: nil) - - guard let strongSelf = self else { - return - } - - let _ = (context.engine.data.get( - TelegramEngine.EngineData.Item.Peer.Peer(id: strongSelf.botId) - ) - |> deliverOnMainQueue).start(next: { botPeer in - guard let botPeer = botPeer else { - return - } - if let strongSelf = self, let navigationController = strongSelf.getNavigationController() { - (strongSelf.parentController() as? AttachmentController)?.minimizeIfNeeded() - strongSelf.context.sharedContext.navigateToChatController(NavigateToChatControllerParams(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(botPeer))) - } - }) - }))) - } - - if let addressName = botPeer?.addressName { - items.append(.action(ContextMenuActionItem(text: presentationData.strings.WebApp_Share, icon: { theme in - return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Forward"), color: theme.contextMenu.primaryColor) - }, action: { [weak self] c, _ in - c?.dismiss(completion: nil) - - guard let self else { - return - } - let shareController = ShareController(context: context, subject: .url("https://t.me/\(addressName)?profile")) - shareController.actionCompleted = { [weak self] in - let presentationData = context.sharedContext.currentPresentationData.with { $0 } - self?.present(UndoOverlayController(presentationData: presentationData, content: .linkCopied(title: nil, text: presentationData.strings.Conversation_LinkCopied), elevatedLayout: false, animateInAsReplacement: false, action: { _ in return false }), in: .window(.root)) - } - self.present(shareController, in: .window(.root)) - }))) - } - - items.append(.action(ContextMenuActionItem(text: presentationData.strings.WebApp_ReloadPage, icon: { theme in - return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Reload"), color: theme.contextMenu.primaryColor) + items.append(.action(ContextMenuActionItem(text: presentationData.strings.WebApp_ReloadPage, icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Reload"), color: theme.contextMenu.primaryColor) + }, action: { [weak self] c, _ in + c?.dismiss(completion: nil) + self?.controllerNode.webView?.reload() + }))) + + if let _ = self.appName { + items.append(.action(ContextMenuActionItem(text: presentationData.strings.WebApp_AddToHomeScreen, icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/AddSquare"), color: theme.contextMenu.primaryColor) }, action: { [weak self] c, _ in c?.dismiss(completion: nil) - - self?.controllerNode.webView?.reload() + self?.controllerNode.addToHomeScreen() }))) - - if let _ = self?.appName { - items.append(.action(ContextMenuActionItem(text: presentationData.strings.WebApp_AddToHomeScreen, icon: { theme in - return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/AddSquare"), color: theme.contextMenu.primaryColor) - }, action: { [weak self] c, _ in - c?.dismiss(completion: nil) - - self?.controllerNode.addToHomeScreen() - }))) - } - - items.append(.action(ContextMenuActionItem(text: presentationData.strings.WebApp_TermsOfUse, icon: { theme in - return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Info"), color: theme.contextMenu.primaryColor) - }, action: { [weak self] c, _ in - c?.dismiss(completion: nil) - - guard let self, let navigationController = self.getNavigationController() else { - return - } - - let context = self.context - let _ = (cachedWebAppTermsPage(context: context) - |> deliverOnMainQueue).startStandalone(next: { resolvedUrl in - context.sharedContext.openResolvedUrl(resolvedUrl, context: context, urlContext: .generic, navigationController: navigationController, forceExternal: true, forceUpdate: false, openPeer: { peer, navigation in - }, sendFile: nil, sendSticker: nil, sendEmoji: nil, requestMessageActionUrlAuth: nil, joinVoiceChat: nil, present: { [weak self] c, arguments in - self?.push(c) - }, dismissInput: {}, contentContext: nil, progress: nil, completion: nil) - }) - }))) - - items.append(.action(ContextMenuActionItem(text: presentationData.strings.WebApp_PrivacyPolicy, icon: { theme in - return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Privacy"), color: theme.contextMenu.primaryColor) - }, action: { [weak self] c, _ in - c?.dismiss(completion: nil) - - guard let self else { - return - } - - (self.parentController() as? AttachmentController)?.minimizeIfNeeded() - if let privacyPolicyUrl { - self.context.sharedContext.openExternalUrl(context: self.context, urlContext: .generic, url: privacyPolicyUrl, forceExternal: false, presentationData: self.presentationData, navigationController: self.getNavigationController(), dismissInput: {}) - } else if let botCommands, botCommands.contains(where: { $0.text == "privacy" }) { - let _ = enqueueMessages(account: self.context.account, peerId: self.botId, messages: [.message(text: "/privacy", attributes: [], inlineStickers: [:], mediaReference: nil, threadId: nil, replyToMessageId: nil, replyToStoryId: nil, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: [])]).startStandalone() - - if let botPeer, let navigationController = self.getNavigationController() { - self.context.sharedContext.navigateToChatController(NavigateToChatControllerParams(navigationController: navigationController, context: self.context, chatLocation: .peer(botPeer))) - } - } else { - self.context.sharedContext.openExternalUrl(context: self.context, urlContext: .generic, url: self.presentationData.strings.WebApp_PrivacyPolicy_URL, forceExternal: false, presentationData: self.presentationData, navigationController: self.getNavigationController(), dismissInput: {}) - } - }))) - - if let _ = attachMenuBot, [.attachMenu, .settings, .generic].contains(source) { - items.append(.action(ContextMenuActionItem(text: presentationData.strings.WebApp_RemoveBot, textColor: .destructive, icon: { theme in - return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Delete"), color: theme.contextMenu.destructiveColor) - }, action: { [weak self] c, _ in - c?.dismiss(completion: nil) - - if let self { - self.removeAttachBot() - } - }))) - } - - return ContextController.Items(content: .list(items)) } - let contextController = ContextController(presentationData: presentationData, source: .reference(WebAppContextReferenceContentSource(controller: self, sourceView: view)), items: items, gesture: gesture) + items.append(.action(ContextMenuActionItem(text: presentationData.strings.WebApp_TermsOfUse, icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Info"), color: theme.contextMenu.primaryColor) + }, action: { [weak self] c, _ in + c?.dismiss(completion: nil) + + guard let self, let navigationController = self.getNavigationController() else { + return + } + + let _ = (cachedWebAppTermsPage(context: context) + |> deliverOnMainQueue).startStandalone(next: { resolvedUrl in + context.sharedContext.openResolvedUrl(resolvedUrl, context: context, urlContext: .generic, navigationController: navigationController, forceExternal: true, forceUpdate: false, openPeer: { _, _ in + }, sendFile: nil, sendSticker: nil, sendEmoji: nil, requestMessageActionUrlAuth: nil, joinVoiceChat: nil, present: { [weak self] controller, _ in + self?.push(controller) + }, dismissInput: {}, contentContext: nil, progress: nil, completion: nil) + }) + }))) + + items.append(.action(ContextMenuActionItem(text: presentationData.strings.WebApp_PrivacyPolicy, icon: { theme in + return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Privacy"), color: theme.contextMenu.primaryColor) + }, action: { [weak self] c, _ in + c?.dismiss(completion: nil) + guard let self else { + return + } + self.context.sharedContext.openExternalUrl(context: self.context, urlContext: .generic, url: self.presentationData.strings.WebApp_PrivacyPolicy_URL, forceExternal: false, presentationData: self.presentationData, navigationController: self.getNavigationController(), dismissInput: {}) + }))) + + let menuItems = Signal.single(ContextController.Items(content: .list(items))) + + let contextController = makeContextController(presentationData: presentationData, source: .reference(WebAppContextReferenceContentSource(controller: self, sourceView: view)), items: menuItems, gesture: gesture) self.presentInGlobalOverlay(contextController) } @@ -3982,6 +3874,24 @@ public final class WebAppController: ViewController, AttachmentContainable { self.controllerNode.setupWebView() } + + // MARK: Swiftgram + override final public func viewWillDisappear(_ animated: Bool) { + if !self.viewWillDisappearCalled { + self.viewWillDisappearCalled = true + self.updateSGWebSettingsIfNeeded() + } + super.viewWillDisappear(animated) + } + + private func updateSGWebSettingsIfNeeded() { + if let url = self.url, let parsedUrl = URL(string: url), parsedUrl.host?.lowercased() == SG_API_WEBAPP_URL_PARSED.host?.lowercased() { + SGLogger.shared.log("WebApp", "Closed webapp") + updateSGWebSettingsInteractivelly(context: self.context) + } + } + + public func requestDismiss(completion: @escaping () -> Void) { if self.controllerNode.needDismissConfirmation { let actionSheet = ActionSheetController(presentationData: self.presentationData) diff --git a/third-party/recaptcha/BUILD b/third-party/recaptcha/BUILD index 8f828772..bb626687 100644 --- a/third-party/recaptcha/BUILD +++ b/third-party/recaptcha/BUILD @@ -6,8 +6,8 @@ load( ) apple_static_xcframework_import( - name = "RecaptchaEnterpriseSDK", - xcframework_imports = glob(["RecaptchaEnterpriseSDK.xcframework/**"]), + name = "RecaptchaEnterprise", + xcframework_imports = glob(["RecaptchaEnterprise.xcframework/**"]), features = [ ], visibility = [